remote_daemon.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. logrus.WithField("pid", pid).
  139. Infof("libcontainerd: %s is still running", binaryName)
  140. return nil
  141. }
  142. configFile, err := r.getContainerdConfig()
  143. if err != nil {
  144. return err
  145. }
  146. args := []string{"--config", configFile}
  147. if r.Debug.Level != "" {
  148. args = append(args, "--log-level", r.Debug.Level)
  149. }
  150. cmd := exec.Command(binaryName, args...)
  151. // redirect containerd logs to docker logs
  152. cmd.Stdout = os.Stdout
  153. cmd.Stderr = os.Stderr
  154. cmd.SysProcAttr = containerdSysProcAttr()
  155. // clear the NOTIFY_SOCKET from the env when starting containerd
  156. cmd.Env = nil
  157. for _, e := range os.Environ() {
  158. if !strings.HasPrefix(e, "NOTIFY_SOCKET") {
  159. cmd.Env = append(cmd.Env, e)
  160. }
  161. }
  162. if err := cmd.Start(); err != nil {
  163. return err
  164. }
  165. r.daemonWaitCh = make(chan struct{})
  166. go func() {
  167. // Reap our child when needed
  168. if err := cmd.Wait(); err != nil {
  169. r.logger.WithError(err).Errorf("containerd did not exit successfully")
  170. }
  171. close(r.daemonWaitCh)
  172. }()
  173. r.daemonPid = cmd.Process.Pid
  174. err = os.WriteFile(filepath.Join(r.stateDir, pidFile), []byte(fmt.Sprintf("%d", r.daemonPid)), 0660)
  175. if err != nil {
  176. system.KillProcess(r.daemonPid)
  177. return errors.Wrap(err, "libcontainerd: failed to save daemon pid to disk")
  178. }
  179. logrus.WithField("pid", r.daemonPid).
  180. Infof("libcontainerd: started new %s process", binaryName)
  181. return nil
  182. }
  183. func (r *remote) monitorDaemon(ctx context.Context) {
  184. var (
  185. transientFailureCount = 0
  186. client *containerd.Client
  187. err error
  188. delay time.Duration
  189. timer = time.NewTimer(0)
  190. started bool
  191. )
  192. defer func() {
  193. if r.daemonPid != -1 {
  194. r.stopDaemon()
  195. }
  196. // cleanup some files
  197. os.Remove(filepath.Join(r.stateDir, pidFile))
  198. r.platformCleanup()
  199. close(r.daemonStopCh)
  200. timer.Stop()
  201. }()
  202. // ensure no races on sending to timer.C even though there is a 0 duration.
  203. if !timer.Stop() {
  204. <-timer.C
  205. }
  206. for {
  207. timer.Reset(delay)
  208. select {
  209. case <-ctx.Done():
  210. r.logger.Info("stopping healthcheck following graceful shutdown")
  211. if client != nil {
  212. client.Close()
  213. }
  214. return
  215. case <-timer.C:
  216. }
  217. if r.daemonPid == -1 {
  218. if r.daemonWaitCh != nil {
  219. select {
  220. case <-ctx.Done():
  221. r.logger.Info("stopping containerd startup following graceful shutdown")
  222. return
  223. case <-r.daemonWaitCh:
  224. }
  225. }
  226. os.RemoveAll(r.GRPC.Address)
  227. if err := r.startContainerd(); err != nil {
  228. if !started {
  229. r.daemonStartCh <- err
  230. return
  231. }
  232. r.logger.WithError(err).Error("failed restarting containerd")
  233. delay = 50 * time.Millisecond
  234. continue
  235. }
  236. client, err = containerd.New(r.GRPC.Address, containerd.WithTimeout(60*time.Second))
  237. if err != nil {
  238. r.logger.WithError(err).Error("failed connecting to containerd")
  239. delay = 100 * time.Millisecond
  240. continue
  241. }
  242. logrus.WithField("address", r.GRPC.Address).Debug("Created containerd monitoring client")
  243. }
  244. if client != nil {
  245. tctx, cancel := context.WithTimeout(ctx, healthCheckTimeout)
  246. _, err := client.IsServing(tctx)
  247. cancel()
  248. if err == nil {
  249. if !started {
  250. close(r.daemonStartCh)
  251. started = true
  252. }
  253. transientFailureCount = 0
  254. select {
  255. case <-r.daemonWaitCh:
  256. case <-ctx.Done():
  257. }
  258. // Set a small delay in case there is a recurring failure (or bug in this code)
  259. // to ensure we don't end up in a super tight loop.
  260. delay = 500 * time.Millisecond
  261. continue
  262. }
  263. r.logger.WithError(err).WithField("binary", binaryName).Debug("daemon is not responding")
  264. transientFailureCount++
  265. if transientFailureCount < maxConnectionRetryCount || system.IsProcessAlive(r.daemonPid) {
  266. delay = time.Duration(transientFailureCount) * 200 * time.Millisecond
  267. continue
  268. }
  269. client.Close()
  270. client = nil
  271. }
  272. if system.IsProcessAlive(r.daemonPid) {
  273. r.logger.WithField("pid", r.daemonPid).Info("killing and restarting containerd")
  274. r.killDaemon()
  275. }
  276. r.daemonPid = -1
  277. delay = 0
  278. transientFailureCount = 0
  279. }
  280. }