daemon.go 52 KB

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