daemon.go 25 KB

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