daemon.go 23 KB

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