remote_daemon.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. timeout := time.NewTimer(startupTimeout)
  78. defer timeout.Stop()
  79. select {
  80. case <-timeout.C:
  81. return nil, errors.New("timeout waiting for containerd to start")
  82. case err := <-r.daemonStartCh:
  83. if err != nil {
  84. return nil, err
  85. }
  86. }
  87. return r, nil
  88. }
  89. func (r *remote) WaitTimeout(d time.Duration) error {
  90. timeout := time.NewTimer(d)
  91. defer timeout.Stop()
  92. select {
  93. case <-timeout.C:
  94. return errors.New("timeout waiting for containerd to stop")
  95. case <-r.daemonStopCh:
  96. }
  97. return nil
  98. }
  99. func (r *remote) Address() string {
  100. return r.GRPC.Address
  101. }
  102. func (r *remote) getContainerdPid() (int, error) {
  103. pidFile := filepath.Join(r.stateDir, pidFile)
  104. f, err := os.OpenFile(pidFile, os.O_RDWR, 0600)
  105. if err != nil {
  106. if os.IsNotExist(err) {
  107. return -1, nil
  108. }
  109. return -1, err
  110. }
  111. defer f.Close()
  112. b := make([]byte, 8)
  113. n, err := f.Read(b)
  114. if err != nil && err != io.EOF {
  115. return -1, err
  116. }
  117. if n > 0 {
  118. pid, err := strconv.ParseUint(string(b[:n]), 10, 64)
  119. if err != nil {
  120. return -1, err
  121. }
  122. if system.IsProcessAlive(int(pid)) {
  123. return int(pid), nil
  124. }
  125. }
  126. return -1, nil
  127. }
  128. func (r *remote) getContainerdConfig() (string, error) {
  129. path := filepath.Join(r.stateDir, configFile)
  130. f, err := os.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
  131. if err != nil {
  132. return "", errors.Wrapf(err, "failed to open containerd config file at %s", path)
  133. }
  134. defer f.Close()
  135. enc := toml.NewEncoder(f)
  136. if err = enc.Encode(r.Config); err != nil {
  137. return "", errors.Wrapf(err, "failed to encode general config")
  138. }
  139. if err = enc.Encode(r.pluginConfs); err != nil {
  140. return "", errors.Wrapf(err, "failed to encode plugin configs")
  141. }
  142. return path, nil
  143. }
  144. func (r *remote) startContainerd() error {
  145. pid, err := r.getContainerdPid()
  146. if err != nil {
  147. return err
  148. }
  149. if pid != -1 {
  150. r.daemonPid = pid
  151. logrus.WithField("pid", pid).
  152. Infof("libcontainerd: %s is still running", binaryName)
  153. return nil
  154. }
  155. configFile, err := r.getContainerdConfig()
  156. if err != nil {
  157. return err
  158. }
  159. args := []string{"--config", configFile}
  160. if r.Debug.Level != "" {
  161. args = append(args, "--log-level", r.Debug.Level)
  162. }
  163. cmd := exec.Command(binaryName, args...)
  164. // redirect containerd logs to docker logs
  165. cmd.Stdout = os.Stdout
  166. cmd.Stderr = os.Stderr
  167. cmd.SysProcAttr = containerdSysProcAttr()
  168. // clear the NOTIFY_SOCKET from the env when starting containerd
  169. cmd.Env = nil
  170. for _, e := range os.Environ() {
  171. if !strings.HasPrefix(e, "NOTIFY_SOCKET") {
  172. cmd.Env = append(cmd.Env, e)
  173. }
  174. }
  175. if err := cmd.Start(); err != nil {
  176. return err
  177. }
  178. r.daemonWaitCh = make(chan struct{})
  179. go func() {
  180. // Reap our child when needed
  181. if err := cmd.Wait(); err != nil {
  182. r.logger.WithError(err).Errorf("containerd did not exit successfully")
  183. }
  184. close(r.daemonWaitCh)
  185. }()
  186. r.daemonPid = cmd.Process.Pid
  187. err = ioutil.WriteFile(filepath.Join(r.stateDir, pidFile), []byte(fmt.Sprintf("%d", r.daemonPid)), 0660)
  188. if err != nil {
  189. system.KillProcess(r.daemonPid)
  190. return errors.Wrap(err, "libcontainerd: failed to save daemon pid to disk")
  191. }
  192. logrus.WithField("pid", r.daemonPid).
  193. Infof("libcontainerd: started new %s process", binaryName)
  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(filepath.Join(r.stateDir, 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. }
  256. if client != nil {
  257. tctx, cancel := context.WithTimeout(ctx, healthCheckTimeout)
  258. _, err := client.IsServing(tctx)
  259. cancel()
  260. if err == nil {
  261. if !started {
  262. close(r.daemonStartCh)
  263. started = true
  264. }
  265. transientFailureCount = 0
  266. delay = 500 * time.Millisecond
  267. continue
  268. }
  269. r.logger.WithError(err).WithField("binary", binaryName).Debug("daemon is not responding")
  270. transientFailureCount++
  271. if transientFailureCount < maxConnectionRetryCount || system.IsProcessAlive(r.daemonPid) {
  272. delay = time.Duration(transientFailureCount) * 200 * time.Millisecond
  273. continue
  274. }
  275. }
  276. if system.IsProcessAlive(r.daemonPid) {
  277. r.logger.WithField("pid", r.daemonPid).Info("killing and restarting containerd")
  278. r.killDaemon()
  279. }
  280. client.Close()
  281. client = nil
  282. r.daemonPid = -1
  283. delay = 0
  284. transientFailureCount = 0
  285. }
  286. }