聊聊DockerEOF问题排查

[[402863]]

本文转载自微信公众号「运维开发故事」,作者运维开发故事。转载本文请联系运维开发故事公众号。

网站建设哪家好,找创新互联建站!专注于网页设计、网站建设、微信开发、小程序开发、集团企业网站建设等服务项目。为回馈新老客户创新互联还提供了福建免费建站欢迎大家使用!

一、前言

问题排查过程,源码部分均由我的开发同事排查和记录;在征得其同意后,由我发表在此。

二、问题

某天接到客户反馈,pod的事件中出现大量的 warning event: Readiness probe failed: OCI runtime exec failed: exec failed: EOF: unknown。但不影响客户访问该服务。

三、环境

特别说明:客户在负责运行业务的k8s节点上坚持开启了cpu-manager

组件 版本  
k8s 1.14.x  

四、排查

1、接到客户反馈后,检查该pod所在节点的kubelet日志,如下:

 
 
 
  1. I0507 03:43:28.310630  57003 prober.go:112] Readiness probe for "adsfadofadfabdfhaodsfa(d1aab5f0- 
  2. ae8f-11eb-a151-080027049c65):c0" failed (failure): OCI runtime exec failed: exec failed: EOF: unknown 
  3. I0507 07:08:49.834093  57003 prober.go:112] Readiness probe for "adsfadofadfabdfhaodsfa(a89a158e- 
  4. ae8f-11eb-a151-080027049c65):c0" failed (failure): OCI runtime exec failed: exec failed: unexpected EOF: unknown 
  5. I0507 10:06:58.307881  57003 prober.go:112] Readiness probe for "adsfadofadfabdfhaodsfa(d1aab5f0- 
  6. ae8f-11eb-a151-080027049c65):c0" failed (failure): OCI runtime exec failed: exec failed: EOF: unknown 

probe的错误类型为failure,对应代码如下:图片2、再查看docker日志,如下:

 
 
 
  1. time="2021-05-06T16:51:40.009989451+08:00" level=error msg="stream copy error: reading from a closed fifo" 
  2. time="2021-05-06T16:51:40.010054596+08:00" level=error msg="stream copy error: reading from a closed fifo" 
  3. time="2021-05-06T16:51:40.170676532+08:00" level=error msg="Error running exec 8e34e8b910694abe95a467b2936b37635fdabd2f7b7c464d 
  4. fef952fa5732aa4e in container: OCI runtime exec failed: exec failed: EOF: unknown" 

虽然从Docker日志中显示是 stream copy error,但实际上是底层的 runc 返回了 EOF,导致返回了 error。3、因为日志中显示 probe 类型为 Failure,因此 e.CombinedOutPut() 的 err != nil,并且 ExitStatus 不为 0,data 的值为 OCI runtime exec failed: exec failed: unexpected EOF: unknown,最终会调用到 RunInContainer 方法

ExecSync 是通过 GRPC 调用了 dockershim 的 ExecSync

dockershim 最终调用到 ExecInContainer 方法,并且该方法的返回了 exitcode 不为 0 的 error。

 
 
 
  1. func (*NativeExecHandler) ExecInContainer(client libdocker.Interface, container *dockertypes.ContainerJSON, cmd []string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool, resize <-chan remotecommand.TerminalSize, timeout time.Duration) error { 
  2.    execObj, err := client.CreateExec(container.ID, createOpts) 
  3.     
  4.    startOpts := dockertypes.ExecStartCheck{Detach: false, Tty: tty} 
  5.    streamOpts := libdocker.StreamOptions{ 
  6.       InputStream:  stdin, 
  7.       OutputStream: stdout, 
  8.       ErrorStream:  stderr, 
  9.       RawTerminal:  tty, 
  10.       ExecStarted:  execStarted, 
  11.    } 
  12.    err = client.StartExec(execObj.ID, startOpts, streamOpts) 
  13.    if err != nil { 
  14.       return err 
  15.    } 
  16.  
  17.     ticker := time.NewTicker(2 * time.Second) 
  18.     defer ticker.Stop() 
  19.     count := 0 
  20.     for { 
  21.        inspect, err2 := client.InspectExec(execObj.ID) 
  22.        if err2 != nil { 
  23.           return err2 
  24.        } 
  25.        if !inspect.Running { 
  26.           if inspect.ExitCode != 0 { 
  27.              err = &dockerExitError{inspect} 
  28.           } 
  29.           break 
  30.        } 
  31.      
  32.        count++ 
  33.        if count == 5 { 
  34.           klog.Errorf("Exec session %s in container %s terminated but process still running!", execObj.ID, container.ID) 
  35.           break 
  36.        } 
  37.      
  38.        <-ticker.C 
  39.     } 
  40.  
  41.    return err 

ExecInContainer 做了以下几件事:

  1. 调用 CreateExec 创建 ExecID
  2. 调用 StartExec 执行 exec,并通过 holdHijackedConnection 来重定向输入输出。将 inputStream 写入到 connection,并将 response stream 重定向到 stdout,stderr。
  3. 调用 InspectExec 获取本次 exec 的运行状态和 exitcode

那么日志中打印的报错就是 response stream 传递过来的字符流。也就是说,dockerd 的 response 中包含了错误值。

此时去 docker 代码中查找原因,ExecStart 会调用到 dockerd 的以下代码:

根据上面 docker 的日志,err 的错误信息为:OCI runtime exec failed: exec failed: EOF: unknown。也就是说 ContainerExecStart 返回了错误。ContainerExecStart 会调用到 containerd.Exec,也就是 dockerd 和 containerd 之间进行通信

 
 
 
  1. // docker/libcontainerd/client_daemon.go 
  2. // Exec creates exec process. 
  3. // 
  4. // The containerd client calls Exec to register the exec config in the shim side. 
  5. // When the client calls Start, the shim will create stdin fifo if needs. But 
  6. // for the container main process, the stdin fifo will be created in Create not 
  7. // the Start call. stdinCloseSync channel should be closed after Start exec 
  8. // process. 
  9. func (c *client) Exec(ctx context.Context, containerID, processID string, spec *specs.Process, withStdin bool, attachStdio StdioCallback) (int, error) { 
  10.    ctr := c.getContainer(containerID) 
  11.    if ctr == nil { 
  12.       return -1, errors.WithStack(newNotFoundError("no such container")) 
  13.    } 
  14.    t := ctr.getTask() 
  15.    if t == nil { 
  16.       return -1, errors.WithStack(newInvalidParameterError("container is not running")) 
  17.    } 
  18.  
  19.    if p := ctr.getProcess(processID); p != nil { 
  20.       return -1, errors.WithStack(newConflictError("id already in use")) 
  21.    } 
  22.  
  23.    var ( 
  24.       p              containerd.Process 
  25.       rio            cio.IO 
  26.       err            error 
  27.       stdinCloseSync = make(chan struct{}) 
  28.    ) 
  29.  
  30.    fifos := newFIFOSet(ctr.bundleDir, processID, withStdin, spec.Terminal) 
  31.  
  32.    defer func() { 
  33.       if err != nil { 
  34.          if rio != nil { 
  35.             rio.Cancel() 
  36.             rio.Close() 
  37.          } 
  38.       } 
  39.    }() 
  40.  
  41.    p, err = t.Exec(ctx, processID, spec, func(id string) (cio.IO, error) { 
  42.       rio, err = c.createIO(fifos, containerID, processID, stdinCloseSync, attachStdio) 
  43.       return rio, err 
  44.    }) 
  45.    if err != nil { 
  46.       close(stdinCloseSync) 
  47.       return -1, wrapError(err) 
  48.    } 
  49.  
  50.    ctr.addProcess(processID, p) 
  51.  
  52.    // Signal c.createIO that it can call CloseIO 
  53.    // 
  54.    // the stdin of exec process will be created after p.Start in containerd 
  55.    defer close(stdinCloseSync) 
  56.  
  57.    if err = p.Start(ctx); err != nil { 
  58.       // use new context for cleanup because old one may be cancelled by user, but leave a timeout to make sure 
  59.       // we are not waiting forever if containerd is unresponsive or to work around fifo cancelling issues in 
  60.       // older containerd-shim 
  61.       ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second) 
  62.       defer cancel() 
  63.       p.Delete(ctx) 
  64.       ctr.deleteProcess(processID) 
  65.       return -1, wrapError(err) 
  66.    } 
  67.  
  68.    return int(p.Pid()), nil 

这里 new 了一个 FIFOSet,而 reading from a closed fifo 仅出现在 fifo 被 close 掉时,仍然在读取的情况。即 f.Close() 发生在 f.Read() 前面。在外层可以看到

 
 
 
  1. defer func() { 
  2.    if err != nil { 
  3.       if rio != nil { 
  4.          rio.Cancel() 
  5.          rio.Close() // 这里 Close 会导致 fifo close 
  6.       } 
  7.    } 
  8. }() 
  9.  
  10. p, err = t.Exec(ctx, processID, spec, func(id string) (cio.IO, error) { 
  11.    rio, err = c.createIO(fifos, containerID, processID, stdinCloseSync, attachStdio) 
  12.    return rio, err 
  13. }) 
  14. if err != nil { 
  15.    close(stdinCloseSync) 
  16.    return -1, wrapError(err) 
  17.  
  18. ctr.addProcess(processID, p) 
  19.  
  20. // Signal c.createIO that it can call CloseIO 
  21. // 
  22. // the stdin of exec process will be created after p.Start in containerd 
  23. defer close(stdinCloseSync) 
  24.  
  25. // p.Start 出错,会导致内部的 fifo 关闭,从而导致 reading from a closed fifo 的问题 
  26. if err = p.Start(ctx); err != nil { 
  27.    // use new context for cleanup because old one may be cancelled by user, but leave a timeout to make sure 
  28.    // we are not waiting forever if containerd is unresponsive or to work around fifo cancelling issues in 
  29.    // older containerd-shim 
  30.    ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second) 
  31.    defer cancel() 
  32.    p.Delete(ctx) 
  33.    ctr.deleteProcess(processID) 
  34.    return -1, wrapError(err) 

p.Start 调用到下面的代码,通过 GRPC 和 containerd 通信。

 
 
 
  1. // github.com/containerd/containerd/task.go 
  2. func (t *task) Start(ctx context.Context) error { 
  3.    r, err := t.client.TaskService().Start(ctx, &tasks.StartRequest{ 
  4.       ContainerID: t.id, 
  5.    }) 
  6.    if err != nil { 
  7.       t.io.Cancel() 
  8.       t.io.Close() 
  9.       return errdefs.FromGRPC(err) 
  10.    } 
  11.    t.pid = r.Pid 
  12.    return nil 

这个 GRPC 调用会到达 containerd 以下的代码:

 
 
 
  1. func (e *execProcess) start(ctx context.Context) (err error) { 
  2.    var ( 
  3.       socket  *runc.Socket 
  4.       pidfile = filepath.Join(e.path, fmt.Sprintf("%s.pid", e.id)) 
  5.    ) 
  6.    if e.stdio.Terminal { 
  7.       if socket, err = runc.NewTempConsoleSocket(); err != nil { 
  8.          return errors.Wrap(err, "failed to create runc console socket") 
  9.       } 
  10.       defer socket.Close() 
  11.    } else if e.stdio.IsNull() { 
  12.       if e.io, err = runc.NewNullIO(); err != nil { 
  13.          return errors.Wrap(err, "creating new NULL IO") 
  14.       } 
  15.    } else { 
  16.       if e.io, err = runc.NewPipeIO(e.parent.IoUID, e.parent.IoGID, withConditionalIO(e.stdio)); err != nil { 
  17.          return errors.Wrap(err, "failed to create runc io pipes") 
  18.       } 
  19.    } 
  20.    opts := &runc.ExecOpts{ 
  21.       PidFile: pidfile, 
  22.       IO:      e.io, 
  23.       Detach:  true, 
  24.    } 
  25.    if socket != nil { 
  26.       opts.ConsoleSocket = socket 
  27.    } 
  28.    // err 返回了 exec failed: EOF: unknown 
  29.    // 这里的 runtime 就是 runc 的二进制文件执行命令 
  30.    if err := e.parent.runtime.Exec(ctx, e.parent.id, e.spec, opts); err != nil { 
  31.       close(e.waitBlock) 
  32.       return e.parent.runtimeError(err, "OCI runtime exec failed") 
  33.    } 

Exec 的代码如下:

 
 
 
  1. // Exec executres and additional process inside the container based on a full 
  2. // OCI Process specification 
  3. func (r *Runc) Exec(context context.Context, id string, spec specs.Process, opts *ExecOpts) error { 
  4.    f, err := ioutil.TempFile(os.Getenv("XDG_RUNTIME_DIR"), "runc-process") 
  5.    if err != nil { 
  6.       return err 
  7.    } 
  8.    defer os.Remove(f.Name()) 
  9.    err = json.NewEncoder(f).Encode(spec) 
  10.    f.Close() 
  11.    if err != nil { 
  12.       return err 
  13.    } 
  14.    args := []string{"exec", "--process", f.Name()} 
  15.    if opts != nil { 
  16.       oargs, err := opts.args() 
  17.       if err != nil { 
  18.          return err 
  19.       } 
  20.       args = append(args, oargs...) 
  21.    } 
  22.    cmd := r.command(context, append(args, id)...) 
  23.    if opts != nil && opts.IO != nil { 
  24.       opts.Set(cmd) 
  25.    } 
  26.    if cmd.Stdout == nil && cmd.Stderr == nil { 
  27.       data, err := cmdOutput(cmd, true) 
  28.       if err != nil { 
  29.          return fmt.Errorf("%s: %s", err, data) 
  30.       } 
  31.       return nil 
  32.    } 
  33.    ec, err := Monitor.Start(cmd) 
  34.    if err != nil { 
  35.       return err 
  36.    } 
  37.    if opts != nil && opts.IO != nil { 
  38.       if c, ok := opts.IO.(StartCloser); ok { 
  39.          if err := c.CloseAfterStart(); err != nil { 
  40.             return err 
  41.          } 
  42.       } 
  43.    } 
  44.    status, err := Monitor.Wait(cmd, ec) 
  45.    if err == nil && status != 0 { 
  46.       err = fmt.Errorf("%s did not terminate sucessfully", cmd.Args[0]) 
  47.    } 
  48.    return err 

因此是 runc 在运行后输出了 exec failed: EOF: unknown 这个错误。

将 runc 指令循环执行,可少量复现。经过排查,发现 runc exec 在运行期间会读取 container 的 state.json,并使用 json decode 时出现异常。

此时联想到开启 kubelet cpu-manager 后,会 update container,也就是更新这个 state.json 文件。导致 runc 读到了部分 cpu-manager 更新的内容。从而导致 json decode 失败。此时排查 runc EOF 和 kubelet cpu-manager update container(默认每 10s 更新一次) 的时间,发现时间点刚好吻合,验证猜想。

查看 runc 是否有修复,发现了这个 pr: https://github.com/opencontainers/runc/pull/2467。 修复思路是将 saveState 变成原子操作,这样就不会出现读取 state.json 时,读到部分写入的内容,导致 unexpected EOF (或 EOF)的问题

 
 
 
  1. // 原来的 
  2. func (c *linuxContainer) saveState(s *State) error { 
  3.    f, err := os.Create(filepath.Join(c.root, stateFilename)) 
  4.    if err != nil { 
  5.       return err 
  6.    } 
  7.    defer f.Close() 
  8.    return utils.WriteJSON(f, s) 
  9. // 修复后的 
  10. func (c *linuxContainer) saveState(s *State) (retErr error) { 
  11.         tmpFile, err := ioutil.TempFile(c.root, "state-") 
  12.         if err != nil { 
  13.                 return err 
  14.         } 
  15.  
  16.         defer func() { 
  17.                 if retErr != nil { 
  18.                         tmpFile.Close() 
  19.                         os.Remove(tmpFile.Name()) 
  20.                 } 
  21.         }() 
  22.  
  23.         err = utils.WriteJSON(tmpFile, s) 
  24.         if err != nil { 
  25.                 return err 
  26.         } 
  27.         err = tmpFile.Close() 
  28.         if err != nil { 
  29.                 return err 
  30.         } 
  31.  
  32.         stateFilePath := filepath.Join(c.root, stateFilename) 
  33.         return os.Rename(tmpFile.Name(), stateFilePath) 

五、解决

关闭cpu-manager

 

升级runc

 

本文标题:聊聊DockerEOF问题排查
网页网址:http://www.hantingmc.com/qtweb/news14/275564.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联