remote_daemon.go 7.4 KB

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