remote_daemon.go 7.6 KB

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