remote_daemon.go 8.4 KB

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