daemon.go 17 KB

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