daemon.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131
  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. "errors"
  9. "fmt"
  10. "io"
  11. "io/ioutil"
  12. "os"
  13. "path/filepath"
  14. "regexp"
  15. "runtime"
  16. "strings"
  17. "sync"
  18. "time"
  19. "github.com/Sirupsen/logrus"
  20. "github.com/docker/docker/api"
  21. derr "github.com/docker/docker/api/errors"
  22. "github.com/docker/docker/daemon/events"
  23. "github.com/docker/docker/daemon/execdriver"
  24. "github.com/docker/docker/daemon/execdriver/execdrivers"
  25. "github.com/docker/docker/daemon/graphdriver"
  26. // register vfs
  27. _ "github.com/docker/docker/daemon/graphdriver/vfs"
  28. "github.com/docker/docker/daemon/logger"
  29. "github.com/docker/docker/daemon/network"
  30. "github.com/docker/docker/graph"
  31. "github.com/docker/docker/image"
  32. "github.com/docker/docker/pkg/archive"
  33. "github.com/docker/docker/pkg/broadcastwriter"
  34. "github.com/docker/docker/pkg/fileutils"
  35. "github.com/docker/docker/pkg/graphdb"
  36. "github.com/docker/docker/pkg/ioutils"
  37. "github.com/docker/docker/pkg/namesgenerator"
  38. "github.com/docker/docker/pkg/nat"
  39. "github.com/docker/docker/pkg/signal"
  40. "github.com/docker/docker/pkg/stringid"
  41. "github.com/docker/docker/pkg/stringutils"
  42. "github.com/docker/docker/pkg/sysinfo"
  43. "github.com/docker/docker/pkg/system"
  44. "github.com/docker/docker/pkg/truncindex"
  45. "github.com/docker/docker/registry"
  46. "github.com/docker/docker/runconfig"
  47. "github.com/docker/docker/trust"
  48. volumedrivers "github.com/docker/docker/volume/drivers"
  49. "github.com/docker/docker/volume/local"
  50. "github.com/docker/libnetwork"
  51. "github.com/opencontainers/runc/libcontainer/netlink"
  52. )
  53. var (
  54. validContainerNameChars = `[a-zA-Z0-9][a-zA-Z0-9_.-]`
  55. validContainerNamePattern = regexp.MustCompile(`^/?` + validContainerNameChars + `+$`)
  56. errSystemNotSupported = errors.New("The Docker daemon is not supported on this platform.")
  57. )
  58. type contStore struct {
  59. s map[string]*Container
  60. sync.Mutex
  61. }
  62. func (c *contStore) Add(id string, cont *Container) {
  63. c.Lock()
  64. c.s[id] = cont
  65. c.Unlock()
  66. }
  67. func (c *contStore) Get(id string) *Container {
  68. c.Lock()
  69. res := c.s[id]
  70. c.Unlock()
  71. return res
  72. }
  73. func (c *contStore) Delete(id string) {
  74. c.Lock()
  75. delete(c.s, id)
  76. c.Unlock()
  77. }
  78. func (c *contStore) List() []*Container {
  79. containers := new(History)
  80. c.Lock()
  81. for _, cont := range c.s {
  82. containers.Add(cont)
  83. }
  84. c.Unlock()
  85. containers.sort()
  86. return *containers
  87. }
  88. // Daemon holds information about the Docker daemon.
  89. type Daemon struct {
  90. ID string
  91. repository string
  92. sysInitPath string
  93. containers *contStore
  94. execCommands *execStore
  95. graph *graph.Graph
  96. repositories *graph.TagStore
  97. idIndex *truncindex.TruncIndex
  98. configStore *Config
  99. containerGraphDB *graphdb.Database
  100. driver graphdriver.Driver
  101. execDriver execdriver.Driver
  102. statsCollector *statsCollector
  103. defaultLogConfig runconfig.LogConfig
  104. RegistryService *registry.Service
  105. EventsService *events.Events
  106. netController libnetwork.NetworkController
  107. volumes *volumeStore
  108. root string
  109. shutdown bool
  110. }
  111. // Get looks for a container using the provided information, which could be
  112. // one of the following inputs from the caller:
  113. // - A full container ID, which will exact match a container in daemon's list
  114. // - A container name, which will only exact match via the GetByName() function
  115. // - A partial container ID prefix (e.g. short ID) of any length that is
  116. // unique enough to only return a single container object
  117. // If none of these searches succeed, an error is returned
  118. func (daemon *Daemon) Get(prefixOrName string) (*Container, error) {
  119. if containerByID := daemon.containers.Get(prefixOrName); containerByID != nil {
  120. // prefix is an exact match to a full container ID
  121. return containerByID, nil
  122. }
  123. // GetByName will match only an exact name provided; we ignore errors
  124. if containerByName, _ := daemon.GetByName(prefixOrName); containerByName != nil {
  125. // prefix is an exact match to a full container Name
  126. return containerByName, nil
  127. }
  128. containerID, indexError := daemon.idIndex.Get(prefixOrName)
  129. if indexError != nil {
  130. // When truncindex defines an error type, use that instead
  131. if strings.Contains(indexError.Error(), "no such id") {
  132. return nil, derr.ErrorCodeNoSuchContainer.WithArgs(prefixOrName)
  133. }
  134. return nil, indexError
  135. }
  136. return daemon.containers.Get(containerID), nil
  137. }
  138. // Exists returns a true if a container of the specified ID or name exists,
  139. // false otherwise.
  140. func (daemon *Daemon) Exists(id string) bool {
  141. c, _ := daemon.Get(id)
  142. return c != nil
  143. }
  144. func (daemon *Daemon) containerRoot(id string) string {
  145. return filepath.Join(daemon.repository, id)
  146. }
  147. // Load reads the contents of a container from disk
  148. // This is typically done at startup.
  149. func (daemon *Daemon) load(id string) (*Container, error) {
  150. container := daemon.newBaseContainer(id)
  151. if err := container.fromDisk(); err != nil {
  152. return nil, err
  153. }
  154. if container.ID != id {
  155. return &container, fmt.Errorf("Container %s is stored at %s", container.ID, id)
  156. }
  157. return &container, nil
  158. }
  159. // Register makes a container object usable by the daemon as <container.ID>
  160. func (daemon *Daemon) Register(container *Container) error {
  161. if container.daemon != nil || daemon.Exists(container.ID) {
  162. return fmt.Errorf("Container is already loaded")
  163. }
  164. if err := validateID(container.ID); err != nil {
  165. return err
  166. }
  167. if err := daemon.ensureName(container); err != nil {
  168. return err
  169. }
  170. container.daemon = daemon
  171. // Attach to stdout and stderr
  172. container.stderr = broadcastwriter.New()
  173. container.stdout = broadcastwriter.New()
  174. // Attach to stdin
  175. if container.Config.OpenStdin {
  176. container.stdin, container.stdinPipe = io.Pipe()
  177. } else {
  178. container.stdinPipe = ioutils.NopWriteCloser(ioutil.Discard) // Silently drop stdin
  179. }
  180. // done
  181. daemon.containers.Add(container.ID, container)
  182. // don't update the Suffixarray if we're starting up
  183. // we'll waste time if we update it for every container
  184. daemon.idIndex.Add(container.ID)
  185. if container.IsRunning() {
  186. logrus.Debugf("killing old running container %s", container.ID)
  187. // Set exit code to 128 + SIGKILL (9) to properly represent unsuccessful exit
  188. container.setStoppedLocking(&execdriver.ExitStatus{ExitCode: 137})
  189. // use the current driver and ensure that the container is dead x.x
  190. cmd := &execdriver.Command{
  191. ID: container.ID,
  192. }
  193. daemon.execDriver.Terminate(cmd)
  194. if err := container.Unmount(); err != nil {
  195. logrus.Debugf("unmount error %s", err)
  196. }
  197. if err := container.toDiskLocking(); err != nil {
  198. logrus.Errorf("Error saving stopped state to disk: %v", err)
  199. }
  200. }
  201. if err := daemon.verifyVolumesInfo(container); err != nil {
  202. return err
  203. }
  204. if err := container.prepareMountPoints(); err != nil {
  205. return err
  206. }
  207. return nil
  208. }
  209. func (daemon *Daemon) ensureName(container *Container) error {
  210. if container.Name == "" {
  211. name, err := daemon.generateNewName(container.ID)
  212. if err != nil {
  213. return err
  214. }
  215. container.Name = name
  216. if err := container.toDiskLocking(); err != nil {
  217. logrus.Errorf("Error saving container name to disk: %v", err)
  218. }
  219. }
  220. return nil
  221. }
  222. func (daemon *Daemon) restore() error {
  223. type cr struct {
  224. container *Container
  225. registered bool
  226. }
  227. var (
  228. debug = os.Getenv("DEBUG") != ""
  229. currentDriver = daemon.driver.String()
  230. containers = make(map[string]*cr)
  231. )
  232. if !debug {
  233. logrus.Info("Loading containers: start.")
  234. }
  235. dir, err := ioutil.ReadDir(daemon.repository)
  236. if err != nil {
  237. return err
  238. }
  239. for _, v := range dir {
  240. id := v.Name()
  241. container, err := daemon.load(id)
  242. if !debug && logrus.GetLevel() == logrus.InfoLevel {
  243. fmt.Print(".")
  244. }
  245. if err != nil {
  246. logrus.Errorf("Failed to load container %v: %v", id, err)
  247. continue
  248. }
  249. // Ignore the container if it does not support the current driver being used by the graph
  250. if (container.Driver == "" && currentDriver == "aufs") || container.Driver == currentDriver {
  251. logrus.Debugf("Loaded container %v", container.ID)
  252. containers[container.ID] = &cr{container: container}
  253. } else {
  254. logrus.Debugf("Cannot load container %s because it was created with another graph driver.", container.ID)
  255. }
  256. }
  257. if entities := daemon.containerGraphDB.List("/", -1); entities != nil {
  258. for _, p := range entities.Paths() {
  259. if !debug && logrus.GetLevel() == logrus.InfoLevel {
  260. fmt.Print(".")
  261. }
  262. e := entities[p]
  263. if c, ok := containers[e.ID()]; ok {
  264. c.registered = true
  265. }
  266. }
  267. }
  268. group := sync.WaitGroup{}
  269. for _, c := range containers {
  270. group.Add(1)
  271. go func(container *Container, registered bool) {
  272. defer group.Done()
  273. if !registered {
  274. // Try to set the default name for a container if it exists prior to links
  275. container.Name, err = daemon.generateNewName(container.ID)
  276. if err != nil {
  277. logrus.Debugf("Setting default id - %s", err)
  278. }
  279. }
  280. if err := daemon.Register(container); err != nil {
  281. logrus.Errorf("Failed to register container %s: %s", container.ID, err)
  282. // The container register failed should not be started.
  283. return
  284. }
  285. // check the restart policy on the containers and restart any container with
  286. // the restart policy of "always"
  287. if daemon.configStore.AutoRestart && container.shouldRestart() {
  288. logrus.Debugf("Starting container %s", container.ID)
  289. if err := container.Start(); err != nil {
  290. logrus.Errorf("Failed to start container %s: %s", container.ID, err)
  291. }
  292. }
  293. }(c.container, c.registered)
  294. }
  295. group.Wait()
  296. if !debug {
  297. if logrus.GetLevel() == logrus.InfoLevel {
  298. fmt.Println()
  299. }
  300. logrus.Info("Loading containers: done.")
  301. }
  302. return nil
  303. }
  304. func (daemon *Daemon) mergeAndVerifyConfig(config *runconfig.Config, img *image.Image) error {
  305. if img != nil && img.Config != nil {
  306. if err := runconfig.Merge(config, img.Config); err != nil {
  307. return err
  308. }
  309. }
  310. if config.Entrypoint.Len() == 0 && config.Cmd.Len() == 0 {
  311. return fmt.Errorf("No command specified")
  312. }
  313. return nil
  314. }
  315. func (daemon *Daemon) generateIDAndName(name string) (string, string, error) {
  316. var (
  317. err error
  318. id = stringid.GenerateNonCryptoID()
  319. )
  320. if name == "" {
  321. if name, err = daemon.generateNewName(id); err != nil {
  322. return "", "", err
  323. }
  324. return id, name, nil
  325. }
  326. if name, err = daemon.reserveName(id, name); err != nil {
  327. return "", "", err
  328. }
  329. return id, name, nil
  330. }
  331. func (daemon *Daemon) reserveName(id, name string) (string, error) {
  332. if !validContainerNamePattern.MatchString(name) {
  333. return "", fmt.Errorf("Invalid container name (%s), only %s are allowed", name, validContainerNameChars)
  334. }
  335. if name[0] != '/' {
  336. name = "/" + name
  337. }
  338. if _, err := daemon.containerGraphDB.Set(name, id); err != nil {
  339. if !graphdb.IsNonUniqueNameError(err) {
  340. return "", err
  341. }
  342. conflictingContainer, err := daemon.GetByName(name)
  343. if err != nil {
  344. if strings.Contains(err.Error(), "Could not find entity") {
  345. return "", err
  346. }
  347. // Remove name and continue starting the container
  348. if err := daemon.containerGraphDB.Delete(name); err != nil {
  349. return "", err
  350. }
  351. } else {
  352. nameAsKnownByUser := strings.TrimPrefix(name, "/")
  353. return "", fmt.Errorf(
  354. "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.", nameAsKnownByUser,
  355. stringid.TruncateID(conflictingContainer.ID))
  356. }
  357. }
  358. return name, nil
  359. }
  360. func (daemon *Daemon) generateNewName(id string) (string, error) {
  361. var name string
  362. for i := 0; i < 6; i++ {
  363. name = namesgenerator.GetRandomName(i)
  364. if name[0] != '/' {
  365. name = "/" + name
  366. }
  367. if _, err := daemon.containerGraphDB.Set(name, id); err != nil {
  368. if !graphdb.IsNonUniqueNameError(err) {
  369. return "", err
  370. }
  371. continue
  372. }
  373. return name, nil
  374. }
  375. name = "/" + stringid.TruncateID(id)
  376. if _, err := daemon.containerGraphDB.Set(name, id); err != nil {
  377. return "", err
  378. }
  379. return name, nil
  380. }
  381. func (daemon *Daemon) generateHostname(id string, config *runconfig.Config) {
  382. // Generate default hostname
  383. // FIXME: the lxc template no longer needs to set a default hostname
  384. if config.Hostname == "" {
  385. config.Hostname = id[:12]
  386. }
  387. }
  388. func (daemon *Daemon) getEntrypointAndArgs(configEntrypoint *stringutils.StrSlice, configCmd *stringutils.StrSlice) (string, []string) {
  389. var (
  390. entrypoint string
  391. args []string
  392. )
  393. cmdSlice := configCmd.Slice()
  394. if configEntrypoint.Len() != 0 {
  395. eSlice := configEntrypoint.Slice()
  396. entrypoint = eSlice[0]
  397. args = append(eSlice[1:], cmdSlice...)
  398. } else {
  399. entrypoint = cmdSlice[0]
  400. args = cmdSlice[1:]
  401. }
  402. return entrypoint, args
  403. }
  404. func (daemon *Daemon) newContainer(name string, config *runconfig.Config, imgID string) (*Container, error) {
  405. var (
  406. id string
  407. err error
  408. )
  409. id, name, err = daemon.generateIDAndName(name)
  410. if err != nil {
  411. return nil, err
  412. }
  413. daemon.generateHostname(id, config)
  414. entrypoint, args := daemon.getEntrypointAndArgs(config.Entrypoint, config.Cmd)
  415. base := daemon.newBaseContainer(id)
  416. base.Created = time.Now().UTC()
  417. base.Path = entrypoint
  418. base.Args = args //FIXME: de-duplicate from config
  419. base.Config = config
  420. base.hostConfig = &runconfig.HostConfig{}
  421. base.ImageID = imgID
  422. base.NetworkSettings = &network.Settings{}
  423. base.Name = name
  424. base.Driver = daemon.driver.String()
  425. base.ExecDriver = daemon.execDriver.Name()
  426. return &base, err
  427. }
  428. // GetFullContainerName returns a constructed container name. I think
  429. // it has to do with the fact that a container is a file on disk and
  430. // this is sort of just creating a file name.
  431. func GetFullContainerName(name string) (string, error) {
  432. if name == "" {
  433. return "", fmt.Errorf("Container name cannot be empty")
  434. }
  435. if name[0] != '/' {
  436. name = "/" + name
  437. }
  438. return name, nil
  439. }
  440. // GetByName returns a container given a name.
  441. func (daemon *Daemon) GetByName(name string) (*Container, error) {
  442. fullName, err := GetFullContainerName(name)
  443. if err != nil {
  444. return nil, err
  445. }
  446. entity := daemon.containerGraphDB.Get(fullName)
  447. if entity == nil {
  448. return nil, fmt.Errorf("Could not find entity for %s", name)
  449. }
  450. e := daemon.containers.Get(entity.ID())
  451. if e == nil {
  452. return nil, fmt.Errorf("Could not find container for entity id %s", entity.ID())
  453. }
  454. return e, nil
  455. }
  456. // children returns all child containers of the container with the
  457. // given name. The containers are returned as a map from the container
  458. // name to a pointer to Container.
  459. func (daemon *Daemon) children(name string) (map[string]*Container, error) {
  460. name, err := GetFullContainerName(name)
  461. if err != nil {
  462. return nil, err
  463. }
  464. children := make(map[string]*Container)
  465. err = daemon.containerGraphDB.Walk(name, func(p string, e *graphdb.Entity) error {
  466. c, err := daemon.Get(e.ID())
  467. if err != nil {
  468. return err
  469. }
  470. children[p] = c
  471. return nil
  472. }, 0)
  473. if err != nil {
  474. return nil, err
  475. }
  476. return children, nil
  477. }
  478. // parents returns the names of the parent containers of the container
  479. // with the given name.
  480. func (daemon *Daemon) parents(name string) ([]string, error) {
  481. name, err := GetFullContainerName(name)
  482. if err != nil {
  483. return nil, err
  484. }
  485. return daemon.containerGraphDB.Parents(name)
  486. }
  487. func (daemon *Daemon) registerLink(parent, child *Container, alias string) error {
  488. fullName := filepath.Join(parent.Name, alias)
  489. if !daemon.containerGraphDB.Exists(fullName) {
  490. _, err := daemon.containerGraphDB.Set(fullName, child.ID)
  491. return err
  492. }
  493. return nil
  494. }
  495. // NewDaemon sets up everything for the daemon to be able to service
  496. // requests from the webserver.
  497. func NewDaemon(config *Config, registryService *registry.Service) (daemon *Daemon, err error) {
  498. setDefaultMtu(config)
  499. // Ensure we have compatible configuration options
  500. if err := checkConfigOptions(config); err != nil {
  501. return nil, err
  502. }
  503. // Do we have a disabled network?
  504. config.DisableBridge = isBridgeNetworkDisabled(config)
  505. // Verify the platform is supported as a daemon
  506. if !platformSupported {
  507. return nil, errSystemNotSupported
  508. }
  509. // Validate platform-specific requirements
  510. if err := checkSystem(); err != nil {
  511. return nil, err
  512. }
  513. // set up SIGUSR1 handler on Unix-like systems, or a Win32 global event
  514. // on Windows to dump Go routine stacks
  515. setupDumpStackTrap()
  516. // get the canonical path to the Docker root directory
  517. var realRoot string
  518. if _, err := os.Stat(config.Root); err != nil && os.IsNotExist(err) {
  519. realRoot = config.Root
  520. } else {
  521. realRoot, err = fileutils.ReadSymlinkedDirectory(config.Root)
  522. if err != nil {
  523. return nil, fmt.Errorf("Unable to get the full path to root (%s): %s", config.Root, err)
  524. }
  525. }
  526. config.Root = realRoot
  527. // Create the root directory if it doesn't exists
  528. if err := system.MkdirAll(config.Root, 0700); err != nil {
  529. return nil, err
  530. }
  531. // set up the tmpDir to use a canonical path
  532. tmp, err := tempDir(config.Root)
  533. if err != nil {
  534. return nil, fmt.Errorf("Unable to get the TempDir under %s: %s", config.Root, err)
  535. }
  536. realTmp, err := fileutils.ReadSymlinkedDirectory(tmp)
  537. if err != nil {
  538. return nil, fmt.Errorf("Unable to get the full path to the TempDir (%s): %s", tmp, err)
  539. }
  540. os.Setenv("TMPDIR", realTmp)
  541. // Set the default driver
  542. graphdriver.DefaultDriver = config.GraphDriver
  543. // Load storage driver
  544. driver, err := graphdriver.New(config.Root, config.GraphOptions)
  545. if err != nil {
  546. return nil, fmt.Errorf("error initializing graphdriver: %v", err)
  547. }
  548. logrus.Debugf("Using graph driver %s", driver)
  549. d := &Daemon{}
  550. d.driver = driver
  551. // Ensure the graph driver is shutdown at a later point
  552. defer func() {
  553. if err != nil {
  554. if err := d.Shutdown(); err != nil {
  555. logrus.Error(err)
  556. }
  557. }
  558. }()
  559. // Verify logging driver type
  560. if config.LogConfig.Type != "none" {
  561. if _, err := logger.GetLogDriver(config.LogConfig.Type); err != nil {
  562. return nil, fmt.Errorf("error finding the logging driver: %v", err)
  563. }
  564. }
  565. logrus.Debugf("Using default logging driver %s", config.LogConfig.Type)
  566. // Configure and validate the kernels security support
  567. if err := configureKernelSecuritySupport(config, d.driver.String()); err != nil {
  568. return nil, err
  569. }
  570. daemonRepo := filepath.Join(config.Root, "containers")
  571. if err := system.MkdirAll(daemonRepo, 0700); err != nil {
  572. return nil, err
  573. }
  574. // Migrate the container if it is aufs and aufs is enabled
  575. if err := migrateIfDownlevel(d.driver, config.Root); err != nil {
  576. return nil, err
  577. }
  578. logrus.Debug("Creating images graph")
  579. g, err := graph.NewGraph(filepath.Join(config.Root, "graph"), d.driver)
  580. if err != nil {
  581. return nil, err
  582. }
  583. // Configure the volumes driver
  584. volStore, err := configureVolumes(config)
  585. if err != nil {
  586. return nil, err
  587. }
  588. trustKey, err := api.LoadOrCreateTrustKey(config.TrustKeyPath)
  589. if err != nil {
  590. return nil, err
  591. }
  592. trustDir := filepath.Join(config.Root, "trust")
  593. if err := system.MkdirAll(trustDir, 0700); err != nil {
  594. return nil, err
  595. }
  596. trustService, err := trust.NewStore(trustDir)
  597. if err != nil {
  598. return nil, fmt.Errorf("could not create trust store: %s", err)
  599. }
  600. eventsService := events.New()
  601. logrus.Debug("Creating repository list")
  602. tagCfg := &graph.TagStoreConfig{
  603. Graph: g,
  604. Key: trustKey,
  605. Registry: registryService,
  606. Events: eventsService,
  607. Trust: trustService,
  608. }
  609. repositories, err := graph.NewTagStore(filepath.Join(config.Root, "repositories-"+d.driver.String()), tagCfg)
  610. if err != nil {
  611. return nil, fmt.Errorf("Couldn't create Tag store repositories-%s: %s", d.driver.String(), err)
  612. }
  613. if restorer, ok := d.driver.(graphdriver.ImageRestorer); ok {
  614. if _, err := restorer.RestoreCustomImages(repositories, g); err != nil {
  615. return nil, fmt.Errorf("Couldn't restore custom images: %s", err)
  616. }
  617. }
  618. d.netController, err = initNetworkController(config)
  619. if err != nil {
  620. return nil, fmt.Errorf("Error initializing network controller: %v", err)
  621. }
  622. graphdbPath := filepath.Join(config.Root, "linkgraph.db")
  623. graph, err := graphdb.NewSqliteConn(graphdbPath)
  624. if err != nil {
  625. return nil, err
  626. }
  627. d.containerGraphDB = graph
  628. var sysInitPath string
  629. if config.ExecDriver == "lxc" {
  630. initPath, err := configureSysInit(config)
  631. if err != nil {
  632. return nil, err
  633. }
  634. sysInitPath = initPath
  635. }
  636. sysInfo := sysinfo.New(false)
  637. // Check if Devices cgroup is mounted, it is hard requirement for container security,
  638. // on Linux/FreeBSD.
  639. if runtime.GOOS != "windows" && !sysInfo.CgroupDevicesEnabled {
  640. return nil, fmt.Errorf("Devices cgroup isn't mounted")
  641. }
  642. ed, err := execdrivers.NewDriver(config.ExecDriver, config.ExecOptions, config.ExecRoot, config.Root, sysInitPath, sysInfo)
  643. if err != nil {
  644. return nil, err
  645. }
  646. d.ID = trustKey.PublicKey().KeyID()
  647. d.repository = daemonRepo
  648. d.containers = &contStore{s: make(map[string]*Container)}
  649. d.execCommands = newExecStore()
  650. d.graph = g
  651. d.repositories = repositories
  652. d.idIndex = truncindex.NewTruncIndex([]string{})
  653. d.configStore = config
  654. d.sysInitPath = sysInitPath
  655. d.execDriver = ed
  656. d.statsCollector = newStatsCollector(1 * time.Second)
  657. d.defaultLogConfig = config.LogConfig
  658. d.RegistryService = registryService
  659. d.EventsService = eventsService
  660. d.volumes = volStore
  661. d.root = config.Root
  662. go d.execCommandGC()
  663. if err := d.restore(); err != nil {
  664. return nil, err
  665. }
  666. return d, nil
  667. }
  668. // Shutdown stops the daemon.
  669. func (daemon *Daemon) Shutdown() error {
  670. daemon.shutdown = true
  671. if daemon.containers != nil {
  672. group := sync.WaitGroup{}
  673. logrus.Debug("starting clean shutdown of all containers...")
  674. for _, container := range daemon.List() {
  675. c := container
  676. if c.IsRunning() {
  677. logrus.Debugf("stopping %s", c.ID)
  678. group.Add(1)
  679. go func() {
  680. defer group.Done()
  681. // TODO(windows): Handle docker restart with paused containers
  682. if c.isPaused() {
  683. // To terminate a process in freezer cgroup, we should send
  684. // SIGTERM to this process then unfreeze it, and the process will
  685. // force to terminate immediately.
  686. logrus.Debugf("Found container %s is paused, sending SIGTERM before unpause it", c.ID)
  687. sig, ok := signal.SignalMap["TERM"]
  688. if !ok {
  689. logrus.Warnf("System does not support SIGTERM")
  690. return
  691. }
  692. if err := daemon.kill(c, int(sig)); err != nil {
  693. logrus.Debugf("sending SIGTERM to container %s with error: %v", c.ID, err)
  694. return
  695. }
  696. if err := c.unpause(); err != nil {
  697. logrus.Debugf("Failed to unpause container %s with error: %v", c.ID, err)
  698. return
  699. }
  700. if _, err := c.WaitStop(10 * time.Second); err != nil {
  701. logrus.Debugf("container %s failed to exit in 10 second of SIGTERM, sending SIGKILL to force", c.ID)
  702. sig, ok := signal.SignalMap["KILL"]
  703. if !ok {
  704. logrus.Warnf("System does not support SIGKILL")
  705. return
  706. }
  707. daemon.kill(c, int(sig))
  708. }
  709. } else {
  710. // If container failed to exit in 10 seconds of SIGTERM, then using the force
  711. if err := c.Stop(10); err != nil {
  712. logrus.Errorf("Stop container %s with error: %v", c.ID, err)
  713. }
  714. }
  715. c.WaitStop(-1 * time.Second)
  716. logrus.Debugf("container stopped %s", c.ID)
  717. }()
  718. }
  719. }
  720. group.Wait()
  721. // trigger libnetwork Stop only if it's initialized
  722. if daemon.netController != nil {
  723. daemon.netController.Stop()
  724. }
  725. }
  726. if daemon.containerGraphDB != nil {
  727. if err := daemon.containerGraphDB.Close(); err != nil {
  728. logrus.Errorf("Error during container graph.Close(): %v", err)
  729. }
  730. }
  731. if daemon.driver != nil {
  732. if err := daemon.driver.Cleanup(); err != nil {
  733. logrus.Errorf("Error during graph storage driver.Cleanup(): %v", err)
  734. }
  735. }
  736. return nil
  737. }
  738. // Mount sets container.basefs
  739. // (is it not set coming in? why is it unset?)
  740. func (daemon *Daemon) Mount(container *Container) error {
  741. dir, err := daemon.driver.Get(container.ID, container.getMountLabel())
  742. if err != nil {
  743. return fmt.Errorf("Error getting container %s from driver %s: %s", container.ID, daemon.driver, err)
  744. }
  745. if container.basefs != dir {
  746. // The mount path reported by the graph driver should always be trusted on Windows, since the
  747. // volume path for a given mounted layer may change over time. This should only be an error
  748. // on non-Windows operating systems.
  749. if container.basefs != "" && runtime.GOOS != "windows" {
  750. daemon.driver.Put(container.ID)
  751. return fmt.Errorf("Error: driver %s is returning inconsistent paths for container %s ('%s' then '%s')",
  752. daemon.driver, container.ID, container.basefs, dir)
  753. }
  754. }
  755. container.basefs = dir
  756. return nil
  757. }
  758. func (daemon *Daemon) unmount(container *Container) error {
  759. daemon.driver.Put(container.ID)
  760. return nil
  761. }
  762. func (daemon *Daemon) run(c *Container, pipes *execdriver.Pipes, startCallback execdriver.DriverCallback) (execdriver.ExitStatus, error) {
  763. hooks := execdriver.Hooks{
  764. Start: startCallback,
  765. }
  766. hooks.PreStart = append(hooks.PreStart, func(processConfig *execdriver.ProcessConfig, pid int) error {
  767. return c.setNetworkNamespaceKey(pid)
  768. })
  769. return daemon.execDriver.Run(c.command, pipes, hooks)
  770. }
  771. func (daemon *Daemon) kill(c *Container, sig int) error {
  772. return daemon.execDriver.Kill(c.command, sig)
  773. }
  774. func (daemon *Daemon) stats(c *Container) (*execdriver.ResourceStats, error) {
  775. return daemon.execDriver.Stats(c.ID)
  776. }
  777. func (daemon *Daemon) subscribeToContainerStats(c *Container) (chan interface{}, error) {
  778. ch := daemon.statsCollector.collect(c)
  779. return ch, nil
  780. }
  781. func (daemon *Daemon) unsubscribeToContainerStats(c *Container, ch chan interface{}) error {
  782. daemon.statsCollector.unsubscribe(c, ch)
  783. return nil
  784. }
  785. func (daemon *Daemon) changes(container *Container) ([]archive.Change, error) {
  786. initID := fmt.Sprintf("%s-init", container.ID)
  787. return daemon.driver.Changes(container.ID, initID)
  788. }
  789. func (daemon *Daemon) diff(container *Container) (archive.Archive, error) {
  790. initID := fmt.Sprintf("%s-init", container.ID)
  791. return daemon.driver.Diff(container.ID, initID)
  792. }
  793. func (daemon *Daemon) createRootfs(container *Container) error {
  794. // Step 1: create the container directory.
  795. // This doubles as a barrier to avoid race conditions.
  796. if err := os.Mkdir(container.root, 0700); err != nil {
  797. return err
  798. }
  799. initID := fmt.Sprintf("%s-init", container.ID)
  800. if err := daemon.driver.Create(initID, container.ImageID); err != nil {
  801. return err
  802. }
  803. initPath, err := daemon.driver.Get(initID, "")
  804. if err != nil {
  805. return err
  806. }
  807. if err := setupInitLayer(initPath); err != nil {
  808. daemon.driver.Put(initID)
  809. return err
  810. }
  811. // We want to unmount init layer before we take snapshot of it
  812. // for the actual container.
  813. daemon.driver.Put(initID)
  814. if err := daemon.driver.Create(container.ID, initID); err != nil {
  815. return err
  816. }
  817. return nil
  818. }
  819. // Graph needs to be removed.
  820. //
  821. // FIXME: this is a convenience function for integration tests
  822. // which need direct access to daemon.graph.
  823. // Once the tests switch to using engine and jobs, this method
  824. // can go away.
  825. func (daemon *Daemon) Graph() *graph.Graph {
  826. return daemon.graph
  827. }
  828. // Repositories returns all repositories.
  829. func (daemon *Daemon) Repositories() *graph.TagStore {
  830. return daemon.repositories
  831. }
  832. func (daemon *Daemon) config() *Config {
  833. return daemon.configStore
  834. }
  835. func (daemon *Daemon) systemInitPath() string {
  836. return daemon.sysInitPath
  837. }
  838. // GraphDriver returns the currently used driver for processing
  839. // container layers.
  840. func (daemon *Daemon) GraphDriver() graphdriver.Driver {
  841. return daemon.driver
  842. }
  843. // ExecutionDriver returns the currently used driver for creating and
  844. // starting execs in a container.
  845. func (daemon *Daemon) ExecutionDriver() execdriver.Driver {
  846. return daemon.execDriver
  847. }
  848. func (daemon *Daemon) containerGraph() *graphdb.Database {
  849. return daemon.containerGraphDB
  850. }
  851. // ImageGetCached returns the earliest created image that is a child
  852. // of the image with imgID, that had the same config when it was
  853. // created. nil is returned if a child cannot be found. An error is
  854. // returned if the parent image cannot be found.
  855. func (daemon *Daemon) ImageGetCached(imgID string, config *runconfig.Config) (*image.Image, error) {
  856. // Retrieve all images
  857. images := daemon.Graph().Map()
  858. // Store the tree in a map of map (map[parentId][childId])
  859. imageMap := make(map[string]map[string]struct{})
  860. for _, img := range images {
  861. if _, exists := imageMap[img.Parent]; !exists {
  862. imageMap[img.Parent] = make(map[string]struct{})
  863. }
  864. imageMap[img.Parent][img.ID] = struct{}{}
  865. }
  866. // Loop on the children of the given image and check the config
  867. var match *image.Image
  868. for elem := range imageMap[imgID] {
  869. img, ok := images[elem]
  870. if !ok {
  871. return nil, fmt.Errorf("unable to find image %q", elem)
  872. }
  873. if runconfig.Compare(&img.ContainerConfig, config) {
  874. if match == nil || match.Created.Before(img.Created) {
  875. match = img
  876. }
  877. }
  878. }
  879. return match, nil
  880. }
  881. // tempDir returns the default directory to use for temporary files.
  882. func tempDir(rootDir string) (string, error) {
  883. var tmpDir string
  884. if tmpDir = os.Getenv("DOCKER_TMPDIR"); tmpDir == "" {
  885. tmpDir = filepath.Join(rootDir, "tmp")
  886. }
  887. return tmpDir, system.MkdirAll(tmpDir, 0700)
  888. }
  889. func (daemon *Daemon) setHostConfig(container *Container, hostConfig *runconfig.HostConfig) error {
  890. container.Lock()
  891. if err := parseSecurityOpt(container, hostConfig); err != nil {
  892. container.Unlock()
  893. return err
  894. }
  895. container.Unlock()
  896. // Do not lock while creating volumes since this could be calling out to external plugins
  897. // Don't want to block other actions, like `docker ps` because we're waiting on an external plugin
  898. if err := daemon.registerMountPoints(container, hostConfig); err != nil {
  899. return err
  900. }
  901. container.Lock()
  902. defer container.Unlock()
  903. // Register any links from the host config before starting the container
  904. if err := daemon.registerLinks(container, hostConfig); err != nil {
  905. return err
  906. }
  907. container.hostConfig = hostConfig
  908. container.toDisk()
  909. return nil
  910. }
  911. func setDefaultMtu(config *Config) {
  912. // do nothing if the config does not have the default 0 value.
  913. if config.Mtu != 0 {
  914. return
  915. }
  916. config.Mtu = defaultNetworkMtu
  917. if routeMtu, err := getDefaultRouteMtu(); err == nil {
  918. config.Mtu = routeMtu
  919. }
  920. }
  921. var errNoDefaultRoute = errors.New("no default route was found")
  922. // getDefaultRouteMtu returns the MTU for the default route's interface.
  923. func getDefaultRouteMtu() (int, error) {
  924. routes, err := netlink.NetworkGetRoutes()
  925. if err != nil {
  926. return 0, err
  927. }
  928. for _, r := range routes {
  929. if r.Default && r.Iface != nil {
  930. return r.Iface.MTU, nil
  931. }
  932. }
  933. return 0, errNoDefaultRoute
  934. }
  935. // verifyContainerSettings performs validation of the hostconfig and config
  936. // structures.
  937. func (daemon *Daemon) verifyContainerSettings(hostConfig *runconfig.HostConfig, config *runconfig.Config) ([]string, error) {
  938. // First perform verification of settings common across all platforms.
  939. if config != nil {
  940. if config.WorkingDir != "" {
  941. config.WorkingDir = filepath.FromSlash(config.WorkingDir) // Ensure in platform semantics
  942. if !system.IsAbs(config.WorkingDir) {
  943. return nil, fmt.Errorf("The working directory '%s' is invalid. It needs to be an absolute path.", config.WorkingDir)
  944. }
  945. }
  946. if len(config.StopSignal) > 0 {
  947. _, err := signal.ParseSignal(config.StopSignal)
  948. if err != nil {
  949. return nil, err
  950. }
  951. }
  952. }
  953. if hostConfig == nil {
  954. return nil, nil
  955. }
  956. for port := range hostConfig.PortBindings {
  957. _, portStr := nat.SplitProtoPort(string(port))
  958. if _, err := nat.ParsePort(portStr); err != nil {
  959. return nil, fmt.Errorf("Invalid port specification: %q", portStr)
  960. }
  961. for _, pb := range hostConfig.PortBindings[port] {
  962. _, err := nat.NewPort(nat.SplitProtoPort(pb.HostPort))
  963. if err != nil {
  964. return nil, fmt.Errorf("Invalid port specification: %q", pb.HostPort)
  965. }
  966. }
  967. }
  968. // Now do platform-specific verification
  969. return verifyPlatformContainerSettings(daemon, hostConfig, config)
  970. }
  971. func configureVolumes(config *Config) (*volumeStore, error) {
  972. volumesDriver, err := local.New(config.Root)
  973. if err != nil {
  974. return nil, err
  975. }
  976. volumedrivers.Register(volumesDriver, volumesDriver.Name())
  977. return newVolumeStore(volumesDriver.List()), nil
  978. }