daemon.go 31 KB

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