daemon.go 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326
  1. // Package daemon exposes the functions that occur on the host server
  2. // that the Docker daemon is running.
  3. //
  4. // In implementing the various functions of the daemon, there is often
  5. // a method-specific struct for configuring the runtime behavior.
  6. package daemon
  7. import (
  8. "encoding/json"
  9. "fmt"
  10. "io/ioutil"
  11. "net"
  12. "os"
  13. "path"
  14. "path/filepath"
  15. "runtime"
  16. "strings"
  17. "sync"
  18. "time"
  19. "github.com/Sirupsen/logrus"
  20. containerd "github.com/docker/containerd/api/grpc/types"
  21. "github.com/docker/docker/api"
  22. "github.com/docker/docker/api/types"
  23. containertypes "github.com/docker/docker/api/types/container"
  24. "github.com/docker/docker/container"
  25. "github.com/docker/docker/daemon/events"
  26. "github.com/docker/docker/daemon/exec"
  27. // register graph drivers
  28. _ "github.com/docker/docker/daemon/graphdriver/register"
  29. "github.com/docker/docker/daemon/initlayer"
  30. "github.com/docker/docker/daemon/stats"
  31. dmetadata "github.com/docker/docker/distribution/metadata"
  32. "github.com/docker/docker/distribution/xfer"
  33. "github.com/docker/docker/dockerversion"
  34. "github.com/docker/docker/image"
  35. "github.com/docker/docker/layer"
  36. "github.com/docker/docker/libcontainerd"
  37. "github.com/docker/docker/migrate/v1"
  38. "github.com/docker/docker/pkg/fileutils"
  39. "github.com/docker/docker/pkg/idtools"
  40. "github.com/docker/docker/pkg/plugingetter"
  41. "github.com/docker/docker/pkg/registrar"
  42. "github.com/docker/docker/pkg/signal"
  43. "github.com/docker/docker/pkg/sysinfo"
  44. "github.com/docker/docker/pkg/system"
  45. "github.com/docker/docker/pkg/truncindex"
  46. "github.com/docker/docker/plugin"
  47. refstore "github.com/docker/docker/reference"
  48. "github.com/docker/docker/registry"
  49. "github.com/docker/docker/runconfig"
  50. volumedrivers "github.com/docker/docker/volume/drivers"
  51. "github.com/docker/docker/volume/local"
  52. "github.com/docker/docker/volume/store"
  53. "github.com/docker/libnetwork"
  54. "github.com/docker/libnetwork/cluster"
  55. nwconfig "github.com/docker/libnetwork/config"
  56. "github.com/docker/libtrust"
  57. "github.com/pkg/errors"
  58. )
  59. var (
  60. // DefaultRuntimeBinary is the default runtime to be used by
  61. // containerd if none is specified
  62. DefaultRuntimeBinary = "docker-runc"
  63. // DefaultInitBinary is the name of the default init binary
  64. DefaultInitBinary = "docker-init"
  65. errSystemNotSupported = errors.New("The Docker daemon is not supported on this platform.")
  66. )
  67. // Daemon holds information about the Docker daemon.
  68. type Daemon struct {
  69. ID string
  70. repository string
  71. containers container.Store
  72. execCommands *exec.Store
  73. referenceStore refstore.Store
  74. downloadManager *xfer.LayerDownloadManager
  75. uploadManager *xfer.LayerUploadManager
  76. distributionMetadataStore dmetadata.Store
  77. trustKey libtrust.PrivateKey
  78. idIndex *truncindex.TruncIndex
  79. configStore *Config
  80. statsCollector *stats.Collector
  81. defaultLogConfig containertypes.LogConfig
  82. RegistryService registry.Service
  83. EventsService *events.Events
  84. netController libnetwork.NetworkController
  85. volumes *store.VolumeStore
  86. discoveryWatcher discoveryReloader
  87. root string
  88. seccompEnabled bool
  89. apparmorEnabled bool
  90. shutdown bool
  91. uidMaps []idtools.IDMap
  92. gidMaps []idtools.IDMap
  93. layerStore layer.Store
  94. imageStore image.Store
  95. PluginStore *plugin.Store // todo: remove
  96. pluginManager *plugin.Manager
  97. nameIndex *registrar.Registrar
  98. linkIndex *linkIndex
  99. containerd libcontainerd.Client
  100. containerdRemote libcontainerd.Remote
  101. defaultIsolation containertypes.Isolation // Default isolation mode on Windows
  102. clusterProvider cluster.Provider
  103. cluster Cluster
  104. machineMemory uint64
  105. seccompProfile []byte
  106. seccompProfilePath string
  107. }
  108. // HasExperimental returns whether the experimental features of the daemon are enabled or not
  109. func (daemon *Daemon) HasExperimental() bool {
  110. if daemon.configStore != nil && daemon.configStore.Experimental {
  111. return true
  112. }
  113. return false
  114. }
  115. func (daemon *Daemon) restore() error {
  116. var (
  117. currentDriver = daemon.GraphDriverName()
  118. containers = make(map[string]*container.Container)
  119. )
  120. logrus.Info("Loading containers: start.")
  121. dir, err := ioutil.ReadDir(daemon.repository)
  122. if err != nil {
  123. return err
  124. }
  125. for _, v := range dir {
  126. id := v.Name()
  127. container, err := daemon.load(id)
  128. if err != nil {
  129. logrus.Errorf("Failed to load container %v: %v", id, err)
  130. continue
  131. }
  132. // Ignore the container if it does not support the current driver being used by the graph
  133. if (container.Driver == "" && currentDriver == "aufs") || container.Driver == currentDriver {
  134. rwlayer, err := daemon.layerStore.GetRWLayer(container.ID)
  135. if err != nil {
  136. logrus.Errorf("Failed to load container mount %v: %v", id, err)
  137. continue
  138. }
  139. container.RWLayer = rwlayer
  140. logrus.Debugf("Loaded container %v", container.ID)
  141. containers[container.ID] = container
  142. } else {
  143. logrus.Debugf("Cannot load container %s because it was created with another graph driver.", container.ID)
  144. }
  145. }
  146. removeContainers := make(map[string]*container.Container)
  147. restartContainers := make(map[*container.Container]chan struct{})
  148. activeSandboxes := make(map[string]interface{})
  149. for id, c := range containers {
  150. if err := daemon.registerName(c); err != nil {
  151. logrus.Errorf("Failed to register container %s: %s", c.ID, err)
  152. delete(containers, id)
  153. continue
  154. }
  155. daemon.Register(c)
  156. // verify that all volumes valid and have been migrated from the pre-1.7 layout
  157. if err := daemon.verifyVolumesInfo(c); err != nil {
  158. // don't skip the container due to error
  159. logrus.Errorf("Failed to verify volumes for container '%s': %v", c.ID, err)
  160. }
  161. // The LogConfig.Type is empty if the container was created before docker 1.12 with default log driver.
  162. // We should rewrite it to use the daemon defaults.
  163. // Fixes https://github.com/docker/docker/issues/22536
  164. if c.HostConfig.LogConfig.Type == "" {
  165. if err := daemon.mergeAndVerifyLogConfig(&c.HostConfig.LogConfig); err != nil {
  166. logrus.Errorf("Failed to verify log config for container %s: %q", c.ID, err)
  167. continue
  168. }
  169. }
  170. }
  171. var wg sync.WaitGroup
  172. var mapLock sync.Mutex
  173. for _, c := range containers {
  174. wg.Add(1)
  175. go func(c *container.Container) {
  176. defer wg.Done()
  177. if err := backportMountSpec(c); err != nil {
  178. logrus.Error("Failed to migrate old mounts to use new spec format")
  179. }
  180. if c.IsRunning() || c.IsPaused() {
  181. c.RestartManager().Cancel() // manually start containers because some need to wait for swarm networking
  182. if err := daemon.containerd.Restore(c.ID, c.InitializeStdio); err != nil {
  183. logrus.Errorf("Failed to restore %s with containerd: %s", c.ID, err)
  184. return
  185. }
  186. // we call Mount and then Unmount to get BaseFs of the container
  187. if err := daemon.Mount(c); err != nil {
  188. // The mount is unlikely to fail. However, in case mount fails
  189. // the container should be allowed to restore here. Some functionalities
  190. // (like docker exec -u user) might be missing but container is able to be
  191. // stopped/restarted/removed.
  192. // See #29365 for related information.
  193. // The error is only logged here.
  194. logrus.Warnf("Failed to mount container on getting BaseFs path %v: %v", c.ID, err)
  195. } else {
  196. // if mount success, then unmount it
  197. if err := daemon.Unmount(c); err != nil {
  198. logrus.Warnf("Failed to umount container on getting BaseFs path %v: %v", c.ID, err)
  199. }
  200. }
  201. c.ResetRestartManager(false)
  202. if !c.HostConfig.NetworkMode.IsContainer() && c.IsRunning() {
  203. options, err := daemon.buildSandboxOptions(c)
  204. if err != nil {
  205. logrus.Warnf("Failed build sandbox option to restore container %s: %v", c.ID, err)
  206. }
  207. mapLock.Lock()
  208. activeSandboxes[c.NetworkSettings.SandboxID] = options
  209. mapLock.Unlock()
  210. }
  211. }
  212. // fixme: only if not running
  213. // get list of containers we need to restart
  214. if !c.IsRunning() && !c.IsPaused() {
  215. // Do not autostart containers which
  216. // has endpoints in a swarm scope
  217. // network yet since the cluster is
  218. // not initialized yet. We will start
  219. // it after the cluster is
  220. // initialized.
  221. if daemon.configStore.AutoRestart && c.ShouldRestart() && !c.NetworkSettings.HasSwarmEndpoint {
  222. mapLock.Lock()
  223. restartContainers[c] = make(chan struct{})
  224. mapLock.Unlock()
  225. } else if c.HostConfig != nil && c.HostConfig.AutoRemove {
  226. mapLock.Lock()
  227. removeContainers[c.ID] = c
  228. mapLock.Unlock()
  229. }
  230. }
  231. if c.RemovalInProgress {
  232. // We probably crashed in the middle of a removal, reset
  233. // the flag.
  234. //
  235. // We DO NOT remove the container here as we do not
  236. // know if the user had requested for either the
  237. // associated volumes, network links or both to also
  238. // be removed. So we put the container in the "dead"
  239. // state and leave further processing up to them.
  240. logrus.Debugf("Resetting RemovalInProgress flag from %v", c.ID)
  241. c.ResetRemovalInProgress()
  242. c.SetDead()
  243. c.ToDisk()
  244. }
  245. }(c)
  246. }
  247. wg.Wait()
  248. daemon.netController, err = daemon.initNetworkController(daemon.configStore, activeSandboxes)
  249. if err != nil {
  250. return fmt.Errorf("Error initializing network controller: %v", err)
  251. }
  252. // Now that all the containers are registered, register the links
  253. for _, c := range containers {
  254. if err := daemon.registerLinks(c, c.HostConfig); err != nil {
  255. logrus.Errorf("failed to register link for container %s: %v", c.ID, err)
  256. }
  257. }
  258. group := sync.WaitGroup{}
  259. for c, notifier := range restartContainers {
  260. group.Add(1)
  261. go func(c *container.Container, chNotify chan struct{}) {
  262. defer group.Done()
  263. logrus.Debugf("Starting container %s", c.ID)
  264. // ignore errors here as this is a best effort to wait for children to be
  265. // running before we try to start the container
  266. children := daemon.children(c)
  267. timeout := time.After(5 * time.Second)
  268. for _, child := range children {
  269. if notifier, exists := restartContainers[child]; exists {
  270. select {
  271. case <-notifier:
  272. case <-timeout:
  273. }
  274. }
  275. }
  276. // Make sure networks are available before starting
  277. daemon.waitForNetworks(c)
  278. if err := daemon.containerStart(c, "", "", true); err != nil {
  279. logrus.Errorf("Failed to start container %s: %s", c.ID, err)
  280. }
  281. close(chNotify)
  282. }(c, notifier)
  283. }
  284. group.Wait()
  285. removeGroup := sync.WaitGroup{}
  286. for id := range removeContainers {
  287. removeGroup.Add(1)
  288. go func(cid string) {
  289. if err := daemon.ContainerRm(cid, &types.ContainerRmConfig{ForceRemove: true, RemoveVolume: true}); err != nil {
  290. logrus.Errorf("Failed to remove container %s: %s", cid, err)
  291. }
  292. removeGroup.Done()
  293. }(id)
  294. }
  295. removeGroup.Wait()
  296. // any containers that were started above would already have had this done,
  297. // however we need to now prepare the mountpoints for the rest of the containers as well.
  298. // This shouldn't cause any issue running on the containers that already had this run.
  299. // This must be run after any containers with a restart policy so that containerized plugins
  300. // can have a chance to be running before we try to initialize them.
  301. for _, c := range containers {
  302. // if the container has restart policy, do not
  303. // prepare the mountpoints since it has been done on restarting.
  304. // This is to speed up the daemon start when a restart container
  305. // has a volume and the volume driver is not available.
  306. if _, ok := restartContainers[c]; ok {
  307. continue
  308. } else if _, ok := removeContainers[c.ID]; ok {
  309. // container is automatically removed, skip it.
  310. continue
  311. }
  312. group.Add(1)
  313. go func(c *container.Container) {
  314. defer group.Done()
  315. if err := daemon.prepareMountPoints(c); err != nil {
  316. logrus.Error(err)
  317. }
  318. }(c)
  319. }
  320. group.Wait()
  321. logrus.Info("Loading containers: done.")
  322. return nil
  323. }
  324. // RestartSwarmContainers restarts any autostart container which has a
  325. // swarm endpoint.
  326. func (daemon *Daemon) RestartSwarmContainers() {
  327. group := sync.WaitGroup{}
  328. for _, c := range daemon.List() {
  329. if !c.IsRunning() && !c.IsPaused() {
  330. // Autostart all the containers which has a
  331. // swarm endpoint now that the cluster is
  332. // initialized.
  333. if daemon.configStore.AutoRestart && c.ShouldRestart() && c.NetworkSettings.HasSwarmEndpoint {
  334. group.Add(1)
  335. go func(c *container.Container) {
  336. defer group.Done()
  337. if err := daemon.containerStart(c, "", "", true); err != nil {
  338. logrus.Error(err)
  339. }
  340. }(c)
  341. }
  342. }
  343. }
  344. group.Wait()
  345. }
  346. // waitForNetworks is used during daemon initialization when starting up containers
  347. // It ensures that all of a container's networks are available before the daemon tries to start the container.
  348. // In practice it just makes sure the discovery service is available for containers which use a network that require discovery.
  349. func (daemon *Daemon) waitForNetworks(c *container.Container) {
  350. if daemon.discoveryWatcher == nil {
  351. return
  352. }
  353. // Make sure if the container has a network that requires discovery that the discovery service is available before starting
  354. for netName := range c.NetworkSettings.Networks {
  355. // If we get `ErrNoSuchNetwork` here, we can assume that it is due to discovery not being ready
  356. // Most likely this is because the K/V store used for discovery is in a container and needs to be started
  357. if _, err := daemon.netController.NetworkByName(netName); err != nil {
  358. if _, ok := err.(libnetwork.ErrNoSuchNetwork); !ok {
  359. continue
  360. }
  361. // use a longish timeout here due to some slowdowns in libnetwork if the k/v store is on anything other than --net=host
  362. // FIXME: why is this slow???
  363. logrus.Debugf("Container %s waiting for network to be ready", c.Name)
  364. select {
  365. case <-daemon.discoveryWatcher.ReadyCh():
  366. case <-time.After(60 * time.Second):
  367. }
  368. return
  369. }
  370. }
  371. }
  372. func (daemon *Daemon) children(c *container.Container) map[string]*container.Container {
  373. return daemon.linkIndex.children(c)
  374. }
  375. // parents returns the names of the parent containers of the container
  376. // with the given name.
  377. func (daemon *Daemon) parents(c *container.Container) map[string]*container.Container {
  378. return daemon.linkIndex.parents(c)
  379. }
  380. func (daemon *Daemon) registerLink(parent, child *container.Container, alias string) error {
  381. fullName := path.Join(parent.Name, alias)
  382. if err := daemon.nameIndex.Reserve(fullName, child.ID); err != nil {
  383. if err == registrar.ErrNameReserved {
  384. logrus.Warnf("error registering link for %s, to %s, as alias %s, ignoring: %v", parent.ID, child.ID, alias, err)
  385. return nil
  386. }
  387. return err
  388. }
  389. daemon.linkIndex.link(parent, child, fullName)
  390. return nil
  391. }
  392. // DaemonJoinsCluster informs the daemon has joined the cluster and provides
  393. // the handler to query the cluster component
  394. func (daemon *Daemon) DaemonJoinsCluster(clusterProvider cluster.Provider) {
  395. daemon.setClusterProvider(clusterProvider)
  396. }
  397. // DaemonLeavesCluster informs the daemon has left the cluster
  398. func (daemon *Daemon) DaemonLeavesCluster() {
  399. // Daemon is in charge of removing the attachable networks with
  400. // connected containers when the node leaves the swarm
  401. daemon.clearAttachableNetworks()
  402. daemon.setClusterProvider(nil)
  403. }
  404. // setClusterProvider sets a component for querying the current cluster state.
  405. func (daemon *Daemon) setClusterProvider(clusterProvider cluster.Provider) {
  406. daemon.clusterProvider = clusterProvider
  407. daemon.netController.SetClusterProvider(clusterProvider)
  408. }
  409. // IsSwarmCompatible verifies if the current daemon
  410. // configuration is compatible with the swarm mode
  411. func (daemon *Daemon) IsSwarmCompatible() error {
  412. if daemon.configStore == nil {
  413. return nil
  414. }
  415. return daemon.configStore.isSwarmCompatible()
  416. }
  417. // NewDaemon sets up everything for the daemon to be able to service
  418. // requests from the webserver.
  419. func NewDaemon(config *Config, registryService registry.Service, containerdRemote libcontainerd.Remote) (daemon *Daemon, err error) {
  420. setDefaultMtu(config)
  421. // Ensure that we have a correct root key limit for launching containers.
  422. if err := ModifyRootKeyLimit(); err != nil {
  423. logrus.Warnf("unable to modify root key limit, number of containers could be limited by this quota: %v", err)
  424. }
  425. // Ensure we have compatible and valid configuration options
  426. if err := verifyDaemonSettings(config); err != nil {
  427. return nil, err
  428. }
  429. // Do we have a disabled network?
  430. config.DisableBridge = isBridgeNetworkDisabled(config)
  431. // Verify the platform is supported as a daemon
  432. if !platformSupported {
  433. return nil, errSystemNotSupported
  434. }
  435. // Validate platform-specific requirements
  436. if err := checkSystem(); err != nil {
  437. return nil, err
  438. }
  439. uidMaps, gidMaps, err := setupRemappedRoot(config)
  440. if err != nil {
  441. return nil, err
  442. }
  443. rootUID, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps)
  444. if err != nil {
  445. return nil, err
  446. }
  447. if err := setupDaemonProcess(config); err != nil {
  448. return nil, err
  449. }
  450. // set up the tmpDir to use a canonical path
  451. tmp, err := tempDir(config.Root, rootUID, rootGID)
  452. if err != nil {
  453. return nil, fmt.Errorf("Unable to get the TempDir under %s: %s", config.Root, err)
  454. }
  455. realTmp, err := fileutils.ReadSymlinkedDirectory(tmp)
  456. if err != nil {
  457. return nil, fmt.Errorf("Unable to get the full path to the TempDir (%s): %s", tmp, err)
  458. }
  459. os.Setenv("TMPDIR", realTmp)
  460. d := &Daemon{configStore: config}
  461. // Ensure the daemon is properly shutdown if there is a failure during
  462. // initialization
  463. defer func() {
  464. if err != nil {
  465. if err := d.Shutdown(); err != nil {
  466. logrus.Error(err)
  467. }
  468. }
  469. }()
  470. if err := d.setupSeccompProfile(); err != nil {
  471. return nil, err
  472. }
  473. // Set the default isolation mode (only applicable on Windows)
  474. if err := d.setDefaultIsolation(); err != nil {
  475. return nil, fmt.Errorf("error setting default isolation mode: %v", err)
  476. }
  477. logrus.Debugf("Using default logging driver %s", config.LogConfig.Type)
  478. if err := configureMaxThreads(config); err != nil {
  479. logrus.Warnf("Failed to configure golang's threads limit: %v", err)
  480. }
  481. if err := ensureDefaultAppArmorProfile(); err != nil {
  482. logrus.Errorf(err.Error())
  483. }
  484. daemonRepo := filepath.Join(config.Root, "containers")
  485. if err := idtools.MkdirAllAs(daemonRepo, 0700, rootUID, rootGID); err != nil && !os.IsExist(err) {
  486. return nil, err
  487. }
  488. if runtime.GOOS == "windows" {
  489. if err := system.MkdirAll(filepath.Join(config.Root, "credentialspecs"), 0); err != nil && !os.IsExist(err) {
  490. return nil, err
  491. }
  492. }
  493. driverName := os.Getenv("DOCKER_DRIVER")
  494. if driverName == "" {
  495. driverName = config.GraphDriver
  496. }
  497. d.RegistryService = registryService
  498. d.PluginStore = plugin.NewStore(config.Root) // todo: remove
  499. // Plugin system initialization should happen before restore. Do not change order.
  500. d.pluginManager, err = plugin.NewManager(plugin.ManagerConfig{
  501. Root: filepath.Join(config.Root, "plugins"),
  502. ExecRoot: getPluginExecRoot(config.Root),
  503. Store: d.PluginStore,
  504. Executor: containerdRemote,
  505. RegistryService: registryService,
  506. LiveRestoreEnabled: config.LiveRestoreEnabled,
  507. LogPluginEvent: d.LogPluginEvent, // todo: make private
  508. })
  509. if err != nil {
  510. return nil, errors.Wrap(err, "couldn't create plugin manager")
  511. }
  512. d.layerStore, err = layer.NewStoreFromOptions(layer.StoreOptions{
  513. StorePath: config.Root,
  514. MetadataStorePathTemplate: filepath.Join(config.Root, "image", "%s", "layerdb"),
  515. GraphDriver: driverName,
  516. GraphDriverOptions: config.GraphOptions,
  517. UIDMaps: uidMaps,
  518. GIDMaps: gidMaps,
  519. PluginGetter: d.PluginStore,
  520. ExperimentalEnabled: config.Experimental,
  521. })
  522. if err != nil {
  523. return nil, err
  524. }
  525. graphDriver := d.layerStore.DriverName()
  526. imageRoot := filepath.Join(config.Root, "image", graphDriver)
  527. // Configure and validate the kernels security support
  528. if err := configureKernelSecuritySupport(config, graphDriver); err != nil {
  529. return nil, err
  530. }
  531. logrus.Debugf("Max Concurrent Downloads: %d", *config.MaxConcurrentDownloads)
  532. d.downloadManager = xfer.NewLayerDownloadManager(d.layerStore, *config.MaxConcurrentDownloads)
  533. logrus.Debugf("Max Concurrent Uploads: %d", *config.MaxConcurrentUploads)
  534. d.uploadManager = xfer.NewLayerUploadManager(*config.MaxConcurrentUploads)
  535. ifs, err := image.NewFSStoreBackend(filepath.Join(imageRoot, "imagedb"))
  536. if err != nil {
  537. return nil, err
  538. }
  539. d.imageStore, err = image.NewImageStore(ifs, d.layerStore)
  540. if err != nil {
  541. return nil, err
  542. }
  543. // Configure the volumes driver
  544. volStore, err := d.configureVolumes(rootUID, rootGID)
  545. if err != nil {
  546. return nil, err
  547. }
  548. trustKey, err := api.LoadOrCreateTrustKey(config.TrustKeyPath)
  549. if err != nil {
  550. return nil, err
  551. }
  552. trustDir := filepath.Join(config.Root, "trust")
  553. if err := system.MkdirAll(trustDir, 0700); err != nil {
  554. return nil, err
  555. }
  556. distributionMetadataStore, err := dmetadata.NewFSMetadataStore(filepath.Join(imageRoot, "distribution"))
  557. if err != nil {
  558. return nil, err
  559. }
  560. eventsService := events.New()
  561. referenceStore, err := refstore.NewReferenceStore(filepath.Join(imageRoot, "repositories.json"))
  562. if err != nil {
  563. return nil, fmt.Errorf("Couldn't create Tag store repositories: %s", err)
  564. }
  565. migrationStart := time.Now()
  566. if err := v1.Migrate(config.Root, graphDriver, d.layerStore, d.imageStore, referenceStore, distributionMetadataStore); err != nil {
  567. logrus.Errorf("Graph migration failed: %q. Your old graph data was found to be too inconsistent for upgrading to content-addressable storage. Some of the old data was probably not upgraded. We recommend starting over with a clean storage directory if possible.", err)
  568. }
  569. logrus.Infof("Graph migration to content-addressability took %.2f seconds", time.Since(migrationStart).Seconds())
  570. // Discovery is only enabled when the daemon is launched with an address to advertise. When
  571. // initialized, the daemon is registered and we can store the discovery backend as it's read-only
  572. if err := d.initDiscovery(config); err != nil {
  573. return nil, err
  574. }
  575. sysInfo := sysinfo.New(false)
  576. // Check if Devices cgroup is mounted, it is hard requirement for container security,
  577. // on Linux.
  578. if runtime.GOOS == "linux" && !sysInfo.CgroupDevicesEnabled {
  579. return nil, errors.New("Devices cgroup isn't mounted")
  580. }
  581. d.ID = trustKey.PublicKey().KeyID()
  582. d.repository = daemonRepo
  583. d.containers = container.NewMemoryStore()
  584. d.execCommands = exec.NewStore()
  585. d.referenceStore = referenceStore
  586. d.distributionMetadataStore = distributionMetadataStore
  587. d.trustKey = trustKey
  588. d.idIndex = truncindex.NewTruncIndex([]string{})
  589. d.statsCollector = d.newStatsCollector(1 * time.Second)
  590. d.defaultLogConfig = containertypes.LogConfig{
  591. Type: config.LogConfig.Type,
  592. Config: config.LogConfig.Config,
  593. }
  594. d.EventsService = eventsService
  595. d.volumes = volStore
  596. d.root = config.Root
  597. d.uidMaps = uidMaps
  598. d.gidMaps = gidMaps
  599. d.seccompEnabled = sysInfo.Seccomp
  600. d.apparmorEnabled = sysInfo.AppArmor
  601. d.nameIndex = registrar.NewRegistrar()
  602. d.linkIndex = newLinkIndex()
  603. d.containerdRemote = containerdRemote
  604. go d.execCommandGC()
  605. d.containerd, err = containerdRemote.Client(d)
  606. if err != nil {
  607. return nil, err
  608. }
  609. if err := d.restore(); err != nil {
  610. return nil, err
  611. }
  612. // FIXME: this method never returns an error
  613. info, _ := d.SystemInfo()
  614. engineVersion.WithValues(
  615. dockerversion.Version,
  616. dockerversion.GitCommit,
  617. info.Architecture,
  618. info.Driver,
  619. info.KernelVersion,
  620. info.OperatingSystem,
  621. ).Set(1)
  622. engineCpus.Set(float64(info.NCPU))
  623. engineMemory.Set(float64(info.MemTotal))
  624. // set up SIGUSR1 handler on Unix-like systems, or a Win32 global event
  625. // on Windows to dump Go routine stacks
  626. stackDumpDir := config.Root
  627. if execRoot := config.GetExecRoot(); execRoot != "" {
  628. stackDumpDir = execRoot
  629. }
  630. d.setupDumpStackTrap(stackDumpDir)
  631. return d, nil
  632. }
  633. func (daemon *Daemon) shutdownContainer(c *container.Container) error {
  634. stopTimeout := c.StopTimeout()
  635. // TODO(windows): Handle docker restart with paused containers
  636. if c.IsPaused() {
  637. // To terminate a process in freezer cgroup, we should send
  638. // SIGTERM to this process then unfreeze it, and the process will
  639. // force to terminate immediately.
  640. logrus.Debugf("Found container %s is paused, sending SIGTERM before unpausing it", c.ID)
  641. sig, ok := signal.SignalMap["TERM"]
  642. if !ok {
  643. return errors.New("System does not support SIGTERM")
  644. }
  645. if err := daemon.kill(c, int(sig)); err != nil {
  646. return fmt.Errorf("sending SIGTERM to container %s with error: %v", c.ID, err)
  647. }
  648. if err := daemon.containerUnpause(c); err != nil {
  649. return fmt.Errorf("Failed to unpause container %s with error: %v", c.ID, err)
  650. }
  651. if _, err := c.WaitStop(time.Duration(stopTimeout) * time.Second); err != nil {
  652. logrus.Debugf("container %s failed to exit in %d second of SIGTERM, sending SIGKILL to force", c.ID, stopTimeout)
  653. sig, ok := signal.SignalMap["KILL"]
  654. if !ok {
  655. return errors.New("System does not support SIGKILL")
  656. }
  657. if err := daemon.kill(c, int(sig)); err != nil {
  658. logrus.Errorf("Failed to SIGKILL container %s", c.ID)
  659. }
  660. c.WaitStop(-1 * time.Second)
  661. return err
  662. }
  663. }
  664. // If container failed to exit in stopTimeout seconds of SIGTERM, then using the force
  665. if err := daemon.containerStop(c, stopTimeout); err != nil {
  666. return fmt.Errorf("Failed to stop container %s with error: %v", c.ID, err)
  667. }
  668. c.WaitStop(-1 * time.Second)
  669. return nil
  670. }
  671. // ShutdownTimeout returns the shutdown timeout based on the max stopTimeout of the containers,
  672. // and is limited by daemon's ShutdownTimeout.
  673. func (daemon *Daemon) ShutdownTimeout() int {
  674. // By default we use daemon's ShutdownTimeout.
  675. shutdownTimeout := daemon.configStore.ShutdownTimeout
  676. graceTimeout := 5
  677. if daemon.containers != nil {
  678. for _, c := range daemon.containers.List() {
  679. if shutdownTimeout >= 0 {
  680. stopTimeout := c.StopTimeout()
  681. if stopTimeout < 0 {
  682. shutdownTimeout = -1
  683. } else {
  684. if stopTimeout+graceTimeout > shutdownTimeout {
  685. shutdownTimeout = stopTimeout + graceTimeout
  686. }
  687. }
  688. }
  689. }
  690. }
  691. return shutdownTimeout
  692. }
  693. // Shutdown stops the daemon.
  694. func (daemon *Daemon) Shutdown() error {
  695. daemon.shutdown = true
  696. // Keep mounts and networking running on daemon shutdown if
  697. // we are to keep containers running and restore them.
  698. if daemon.configStore.LiveRestoreEnabled && daemon.containers != nil {
  699. // check if there are any running containers, if none we should do some cleanup
  700. if ls, err := daemon.Containers(&types.ContainerListOptions{}); len(ls) != 0 || err != nil {
  701. return nil
  702. }
  703. }
  704. if daemon.containers != nil {
  705. logrus.Debugf("start clean shutdown of all containers with a %d seconds timeout...", daemon.configStore.ShutdownTimeout)
  706. daemon.containers.ApplyAll(func(c *container.Container) {
  707. if !c.IsRunning() {
  708. return
  709. }
  710. logrus.Debugf("stopping %s", c.ID)
  711. if err := daemon.shutdownContainer(c); err != nil {
  712. logrus.Errorf("Stop container error: %v", err)
  713. return
  714. }
  715. if mountid, err := daemon.layerStore.GetMountID(c.ID); err == nil {
  716. daemon.cleanupMountsByID(mountid)
  717. }
  718. logrus.Debugf("container stopped %s", c.ID)
  719. })
  720. }
  721. if daemon.volumes != nil {
  722. if err := daemon.volumes.Shutdown(); err != nil {
  723. logrus.Errorf("Error shutting down volume store: %v", err)
  724. }
  725. }
  726. if daemon.layerStore != nil {
  727. if err := daemon.layerStore.Cleanup(); err != nil {
  728. logrus.Errorf("Error during layer Store.Cleanup(): %v", err)
  729. }
  730. }
  731. // Shutdown plugins after containers and layerstore. Don't change the order.
  732. daemon.pluginShutdown()
  733. // trigger libnetwork Stop only if it's initialized
  734. if daemon.netController != nil {
  735. daemon.netController.Stop()
  736. }
  737. if err := daemon.cleanupMounts(); err != nil {
  738. return err
  739. }
  740. return nil
  741. }
  742. // Mount sets container.BaseFS
  743. // (is it not set coming in? why is it unset?)
  744. func (daemon *Daemon) Mount(container *container.Container) error {
  745. dir, err := container.RWLayer.Mount(container.GetMountLabel())
  746. if err != nil {
  747. return err
  748. }
  749. logrus.Debugf("container mounted via layerStore: %v", dir)
  750. if container.BaseFS != dir {
  751. // The mount path reported by the graph driver should always be trusted on Windows, since the
  752. // volume path for a given mounted layer may change over time. This should only be an error
  753. // on non-Windows operating systems.
  754. if container.BaseFS != "" && runtime.GOOS != "windows" {
  755. daemon.Unmount(container)
  756. return fmt.Errorf("Error: driver %s is returning inconsistent paths for container %s ('%s' then '%s')",
  757. daemon.GraphDriverName(), container.ID, container.BaseFS, dir)
  758. }
  759. }
  760. container.BaseFS = dir // TODO: combine these fields
  761. return nil
  762. }
  763. // Unmount unsets the container base filesystem
  764. func (daemon *Daemon) Unmount(container *container.Container) error {
  765. if err := container.RWLayer.Unmount(); err != nil {
  766. logrus.Errorf("Error unmounting container %s: %s", container.ID, err)
  767. return err
  768. }
  769. return nil
  770. }
  771. // V4Subnets returns the IPv4 subnets of networks that are managed by Docker.
  772. func (daemon *Daemon) V4Subnets() []net.IPNet {
  773. var subnets []net.IPNet
  774. managedNetworks := daemon.netController.Networks()
  775. for _, managedNetwork := range managedNetworks {
  776. v4Infos, _ := managedNetwork.Info().IpamInfo()
  777. for _, v4Info := range v4Infos {
  778. if v4Info.IPAMData.Pool != nil {
  779. subnets = append(subnets, *v4Info.IPAMData.Pool)
  780. }
  781. }
  782. }
  783. return subnets
  784. }
  785. // V6Subnets returns the IPv6 subnets of networks that are managed by Docker.
  786. func (daemon *Daemon) V6Subnets() []net.IPNet {
  787. var subnets []net.IPNet
  788. managedNetworks := daemon.netController.Networks()
  789. for _, managedNetwork := range managedNetworks {
  790. _, v6Infos := managedNetwork.Info().IpamInfo()
  791. for _, v6Info := range v6Infos {
  792. if v6Info.IPAMData.Pool != nil {
  793. subnets = append(subnets, *v6Info.IPAMData.Pool)
  794. }
  795. }
  796. }
  797. return subnets
  798. }
  799. // GraphDriverName returns the name of the graph driver used by the layer.Store
  800. func (daemon *Daemon) GraphDriverName() string {
  801. return daemon.layerStore.DriverName()
  802. }
  803. // GetUIDGIDMaps returns the current daemon's user namespace settings
  804. // for the full uid and gid maps which will be applied to containers
  805. // started in this instance.
  806. func (daemon *Daemon) GetUIDGIDMaps() ([]idtools.IDMap, []idtools.IDMap) {
  807. return daemon.uidMaps, daemon.gidMaps
  808. }
  809. // GetRemappedUIDGID returns the current daemon's uid and gid values
  810. // if user namespaces are in use for this daemon instance. If not
  811. // this function will return "real" root values of 0, 0.
  812. func (daemon *Daemon) GetRemappedUIDGID() (int, int) {
  813. uid, gid, _ := idtools.GetRootUIDGID(daemon.uidMaps, daemon.gidMaps)
  814. return uid, gid
  815. }
  816. // tempDir returns the default directory to use for temporary files.
  817. func tempDir(rootDir string, rootUID, rootGID int) (string, error) {
  818. var tmpDir string
  819. if tmpDir = os.Getenv("DOCKER_TMPDIR"); tmpDir == "" {
  820. tmpDir = filepath.Join(rootDir, "tmp")
  821. }
  822. return tmpDir, idtools.MkdirAllAs(tmpDir, 0700, rootUID, rootGID)
  823. }
  824. func (daemon *Daemon) setupInitLayer(initPath string) error {
  825. rootUID, rootGID := daemon.GetRemappedUIDGID()
  826. return initlayer.Setup(initPath, rootUID, rootGID)
  827. }
  828. func setDefaultMtu(config *Config) {
  829. // do nothing if the config does not have the default 0 value.
  830. if config.Mtu != 0 {
  831. return
  832. }
  833. config.Mtu = defaultNetworkMtu
  834. }
  835. func (daemon *Daemon) configureVolumes(rootUID, rootGID int) (*store.VolumeStore, error) {
  836. volumesDriver, err := local.New(daemon.configStore.Root, rootUID, rootGID)
  837. if err != nil {
  838. return nil, err
  839. }
  840. volumedrivers.RegisterPluginGetter(daemon.PluginStore)
  841. if !volumedrivers.Register(volumesDriver, volumesDriver.Name()) {
  842. return nil, errors.New("local volume driver could not be registered")
  843. }
  844. return store.New(daemon.configStore.Root)
  845. }
  846. // IsShuttingDown tells whether the daemon is shutting down or not
  847. func (daemon *Daemon) IsShuttingDown() bool {
  848. return daemon.shutdown
  849. }
  850. // initDiscovery initializes the discovery watcher for this daemon.
  851. func (daemon *Daemon) initDiscovery(config *Config) error {
  852. advertise, err := parseClusterAdvertiseSettings(config.ClusterStore, config.ClusterAdvertise)
  853. if err != nil {
  854. if err == errDiscoveryDisabled {
  855. return nil
  856. }
  857. return err
  858. }
  859. config.ClusterAdvertise = advertise
  860. discoveryWatcher, err := initDiscovery(config.ClusterStore, config.ClusterAdvertise, config.ClusterOpts)
  861. if err != nil {
  862. return fmt.Errorf("discovery initialization failed (%v)", err)
  863. }
  864. daemon.discoveryWatcher = discoveryWatcher
  865. return nil
  866. }
  867. // Reload reads configuration changes and modifies the
  868. // daemon according to those changes.
  869. // These are the settings that Reload changes:
  870. // - Daemon labels
  871. // - Daemon debug log level
  872. // - Insecure registries
  873. // - Registry mirrors
  874. // - Daemon max concurrent downloads
  875. // - Daemon max concurrent uploads
  876. // - Cluster discovery (reconfigure and restart)
  877. // - Daemon live restore
  878. // - Daemon shutdown timeout (in seconds)
  879. func (daemon *Daemon) Reload(config *Config) (err error) {
  880. daemon.configStore.reloadLock.Lock()
  881. attributes := daemon.platformReload(config)
  882. defer func() {
  883. // we're unlocking here, because
  884. // LogDaemonEventWithAttributes() -> SystemInfo() -> GetAllRuntimes()
  885. // holds that lock too.
  886. daemon.configStore.reloadLock.Unlock()
  887. if err == nil {
  888. daemon.LogDaemonEventWithAttributes("reload", attributes)
  889. }
  890. }()
  891. if err := daemon.reloadClusterDiscovery(config); err != nil {
  892. return err
  893. }
  894. if config.IsValueSet("labels") {
  895. daemon.configStore.Labels = config.Labels
  896. }
  897. if config.IsValueSet("debug") {
  898. daemon.configStore.Debug = config.Debug
  899. }
  900. if config.IsValueSet("insecure-registries") {
  901. daemon.configStore.InsecureRegistries = config.InsecureRegistries
  902. if err := daemon.RegistryService.LoadInsecureRegistries(config.InsecureRegistries); err != nil {
  903. return err
  904. }
  905. }
  906. if config.IsValueSet("registry-mirrors") {
  907. daemon.configStore.Mirrors = config.Mirrors
  908. if err := daemon.RegistryService.LoadMirrors(config.Mirrors); err != nil {
  909. return err
  910. }
  911. }
  912. if config.IsValueSet("live-restore") {
  913. daemon.configStore.LiveRestoreEnabled = config.LiveRestoreEnabled
  914. if err := daemon.containerdRemote.UpdateOptions(libcontainerd.WithLiveRestore(config.LiveRestoreEnabled)); err != nil {
  915. return err
  916. }
  917. }
  918. // If no value is set for max-concurrent-downloads we assume it is the default value
  919. // We always "reset" as the cost is lightweight and easy to maintain.
  920. if config.IsValueSet("max-concurrent-downloads") && config.MaxConcurrentDownloads != nil {
  921. *daemon.configStore.MaxConcurrentDownloads = *config.MaxConcurrentDownloads
  922. } else {
  923. maxConcurrentDownloads := defaultMaxConcurrentDownloads
  924. daemon.configStore.MaxConcurrentDownloads = &maxConcurrentDownloads
  925. }
  926. logrus.Debugf("Reset Max Concurrent Downloads: %d", *daemon.configStore.MaxConcurrentDownloads)
  927. if daemon.downloadManager != nil {
  928. daemon.downloadManager.SetConcurrency(*daemon.configStore.MaxConcurrentDownloads)
  929. }
  930. // If no value is set for max-concurrent-upload we assume it is the default value
  931. // We always "reset" as the cost is lightweight and easy to maintain.
  932. if config.IsValueSet("max-concurrent-uploads") && config.MaxConcurrentUploads != nil {
  933. *daemon.configStore.MaxConcurrentUploads = *config.MaxConcurrentUploads
  934. } else {
  935. maxConcurrentUploads := defaultMaxConcurrentUploads
  936. daemon.configStore.MaxConcurrentUploads = &maxConcurrentUploads
  937. }
  938. logrus.Debugf("Reset Max Concurrent Uploads: %d", *daemon.configStore.MaxConcurrentUploads)
  939. if daemon.uploadManager != nil {
  940. daemon.uploadManager.SetConcurrency(*daemon.configStore.MaxConcurrentUploads)
  941. }
  942. if config.IsValueSet("shutdown-timeout") {
  943. daemon.configStore.ShutdownTimeout = config.ShutdownTimeout
  944. logrus.Debugf("Reset Shutdown Timeout: %d", daemon.configStore.ShutdownTimeout)
  945. }
  946. // We emit daemon reload event here with updatable configurations
  947. attributes["debug"] = fmt.Sprintf("%t", daemon.configStore.Debug)
  948. attributes["live-restore"] = fmt.Sprintf("%t", daemon.configStore.LiveRestoreEnabled)
  949. if daemon.configStore.InsecureRegistries != nil {
  950. insecureRegistries, err := json.Marshal(daemon.configStore.InsecureRegistries)
  951. if err != nil {
  952. return err
  953. }
  954. attributes["insecure-registries"] = string(insecureRegistries)
  955. } else {
  956. attributes["insecure-registries"] = "[]"
  957. }
  958. if daemon.configStore.Mirrors != nil {
  959. mirrors, err := json.Marshal(daemon.configStore.Mirrors)
  960. if err != nil {
  961. return err
  962. }
  963. attributes["registry-mirrors"] = string(mirrors)
  964. } else {
  965. attributes["registry-mirrors"] = "[]"
  966. }
  967. attributes["cluster-store"] = daemon.configStore.ClusterStore
  968. if daemon.configStore.ClusterOpts != nil {
  969. opts, err := json.Marshal(daemon.configStore.ClusterOpts)
  970. if err != nil {
  971. return err
  972. }
  973. attributes["cluster-store-opts"] = string(opts)
  974. } else {
  975. attributes["cluster-store-opts"] = "{}"
  976. }
  977. attributes["cluster-advertise"] = daemon.configStore.ClusterAdvertise
  978. if daemon.configStore.Labels != nil {
  979. labels, err := json.Marshal(daemon.configStore.Labels)
  980. if err != nil {
  981. return err
  982. }
  983. attributes["labels"] = string(labels)
  984. } else {
  985. attributes["labels"] = "[]"
  986. }
  987. attributes["max-concurrent-downloads"] = fmt.Sprintf("%d", *daemon.configStore.MaxConcurrentDownloads)
  988. attributes["max-concurrent-uploads"] = fmt.Sprintf("%d", *daemon.configStore.MaxConcurrentUploads)
  989. attributes["shutdown-timeout"] = fmt.Sprintf("%d", daemon.configStore.ShutdownTimeout)
  990. return nil
  991. }
  992. func (daemon *Daemon) reloadClusterDiscovery(config *Config) error {
  993. var err error
  994. newAdvertise := daemon.configStore.ClusterAdvertise
  995. newClusterStore := daemon.configStore.ClusterStore
  996. if config.IsValueSet("cluster-advertise") {
  997. if config.IsValueSet("cluster-store") {
  998. newClusterStore = config.ClusterStore
  999. }
  1000. newAdvertise, err = parseClusterAdvertiseSettings(newClusterStore, config.ClusterAdvertise)
  1001. if err != nil && err != errDiscoveryDisabled {
  1002. return err
  1003. }
  1004. }
  1005. if daemon.clusterProvider != nil {
  1006. if err := config.isSwarmCompatible(); err != nil {
  1007. return err
  1008. }
  1009. }
  1010. // check discovery modifications
  1011. if !modifiedDiscoverySettings(daemon.configStore, newAdvertise, newClusterStore, config.ClusterOpts) {
  1012. return nil
  1013. }
  1014. // enable discovery for the first time if it was not previously enabled
  1015. if daemon.discoveryWatcher == nil {
  1016. discoveryWatcher, err := initDiscovery(newClusterStore, newAdvertise, config.ClusterOpts)
  1017. if err != nil {
  1018. return fmt.Errorf("discovery initialization failed (%v)", err)
  1019. }
  1020. daemon.discoveryWatcher = discoveryWatcher
  1021. } else {
  1022. if err == errDiscoveryDisabled {
  1023. // disable discovery if it was previously enabled and it's disabled now
  1024. daemon.discoveryWatcher.Stop()
  1025. } else {
  1026. // reload discovery
  1027. if err = daemon.discoveryWatcher.Reload(config.ClusterStore, newAdvertise, config.ClusterOpts); err != nil {
  1028. return err
  1029. }
  1030. }
  1031. }
  1032. daemon.configStore.ClusterStore = newClusterStore
  1033. daemon.configStore.ClusterOpts = config.ClusterOpts
  1034. daemon.configStore.ClusterAdvertise = newAdvertise
  1035. if daemon.netController == nil {
  1036. return nil
  1037. }
  1038. netOptions, err := daemon.networkOptions(daemon.configStore, daemon.PluginStore, nil)
  1039. if err != nil {
  1040. logrus.WithError(err).Warnf("failed to get options with network controller")
  1041. return nil
  1042. }
  1043. err = daemon.netController.ReloadConfiguration(netOptions...)
  1044. if err != nil {
  1045. logrus.Warnf("Failed to reload configuration with network controller: %v", err)
  1046. }
  1047. return nil
  1048. }
  1049. func isBridgeNetworkDisabled(config *Config) bool {
  1050. return config.bridgeConfig.Iface == disableNetworkBridge
  1051. }
  1052. func (daemon *Daemon) networkOptions(dconfig *Config, pg plugingetter.PluginGetter, activeSandboxes map[string]interface{}) ([]nwconfig.Option, error) {
  1053. options := []nwconfig.Option{}
  1054. if dconfig == nil {
  1055. return options, nil
  1056. }
  1057. options = append(options, nwconfig.OptionExperimental(dconfig.Experimental))
  1058. options = append(options, nwconfig.OptionDataDir(dconfig.Root))
  1059. options = append(options, nwconfig.OptionExecRoot(dconfig.GetExecRoot()))
  1060. dd := runconfig.DefaultDaemonNetworkMode()
  1061. dn := runconfig.DefaultDaemonNetworkMode().NetworkName()
  1062. options = append(options, nwconfig.OptionDefaultDriver(string(dd)))
  1063. options = append(options, nwconfig.OptionDefaultNetwork(dn))
  1064. if strings.TrimSpace(dconfig.ClusterStore) != "" {
  1065. kv := strings.Split(dconfig.ClusterStore, "://")
  1066. if len(kv) != 2 {
  1067. return nil, errors.New("kv store daemon config must be of the form KV-PROVIDER://KV-URL")
  1068. }
  1069. options = append(options, nwconfig.OptionKVProvider(kv[0]))
  1070. options = append(options, nwconfig.OptionKVProviderURL(kv[1]))
  1071. }
  1072. if len(dconfig.ClusterOpts) > 0 {
  1073. options = append(options, nwconfig.OptionKVOpts(dconfig.ClusterOpts))
  1074. }
  1075. if daemon.discoveryWatcher != nil {
  1076. options = append(options, nwconfig.OptionDiscoveryWatcher(daemon.discoveryWatcher))
  1077. }
  1078. if dconfig.ClusterAdvertise != "" {
  1079. options = append(options, nwconfig.OptionDiscoveryAddress(dconfig.ClusterAdvertise))
  1080. }
  1081. options = append(options, nwconfig.OptionLabels(dconfig.Labels))
  1082. options = append(options, driverOptions(dconfig)...)
  1083. if daemon.configStore != nil && daemon.configStore.LiveRestoreEnabled && len(activeSandboxes) != 0 {
  1084. options = append(options, nwconfig.OptionActiveSandboxes(activeSandboxes))
  1085. }
  1086. if pg != nil {
  1087. options = append(options, nwconfig.OptionPluginGetter(pg))
  1088. }
  1089. return options, nil
  1090. }
  1091. func copyBlkioEntry(entries []*containerd.BlkioStatsEntry) []types.BlkioStatEntry {
  1092. out := make([]types.BlkioStatEntry, len(entries))
  1093. for i, re := range entries {
  1094. out[i] = types.BlkioStatEntry{
  1095. Major: re.Major,
  1096. Minor: re.Minor,
  1097. Op: re.Op,
  1098. Value: re.Value,
  1099. }
  1100. }
  1101. return out
  1102. }
  1103. // GetCluster returns the cluster
  1104. func (daemon *Daemon) GetCluster() Cluster {
  1105. return daemon.cluster
  1106. }
  1107. // SetCluster sets the cluster
  1108. func (daemon *Daemon) SetCluster(cluster Cluster) {
  1109. daemon.cluster = cluster
  1110. }
  1111. func (daemon *Daemon) pluginShutdown() {
  1112. manager := daemon.pluginManager
  1113. // Check for a valid manager object. In error conditions, daemon init can fail
  1114. // and shutdown called, before plugin manager is initialized.
  1115. if manager != nil {
  1116. manager.Shutdown()
  1117. }
  1118. }
  1119. // PluginManager returns current pluginManager associated with the daemon
  1120. func (daemon *Daemon) PluginManager() *plugin.Manager { // set up before daemon to avoid this method
  1121. return daemon.pluginManager
  1122. }
  1123. // PluginGetter returns current pluginStore associated with the daemon
  1124. func (daemon *Daemon) PluginGetter() *plugin.Store {
  1125. return daemon.PluginStore
  1126. }
  1127. // CreateDaemonRoot creates the root for the daemon
  1128. func CreateDaemonRoot(config *Config) error {
  1129. // get the canonical path to the Docker root directory
  1130. var realRoot string
  1131. if _, err := os.Stat(config.Root); err != nil && os.IsNotExist(err) {
  1132. realRoot = config.Root
  1133. } else {
  1134. realRoot, err = fileutils.ReadSymlinkedDirectory(config.Root)
  1135. if err != nil {
  1136. return fmt.Errorf("Unable to get the full path to root (%s): %s", config.Root, err)
  1137. }
  1138. }
  1139. uidMaps, gidMaps, err := setupRemappedRoot(config)
  1140. if err != nil {
  1141. return err
  1142. }
  1143. rootUID, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps)
  1144. if err != nil {
  1145. return err
  1146. }
  1147. if err := setupDaemonRoot(config, realRoot, rootUID, rootGID); err != nil {
  1148. return err
  1149. }
  1150. return nil
  1151. }