daemon.go 31 KB

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