daemon.go 16 KB

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