daemon.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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/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/pkg/system"
  43. "github.com/docker/docker/registry"
  44. "github.com/docker/docker/runconfig"
  45. "github.com/docker/go-connections/tlsconfig"
  46. "github.com/spf13/pflag"
  47. )
  48. const (
  49. flagDaemonConfigFile = "config-file"
  50. )
  51. // DaemonCli represents the daemon CLI.
  52. type DaemonCli struct {
  53. *daemon.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 *daemon.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(cliconfig.Dir(), 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. d, err := daemon.NewDaemon(cli.Config, registryService, containerdRemote)
  225. if err != nil {
  226. return fmt.Errorf("Error starting daemon: %v", err)
  227. }
  228. if cli.Config.MetricsAddress != "" {
  229. if !d.HasExperimental() {
  230. return fmt.Errorf("metrics-addr is only supported when experimental is enabled")
  231. }
  232. if err := startMetricsServer(cli.Config.MetricsAddress); err != nil {
  233. return err
  234. }
  235. }
  236. name, _ := os.Hostname()
  237. c, err := cluster.New(cluster.Config{
  238. Root: cli.Config.Root,
  239. Name: name,
  240. Backend: d,
  241. NetworkSubnetsProvider: d,
  242. DefaultAdvertiseAddr: cli.Config.SwarmDefaultAdvertiseAddr,
  243. RuntimeRoot: cli.getSwarmRunRoot(),
  244. })
  245. if err != nil {
  246. logrus.Fatalf("Error creating cluster component: %v", err)
  247. }
  248. // Restart all autostart containers which has a swarm endpoint
  249. // and is not yet running now that we have successfully
  250. // initialized the cluster.
  251. d.RestartSwarmContainers()
  252. logrus.Info("Daemon has completed initialization")
  253. logrus.WithFields(logrus.Fields{
  254. "version": dockerversion.Version,
  255. "commit": dockerversion.GitCommit,
  256. "graphdriver": d.GraphDriverName(),
  257. }).Info("Docker daemon")
  258. cli.d = d
  259. // initMiddlewares needs cli.d to be populated. Dont change this init order.
  260. if err := cli.initMiddlewares(api, serverConfig); err != nil {
  261. logrus.Fatalf("Error creating middlewares: %v", err)
  262. }
  263. d.SetCluster(c)
  264. initRouter(api, d, c)
  265. cli.setupConfigReloadTrap()
  266. // The serve API routine never exits unless an error occurs
  267. // We need to start it as a goroutine and wait on it so
  268. // daemon doesn't exit
  269. serveAPIWait := make(chan error)
  270. go api.Wait(serveAPIWait)
  271. // after the daemon is done setting up we can notify systemd api
  272. notifySystem()
  273. // Daemon is fully initialized and handling API traffic
  274. // Wait for serve API to complete
  275. errAPI := <-serveAPIWait
  276. c.Cleanup()
  277. shutdownDaemon(d)
  278. containerdRemote.Cleanup()
  279. if errAPI != nil {
  280. return fmt.Errorf("Shutting down due to ServeAPI error: %v", errAPI)
  281. }
  282. return nil
  283. }
  284. func (cli *DaemonCli) reloadConfig() {
  285. reload := func(config *daemon.Config) {
  286. // Revalidate and reload the authorization plugins
  287. if err := validateAuthzPlugins(config.AuthorizationPlugins, cli.d.PluginStore); err != nil {
  288. logrus.Fatalf("Error validating authorization plugin: %v", err)
  289. return
  290. }
  291. cli.authzMiddleware.SetPlugins(config.AuthorizationPlugins)
  292. if err := cli.d.Reload(config); err != nil {
  293. logrus.Errorf("Error reconfiguring the daemon: %v", err)
  294. return
  295. }
  296. if config.IsValueSet("debug") {
  297. debugEnabled := debug.IsEnabled()
  298. switch {
  299. case debugEnabled && !config.Debug: // disable debug
  300. debug.Disable()
  301. cli.api.DisableProfiler()
  302. case config.Debug && !debugEnabled: // enable debug
  303. debug.Enable()
  304. cli.api.EnableProfiler()
  305. }
  306. }
  307. }
  308. if err := daemon.ReloadConfiguration(*cli.configFile, cli.flags, reload); err != nil {
  309. logrus.Error(err)
  310. }
  311. }
  312. func (cli *DaemonCli) stop() {
  313. cli.api.Close()
  314. }
  315. // shutdownDaemon just wraps daemon.Shutdown() to handle a timeout in case
  316. // d.Shutdown() is waiting too long to kill container or worst it's
  317. // blocked there
  318. func shutdownDaemon(d *daemon.Daemon) {
  319. shutdownTimeout := d.ShutdownTimeout()
  320. ch := make(chan struct{})
  321. go func() {
  322. d.Shutdown()
  323. close(ch)
  324. }()
  325. if shutdownTimeout < 0 {
  326. <-ch
  327. logrus.Debug("Clean shutdown succeeded")
  328. return
  329. }
  330. select {
  331. case <-ch:
  332. logrus.Debug("Clean shutdown succeeded")
  333. case <-time.After(time.Duration(shutdownTimeout) * time.Second):
  334. logrus.Error("Force shutdown daemon")
  335. }
  336. }
  337. func loadDaemonCliConfig(opts daemonOptions) (*daemon.Config, error) {
  338. config := opts.daemonConfig
  339. flags := opts.flags
  340. config.Debug = opts.common.Debug
  341. config.Hosts = opts.common.Hosts
  342. config.LogLevel = opts.common.LogLevel
  343. config.TLS = opts.common.TLS
  344. config.TLSVerify = opts.common.TLSVerify
  345. config.CommonTLSOptions = daemon.CommonTLSOptions{}
  346. if opts.common.TLSOptions != nil {
  347. config.CommonTLSOptions.CAFile = opts.common.TLSOptions.CAFile
  348. config.CommonTLSOptions.CertFile = opts.common.TLSOptions.CertFile
  349. config.CommonTLSOptions.KeyFile = opts.common.TLSOptions.KeyFile
  350. }
  351. if opts.configFile != "" {
  352. c, err := daemon.MergeDaemonConfigurations(config, flags, opts.configFile)
  353. if err != nil {
  354. if flags.Changed(flagDaemonConfigFile) || !os.IsNotExist(err) {
  355. return nil, fmt.Errorf("unable to configure the Docker daemon with file %s: %v\n", opts.configFile, err)
  356. }
  357. }
  358. // the merged configuration can be nil if the config file didn't exist.
  359. // leave the current configuration as it is if when that happens.
  360. if c != nil {
  361. config = c
  362. }
  363. }
  364. if err := daemon.ValidateConfiguration(config); err != nil {
  365. return nil, err
  366. }
  367. // Labels of the docker engine used to allow multiple values associated with the same key.
  368. // This is deprecated in 1.13, and, be removed after 3 release cycles.
  369. // The following will check the conflict of labels, and report a warning for deprecation.
  370. //
  371. // TODO: After 3 release cycles (1.16) an error will be returned, and labels will be
  372. // sanitized to consolidate duplicate key-value pairs (config.Labels = newLabels):
  373. //
  374. // newLabels, err := daemon.GetConflictFreeLabels(config.Labels)
  375. // if err != nil {
  376. // return nil, err
  377. // }
  378. // config.Labels = newLabels
  379. //
  380. if _, err := daemon.GetConflictFreeLabels(config.Labels); err != nil {
  381. logrus.Warnf("Engine labels with duplicate keys and conflicting values have been deprecated: %s", err)
  382. }
  383. // Regardless of whether the user sets it to true or false, if they
  384. // specify TLSVerify at all then we need to turn on TLS
  385. if config.IsValueSet(cliflags.FlagTLSVerify) {
  386. config.TLS = true
  387. }
  388. // ensure that the log level is the one set after merging configurations
  389. cliflags.SetLogLevel(config.LogLevel)
  390. return config, nil
  391. }
  392. func initRouter(s *apiserver.Server, d *daemon.Daemon, c *cluster.Cluster) {
  393. decoder := runconfig.ContainerDecoder{}
  394. routers := []router.Router{
  395. // we need to add the checkpoint router before the container router or the DELETE gets masked
  396. checkpointrouter.NewRouter(d, decoder),
  397. container.NewRouter(d, decoder),
  398. image.NewRouter(d, decoder),
  399. systemrouter.NewRouter(d, c),
  400. volume.NewRouter(d),
  401. build.NewRouter(dockerfile.NewBuildManager(d)),
  402. swarmrouter.NewRouter(c),
  403. pluginrouter.NewRouter(d.PluginManager()),
  404. }
  405. if d.NetworkControllerEnabled() {
  406. routers = append(routers, network.NewRouter(d, c))
  407. }
  408. if d.HasExperimental() {
  409. for _, r := range routers {
  410. for _, route := range r.Routes() {
  411. if experimental, ok := route.(router.ExperimentalRoute); ok {
  412. experimental.Enable()
  413. }
  414. }
  415. }
  416. }
  417. s.InitRouter(debug.IsEnabled(), routers...)
  418. }
  419. func (cli *DaemonCli) initMiddlewares(s *apiserver.Server, cfg *apiserver.Config) error {
  420. v := cfg.Version
  421. exp := middleware.NewExperimentalMiddleware(cli.d.HasExperimental())
  422. s.UseMiddleware(exp)
  423. vm := middleware.NewVersionMiddleware(v, api.DefaultVersion, api.MinVersion)
  424. s.UseMiddleware(vm)
  425. if cfg.EnableCors {
  426. c := middleware.NewCORSMiddleware(cfg.CorsHeaders)
  427. s.UseMiddleware(c)
  428. }
  429. if err := validateAuthzPlugins(cli.Config.AuthorizationPlugins, cli.d.PluginStore); err != nil {
  430. return fmt.Errorf("Error validating authorization plugin: %v", err)
  431. }
  432. cli.authzMiddleware = authorization.NewMiddleware(cli.Config.AuthorizationPlugins, cli.d.PluginStore)
  433. s.UseMiddleware(cli.authzMiddleware)
  434. return nil
  435. }
  436. // validates that the plugins requested with the --authorization-plugin flag are valid AuthzDriver
  437. // plugins present on the host and available to the daemon
  438. func validateAuthzPlugins(requestedPlugins []string, pg plugingetter.PluginGetter) error {
  439. for _, reqPlugin := range requestedPlugins {
  440. if _, err := pg.Get(reqPlugin, authorization.AuthZApiImplements, plugingetter.LOOKUP); err != nil {
  441. return err
  442. }
  443. }
  444. return nil
  445. }