daemon.go 38 KB

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