remote_daemon.go 6.9 KB

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