daemon.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. package main
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "fmt"
  6. "os"
  7. "path/filepath"
  8. "runtime"
  9. "strings"
  10. "time"
  11. "github.com/docker/distribution/uuid"
  12. "github.com/docker/docker/api"
  13. apiserver "github.com/docker/docker/api/server"
  14. buildbackend "github.com/docker/docker/api/server/backend/build"
  15. "github.com/docker/docker/api/server/middleware"
  16. "github.com/docker/docker/api/server/router"
  17. "github.com/docker/docker/api/server/router/build"
  18. checkpointrouter "github.com/docker/docker/api/server/router/checkpoint"
  19. "github.com/docker/docker/api/server/router/container"
  20. distributionrouter "github.com/docker/docker/api/server/router/distribution"
  21. "github.com/docker/docker/api/server/router/image"
  22. "github.com/docker/docker/api/server/router/network"
  23. pluginrouter "github.com/docker/docker/api/server/router/plugin"
  24. sessionrouter "github.com/docker/docker/api/server/router/session"
  25. swarmrouter "github.com/docker/docker/api/server/router/swarm"
  26. systemrouter "github.com/docker/docker/api/server/router/system"
  27. "github.com/docker/docker/api/server/router/volume"
  28. buildkit "github.com/docker/docker/builder/builder-next"
  29. "github.com/docker/docker/builder/dockerfile"
  30. "github.com/docker/docker/builder/fscache"
  31. "github.com/docker/docker/cli/debug"
  32. "github.com/docker/docker/daemon"
  33. "github.com/docker/docker/daemon/cluster"
  34. "github.com/docker/docker/daemon/config"
  35. "github.com/docker/docker/daemon/listeners"
  36. "github.com/docker/docker/dockerversion"
  37. "github.com/docker/docker/libcontainerd/supervisor"
  38. dopts "github.com/docker/docker/opts"
  39. "github.com/docker/docker/pkg/authorization"
  40. "github.com/docker/docker/pkg/jsonmessage"
  41. "github.com/docker/docker/pkg/pidfile"
  42. "github.com/docker/docker/pkg/plugingetter"
  43. "github.com/docker/docker/pkg/signal"
  44. "github.com/docker/docker/pkg/system"
  45. "github.com/docker/docker/plugin"
  46. "github.com/docker/docker/runconfig"
  47. "github.com/docker/go-connections/tlsconfig"
  48. swarmapi "github.com/docker/swarmkit/api"
  49. "github.com/moby/buildkit/session"
  50. "github.com/pkg/errors"
  51. "github.com/sirupsen/logrus"
  52. "github.com/spf13/pflag"
  53. )
  54. // DaemonCli represents the daemon CLI.
  55. type DaemonCli struct {
  56. *config.Config
  57. configFile *string
  58. flags *pflag.FlagSet
  59. api *apiserver.Server
  60. d *daemon.Daemon
  61. authzMiddleware *authorization.Middleware // authzMiddleware enables to dynamically reload the authorization plugins
  62. }
  63. // NewDaemonCli returns a daemon CLI
  64. func NewDaemonCli() *DaemonCli {
  65. return &DaemonCli{}
  66. }
  67. func (cli *DaemonCli) start(opts *daemonOptions) (err error) {
  68. stopc := make(chan bool)
  69. defer close(stopc)
  70. // warn from uuid package when running the daemon
  71. uuid.Loggerf = logrus.Warnf
  72. opts.SetDefaultOptions(opts.flags)
  73. if cli.Config, err = loadDaemonCliConfig(opts); err != nil {
  74. return err
  75. }
  76. cli.configFile = &opts.configFile
  77. cli.flags = opts.flags
  78. if cli.Config.Debug {
  79. debug.Enable()
  80. }
  81. if cli.Config.Experimental {
  82. logrus.Warn("Running experimental build")
  83. }
  84. logrus.SetFormatter(&logrus.TextFormatter{
  85. TimestampFormat: jsonmessage.RFC3339NanoFixed,
  86. DisableColors: cli.Config.RawLogs,
  87. FullTimestamp: true,
  88. })
  89. system.InitLCOW(cli.Config.Experimental)
  90. if err := setDefaultUmask(); err != nil {
  91. return fmt.Errorf("Failed to set umask: %v", err)
  92. }
  93. // Create the daemon root before we create ANY other files (PID, or migrate keys)
  94. // to ensure the appropriate ACL is set (particularly relevant on Windows)
  95. if err := daemon.CreateDaemonRoot(cli.Config); err != nil {
  96. return err
  97. }
  98. if err := system.MkdirAll(cli.Config.ExecRoot, 0700, ""); err != nil {
  99. return err
  100. }
  101. if cli.Pidfile != "" {
  102. pf, err := pidfile.New(cli.Pidfile)
  103. if err != nil {
  104. return fmt.Errorf("Error starting daemon: %v", err)
  105. }
  106. defer func() {
  107. if err := pf.Remove(); err != nil {
  108. logrus.Error(err)
  109. }
  110. }()
  111. }
  112. serverConfig, err := newAPIServerConfig(cli)
  113. if err != nil {
  114. return fmt.Errorf("Failed to create API server: %v", err)
  115. }
  116. cli.api = apiserver.New(serverConfig)
  117. hosts, err := loadListeners(cli, serverConfig)
  118. if err != nil {
  119. return fmt.Errorf("Failed to load listeners: %v", err)
  120. }
  121. ctx, cancel := context.WithCancel(context.Background())
  122. if cli.Config.ContainerdAddr == "" && runtime.GOOS != "windows" {
  123. opts, err := cli.getContainerdDaemonOpts()
  124. if err != nil {
  125. cancel()
  126. return fmt.Errorf("Failed to generate containerd options: %v", err)
  127. }
  128. r, err := supervisor.Start(ctx, filepath.Join(cli.Config.Root, "containerd"), filepath.Join(cli.Config.ExecRoot, "containerd"), opts...)
  129. if err != nil {
  130. cancel()
  131. return fmt.Errorf("Failed to start containerd: %v", err)
  132. }
  133. cli.Config.ContainerdAddr = r.Address()
  134. // Try to wait for containerd to shutdown
  135. defer r.WaitTimeout(10 * time.Second)
  136. }
  137. defer cancel()
  138. signal.Trap(func() {
  139. cli.stop()
  140. <-stopc // wait for daemonCli.start() to return
  141. }, logrus.StandardLogger())
  142. // Notify that the API is active, but before daemon is set up.
  143. preNotifySystem()
  144. pluginStore := plugin.NewStore()
  145. if err := cli.initMiddlewares(cli.api, serverConfig, pluginStore); err != nil {
  146. logrus.Fatalf("Error creating middlewares: %v", err)
  147. }
  148. d, err := daemon.NewDaemon(ctx, cli.Config, pluginStore)
  149. if err != nil {
  150. return fmt.Errorf("Error starting daemon: %v", err)
  151. }
  152. d.StoreHosts(hosts)
  153. // validate after NewDaemon has restored enabled plugins. Dont change order.
  154. if err := validateAuthzPlugins(cli.Config.AuthorizationPlugins, pluginStore); err != nil {
  155. return fmt.Errorf("Error validating authorization plugin: %v", err)
  156. }
  157. // TODO: move into startMetricsServer()
  158. if cli.Config.MetricsAddress != "" {
  159. if !d.HasExperimental() {
  160. return fmt.Errorf("metrics-addr is only supported when experimental is enabled")
  161. }
  162. if err := startMetricsServer(cli.Config.MetricsAddress); err != nil {
  163. return err
  164. }
  165. }
  166. c, err := createAndStartCluster(cli, d)
  167. if err != nil {
  168. logrus.Fatalf("Error starting cluster component: %v", err)
  169. }
  170. // Restart all autostart containers which has a swarm endpoint
  171. // and is not yet running now that we have successfully
  172. // initialized the cluster.
  173. d.RestartSwarmContainers()
  174. logrus.Info("Daemon has completed initialization")
  175. cli.d = d
  176. routerOptions, err := newRouterOptions(cli.Config, d)
  177. if err != nil {
  178. return err
  179. }
  180. routerOptions.api = cli.api
  181. routerOptions.cluster = c
  182. initRouter(routerOptions)
  183. go d.ProcessClusterNotifications(ctx, c.GetWatchStream())
  184. cli.setupConfigReloadTrap()
  185. // The serve API routine never exits unless an error occurs
  186. // We need to start it as a goroutine and wait on it so
  187. // daemon doesn't exit
  188. serveAPIWait := make(chan error)
  189. go cli.api.Wait(serveAPIWait)
  190. // after the daemon is done setting up we can notify systemd api
  191. notifySystem()
  192. // Daemon is fully initialized and handling API traffic
  193. // Wait for serve API to complete
  194. errAPI := <-serveAPIWait
  195. c.Cleanup()
  196. shutdownDaemon(d)
  197. // Stop notification processing and any background processes
  198. cancel()
  199. if errAPI != nil {
  200. return fmt.Errorf("Shutting down due to ServeAPI error: %v", errAPI)
  201. }
  202. return nil
  203. }
  204. type routerOptions struct {
  205. sessionManager *session.Manager
  206. buildBackend *buildbackend.Backend
  207. buildCache *fscache.FSCache // legacy
  208. features *map[string]bool
  209. buildkit *buildkit.Builder
  210. daemon *daemon.Daemon
  211. api *apiserver.Server
  212. cluster *cluster.Cluster
  213. }
  214. func newRouterOptions(config *config.Config, d *daemon.Daemon) (routerOptions, error) {
  215. opts := routerOptions{}
  216. sm, err := session.NewManager()
  217. if err != nil {
  218. return opts, errors.Wrap(err, "failed to create sessionmanager")
  219. }
  220. builderStateDir := filepath.Join(config.Root, "builder")
  221. buildCache, err := fscache.NewFSCache(fscache.Opt{
  222. Backend: fscache.NewNaiveCacheBackend(builderStateDir),
  223. Root: builderStateDir,
  224. GCPolicy: fscache.GCPolicy{ // TODO: expose this in config
  225. MaxSize: 1024 * 1024 * 512, // 512MB
  226. MaxKeepDuration: 7 * 24 * time.Hour, // 1 week
  227. },
  228. })
  229. if err != nil {
  230. return opts, errors.Wrap(err, "failed to create fscache")
  231. }
  232. manager, err := dockerfile.NewBuildManager(d.BuilderBackend(), sm, buildCache, d.IdentityMapping())
  233. if err != nil {
  234. return opts, err
  235. }
  236. cgroupParent := "docker"
  237. useSystemd := daemon.UsingSystemd(config)
  238. if useSystemd {
  239. cgroupParent = "system.slice"
  240. }
  241. if config.CgroupParent != "" {
  242. cgroupParent = config.CgroupParent
  243. }
  244. if useSystemd {
  245. cgroupParent = cgroupParent + ":" + "docker" + ":"
  246. }
  247. bk, err := buildkit.New(buildkit.Opt{
  248. SessionManager: sm,
  249. Root: filepath.Join(config.Root, "buildkit"),
  250. Dist: d.DistributionServices(),
  251. NetworkController: d.NetworkController(),
  252. DefaultCgroupParent: cgroupParent,
  253. })
  254. if err != nil {
  255. return opts, err
  256. }
  257. bb, err := buildbackend.NewBackend(d.ImageService(), manager, buildCache, bk)
  258. if err != nil {
  259. return opts, errors.Wrap(err, "failed to create buildmanager")
  260. }
  261. return routerOptions{
  262. sessionManager: sm,
  263. buildBackend: bb,
  264. buildCache: buildCache,
  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. // The namespaces com.docker.*, io.docker.*, org.dockerproject.* have been documented
  279. // to be reserved for Docker's internal use, but this was never enforced. Allowing
  280. // configured labels to use these namespaces are deprecated for 18.05.
  281. //
  282. // The following will check the usage of such labels, and report a warning for deprecation.
  283. //
  284. // TODO: At the next stable release, the validation should be folded into the other
  285. // configuration validation functions and an error will be returned instead, and this
  286. // block should be deleted.
  287. if err := config.ValidateReservedNamespaceLabels(c.Labels); err != nil {
  288. logrus.Warnf("Configured labels using reserved namespaces is deprecated: %s", err)
  289. }
  290. if err := cli.d.Reload(c); err != nil {
  291. logrus.Errorf("Error reconfiguring the daemon: %v", err)
  292. return
  293. }
  294. if c.IsValueSet("debug") {
  295. debugEnabled := debug.IsEnabled()
  296. switch {
  297. case debugEnabled && !c.Debug: // disable debug
  298. debug.Disable()
  299. case c.Debug && !debugEnabled: // enable debug
  300. debug.Enable()
  301. }
  302. }
  303. }
  304. if err := config.Reload(*cli.configFile, cli.flags, reload); err != nil {
  305. logrus.Error(err)
  306. }
  307. }
  308. func (cli *DaemonCli) stop() {
  309. cli.api.Close()
  310. }
  311. // shutdownDaemon just wraps daemon.Shutdown() to handle a timeout in case
  312. // d.Shutdown() is waiting too long to kill container or worst it's
  313. // blocked there
  314. func shutdownDaemon(d *daemon.Daemon) {
  315. shutdownTimeout := d.ShutdownTimeout()
  316. ch := make(chan struct{})
  317. go func() {
  318. d.Shutdown()
  319. close(ch)
  320. }()
  321. if shutdownTimeout < 0 {
  322. <-ch
  323. logrus.Debug("Clean shutdown succeeded")
  324. return
  325. }
  326. select {
  327. case <-ch:
  328. logrus.Debug("Clean shutdown succeeded")
  329. case <-time.After(time.Duration(shutdownTimeout) * time.Second):
  330. logrus.Error("Force shutdown daemon")
  331. }
  332. }
  333. func loadDaemonCliConfig(opts *daemonOptions) (*config.Config, error) {
  334. conf := opts.daemonConfig
  335. flags := opts.flags
  336. conf.Debug = opts.Debug
  337. conf.Hosts = opts.Hosts
  338. conf.LogLevel = opts.LogLevel
  339. conf.TLS = opts.TLS
  340. conf.TLSVerify = opts.TLSVerify
  341. conf.CommonTLSOptions = config.CommonTLSOptions{}
  342. if opts.TLSOptions != nil {
  343. conf.CommonTLSOptions.CAFile = opts.TLSOptions.CAFile
  344. conf.CommonTLSOptions.CertFile = opts.TLSOptions.CertFile
  345. conf.CommonTLSOptions.KeyFile = opts.TLSOptions.KeyFile
  346. }
  347. if conf.TrustKeyPath == "" {
  348. conf.TrustKeyPath = filepath.Join(
  349. getDaemonConfDir(conf.Root),
  350. defaultTrustKeyFile)
  351. }
  352. if flags.Changed("graph") && flags.Changed("data-root") {
  353. return nil, fmt.Errorf(`cannot specify both "--graph" and "--data-root" option`)
  354. }
  355. if opts.configFile != "" {
  356. c, err := config.MergeDaemonConfigurations(conf, flags, opts.configFile)
  357. if err != nil {
  358. if flags.Changed("config-file") || !os.IsNotExist(err) {
  359. return nil, fmt.Errorf("unable to configure the Docker daemon with file %s: %v", opts.configFile, err)
  360. }
  361. }
  362. // the merged configuration can be nil if the config file didn't exist.
  363. // leave the current configuration as it is if when that happens.
  364. if c != nil {
  365. conf = c
  366. }
  367. }
  368. if err := config.Validate(conf); err != nil {
  369. return nil, err
  370. }
  371. if runtime.GOOS != "windows" {
  372. if flags.Changed("disable-legacy-registry") {
  373. // TODO: Remove this error after 3 release cycles (18.03)
  374. return nil, errors.New("ERROR: The '--disable-legacy-registry' flag has been removed. Interacting with legacy (v1) registries is no longer supported")
  375. }
  376. if !conf.V2Only {
  377. // TODO: Remove this error after 3 release cycles (18.03)
  378. return nil, errors.New("ERROR: The 'disable-legacy-registry' configuration option has been removed. Interacting with legacy (v1) registries is no longer supported")
  379. }
  380. }
  381. if flags.Changed("graph") {
  382. logrus.Warnf(`The "-g / --graph" flag is deprecated. Please use "--data-root" instead`)
  383. }
  384. // Check if duplicate label-keys with different values are found
  385. newLabels, err := config.GetConflictFreeLabels(conf.Labels)
  386. if err != nil {
  387. return nil, err
  388. }
  389. // The namespaces com.docker.*, io.docker.*, org.dockerproject.* have been documented
  390. // to be reserved for Docker's internal use, but this was never enforced. Allowing
  391. // configured labels to use these namespaces are deprecated for 18.05.
  392. //
  393. // The following will check the usage of such labels, and report a warning for deprecation.
  394. //
  395. // TODO: At the next stable release, the validation should be folded into the other
  396. // configuration validation functions and an error will be returned instead, and this
  397. // block should be deleted.
  398. if err := config.ValidateReservedNamespaceLabels(newLabels); err != nil {
  399. logrus.Warnf("Configured labels using reserved namespaces is deprecated: %s", err)
  400. }
  401. conf.Labels = newLabels
  402. // Regardless of whether the user sets it to true or false, if they
  403. // specify TLSVerify at all then we need to turn on TLS
  404. if conf.IsValueSet(FlagTLSVerify) {
  405. conf.TLS = true
  406. }
  407. // ensure that the log level is the one set after merging configurations
  408. setLogLevel(conf.LogLevel)
  409. return conf, nil
  410. }
  411. func initRouter(opts routerOptions) {
  412. decoder := runconfig.ContainerDecoder{}
  413. routers := []router.Router{
  414. // we need to add the checkpoint router before the container router or the DELETE gets masked
  415. checkpointrouter.NewRouter(opts.daemon, decoder),
  416. container.NewRouter(opts.daemon, decoder),
  417. image.NewRouter(opts.daemon.ImageService()),
  418. systemrouter.NewRouter(opts.daemon, opts.cluster, opts.buildCache, opts.buildkit, opts.features),
  419. volume.NewRouter(opts.daemon.VolumesService()),
  420. build.NewRouter(opts.buildBackend, opts.daemon, opts.features),
  421. sessionrouter.NewRouter(opts.sessionManager),
  422. swarmrouter.NewRouter(opts.cluster),
  423. pluginrouter.NewRouter(opts.daemon.PluginManager()),
  424. distributionrouter.NewRouter(opts.daemon.ImageService()),
  425. }
  426. if opts.daemon.NetworkControllerEnabled() {
  427. routers = append(routers, network.NewRouter(opts.daemon, opts.cluster))
  428. }
  429. if opts.daemon.HasExperimental() {
  430. for _, r := range routers {
  431. for _, route := range r.Routes() {
  432. if experimental, ok := route.(router.ExperimentalRoute); ok {
  433. experimental.Enable()
  434. }
  435. }
  436. }
  437. }
  438. opts.api.InitRouter(routers...)
  439. }
  440. // TODO: remove this from cli and return the authzMiddleware
  441. func (cli *DaemonCli) initMiddlewares(s *apiserver.Server, cfg *apiserver.Config, pluginStore plugingetter.PluginGetter) error {
  442. v := cfg.Version
  443. exp := middleware.NewExperimentalMiddleware(cli.Config.Experimental)
  444. s.UseMiddleware(exp)
  445. vm := middleware.NewVersionMiddleware(v, api.DefaultVersion, api.MinVersion)
  446. s.UseMiddleware(vm)
  447. if cfg.CorsHeaders != "" {
  448. c := middleware.NewCORSMiddleware(cfg.CorsHeaders)
  449. s.UseMiddleware(c)
  450. }
  451. cli.authzMiddleware = authorization.NewMiddleware(cli.Config.AuthorizationPlugins, pluginStore)
  452. cli.Config.AuthzMiddleware = cli.authzMiddleware
  453. s.UseMiddleware(cli.authzMiddleware)
  454. return nil
  455. }
  456. func (cli *DaemonCli) getContainerdDaemonOpts() ([]supervisor.DaemonOpt, error) {
  457. opts, err := cli.getPlatformContainerdDaemonOpts()
  458. if err != nil {
  459. return nil, err
  460. }
  461. if cli.Config.Debug {
  462. opts = append(opts, supervisor.WithLogLevel("debug"))
  463. } else if cli.Config.LogLevel != "" {
  464. opts = append(opts, supervisor.WithLogLevel(cli.Config.LogLevel))
  465. }
  466. if !cli.Config.CriContainerd {
  467. opts = append(opts, supervisor.WithPlugin("cri", nil))
  468. }
  469. return opts, nil
  470. }
  471. func newAPIServerConfig(cli *DaemonCli) (*apiserver.Config, error) {
  472. serverConfig := &apiserver.Config{
  473. Logging: true,
  474. SocketGroup: cli.Config.SocketGroup,
  475. Version: dockerversion.Version,
  476. CorsHeaders: cli.Config.CorsHeaders,
  477. }
  478. if cli.Config.TLS {
  479. tlsOptions := tlsconfig.Options{
  480. CAFile: cli.Config.CommonTLSOptions.CAFile,
  481. CertFile: cli.Config.CommonTLSOptions.CertFile,
  482. KeyFile: cli.Config.CommonTLSOptions.KeyFile,
  483. ExclusiveRootPools: true,
  484. }
  485. if cli.Config.TLSVerify {
  486. // server requires and verifies client's certificate
  487. tlsOptions.ClientAuth = tls.RequireAndVerifyClientCert
  488. }
  489. tlsConfig, err := tlsconfig.Server(tlsOptions)
  490. if err != nil {
  491. return nil, err
  492. }
  493. serverConfig.TLSConfig = tlsConfig
  494. }
  495. if len(cli.Config.Hosts) == 0 {
  496. cli.Config.Hosts = make([]string, 1)
  497. }
  498. return serverConfig, nil
  499. }
  500. func loadListeners(cli *DaemonCli, serverConfig *apiserver.Config) ([]string, error) {
  501. var hosts []string
  502. for i := 0; i < len(cli.Config.Hosts); i++ {
  503. var err error
  504. if cli.Config.Hosts[i], err = dopts.ParseHost(cli.Config.TLS, cli.Config.Hosts[i]); err != nil {
  505. return nil, fmt.Errorf("error parsing -H %s : %v", cli.Config.Hosts[i], err)
  506. }
  507. protoAddr := cli.Config.Hosts[i]
  508. protoAddrParts := strings.SplitN(protoAddr, "://", 2)
  509. if len(protoAddrParts) != 2 {
  510. return nil, fmt.Errorf("bad format %s, expected PROTO://ADDR", protoAddr)
  511. }
  512. proto := protoAddrParts[0]
  513. addr := protoAddrParts[1]
  514. // It's a bad idea to bind to TCP without tlsverify.
  515. if proto == "tcp" && (serverConfig.TLSConfig == nil || serverConfig.TLSConfig.ClientAuth != tls.RequireAndVerifyClientCert) {
  516. logrus.Warn("[!] DON'T BIND ON ANY IP ADDRESS WITHOUT setting --tlsverify IF YOU DON'T KNOW WHAT YOU'RE DOING [!]")
  517. }
  518. ls, err := listeners.Init(proto, addr, serverConfig.SocketGroup, serverConfig.TLSConfig)
  519. if err != nil {
  520. return nil, err
  521. }
  522. ls = wrapListeners(proto, ls)
  523. // If we're binding to a TCP port, make sure that a container doesn't try to use it.
  524. if proto == "tcp" {
  525. if err := allocateDaemonPort(addr); err != nil {
  526. return nil, err
  527. }
  528. }
  529. logrus.Debugf("Listener created for HTTP on %s (%s)", proto, addr)
  530. hosts = append(hosts, protoAddrParts[1])
  531. cli.api.Accept(addr, ls...)
  532. }
  533. return hosts, nil
  534. }
  535. func createAndStartCluster(cli *DaemonCli, d *daemon.Daemon) (*cluster.Cluster, error) {
  536. name, _ := os.Hostname()
  537. // Use a buffered channel to pass changes from store watch API to daemon
  538. // A buffer allows store watch API and daemon processing to not wait for each other
  539. watchStream := make(chan *swarmapi.WatchMessage, 32)
  540. c, err := cluster.New(cluster.Config{
  541. Root: cli.Config.Root,
  542. Name: name,
  543. Backend: d,
  544. VolumeBackend: d.VolumesService(),
  545. ImageBackend: d.ImageService(),
  546. PluginBackend: d.PluginManager(),
  547. NetworkSubnetsProvider: d,
  548. DefaultAdvertiseAddr: cli.Config.SwarmDefaultAdvertiseAddr,
  549. RaftHeartbeatTick: cli.Config.SwarmRaftHeartbeatTick,
  550. RaftElectionTick: cli.Config.SwarmRaftElectionTick,
  551. RuntimeRoot: cli.getSwarmRunRoot(),
  552. WatchStream: watchStream,
  553. })
  554. if err != nil {
  555. return nil, err
  556. }
  557. d.SetCluster(c)
  558. err = c.Start()
  559. return c, err
  560. }
  561. // validates that the plugins requested with the --authorization-plugin flag are valid AuthzDriver
  562. // plugins present on the host and available to the daemon
  563. func validateAuthzPlugins(requestedPlugins []string, pg plugingetter.PluginGetter) error {
  564. for _, reqPlugin := range requestedPlugins {
  565. if _, err := pg.Get(reqPlugin, authorization.AuthZApiImplements, plugingetter.Lookup); err != nil {
  566. return err
  567. }
  568. }
  569. return nil
  570. }