remote_daemon.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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. if err != nil {
  159. startedCh <- err
  160. return
  161. }
  162. r.daemonWaitCh = make(chan struct{})
  163. startedCh <- nil
  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. }