daemon.go 15 KB

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