daemon.go 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635
  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. "fmt"
  9. "io"
  10. "io/ioutil"
  11. "net"
  12. "os"
  13. "path"
  14. "path/filepath"
  15. "runtime"
  16. "strings"
  17. "sync"
  18. "syscall"
  19. "time"
  20. "github.com/Sirupsen/logrus"
  21. containerd "github.com/docker/containerd/api/grpc/types"
  22. "github.com/docker/docker/api"
  23. "github.com/docker/docker/builder"
  24. "github.com/docker/docker/container"
  25. "github.com/docker/docker/daemon/events"
  26. "github.com/docker/docker/daemon/exec"
  27. "github.com/docker/docker/errors"
  28. "github.com/docker/engine-api/types"
  29. containertypes "github.com/docker/engine-api/types/container"
  30. eventtypes "github.com/docker/engine-api/types/events"
  31. "github.com/docker/engine-api/types/filters"
  32. networktypes "github.com/docker/engine-api/types/network"
  33. registrytypes "github.com/docker/engine-api/types/registry"
  34. "github.com/docker/engine-api/types/strslice"
  35. // register graph drivers
  36. _ "github.com/docker/docker/daemon/graphdriver/register"
  37. "github.com/docker/docker/daemon/logger"
  38. "github.com/docker/docker/daemon/network"
  39. dmetadata "github.com/docker/docker/distribution/metadata"
  40. "github.com/docker/docker/distribution/xfer"
  41. "github.com/docker/docker/dockerversion"
  42. "github.com/docker/docker/image"
  43. "github.com/docker/docker/image/tarexport"
  44. "github.com/docker/docker/layer"
  45. "github.com/docker/docker/libcontainerd"
  46. "github.com/docker/docker/migrate/v1"
  47. "github.com/docker/docker/pkg/archive"
  48. "github.com/docker/docker/pkg/fileutils"
  49. "github.com/docker/docker/pkg/graphdb"
  50. "github.com/docker/docker/pkg/idtools"
  51. "github.com/docker/docker/pkg/namesgenerator"
  52. "github.com/docker/docker/pkg/progress"
  53. "github.com/docker/docker/pkg/registrar"
  54. "github.com/docker/docker/pkg/signal"
  55. "github.com/docker/docker/pkg/streamformatter"
  56. "github.com/docker/docker/pkg/stringid"
  57. "github.com/docker/docker/pkg/sysinfo"
  58. "github.com/docker/docker/pkg/system"
  59. "github.com/docker/docker/pkg/truncindex"
  60. "github.com/docker/docker/reference"
  61. "github.com/docker/docker/registry"
  62. "github.com/docker/docker/runconfig"
  63. "github.com/docker/docker/utils"
  64. volumedrivers "github.com/docker/docker/volume/drivers"
  65. "github.com/docker/docker/volume/local"
  66. "github.com/docker/docker/volume/store"
  67. "github.com/docker/go-connections/nat"
  68. "github.com/docker/libnetwork"
  69. nwconfig "github.com/docker/libnetwork/config"
  70. "github.com/docker/libtrust"
  71. "golang.org/x/net/context"
  72. )
  73. const (
  74. // maxDownloadConcurrency is the maximum number of downloads that
  75. // may take place at a time for each pull.
  76. maxDownloadConcurrency = 3
  77. // maxUploadConcurrency is the maximum number of uploads that
  78. // may take place at a time for each push.
  79. maxUploadConcurrency = 5
  80. )
  81. var (
  82. validContainerNameChars = utils.RestrictedNameChars
  83. validContainerNamePattern = utils.RestrictedNamePattern
  84. errSystemNotSupported = fmt.Errorf("The Docker daemon is not supported on this platform.")
  85. )
  86. // ErrImageDoesNotExist is error returned when no image can be found for a reference.
  87. type ErrImageDoesNotExist struct {
  88. RefOrID string
  89. }
  90. func (e ErrImageDoesNotExist) Error() string {
  91. return fmt.Sprintf("no such id: %s", e.RefOrID)
  92. }
  93. // Daemon holds information about the Docker daemon.
  94. type Daemon struct {
  95. ID string
  96. repository string
  97. containers container.Store
  98. execCommands *exec.Store
  99. referenceStore reference.Store
  100. downloadManager *xfer.LayerDownloadManager
  101. uploadManager *xfer.LayerUploadManager
  102. distributionMetadataStore dmetadata.Store
  103. trustKey libtrust.PrivateKey
  104. idIndex *truncindex.TruncIndex
  105. configStore *Config
  106. statsCollector *statsCollector
  107. defaultLogConfig containertypes.LogConfig
  108. RegistryService *registry.Service
  109. EventsService *events.Events
  110. netController libnetwork.NetworkController
  111. volumes *store.VolumeStore
  112. discoveryWatcher discoveryReloader
  113. root string
  114. seccompEnabled bool
  115. shutdown bool
  116. uidMaps []idtools.IDMap
  117. gidMaps []idtools.IDMap
  118. layerStore layer.Store
  119. imageStore image.Store
  120. nameIndex *registrar.Registrar
  121. linkIndex *linkIndex
  122. containerd libcontainerd.Client
  123. defaultIsolation containertypes.Isolation // Default isolation mode on Windows
  124. }
  125. // GetContainer looks for a container using the provided information, which could be
  126. // one of the following inputs from the caller:
  127. // - A full container ID, which will exact match a container in daemon's list
  128. // - A container name, which will only exact match via the GetByName() function
  129. // - A partial container ID prefix (e.g. short ID) of any length that is
  130. // unique enough to only return a single container object
  131. // If none of these searches succeed, an error is returned
  132. func (daemon *Daemon) GetContainer(prefixOrName string) (*container.Container, error) {
  133. if containerByID := daemon.containers.Get(prefixOrName); containerByID != nil {
  134. // prefix is an exact match to a full container ID
  135. return containerByID, nil
  136. }
  137. // GetByName will match only an exact name provided; we ignore errors
  138. if containerByName, _ := daemon.GetByName(prefixOrName); containerByName != nil {
  139. // prefix is an exact match to a full container Name
  140. return containerByName, nil
  141. }
  142. containerID, indexError := daemon.idIndex.Get(prefixOrName)
  143. if indexError != nil {
  144. // When truncindex defines an error type, use that instead
  145. if indexError == truncindex.ErrNotExist {
  146. err := fmt.Errorf("No such container: %s", prefixOrName)
  147. return nil, errors.NewRequestNotFoundError(err)
  148. }
  149. return nil, indexError
  150. }
  151. return daemon.containers.Get(containerID), nil
  152. }
  153. // Exists returns a true if a container of the specified ID or name exists,
  154. // false otherwise.
  155. func (daemon *Daemon) Exists(id string) bool {
  156. c, _ := daemon.GetContainer(id)
  157. return c != nil
  158. }
  159. // IsPaused returns a bool indicating if the specified container is paused.
  160. func (daemon *Daemon) IsPaused(id string) bool {
  161. c, _ := daemon.GetContainer(id)
  162. return c.State.IsPaused()
  163. }
  164. func (daemon *Daemon) containerRoot(id string) string {
  165. return filepath.Join(daemon.repository, id)
  166. }
  167. // Load reads the contents of a container from disk
  168. // This is typically done at startup.
  169. func (daemon *Daemon) load(id string) (*container.Container, error) {
  170. container := daemon.newBaseContainer(id)
  171. if err := container.FromDisk(); err != nil {
  172. return nil, err
  173. }
  174. if container.ID != id {
  175. return container, fmt.Errorf("Container %s is stored at %s", container.ID, id)
  176. }
  177. return container, nil
  178. }
  179. func (daemon *Daemon) registerName(container *container.Container) error {
  180. if daemon.Exists(container.ID) {
  181. return fmt.Errorf("Container is already loaded")
  182. }
  183. if err := validateID(container.ID); err != nil {
  184. return err
  185. }
  186. if container.Name == "" {
  187. name, err := daemon.generateNewName(container.ID)
  188. if err != nil {
  189. return err
  190. }
  191. container.Name = name
  192. if err := container.ToDiskLocking(); err != nil {
  193. logrus.Errorf("Error saving container name to disk: %v", err)
  194. }
  195. }
  196. return daemon.nameIndex.Reserve(container.Name, container.ID)
  197. }
  198. // Register makes a container object usable by the daemon as <container.ID>
  199. func (daemon *Daemon) Register(c *container.Container) error {
  200. // Attach to stdout and stderr
  201. if c.Config.OpenStdin {
  202. c.NewInputPipes()
  203. } else {
  204. c.NewNopInputPipe()
  205. }
  206. daemon.containers.Add(c.ID, c)
  207. daemon.idIndex.Add(c.ID)
  208. return nil
  209. }
  210. func (daemon *Daemon) restore() error {
  211. var (
  212. debug = utils.IsDebugEnabled()
  213. currentDriver = daemon.GraphDriverName()
  214. containers = make(map[string]*container.Container)
  215. )
  216. if !debug {
  217. logrus.Info("Loading containers: start.")
  218. }
  219. dir, err := ioutil.ReadDir(daemon.repository)
  220. if err != nil {
  221. return err
  222. }
  223. for _, v := range dir {
  224. id := v.Name()
  225. container, err := daemon.load(id)
  226. if !debug && logrus.GetLevel() == logrus.InfoLevel {
  227. fmt.Print(".")
  228. }
  229. if err != nil {
  230. logrus.Errorf("Failed to load container %v: %v", id, err)
  231. continue
  232. }
  233. // Ignore the container if it does not support the current driver being used by the graph
  234. if (container.Driver == "" && currentDriver == "aufs") || container.Driver == currentDriver {
  235. rwlayer, err := daemon.layerStore.GetRWLayer(container.ID)
  236. if err != nil {
  237. logrus.Errorf("Failed to load container mount %v: %v", id, err)
  238. continue
  239. }
  240. container.RWLayer = rwlayer
  241. logrus.Debugf("Loaded container %v", container.ID)
  242. containers[container.ID] = container
  243. } else {
  244. logrus.Debugf("Cannot load container %s because it was created with another graph driver.", container.ID)
  245. }
  246. }
  247. var migrateLegacyLinks bool
  248. restartContainers := make(map[*container.Container]chan struct{})
  249. for _, c := range containers {
  250. if err := daemon.registerName(c); err != nil {
  251. logrus.Errorf("Failed to register container %s: %s", c.ID, err)
  252. continue
  253. }
  254. if err := daemon.Register(c); err != nil {
  255. logrus.Errorf("Failed to register container %s: %s", c.ID, err)
  256. continue
  257. }
  258. }
  259. var wg sync.WaitGroup
  260. var mapLock sync.Mutex
  261. for _, c := range containers {
  262. wg.Add(1)
  263. go func(c *container.Container) {
  264. defer wg.Done()
  265. rm := c.RestartManager(false)
  266. if c.IsRunning() || c.IsPaused() {
  267. // Fix activityCount such that graph mounts can be unmounted later
  268. if err := daemon.layerStore.ReinitRWLayer(c.RWLayer); err != nil {
  269. logrus.Errorf("Failed to ReinitRWLayer for %s due to %s", c.ID, err)
  270. return
  271. }
  272. if err := daemon.containerd.Restore(c.ID, libcontainerd.WithRestartManager(rm)); err != nil {
  273. logrus.Errorf("Failed to restore with containerd: %q", err)
  274. return
  275. }
  276. }
  277. // fixme: only if not running
  278. // get list of containers we need to restart
  279. if daemon.configStore.AutoRestart && !c.IsRunning() && !c.IsPaused() && c.ShouldRestart() {
  280. mapLock.Lock()
  281. restartContainers[c] = make(chan struct{})
  282. mapLock.Unlock()
  283. }
  284. // if c.hostConfig.Links is nil (not just empty), then it is using the old sqlite links and needs to be migrated
  285. if c.HostConfig != nil && c.HostConfig.Links == nil {
  286. migrateLegacyLinks = true
  287. }
  288. }(c)
  289. }
  290. wg.Wait()
  291. // migrate any legacy links from sqlite
  292. linkdbFile := filepath.Join(daemon.root, "linkgraph.db")
  293. var legacyLinkDB *graphdb.Database
  294. if migrateLegacyLinks {
  295. legacyLinkDB, err = graphdb.NewSqliteConn(linkdbFile)
  296. if err != nil {
  297. return fmt.Errorf("error connecting to legacy link graph DB %s, container links may be lost: %v", linkdbFile, err)
  298. }
  299. defer legacyLinkDB.Close()
  300. }
  301. // Now that all the containers are registered, register the links
  302. for _, c := range containers {
  303. if migrateLegacyLinks {
  304. if err := daemon.migrateLegacySqliteLinks(legacyLinkDB, c); err != nil {
  305. return err
  306. }
  307. }
  308. if err := daemon.registerLinks(c, c.HostConfig); err != nil {
  309. logrus.Errorf("failed to register link for container %s: %v", c.ID, err)
  310. }
  311. }
  312. group := sync.WaitGroup{}
  313. for c, notifier := range restartContainers {
  314. group.Add(1)
  315. go func(c *container.Container, chNotify chan struct{}) {
  316. defer group.Done()
  317. logrus.Debugf("Starting container %s", c.ID)
  318. // ignore errors here as this is a best effort to wait for children to be
  319. // running before we try to start the container
  320. children := daemon.children(c)
  321. timeout := time.After(5 * time.Second)
  322. for _, child := range children {
  323. if notifier, exists := restartContainers[child]; exists {
  324. select {
  325. case <-notifier:
  326. case <-timeout:
  327. }
  328. }
  329. }
  330. if err := daemon.containerStart(c); err != nil {
  331. logrus.Errorf("Failed to start container %s: %s", c.ID, err)
  332. }
  333. close(chNotify)
  334. }(c, notifier)
  335. }
  336. group.Wait()
  337. // any containers that were started above would already have had this done,
  338. // however we need to now prepare the mountpoints for the rest of the containers as well.
  339. // This shouldn't cause any issue running on the containers that already had this run.
  340. // This must be run after any containers with a restart policy so that containerized plugins
  341. // can have a chance to be running before we try to initialize them.
  342. for _, c := range containers {
  343. // if the container has restart policy, do not
  344. // prepare the mountpoints since it has been done on restarting.
  345. // This is to speed up the daemon start when a restart container
  346. // has a volume and the volume dirver is not available.
  347. if _, ok := restartContainers[c]; ok {
  348. continue
  349. }
  350. group.Add(1)
  351. go func(c *container.Container) {
  352. defer group.Done()
  353. if err := daemon.prepareMountPoints(c); err != nil {
  354. logrus.Error(err)
  355. }
  356. }(c)
  357. }
  358. group.Wait()
  359. if !debug {
  360. if logrus.GetLevel() == logrus.InfoLevel {
  361. fmt.Println()
  362. }
  363. logrus.Info("Loading containers: done.")
  364. }
  365. return nil
  366. }
  367. func (daemon *Daemon) mergeAndVerifyConfig(config *containertypes.Config, img *image.Image) error {
  368. if img != nil && img.Config != nil {
  369. if err := merge(config, img.Config); err != nil {
  370. return err
  371. }
  372. }
  373. if len(config.Entrypoint) == 0 && len(config.Cmd) == 0 {
  374. return fmt.Errorf("No command specified")
  375. }
  376. return nil
  377. }
  378. func (daemon *Daemon) generateIDAndName(name string) (string, string, error) {
  379. var (
  380. err error
  381. id = stringid.GenerateNonCryptoID()
  382. )
  383. if name == "" {
  384. if name, err = daemon.generateNewName(id); err != nil {
  385. return "", "", err
  386. }
  387. return id, name, nil
  388. }
  389. if name, err = daemon.reserveName(id, name); err != nil {
  390. return "", "", err
  391. }
  392. return id, name, nil
  393. }
  394. func (daemon *Daemon) reserveName(id, name string) (string, error) {
  395. if !validContainerNamePattern.MatchString(name) {
  396. return "", fmt.Errorf("Invalid container name (%s), only %s are allowed", name, validContainerNameChars)
  397. }
  398. if name[0] != '/' {
  399. name = "/" + name
  400. }
  401. if err := daemon.nameIndex.Reserve(name, id); err != nil {
  402. if err == registrar.ErrNameReserved {
  403. id, err := daemon.nameIndex.Get(name)
  404. if err != nil {
  405. logrus.Errorf("got unexpected error while looking up reserved name: %v", err)
  406. return "", err
  407. }
  408. return "", fmt.Errorf("Conflict. The name %q is already in use by container %s. You have to remove (or rename) that container to be able to reuse that name.", name, id)
  409. }
  410. return "", fmt.Errorf("error reserving name: %s, error: %v", name, err)
  411. }
  412. return name, nil
  413. }
  414. func (daemon *Daemon) releaseName(name string) {
  415. daemon.nameIndex.Release(name)
  416. }
  417. func (daemon *Daemon) generateNewName(id string) (string, error) {
  418. var name string
  419. for i := 0; i < 6; i++ {
  420. name = namesgenerator.GetRandomName(i)
  421. if name[0] != '/' {
  422. name = "/" + name
  423. }
  424. if err := daemon.nameIndex.Reserve(name, id); err != nil {
  425. if err == registrar.ErrNameReserved {
  426. continue
  427. }
  428. return "", err
  429. }
  430. return name, nil
  431. }
  432. name = "/" + stringid.TruncateID(id)
  433. if err := daemon.nameIndex.Reserve(name, id); err != nil {
  434. return "", err
  435. }
  436. return name, nil
  437. }
  438. func (daemon *Daemon) generateHostname(id string, config *containertypes.Config) {
  439. // Generate default hostname
  440. if config.Hostname == "" {
  441. config.Hostname = id[:12]
  442. }
  443. }
  444. func (daemon *Daemon) getEntrypointAndArgs(configEntrypoint strslice.StrSlice, configCmd strslice.StrSlice) (string, []string) {
  445. if len(configEntrypoint) != 0 {
  446. return configEntrypoint[0], append(configEntrypoint[1:], configCmd...)
  447. }
  448. return configCmd[0], configCmd[1:]
  449. }
  450. func (daemon *Daemon) newContainer(name string, config *containertypes.Config, imgID image.ID) (*container.Container, error) {
  451. var (
  452. id string
  453. err error
  454. noExplicitName = name == ""
  455. )
  456. id, name, err = daemon.generateIDAndName(name)
  457. if err != nil {
  458. return nil, err
  459. }
  460. daemon.generateHostname(id, config)
  461. entrypoint, args := daemon.getEntrypointAndArgs(config.Entrypoint, config.Cmd)
  462. base := daemon.newBaseContainer(id)
  463. base.Created = time.Now().UTC()
  464. base.Path = entrypoint
  465. base.Args = args //FIXME: de-duplicate from config
  466. base.Config = config
  467. base.HostConfig = &containertypes.HostConfig{}
  468. base.ImageID = imgID
  469. base.NetworkSettings = &network.Settings{IsAnonymousEndpoint: noExplicitName}
  470. base.Name = name
  471. base.Driver = daemon.GraphDriverName()
  472. return base, err
  473. }
  474. // GetByName returns a container given a name.
  475. func (daemon *Daemon) GetByName(name string) (*container.Container, error) {
  476. fullName := name
  477. if name[0] != '/' {
  478. fullName = "/" + name
  479. }
  480. id, err := daemon.nameIndex.Get(fullName)
  481. if err != nil {
  482. return nil, fmt.Errorf("Could not find entity for %s", name)
  483. }
  484. e := daemon.containers.Get(id)
  485. if e == nil {
  486. return nil, fmt.Errorf("Could not find container for entity id %s", id)
  487. }
  488. return e, nil
  489. }
  490. // SubscribeToEvents returns the currently record of events, a channel to stream new events from, and a function to cancel the stream of events.
  491. func (daemon *Daemon) SubscribeToEvents(since, sinceNano int64, filter filters.Args) ([]eventtypes.Message, chan interface{}) {
  492. ef := events.NewFilter(filter)
  493. return daemon.EventsService.SubscribeTopic(since, sinceNano, ef)
  494. }
  495. // UnsubscribeFromEvents stops the event subscription for a client by closing the
  496. // channel where the daemon sends events to.
  497. func (daemon *Daemon) UnsubscribeFromEvents(listener chan interface{}) {
  498. daemon.EventsService.Evict(listener)
  499. }
  500. // GetLabels for a container or image id
  501. func (daemon *Daemon) GetLabels(id string) map[string]string {
  502. // TODO: TestCase
  503. container := daemon.containers.Get(id)
  504. if container != nil {
  505. return container.Config.Labels
  506. }
  507. img, err := daemon.GetImage(id)
  508. if err == nil {
  509. return img.ContainerConfig.Labels
  510. }
  511. return nil
  512. }
  513. func (daemon *Daemon) children(c *container.Container) map[string]*container.Container {
  514. return daemon.linkIndex.children(c)
  515. }
  516. // parents returns the names of the parent containers of the container
  517. // with the given name.
  518. func (daemon *Daemon) parents(c *container.Container) map[string]*container.Container {
  519. return daemon.linkIndex.parents(c)
  520. }
  521. func (daemon *Daemon) registerLink(parent, child *container.Container, alias string) error {
  522. fullName := path.Join(parent.Name, alias)
  523. if err := daemon.nameIndex.Reserve(fullName, child.ID); err != nil {
  524. if err == registrar.ErrNameReserved {
  525. logrus.Warnf("error registering link for %s, to %s, as alias %s, ignoring: %v", parent.ID, child.ID, alias, err)
  526. return nil
  527. }
  528. return err
  529. }
  530. daemon.linkIndex.link(parent, child, fullName)
  531. return nil
  532. }
  533. // NewDaemon sets up everything for the daemon to be able to service
  534. // requests from the webserver.
  535. func NewDaemon(config *Config, registryService *registry.Service, containerdRemote libcontainerd.Remote) (daemon *Daemon, err error) {
  536. setDefaultMtu(config)
  537. // Ensure we have compatible and valid configuration options
  538. if err := verifyDaemonSettings(config); err != nil {
  539. return nil, err
  540. }
  541. // Do we have a disabled network?
  542. config.DisableBridge = isBridgeNetworkDisabled(config)
  543. // Verify the platform is supported as a daemon
  544. if !platformSupported {
  545. return nil, errSystemNotSupported
  546. }
  547. // Validate platform-specific requirements
  548. if err := checkSystem(); err != nil {
  549. return nil, err
  550. }
  551. // set up SIGUSR1 handler on Unix-like systems, or a Win32 global event
  552. // on Windows to dump Go routine stacks
  553. setupDumpStackTrap()
  554. uidMaps, gidMaps, err := setupRemappedRoot(config)
  555. if err != nil {
  556. return nil, err
  557. }
  558. rootUID, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps)
  559. if err != nil {
  560. return nil, err
  561. }
  562. // get the canonical path to the Docker root directory
  563. var realRoot string
  564. if _, err := os.Stat(config.Root); err != nil && os.IsNotExist(err) {
  565. realRoot = config.Root
  566. } else {
  567. realRoot, err = fileutils.ReadSymlinkedDirectory(config.Root)
  568. if err != nil {
  569. return nil, fmt.Errorf("Unable to get the full path to root (%s): %s", config.Root, err)
  570. }
  571. }
  572. if err = setupDaemonRoot(config, realRoot, rootUID, rootGID); err != nil {
  573. return nil, err
  574. }
  575. // set up the tmpDir to use a canonical path
  576. tmp, err := tempDir(config.Root, rootUID, rootGID)
  577. if err != nil {
  578. return nil, fmt.Errorf("Unable to get the TempDir under %s: %s", config.Root, err)
  579. }
  580. realTmp, err := fileutils.ReadSymlinkedDirectory(tmp)
  581. if err != nil {
  582. return nil, fmt.Errorf("Unable to get the full path to the TempDir (%s): %s", tmp, err)
  583. }
  584. os.Setenv("TMPDIR", realTmp)
  585. d := &Daemon{configStore: config}
  586. // Ensure the daemon is properly shutdown if there is a failure during
  587. // initialization
  588. defer func() {
  589. if err != nil {
  590. if err := d.Shutdown(); err != nil {
  591. logrus.Error(err)
  592. }
  593. }
  594. }()
  595. // Set the default isolation mode (only applicable on Windows)
  596. if err := d.setDefaultIsolation(); err != nil {
  597. return nil, fmt.Errorf("error setting default isolation mode: %v", err)
  598. }
  599. // Verify logging driver type
  600. if config.LogConfig.Type != "none" {
  601. if _, err := logger.GetLogDriver(config.LogConfig.Type); err != nil {
  602. return nil, fmt.Errorf("error finding the logging driver: %v", err)
  603. }
  604. }
  605. logrus.Debugf("Using default logging driver %s", config.LogConfig.Type)
  606. if err := configureMaxThreads(config); err != nil {
  607. logrus.Warnf("Failed to configure golang's threads limit: %v", err)
  608. }
  609. installDefaultAppArmorProfile()
  610. daemonRepo := filepath.Join(config.Root, "containers")
  611. if err := idtools.MkdirAllAs(daemonRepo, 0700, rootUID, rootGID); err != nil && !os.IsExist(err) {
  612. return nil, err
  613. }
  614. driverName := os.Getenv("DOCKER_DRIVER")
  615. if driverName == "" {
  616. driverName = config.GraphDriver
  617. }
  618. d.layerStore, err = layer.NewStoreFromOptions(layer.StoreOptions{
  619. StorePath: config.Root,
  620. MetadataStorePathTemplate: filepath.Join(config.Root, "image", "%s", "layerdb"),
  621. GraphDriver: driverName,
  622. GraphDriverOptions: config.GraphOptions,
  623. UIDMaps: uidMaps,
  624. GIDMaps: gidMaps,
  625. })
  626. if err != nil {
  627. return nil, err
  628. }
  629. graphDriver := d.layerStore.DriverName()
  630. imageRoot := filepath.Join(config.Root, "image", graphDriver)
  631. // Configure and validate the kernels security support
  632. if err := configureKernelSecuritySupport(config, graphDriver); err != nil {
  633. return nil, err
  634. }
  635. d.downloadManager = xfer.NewLayerDownloadManager(d.layerStore, maxDownloadConcurrency)
  636. d.uploadManager = xfer.NewLayerUploadManager(maxUploadConcurrency)
  637. ifs, err := image.NewFSStoreBackend(filepath.Join(imageRoot, "imagedb"))
  638. if err != nil {
  639. return nil, err
  640. }
  641. d.imageStore, err = image.NewImageStore(ifs, d.layerStore)
  642. if err != nil {
  643. return nil, err
  644. }
  645. // Configure the volumes driver
  646. volStore, err := configureVolumes(config, rootUID, rootGID)
  647. if err != nil {
  648. return nil, err
  649. }
  650. trustKey, err := api.LoadOrCreateTrustKey(config.TrustKeyPath)
  651. if err != nil {
  652. return nil, err
  653. }
  654. trustDir := filepath.Join(config.Root, "trust")
  655. if err := system.MkdirAll(trustDir, 0700); err != nil {
  656. return nil, err
  657. }
  658. distributionMetadataStore, err := dmetadata.NewFSMetadataStore(filepath.Join(imageRoot, "distribution"))
  659. if err != nil {
  660. return nil, err
  661. }
  662. eventsService := events.New()
  663. referenceStore, err := reference.NewReferenceStore(filepath.Join(imageRoot, "repositories.json"))
  664. if err != nil {
  665. return nil, fmt.Errorf("Couldn't create Tag store repositories: %s", err)
  666. }
  667. if err := restoreCustomImage(d.imageStore, d.layerStore, referenceStore); err != nil {
  668. return nil, fmt.Errorf("Couldn't restore custom images: %s", err)
  669. }
  670. migrationStart := time.Now()
  671. if err := v1.Migrate(config.Root, graphDriver, d.layerStore, d.imageStore, referenceStore, distributionMetadataStore); err != nil {
  672. 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)
  673. }
  674. logrus.Infof("Graph migration to content-addressability took %.2f seconds", time.Since(migrationStart).Seconds())
  675. // Discovery is only enabled when the daemon is launched with an address to advertise. When
  676. // initialized, the daemon is registered and we can store the discovery backend as its read-only
  677. if err := d.initDiscovery(config); err != nil {
  678. return nil, err
  679. }
  680. d.netController, err = d.initNetworkController(config)
  681. if err != nil {
  682. return nil, fmt.Errorf("Error initializing network controller: %v", err)
  683. }
  684. sysInfo := sysinfo.New(false)
  685. // Check if Devices cgroup is mounted, it is hard requirement for container security,
  686. // on Linux/FreeBSD.
  687. if runtime.GOOS != "windows" && !sysInfo.CgroupDevicesEnabled {
  688. return nil, fmt.Errorf("Devices cgroup isn't mounted")
  689. }
  690. d.ID = trustKey.PublicKey().KeyID()
  691. d.repository = daemonRepo
  692. d.containers = container.NewMemoryStore()
  693. d.execCommands = exec.NewStore()
  694. d.referenceStore = referenceStore
  695. d.distributionMetadataStore = distributionMetadataStore
  696. d.trustKey = trustKey
  697. d.idIndex = truncindex.NewTruncIndex([]string{})
  698. d.statsCollector = d.newStatsCollector(1 * time.Second)
  699. d.defaultLogConfig = containertypes.LogConfig{
  700. Type: config.LogConfig.Type,
  701. Config: config.LogConfig.Config,
  702. }
  703. d.RegistryService = registryService
  704. d.EventsService = eventsService
  705. d.volumes = volStore
  706. d.root = config.Root
  707. d.uidMaps = uidMaps
  708. d.gidMaps = gidMaps
  709. d.seccompEnabled = sysInfo.Seccomp
  710. d.nameIndex = registrar.NewRegistrar()
  711. d.linkIndex = newLinkIndex()
  712. go d.execCommandGC()
  713. d.containerd, err = containerdRemote.Client(d)
  714. if err != nil {
  715. return nil, err
  716. }
  717. if err := d.restore(); err != nil {
  718. return nil, err
  719. }
  720. return d, nil
  721. }
  722. func (daemon *Daemon) shutdownContainer(c *container.Container) error {
  723. // TODO(windows): Handle docker restart with paused containers
  724. if c.IsPaused() {
  725. // To terminate a process in freezer cgroup, we should send
  726. // SIGTERM to this process then unfreeze it, and the process will
  727. // force to terminate immediately.
  728. logrus.Debugf("Found container %s is paused, sending SIGTERM before unpause it", c.ID)
  729. sig, ok := signal.SignalMap["TERM"]
  730. if !ok {
  731. return fmt.Errorf("System doesn not support SIGTERM")
  732. }
  733. if err := daemon.kill(c, int(sig)); err != nil {
  734. return fmt.Errorf("sending SIGTERM to container %s with error: %v", c.ID, err)
  735. }
  736. if err := daemon.containerUnpause(c); err != nil {
  737. return fmt.Errorf("Failed to unpause container %s with error: %v", c.ID, err)
  738. }
  739. if _, err := c.WaitStop(10 * time.Second); err != nil {
  740. logrus.Debugf("container %s failed to exit in 10 second of SIGTERM, sending SIGKILL to force", c.ID)
  741. sig, ok := signal.SignalMap["KILL"]
  742. if !ok {
  743. return fmt.Errorf("System does not support SIGKILL")
  744. }
  745. if err := daemon.kill(c, int(sig)); err != nil {
  746. logrus.Errorf("Failed to SIGKILL container %s", c.ID)
  747. }
  748. c.WaitStop(-1 * time.Second)
  749. return err
  750. }
  751. }
  752. // If container failed to exit in 10 seconds of SIGTERM, then using the force
  753. if err := daemon.containerStop(c, 10); err != nil {
  754. return fmt.Errorf("Stop container %s with error: %v", c.ID, err)
  755. }
  756. c.WaitStop(-1 * time.Second)
  757. return nil
  758. }
  759. // Shutdown stops the daemon.
  760. func (daemon *Daemon) Shutdown() error {
  761. daemon.shutdown = true
  762. if daemon.containers != nil {
  763. logrus.Debug("starting clean shutdown of all containers...")
  764. daemon.containers.ApplyAll(func(c *container.Container) {
  765. if !c.IsRunning() {
  766. return
  767. }
  768. logrus.Debugf("stopping %s", c.ID)
  769. if err := daemon.shutdownContainer(c); err != nil {
  770. logrus.Errorf("Stop container error: %v", err)
  771. return
  772. }
  773. if mountid, err := daemon.layerStore.GetMountID(c.ID); err == nil {
  774. daemon.cleanupMountsByID(mountid)
  775. }
  776. logrus.Debugf("container stopped %s", c.ID)
  777. })
  778. }
  779. // trigger libnetwork Stop only if it's initialized
  780. if daemon.netController != nil {
  781. daemon.netController.Stop()
  782. }
  783. if daemon.layerStore != nil {
  784. if err := daemon.layerStore.Cleanup(); err != nil {
  785. logrus.Errorf("Error during layer Store.Cleanup(): %v", err)
  786. }
  787. }
  788. if err := daemon.cleanupMounts(); err != nil {
  789. return err
  790. }
  791. return nil
  792. }
  793. // Mount sets container.BaseFS
  794. // (is it not set coming in? why is it unset?)
  795. func (daemon *Daemon) Mount(container *container.Container) error {
  796. dir, err := container.RWLayer.Mount(container.GetMountLabel())
  797. if err != nil {
  798. return err
  799. }
  800. logrus.Debugf("container mounted via layerStore: %v", dir)
  801. if container.BaseFS != dir {
  802. // The mount path reported by the graph driver should always be trusted on Windows, since the
  803. // volume path for a given mounted layer may change over time. This should only be an error
  804. // on non-Windows operating systems.
  805. if container.BaseFS != "" && runtime.GOOS != "windows" {
  806. daemon.Unmount(container)
  807. return fmt.Errorf("Error: driver %s is returning inconsistent paths for container %s ('%s' then '%s')",
  808. daemon.GraphDriverName(), container.ID, container.BaseFS, dir)
  809. }
  810. }
  811. container.BaseFS = dir // TODO: combine these fields
  812. return nil
  813. }
  814. // Unmount unsets the container base filesystem
  815. func (daemon *Daemon) Unmount(container *container.Container) error {
  816. if err := container.RWLayer.Unmount(); err != nil {
  817. logrus.Errorf("Error unmounting container %s: %s", container.ID, err)
  818. return err
  819. }
  820. return nil
  821. }
  822. func (daemon *Daemon) kill(c *container.Container, sig int) error {
  823. return daemon.containerd.Signal(c.ID, sig)
  824. }
  825. func (daemon *Daemon) subscribeToContainerStats(c *container.Container) chan interface{} {
  826. return daemon.statsCollector.collect(c)
  827. }
  828. func (daemon *Daemon) unsubscribeToContainerStats(c *container.Container, ch chan interface{}) {
  829. daemon.statsCollector.unsubscribe(c, ch)
  830. }
  831. func (daemon *Daemon) changes(container *container.Container) ([]archive.Change, error) {
  832. return container.RWLayer.Changes()
  833. }
  834. func writeDistributionProgress(cancelFunc func(), outStream io.Writer, progressChan <-chan progress.Progress) {
  835. progressOutput := streamformatter.NewJSONStreamFormatter().NewProgressOutput(outStream, false)
  836. operationCancelled := false
  837. for prog := range progressChan {
  838. if err := progressOutput.WriteProgress(prog); err != nil && !operationCancelled {
  839. // don't log broken pipe errors as this is the normal case when a client aborts
  840. if isBrokenPipe(err) {
  841. logrus.Info("Pull session cancelled")
  842. } else {
  843. logrus.Errorf("error writing progress to client: %v", err)
  844. }
  845. cancelFunc()
  846. operationCancelled = true
  847. // Don't return, because we need to continue draining
  848. // progressChan until it's closed to avoid a deadlock.
  849. }
  850. }
  851. }
  852. func isBrokenPipe(e error) bool {
  853. if netErr, ok := e.(*net.OpError); ok {
  854. e = netErr.Err
  855. if sysErr, ok := netErr.Err.(*os.SyscallError); ok {
  856. e = sysErr.Err
  857. }
  858. }
  859. return e == syscall.EPIPE
  860. }
  861. // ExportImage exports a list of images to the given output stream. The
  862. // exported images are archived into a tar when written to the output
  863. // stream. All images with the given tag and all versions containing
  864. // the same tag are exported. names is the set of tags to export, and
  865. // outStream is the writer which the images are written to.
  866. func (daemon *Daemon) ExportImage(names []string, outStream io.Writer) error {
  867. imageExporter := tarexport.NewTarExporter(daemon.imageStore, daemon.layerStore, daemon.referenceStore)
  868. return imageExporter.Save(names, outStream)
  869. }
  870. // LookupImage looks up an image by name and returns it as an ImageInspect
  871. // structure.
  872. func (daemon *Daemon) LookupImage(name string) (*types.ImageInspect, error) {
  873. img, err := daemon.GetImage(name)
  874. if err != nil {
  875. return nil, fmt.Errorf("No such image: %s", name)
  876. }
  877. refs := daemon.referenceStore.References(img.ID())
  878. repoTags := []string{}
  879. repoDigests := []string{}
  880. for _, ref := range refs {
  881. switch ref.(type) {
  882. case reference.NamedTagged:
  883. repoTags = append(repoTags, ref.String())
  884. case reference.Canonical:
  885. repoDigests = append(repoDigests, ref.String())
  886. }
  887. }
  888. var size int64
  889. var layerMetadata map[string]string
  890. layerID := img.RootFS.ChainID()
  891. if layerID != "" {
  892. l, err := daemon.layerStore.Get(layerID)
  893. if err != nil {
  894. return nil, err
  895. }
  896. defer layer.ReleaseAndLog(daemon.layerStore, l)
  897. size, err = l.Size()
  898. if err != nil {
  899. return nil, err
  900. }
  901. layerMetadata, err = l.Metadata()
  902. if err != nil {
  903. return nil, err
  904. }
  905. }
  906. comment := img.Comment
  907. if len(comment) == 0 && len(img.History) > 0 {
  908. comment = img.History[len(img.History)-1].Comment
  909. }
  910. imageInspect := &types.ImageInspect{
  911. ID: img.ID().String(),
  912. RepoTags: repoTags,
  913. RepoDigests: repoDigests,
  914. Parent: img.Parent.String(),
  915. Comment: comment,
  916. Created: img.Created.Format(time.RFC3339Nano),
  917. Container: img.Container,
  918. ContainerConfig: &img.ContainerConfig,
  919. DockerVersion: img.DockerVersion,
  920. Author: img.Author,
  921. Config: img.Config,
  922. Architecture: img.Architecture,
  923. Os: img.OS,
  924. Size: size,
  925. VirtualSize: size, // TODO: field unused, deprecate
  926. RootFS: rootFSToAPIType(img.RootFS),
  927. }
  928. imageInspect.GraphDriver.Name = daemon.GraphDriverName()
  929. imageInspect.GraphDriver.Data = layerMetadata
  930. return imageInspect, nil
  931. }
  932. // LoadImage uploads a set of images into the repository. This is the
  933. // complement of ImageExport. The input stream is an uncompressed tar
  934. // ball containing images and metadata.
  935. func (daemon *Daemon) LoadImage(inTar io.ReadCloser, outStream io.Writer, quiet bool) error {
  936. imageExporter := tarexport.NewTarExporter(daemon.imageStore, daemon.layerStore, daemon.referenceStore)
  937. return imageExporter.Load(inTar, outStream, quiet)
  938. }
  939. // ImageHistory returns a slice of ImageHistory structures for the specified image
  940. // name by walking the image lineage.
  941. func (daemon *Daemon) ImageHistory(name string) ([]*types.ImageHistory, error) {
  942. img, err := daemon.GetImage(name)
  943. if err != nil {
  944. return nil, err
  945. }
  946. history := []*types.ImageHistory{}
  947. layerCounter := 0
  948. rootFS := *img.RootFS
  949. rootFS.DiffIDs = nil
  950. for _, h := range img.History {
  951. var layerSize int64
  952. if !h.EmptyLayer {
  953. if len(img.RootFS.DiffIDs) <= layerCounter {
  954. return nil, fmt.Errorf("too many non-empty layers in History section")
  955. }
  956. rootFS.Append(img.RootFS.DiffIDs[layerCounter])
  957. l, err := daemon.layerStore.Get(rootFS.ChainID())
  958. if err != nil {
  959. return nil, err
  960. }
  961. layerSize, err = l.DiffSize()
  962. layer.ReleaseAndLog(daemon.layerStore, l)
  963. if err != nil {
  964. return nil, err
  965. }
  966. layerCounter++
  967. }
  968. history = append([]*types.ImageHistory{{
  969. ID: "<missing>",
  970. Created: h.Created.Unix(),
  971. CreatedBy: h.CreatedBy,
  972. Comment: h.Comment,
  973. Size: layerSize,
  974. }}, history...)
  975. }
  976. // Fill in image IDs and tags
  977. histImg := img
  978. id := img.ID()
  979. for _, h := range history {
  980. h.ID = id.String()
  981. var tags []string
  982. for _, r := range daemon.referenceStore.References(id) {
  983. if _, ok := r.(reference.NamedTagged); ok {
  984. tags = append(tags, r.String())
  985. }
  986. }
  987. h.Tags = tags
  988. id = histImg.Parent
  989. if id == "" {
  990. break
  991. }
  992. histImg, err = daemon.GetImage(id.String())
  993. if err != nil {
  994. break
  995. }
  996. }
  997. return history, nil
  998. }
  999. // GetImageID returns an image ID corresponding to the image referred to by
  1000. // refOrID.
  1001. func (daemon *Daemon) GetImageID(refOrID string) (image.ID, error) {
  1002. id, ref, err := reference.ParseIDOrReference(refOrID)
  1003. if err != nil {
  1004. return "", err
  1005. }
  1006. if id != "" {
  1007. if _, err := daemon.imageStore.Get(image.ID(id)); err != nil {
  1008. return "", ErrImageDoesNotExist{refOrID}
  1009. }
  1010. return image.ID(id), nil
  1011. }
  1012. if id, err := daemon.referenceStore.Get(ref); err == nil {
  1013. return id, nil
  1014. }
  1015. if tagged, ok := ref.(reference.NamedTagged); ok {
  1016. if id, err := daemon.imageStore.Search(tagged.Tag()); err == nil {
  1017. for _, namedRef := range daemon.referenceStore.References(id) {
  1018. if namedRef.Name() == ref.Name() {
  1019. return id, nil
  1020. }
  1021. }
  1022. }
  1023. }
  1024. // Search based on ID
  1025. if id, err := daemon.imageStore.Search(refOrID); err == nil {
  1026. return id, nil
  1027. }
  1028. return "", ErrImageDoesNotExist{refOrID}
  1029. }
  1030. // GetImage returns an image corresponding to the image referred to by refOrID.
  1031. func (daemon *Daemon) GetImage(refOrID string) (*image.Image, error) {
  1032. imgID, err := daemon.GetImageID(refOrID)
  1033. if err != nil {
  1034. return nil, err
  1035. }
  1036. return daemon.imageStore.Get(imgID)
  1037. }
  1038. // GetImageOnBuild looks up a Docker image referenced by `name`.
  1039. func (daemon *Daemon) GetImageOnBuild(name string) (builder.Image, error) {
  1040. img, err := daemon.GetImage(name)
  1041. if err != nil {
  1042. return nil, err
  1043. }
  1044. return img, nil
  1045. }
  1046. // GraphDriverName returns the name of the graph driver used by the layer.Store
  1047. func (daemon *Daemon) GraphDriverName() string {
  1048. return daemon.layerStore.DriverName()
  1049. }
  1050. // GetUIDGIDMaps returns the current daemon's user namespace settings
  1051. // for the full uid and gid maps which will be applied to containers
  1052. // started in this instance.
  1053. func (daemon *Daemon) GetUIDGIDMaps() ([]idtools.IDMap, []idtools.IDMap) {
  1054. return daemon.uidMaps, daemon.gidMaps
  1055. }
  1056. // GetRemappedUIDGID returns the current daemon's uid and gid values
  1057. // if user namespaces are in use for this daemon instance. If not
  1058. // this function will return "real" root values of 0, 0.
  1059. func (daemon *Daemon) GetRemappedUIDGID() (int, int) {
  1060. uid, gid, _ := idtools.GetRootUIDGID(daemon.uidMaps, daemon.gidMaps)
  1061. return uid, gid
  1062. }
  1063. // GetCachedImage returns the most recent created image that is a child
  1064. // of the image with imgID, that had the same config when it was
  1065. // created. nil is returned if a child cannot be found. An error is
  1066. // returned if the parent image cannot be found.
  1067. func (daemon *Daemon) GetCachedImage(imgID image.ID, config *containertypes.Config) (*image.Image, error) {
  1068. // Loop on the children of the given image and check the config
  1069. getMatch := func(siblings []image.ID) (*image.Image, error) {
  1070. var match *image.Image
  1071. for _, id := range siblings {
  1072. img, err := daemon.imageStore.Get(id)
  1073. if err != nil {
  1074. return nil, fmt.Errorf("unable to find image %q", id)
  1075. }
  1076. if runconfig.Compare(&img.ContainerConfig, config) {
  1077. // check for the most up to date match
  1078. if match == nil || match.Created.Before(img.Created) {
  1079. match = img
  1080. }
  1081. }
  1082. }
  1083. return match, nil
  1084. }
  1085. // In this case, this is `FROM scratch`, which isn't an actual image.
  1086. if imgID == "" {
  1087. images := daemon.imageStore.Map()
  1088. var siblings []image.ID
  1089. for id, img := range images {
  1090. if img.Parent == imgID {
  1091. siblings = append(siblings, id)
  1092. }
  1093. }
  1094. return getMatch(siblings)
  1095. }
  1096. // find match from child images
  1097. siblings := daemon.imageStore.Children(imgID)
  1098. return getMatch(siblings)
  1099. }
  1100. // GetCachedImageOnBuild returns a reference to a cached image whose parent equals `parent`
  1101. // and runconfig equals `cfg`. A cache miss is expected to return an empty ID and a nil error.
  1102. func (daemon *Daemon) GetCachedImageOnBuild(imgID string, cfg *containertypes.Config) (string, error) {
  1103. cache, err := daemon.GetCachedImage(image.ID(imgID), cfg)
  1104. if cache == nil || err != nil {
  1105. return "", err
  1106. }
  1107. return cache.ID().String(), nil
  1108. }
  1109. // tempDir returns the default directory to use for temporary files.
  1110. func tempDir(rootDir string, rootUID, rootGID int) (string, error) {
  1111. var tmpDir string
  1112. if tmpDir = os.Getenv("DOCKER_TMPDIR"); tmpDir == "" {
  1113. tmpDir = filepath.Join(rootDir, "tmp")
  1114. }
  1115. return tmpDir, idtools.MkdirAllAs(tmpDir, 0700, rootUID, rootGID)
  1116. }
  1117. func (daemon *Daemon) setSecurityOptions(container *container.Container, hostConfig *containertypes.HostConfig) error {
  1118. container.Lock()
  1119. defer container.Unlock()
  1120. return parseSecurityOpt(container, hostConfig)
  1121. }
  1122. func (daemon *Daemon) setHostConfig(container *container.Container, hostConfig *containertypes.HostConfig) error {
  1123. // Do not lock while creating volumes since this could be calling out to external plugins
  1124. // Don't want to block other actions, like `docker ps` because we're waiting on an external plugin
  1125. if err := daemon.registerMountPoints(container, hostConfig); err != nil {
  1126. return err
  1127. }
  1128. container.Lock()
  1129. defer container.Unlock()
  1130. // Register any links from the host config before starting the container
  1131. if err := daemon.registerLinks(container, hostConfig); err != nil {
  1132. return err
  1133. }
  1134. // make sure links is not nil
  1135. // this ensures that on the next daemon restart we don't try to migrate from legacy sqlite links
  1136. if hostConfig.Links == nil {
  1137. hostConfig.Links = []string{}
  1138. }
  1139. container.HostConfig = hostConfig
  1140. return container.ToDisk()
  1141. }
  1142. func (daemon *Daemon) setupInitLayer(initPath string) error {
  1143. rootUID, rootGID := daemon.GetRemappedUIDGID()
  1144. return setupInitLayer(initPath, rootUID, rootGID)
  1145. }
  1146. func setDefaultMtu(config *Config) {
  1147. // do nothing if the config does not have the default 0 value.
  1148. if config.Mtu != 0 {
  1149. return
  1150. }
  1151. config.Mtu = defaultNetworkMtu
  1152. }
  1153. // verifyContainerSettings performs validation of the hostconfig and config
  1154. // structures.
  1155. func (daemon *Daemon) verifyContainerSettings(hostConfig *containertypes.HostConfig, config *containertypes.Config, update bool) ([]string, error) {
  1156. // First perform verification of settings common across all platforms.
  1157. if config != nil {
  1158. if config.WorkingDir != "" {
  1159. config.WorkingDir = filepath.FromSlash(config.WorkingDir) // Ensure in platform semantics
  1160. if !system.IsAbs(config.WorkingDir) {
  1161. return nil, fmt.Errorf("The working directory '%s' is invalid. It needs to be an absolute path", config.WorkingDir)
  1162. }
  1163. }
  1164. if len(config.StopSignal) > 0 {
  1165. _, err := signal.ParseSignal(config.StopSignal)
  1166. if err != nil {
  1167. return nil, err
  1168. }
  1169. }
  1170. }
  1171. if hostConfig == nil {
  1172. return nil, nil
  1173. }
  1174. logCfg := daemon.getLogConfig(hostConfig.LogConfig)
  1175. if err := logger.ValidateLogOpts(logCfg.Type, logCfg.Config); err != nil {
  1176. return nil, err
  1177. }
  1178. for port := range hostConfig.PortBindings {
  1179. _, portStr := nat.SplitProtoPort(string(port))
  1180. if _, err := nat.ParsePort(portStr); err != nil {
  1181. return nil, fmt.Errorf("Invalid port specification: %q", portStr)
  1182. }
  1183. for _, pb := range hostConfig.PortBindings[port] {
  1184. _, err := nat.NewPort(nat.SplitProtoPort(pb.HostPort))
  1185. if err != nil {
  1186. return nil, fmt.Errorf("Invalid port specification: %q", pb.HostPort)
  1187. }
  1188. }
  1189. }
  1190. // Now do platform-specific verification
  1191. return verifyPlatformContainerSettings(daemon, hostConfig, config, update)
  1192. }
  1193. // Checks if the client set configurations for more than one network while creating a container
  1194. func (daemon *Daemon) verifyNetworkingConfig(nwConfig *networktypes.NetworkingConfig) error {
  1195. if nwConfig == nil || len(nwConfig.EndpointsConfig) <= 1 {
  1196. return nil
  1197. }
  1198. l := make([]string, 0, len(nwConfig.EndpointsConfig))
  1199. for k := range nwConfig.EndpointsConfig {
  1200. l = append(l, k)
  1201. }
  1202. err := fmt.Errorf("Container cannot be connected to network endpoints: %s", strings.Join(l, ", "))
  1203. return errors.NewBadRequestError(err)
  1204. }
  1205. func configureVolumes(config *Config, rootUID, rootGID int) (*store.VolumeStore, error) {
  1206. volumesDriver, err := local.New(config.Root, rootUID, rootGID)
  1207. if err != nil {
  1208. return nil, err
  1209. }
  1210. volumedrivers.Register(volumesDriver, volumesDriver.Name())
  1211. return store.New(config.Root)
  1212. }
  1213. // AuthenticateToRegistry checks the validity of credentials in authConfig
  1214. func (daemon *Daemon) AuthenticateToRegistry(ctx context.Context, authConfig *types.AuthConfig) (string, string, error) {
  1215. return daemon.RegistryService.Auth(authConfig, dockerversion.DockerUserAgent(ctx))
  1216. }
  1217. // SearchRegistryForImages queries the registry for images matching
  1218. // term. authConfig is used to login.
  1219. func (daemon *Daemon) SearchRegistryForImages(ctx context.Context, term string,
  1220. authConfig *types.AuthConfig,
  1221. headers map[string][]string) (*registrytypes.SearchResults, error) {
  1222. return daemon.RegistryService.Search(term, authConfig, dockerversion.DockerUserAgent(ctx), headers)
  1223. }
  1224. // IsShuttingDown tells whether the daemon is shutting down or not
  1225. func (daemon *Daemon) IsShuttingDown() bool {
  1226. return daemon.shutdown
  1227. }
  1228. // GetContainerStats collects all the stats published by a container
  1229. func (daemon *Daemon) GetContainerStats(container *container.Container) (*types.StatsJSON, error) {
  1230. stats, err := daemon.stats(container)
  1231. if err != nil {
  1232. return nil, err
  1233. }
  1234. if stats.Networks, err = daemon.getNetworkStats(container); err != nil {
  1235. return nil, err
  1236. }
  1237. return stats, nil
  1238. }
  1239. // Resolve Network SandboxID in case the container reuse another container's network stack
  1240. func (daemon *Daemon) getNetworkSandboxID(c *container.Container) (string, error) {
  1241. curr := c
  1242. for curr.HostConfig.NetworkMode.IsContainer() {
  1243. containerID := curr.HostConfig.NetworkMode.ConnectedContainer()
  1244. connected, err := daemon.GetContainer(containerID)
  1245. if err != nil {
  1246. return "", fmt.Errorf("Could not get container for %s", containerID)
  1247. }
  1248. curr = connected
  1249. }
  1250. return curr.NetworkSettings.SandboxID, nil
  1251. }
  1252. func (daemon *Daemon) getNetworkStats(c *container.Container) (map[string]types.NetworkStats, error) {
  1253. sandboxID, err := daemon.getNetworkSandboxID(c)
  1254. if err != nil {
  1255. return nil, err
  1256. }
  1257. sb, err := daemon.netController.SandboxByID(sandboxID)
  1258. if err != nil {
  1259. return nil, err
  1260. }
  1261. lnstats, err := sb.Statistics()
  1262. if err != nil {
  1263. return nil, err
  1264. }
  1265. stats := make(map[string]types.NetworkStats)
  1266. // Convert libnetwork nw stats into engine-api stats
  1267. for ifName, ifStats := range lnstats {
  1268. stats[ifName] = types.NetworkStats{
  1269. RxBytes: ifStats.RxBytes,
  1270. RxPackets: ifStats.RxPackets,
  1271. RxErrors: ifStats.RxErrors,
  1272. RxDropped: ifStats.RxDropped,
  1273. TxBytes: ifStats.TxBytes,
  1274. TxPackets: ifStats.TxPackets,
  1275. TxErrors: ifStats.TxErrors,
  1276. TxDropped: ifStats.TxDropped,
  1277. }
  1278. }
  1279. return stats, nil
  1280. }
  1281. // newBaseContainer creates a new container with its initial
  1282. // configuration based on the root storage from the daemon.
  1283. func (daemon *Daemon) newBaseContainer(id string) *container.Container {
  1284. return container.NewBaseContainer(id, daemon.containerRoot(id))
  1285. }
  1286. // initDiscovery initializes the discovery watcher for this daemon.
  1287. func (daemon *Daemon) initDiscovery(config *Config) error {
  1288. advertise, err := parseClusterAdvertiseSettings(config.ClusterStore, config.ClusterAdvertise)
  1289. if err != nil {
  1290. if err == errDiscoveryDisabled {
  1291. return nil
  1292. }
  1293. return err
  1294. }
  1295. config.ClusterAdvertise = advertise
  1296. discoveryWatcher, err := initDiscovery(config.ClusterStore, config.ClusterAdvertise, config.ClusterOpts)
  1297. if err != nil {
  1298. return fmt.Errorf("discovery initialization failed (%v)", err)
  1299. }
  1300. daemon.discoveryWatcher = discoveryWatcher
  1301. return nil
  1302. }
  1303. // Reload reads configuration changes and modifies the
  1304. // daemon according to those changes.
  1305. // These are the settings that Reload changes:
  1306. // - Daemon labels.
  1307. // - Daemon debug log level.
  1308. // - Cluster discovery (reconfigure and restart).
  1309. func (daemon *Daemon) Reload(config *Config) error {
  1310. daemon.configStore.reloadLock.Lock()
  1311. defer daemon.configStore.reloadLock.Unlock()
  1312. if config.IsValueSet("label") {
  1313. daemon.configStore.Labels = config.Labels
  1314. }
  1315. if config.IsValueSet("debug") {
  1316. daemon.configStore.Debug = config.Debug
  1317. }
  1318. return daemon.reloadClusterDiscovery(config)
  1319. }
  1320. func (daemon *Daemon) reloadClusterDiscovery(config *Config) error {
  1321. var err error
  1322. newAdvertise := daemon.configStore.ClusterAdvertise
  1323. newClusterStore := daemon.configStore.ClusterStore
  1324. if config.IsValueSet("cluster-advertise") {
  1325. if config.IsValueSet("cluster-store") {
  1326. newClusterStore = config.ClusterStore
  1327. }
  1328. newAdvertise, err = parseClusterAdvertiseSettings(newClusterStore, config.ClusterAdvertise)
  1329. if err != nil && err != errDiscoveryDisabled {
  1330. return err
  1331. }
  1332. }
  1333. // check discovery modifications
  1334. if !modifiedDiscoverySettings(daemon.configStore, newAdvertise, newClusterStore, config.ClusterOpts) {
  1335. return nil
  1336. }
  1337. // enable discovery for the first time if it was not previously enabled
  1338. if daemon.discoveryWatcher == nil {
  1339. discoveryWatcher, err := initDiscovery(newClusterStore, newAdvertise, config.ClusterOpts)
  1340. if err != nil {
  1341. return fmt.Errorf("discovery initialization failed (%v)", err)
  1342. }
  1343. daemon.discoveryWatcher = discoveryWatcher
  1344. } else {
  1345. if err == errDiscoveryDisabled {
  1346. // disable discovery if it was previously enabled and it's disabled now
  1347. daemon.discoveryWatcher.Stop()
  1348. } else {
  1349. // reload discovery
  1350. if err = daemon.discoveryWatcher.Reload(config.ClusterStore, newAdvertise, config.ClusterOpts); err != nil {
  1351. return err
  1352. }
  1353. }
  1354. }
  1355. daemon.configStore.ClusterStore = newClusterStore
  1356. daemon.configStore.ClusterOpts = config.ClusterOpts
  1357. daemon.configStore.ClusterAdvertise = newAdvertise
  1358. if daemon.netController == nil {
  1359. return nil
  1360. }
  1361. netOptions, err := daemon.networkOptions(daemon.configStore)
  1362. if err != nil {
  1363. logrus.Warnf("Failed to reload configuration with network controller: %v", err)
  1364. return nil
  1365. }
  1366. err = daemon.netController.ReloadConfiguration(netOptions...)
  1367. if err != nil {
  1368. logrus.Warnf("Failed to reload configuration with network controller: %v", err)
  1369. }
  1370. return nil
  1371. }
  1372. func validateID(id string) error {
  1373. if id == "" {
  1374. return fmt.Errorf("Invalid empty id")
  1375. }
  1376. return nil
  1377. }
  1378. func isBridgeNetworkDisabled(config *Config) bool {
  1379. return config.bridgeConfig.Iface == disableNetworkBridge
  1380. }
  1381. func (daemon *Daemon) networkOptions(dconfig *Config) ([]nwconfig.Option, error) {
  1382. options := []nwconfig.Option{}
  1383. if dconfig == nil {
  1384. return options, nil
  1385. }
  1386. options = append(options, nwconfig.OptionDataDir(dconfig.Root))
  1387. dd := runconfig.DefaultDaemonNetworkMode()
  1388. dn := runconfig.DefaultDaemonNetworkMode().NetworkName()
  1389. options = append(options, nwconfig.OptionDefaultDriver(string(dd)))
  1390. options = append(options, nwconfig.OptionDefaultNetwork(dn))
  1391. if strings.TrimSpace(dconfig.ClusterStore) != "" {
  1392. kv := strings.Split(dconfig.ClusterStore, "://")
  1393. if len(kv) != 2 {
  1394. return nil, fmt.Errorf("kv store daemon config must be of the form KV-PROVIDER://KV-URL")
  1395. }
  1396. options = append(options, nwconfig.OptionKVProvider(kv[0]))
  1397. options = append(options, nwconfig.OptionKVProviderURL(kv[1]))
  1398. }
  1399. if len(dconfig.ClusterOpts) > 0 {
  1400. options = append(options, nwconfig.OptionKVOpts(dconfig.ClusterOpts))
  1401. }
  1402. if daemon.discoveryWatcher != nil {
  1403. options = append(options, nwconfig.OptionDiscoveryWatcher(daemon.discoveryWatcher))
  1404. }
  1405. if dconfig.ClusterAdvertise != "" {
  1406. options = append(options, nwconfig.OptionDiscoveryAddress(dconfig.ClusterAdvertise))
  1407. }
  1408. options = append(options, nwconfig.OptionLabels(dconfig.Labels))
  1409. options = append(options, driverOptions(dconfig)...)
  1410. return options, nil
  1411. }
  1412. func copyBlkioEntry(entries []*containerd.BlkioStatsEntry) []types.BlkioStatEntry {
  1413. out := make([]types.BlkioStatEntry, len(entries))
  1414. for i, re := range entries {
  1415. out[i] = types.BlkioStatEntry{
  1416. Major: re.Major,
  1417. Minor: re.Minor,
  1418. Op: re.Op,
  1419. Value: re.Value,
  1420. }
  1421. }
  1422. return out
  1423. }