remote_daemon.go 7.6 KB

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