daemon.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  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. conf.LogFormat = opts.LogFormat
  412. if flags.Changed(FlagTLS) {
  413. conf.TLS = &opts.TLS
  414. }
  415. if flags.Changed(FlagTLSVerify) {
  416. conf.TLSVerify = &opts.TLSVerify
  417. v := true
  418. conf.TLS = &v
  419. }
  420. if opts.TLSOptions != nil {
  421. conf.TLSOptions = config.TLSOptions{
  422. CAFile: opts.TLSOptions.CAFile,
  423. CertFile: opts.TLSOptions.CertFile,
  424. KeyFile: opts.TLSOptions.KeyFile,
  425. }
  426. } else {
  427. conf.TLSOptions = config.TLSOptions{}
  428. }
  429. if opts.configFile != "" {
  430. c, err := config.MergeDaemonConfigurations(conf, flags, opts.configFile)
  431. if err != nil {
  432. if flags.Changed("config-file") || !os.IsNotExist(err) {
  433. return nil, errors.Wrapf(err, "unable to configure the Docker daemon with file %s", opts.configFile)
  434. }
  435. }
  436. // the merged configuration can be nil if the config file didn't exist.
  437. // leave the current configuration as it is if when that happens.
  438. if c != nil {
  439. conf = c
  440. }
  441. }
  442. if err := normalizeHosts(conf); err != nil {
  443. return nil, err
  444. }
  445. if err := config.Validate(conf); err != nil {
  446. return nil, err
  447. }
  448. // Check if duplicate label-keys with different values are found
  449. newLabels, err := config.GetConflictFreeLabels(conf.Labels)
  450. if err != nil {
  451. return nil, err
  452. }
  453. conf.Labels = newLabels
  454. // Regardless of whether the user sets it to true or false, if they
  455. // specify TLSVerify at all then we need to turn on TLS
  456. if conf.IsValueSet(FlagTLSVerify) {
  457. v := true
  458. conf.TLS = &v
  459. }
  460. if conf.TLSVerify == nil && conf.TLS != nil {
  461. conf.TLSVerify = conf.TLS
  462. }
  463. err = validateCPURealtimeOptions(conf)
  464. if err != nil {
  465. return nil, err
  466. }
  467. return conf, nil
  468. }
  469. // normalizeHosts normalizes the configured config.Hosts and remove duplicates.
  470. // It returns an error if it fails to parse a host.
  471. func normalizeHosts(config *config.Config) error {
  472. if len(config.Hosts) == 0 {
  473. // if no hosts are configured, create a single entry slice, so that the
  474. // default is used.
  475. //
  476. // TODO(thaJeztah) implement a cleaner way for this; this depends on a
  477. // side-effect of how we parse empty/partial hosts.
  478. config.Hosts = make([]string, 1)
  479. }
  480. hosts := make([]string, 0, len(config.Hosts))
  481. seen := make(map[string]struct{}, len(config.Hosts))
  482. useTLS := DefaultTLSValue
  483. if config.TLS != nil {
  484. useTLS = *config.TLS
  485. }
  486. for _, h := range config.Hosts {
  487. host, err := dopts.ParseHost(useTLS, honorXDG, h)
  488. if err != nil {
  489. return err
  490. }
  491. if _, ok := seen[host]; ok {
  492. continue
  493. }
  494. seen[host] = struct{}{}
  495. hosts = append(hosts, host)
  496. }
  497. sort.Strings(hosts)
  498. config.Hosts = hosts
  499. return nil
  500. }
  501. func (opts routerOptions) Build() []router.Router {
  502. decoder := runconfig.ContainerDecoder{
  503. GetSysInfo: func() *sysinfo.SysInfo {
  504. return opts.daemon.RawSysInfo()
  505. },
  506. }
  507. routers := []router.Router{
  508. // we need to add the checkpoint router before the container router or the DELETE gets masked
  509. checkpointrouter.NewRouter(opts.daemon, decoder),
  510. container.NewRouter(opts.daemon, decoder, opts.daemon.RawSysInfo().CgroupUnified),
  511. image.NewRouter(
  512. opts.daemon.ImageService(),
  513. opts.daemon.RegistryService(),
  514. opts.daemon.ReferenceStore,
  515. opts.daemon.ImageService().DistributionServices().ImageStore,
  516. opts.daemon.ImageService().DistributionServices().LayerStore,
  517. ),
  518. systemrouter.NewRouter(opts.daemon, opts.cluster, opts.buildkit, opts.daemon.Features),
  519. volume.NewRouter(opts.daemon.VolumesService(), opts.cluster),
  520. build.NewRouter(opts.buildBackend, opts.daemon),
  521. sessionrouter.NewRouter(opts.sessionManager),
  522. swarmrouter.NewRouter(opts.cluster),
  523. pluginrouter.NewRouter(opts.daemon.PluginManager()),
  524. distributionrouter.NewRouter(opts.daemon.ImageBackend()),
  525. }
  526. if opts.buildBackend != nil {
  527. routers = append(routers, grpcrouter.NewRouter(opts.buildBackend))
  528. }
  529. if opts.daemon.NetworkControllerEnabled() {
  530. routers = append(routers, network.NewRouter(opts.daemon, opts.cluster))
  531. }
  532. if opts.daemon.HasExperimental() {
  533. for _, r := range routers {
  534. for _, route := range r.Routes() {
  535. if experimental, ok := route.(router.ExperimentalRoute); ok {
  536. experimental.Enable()
  537. }
  538. }
  539. }
  540. }
  541. return routers
  542. }
  543. func initMiddlewares(s *apiserver.Server, cfg *config.Config, pluginStore plugingetter.PluginGetter) *authorization.Middleware {
  544. v := dockerversion.Version
  545. exp := middleware.NewExperimentalMiddleware(cfg.Experimental)
  546. s.UseMiddleware(exp)
  547. vm := middleware.NewVersionMiddleware(v, api.DefaultVersion, api.MinVersion)
  548. s.UseMiddleware(vm)
  549. if cfg.CorsHeaders != "" {
  550. c := middleware.NewCORSMiddleware(cfg.CorsHeaders)
  551. s.UseMiddleware(c)
  552. }
  553. authzMiddleware := authorization.NewMiddleware(cfg.AuthorizationPlugins, pluginStore)
  554. s.UseMiddleware(authzMiddleware)
  555. return authzMiddleware
  556. }
  557. func (cli *DaemonCli) getContainerdDaemonOpts() ([]supervisor.DaemonOpt, error) {
  558. var opts []supervisor.DaemonOpt
  559. if cli.Debug {
  560. opts = append(opts, supervisor.WithLogLevel("debug"))
  561. } else {
  562. opts = append(opts, supervisor.WithLogLevel(cli.LogLevel))
  563. }
  564. if logFormat := cli.Config.LogFormat; logFormat != "" {
  565. opts = append(opts, supervisor.WithLogFormat(logFormat))
  566. }
  567. if !cli.CriContainerd {
  568. // CRI support in the managed daemon is currently opt-in.
  569. //
  570. // It's disabled by default, originally because it was listening on
  571. // a TCP connection at 0.0.0.0:10010, which was considered a security
  572. // risk, and could conflict with user's container ports.
  573. //
  574. // Current versions of containerd started now listen on localhost on
  575. // an ephemeral port instead, but could still conflict with container
  576. // ports, and running kubernetes using the static binaries is not a
  577. // common scenario, so we (for now) continue disabling it by default.
  578. //
  579. // Also see https://github.com/containerd/containerd/issues/2483#issuecomment-407530608
  580. opts = append(opts, supervisor.WithCRIDisabled())
  581. }
  582. return opts, nil
  583. }
  584. func newAPIServerTLSConfig(config *config.Config) (*tls.Config, error) {
  585. var tlsConfig *tls.Config
  586. if config.TLS != nil && *config.TLS {
  587. var (
  588. clientAuth tls.ClientAuthType
  589. err error
  590. )
  591. if config.TLSVerify == nil || *config.TLSVerify {
  592. // server requires and verifies client's certificate
  593. clientAuth = tls.RequireAndVerifyClientCert
  594. }
  595. tlsConfig, err = tlsconfig.Server(tlsconfig.Options{
  596. CAFile: config.TLSOptions.CAFile,
  597. CertFile: config.TLSOptions.CertFile,
  598. KeyFile: config.TLSOptions.KeyFile,
  599. ExclusiveRootPools: true,
  600. ClientAuth: clientAuth,
  601. })
  602. if err != nil {
  603. return nil, errors.Wrap(err, "invalid TLS configuration")
  604. }
  605. }
  606. return tlsConfig, nil
  607. }
  608. // checkTLSAuthOK checks basically for an explicitly disabled TLS/TLSVerify
  609. // Going forward we do not want to support a scenario where dockerd listens
  610. // on TCP without either TLS client auth (or an explicit opt-in to disable it)
  611. func checkTLSAuthOK(c *config.Config) bool {
  612. if c.TLS == nil {
  613. // Either TLS is enabled by default, in which case TLS verification should be enabled by default, or explicitly disabled
  614. // Or TLS is disabled by default... in any of these cases, we can just take the default value as to how to proceed
  615. return DefaultTLSValue
  616. }
  617. if !*c.TLS {
  618. // TLS is explicitly disabled, which is supported
  619. return true
  620. }
  621. if c.TLSVerify == nil {
  622. // this actually shouldn't happen since we set TLSVerify on the config object anyway
  623. // But in case it does get here, be cautious and assume this is not supported.
  624. return false
  625. }
  626. // Either TLSVerify is explicitly enabled or disabled, both cases are supported
  627. return true
  628. }
  629. func loadListeners(cfg *config.Config, tlsConfig *tls.Config) ([]net.Listener, []string, error) {
  630. ctx := context.TODO()
  631. if len(cfg.Hosts) == 0 {
  632. return nil, nil, errors.New("no hosts configured")
  633. }
  634. var (
  635. hosts []string
  636. lss []net.Listener
  637. )
  638. for i := 0; i < len(cfg.Hosts); i++ {
  639. protoAddr := cfg.Hosts[i]
  640. proto, addr, ok := strings.Cut(protoAddr, "://")
  641. if !ok {
  642. return nil, nil, fmt.Errorf("bad format %s, expected PROTO://ADDR", protoAddr)
  643. }
  644. // It's a bad idea to bind to TCP without tlsverify.
  645. authEnabled := tlsConfig != nil && tlsConfig.ClientAuth == tls.RequireAndVerifyClientCert
  646. if proto == "tcp" && !authEnabled {
  647. 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.")
  648. 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!")
  649. time.Sleep(time.Second)
  650. // If TLSVerify is explicitly set to false we'll take that as "Please let me shoot myself in the foot"
  651. // 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
  652. if !checkTLSAuthOK(cfg) {
  653. ipAddr, _, err := net.SplitHostPort(addr)
  654. if err != nil {
  655. return nil, nil, errors.Wrap(err, "error parsing tcp address")
  656. }
  657. // shortcut all this extra stuff for literal "localhost"
  658. // -H supports specifying hostnames, since we want to bypass this on loopback interfaces we'll look it up here.
  659. if ipAddr != "localhost" {
  660. ip := net.ParseIP(ipAddr)
  661. if ip == nil {
  662. ipA, err := net.ResolveIPAddr("ip", ipAddr)
  663. if err != nil {
  664. log.G(ctx).WithError(err).WithField("host", ipAddr).Error("Error looking up specified host address")
  665. }
  666. if ipA != nil {
  667. ip = ipA.IP
  668. }
  669. }
  670. if ip == nil || !ip.IsLoopback() {
  671. 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")
  672. log.G(ctx).WithField("host", protoAddr).Warn("Please consider generating tls certificates with client validation to prevent exposing unauthenticated root access to your network")
  673. log.G(ctx).WithField("host", protoAddr).Warnf("You can override this by explicitly specifying '--%s=false' or '--%s=false'", FlagTLS, FlagTLSVerify)
  674. 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")
  675. time.Sleep(15 * time.Second)
  676. }
  677. }
  678. }
  679. }
  680. // If we're binding to a TCP port, make sure that a container doesn't try to use it.
  681. if proto == "tcp" {
  682. if err := allocateDaemonPort(addr); err != nil {
  683. return nil, nil, err
  684. }
  685. }
  686. ls, err := listeners.Init(proto, addr, cfg.SocketGroup, tlsConfig)
  687. if err != nil {
  688. return nil, nil, err
  689. }
  690. log.G(ctx).Debugf("Listener created for HTTP on %s (%s)", proto, addr)
  691. hosts = append(hosts, addr)
  692. lss = append(lss, ls...)
  693. }
  694. return lss, hosts, nil
  695. }
  696. func createAndStartCluster(cli *DaemonCli, d *daemon.Daemon) (*cluster.Cluster, error) {
  697. name, _ := os.Hostname()
  698. // Use a buffered channel to pass changes from store watch API to daemon
  699. // A buffer allows store watch API and daemon processing to not wait for each other
  700. watchStream := make(chan *swarmapi.WatchMessage, 32)
  701. c, err := cluster.New(cluster.Config{
  702. Root: cli.Config.Root,
  703. Name: name,
  704. Backend: d,
  705. VolumeBackend: d.VolumesService(),
  706. ImageBackend: d.ImageBackend(),
  707. PluginBackend: d.PluginManager(),
  708. NetworkSubnetsProvider: d,
  709. DefaultAdvertiseAddr: cli.Config.SwarmDefaultAdvertiseAddr,
  710. RaftHeartbeatTick: cli.Config.SwarmRaftHeartbeatTick,
  711. RaftElectionTick: cli.Config.SwarmRaftElectionTick,
  712. RuntimeRoot: cli.getSwarmRunRoot(),
  713. WatchStream: watchStream,
  714. })
  715. if err != nil {
  716. return nil, err
  717. }
  718. d.SetCluster(c)
  719. err = c.Start()
  720. return c, err
  721. }
  722. // validates that the plugins requested with the --authorization-plugin flag are valid AuthzDriver
  723. // plugins present on the host and available to the daemon
  724. func validateAuthzPlugins(requestedPlugins []string, pg plugingetter.PluginGetter) error {
  725. for _, reqPlugin := range requestedPlugins {
  726. if _, err := pg.Get(reqPlugin, authorization.AuthZApiImplements, plugingetter.Lookup); err != nil {
  727. return err
  728. }
  729. }
  730. return nil
  731. }
  732. func systemContainerdRunning(honorXDG bool) (string, bool, error) {
  733. addr := containerddefaults.DefaultAddress
  734. if honorXDG {
  735. runtimeDir, err := homedir.GetRuntimeDir()
  736. if err != nil {
  737. return "", false, err
  738. }
  739. addr = filepath.Join(runtimeDir, "containerd", "containerd.sock")
  740. }
  741. _, err := os.Lstat(addr)
  742. return addr, err == nil, nil
  743. }
  744. // configureDaemonLogs sets the logrus logging level and formatting. It expects
  745. // the passed configuration to already be validated, and ignores invalid options.
  746. func configureDaemonLogs(conf *config.Config) {
  747. if conf.LogLevel != "" {
  748. lvl, err := logrus.ParseLevel(conf.LogLevel)
  749. if err == nil {
  750. logrus.SetLevel(lvl)
  751. }
  752. } else {
  753. logrus.SetLevel(logrus.InfoLevel)
  754. }
  755. logFormat := conf.LogFormat
  756. if logFormat == "" {
  757. logFormat = log.TextFormat
  758. }
  759. var formatter logrus.Formatter
  760. switch logFormat {
  761. case log.JSONFormat:
  762. formatter = &logrus.JSONFormatter{
  763. TimestampFormat: jsonmessage.RFC3339NanoFixed,
  764. }
  765. case log.TextFormat:
  766. formatter = &logrus.TextFormatter{
  767. TimestampFormat: jsonmessage.RFC3339NanoFixed,
  768. DisableColors: conf.RawLogs,
  769. FullTimestamp: true,
  770. }
  771. default:
  772. panic("unsupported log format " + logFormat)
  773. }
  774. logrus.SetFormatter(formatter)
  775. }
  776. func configureProxyEnv(conf *config.Config) {
  777. if p := conf.HTTPProxy; p != "" {
  778. overrideProxyEnv("HTTP_PROXY", p)
  779. overrideProxyEnv("http_proxy", p)
  780. }
  781. if p := conf.HTTPSProxy; p != "" {
  782. overrideProxyEnv("HTTPS_PROXY", p)
  783. overrideProxyEnv("https_proxy", p)
  784. }
  785. if p := conf.NoProxy; p != "" {
  786. overrideProxyEnv("NO_PROXY", p)
  787. overrideProxyEnv("no_proxy", p)
  788. }
  789. }
  790. func overrideProxyEnv(name, val string) {
  791. if oldVal := os.Getenv(name); oldVal != "" && oldVal != val {
  792. log.G(context.TODO()).WithFields(logrus.Fields{
  793. "name": name,
  794. "old-value": config.MaskCredentials(oldVal),
  795. "new-value": config.MaskCredentials(val),
  796. }).Warn("overriding existing proxy variable with value from configuration")
  797. }
  798. _ = os.Setenv(name, val)
  799. }