daemon.go 15 KB

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