daemon.go 41 KB

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