daemon.go 16 KB

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