daemon.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. package main
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "fmt"
  6. "net"
  7. "os"
  8. "path/filepath"
  9. "runtime"
  10. "sort"
  11. "strings"
  12. "time"
  13. containerddefaults "github.com/containerd/containerd/defaults"
  14. "github.com/docker/docker/api"
  15. apiserver "github.com/docker/docker/api/server"
  16. buildbackend "github.com/docker/docker/api/server/backend/build"
  17. "github.com/docker/docker/api/server/middleware"
  18. "github.com/docker/docker/api/server/router"
  19. "github.com/docker/docker/api/server/router/build"
  20. checkpointrouter "github.com/docker/docker/api/server/router/checkpoint"
  21. "github.com/docker/docker/api/server/router/container"
  22. distributionrouter "github.com/docker/docker/api/server/router/distribution"
  23. grpcrouter "github.com/docker/docker/api/server/router/grpc"
  24. "github.com/docker/docker/api/server/router/image"
  25. "github.com/docker/docker/api/server/router/network"
  26. pluginrouter "github.com/docker/docker/api/server/router/plugin"
  27. sessionrouter "github.com/docker/docker/api/server/router/session"
  28. swarmrouter "github.com/docker/docker/api/server/router/swarm"
  29. systemrouter "github.com/docker/docker/api/server/router/system"
  30. "github.com/docker/docker/api/server/router/volume"
  31. buildkit "github.com/docker/docker/builder/builder-next"
  32. "github.com/docker/docker/builder/dockerfile"
  33. "github.com/docker/docker/cli/debug"
  34. "github.com/docker/docker/cmd/dockerd/trap"
  35. "github.com/docker/docker/daemon"
  36. "github.com/docker/docker/daemon/cluster"
  37. "github.com/docker/docker/daemon/config"
  38. "github.com/docker/docker/daemon/listeners"
  39. "github.com/docker/docker/dockerversion"
  40. "github.com/docker/docker/libcontainerd/supervisor"
  41. dopts "github.com/docker/docker/opts"
  42. "github.com/docker/docker/pkg/authorization"
  43. "github.com/docker/docker/pkg/homedir"
  44. "github.com/docker/docker/pkg/jsonmessage"
  45. "github.com/docker/docker/pkg/pidfile"
  46. "github.com/docker/docker/pkg/plugingetter"
  47. "github.com/docker/docker/pkg/sysinfo"
  48. "github.com/docker/docker/pkg/system"
  49. "github.com/docker/docker/plugin"
  50. "github.com/docker/docker/rootless"
  51. "github.com/docker/docker/runconfig"
  52. "github.com/docker/go-connections/tlsconfig"
  53. "github.com/moby/buildkit/session"
  54. swarmapi "github.com/moby/swarmkit/v2/api"
  55. "github.com/pkg/errors"
  56. "github.com/sirupsen/logrus"
  57. "github.com/spf13/pflag"
  58. )
  59. // DaemonCli represents the daemon CLI.
  60. type DaemonCli struct {
  61. *config.Config
  62. configFile *string
  63. flags *pflag.FlagSet
  64. api *apiserver.Server
  65. d *daemon.Daemon
  66. authzMiddleware *authorization.Middleware // authzMiddleware enables to dynamically reload the authorization plugins
  67. }
  68. // NewDaemonCli returns a daemon CLI
  69. func NewDaemonCli() *DaemonCli {
  70. return &DaemonCli{}
  71. }
  72. func (cli *DaemonCli) start(opts *daemonOptions) (err error) {
  73. if cli.Config, err = loadDaemonCliConfig(opts); err != nil {
  74. return err
  75. }
  76. if err := checkDeprecatedOptions(cli.Config); err != nil {
  77. return err
  78. }
  79. serverConfig, err := newAPIServerConfig(cli.Config)
  80. if err != nil {
  81. return err
  82. }
  83. if opts.Validate {
  84. // If config wasn't OK we wouldn't have made it this far.
  85. _, _ = fmt.Fprintln(os.Stderr, "configuration OK")
  86. return nil
  87. }
  88. configureProxyEnv(cli.Config)
  89. configureDaemonLogs(cli.Config)
  90. logrus.Info("Starting up")
  91. cli.configFile = &opts.configFile
  92. cli.flags = opts.flags
  93. if cli.Config.Debug {
  94. debug.Enable()
  95. }
  96. if cli.Config.Experimental {
  97. logrus.Warn("Running experimental build")
  98. }
  99. if cli.Config.IsRootless() {
  100. logrus.Warn("Running in rootless mode. This mode has feature limitations.")
  101. }
  102. if rootless.RunningWithRootlessKit() {
  103. logrus.Info("Running with RootlessKit integration")
  104. if !cli.Config.IsRootless() {
  105. return fmt.Errorf("rootless mode needs to be enabled for running with RootlessKit")
  106. }
  107. }
  108. // return human-friendly error before creating files
  109. if runtime.GOOS == "linux" && os.Geteuid() != 0 {
  110. return fmt.Errorf("dockerd needs to be started with root privileges. To run dockerd in rootless mode as an unprivileged user, see https://docs.docker.com/go/rootless/")
  111. }
  112. if err := setDefaultUmask(); err != nil {
  113. return err
  114. }
  115. // Create the daemon root before we create ANY other files (PID, or migrate keys)
  116. // to ensure the appropriate ACL is set (particularly relevant on Windows)
  117. if err := daemon.CreateDaemonRoot(cli.Config); err != nil {
  118. return err
  119. }
  120. if err := system.MkdirAll(cli.Config.ExecRoot, 0700); err != nil {
  121. return err
  122. }
  123. potentiallyUnderRuntimeDir := []string{cli.Config.ExecRoot}
  124. if cli.Pidfile != "" {
  125. pf, err := pidfile.New(cli.Pidfile)
  126. if err != nil {
  127. return errors.Wrap(err, "failed to start daemon")
  128. }
  129. potentiallyUnderRuntimeDir = append(potentiallyUnderRuntimeDir, cli.Pidfile)
  130. defer func() {
  131. if err := pf.Remove(); err != nil {
  132. logrus.Error(err)
  133. }
  134. }()
  135. }
  136. if cli.Config.IsRootless() {
  137. // Set sticky bit if XDG_RUNTIME_DIR is set && the file is actually under XDG_RUNTIME_DIR
  138. if _, err := homedir.StickRuntimeDirContents(potentiallyUnderRuntimeDir); err != nil {
  139. // StickRuntimeDirContents returns nil error if XDG_RUNTIME_DIR is just unset
  140. logrus.WithError(err).Warn("cannot set sticky bit on files under XDG_RUNTIME_DIR")
  141. }
  142. }
  143. cli.api = apiserver.New(serverConfig)
  144. hosts, err := loadListeners(cli, serverConfig)
  145. if err != nil {
  146. return errors.Wrap(err, "failed to load listeners")
  147. }
  148. ctx, cancel := context.WithCancel(context.Background())
  149. waitForContainerDShutdown, err := cli.initContainerD(ctx)
  150. if waitForContainerDShutdown != nil {
  151. defer waitForContainerDShutdown(10 * time.Second)
  152. }
  153. if err != nil {
  154. cancel()
  155. return err
  156. }
  157. defer cancel()
  158. stopc := make(chan bool)
  159. defer close(stopc)
  160. trap.Trap(func() {
  161. cli.stop()
  162. <-stopc // wait for daemonCli.start() to return
  163. }, logrus.StandardLogger())
  164. // Notify that the API is active, but before daemon is set up.
  165. preNotifyReady()
  166. pluginStore := plugin.NewStore()
  167. if err := cli.initMiddlewares(cli.api, serverConfig, pluginStore); err != nil {
  168. logrus.Fatalf("Error creating middlewares: %v", err)
  169. }
  170. d, err := daemon.NewDaemon(ctx, cli.Config, pluginStore)
  171. if err != nil {
  172. return errors.Wrap(err, "failed to start daemon")
  173. }
  174. d.StoreHosts(hosts)
  175. // validate after NewDaemon has restored enabled plugins. Don't change order.
  176. if err := validateAuthzPlugins(cli.Config.AuthorizationPlugins, pluginStore); err != nil {
  177. return errors.Wrap(err, "failed to validate authorization plugin")
  178. }
  179. cli.d = d
  180. if err := startMetricsServer(cli.Config.MetricsAddress); err != nil {
  181. return errors.Wrap(err, "failed to start metrics server")
  182. }
  183. c, err := createAndStartCluster(cli, d)
  184. if err != nil {
  185. logrus.Fatalf("Error starting cluster component: %v", err)
  186. }
  187. // Restart all autostart containers which has a swarm endpoint
  188. // and is not yet running now that we have successfully
  189. // initialized the cluster.
  190. d.RestartSwarmContainers()
  191. logrus.Info("Daemon has completed initialization")
  192. routerOptions, err := newRouterOptions(cli.Config, d)
  193. if err != nil {
  194. return err
  195. }
  196. routerOptions.api = cli.api
  197. routerOptions.cluster = c
  198. initRouter(routerOptions)
  199. go d.ProcessClusterNotifications(ctx, c.GetWatchStream())
  200. cli.setupConfigReloadTrap()
  201. // The serve API routine never exits unless an error occurs
  202. // We need to start it as a goroutine and wait on it so
  203. // daemon doesn't exit
  204. serveAPIWait := make(chan error)
  205. go cli.api.Wait(serveAPIWait)
  206. // after the daemon is done setting up we can notify systemd api
  207. notifyReady()
  208. // Daemon is fully initialized and handling API traffic
  209. // Wait for serve API to complete
  210. errAPI := <-serveAPIWait
  211. c.Cleanup()
  212. // notify systemd that we're shutting down
  213. notifyStopping()
  214. shutdownDaemon(d)
  215. // Stop notification processing and any background processes
  216. cancel()
  217. if errAPI != nil {
  218. return errors.Wrap(errAPI, "shutting down due to ServeAPI error")
  219. }
  220. logrus.Info("Daemon shutdown complete")
  221. return nil
  222. }
  223. type routerOptions struct {
  224. sessionManager *session.Manager
  225. buildBackend *buildbackend.Backend
  226. features *map[string]bool
  227. buildkit *buildkit.Builder
  228. daemon *daemon.Daemon
  229. api *apiserver.Server
  230. cluster *cluster.Cluster
  231. }
  232. func newRouterOptions(config *config.Config, d *daemon.Daemon) (routerOptions, error) {
  233. opts := routerOptions{}
  234. sm, err := session.NewManager()
  235. if err != nil {
  236. return opts, errors.Wrap(err, "failed to create sessionmanager")
  237. }
  238. manager, err := dockerfile.NewBuildManager(d.BuilderBackend(), d.IdentityMapping())
  239. if err != nil {
  240. return opts, err
  241. }
  242. cgroupParent := newCgroupParent(config)
  243. bk, err := buildkit.New(buildkit.Opt{
  244. SessionManager: sm,
  245. Root: filepath.Join(config.Root, "buildkit"),
  246. Dist: d.DistributionServices(),
  247. NetworkController: d.NetworkController(),
  248. DefaultCgroupParent: cgroupParent,
  249. RegistryHosts: d.RegistryHosts(),
  250. BuilderConfig: config.Builder,
  251. Rootless: d.Rootless(),
  252. IdentityMapping: d.IdentityMapping(),
  253. DNSConfig: config.DNSConfig,
  254. ApparmorProfile: daemon.DefaultApparmorProfile(),
  255. })
  256. if err != nil {
  257. return opts, err
  258. }
  259. bb, err := buildbackend.NewBackend(d.ImageService(), manager, bk, d.EventsService)
  260. if err != nil {
  261. return opts, errors.Wrap(err, "failed to create buildmanager")
  262. }
  263. return routerOptions{
  264. sessionManager: sm,
  265. buildBackend: bb,
  266. buildkit: bk,
  267. features: d.Features(),
  268. daemon: d,
  269. }, nil
  270. }
  271. func (cli *DaemonCli) reloadConfig() {
  272. reload := func(c *config.Config) {
  273. // Revalidate and reload the authorization plugins
  274. if err := validateAuthzPlugins(c.AuthorizationPlugins, cli.d.PluginStore); err != nil {
  275. logrus.Fatalf("Error validating authorization plugin: %v", err)
  276. return
  277. }
  278. cli.authzMiddleware.SetPlugins(c.AuthorizationPlugins)
  279. if err := cli.d.Reload(c); err != nil {
  280. logrus.Errorf("Error reconfiguring the daemon: %v", err)
  281. return
  282. }
  283. if c.IsValueSet("debug") {
  284. debugEnabled := debug.IsEnabled()
  285. switch {
  286. case debugEnabled && !c.Debug: // disable debug
  287. debug.Disable()
  288. case c.Debug && !debugEnabled: // enable debug
  289. debug.Enable()
  290. }
  291. }
  292. }
  293. if err := config.Reload(*cli.configFile, cli.flags, reload); err != nil {
  294. logrus.Error(err)
  295. }
  296. }
  297. func (cli *DaemonCli) stop() {
  298. cli.api.Close()
  299. }
  300. // shutdownDaemon just wraps daemon.Shutdown() to handle a timeout in case
  301. // d.Shutdown() is waiting too long to kill container or worst it's
  302. // blocked there
  303. func shutdownDaemon(d *daemon.Daemon) {
  304. shutdownTimeout := d.ShutdownTimeout()
  305. ch := make(chan struct{})
  306. go func() {
  307. d.Shutdown()
  308. close(ch)
  309. }()
  310. if shutdownTimeout < 0 {
  311. <-ch
  312. logrus.Debug("Clean shutdown succeeded")
  313. return
  314. }
  315. timeout := time.NewTimer(time.Duration(shutdownTimeout) * time.Second)
  316. defer timeout.Stop()
  317. select {
  318. case <-ch:
  319. logrus.Debug("Clean shutdown succeeded")
  320. case <-timeout.C:
  321. logrus.Error("Force shutdown daemon")
  322. }
  323. }
  324. func loadDaemonCliConfig(opts *daemonOptions) (*config.Config, error) {
  325. if !opts.flags.Parsed() {
  326. return nil, errors.New(`cannot load CLI config before flags are parsed`)
  327. }
  328. opts.setDefaultOptions()
  329. conf := opts.daemonConfig
  330. flags := opts.flags
  331. conf.Debug = opts.Debug
  332. conf.Hosts = opts.Hosts
  333. conf.LogLevel = opts.LogLevel
  334. if flags.Changed("graph") && flags.Changed("data-root") {
  335. return nil, errors.New(`cannot specify both "--graph" and "--data-root" option`)
  336. }
  337. if flags.Changed(FlagTLS) {
  338. conf.TLS = &opts.TLS
  339. }
  340. if flags.Changed(FlagTLSVerify) {
  341. conf.TLSVerify = &opts.TLSVerify
  342. v := true
  343. conf.TLS = &v
  344. }
  345. if opts.TLSOptions != nil {
  346. conf.CommonTLSOptions = config.CommonTLSOptions{
  347. CAFile: opts.TLSOptions.CAFile,
  348. CertFile: opts.TLSOptions.CertFile,
  349. KeyFile: opts.TLSOptions.KeyFile,
  350. }
  351. } else {
  352. conf.CommonTLSOptions = config.CommonTLSOptions{}
  353. }
  354. if conf.TrustKeyPath == "" {
  355. daemonConfDir, err := getDaemonConfDir(conf.Root)
  356. if err != nil {
  357. return nil, err
  358. }
  359. conf.TrustKeyPath = filepath.Join(daemonConfDir, defaultTrustKeyFile)
  360. }
  361. if opts.configFile != "" {
  362. c, err := config.MergeDaemonConfigurations(conf, flags, opts.configFile)
  363. if err != nil {
  364. if flags.Changed("config-file") || !os.IsNotExist(err) {
  365. return nil, errors.Wrapf(err, "unable to configure the Docker daemon with file %s", opts.configFile)
  366. }
  367. }
  368. // the merged configuration can be nil if the config file didn't exist.
  369. // leave the current configuration as it is if when that happens.
  370. if c != nil {
  371. conf = c
  372. }
  373. }
  374. if err := normalizeHosts(conf); err != nil {
  375. return nil, err
  376. }
  377. if err := config.Validate(conf); err != nil {
  378. return nil, err
  379. }
  380. if flags.Changed("graph") {
  381. logrus.Warnf(`The "-g / --graph" flag is deprecated. Please use "--data-root" instead`)
  382. }
  383. // Check if duplicate label-keys with different values are found
  384. newLabels, err := config.GetConflictFreeLabels(conf.Labels)
  385. if err != nil {
  386. return nil, err
  387. }
  388. conf.Labels = newLabels
  389. // Regardless of whether the user sets it to true or false, if they
  390. // specify TLSVerify at all then we need to turn on TLS
  391. if conf.IsValueSet(FlagTLSVerify) {
  392. v := true
  393. conf.TLS = &v
  394. }
  395. if conf.TLSVerify == nil && conf.TLS != nil {
  396. conf.TLSVerify = conf.TLS
  397. }
  398. err = validateCPURealtimeOptions(conf)
  399. if err != nil {
  400. return nil, err
  401. }
  402. return conf, nil
  403. }
  404. // normalizeHosts normalizes the configured config.Hosts and remove duplicates.
  405. // It returns an error if it fails to parse a host.
  406. func normalizeHosts(config *config.Config) error {
  407. if len(config.Hosts) == 0 {
  408. // if no hosts are configured, create a single entry slice, so that the
  409. // default is used.
  410. //
  411. // TODO(thaJeztah) implement a cleaner way for this; this depends on a
  412. // side-effect of how we parse empty/partial hosts.
  413. config.Hosts = make([]string, 1)
  414. }
  415. hosts := make([]string, 0, len(config.Hosts))
  416. seen := make(map[string]struct{}, len(config.Hosts))
  417. useTLS := DefaultTLSValue
  418. if config.TLS != nil {
  419. useTLS = *config.TLS
  420. }
  421. for _, h := range config.Hosts {
  422. host, err := dopts.ParseHost(useTLS, honorXDG, h)
  423. if err != nil {
  424. return err
  425. }
  426. if _, ok := seen[host]; ok {
  427. continue
  428. }
  429. seen[host] = struct{}{}
  430. hosts = append(hosts, host)
  431. }
  432. sort.Strings(hosts)
  433. config.Hosts = hosts
  434. return nil
  435. }
  436. func checkDeprecatedOptions(config *config.Config) error {
  437. // Overlay networks with external k/v stores have been deprecated
  438. if config.ClusterAdvertise != "" || len(config.ClusterOpts) > 0 || config.ClusterStore != "" {
  439. return errors.New("Host-discovery and overlay networks with external k/v stores are deprecated. The 'cluster-advertise', 'cluster-store', and 'cluster-store-opt' options have been removed")
  440. }
  441. return nil
  442. }
  443. func initRouter(opts routerOptions) {
  444. decoder := runconfig.ContainerDecoder{
  445. GetSysInfo: func() *sysinfo.SysInfo {
  446. return opts.daemon.RawSysInfo()
  447. },
  448. }
  449. routers := []router.Router{
  450. // we need to add the checkpoint router before the container router or the DELETE gets masked
  451. checkpointrouter.NewRouter(opts.daemon, decoder),
  452. container.NewRouter(opts.daemon, decoder, opts.daemon.RawSysInfo().CgroupUnified),
  453. image.NewRouter(
  454. opts.daemon.ImageService(),
  455. opts.daemon.ReferenceStore,
  456. opts.daemon.ImageService().DistributionServices().ImageStore,
  457. opts.daemon.ImageService().DistributionServices().LayerStore,
  458. ),
  459. systemrouter.NewRouter(opts.daemon, opts.cluster, opts.buildkit, opts.features),
  460. volume.NewRouter(opts.daemon.VolumesService(), opts.cluster),
  461. build.NewRouter(opts.buildBackend, opts.daemon, opts.features),
  462. sessionrouter.NewRouter(opts.sessionManager),
  463. swarmrouter.NewRouter(opts.cluster),
  464. pluginrouter.NewRouter(opts.daemon.PluginManager()),
  465. distributionrouter.NewRouter(opts.daemon.ImageService()),
  466. }
  467. grpcBackends := []grpcrouter.Backend{}
  468. for _, b := range []interface{}{opts.daemon, opts.buildBackend} {
  469. if b, ok := b.(grpcrouter.Backend); ok {
  470. grpcBackends = append(grpcBackends, b)
  471. }
  472. }
  473. if len(grpcBackends) > 0 {
  474. routers = append(routers, grpcrouter.NewRouter(grpcBackends...))
  475. }
  476. if opts.daemon.NetworkControllerEnabled() {
  477. routers = append(routers, network.NewRouter(opts.daemon, opts.cluster))
  478. }
  479. if opts.daemon.HasExperimental() {
  480. for _, r := range routers {
  481. for _, route := range r.Routes() {
  482. if experimental, ok := route.(router.ExperimentalRoute); ok {
  483. experimental.Enable()
  484. }
  485. }
  486. }
  487. }
  488. opts.api.InitRouter(routers...)
  489. }
  490. // TODO: remove this from cli and return the authzMiddleware
  491. func (cli *DaemonCli) initMiddlewares(s *apiserver.Server, cfg *apiserver.Config, pluginStore plugingetter.PluginGetter) error {
  492. v := cfg.Version
  493. exp := middleware.NewExperimentalMiddleware(cli.Config.Experimental)
  494. s.UseMiddleware(exp)
  495. vm := middleware.NewVersionMiddleware(v, api.DefaultVersion, api.MinVersion)
  496. s.UseMiddleware(vm)
  497. if cfg.CorsHeaders != "" {
  498. c := middleware.NewCORSMiddleware(cfg.CorsHeaders)
  499. s.UseMiddleware(c)
  500. }
  501. cli.authzMiddleware = authorization.NewMiddleware(cli.Config.AuthorizationPlugins, pluginStore)
  502. cli.Config.AuthzMiddleware = cli.authzMiddleware
  503. s.UseMiddleware(cli.authzMiddleware)
  504. return nil
  505. }
  506. func (cli *DaemonCli) getContainerdDaemonOpts() ([]supervisor.DaemonOpt, error) {
  507. opts, err := cli.getPlatformContainerdDaemonOpts()
  508. if err != nil {
  509. return nil, err
  510. }
  511. if cli.Config.Debug {
  512. opts = append(opts, supervisor.WithLogLevel("debug"))
  513. } else if cli.Config.LogLevel != "" {
  514. opts = append(opts, supervisor.WithLogLevel(cli.Config.LogLevel))
  515. }
  516. if !cli.Config.CriContainerd {
  517. opts = append(opts, supervisor.WithPlugin("cri", nil))
  518. }
  519. return opts, nil
  520. }
  521. func newAPIServerConfig(config *config.Config) (*apiserver.Config, error) {
  522. var tlsConfig *tls.Config
  523. if config.TLS != nil && *config.TLS {
  524. var (
  525. clientAuth tls.ClientAuthType
  526. err error
  527. )
  528. if config.TLSVerify == nil || *config.TLSVerify {
  529. // server requires and verifies client's certificate
  530. clientAuth = tls.RequireAndVerifyClientCert
  531. }
  532. tlsConfig, err = tlsconfig.Server(tlsconfig.Options{
  533. CAFile: config.CommonTLSOptions.CAFile,
  534. CertFile: config.CommonTLSOptions.CertFile,
  535. KeyFile: config.CommonTLSOptions.KeyFile,
  536. ExclusiveRootPools: true,
  537. ClientAuth: clientAuth,
  538. })
  539. if err != nil {
  540. return nil, errors.Wrap(err, "invalid TLS configuration")
  541. }
  542. }
  543. return &apiserver.Config{
  544. SocketGroup: config.SocketGroup,
  545. Version: dockerversion.Version,
  546. CorsHeaders: config.CorsHeaders,
  547. TLSConfig: tlsConfig,
  548. Hosts: config.Hosts,
  549. }, nil
  550. }
  551. // checkTLSAuthOK checks basically for an explicitly disabled TLS/TLSVerify
  552. // Going forward we do not want to support a scenario where dockerd listens
  553. // on TCP without either TLS client auth (or an explicit opt-in to disable it)
  554. func checkTLSAuthOK(c *config.Config) bool {
  555. if c.TLS == nil {
  556. // Either TLS is enabled by default, in which case TLS verification should be enabled by default, or explicitly disabled
  557. // Or TLS is disabled by default... in any of these cases, we can just take the default value as to how to proceed
  558. return DefaultTLSValue
  559. }
  560. if !*c.TLS {
  561. // TLS is explicitly disabled, which is supported
  562. return true
  563. }
  564. if c.TLSVerify == nil {
  565. // this actually shouldn't happen since we set TLSVerify on the config object anyway
  566. // But in case it does get here, be cautious and assume this is not supported.
  567. return false
  568. }
  569. // Either TLSVerify is explicitly enabled or disabled, both cases are supported
  570. return true
  571. }
  572. func loadListeners(cli *DaemonCli, serverConfig *apiserver.Config) ([]string, error) {
  573. if len(serverConfig.Hosts) == 0 {
  574. return nil, errors.New("no hosts configured")
  575. }
  576. var hosts []string
  577. for i := 0; i < len(serverConfig.Hosts); i++ {
  578. protoAddr := serverConfig.Hosts[i]
  579. protoAddrParts := strings.SplitN(serverConfig.Hosts[i], "://", 2)
  580. if len(protoAddrParts) != 2 {
  581. return nil, fmt.Errorf("bad format %s, expected PROTO://ADDR", protoAddr)
  582. }
  583. proto, addr := protoAddrParts[0], protoAddrParts[1]
  584. // It's a bad idea to bind to TCP without tlsverify.
  585. authEnabled := serverConfig.TLSConfig != nil && serverConfig.TLSConfig.ClientAuth == tls.RequireAndVerifyClientCert
  586. if proto == "tcp" && !authEnabled {
  587. logrus.WithField("host", protoAddr).Warn("Binding to IP address without --tlsverify is insecure and gives root access on this machine to everyone who has access to your network.")
  588. logrus.WithField("host", protoAddr).Warn("Binding to an IP address, even on localhost, can also give access to scripts run in a browser. Be safe out there!")
  589. time.Sleep(time.Second)
  590. // If TLSVerify is explicitly set to false we'll take that as "Please let me shoot myself in the foot"
  591. // We do not want to continue to support a default mode where tls verification is disabled, so we do some extra warnings here and eventually remove support
  592. if !checkTLSAuthOK(cli.Config) {
  593. ipAddr, _, err := net.SplitHostPort(addr)
  594. if err != nil {
  595. return nil, errors.Wrap(err, "error parsing tcp address")
  596. }
  597. // shortcut all this extra stuff for literal "localhost"
  598. // -H supports specifying hostnames, since we want to bypass this on loopback interfaces we'll look it up here.
  599. if ipAddr != "localhost" {
  600. ip := net.ParseIP(ipAddr)
  601. if ip == nil {
  602. ipA, err := net.ResolveIPAddr("ip", ipAddr)
  603. if err != nil {
  604. logrus.WithError(err).WithField("host", ipAddr).Error("Error looking up specified host address")
  605. }
  606. if ipA != nil {
  607. ip = ipA.IP
  608. }
  609. }
  610. if ip == nil || !ip.IsLoopback() {
  611. logrus.WithField("host", protoAddr).Warn("Binding to an IP address without --tlsverify is deprecated. Startup is intentionally being slowed down to show this message")
  612. logrus.WithField("host", protoAddr).Warn("Please consider generating tls certificates with client validation to prevent exposing unauthenticated root access to your network")
  613. logrus.WithField("host", protoAddr).Warnf("You can override this by explicitly specifying '--%s=false' or '--%s=false'", FlagTLS, FlagTLSVerify)
  614. logrus.WithField("host", protoAddr).Warnf("Support for listening on TCP without authentication or explicit intent to run without authentication will be removed in the next release")
  615. time.Sleep(15 * time.Second)
  616. }
  617. }
  618. }
  619. }
  620. // If we're binding to a TCP port, make sure that a container doesn't try to use it.
  621. if proto == "tcp" {
  622. if err := allocateDaemonPort(addr); err != nil {
  623. return nil, err
  624. }
  625. }
  626. ls, err := listeners.Init(proto, addr, serverConfig.SocketGroup, serverConfig.TLSConfig)
  627. if err != nil {
  628. return nil, err
  629. }
  630. logrus.Debugf("Listener created for HTTP on %s (%s)", proto, addr)
  631. hosts = append(hosts, protoAddrParts[1])
  632. cli.api.Accept(addr, ls...)
  633. }
  634. return hosts, nil
  635. }
  636. func createAndStartCluster(cli *DaemonCli, d *daemon.Daemon) (*cluster.Cluster, error) {
  637. name, _ := os.Hostname()
  638. // Use a buffered channel to pass changes from store watch API to daemon
  639. // A buffer allows store watch API and daemon processing to not wait for each other
  640. watchStream := make(chan *swarmapi.WatchMessage, 32)
  641. c, err := cluster.New(cluster.Config{
  642. Root: cli.Config.Root,
  643. Name: name,
  644. Backend: d,
  645. VolumeBackend: d.VolumesService(),
  646. ImageBackend: d.ImageService(),
  647. PluginBackend: d.PluginManager(),
  648. NetworkSubnetsProvider: d,
  649. DefaultAdvertiseAddr: cli.Config.SwarmDefaultAdvertiseAddr,
  650. RaftHeartbeatTick: cli.Config.SwarmRaftHeartbeatTick,
  651. RaftElectionTick: cli.Config.SwarmRaftElectionTick,
  652. RuntimeRoot: cli.getSwarmRunRoot(),
  653. WatchStream: watchStream,
  654. })
  655. if err != nil {
  656. return nil, err
  657. }
  658. d.SetCluster(c)
  659. err = c.Start()
  660. return c, err
  661. }
  662. // validates that the plugins requested with the --authorization-plugin flag are valid AuthzDriver
  663. // plugins present on the host and available to the daemon
  664. func validateAuthzPlugins(requestedPlugins []string, pg plugingetter.PluginGetter) error {
  665. for _, reqPlugin := range requestedPlugins {
  666. if _, err := pg.Get(reqPlugin, authorization.AuthZApiImplements, plugingetter.Lookup); err != nil {
  667. return err
  668. }
  669. }
  670. return nil
  671. }
  672. func systemContainerdRunning(honorXDG bool) (string, bool, error) {
  673. addr := containerddefaults.DefaultAddress
  674. if honorXDG {
  675. runtimeDir, err := homedir.GetRuntimeDir()
  676. if err != nil {
  677. return "", false, err
  678. }
  679. addr = filepath.Join(runtimeDir, "containerd", "containerd.sock")
  680. }
  681. _, err := os.Lstat(addr)
  682. return addr, err == nil, nil
  683. }
  684. // configureDaemonLogs sets the logrus logging level and formatting. It expects
  685. // the passed configuration to already be validated, and ignores invalid options.
  686. func configureDaemonLogs(conf *config.Config) {
  687. if conf.LogLevel != "" {
  688. lvl, err := logrus.ParseLevel(conf.LogLevel)
  689. if err == nil {
  690. logrus.SetLevel(lvl)
  691. }
  692. } else {
  693. logrus.SetLevel(logrus.InfoLevel)
  694. }
  695. logrus.SetFormatter(&logrus.TextFormatter{
  696. TimestampFormat: jsonmessage.RFC3339NanoFixed,
  697. DisableColors: conf.RawLogs,
  698. FullTimestamp: true,
  699. })
  700. }
  701. func configureProxyEnv(conf *config.Config) {
  702. if p := conf.HTTPProxy; p != "" {
  703. overrideProxyEnv("HTTP_PROXY", p)
  704. overrideProxyEnv("http_proxy", p)
  705. }
  706. if p := conf.HTTPSProxy; p != "" {
  707. overrideProxyEnv("HTTPS_PROXY", p)
  708. overrideProxyEnv("https_proxy", p)
  709. }
  710. if p := conf.NoProxy; p != "" {
  711. overrideProxyEnv("NO_PROXY", p)
  712. overrideProxyEnv("no_proxy", p)
  713. }
  714. }
  715. func overrideProxyEnv(name, val string) {
  716. if oldVal := os.Getenv(name); oldVal != "" && oldVal != val {
  717. logrus.WithFields(logrus.Fields{
  718. "name": name,
  719. "old-value": config.MaskCredentials(oldVal),
  720. "new-value": config.MaskCredentials(val),
  721. }).Warn("overriding existing proxy variable with value from configuration")
  722. }
  723. _ = os.Setenv(name, val)
  724. }