remote_daemon.go 7.4 KB

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