daemon.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  1. package main
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "fmt"
  6. "net"
  7. "os"
  8. "path/filepath"
  9. "runtime"
  10. "strings"
  11. "time"
  12. containerddefaults "github.com/containerd/containerd/defaults"
  13. "github.com/docker/docker/api"
  14. apiserver "github.com/docker/docker/api/server"
  15. buildbackend "github.com/docker/docker/api/server/backend/build"
  16. "github.com/docker/docker/api/server/middleware"
  17. "github.com/docker/docker/api/server/router"
  18. "github.com/docker/docker/api/server/router/build"
  19. checkpointrouter "github.com/docker/docker/api/server/router/checkpoint"
  20. "github.com/docker/docker/api/server/router/container"
  21. distributionrouter "github.com/docker/docker/api/server/router/distribution"
  22. grpcrouter "github.com/docker/docker/api/server/router/grpc"
  23. "github.com/docker/docker/api/server/router/image"
  24. "github.com/docker/docker/api/server/router/network"
  25. pluginrouter "github.com/docker/docker/api/server/router/plugin"
  26. sessionrouter "github.com/docker/docker/api/server/router/session"
  27. swarmrouter "github.com/docker/docker/api/server/router/swarm"
  28. systemrouter "github.com/docker/docker/api/server/router/system"
  29. "github.com/docker/docker/api/server/router/volume"
  30. buildkit "github.com/docker/docker/builder/builder-next"
  31. "github.com/docker/docker/builder/dockerfile"
  32. "github.com/docker/docker/cli/debug"
  33. "github.com/docker/docker/daemon"
  34. "github.com/docker/docker/daemon/cluster"
  35. "github.com/docker/docker/daemon/config"
  36. "github.com/docker/docker/daemon/listeners"
  37. "github.com/docker/docker/dockerversion"
  38. "github.com/docker/docker/libcontainerd/supervisor"
  39. dopts "github.com/docker/docker/opts"
  40. "github.com/docker/docker/pkg/authorization"
  41. "github.com/docker/docker/pkg/homedir"
  42. "github.com/docker/docker/pkg/jsonmessage"
  43. "github.com/docker/docker/pkg/pidfile"
  44. "github.com/docker/docker/pkg/plugingetter"
  45. "github.com/docker/docker/pkg/signal"
  46. "github.com/docker/docker/pkg/sysinfo"
  47. "github.com/docker/docker/pkg/system"
  48. "github.com/docker/docker/plugin"
  49. "github.com/docker/docker/rootless"
  50. "github.com/docker/docker/runconfig"
  51. "github.com/docker/go-connections/tlsconfig"
  52. swarmapi "github.com/docker/swarmkit/api"
  53. "github.com/moby/buildkit/session"
  54. "github.com/pkg/errors"
  55. "github.com/sirupsen/logrus"
  56. "github.com/spf13/pflag"
  57. )
  58. // DaemonCli represents the daemon CLI.
  59. type DaemonCli struct {
  60. *config.Config
  61. configFile *string
  62. flags *pflag.FlagSet
  63. api *apiserver.Server
  64. d *daemon.Daemon
  65. authzMiddleware *authorization.Middleware // authzMiddleware enables to dynamically reload the authorization plugins
  66. }
  67. // NewDaemonCli returns a daemon CLI
  68. func NewDaemonCli() *DaemonCli {
  69. return &DaemonCli{}
  70. }
  71. func (cli *DaemonCli) start(opts *daemonOptions) (err error) {
  72. opts.SetDefaultOptions(opts.flags)
  73. if cli.Config, err = loadDaemonCliConfig(opts); err != nil {
  74. return err
  75. }
  76. if opts.Validate {
  77. // If config wasn't OK we wouldn't have made it this far.
  78. fmt.Fprintln(os.Stderr, "configuration OK")
  79. return nil
  80. }
  81. warnOnDeprecatedConfigOptions(cli.Config)
  82. if err := configureDaemonLogs(cli.Config); err != nil {
  83. return err
  84. }
  85. logrus.Info("Starting up")
  86. cli.configFile = &opts.configFile
  87. cli.flags = opts.flags
  88. if cli.Config.Debug {
  89. debug.Enable()
  90. }
  91. if cli.Config.Experimental {
  92. logrus.Warn("Running experimental build")
  93. }
  94. if cli.Config.IsRootless() {
  95. logrus.Warn("Running in rootless mode. This mode has feature limitations.")
  96. }
  97. if rootless.RunningWithRootlessKit() {
  98. logrus.Info("Running with RootlessKit integration")
  99. if !cli.Config.IsRootless() {
  100. return fmt.Errorf("rootless mode needs to be enabled for running with RootlessKit")
  101. }
  102. }
  103. // return human-friendly error before creating files
  104. if runtime.GOOS == "linux" && os.Geteuid() != 0 {
  105. return fmt.Errorf("dockerd needs to be started with root. To see how to run dockerd in rootless mode with unprivileged user, see the documentation")
  106. }
  107. if err := setDefaultUmask(); err != nil {
  108. return err
  109. }
  110. // Create the daemon root before we create ANY other files (PID, or migrate keys)
  111. // to ensure the appropriate ACL is set (particularly relevant on Windows)
  112. if err := daemon.CreateDaemonRoot(cli.Config); err != nil {
  113. return err
  114. }
  115. if err := system.MkdirAll(cli.Config.ExecRoot, 0700); err != nil {
  116. return err
  117. }
  118. potentiallyUnderRuntimeDir := []string{cli.Config.ExecRoot}
  119. if cli.Pidfile != "" {
  120. pf, err := pidfile.New(cli.Pidfile)
  121. if err != nil {
  122. return errors.Wrap(err, "failed to start daemon")
  123. }
  124. potentiallyUnderRuntimeDir = append(potentiallyUnderRuntimeDir, cli.Pidfile)
  125. defer func() {
  126. if err := pf.Remove(); err != nil {
  127. logrus.Error(err)
  128. }
  129. }()
  130. }
  131. if cli.Config.IsRootless() {
  132. // Set sticky bit if XDG_RUNTIME_DIR is set && the file is actually under XDG_RUNTIME_DIR
  133. if _, err := homedir.StickRuntimeDirContents(potentiallyUnderRuntimeDir); err != nil {
  134. // StickRuntimeDirContents returns nil error if XDG_RUNTIME_DIR is just unset
  135. logrus.WithError(err).Warn("cannot set sticky bit on files under XDG_RUNTIME_DIR")
  136. }
  137. }
  138. serverConfig, err := newAPIServerConfig(cli)
  139. if err != nil {
  140. return errors.Wrap(err, "failed to create API server")
  141. }
  142. cli.api = apiserver.New(serverConfig)
  143. hosts, err := loadListeners(cli, serverConfig)
  144. if err != nil {
  145. return errors.Wrap(err, "failed to load listeners")
  146. }
  147. ctx, cancel := context.WithCancel(context.Background())
  148. waitForContainerDShutdown, err := cli.initContainerD(ctx)
  149. if waitForContainerDShutdown != nil {
  150. defer waitForContainerDShutdown(10 * time.Second)
  151. }
  152. if err != nil {
  153. cancel()
  154. return err
  155. }
  156. defer cancel()
  157. stopc := make(chan bool)
  158. defer close(stopc)
  159. signal.Trap(func() {
  160. cli.stop()
  161. <-stopc // wait for daemonCli.start() to return
  162. }, logrus.StandardLogger())
  163. // Notify that the API is active, but before daemon is set up.
  164. preNotifyReady()
  165. pluginStore := plugin.NewStore()
  166. if err := cli.initMiddlewares(cli.api, serverConfig, pluginStore); err != nil {
  167. logrus.Fatalf("Error creating middlewares: %v", err)
  168. }
  169. d, err := daemon.NewDaemon(ctx, cli.Config, pluginStore)
  170. if err != nil {
  171. return errors.Wrap(err, "failed to start daemon")
  172. }
  173. d.StoreHosts(hosts)
  174. // validate after NewDaemon has restored enabled plugins. Don't change order.
  175. if err := validateAuthzPlugins(cli.Config.AuthorizationPlugins, pluginStore); err != nil {
  176. return errors.Wrap(err, "failed to validate authorization plugin")
  177. }
  178. cli.d = d
  179. if err := startMetricsServer(cli.Config.MetricsAddress); err != nil {
  180. return errors.Wrap(err, "failed to start metrics server")
  181. }
  182. c, err := createAndStartCluster(cli, d)
  183. if err != nil {
  184. logrus.Fatalf("Error starting cluster component: %v", err)
  185. }
  186. // Restart all autostart containers which has a swarm endpoint
  187. // and is not yet running now that we have successfully
  188. // initialized the cluster.
  189. d.RestartSwarmContainers()
  190. logrus.Info("Daemon has completed initialization")
  191. routerOptions, err := newRouterOptions(cli.Config, d)
  192. if err != nil {
  193. return err
  194. }
  195. routerOptions.api = cli.api
  196. routerOptions.cluster = c
  197. initRouter(routerOptions)
  198. go d.ProcessClusterNotifications(ctx, c.GetWatchStream())
  199. cli.setupConfigReloadTrap()
  200. // The serve API routine never exits unless an error occurs
  201. // We need to start it as a goroutine and wait on it so
  202. // daemon doesn't exit
  203. serveAPIWait := make(chan error)
  204. go cli.api.Wait(serveAPIWait)
  205. // after the daemon is done setting up we can notify systemd api
  206. notifyReady()
  207. // Daemon is fully initialized and handling API traffic
  208. // Wait for serve API to complete
  209. errAPI := <-serveAPIWait
  210. c.Cleanup()
  211. // notify systemd that we're shutting down
  212. notifyStopping()
  213. shutdownDaemon(d)
  214. // Stop notification processing and any background processes
  215. cancel()
  216. if errAPI != nil {
  217. return errors.Wrap(errAPI, "shutting down due to ServeAPI error")
  218. }
  219. logrus.Info("Daemon shutdown complete")
  220. return nil
  221. }
  222. type routerOptions struct {
  223. sessionManager *session.Manager
  224. buildBackend *buildbackend.Backend
  225. features *map[string]bool
  226. buildkit *buildkit.Builder
  227. daemon *daemon.Daemon
  228. api *apiserver.Server
  229. cluster *cluster.Cluster
  230. }
  231. func newRouterOptions(config *config.Config, d *daemon.Daemon) (routerOptions, error) {
  232. opts := routerOptions{}
  233. sm, err := session.NewManager()
  234. if err != nil {
  235. return opts, errors.Wrap(err, "failed to create sessionmanager")
  236. }
  237. manager, err := dockerfile.NewBuildManager(d.BuilderBackend(), d.IdentityMapping())
  238. if err != nil {
  239. return opts, err
  240. }
  241. cgroupParent := newCgroupParent(config)
  242. bk, err := buildkit.New(buildkit.Opt{
  243. SessionManager: sm,
  244. Root: filepath.Join(config.Root, "buildkit"),
  245. Dist: d.DistributionServices(),
  246. NetworkController: d.NetworkController(),
  247. DefaultCgroupParent: cgroupParent,
  248. RegistryHosts: d.RegistryHosts(),
  249. BuilderConfig: config.Builder,
  250. Rootless: d.Rootless(),
  251. IdentityMapping: d.IdentityMapping(),
  252. DNSConfig: config.DNSConfig,
  253. ApparmorProfile: daemon.DefaultApparmorProfile(),
  254. })
  255. if err != nil {
  256. return opts, err
  257. }
  258. bb, err := buildbackend.NewBackend(d.ImageService(), manager, bk, d.EventsService)
  259. if err != nil {
  260. return opts, errors.Wrap(err, "failed to create buildmanager")
  261. }
  262. return routerOptions{
  263. sessionManager: sm,
  264. buildBackend: bb,
  265. buildkit: bk,
  266. features: d.Features(),
  267. daemon: d,
  268. }, nil
  269. }
  270. func (cli *DaemonCli) reloadConfig() {
  271. reload := func(c *config.Config) {
  272. // Revalidate and reload the authorization plugins
  273. if err := validateAuthzPlugins(c.AuthorizationPlugins, cli.d.PluginStore); err != nil {
  274. logrus.Fatalf("Error validating authorization plugin: %v", err)
  275. return
  276. }
  277. cli.authzMiddleware.SetPlugins(c.AuthorizationPlugins)
  278. if err := cli.d.Reload(c); err != nil {
  279. logrus.Errorf("Error reconfiguring the daemon: %v", err)
  280. return
  281. }
  282. if c.IsValueSet("debug") {
  283. debugEnabled := debug.IsEnabled()
  284. switch {
  285. case debugEnabled && !c.Debug: // disable debug
  286. debug.Disable()
  287. case c.Debug && !debugEnabled: // enable debug
  288. debug.Enable()
  289. }
  290. }
  291. }
  292. if err := config.Reload(*cli.configFile, cli.flags, reload); err != nil {
  293. logrus.Error(err)
  294. }
  295. }
  296. func (cli *DaemonCli) stop() {
  297. cli.api.Close()
  298. }
  299. // shutdownDaemon just wraps daemon.Shutdown() to handle a timeout in case
  300. // d.Shutdown() is waiting too long to kill container or worst it's
  301. // blocked there
  302. func shutdownDaemon(d *daemon.Daemon) {
  303. shutdownTimeout := d.ShutdownTimeout()
  304. ch := make(chan struct{})
  305. go func() {
  306. d.Shutdown()
  307. close(ch)
  308. }()
  309. if shutdownTimeout < 0 {
  310. <-ch
  311. logrus.Debug("Clean shutdown succeeded")
  312. return
  313. }
  314. timeout := time.NewTimer(time.Duration(shutdownTimeout) * time.Second)
  315. defer timeout.Stop()
  316. select {
  317. case <-ch:
  318. logrus.Debug("Clean shutdown succeeded")
  319. case <-timeout.C:
  320. logrus.Error("Force shutdown daemon")
  321. }
  322. }
  323. func loadDaemonCliConfig(opts *daemonOptions) (*config.Config, error) {
  324. conf := opts.daemonConfig
  325. flags := opts.flags
  326. conf.Debug = opts.Debug
  327. conf.Hosts = opts.Hosts
  328. conf.LogLevel = opts.LogLevel
  329. if opts.flags.Changed(FlagTLS) {
  330. conf.TLS = &opts.TLS
  331. }
  332. if opts.flags.Changed(FlagTLSVerify) {
  333. conf.TLSVerify = &opts.TLSVerify
  334. v := true
  335. conf.TLS = &v
  336. }
  337. conf.CommonTLSOptions = config.CommonTLSOptions{}
  338. if opts.TLSOptions != nil {
  339. conf.CommonTLSOptions.CAFile = opts.TLSOptions.CAFile
  340. conf.CommonTLSOptions.CertFile = opts.TLSOptions.CertFile
  341. conf.CommonTLSOptions.KeyFile = opts.TLSOptions.KeyFile
  342. }
  343. if conf.TrustKeyPath == "" {
  344. daemonConfDir, err := getDaemonConfDir(conf.Root)
  345. if err != nil {
  346. return nil, err
  347. }
  348. conf.TrustKeyPath = filepath.Join(daemonConfDir, defaultTrustKeyFile)
  349. }
  350. if flags.Changed("graph") && flags.Changed("data-root") {
  351. return nil, errors.New(`cannot specify both "--graph" and "--data-root" option`)
  352. }
  353. if opts.configFile != "" {
  354. c, err := config.MergeDaemonConfigurations(conf, flags, opts.configFile)
  355. if err != nil {
  356. if flags.Changed("config-file") || !os.IsNotExist(err) {
  357. return nil, errors.Wrapf(err, "unable to configure the Docker daemon with file %s", opts.configFile)
  358. }
  359. }
  360. // the merged configuration can be nil if the config file didn't exist.
  361. // leave the current configuration as it is if when that happens.
  362. if c != nil {
  363. conf = c
  364. }
  365. }
  366. if err := config.Validate(conf); err != nil {
  367. return nil, err
  368. }
  369. if flags.Changed("graph") {
  370. logrus.Warnf(`The "-g / --graph" flag is deprecated. Please use "--data-root" instead`)
  371. }
  372. // Check if duplicate label-keys with different values are found
  373. newLabels, err := config.GetConflictFreeLabels(conf.Labels)
  374. if err != nil {
  375. return nil, err
  376. }
  377. conf.Labels = newLabels
  378. // Regardless of whether the user sets it to true or false, if they
  379. // specify TLSVerify at all then we need to turn on TLS
  380. if conf.IsValueSet(FlagTLSVerify) {
  381. v := true
  382. conf.TLS = &v
  383. }
  384. if conf.TLSVerify == nil && conf.TLS != nil {
  385. conf.TLSVerify = conf.TLS
  386. }
  387. return conf, nil
  388. }
  389. func warnOnDeprecatedConfigOptions(config *config.Config) {
  390. if config.ClusterAdvertise != "" {
  391. logrus.Warn(`The "cluster-advertise" option is deprecated. To be removed soon.`)
  392. }
  393. if config.ClusterStore != "" {
  394. logrus.Warn(`The "cluster-store" option is deprecated. To be removed soon.`)
  395. }
  396. if len(config.ClusterOpts) > 0 {
  397. logrus.Warn(`The "cluster-store-opt" option is deprecated. To be removed soon.`)
  398. }
  399. }
  400. func initRouter(opts routerOptions) {
  401. decoder := runconfig.ContainerDecoder{
  402. GetSysInfo: func() *sysinfo.SysInfo {
  403. return opts.daemon.RawSysInfo()
  404. },
  405. }
  406. routers := []router.Router{
  407. // we need to add the checkpoint router before the container router or the DELETE gets masked
  408. checkpointrouter.NewRouter(opts.daemon, decoder),
  409. container.NewRouter(opts.daemon, decoder, opts.daemon.RawSysInfo().CgroupUnified),
  410. image.NewRouter(opts.daemon.ImageService()),
  411. systemrouter.NewRouter(opts.daemon, opts.cluster, opts.buildkit, opts.features),
  412. volume.NewRouter(opts.daemon.VolumesService()),
  413. build.NewRouter(opts.buildBackend, opts.daemon, opts.features),
  414. sessionrouter.NewRouter(opts.sessionManager),
  415. swarmrouter.NewRouter(opts.cluster),
  416. pluginrouter.NewRouter(opts.daemon.PluginManager()),
  417. distributionrouter.NewRouter(opts.daemon.ImageService()),
  418. }
  419. grpcBackends := []grpcrouter.Backend{}
  420. for _, b := range []interface{}{opts.daemon, opts.buildBackend} {
  421. if b, ok := b.(grpcrouter.Backend); ok {
  422. grpcBackends = append(grpcBackends, b)
  423. }
  424. }
  425. if len(grpcBackends) > 0 {
  426. routers = append(routers, grpcrouter.NewRouter(grpcBackends...))
  427. }
  428. if opts.daemon.NetworkControllerEnabled() {
  429. routers = append(routers, network.NewRouter(opts.daemon, opts.cluster))
  430. }
  431. if opts.daemon.HasExperimental() {
  432. for _, r := range routers {
  433. for _, route := range r.Routes() {
  434. if experimental, ok := route.(router.ExperimentalRoute); ok {
  435. experimental.Enable()
  436. }
  437. }
  438. }
  439. }
  440. opts.api.InitRouter(routers...)
  441. }
  442. // TODO: remove this from cli and return the authzMiddleware
  443. func (cli *DaemonCli) initMiddlewares(s *apiserver.Server, cfg *apiserver.Config, pluginStore plugingetter.PluginGetter) error {
  444. v := cfg.Version
  445. exp := middleware.NewExperimentalMiddleware(cli.Config.Experimental)
  446. s.UseMiddleware(exp)
  447. vm := middleware.NewVersionMiddleware(v, api.DefaultVersion, api.MinVersion)
  448. s.UseMiddleware(vm)
  449. if cfg.CorsHeaders != "" {
  450. c := middleware.NewCORSMiddleware(cfg.CorsHeaders)
  451. s.UseMiddleware(c)
  452. }
  453. cli.authzMiddleware = authorization.NewMiddleware(cli.Config.AuthorizationPlugins, pluginStore)
  454. cli.Config.AuthzMiddleware = cli.authzMiddleware
  455. s.UseMiddleware(cli.authzMiddleware)
  456. return nil
  457. }
  458. func (cli *DaemonCli) getContainerdDaemonOpts() ([]supervisor.DaemonOpt, error) {
  459. opts, err := cli.getPlatformContainerdDaemonOpts()
  460. if err != nil {
  461. return nil, err
  462. }
  463. if cli.Config.Debug {
  464. opts = append(opts, supervisor.WithLogLevel("debug"))
  465. } else if cli.Config.LogLevel != "" {
  466. opts = append(opts, supervisor.WithLogLevel(cli.Config.LogLevel))
  467. }
  468. if !cli.Config.CriContainerd {
  469. opts = append(opts, supervisor.WithPlugin("cri", nil))
  470. }
  471. return opts, nil
  472. }
  473. func newAPIServerConfig(cli *DaemonCli) (*apiserver.Config, error) {
  474. serverConfig := &apiserver.Config{
  475. Logging: true,
  476. SocketGroup: cli.Config.SocketGroup,
  477. Version: dockerversion.Version,
  478. CorsHeaders: cli.Config.CorsHeaders,
  479. }
  480. if cli.Config.TLS != nil && *cli.Config.TLS {
  481. tlsOptions := tlsconfig.Options{
  482. CAFile: cli.Config.CommonTLSOptions.CAFile,
  483. CertFile: cli.Config.CommonTLSOptions.CertFile,
  484. KeyFile: cli.Config.CommonTLSOptions.KeyFile,
  485. ExclusiveRootPools: true,
  486. }
  487. if cli.Config.TLSVerify == nil || *cli.Config.TLSVerify {
  488. // server requires and verifies client's certificate
  489. tlsOptions.ClientAuth = tls.RequireAndVerifyClientCert
  490. }
  491. tlsConfig, err := tlsconfig.Server(tlsOptions)
  492. if err != nil {
  493. return nil, err
  494. }
  495. serverConfig.TLSConfig = tlsConfig
  496. }
  497. if len(cli.Config.Hosts) == 0 {
  498. cli.Config.Hosts = make([]string, 1)
  499. }
  500. return serverConfig, nil
  501. }
  502. // checkTLSAuthOK checks basically for an explicitly disabled TLS/TLSVerify
  503. // Going forward we do not want to support a scenario where dockerd listens
  504. // on TCP without either TLS client auth (or an explicit opt-in to disable it)
  505. func checkTLSAuthOK(c *config.Config) bool {
  506. if c.TLS == nil {
  507. // Either TLS is enabled by default, in which case TLS verification should be enabled by default, or explicitly disabled
  508. // Or TLS is disabled by default... in any of these cases, we can just take the default value as to how to proceed
  509. return DefaultTLSValue
  510. }
  511. if !*c.TLS {
  512. // TLS is explicitly disabled, which is supported
  513. return true
  514. }
  515. if c.TLSVerify == nil {
  516. // this actually shouldn't happen since we set TLSVerify on the config object anyway
  517. // But in case it does get here, be cautious and assume this is not supported.
  518. return false
  519. }
  520. // Either TLSVerify is explicitly enabled or disabled, both cases are supported
  521. return true
  522. }
  523. func loadListeners(cli *DaemonCli, serverConfig *apiserver.Config) ([]string, error) {
  524. var hosts []string
  525. seen := make(map[string]struct{}, len(cli.Config.Hosts))
  526. useTLS := DefaultTLSValue
  527. if cli.Config.TLS != nil {
  528. useTLS = *cli.Config.TLS
  529. }
  530. for i := 0; i < len(cli.Config.Hosts); i++ {
  531. var err error
  532. if cli.Config.Hosts[i], err = dopts.ParseHost(useTLS, honorXDG, cli.Config.Hosts[i]); err != nil {
  533. return nil, errors.Wrapf(err, "error parsing -H %s", cli.Config.Hosts[i])
  534. }
  535. if _, ok := seen[cli.Config.Hosts[i]]; ok {
  536. continue
  537. }
  538. seen[cli.Config.Hosts[i]] = struct{}{}
  539. protoAddr := cli.Config.Hosts[i]
  540. protoAddrParts := strings.SplitN(protoAddr, "://", 2)
  541. if len(protoAddrParts) != 2 {
  542. return nil, fmt.Errorf("bad format %s, expected PROTO://ADDR", protoAddr)
  543. }
  544. proto := protoAddrParts[0]
  545. addr := protoAddrParts[1]
  546. // It's a bad idea to bind to TCP without tlsverify.
  547. authEnabled := serverConfig.TLSConfig != nil && serverConfig.TLSConfig.ClientAuth == tls.RequireAndVerifyClientCert
  548. if proto == "tcp" && !authEnabled {
  549. logrus.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.")
  550. logrus.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!")
  551. time.Sleep(time.Second)
  552. // If TLSVerify is explicitly set to false we'll take that as "Please let me shoot myself in the foot"
  553. // 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
  554. if !checkTLSAuthOK(cli.Config) {
  555. ipAddr, _, err := net.SplitHostPort(addr)
  556. if err != nil {
  557. return nil, errors.Wrap(err, "error parsing tcp address")
  558. }
  559. // shortcut all this extra stuff for literal "localhost"
  560. // -H supports specifying hostnames, since we want to bypass this on loopback interfaces we'll look it up here.
  561. if ipAddr != "localhost" {
  562. ip := net.ParseIP(ipAddr)
  563. if ip == nil {
  564. ipA, err := net.ResolveIPAddr("ip", ipAddr)
  565. if err != nil {
  566. logrus.WithError(err).WithField("host", ipAddr).Error("Error looking up specified host address")
  567. }
  568. if ipA != nil {
  569. ip = ipA.IP
  570. }
  571. }
  572. if ip == nil || !ip.IsLoopback() {
  573. logrus.WithField("host", protoAddr).Warn("Binding to an IP address without --tlsverify is deprecated. Startup is intentionally being slowed down to show this message")
  574. logrus.WithField("host", protoAddr).Warn("Please consider generating tls certificates with client validation to prevent exposing unauthenticated root access to your network")
  575. logrus.WithField("host", protoAddr).Warnf("You can override this by explicitly specifying '--%s=false' or '--%s=false'", FlagTLS, FlagTLSVerify)
  576. logrus.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")
  577. time.Sleep(15 * time.Second)
  578. }
  579. }
  580. }
  581. }
  582. ls, err := listeners.Init(proto, addr, serverConfig.SocketGroup, serverConfig.TLSConfig)
  583. if err != nil {
  584. return nil, err
  585. }
  586. // If we're binding to a TCP port, make sure that a container doesn't try to use it.
  587. if proto == "tcp" {
  588. if err := allocateDaemonPort(addr); err != nil {
  589. return nil, err
  590. }
  591. }
  592. logrus.Debugf("Listener created for HTTP on %s (%s)", proto, addr)
  593. hosts = append(hosts, protoAddrParts[1])
  594. cli.api.Accept(addr, ls...)
  595. }
  596. return hosts, nil
  597. }
  598. func createAndStartCluster(cli *DaemonCli, d *daemon.Daemon) (*cluster.Cluster, error) {
  599. name, _ := os.Hostname()
  600. // Use a buffered channel to pass changes from store watch API to daemon
  601. // A buffer allows store watch API and daemon processing to not wait for each other
  602. watchStream := make(chan *swarmapi.WatchMessage, 32)
  603. c, err := cluster.New(cluster.Config{
  604. Root: cli.Config.Root,
  605. Name: name,
  606. Backend: d,
  607. VolumeBackend: d.VolumesService(),
  608. ImageBackend: d.ImageService(),
  609. PluginBackend: d.PluginManager(),
  610. NetworkSubnetsProvider: d,
  611. DefaultAdvertiseAddr: cli.Config.SwarmDefaultAdvertiseAddr,
  612. RaftHeartbeatTick: cli.Config.SwarmRaftHeartbeatTick,
  613. RaftElectionTick: cli.Config.SwarmRaftElectionTick,
  614. RuntimeRoot: cli.getSwarmRunRoot(),
  615. WatchStream: watchStream,
  616. })
  617. if err != nil {
  618. return nil, err
  619. }
  620. d.SetCluster(c)
  621. err = c.Start()
  622. return c, err
  623. }
  624. // validates that the plugins requested with the --authorization-plugin flag are valid AuthzDriver
  625. // plugins present on the host and available to the daemon
  626. func validateAuthzPlugins(requestedPlugins []string, pg plugingetter.PluginGetter) error {
  627. for _, reqPlugin := range requestedPlugins {
  628. if _, err := pg.Get(reqPlugin, authorization.AuthZApiImplements, plugingetter.Lookup); err != nil {
  629. return err
  630. }
  631. }
  632. return nil
  633. }
  634. func systemContainerdRunning(honorXDG bool) (string, bool, error) {
  635. addr := containerddefaults.DefaultAddress
  636. if honorXDG {
  637. runtimeDir, err := homedir.GetRuntimeDir()
  638. if err != nil {
  639. return "", false, err
  640. }
  641. addr = filepath.Join(runtimeDir, "containerd", "containerd.sock")
  642. }
  643. _, err := os.Lstat(addr)
  644. return addr, err == nil, nil
  645. }
  646. // configureDaemonLogs sets the logrus logging level and formatting
  647. func configureDaemonLogs(conf *config.Config) error {
  648. if conf.LogLevel != "" {
  649. lvl, err := logrus.ParseLevel(conf.LogLevel)
  650. if err != nil {
  651. return fmt.Errorf("unable to parse logging level: %s", conf.LogLevel)
  652. }
  653. logrus.SetLevel(lvl)
  654. } else {
  655. logrus.SetLevel(logrus.InfoLevel)
  656. }
  657. logrus.SetFormatter(&logrus.TextFormatter{
  658. TimestampFormat: jsonmessage.RFC3339NanoFixed,
  659. DisableColors: conf.RawLogs,
  660. FullTimestamp: true,
  661. })
  662. return nil
  663. }