daemon.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  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. metricsEnv = "OTEL_EXPORTER_OTLP_METRICS_PROTOCOL"
  327. protoEnv = "OTEL_EXPORTER_OTLP_PROTOCOL"
  328. defaultProto = "http/protobuf"
  329. )
  330. if os.Getenv(protoEnv) == "" {
  331. if os.Getenv(tracesEnv) == "" {
  332. os.Setenv(tracesEnv, defaultProto)
  333. }
  334. if os.Getenv(metricsEnv) == "" {
  335. os.Setenv(metricsEnv, defaultProto)
  336. }
  337. }
  338. }
  339. type routerOptions struct {
  340. sessionManager *session.Manager
  341. buildBackend *buildbackend.Backend
  342. features func() map[string]bool
  343. buildkit *buildkit.Builder
  344. daemon *daemon.Daemon
  345. cluster *cluster.Cluster
  346. }
  347. func newRouterOptions(ctx context.Context, config *config.Config, d *daemon.Daemon, c *cluster.Cluster) (routerOptions, error) {
  348. sm, err := session.NewManager()
  349. if err != nil {
  350. return routerOptions{}, errors.Wrap(err, "failed to create sessionmanager")
  351. }
  352. manager, err := dockerfile.NewBuildManager(d.BuilderBackend(), d.IdentityMapping())
  353. if err != nil {
  354. return routerOptions{}, err
  355. }
  356. cgroupParent := newCgroupParent(config)
  357. bk, err := buildkit.New(ctx, buildkit.Opt{
  358. SessionManager: sm,
  359. Root: filepath.Join(config.Root, "buildkit"),
  360. EngineID: d.ID(),
  361. Dist: d.DistributionServices(),
  362. ImageTagger: d.ImageService(),
  363. NetworkController: d.NetworkController(),
  364. DefaultCgroupParent: cgroupParent,
  365. RegistryHosts: d.RegistryHosts,
  366. BuilderConfig: config.Builder,
  367. Rootless: daemon.Rootless(config),
  368. IdentityMapping: d.IdentityMapping(),
  369. DNSConfig: config.DNSConfig,
  370. ApparmorProfile: daemon.DefaultApparmorProfile(),
  371. UseSnapshotter: d.UsesSnapshotter(),
  372. Snapshotter: d.ImageService().StorageDriver(),
  373. ContainerdAddress: config.ContainerdAddr,
  374. ContainerdNamespace: config.ContainerdNamespace,
  375. })
  376. if err != nil {
  377. return routerOptions{}, err
  378. }
  379. bb, err := buildbackend.NewBackend(d.ImageService(), manager, bk, d.EventsService)
  380. if err != nil {
  381. return routerOptions{}, errors.Wrap(err, "failed to create buildmanager")
  382. }
  383. return routerOptions{
  384. sessionManager: sm,
  385. buildBackend: bb,
  386. features: d.Features,
  387. buildkit: bk,
  388. daemon: d,
  389. cluster: c,
  390. }, nil
  391. }
  392. func (cli *DaemonCli) reloadConfig() {
  393. ctx := context.TODO()
  394. reload := func(c *config.Config) {
  395. if err := validateAuthzPlugins(c.AuthorizationPlugins, cli.d.PluginStore); err != nil {
  396. log.G(ctx).Fatalf("Error validating authorization plugin: %v", err)
  397. return
  398. }
  399. if err := cli.d.Reload(c); err != nil {
  400. log.G(ctx).Errorf("Error reconfiguring the daemon: %v", err)
  401. return
  402. }
  403. // Apply our own configuration only after the daemon reload has succeeded. We
  404. // don't want to partially apply the config if the daemon is unhappy with it.
  405. cli.authzMiddleware.SetPlugins(c.AuthorizationPlugins)
  406. if c.IsValueSet("debug") {
  407. debugEnabled := debug.IsEnabled()
  408. switch {
  409. case debugEnabled && !c.Debug: // disable debug
  410. debug.Disable()
  411. case c.Debug && !debugEnabled: // enable debug
  412. debug.Enable()
  413. }
  414. }
  415. }
  416. if err := config.Reload(*cli.configFile, cli.flags, reload); err != nil {
  417. log.G(ctx).Error(err)
  418. }
  419. }
  420. func (cli *DaemonCli) stop() {
  421. // Signal that the API server should shut down as soon as possible.
  422. // This construct is used rather than directly shutting down the HTTP
  423. // server to avoid any issues if this method is called before the server
  424. // has been instantiated in cli.start(). If this method is called first,
  425. // the HTTP server will be shut down immediately upon instantiation.
  426. cli.stopOnce.Do(func() {
  427. close(cli.apiShutdown)
  428. })
  429. }
  430. // shutdownDaemon just wraps daemon.Shutdown() to handle a timeout in case
  431. // d.Shutdown() is waiting too long to kill container or worst it's
  432. // blocked there
  433. func shutdownDaemon(ctx context.Context, d *daemon.Daemon) {
  434. var cancel context.CancelFunc
  435. if timeout := d.ShutdownTimeout(); timeout >= 0 {
  436. ctx, cancel = context.WithTimeout(ctx, time.Duration(timeout)*time.Second)
  437. } else {
  438. ctx, cancel = context.WithCancel(ctx)
  439. }
  440. go func() {
  441. defer cancel()
  442. d.Shutdown(ctx)
  443. }()
  444. <-ctx.Done()
  445. if errors.Is(ctx.Err(), context.DeadlineExceeded) {
  446. log.G(ctx).Error("Force shutdown daemon")
  447. } else {
  448. log.G(ctx).Debug("Clean shutdown succeeded")
  449. }
  450. }
  451. func loadDaemonCliConfig(opts *daemonOptions) (*config.Config, error) {
  452. if !opts.flags.Parsed() {
  453. return nil, errors.New(`cannot load CLI config before flags are parsed`)
  454. }
  455. opts.setDefaultOptions()
  456. conf := opts.daemonConfig
  457. flags := opts.flags
  458. conf.Debug = opts.Debug
  459. conf.Hosts = opts.Hosts
  460. conf.LogLevel = opts.LogLevel
  461. conf.LogFormat = log.OutputFormat(opts.LogFormat)
  462. // The DOCKER_MIN_API_VERSION env-var allows overriding the minimum API
  463. // version provided by the daemon within constraints of the minimum and
  464. // maximum (current) supported API versions.
  465. //
  466. // API versions older than [config.defaultMinAPIVersion] are deprecated and
  467. // to be removed in a future release. The "DOCKER_MIN_API_VERSION" env-var
  468. // should only be used for exceptional cases.
  469. if ver := os.Getenv("DOCKER_MIN_API_VERSION"); ver != "" {
  470. if err := config.ValidateMinAPIVersion(ver); err != nil {
  471. return nil, errors.Wrap(err, "invalid DOCKER_MIN_API_VERSION")
  472. }
  473. conf.MinAPIVersion = ver
  474. }
  475. if flags.Changed(FlagTLS) {
  476. conf.TLS = &opts.TLS
  477. }
  478. if flags.Changed(FlagTLSVerify) {
  479. conf.TLSVerify = &opts.TLSVerify
  480. v := true
  481. conf.TLS = &v
  482. }
  483. if opts.TLSOptions != nil {
  484. conf.TLSOptions = config.TLSOptions{
  485. CAFile: opts.TLSOptions.CAFile,
  486. CertFile: opts.TLSOptions.CertFile,
  487. KeyFile: opts.TLSOptions.KeyFile,
  488. }
  489. } else {
  490. conf.TLSOptions = config.TLSOptions{}
  491. }
  492. if opts.configFile != "" {
  493. c, err := config.MergeDaemonConfigurations(conf, flags, opts.configFile)
  494. if err != nil {
  495. if flags.Changed("config-file") || !os.IsNotExist(err) {
  496. return nil, errors.Wrapf(err, "unable to configure the Docker daemon with file %s", opts.configFile)
  497. }
  498. }
  499. // the merged configuration can be nil if the config file didn't exist.
  500. // leave the current configuration as it is if when that happens.
  501. if c != nil {
  502. conf = c
  503. }
  504. }
  505. if err := normalizeHosts(conf); err != nil {
  506. return nil, err
  507. }
  508. if err := config.Validate(conf); err != nil {
  509. return nil, err
  510. }
  511. // Check if duplicate label-keys with different values are found
  512. newLabels, err := config.GetConflictFreeLabels(conf.Labels)
  513. if err != nil {
  514. return nil, err
  515. }
  516. conf.Labels = newLabels
  517. // Regardless of whether the user sets it to true or false, if they
  518. // specify TLSVerify at all then we need to turn on TLS
  519. if conf.IsValueSet(FlagTLSVerify) {
  520. v := true
  521. conf.TLS = &v
  522. }
  523. if conf.TLSVerify == nil && conf.TLS != nil {
  524. conf.TLSVerify = conf.TLS
  525. }
  526. err = validateCPURealtimeOptions(conf)
  527. if err != nil {
  528. return nil, err
  529. }
  530. if conf.CDISpecDirs == nil {
  531. // If the CDISpecDirs is not set at this stage, we set it to the default.
  532. conf.CDISpecDirs = append([]string(nil), cdi.DefaultSpecDirs...)
  533. } else if len(conf.CDISpecDirs) == 1 && conf.CDISpecDirs[0] == "" {
  534. // If CDISpecDirs is set to an empty string, we clear it to ensure that CDI is disabled.
  535. conf.CDISpecDirs = nil
  536. }
  537. if !conf.Features["cdi"] {
  538. // If the CDI feature is not enabled, we clear the CDISpecDirs to ensure that CDI is disabled.
  539. conf.CDISpecDirs = nil
  540. }
  541. if err := loadCLIPlatformConfig(conf); err != nil {
  542. return nil, err
  543. }
  544. return conf, nil
  545. }
  546. // normalizeHosts normalizes the configured config.Hosts and remove duplicates.
  547. // It returns an error if it fails to parse a host.
  548. func normalizeHosts(config *config.Config) error {
  549. if len(config.Hosts) == 0 {
  550. // if no hosts are configured, create a single entry slice, so that the
  551. // default is used.
  552. //
  553. // TODO(thaJeztah) implement a cleaner way for this; this depends on a
  554. // side-effect of how we parse empty/partial hosts.
  555. config.Hosts = make([]string, 1)
  556. }
  557. hosts := make([]string, 0, len(config.Hosts))
  558. seen := make(map[string]struct{}, len(config.Hosts))
  559. useTLS := DefaultTLSValue
  560. if config.TLS != nil {
  561. useTLS = *config.TLS
  562. }
  563. for _, h := range config.Hosts {
  564. host, err := dopts.ParseHost(useTLS, honorXDG, h)
  565. if err != nil {
  566. return err
  567. }
  568. if _, ok := seen[host]; ok {
  569. continue
  570. }
  571. seen[host] = struct{}{}
  572. hosts = append(hosts, host)
  573. }
  574. sort.Strings(hosts)
  575. config.Hosts = hosts
  576. return nil
  577. }
  578. func (opts routerOptions) Build() []router.Router {
  579. decoder := runconfig.ContainerDecoder{
  580. GetSysInfo: func() *sysinfo.SysInfo {
  581. return opts.daemon.RawSysInfo()
  582. },
  583. }
  584. routers := []router.Router{
  585. // we need to add the checkpoint router before the container router or the DELETE gets masked
  586. checkpointrouter.NewRouter(opts.daemon, decoder),
  587. container.NewRouter(opts.daemon, decoder, opts.daemon.RawSysInfo().CgroupUnified),
  588. image.NewRouter(
  589. opts.daemon.ImageService(),
  590. opts.daemon.RegistryService(),
  591. opts.daemon.ReferenceStore,
  592. opts.daemon.ImageService().DistributionServices().ImageStore,
  593. opts.daemon.ImageService().DistributionServices().LayerStore,
  594. ),
  595. systemrouter.NewRouter(opts.daemon, opts.cluster, opts.buildkit, opts.daemon.Features),
  596. volume.NewRouter(opts.daemon.VolumesService(), opts.cluster),
  597. build.NewRouter(opts.buildBackend, opts.daemon),
  598. sessionrouter.NewRouter(opts.sessionManager),
  599. swarmrouter.NewRouter(opts.cluster),
  600. pluginrouter.NewRouter(opts.daemon.PluginManager()),
  601. distributionrouter.NewRouter(opts.daemon.ImageBackend()),
  602. }
  603. if opts.buildBackend != nil {
  604. routers = append(routers, grpcrouter.NewRouter(opts.buildBackend))
  605. }
  606. if opts.daemon.NetworkControllerEnabled() {
  607. routers = append(routers, network.NewRouter(opts.daemon, opts.cluster))
  608. }
  609. if opts.daemon.HasExperimental() {
  610. for _, r := range routers {
  611. for _, route := range r.Routes() {
  612. if experimental, ok := route.(router.ExperimentalRoute); ok {
  613. experimental.Enable()
  614. }
  615. }
  616. }
  617. }
  618. return routers
  619. }
  620. func initMiddlewares(s *apiserver.Server, cfg *config.Config, pluginStore plugingetter.PluginGetter) (*authorization.Middleware, error) {
  621. exp := middleware.NewExperimentalMiddleware(cfg.Experimental)
  622. s.UseMiddleware(exp)
  623. vm, err := middleware.NewVersionMiddleware(dockerversion.Version, api.DefaultVersion, cfg.MinAPIVersion)
  624. if err != nil {
  625. return nil, err
  626. }
  627. s.UseMiddleware(*vm)
  628. if cfg.CorsHeaders != "" {
  629. c := middleware.NewCORSMiddleware(cfg.CorsHeaders)
  630. s.UseMiddleware(c)
  631. }
  632. authzMiddleware := authorization.NewMiddleware(cfg.AuthorizationPlugins, pluginStore)
  633. s.UseMiddleware(authzMiddleware)
  634. return authzMiddleware, nil
  635. }
  636. func (cli *DaemonCli) getContainerdDaemonOpts() ([]supervisor.DaemonOpt, error) {
  637. var opts []supervisor.DaemonOpt
  638. if cli.Debug {
  639. opts = append(opts, supervisor.WithLogLevel("debug"))
  640. } else {
  641. opts = append(opts, supervisor.WithLogLevel(cli.LogLevel))
  642. }
  643. if logFormat := cli.Config.LogFormat; logFormat != "" {
  644. opts = append(opts, supervisor.WithLogFormat(logFormat))
  645. }
  646. if !cli.CriContainerd {
  647. // CRI support in the managed daemon is currently opt-in.
  648. //
  649. // It's disabled by default, originally because it was listening on
  650. // a TCP connection at 0.0.0.0:10010, which was considered a security
  651. // risk, and could conflict with user's container ports.
  652. //
  653. // Current versions of containerd started now listen on localhost on
  654. // an ephemeral port instead, but could still conflict with container
  655. // ports, and running kubernetes using the static binaries is not a
  656. // common scenario, so we (for now) continue disabling it by default.
  657. //
  658. // Also see https://github.com/containerd/containerd/issues/2483#issuecomment-407530608
  659. opts = append(opts, supervisor.WithCRIDisabled())
  660. }
  661. return opts, nil
  662. }
  663. func newAPIServerTLSConfig(config *config.Config) (*tls.Config, error) {
  664. var tlsConfig *tls.Config
  665. if config.TLS != nil && *config.TLS {
  666. var (
  667. clientAuth tls.ClientAuthType
  668. err error
  669. )
  670. if config.TLSVerify == nil || *config.TLSVerify {
  671. // server requires and verifies client's certificate
  672. clientAuth = tls.RequireAndVerifyClientCert
  673. }
  674. tlsConfig, err = tlsconfig.Server(tlsconfig.Options{
  675. CAFile: config.TLSOptions.CAFile,
  676. CertFile: config.TLSOptions.CertFile,
  677. KeyFile: config.TLSOptions.KeyFile,
  678. ExclusiveRootPools: true,
  679. ClientAuth: clientAuth,
  680. })
  681. if err != nil {
  682. return nil, errors.Wrap(err, "invalid TLS configuration")
  683. }
  684. }
  685. return tlsConfig, nil
  686. }
  687. // checkTLSAuthOK checks basically for an explicitly disabled TLS/TLSVerify
  688. // Going forward we do not want to support a scenario where dockerd listens
  689. // on TCP without either TLS client auth (or an explicit opt-in to disable it)
  690. func checkTLSAuthOK(c *config.Config) bool {
  691. if c.TLS == nil {
  692. // Either TLS is enabled by default, in which case TLS verification should be enabled by default, or explicitly disabled
  693. // Or TLS is disabled by default... in any of these cases, we can just take the default value as to how to proceed
  694. return DefaultTLSValue
  695. }
  696. if !*c.TLS {
  697. // TLS is explicitly disabled, which is supported
  698. return true
  699. }
  700. if c.TLSVerify == nil {
  701. // this actually shouldn't happen since we set TLSVerify on the config object anyway
  702. // But in case it does get here, be cautious and assume this is not supported.
  703. return false
  704. }
  705. // Either TLSVerify is explicitly enabled or disabled, both cases are supported
  706. return true
  707. }
  708. func loadListeners(cfg *config.Config, tlsConfig *tls.Config) ([]net.Listener, []string, error) {
  709. ctx := context.TODO()
  710. if len(cfg.Hosts) == 0 {
  711. return nil, nil, errors.New("no hosts configured")
  712. }
  713. var (
  714. hosts []string
  715. lss []net.Listener
  716. )
  717. for i := 0; i < len(cfg.Hosts); i++ {
  718. protoAddr := cfg.Hosts[i]
  719. proto, addr, ok := strings.Cut(protoAddr, "://")
  720. if !ok {
  721. return nil, nil, fmt.Errorf("bad format %s, expected PROTO://ADDR", protoAddr)
  722. }
  723. // It's a bad idea to bind to TCP without tlsverify.
  724. authEnabled := tlsConfig != nil && tlsConfig.ClientAuth == tls.RequireAndVerifyClientCert
  725. if proto == "tcp" && !authEnabled {
  726. 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.")
  727. 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!")
  728. time.Sleep(time.Second)
  729. // If TLSVerify is explicitly set to false we'll take that as "Please let me shoot myself in the foot"
  730. // 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
  731. if !checkTLSAuthOK(cfg) {
  732. ipAddr, _, err := net.SplitHostPort(addr)
  733. if err != nil {
  734. return nil, nil, errors.Wrap(err, "error parsing tcp address")
  735. }
  736. // shortcut all this extra stuff for literal "localhost"
  737. // -H supports specifying hostnames, since we want to bypass this on loopback interfaces we'll look it up here.
  738. if ipAddr != "localhost" {
  739. ip := net.ParseIP(ipAddr)
  740. if ip == nil {
  741. ipA, err := net.ResolveIPAddr("ip", ipAddr)
  742. if err != nil {
  743. log.G(ctx).WithError(err).WithField("host", ipAddr).Error("Error looking up specified host address")
  744. }
  745. if ipA != nil {
  746. ip = ipA.IP
  747. }
  748. }
  749. if ip == nil || !ip.IsLoopback() {
  750. 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")
  751. log.G(ctx).WithField("host", protoAddr).Warn("Please consider generating tls certificates with client validation to prevent exposing unauthenticated root access to your network")
  752. log.G(ctx).WithField("host", protoAddr).Warnf("You can override this by explicitly specifying '--%s=false' or '--%s=false'", FlagTLS, FlagTLSVerify)
  753. 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")
  754. time.Sleep(15 * time.Second)
  755. }
  756. }
  757. }
  758. }
  759. // If we're binding to a TCP port, make sure that a container doesn't try to use it.
  760. if proto == "tcp" {
  761. if err := allocateDaemonPort(addr); err != nil {
  762. return nil, nil, err
  763. }
  764. }
  765. ls, err := listeners.Init(proto, addr, cfg.SocketGroup, tlsConfig)
  766. if err != nil {
  767. return nil, nil, err
  768. }
  769. log.G(ctx).Debugf("Listener created for HTTP on %s (%s)", proto, addr)
  770. hosts = append(hosts, addr)
  771. lss = append(lss, ls...)
  772. }
  773. return lss, hosts, nil
  774. }
  775. func createAndStartCluster(cli *DaemonCli, d *daemon.Daemon) (*cluster.Cluster, error) {
  776. name, _ := os.Hostname()
  777. // Use a buffered channel to pass changes from store watch API to daemon
  778. // A buffer allows store watch API and daemon processing to not wait for each other
  779. watchStream := make(chan *swarmapi.WatchMessage, 32)
  780. c, err := cluster.New(cluster.Config{
  781. Root: cli.Config.Root,
  782. Name: name,
  783. Backend: d,
  784. VolumeBackend: d.VolumesService(),
  785. ImageBackend: d.ImageBackend(),
  786. PluginBackend: d.PluginManager(),
  787. NetworkSubnetsProvider: d,
  788. DefaultAdvertiseAddr: cli.Config.SwarmDefaultAdvertiseAddr,
  789. RaftHeartbeatTick: cli.Config.SwarmRaftHeartbeatTick,
  790. RaftElectionTick: cli.Config.SwarmRaftElectionTick,
  791. RuntimeRoot: cli.getSwarmRunRoot(),
  792. WatchStream: watchStream,
  793. })
  794. if err != nil {
  795. return nil, err
  796. }
  797. d.SetCluster(c)
  798. err = c.Start()
  799. return c, err
  800. }
  801. // validates that the plugins requested with the --authorization-plugin flag are valid AuthzDriver
  802. // plugins present on the host and available to the daemon
  803. func validateAuthzPlugins(requestedPlugins []string, pg plugingetter.PluginGetter) error {
  804. for _, reqPlugin := range requestedPlugins {
  805. if _, err := pg.Get(reqPlugin, authorization.AuthZApiImplements, plugingetter.Lookup); err != nil {
  806. return err
  807. }
  808. }
  809. return nil
  810. }
  811. func systemContainerdRunning(honorXDG bool) (string, bool, error) {
  812. addr := containerddefaults.DefaultAddress
  813. if honorXDG {
  814. runtimeDir, err := homedir.GetRuntimeDir()
  815. if err != nil {
  816. return "", false, err
  817. }
  818. addr = filepath.Join(runtimeDir, "containerd", "containerd.sock")
  819. }
  820. _, err := os.Lstat(addr)
  821. return addr, err == nil, nil
  822. }
  823. // configureDaemonLogs sets the logging level and formatting. It expects
  824. // the passed configuration to already be validated, and ignores invalid options.
  825. func configureDaemonLogs(conf *config.Config) {
  826. switch conf.LogFormat {
  827. case log.JSONFormat:
  828. if err := log.SetFormat(log.JSONFormat); err != nil {
  829. panic(err.Error())
  830. }
  831. case log.TextFormat, "":
  832. if err := log.SetFormat(log.TextFormat); err != nil {
  833. panic(err.Error())
  834. }
  835. if conf.RawLogs {
  836. // FIXME(thaJeztah): this needs a better solution: containerd doesn't allow disabling colors, and this code is depending on internal knowledge of "log.SetFormat"
  837. if l, ok := log.L.Logger.Formatter.(*logrus.TextFormatter); ok {
  838. l.DisableColors = true
  839. }
  840. }
  841. default:
  842. panic("unsupported log format " + conf.LogFormat)
  843. }
  844. logLevel := conf.LogLevel
  845. if logLevel == "" {
  846. logLevel = "info"
  847. }
  848. if err := log.SetLevel(logLevel); err != nil {
  849. log.G(context.TODO()).WithError(err).Warn("configure log level")
  850. }
  851. }
  852. func configureProxyEnv(conf *config.Config) {
  853. if p := conf.HTTPProxy; p != "" {
  854. overrideProxyEnv("HTTP_PROXY", p)
  855. overrideProxyEnv("http_proxy", p)
  856. }
  857. if p := conf.HTTPSProxy; p != "" {
  858. overrideProxyEnv("HTTPS_PROXY", p)
  859. overrideProxyEnv("https_proxy", p)
  860. }
  861. if p := conf.NoProxy; p != "" {
  862. overrideProxyEnv("NO_PROXY", p)
  863. overrideProxyEnv("no_proxy", p)
  864. }
  865. }
  866. func overrideProxyEnv(name, val string) {
  867. if oldVal := os.Getenv(name); oldVal != "" && oldVal != val {
  868. log.G(context.TODO()).WithFields(log.Fields{
  869. "name": name,
  870. "old-value": config.MaskCredentials(oldVal),
  871. "new-value": config.MaskCredentials(val),
  872. }).Warn("overriding existing proxy variable with value from configuration")
  873. }
  874. _ = os.Setenv(name, val)
  875. }