daemon.go 29 KB

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