remote_daemon.go 8.2 KB

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