daemon.go 30 KB

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