daemon.go 32 KB

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