daemon.go 32 KB

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