daemon.go 15 KB

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