daemon.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  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. buildkit *buildkit.Builder
  209. daemon *daemon.Daemon
  210. api *apiserver.Server
  211. cluster *cluster.Cluster
  212. }
  213. func newRouterOptions(config *config.Config, daemon *daemon.Daemon) (routerOptions, error) {
  214. opts := routerOptions{}
  215. sm, err := session.NewManager()
  216. if err != nil {
  217. return opts, errors.Wrap(err, "failed to create sessionmanager")
  218. }
  219. builderStateDir := filepath.Join(config.Root, "builder")
  220. buildCache, err := fscache.NewFSCache(fscache.Opt{
  221. Backend: fscache.NewNaiveCacheBackend(builderStateDir),
  222. Root: builderStateDir,
  223. GCPolicy: fscache.GCPolicy{ // TODO: expose this in config
  224. MaxSize: 1024 * 1024 * 512, // 512MB
  225. MaxKeepDuration: 7 * 24 * time.Hour, // 1 week
  226. },
  227. })
  228. if err != nil {
  229. return opts, errors.Wrap(err, "failed to create fscache")
  230. }
  231. manager, err := dockerfile.NewBuildManager(daemon.BuilderBackend(), sm, buildCache, daemon.IdentityMapping())
  232. if err != nil {
  233. return opts, err
  234. }
  235. buildkit, err := buildkit.New(buildkit.Opt{
  236. SessionManager: sm,
  237. Root: filepath.Join(config.Root, "buildkit"),
  238. Dist: daemon.DistributionServices(),
  239. })
  240. if err != nil {
  241. return opts, err
  242. }
  243. bb, err := buildbackend.NewBackend(daemon.ImageService(), manager, buildCache, buildkit)
  244. if err != nil {
  245. return opts, errors.Wrap(err, "failed to create buildmanager")
  246. }
  247. return routerOptions{
  248. sessionManager: sm,
  249. buildBackend: bb,
  250. buildCache: buildCache,
  251. buildkit: buildkit,
  252. daemon: daemon,
  253. }, nil
  254. }
  255. func (cli *DaemonCli) reloadConfig() {
  256. reload := func(c *config.Config) {
  257. // Revalidate and reload the authorization plugins
  258. if err := validateAuthzPlugins(c.AuthorizationPlugins, cli.d.PluginStore); err != nil {
  259. logrus.Fatalf("Error validating authorization plugin: %v", err)
  260. return
  261. }
  262. cli.authzMiddleware.SetPlugins(c.AuthorizationPlugins)
  263. // The namespaces com.docker.*, io.docker.*, org.dockerproject.* have been documented
  264. // to be reserved for Docker's internal use, but this was never enforced. Allowing
  265. // configured labels to use these namespaces are deprecated for 18.05.
  266. //
  267. // The following will check the usage of such labels, and report a warning for deprecation.
  268. //
  269. // TODO: At the next stable release, the validation should be folded into the other
  270. // configuration validation functions and an error will be returned instead, and this
  271. // block should be deleted.
  272. if err := config.ValidateReservedNamespaceLabels(c.Labels); err != nil {
  273. logrus.Warnf("Configured labels using reserved namespaces is deprecated: %s", err)
  274. }
  275. if err := cli.d.Reload(c); err != nil {
  276. logrus.Errorf("Error reconfiguring the daemon: %v", err)
  277. return
  278. }
  279. if c.IsValueSet("debug") {
  280. debugEnabled := debug.IsEnabled()
  281. switch {
  282. case debugEnabled && !c.Debug: // disable debug
  283. debug.Disable()
  284. case c.Debug && !debugEnabled: // enable debug
  285. debug.Enable()
  286. }
  287. }
  288. }
  289. if err := config.Reload(*cli.configFile, cli.flags, reload); err != nil {
  290. logrus.Error(err)
  291. }
  292. }
  293. func (cli *DaemonCli) stop() {
  294. cli.api.Close()
  295. }
  296. // shutdownDaemon just wraps daemon.Shutdown() to handle a timeout in case
  297. // d.Shutdown() is waiting too long to kill container or worst it's
  298. // blocked there
  299. func shutdownDaemon(d *daemon.Daemon) {
  300. shutdownTimeout := d.ShutdownTimeout()
  301. ch := make(chan struct{})
  302. go func() {
  303. d.Shutdown()
  304. close(ch)
  305. }()
  306. if shutdownTimeout < 0 {
  307. <-ch
  308. logrus.Debug("Clean shutdown succeeded")
  309. return
  310. }
  311. select {
  312. case <-ch:
  313. logrus.Debug("Clean shutdown succeeded")
  314. case <-time.After(time.Duration(shutdownTimeout) * time.Second):
  315. logrus.Error("Force shutdown daemon")
  316. }
  317. }
  318. func loadDaemonCliConfig(opts *daemonOptions) (*config.Config, error) {
  319. conf := opts.daemonConfig
  320. flags := opts.flags
  321. conf.Debug = opts.Debug
  322. conf.Hosts = opts.Hosts
  323. conf.LogLevel = opts.LogLevel
  324. conf.TLS = opts.TLS
  325. conf.TLSVerify = opts.TLSVerify
  326. conf.CommonTLSOptions = config.CommonTLSOptions{}
  327. if opts.TLSOptions != nil {
  328. conf.CommonTLSOptions.CAFile = opts.TLSOptions.CAFile
  329. conf.CommonTLSOptions.CertFile = opts.TLSOptions.CertFile
  330. conf.CommonTLSOptions.KeyFile = opts.TLSOptions.KeyFile
  331. }
  332. if conf.TrustKeyPath == "" {
  333. conf.TrustKeyPath = filepath.Join(
  334. getDaemonConfDir(conf.Root),
  335. defaultTrustKeyFile)
  336. }
  337. if flags.Changed("graph") && flags.Changed("data-root") {
  338. return nil, fmt.Errorf(`cannot specify both "--graph" and "--data-root" option`)
  339. }
  340. if opts.configFile != "" {
  341. c, err := config.MergeDaemonConfigurations(conf, flags, opts.configFile)
  342. if err != nil {
  343. if flags.Changed("config-file") || !os.IsNotExist(err) {
  344. return nil, fmt.Errorf("unable to configure the Docker daemon with file %s: %v", opts.configFile, err)
  345. }
  346. }
  347. // the merged configuration can be nil if the config file didn't exist.
  348. // leave the current configuration as it is if when that happens.
  349. if c != nil {
  350. conf = c
  351. }
  352. }
  353. if err := config.Validate(conf); err != nil {
  354. return nil, err
  355. }
  356. if runtime.GOOS != "windows" {
  357. if flags.Changed("disable-legacy-registry") {
  358. // TODO: Remove this error after 3 release cycles (18.03)
  359. return nil, errors.New("ERROR: The '--disable-legacy-registry' flag has been removed. Interacting with legacy (v1) registries is no longer supported")
  360. }
  361. if !conf.V2Only {
  362. // TODO: Remove this error after 3 release cycles (18.03)
  363. return nil, errors.New("ERROR: The 'disable-legacy-registry' configuration option has been removed. Interacting with legacy (v1) registries is no longer supported")
  364. }
  365. }
  366. if flags.Changed("graph") {
  367. logrus.Warnf(`The "-g / --graph" flag is deprecated. Please use "--data-root" instead`)
  368. }
  369. // Check if duplicate label-keys with different values are found
  370. newLabels, err := config.GetConflictFreeLabels(conf.Labels)
  371. if err != nil {
  372. return nil, err
  373. }
  374. // The namespaces com.docker.*, io.docker.*, org.dockerproject.* have been documented
  375. // to be reserved for Docker's internal use, but this was never enforced. Allowing
  376. // configured labels to use these namespaces are deprecated for 18.05.
  377. //
  378. // The following will check the usage of such labels, and report a warning for deprecation.
  379. //
  380. // TODO: At the next stable release, the validation should be folded into the other
  381. // configuration validation functions and an error will be returned instead, and this
  382. // block should be deleted.
  383. if err := config.ValidateReservedNamespaceLabels(newLabels); err != nil {
  384. logrus.Warnf("Configured labels using reserved namespaces is deprecated: %s", err)
  385. }
  386. conf.Labels = newLabels
  387. // Regardless of whether the user sets it to true or false, if they
  388. // specify TLSVerify at all then we need to turn on TLS
  389. if conf.IsValueSet(FlagTLSVerify) {
  390. conf.TLS = true
  391. }
  392. // ensure that the log level is the one set after merging configurations
  393. setLogLevel(conf.LogLevel)
  394. return conf, nil
  395. }
  396. func initRouter(opts routerOptions) {
  397. decoder := runconfig.ContainerDecoder{}
  398. routers := []router.Router{
  399. // we need to add the checkpoint router before the container router or the DELETE gets masked
  400. checkpointrouter.NewRouter(opts.daemon, decoder),
  401. container.NewRouter(opts.daemon, decoder),
  402. image.NewRouter(opts.daemon.ImageService()),
  403. systemrouter.NewRouter(opts.daemon, opts.cluster, opts.buildCache, opts.buildkit),
  404. volume.NewRouter(opts.daemon.VolumesService()),
  405. build.NewRouter(opts.buildBackend, opts.daemon),
  406. sessionrouter.NewRouter(opts.sessionManager),
  407. swarmrouter.NewRouter(opts.cluster),
  408. pluginrouter.NewRouter(opts.daemon.PluginManager()),
  409. distributionrouter.NewRouter(opts.daemon.ImageService()),
  410. }
  411. if opts.daemon.NetworkControllerEnabled() {
  412. routers = append(routers, network.NewRouter(opts.daemon, opts.cluster))
  413. }
  414. if opts.daemon.HasExperimental() {
  415. for _, r := range routers {
  416. for _, route := range r.Routes() {
  417. if experimental, ok := route.(router.ExperimentalRoute); ok {
  418. experimental.Enable()
  419. }
  420. }
  421. }
  422. }
  423. opts.api.InitRouter(routers...)
  424. }
  425. // TODO: remove this from cli and return the authzMiddleware
  426. func (cli *DaemonCli) initMiddlewares(s *apiserver.Server, cfg *apiserver.Config, pluginStore plugingetter.PluginGetter) error {
  427. v := cfg.Version
  428. exp := middleware.NewExperimentalMiddleware(cli.Config.Experimental)
  429. s.UseMiddleware(exp)
  430. vm := middleware.NewVersionMiddleware(v, api.DefaultVersion, api.MinVersion)
  431. s.UseMiddleware(vm)
  432. if cfg.CorsHeaders != "" {
  433. c := middleware.NewCORSMiddleware(cfg.CorsHeaders)
  434. s.UseMiddleware(c)
  435. }
  436. cli.authzMiddleware = authorization.NewMiddleware(cli.Config.AuthorizationPlugins, pluginStore)
  437. cli.Config.AuthzMiddleware = cli.authzMiddleware
  438. s.UseMiddleware(cli.authzMiddleware)
  439. return nil
  440. }
  441. func (cli *DaemonCli) getContainerdDaemonOpts() ([]supervisor.DaemonOpt, error) {
  442. opts, err := cli.getPlatformContainerdDaemonOpts()
  443. if err != nil {
  444. return nil, err
  445. }
  446. if cli.Config.Debug {
  447. opts = append(opts, supervisor.WithLogLevel("debug"))
  448. } else if cli.Config.LogLevel != "" {
  449. opts = append(opts, supervisor.WithLogLevel(cli.Config.LogLevel))
  450. }
  451. if !cli.Config.CriContainerd {
  452. opts = append(opts, supervisor.WithPlugin("cri", nil))
  453. }
  454. return opts, nil
  455. }
  456. func newAPIServerConfig(cli *DaemonCli) (*apiserver.Config, error) {
  457. serverConfig := &apiserver.Config{
  458. Logging: true,
  459. SocketGroup: cli.Config.SocketGroup,
  460. Version: dockerversion.Version,
  461. CorsHeaders: cli.Config.CorsHeaders,
  462. }
  463. if cli.Config.TLS {
  464. tlsOptions := tlsconfig.Options{
  465. CAFile: cli.Config.CommonTLSOptions.CAFile,
  466. CertFile: cli.Config.CommonTLSOptions.CertFile,
  467. KeyFile: cli.Config.CommonTLSOptions.KeyFile,
  468. ExclusiveRootPools: true,
  469. }
  470. if cli.Config.TLSVerify {
  471. // server requires and verifies client's certificate
  472. tlsOptions.ClientAuth = tls.RequireAndVerifyClientCert
  473. }
  474. tlsConfig, err := tlsconfig.Server(tlsOptions)
  475. if err != nil {
  476. return nil, err
  477. }
  478. serverConfig.TLSConfig = tlsConfig
  479. }
  480. if len(cli.Config.Hosts) == 0 {
  481. cli.Config.Hosts = make([]string, 1)
  482. }
  483. return serverConfig, nil
  484. }
  485. func loadListeners(cli *DaemonCli, serverConfig *apiserver.Config) ([]string, error) {
  486. var hosts []string
  487. for i := 0; i < len(cli.Config.Hosts); i++ {
  488. var err error
  489. if cli.Config.Hosts[i], err = dopts.ParseHost(cli.Config.TLS, cli.Config.Hosts[i]); err != nil {
  490. return nil, fmt.Errorf("error parsing -H %s : %v", cli.Config.Hosts[i], err)
  491. }
  492. protoAddr := cli.Config.Hosts[i]
  493. protoAddrParts := strings.SplitN(protoAddr, "://", 2)
  494. if len(protoAddrParts) != 2 {
  495. return nil, fmt.Errorf("bad format %s, expected PROTO://ADDR", protoAddr)
  496. }
  497. proto := protoAddrParts[0]
  498. addr := protoAddrParts[1]
  499. // It's a bad idea to bind to TCP without tlsverify.
  500. if proto == "tcp" && (serverConfig.TLSConfig == nil || serverConfig.TLSConfig.ClientAuth != tls.RequireAndVerifyClientCert) {
  501. logrus.Warn("[!] DON'T BIND ON ANY IP ADDRESS WITHOUT setting --tlsverify IF YOU DON'T KNOW WHAT YOU'RE DOING [!]")
  502. }
  503. ls, err := listeners.Init(proto, addr, serverConfig.SocketGroup, serverConfig.TLSConfig)
  504. if err != nil {
  505. return nil, err
  506. }
  507. ls = wrapListeners(proto, ls)
  508. // If we're binding to a TCP port, make sure that a container doesn't try to use it.
  509. if proto == "tcp" {
  510. if err := allocateDaemonPort(addr); err != nil {
  511. return nil, err
  512. }
  513. }
  514. logrus.Debugf("Listener created for HTTP on %s (%s)", proto, addr)
  515. hosts = append(hosts, protoAddrParts[1])
  516. cli.api.Accept(addr, ls...)
  517. }
  518. return hosts, nil
  519. }
  520. func createAndStartCluster(cli *DaemonCli, d *daemon.Daemon) (*cluster.Cluster, error) {
  521. name, _ := os.Hostname()
  522. // Use a buffered channel to pass changes from store watch API to daemon
  523. // A buffer allows store watch API and daemon processing to not wait for each other
  524. watchStream := make(chan *swarmapi.WatchMessage, 32)
  525. c, err := cluster.New(cluster.Config{
  526. Root: cli.Config.Root,
  527. Name: name,
  528. Backend: d,
  529. VolumeBackend: d.VolumesService(),
  530. ImageBackend: d.ImageService(),
  531. PluginBackend: d.PluginManager(),
  532. NetworkSubnetsProvider: d,
  533. DefaultAdvertiseAddr: cli.Config.SwarmDefaultAdvertiseAddr,
  534. RaftHeartbeatTick: cli.Config.SwarmRaftHeartbeatTick,
  535. RaftElectionTick: cli.Config.SwarmRaftElectionTick,
  536. RuntimeRoot: cli.getSwarmRunRoot(),
  537. WatchStream: watchStream,
  538. })
  539. if err != nil {
  540. return nil, err
  541. }
  542. d.SetCluster(c)
  543. err = c.Start()
  544. return c, err
  545. }
  546. // validates that the plugins requested with the --authorization-plugin flag are valid AuthzDriver
  547. // plugins present on the host and available to the daemon
  548. func validateAuthzPlugins(requestedPlugins []string, pg plugingetter.PluginGetter) error {
  549. for _, reqPlugin := range requestedPlugins {
  550. if _, err := pg.Get(reqPlugin, authorization.AuthZApiImplements, plugingetter.Lookup); err != nil {
  551. return err
  552. }
  553. }
  554. return nil
  555. }