daemon.go 52 KB

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