remote_daemon.go 7.2 KB

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