daemon.go 28 KB

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