daemon.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. package main
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "fmt"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "time"
  10. "github.com/docker/distribution/uuid"
  11. "github.com/docker/docker/api"
  12. apiserver "github.com/docker/docker/api/server"
  13. buildbackend "github.com/docker/docker/api/server/backend/build"
  14. "github.com/docker/docker/api/server/middleware"
  15. "github.com/docker/docker/api/server/router"
  16. "github.com/docker/docker/api/server/router/build"
  17. checkpointrouter "github.com/docker/docker/api/server/router/checkpoint"
  18. "github.com/docker/docker/api/server/router/container"
  19. distributionrouter "github.com/docker/docker/api/server/router/distribution"
  20. "github.com/docker/docker/api/server/router/image"
  21. "github.com/docker/docker/api/server/router/network"
  22. pluginrouter "github.com/docker/docker/api/server/router/plugin"
  23. sessionrouter "github.com/docker/docker/api/server/router/session"
  24. swarmrouter "github.com/docker/docker/api/server/router/swarm"
  25. systemrouter "github.com/docker/docker/api/server/router/system"
  26. "github.com/docker/docker/api/server/router/volume"
  27. "github.com/docker/docker/builder/dockerfile"
  28. "github.com/docker/docker/builder/fscache"
  29. "github.com/docker/docker/cli/debug"
  30. "github.com/docker/docker/daemon"
  31. "github.com/docker/docker/daemon/cluster"
  32. "github.com/docker/docker/daemon/config"
  33. "github.com/docker/docker/daemon/listeners"
  34. "github.com/docker/docker/daemon/logger"
  35. "github.com/docker/docker/dockerversion"
  36. "github.com/docker/docker/libcontainerd"
  37. dopts "github.com/docker/docker/opts"
  38. "github.com/docker/docker/pkg/authorization"
  39. "github.com/docker/docker/pkg/jsonlog"
  40. "github.com/docker/docker/pkg/pidfile"
  41. "github.com/docker/docker/pkg/plugingetter"
  42. "github.com/docker/docker/pkg/signal"
  43. "github.com/docker/docker/pkg/system"
  44. "github.com/docker/docker/plugin"
  45. "github.com/docker/docker/registry"
  46. "github.com/docker/docker/runconfig"
  47. "github.com/docker/go-connections/tlsconfig"
  48. swarmapi "github.com/docker/swarmkit/api"
  49. "github.com/moby/buildkit/session"
  50. "github.com/pkg/errors"
  51. "github.com/sirupsen/logrus"
  52. "github.com/spf13/pflag"
  53. )
  54. // DaemonCli represents the daemon CLI.
  55. type DaemonCli struct {
  56. *config.Config
  57. configFile *string
  58. flags *pflag.FlagSet
  59. api *apiserver.Server
  60. d *daemon.Daemon
  61. authzMiddleware *authorization.Middleware // authzMiddleware enables to dynamically reload the authorization plugins
  62. }
  63. // NewDaemonCli returns a daemon CLI
  64. func NewDaemonCli() *DaemonCli {
  65. return &DaemonCli{}
  66. }
  67. func (cli *DaemonCli) start(opts *daemonOptions) (err error) {
  68. stopc := make(chan bool)
  69. defer close(stopc)
  70. // warn from uuid package when running the daemon
  71. uuid.Loggerf = logrus.Warnf
  72. opts.SetDefaultOptions(opts.flags)
  73. if cli.Config, err = loadDaemonCliConfig(opts); err != nil {
  74. return err
  75. }
  76. cli.configFile = &opts.configFile
  77. cli.flags = opts.flags
  78. if cli.Config.Debug {
  79. debug.Enable()
  80. }
  81. if cli.Config.Experimental {
  82. logrus.Warn("Running experimental build")
  83. }
  84. logrus.SetFormatter(&logrus.TextFormatter{
  85. TimestampFormat: jsonlog.RFC3339NanoFixed,
  86. DisableColors: cli.Config.RawLogs,
  87. FullTimestamp: true,
  88. })
  89. if err := setDefaultUmask(); err != nil {
  90. return fmt.Errorf("Failed to set umask: %v", err)
  91. }
  92. if len(cli.LogConfig.Config) > 0 {
  93. if err := logger.ValidateLogOpts(cli.LogConfig.Type, cli.LogConfig.Config); err != nil {
  94. return fmt.Errorf("Failed to set log opts: %v", err)
  95. }
  96. }
  97. // Create the daemon root before we create ANY other files (PID, or migrate keys)
  98. // to ensure the appropriate ACL is set (particularly relevant on Windows)
  99. if err := daemon.CreateDaemonRoot(cli.Config); err != nil {
  100. return err
  101. }
  102. if cli.Pidfile != "" {
  103. pf, err := pidfile.New(cli.Pidfile)
  104. if err != nil {
  105. return fmt.Errorf("Error starting daemon: %v", err)
  106. }
  107. defer func() {
  108. if err := pf.Remove(); err != nil {
  109. logrus.Error(err)
  110. }
  111. }()
  112. }
  113. // TODO: extract to newApiServerConfig()
  114. serverConfig := &apiserver.Config{
  115. Logging: true,
  116. SocketGroup: cli.Config.SocketGroup,
  117. Version: dockerversion.Version,
  118. EnableCors: cli.Config.EnableCors,
  119. CorsHeaders: cli.Config.CorsHeaders,
  120. }
  121. if cli.Config.TLS {
  122. tlsOptions := tlsconfig.Options{
  123. CAFile: cli.Config.CommonTLSOptions.CAFile,
  124. CertFile: cli.Config.CommonTLSOptions.CertFile,
  125. KeyFile: cli.Config.CommonTLSOptions.KeyFile,
  126. ExclusiveRootPools: true,
  127. }
  128. if cli.Config.TLSVerify {
  129. // server requires and verifies client's certificate
  130. tlsOptions.ClientAuth = tls.RequireAndVerifyClientCert
  131. }
  132. tlsConfig, err := tlsconfig.Server(tlsOptions)
  133. if err != nil {
  134. return err
  135. }
  136. serverConfig.TLSConfig = tlsConfig
  137. }
  138. if len(cli.Config.Hosts) == 0 {
  139. cli.Config.Hosts = make([]string, 1)
  140. }
  141. cli.api = apiserver.New(serverConfig)
  142. var hosts []string
  143. for i := 0; i < len(cli.Config.Hosts); i++ {
  144. var err error
  145. if cli.Config.Hosts[i], err = dopts.ParseHost(cli.Config.TLS, cli.Config.Hosts[i]); err != nil {
  146. return fmt.Errorf("error parsing -H %s : %v", cli.Config.Hosts[i], err)
  147. }
  148. protoAddr := cli.Config.Hosts[i]
  149. protoAddrParts := strings.SplitN(protoAddr, "://", 2)
  150. if len(protoAddrParts) != 2 {
  151. return fmt.Errorf("bad format %s, expected PROTO://ADDR", protoAddr)
  152. }
  153. proto := protoAddrParts[0]
  154. addr := protoAddrParts[1]
  155. // It's a bad idea to bind to TCP without tlsverify.
  156. if proto == "tcp" && (serverConfig.TLSConfig == nil || serverConfig.TLSConfig.ClientAuth != tls.RequireAndVerifyClientCert) {
  157. logrus.Warn("[!] DON'T BIND ON ANY IP ADDRESS WITHOUT setting --tlsverify IF YOU DON'T KNOW WHAT YOU'RE DOING [!]")
  158. }
  159. ls, err := listeners.Init(proto, addr, serverConfig.SocketGroup, serverConfig.TLSConfig)
  160. if err != nil {
  161. return err
  162. }
  163. ls = wrapListeners(proto, ls)
  164. // If we're binding to a TCP port, make sure that a container doesn't try to use it.
  165. if proto == "tcp" {
  166. if err := allocateDaemonPort(addr); err != nil {
  167. return err
  168. }
  169. }
  170. logrus.Debugf("Listener created for HTTP on %s (%s)", proto, addr)
  171. hosts = append(hosts, protoAddrParts[1])
  172. cli.api.Accept(addr, ls...)
  173. }
  174. registryService := registry.NewService(cli.Config.ServiceOptions)
  175. containerdRemote, err := libcontainerd.New(cli.getLibcontainerdRoot(), cli.getPlatformRemoteOptions()...)
  176. if err != nil {
  177. return err
  178. }
  179. signal.Trap(func() {
  180. cli.stop()
  181. <-stopc // wait for daemonCli.start() to return
  182. }, logrus.StandardLogger())
  183. // Notify that the API is active, but before daemon is set up.
  184. preNotifySystem()
  185. pluginStore := plugin.NewStore()
  186. if err := cli.initMiddlewares(cli.api, serverConfig, pluginStore); err != nil {
  187. logrus.Fatalf("Error creating middlewares: %v", err)
  188. }
  189. if system.LCOWSupported() {
  190. logrus.Warnln("LCOW support is enabled - this feature is incomplete")
  191. }
  192. d, err := daemon.NewDaemon(cli.Config, registryService, containerdRemote, pluginStore)
  193. if err != nil {
  194. return fmt.Errorf("Error starting daemon: %v", err)
  195. }
  196. d.StoreHosts(hosts)
  197. // validate after NewDaemon has restored enabled plugins. Dont change order.
  198. if err := validateAuthzPlugins(cli.Config.AuthorizationPlugins, pluginStore); err != nil {
  199. return fmt.Errorf("Error validating authorization plugin: %v", err)
  200. }
  201. // TODO: move into startMetricsServer()
  202. if cli.Config.MetricsAddress != "" {
  203. if !d.HasExperimental() {
  204. return fmt.Errorf("metrics-addr is only supported when experimental is enabled")
  205. }
  206. if err := startMetricsServer(cli.Config.MetricsAddress); err != nil {
  207. return err
  208. }
  209. }
  210. // TODO: createAndStartCluster()
  211. name, _ := os.Hostname()
  212. // Use a buffered channel to pass changes from store watch API to daemon
  213. // A buffer allows store watch API and daemon processing to not wait for each other
  214. watchStream := make(chan *swarmapi.WatchMessage, 32)
  215. c, err := cluster.New(cluster.Config{
  216. Root: cli.Config.Root,
  217. Name: name,
  218. Backend: d,
  219. PluginBackend: d.PluginManager(),
  220. NetworkSubnetsProvider: d,
  221. DefaultAdvertiseAddr: cli.Config.SwarmDefaultAdvertiseAddr,
  222. RuntimeRoot: cli.getSwarmRunRoot(),
  223. WatchStream: watchStream,
  224. })
  225. if err != nil {
  226. logrus.Fatalf("Error creating cluster component: %v", err)
  227. }
  228. d.SetCluster(c)
  229. err = c.Start()
  230. if err != nil {
  231. logrus.Fatalf("Error starting cluster component: %v", err)
  232. }
  233. // Restart all autostart containers which has a swarm endpoint
  234. // and is not yet running now that we have successfully
  235. // initialized the cluster.
  236. d.RestartSwarmContainers()
  237. logrus.Info("Daemon has completed initialization")
  238. cli.d = d
  239. routerOptions, err := newRouterOptions(cli.Config, d)
  240. if err != nil {
  241. return err
  242. }
  243. routerOptions.api = cli.api
  244. routerOptions.cluster = c
  245. initRouter(routerOptions)
  246. // process cluster change notifications
  247. watchCtx, cancel := context.WithCancel(context.Background())
  248. defer cancel()
  249. go d.ProcessClusterNotifications(watchCtx, watchStream)
  250. cli.setupConfigReloadTrap()
  251. // The serve API routine never exits unless an error occurs
  252. // We need to start it as a goroutine and wait on it so
  253. // daemon doesn't exit
  254. serveAPIWait := make(chan error)
  255. go cli.api.Wait(serveAPIWait)
  256. // after the daemon is done setting up we can notify systemd api
  257. notifySystem()
  258. // Daemon is fully initialized and handling API traffic
  259. // Wait for serve API to complete
  260. errAPI := <-serveAPIWait
  261. c.Cleanup()
  262. shutdownDaemon(d)
  263. containerdRemote.Cleanup()
  264. if errAPI != nil {
  265. return fmt.Errorf("Shutting down due to ServeAPI error: %v", errAPI)
  266. }
  267. return nil
  268. }
  269. type routerOptions struct {
  270. sessionManager *session.Manager
  271. buildBackend *buildbackend.Backend
  272. buildCache *fscache.FSCache
  273. daemon *daemon.Daemon
  274. api *apiserver.Server
  275. cluster *cluster.Cluster
  276. }
  277. func newRouterOptions(config *config.Config, daemon *daemon.Daemon) (routerOptions, error) {
  278. opts := routerOptions{}
  279. sm, err := session.NewManager()
  280. if err != nil {
  281. return opts, errors.Wrap(err, "failed to create sessionmanager")
  282. }
  283. builderStateDir := filepath.Join(config.Root, "builder")
  284. buildCache, err := fscache.NewFSCache(fscache.Opt{
  285. Backend: fscache.NewNaiveCacheBackend(builderStateDir),
  286. Root: builderStateDir,
  287. GCPolicy: fscache.GCPolicy{ // TODO: expose this in config
  288. MaxSize: 1024 * 1024 * 512, // 512MB
  289. MaxKeepDuration: 7 * 24 * time.Hour, // 1 week
  290. },
  291. })
  292. if err != nil {
  293. return opts, errors.Wrap(err, "failed to create fscache")
  294. }
  295. manager, err := dockerfile.NewBuildManager(daemon, sm, buildCache, daemon.IDMappings())
  296. if err != nil {
  297. return opts, err
  298. }
  299. bb, err := buildbackend.NewBackend(daemon, manager, buildCache)
  300. if err != nil {
  301. return opts, errors.Wrap(err, "failed to create buildmanager")
  302. }
  303. return routerOptions{
  304. sessionManager: sm,
  305. buildBackend: bb,
  306. buildCache: buildCache,
  307. daemon: daemon,
  308. }, nil
  309. }
  310. func (cli *DaemonCli) reloadConfig() {
  311. reload := func(config *config.Config) {
  312. // Revalidate and reload the authorization plugins
  313. if err := validateAuthzPlugins(config.AuthorizationPlugins, cli.d.PluginStore); err != nil {
  314. logrus.Fatalf("Error validating authorization plugin: %v", err)
  315. return
  316. }
  317. cli.authzMiddleware.SetPlugins(config.AuthorizationPlugins)
  318. if err := cli.d.Reload(config); err != nil {
  319. logrus.Errorf("Error reconfiguring the daemon: %v", err)
  320. return
  321. }
  322. if config.IsValueSet("debug") {
  323. debugEnabled := debug.IsEnabled()
  324. switch {
  325. case debugEnabled && !config.Debug: // disable debug
  326. debug.Disable()
  327. case config.Debug && !debugEnabled: // enable debug
  328. debug.Enable()
  329. }
  330. }
  331. }
  332. if err := config.Reload(*cli.configFile, cli.flags, reload); err != nil {
  333. logrus.Error(err)
  334. }
  335. }
  336. func (cli *DaemonCli) stop() {
  337. cli.api.Close()
  338. }
  339. // shutdownDaemon just wraps daemon.Shutdown() to handle a timeout in case
  340. // d.Shutdown() is waiting too long to kill container or worst it's
  341. // blocked there
  342. func shutdownDaemon(d *daemon.Daemon) {
  343. shutdownTimeout := d.ShutdownTimeout()
  344. ch := make(chan struct{})
  345. go func() {
  346. d.Shutdown()
  347. close(ch)
  348. }()
  349. if shutdownTimeout < 0 {
  350. <-ch
  351. logrus.Debug("Clean shutdown succeeded")
  352. return
  353. }
  354. select {
  355. case <-ch:
  356. logrus.Debug("Clean shutdown succeeded")
  357. case <-time.After(time.Duration(shutdownTimeout) * time.Second):
  358. logrus.Error("Force shutdown daemon")
  359. }
  360. }
  361. func loadDaemonCliConfig(opts *daemonOptions) (*config.Config, error) {
  362. conf := opts.daemonConfig
  363. flags := opts.flags
  364. conf.Debug = opts.Debug
  365. conf.Hosts = opts.Hosts
  366. conf.LogLevel = opts.LogLevel
  367. conf.TLS = opts.TLS
  368. conf.TLSVerify = opts.TLSVerify
  369. conf.CommonTLSOptions = config.CommonTLSOptions{}
  370. if opts.TLSOptions != nil {
  371. conf.CommonTLSOptions.CAFile = opts.TLSOptions.CAFile
  372. conf.CommonTLSOptions.CertFile = opts.TLSOptions.CertFile
  373. conf.CommonTLSOptions.KeyFile = opts.TLSOptions.KeyFile
  374. }
  375. if conf.TrustKeyPath == "" {
  376. conf.TrustKeyPath = filepath.Join(
  377. getDaemonConfDir(conf.Root),
  378. defaultTrustKeyFile)
  379. }
  380. if flags.Changed("graph") && flags.Changed("data-root") {
  381. return nil, fmt.Errorf(`cannot specify both "--graph" and "--data-root" option`)
  382. }
  383. if opts.configFile != "" {
  384. c, err := config.MergeDaemonConfigurations(conf, flags, opts.configFile)
  385. if err != nil {
  386. if flags.Changed("config-file") || !os.IsNotExist(err) {
  387. return nil, fmt.Errorf("unable to configure the Docker daemon with file %s: %v\n", opts.configFile, err)
  388. }
  389. }
  390. // the merged configuration can be nil if the config file didn't exist.
  391. // leave the current configuration as it is if when that happens.
  392. if c != nil {
  393. conf = c
  394. }
  395. }
  396. if err := config.Validate(conf); err != nil {
  397. return nil, err
  398. }
  399. if conf.V2Only == false {
  400. logrus.Warnf(`The "disable-legacy-registry" option is deprecated and wil be removed in Docker v17.12. Interacting with legacy (v1) registries will no longer be supported in Docker v17.12"`)
  401. }
  402. if flags.Changed("graph") {
  403. logrus.Warnf(`The "-g / --graph" flag is deprecated. Please use "--data-root" instead`)
  404. }
  405. // Labels of the docker engine used to allow multiple values associated with the same key.
  406. // This is deprecated in 1.13, and, be removed after 3 release cycles.
  407. // The following will check the conflict of labels, and report a warning for deprecation.
  408. //
  409. // TODO: After 3 release cycles (17.12) an error will be returned, and labels will be
  410. // sanitized to consolidate duplicate key-value pairs (config.Labels = newLabels):
  411. //
  412. // newLabels, err := daemon.GetConflictFreeLabels(config.Labels)
  413. // if err != nil {
  414. // return nil, err
  415. // }
  416. // config.Labels = newLabels
  417. //
  418. if _, err := config.GetConflictFreeLabels(conf.Labels); err != nil {
  419. logrus.Warnf("Engine labels with duplicate keys and conflicting values have been deprecated: %s", err)
  420. }
  421. // Regardless of whether the user sets it to true or false, if they
  422. // specify TLSVerify at all then we need to turn on TLS
  423. if conf.IsValueSet(FlagTLSVerify) {
  424. conf.TLS = true
  425. }
  426. // ensure that the log level is the one set after merging configurations
  427. setLogLevel(conf.LogLevel)
  428. return conf, nil
  429. }
  430. func initRouter(opts routerOptions) {
  431. decoder := runconfig.ContainerDecoder{}
  432. routers := []router.Router{
  433. // we need to add the checkpoint router before the container router or the DELETE gets masked
  434. checkpointrouter.NewRouter(opts.daemon, decoder),
  435. container.NewRouter(opts.daemon, decoder),
  436. image.NewRouter(opts.daemon, decoder),
  437. systemrouter.NewRouter(opts.daemon, opts.cluster, opts.buildCache),
  438. volume.NewRouter(opts.daemon),
  439. build.NewRouter(opts.buildBackend, opts.daemon),
  440. sessionrouter.NewRouter(opts.sessionManager),
  441. swarmrouter.NewRouter(opts.cluster),
  442. pluginrouter.NewRouter(opts.daemon.PluginManager()),
  443. distributionrouter.NewRouter(opts.daemon),
  444. }
  445. if opts.daemon.NetworkControllerEnabled() {
  446. routers = append(routers, network.NewRouter(opts.daemon, opts.cluster))
  447. }
  448. if opts.daemon.HasExperimental() {
  449. for _, r := range routers {
  450. for _, route := range r.Routes() {
  451. if experimental, ok := route.(router.ExperimentalRoute); ok {
  452. experimental.Enable()
  453. }
  454. }
  455. }
  456. }
  457. opts.api.InitRouter(routers...)
  458. }
  459. // TODO: remove this from cli and return the authzMiddleware
  460. func (cli *DaemonCli) initMiddlewares(s *apiserver.Server, cfg *apiserver.Config, pluginStore *plugin.Store) error {
  461. v := cfg.Version
  462. exp := middleware.NewExperimentalMiddleware(cli.Config.Experimental)
  463. s.UseMiddleware(exp)
  464. vm := middleware.NewVersionMiddleware(v, api.DefaultVersion, api.MinVersion)
  465. s.UseMiddleware(vm)
  466. if cfg.EnableCors || cfg.CorsHeaders != "" {
  467. c := middleware.NewCORSMiddleware(cfg.CorsHeaders)
  468. s.UseMiddleware(c)
  469. }
  470. cli.authzMiddleware = authorization.NewMiddleware(cli.Config.AuthorizationPlugins, pluginStore)
  471. cli.Config.AuthzMiddleware = cli.authzMiddleware
  472. s.UseMiddleware(cli.authzMiddleware)
  473. return nil
  474. }
  475. // validates that the plugins requested with the --authorization-plugin flag are valid AuthzDriver
  476. // plugins present on the host and available to the daemon
  477. func validateAuthzPlugins(requestedPlugins []string, pg plugingetter.PluginGetter) error {
  478. for _, reqPlugin := range requestedPlugins {
  479. if _, err := pg.Get(reqPlugin, authorization.AuthZApiImplements, plugingetter.Lookup); err != nil {
  480. return err
  481. }
  482. }
  483. return nil
  484. }