daemon.go 36 KB

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