自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

聊聊Docker EOF問題排查

安全 應用安全
問題排查過程,源碼部分均由我的開發(fā)同事排查和記錄;在征得其同意后,由我發(fā)表在此。

[[402863]]

本文轉載自微信公眾號「運維開發(fā)故事」,作者運維開發(fā)故事。轉載本文請聯(lián)系運維開發(fā)故事公眾號。

一、前言

問題排查過程,源碼部分均由我的開發(fā)同事排查和記錄;在征得其同意后,由我發(fā)表在此。

二、問題

某天接到客戶反饋,pod的事件中出現(xiàn)大量的 warning event: Readiness probe failed: OCI runtime exec failed: exec failed: EOF: unknown。但不影響客戶訪問該服務。

三、環(huán)境

特別說明:客戶在負責運行業(yè)務的k8s節(jié)點上堅持開啟了cpu-manager

組件 版本  
k8s 1.14.x  

四、排查

1、接到客戶反饋后,檢查該pod所在節(jié)點的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 創(chuàng)建 ExecID
  2. 調用 StartExec 執(zhí)行 exec,并通過 holdHijackedConnection 來重定向輸入輸出。將 inputStream 寫入到 connection,并將 response stream 重定向到 stdout,stderr。
  3. 調用 InspectExec 獲取本次 exec 的運行狀態(tài)和 exitcode

那么日志中打印的報錯就是 response stream 傳遞過來的字符流。也就是說,dockerd 的 response 中包含了錯誤值。

此時去 docker 代碼中查找原因,ExecStart 會調用到 dockerd 的以下代碼:

根據(jù)上面 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 僅出現(xiàn)在 fifo 被 close 掉時,仍然在讀取的情況。即 f.Close() 發(fā)生在 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 的二進制文件執(zhí)行命令 
  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 指令循環(huán)執(zhí)行,可少量復現(xiàn)。經(jīng)過排查,發(fā)現(xiàn) runc exec 在運行期間會讀取 container 的 state.json,并使用 json decode 時出現(xiàn)異常。

此時聯(lián)想到開啟 kubelet cpu-manager 后,會 update container,也就是更新這個 state.json 文件。導致 runc 讀到了部分 cpu-manager 更新的內容。從而導致 json decode 失敗。此時排查 runc EOF 和 kubelet cpu-manager update container(默認每 10s 更新一次) 的時間,發(fā)現(xiàn)時間點剛好吻合,驗證猜想。

查看 runc 是否有修復,發(fā)現(xiàn)了這個 pr: https://github.com/opencontainers/runc/pull/2467。 修復思路是將 saveState 變成原子操作,這樣就不會出現(xiàn)讀取 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

 

責任編輯:武曉燕 來源: 運維開發(fā)故事
相關推薦

2021-11-14 05:00:56

排查Sdk方式

2020-05-09 13:49:00

內存空間垃圾

2021-08-24 08:01:15

死鎖工具多線編程

2024-08-14 14:20:00

2022-07-26 07:14:52

Docker宿主命令

2022-01-26 19:42:05

MySQL亂碼排查

2021-12-01 15:03:56

Java開發(fā)代碼

2024-10-29 08:08:44

2024-02-21 08:19:54

2024-12-02 09:10:15

Redis性能優(yōu)化

2022-03-04 08:45:11

Docker開源Linux

2020-12-04 14:19:08

KubernetesDocker容器

2021-11-09 06:55:03

SQLServer排序

2021-10-14 07:28:03

Kubernetes通用排查

2021-06-28 08:00:00

Python開發(fā)編程語言

2023-07-26 07:18:54

死鎖線程池

2024-08-19 00:10:00

C++內存

2023-02-10 21:18:10

IO測試磁盤

2018-11-06 12:12:00

MySQL內存排查

2015-07-20 10:23:24

NET內存問題排查
點贊
收藏

51CTO技術棧公眾號