remote_daemon.go 9.0 KB

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