remote_daemon.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. package supervisor // import "github.com/docker/docker/libcontainerd/supervisor"
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "os"
  7. "os/exec"
  8. "path/filepath"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "github.com/containerd/containerd"
  13. "github.com/containerd/containerd/services/server/config"
  14. "github.com/docker/docker/pkg/system"
  15. "github.com/pelletier/go-toml"
  16. "github.com/pkg/errors"
  17. "github.com/sirupsen/logrus"
  18. )
  19. const (
  20. maxConnectionRetryCount = 3
  21. healthCheckTimeout = 3 * time.Second
  22. shutdownTimeout = 15 * time.Second
  23. startupTimeout = 15 * time.Second
  24. configFile = "containerd.toml"
  25. binaryName = "containerd"
  26. pidFile = "containerd.pid"
  27. )
  28. type remote struct {
  29. config.Config
  30. daemonPid int
  31. logger *logrus.Entry
  32. daemonWaitCh chan struct{}
  33. daemonStartCh chan error
  34. daemonStopCh chan struct{}
  35. stateDir string
  36. }
  37. // Daemon represents a running containerd daemon
  38. type Daemon interface {
  39. WaitTimeout(time.Duration) error
  40. Address() string
  41. }
  42. // DaemonOpt allows to configure parameters of container daemons
  43. type DaemonOpt func(c *remote) error
  44. // Start starts a containerd daemon and monitors it
  45. func Start(ctx context.Context, rootDir, stateDir string, opts ...DaemonOpt) (Daemon, error) {
  46. r := &remote{
  47. stateDir: stateDir,
  48. Config: config.Config{
  49. Version: 2,
  50. Root: filepath.Join(rootDir, "daemon"),
  51. State: filepath.Join(stateDir, "daemon"),
  52. },
  53. daemonPid: -1,
  54. logger: logrus.WithField("module", "libcontainerd"),
  55. daemonStartCh: make(chan error, 1),
  56. daemonStopCh: make(chan struct{}),
  57. }
  58. for _, opt := range opts {
  59. if err := opt(r); err != nil {
  60. return nil, err
  61. }
  62. }
  63. r.setDefaults()
  64. if err := system.MkdirAll(stateDir, 0700); err != nil {
  65. return nil, err
  66. }
  67. go r.monitorDaemon(ctx)
  68. timeout := time.NewTimer(startupTimeout)
  69. defer timeout.Stop()
  70. select {
  71. case <-timeout.C:
  72. return nil, errors.New("timeout waiting for containerd to start")
  73. case err := <-r.daemonStartCh:
  74. if err != nil {
  75. return nil, err
  76. }
  77. }
  78. return r, nil
  79. }
  80. func (r *remote) WaitTimeout(d time.Duration) error {
  81. timeout := time.NewTimer(d)
  82. defer timeout.Stop()
  83. select {
  84. case <-timeout.C:
  85. return errors.New("timeout waiting for containerd to stop")
  86. case <-r.daemonStopCh:
  87. }
  88. return nil
  89. }
  90. func (r *remote) Address() string {
  91. return r.GRPC.Address
  92. }
  93. func (r *remote) getContainerdPid() (int, error) {
  94. pidFile := filepath.Join(r.stateDir, pidFile)
  95. f, err := os.OpenFile(pidFile, os.O_RDWR, 0600)
  96. if err != nil {
  97. if os.IsNotExist(err) {
  98. return -1, nil
  99. }
  100. return -1, err
  101. }
  102. defer f.Close()
  103. b := make([]byte, 8)
  104. n, err := f.Read(b)
  105. if err != nil && err != io.EOF {
  106. return -1, err
  107. }
  108. if n > 0 {
  109. pid, err := strconv.ParseUint(string(b[:n]), 10, 64)
  110. if err != nil {
  111. return -1, err
  112. }
  113. if system.IsProcessAlive(int(pid)) {
  114. return int(pid), nil
  115. }
  116. }
  117. return -1, nil
  118. }
  119. func (r *remote) getContainerdConfig() (string, error) {
  120. path := filepath.Join(r.stateDir, configFile)
  121. f, err := os.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
  122. if err != nil {
  123. return "", errors.Wrapf(err, "failed to open containerd config file at %s", path)
  124. }
  125. defer f.Close()
  126. if err := toml.NewEncoder(f).Encode(r); err != nil {
  127. return "", errors.Wrapf(err, "failed to write containerd config file (%s)", path)
  128. }
  129. return path, nil
  130. }
  131. func (r *remote) startContainerd() error {
  132. pid, err := r.getContainerdPid()
  133. if err != nil {
  134. return err
  135. }
  136. if pid != -1 {
  137. r.daemonPid = pid
  138. r.logger.WithField("pid", pid).Infof("%s is still running", binaryName)
  139. return nil
  140. }
  141. configFile, err := r.getContainerdConfig()
  142. if err != nil {
  143. return err
  144. }
  145. args := []string{"--config", configFile}
  146. if r.Debug.Level != "" {
  147. args = append(args, "--log-level", r.Debug.Level)
  148. }
  149. cmd := exec.Command(binaryName, args...)
  150. // redirect containerd logs to docker logs
  151. cmd.Stdout = os.Stdout
  152. cmd.Stderr = os.Stderr
  153. cmd.SysProcAttr = containerdSysProcAttr()
  154. // clear the NOTIFY_SOCKET from the env when starting containerd
  155. cmd.Env = nil
  156. for _, e := range os.Environ() {
  157. if !strings.HasPrefix(e, "NOTIFY_SOCKET") {
  158. cmd.Env = append(cmd.Env, e)
  159. }
  160. }
  161. if err := cmd.Start(); err != nil {
  162. return err
  163. }
  164. r.daemonWaitCh = make(chan struct{})
  165. go func() {
  166. // Reap our child when needed
  167. if err := cmd.Wait(); err != nil {
  168. r.logger.WithError(err).Errorf("containerd did not exit successfully")
  169. }
  170. close(r.daemonWaitCh)
  171. }()
  172. r.daemonPid = cmd.Process.Pid
  173. err = os.WriteFile(filepath.Join(r.stateDir, pidFile), []byte(fmt.Sprintf("%d", r.daemonPid)), 0660)
  174. if err != nil {
  175. system.KillProcess(r.daemonPid)
  176. return errors.Wrap(err, "libcontainerd: failed to save daemon pid to disk")
  177. }
  178. r.logger.WithField("pid", r.daemonPid).Infof("started new %s process", binaryName)
  179. return nil
  180. }
  181. func (r *remote) monitorDaemon(ctx context.Context) {
  182. var (
  183. transientFailureCount = 0
  184. client *containerd.Client
  185. err error
  186. delay time.Duration
  187. timer = time.NewTimer(0)
  188. started bool
  189. )
  190. defer func() {
  191. if r.daemonPid != -1 {
  192. r.stopDaemon()
  193. }
  194. // cleanup some files
  195. os.Remove(filepath.Join(r.stateDir, pidFile))
  196. r.platformCleanup()
  197. close(r.daemonStopCh)
  198. timer.Stop()
  199. }()
  200. // ensure no races on sending to timer.C even though there is a 0 duration.
  201. if !timer.Stop() {
  202. <-timer.C
  203. }
  204. for {
  205. timer.Reset(delay)
  206. select {
  207. case <-ctx.Done():
  208. r.logger.Info("stopping healthcheck following graceful shutdown")
  209. if client != nil {
  210. client.Close()
  211. }
  212. return
  213. case <-timer.C:
  214. }
  215. if r.daemonPid == -1 {
  216. if r.daemonWaitCh != nil {
  217. select {
  218. case <-ctx.Done():
  219. r.logger.Info("stopping containerd startup following graceful shutdown")
  220. return
  221. case <-r.daemonWaitCh:
  222. }
  223. }
  224. os.RemoveAll(r.GRPC.Address)
  225. if err := r.startContainerd(); err != nil {
  226. if !started {
  227. r.daemonStartCh <- err
  228. return
  229. }
  230. r.logger.WithError(err).Error("failed restarting containerd")
  231. delay = 50 * time.Millisecond
  232. continue
  233. }
  234. client, err = containerd.New(r.GRPC.Address, containerd.WithTimeout(60*time.Second))
  235. if err != nil {
  236. r.logger.WithError(err).Error("failed connecting to containerd")
  237. delay = 100 * time.Millisecond
  238. continue
  239. }
  240. r.logger.WithField("address", r.GRPC.Address).Debug("created containerd monitoring client")
  241. }
  242. if client != nil {
  243. tctx, cancel := context.WithTimeout(ctx, healthCheckTimeout)
  244. _, err := client.IsServing(tctx)
  245. cancel()
  246. if err == nil {
  247. if !started {
  248. close(r.daemonStartCh)
  249. started = true
  250. }
  251. transientFailureCount = 0
  252. select {
  253. case <-r.daemonWaitCh:
  254. case <-ctx.Done():
  255. }
  256. // Set a small delay in case there is a recurring failure (or bug in this code)
  257. // to ensure we don't end up in a super tight loop.
  258. delay = 500 * time.Millisecond
  259. continue
  260. }
  261. r.logger.WithError(err).WithField("binary", binaryName).Debug("daemon is not responding")
  262. transientFailureCount++
  263. if transientFailureCount < maxConnectionRetryCount || system.IsProcessAlive(r.daemonPid) {
  264. delay = time.Duration(transientFailureCount) * 200 * time.Millisecond
  265. continue
  266. }
  267. client.Close()
  268. client = nil
  269. }
  270. if system.IsProcessAlive(r.daemonPid) {
  271. r.logger.WithField("pid", r.daemonPid).Info("killing and restarting containerd")
  272. r.killDaemon()
  273. }
  274. r.daemonPid = -1
  275. delay = 0
  276. transientFailureCount = 0
  277. }
  278. }