remote_daemon.go 8.1 KB

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