remote_daemon.go 8.4 KB

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