daemon.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  1. package daemon
  2. import (
  3. "container/list"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "log"
  8. "os"
  9. "path"
  10. "regexp"
  11. "strings"
  12. "sync"
  13. "time"
  14. "github.com/dotcloud/docker/archive"
  15. "github.com/dotcloud/docker/daemon/execdriver"
  16. "github.com/dotcloud/docker/daemon/execdriver/execdrivers"
  17. "github.com/dotcloud/docker/daemon/execdriver/lxc"
  18. "github.com/dotcloud/docker/daemon/graphdriver"
  19. _ "github.com/dotcloud/docker/daemon/graphdriver/vfs"
  20. _ "github.com/dotcloud/docker/daemon/networkdriver/bridge"
  21. "github.com/dotcloud/docker/daemon/networkdriver/portallocator"
  22. "github.com/dotcloud/docker/daemonconfig"
  23. "github.com/dotcloud/docker/dockerversion"
  24. "github.com/dotcloud/docker/engine"
  25. "github.com/dotcloud/docker/graph"
  26. "github.com/dotcloud/docker/image"
  27. "github.com/dotcloud/docker/pkg/graphdb"
  28. "github.com/dotcloud/docker/pkg/label"
  29. "github.com/dotcloud/docker/pkg/mount"
  30. "github.com/dotcloud/docker/pkg/selinux"
  31. "github.com/dotcloud/docker/pkg/sysinfo"
  32. "github.com/dotcloud/docker/runconfig"
  33. "github.com/dotcloud/docker/utils"
  34. )
  35. // Set the max depth to the aufs default that most
  36. // kernels are compiled with
  37. // For more information see: http://sourceforge.net/p/aufs/aufs3-standalone/ci/aufs3.12/tree/config.mk
  38. const MaxImageDepth = 127
  39. var (
  40. DefaultDns = []string{"8.8.8.8", "8.8.4.4"}
  41. validContainerNameChars = `[a-zA-Z0-9_.-]`
  42. validContainerNamePattern = regexp.MustCompile(`^/?` + validContainerNameChars + `+$`)
  43. )
  44. type Daemon struct {
  45. repository string
  46. sysInitPath string
  47. containers *list.List
  48. graph *graph.Graph
  49. repositories *graph.TagStore
  50. idIndex *utils.TruncIndex
  51. sysInfo *sysinfo.SysInfo
  52. volumes *graph.Graph
  53. srv Server
  54. eng *engine.Engine
  55. config *daemonconfig.Config
  56. containerGraph *graphdb.Database
  57. driver graphdriver.Driver
  58. execDriver execdriver.Driver
  59. }
  60. // Mountpoints should be private to the container
  61. func remountPrivate(mountPoint string) error {
  62. mounted, err := mount.Mounted(mountPoint)
  63. if err != nil {
  64. return err
  65. }
  66. if !mounted {
  67. if err := mount.Mount(mountPoint, mountPoint, "none", "bind,rw"); err != nil {
  68. return err
  69. }
  70. }
  71. return mount.ForceMount("", mountPoint, "none", "private")
  72. }
  73. // List returns an array of all containers registered in the daemon.
  74. func (daemon *Daemon) List() []*Container {
  75. containers := new(History)
  76. for e := daemon.containers.Front(); e != nil; e = e.Next() {
  77. containers.Add(e.Value.(*Container))
  78. }
  79. return *containers
  80. }
  81. func (daemon *Daemon) getContainerElement(id string) *list.Element {
  82. for e := daemon.containers.Front(); e != nil; e = e.Next() {
  83. container := e.Value.(*Container)
  84. if container.ID == id {
  85. return e
  86. }
  87. }
  88. return nil
  89. }
  90. // Get looks for a container by the specified ID or name, and returns it.
  91. // If the container is not found, or if an error occurs, nil is returned.
  92. func (daemon *Daemon) Get(name string) *Container {
  93. if c, _ := daemon.GetByName(name); c != nil {
  94. return c
  95. }
  96. id, err := daemon.idIndex.Get(name)
  97. if err != nil {
  98. return nil
  99. }
  100. e := daemon.getContainerElement(id)
  101. if e == nil {
  102. return nil
  103. }
  104. return e.Value.(*Container)
  105. }
  106. // Exists returns a true if a container of the specified ID or name exists,
  107. // false otherwise.
  108. func (daemon *Daemon) Exists(id string) bool {
  109. return daemon.Get(id) != nil
  110. }
  111. func (daemon *Daemon) containerRoot(id string) string {
  112. return path.Join(daemon.repository, id)
  113. }
  114. // Load reads the contents of a container from disk
  115. // This is typically done at startup.
  116. func (daemon *Daemon) load(id string) (*Container, error) {
  117. container := &Container{root: daemon.containerRoot(id)}
  118. if err := container.FromDisk(); err != nil {
  119. return nil, err
  120. }
  121. if container.ID != id {
  122. return container, fmt.Errorf("Container %s is stored at %s", container.ID, id)
  123. }
  124. return container, nil
  125. }
  126. // Register makes a container object usable by the daemon as <container.ID>
  127. func (daemon *Daemon) Register(container *Container) error {
  128. if container.daemon != nil || daemon.Exists(container.ID) {
  129. return fmt.Errorf("Container is already loaded")
  130. }
  131. if err := validateID(container.ID); err != nil {
  132. return err
  133. }
  134. if err := daemon.ensureName(container); err != nil {
  135. return err
  136. }
  137. container.daemon = daemon
  138. // Attach to stdout and stderr
  139. container.stderr = utils.NewWriteBroadcaster()
  140. container.stdout = utils.NewWriteBroadcaster()
  141. // Attach to stdin
  142. if container.Config.OpenStdin {
  143. container.stdin, container.stdinPipe = io.Pipe()
  144. } else {
  145. container.stdinPipe = utils.NopWriteCloser(ioutil.Discard) // Silently drop stdin
  146. }
  147. // done
  148. daemon.containers.PushBack(container)
  149. daemon.idIndex.Add(container.ID)
  150. // FIXME: if the container is supposed to be running but is not, auto restart it?
  151. // if so, then we need to restart monitor and init a new lock
  152. // If the container is supposed to be running, make sure of it
  153. if container.State.IsRunning() {
  154. utils.Debugf("killing old running container %s", container.ID)
  155. existingPid := container.State.Pid
  156. container.State.SetStopped(0)
  157. // We only have to handle this for lxc because the other drivers will ensure that
  158. // no processes are left when docker dies
  159. if container.ExecDriver == "" || strings.Contains(container.ExecDriver, "lxc") {
  160. lxc.KillLxc(container.ID, 9)
  161. } else {
  162. // use the current driver and ensure that the container is dead x.x
  163. cmd := &execdriver.Command{
  164. ID: container.ID,
  165. }
  166. var err error
  167. cmd.Process, err = os.FindProcess(existingPid)
  168. if err != nil {
  169. utils.Debugf("cannot find existing process for %d", existingPid)
  170. }
  171. daemon.execDriver.Terminate(cmd)
  172. }
  173. if err := container.Unmount(); err != nil {
  174. utils.Debugf("unmount error %s", err)
  175. }
  176. if err := container.ToDisk(); err != nil {
  177. utils.Debugf("saving stopped state to disk %s", err)
  178. }
  179. info := daemon.execDriver.Info(container.ID)
  180. if !info.IsRunning() {
  181. utils.Debugf("Container %s was supposed to be running but is not.", container.ID)
  182. if daemon.config.AutoRestart {
  183. utils.Debugf("Restarting")
  184. if err := container.Unmount(); err != nil {
  185. utils.Debugf("restart unmount error %s", err)
  186. }
  187. if err := container.Start(); err != nil {
  188. return err
  189. }
  190. } else {
  191. utils.Debugf("Marking as stopped")
  192. container.State.SetStopped(-127)
  193. if err := container.ToDisk(); err != nil {
  194. return err
  195. }
  196. }
  197. }
  198. } else {
  199. // When the container is not running, we still initialize the waitLock
  200. // chan and close it. Receiving on nil chan blocks whereas receiving on a
  201. // closed chan does not. In this case we do not want to block.
  202. container.waitLock = make(chan struct{})
  203. close(container.waitLock)
  204. }
  205. return nil
  206. }
  207. func (daemon *Daemon) ensureName(container *Container) error {
  208. if container.Name == "" {
  209. name, err := generateRandomName(daemon)
  210. if err != nil {
  211. name = utils.TruncateID(container.ID)
  212. }
  213. container.Name = name
  214. if err := container.ToDisk(); err != nil {
  215. utils.Debugf("Error saving container name %s", err)
  216. }
  217. if !daemon.containerGraph.Exists(name) {
  218. if _, err := daemon.containerGraph.Set(name, container.ID); err != nil {
  219. utils.Debugf("Setting default id - %s", err)
  220. }
  221. }
  222. }
  223. return nil
  224. }
  225. func (daemon *Daemon) LogToDisk(src *utils.WriteBroadcaster, dst, stream string) error {
  226. log, err := os.OpenFile(dst, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0600)
  227. if err != nil {
  228. return err
  229. }
  230. src.AddWriter(log, stream)
  231. return nil
  232. }
  233. // Destroy unregisters a container from the daemon and cleanly removes its contents from the filesystem.
  234. func (daemon *Daemon) Destroy(container *Container) error {
  235. if container == nil {
  236. return fmt.Errorf("The given container is <nil>")
  237. }
  238. element := daemon.getContainerElement(container.ID)
  239. if element == nil {
  240. return fmt.Errorf("Container %v not found - maybe it was already destroyed?", container.ID)
  241. }
  242. if err := container.Stop(3); err != nil {
  243. return err
  244. }
  245. if err := daemon.driver.Remove(container.ID); err != nil {
  246. return fmt.Errorf("Driver %s failed to remove root filesystem %s: %s", daemon.driver, container.ID, err)
  247. }
  248. initID := fmt.Sprintf("%s-init", container.ID)
  249. if err := daemon.driver.Remove(initID); err != nil {
  250. return fmt.Errorf("Driver %s failed to remove init filesystem %s: %s", daemon.driver, initID, err)
  251. }
  252. if _, err := daemon.containerGraph.Purge(container.ID); err != nil {
  253. utils.Debugf("Unable to remove container from link graph: %s", err)
  254. }
  255. // Deregister the container before removing its directory, to avoid race conditions
  256. daemon.idIndex.Delete(container.ID)
  257. daemon.containers.Remove(element)
  258. if err := os.RemoveAll(container.root); err != nil {
  259. return fmt.Errorf("Unable to remove filesystem for %v: %v", container.ID, err)
  260. }
  261. selinux.FreeLxcContexts(container.ProcessLabel)
  262. return nil
  263. }
  264. func (daemon *Daemon) restore() error {
  265. if os.Getenv("DEBUG") == "" && os.Getenv("TEST") == "" {
  266. fmt.Printf("Loading containers: ")
  267. }
  268. dir, err := ioutil.ReadDir(daemon.repository)
  269. if err != nil {
  270. return err
  271. }
  272. containers := make(map[string]*Container)
  273. currentDriver := daemon.driver.String()
  274. for _, v := range dir {
  275. id := v.Name()
  276. container, err := daemon.load(id)
  277. if os.Getenv("DEBUG") == "" && os.Getenv("TEST") == "" {
  278. fmt.Print(".")
  279. }
  280. if err != nil {
  281. utils.Errorf("Failed to load container %v: %v", id, err)
  282. continue
  283. }
  284. // Ignore the container if it does not support the current driver being used by the graph
  285. if container.Driver == "" && currentDriver == "aufs" || container.Driver == currentDriver {
  286. utils.Debugf("Loaded container %v", container.ID)
  287. containers[container.ID] = container
  288. } else {
  289. utils.Debugf("Cannot load container %s because it was created with another graph driver.", container.ID)
  290. }
  291. }
  292. register := func(container *Container) {
  293. if err := daemon.Register(container); err != nil {
  294. utils.Debugf("Failed to register container %s: %s", container.ID, err)
  295. }
  296. }
  297. if entities := daemon.containerGraph.List("/", -1); entities != nil {
  298. for _, p := range entities.Paths() {
  299. if os.Getenv("DEBUG") == "" && os.Getenv("TEST") == "" {
  300. fmt.Print(".")
  301. }
  302. e := entities[p]
  303. if container, ok := containers[e.ID()]; ok {
  304. register(container)
  305. delete(containers, e.ID())
  306. }
  307. }
  308. }
  309. // Any containers that are left over do not exist in the graph
  310. for _, container := range containers {
  311. // Try to set the default name for a container if it exists prior to links
  312. container.Name, err = generateRandomName(daemon)
  313. if err != nil {
  314. container.Name = utils.TruncateID(container.ID)
  315. }
  316. if _, err := daemon.containerGraph.Set(container.Name, container.ID); err != nil {
  317. utils.Debugf("Setting default id - %s", err)
  318. }
  319. register(container)
  320. }
  321. if os.Getenv("DEBUG") == "" && os.Getenv("TEST") == "" {
  322. fmt.Printf(": done.\n")
  323. }
  324. return nil
  325. }
  326. // Create creates a new container from the given configuration with a given name.
  327. func (daemon *Daemon) Create(config *runconfig.Config, name string) (*Container, []string, error) {
  328. var (
  329. container *Container
  330. warnings []string
  331. )
  332. img, err := daemon.repositories.LookupImage(config.Image)
  333. if err != nil {
  334. return nil, nil, err
  335. }
  336. if err := daemon.checkImageDepth(img); err != nil {
  337. return nil, nil, err
  338. }
  339. if warnings, err = daemon.mergeAndVerifyConfig(config, img); err != nil {
  340. return nil, nil, err
  341. }
  342. if container, err = daemon.newContainer(name, config, img); err != nil {
  343. return nil, nil, err
  344. }
  345. if err := daemon.createRootfs(container, img); err != nil {
  346. return nil, nil, err
  347. }
  348. if err := container.ToDisk(); err != nil {
  349. return nil, nil, err
  350. }
  351. if err := daemon.Register(container); err != nil {
  352. return nil, nil, err
  353. }
  354. return container, warnings, nil
  355. }
  356. func (daemon *Daemon) checkImageDepth(img *image.Image) error {
  357. // We add 2 layers to the depth because the container's rw and
  358. // init layer add to the restriction
  359. depth, err := img.Depth()
  360. if err != nil {
  361. return err
  362. }
  363. if depth+2 >= MaxImageDepth {
  364. return fmt.Errorf("Cannot create container with more than %d parents", MaxImageDepth)
  365. }
  366. return nil
  367. }
  368. func (daemon *Daemon) checkDeprecatedExpose(config *runconfig.Config) bool {
  369. if config != nil {
  370. if config.PortSpecs != nil {
  371. for _, p := range config.PortSpecs {
  372. if strings.Contains(p, ":") {
  373. return true
  374. }
  375. }
  376. }
  377. }
  378. return false
  379. }
  380. func (daemon *Daemon) mergeAndVerifyConfig(config *runconfig.Config, img *image.Image) ([]string, error) {
  381. warnings := []string{}
  382. if daemon.checkDeprecatedExpose(img.Config) || daemon.checkDeprecatedExpose(config) {
  383. warnings = append(warnings, "The mapping to public ports on your host via Dockerfile EXPOSE (host:port:port) has been deprecated. Use -p to publish the ports.")
  384. }
  385. if img.Config != nil {
  386. if err := runconfig.Merge(config, img.Config); err != nil {
  387. return nil, err
  388. }
  389. }
  390. if len(config.Entrypoint) == 0 && len(config.Cmd) == 0 {
  391. return nil, fmt.Errorf("No command specified")
  392. }
  393. return warnings, nil
  394. }
  395. func (daemon *Daemon) generateIdAndName(name string) (string, string, error) {
  396. var (
  397. err error
  398. id = utils.GenerateRandomID()
  399. )
  400. if name == "" {
  401. name, err = generateRandomName(daemon)
  402. if err != nil {
  403. name = utils.TruncateID(id)
  404. }
  405. } else {
  406. if !validContainerNamePattern.MatchString(name) {
  407. return "", "", fmt.Errorf("Invalid container name (%s), only %s are allowed", name, validContainerNameChars)
  408. }
  409. }
  410. if name[0] != '/' {
  411. name = "/" + name
  412. }
  413. // Set the enitity in the graph using the default name specified
  414. if _, err := daemon.containerGraph.Set(name, id); err != nil {
  415. if !graphdb.IsNonUniqueNameError(err) {
  416. return "", "", err
  417. }
  418. conflictingContainer, err := daemon.GetByName(name)
  419. if err != nil {
  420. if strings.Contains(err.Error(), "Could not find entity") {
  421. return "", "", err
  422. }
  423. // Remove name and continue starting the container
  424. if err := daemon.containerGraph.Delete(name); err != nil {
  425. return "", "", err
  426. }
  427. } else {
  428. nameAsKnownByUser := strings.TrimPrefix(name, "/")
  429. return "", "", fmt.Errorf(
  430. "Conflict, The name %s is already assigned to %s. You have to delete (or rename) that container to be able to assign %s to a container again.", nameAsKnownByUser,
  431. utils.TruncateID(conflictingContainer.ID), nameAsKnownByUser)
  432. }
  433. }
  434. return id, name, nil
  435. }
  436. func (daemon *Daemon) generateHostname(id string, config *runconfig.Config) {
  437. // Generate default hostname
  438. // FIXME: the lxc template no longer needs to set a default hostname
  439. if config.Hostname == "" {
  440. config.Hostname = id[:12]
  441. }
  442. }
  443. func (daemon *Daemon) getEntrypointAndArgs(config *runconfig.Config) (string, []string) {
  444. var (
  445. entrypoint string
  446. args []string
  447. )
  448. if len(config.Entrypoint) != 0 {
  449. entrypoint = config.Entrypoint[0]
  450. args = append(config.Entrypoint[1:], config.Cmd...)
  451. } else {
  452. entrypoint = config.Cmd[0]
  453. args = config.Cmd[1:]
  454. }
  455. return entrypoint, args
  456. }
  457. func (daemon *Daemon) newContainer(name string, config *runconfig.Config, img *image.Image) (*Container, error) {
  458. var (
  459. id string
  460. err error
  461. )
  462. id, name, err = daemon.generateIdAndName(name)
  463. if err != nil {
  464. return nil, err
  465. }
  466. daemon.generateHostname(id, config)
  467. entrypoint, args := daemon.getEntrypointAndArgs(config)
  468. container := &Container{
  469. // FIXME: we should generate the ID here instead of receiving it as an argument
  470. ID: id,
  471. Created: time.Now().UTC(),
  472. Path: entrypoint,
  473. Args: args, //FIXME: de-duplicate from config
  474. Config: config,
  475. hostConfig: &runconfig.HostConfig{},
  476. Image: img.ID, // Always use the resolved image id
  477. NetworkSettings: &NetworkSettings{},
  478. Name: name,
  479. Driver: daemon.driver.String(),
  480. ExecDriver: daemon.execDriver.Name(),
  481. }
  482. container.root = daemon.containerRoot(container.ID)
  483. if container.ProcessLabel, container.MountLabel, err = label.GenLabels(""); err != nil {
  484. return nil, err
  485. }
  486. return container, nil
  487. }
  488. func (daemon *Daemon) createRootfs(container *Container, img *image.Image) error {
  489. // Step 1: create the container directory.
  490. // This doubles as a barrier to avoid race conditions.
  491. if err := os.Mkdir(container.root, 0700); err != nil {
  492. return err
  493. }
  494. initID := fmt.Sprintf("%s-init", container.ID)
  495. if err := daemon.driver.Create(initID, img.ID); err != nil {
  496. return err
  497. }
  498. initPath, err := daemon.driver.Get(initID, "")
  499. if err != nil {
  500. return err
  501. }
  502. defer daemon.driver.Put(initID)
  503. if err := graph.SetupInitLayer(initPath); err != nil {
  504. return err
  505. }
  506. if err := daemon.driver.Create(container.ID, initID); err != nil {
  507. return err
  508. }
  509. return nil
  510. }
  511. // Commit creates a new filesystem image from the current state of a container.
  512. // The image can optionally be tagged into a repository
  513. func (daemon *Daemon) Commit(container *Container, repository, tag, comment, author string, config *runconfig.Config) (*image.Image, error) {
  514. // FIXME: freeze the container before copying it to avoid data corruption?
  515. if err := container.Mount(); err != nil {
  516. return nil, err
  517. }
  518. defer container.Unmount()
  519. rwTar, err := container.ExportRw()
  520. if err != nil {
  521. return nil, err
  522. }
  523. defer rwTar.Close()
  524. // Create a new image from the container's base layers + a new layer from container changes
  525. var (
  526. containerID, containerImage string
  527. containerConfig *runconfig.Config
  528. )
  529. if container != nil {
  530. containerID = container.ID
  531. containerImage = container.Image
  532. containerConfig = container.Config
  533. }
  534. img, err := daemon.graph.Create(rwTar, containerID, containerImage, comment, author, containerConfig, config)
  535. if err != nil {
  536. return nil, err
  537. }
  538. // Register the image if needed
  539. if repository != "" {
  540. if err := daemon.repositories.Set(repository, tag, img.ID, true); err != nil {
  541. return img, err
  542. }
  543. }
  544. return img, nil
  545. }
  546. func GetFullContainerName(name string) (string, error) {
  547. if name == "" {
  548. return "", fmt.Errorf("Container name cannot be empty")
  549. }
  550. if name[0] != '/' {
  551. name = "/" + name
  552. }
  553. return name, nil
  554. }
  555. func (daemon *Daemon) GetByName(name string) (*Container, error) {
  556. fullName, err := GetFullContainerName(name)
  557. if err != nil {
  558. return nil, err
  559. }
  560. entity := daemon.containerGraph.Get(fullName)
  561. if entity == nil {
  562. return nil, fmt.Errorf("Could not find entity for %s", name)
  563. }
  564. e := daemon.getContainerElement(entity.ID())
  565. if e == nil {
  566. return nil, fmt.Errorf("Could not find container for entity id %s", entity.ID())
  567. }
  568. return e.Value.(*Container), nil
  569. }
  570. func (daemon *Daemon) Children(name string) (map[string]*Container, error) {
  571. name, err := GetFullContainerName(name)
  572. if err != nil {
  573. return nil, err
  574. }
  575. children := make(map[string]*Container)
  576. err = daemon.containerGraph.Walk(name, func(p string, e *graphdb.Entity) error {
  577. c := daemon.Get(e.ID())
  578. if c == nil {
  579. return fmt.Errorf("Could not get container for name %s and id %s", e.ID(), p)
  580. }
  581. children[p] = c
  582. return nil
  583. }, 0)
  584. if err != nil {
  585. return nil, err
  586. }
  587. return children, nil
  588. }
  589. func (daemon *Daemon) RegisterLink(parent, child *Container, alias string) error {
  590. fullName := path.Join(parent.Name, alias)
  591. if !daemon.containerGraph.Exists(fullName) {
  592. _, err := daemon.containerGraph.Set(fullName, child.ID)
  593. return err
  594. }
  595. return nil
  596. }
  597. // FIXME: harmonize with NewGraph()
  598. func NewDaemon(config *daemonconfig.Config, eng *engine.Engine) (*Daemon, error) {
  599. daemon, err := NewDaemonFromDirectory(config, eng)
  600. if err != nil {
  601. return nil, err
  602. }
  603. return daemon, nil
  604. }
  605. func NewDaemonFromDirectory(config *daemonconfig.Config, eng *engine.Engine) (*Daemon, error) {
  606. if !config.EnableSelinuxSupport {
  607. selinux.SetDisabled()
  608. }
  609. // Set the default driver
  610. graphdriver.DefaultDriver = config.GraphDriver
  611. // Load storage driver
  612. driver, err := graphdriver.New(config.Root)
  613. if err != nil {
  614. return nil, err
  615. }
  616. utils.Debugf("Using graph driver %s", driver)
  617. if err := remountPrivate(config.Root); err != nil {
  618. return nil, err
  619. }
  620. daemonRepo := path.Join(config.Root, "containers")
  621. if err := os.MkdirAll(daemonRepo, 0700); err != nil && !os.IsExist(err) {
  622. return nil, err
  623. }
  624. // Migrate the container if it is aufs and aufs is enabled
  625. if err = migrateIfAufs(driver, config.Root); err != nil {
  626. return nil, err
  627. }
  628. utils.Debugf("Creating images graph")
  629. g, err := graph.NewGraph(path.Join(config.Root, "graph"), driver)
  630. if err != nil {
  631. return nil, err
  632. }
  633. // We don't want to use a complex driver like aufs or devmapper
  634. // for volumes, just a plain filesystem
  635. volumesDriver, err := graphdriver.GetDriver("vfs", config.Root)
  636. if err != nil {
  637. return nil, err
  638. }
  639. utils.Debugf("Creating volumes graph")
  640. volumes, err := graph.NewGraph(path.Join(config.Root, "volumes"), volumesDriver)
  641. if err != nil {
  642. return nil, err
  643. }
  644. utils.Debugf("Creating repository list")
  645. repositories, err := graph.NewTagStore(path.Join(config.Root, "repositories-"+driver.String()), g)
  646. if err != nil {
  647. return nil, fmt.Errorf("Couldn't create Tag store: %s", err)
  648. }
  649. if !config.DisableNetwork {
  650. job := eng.Job("init_networkdriver")
  651. job.SetenvBool("EnableIptables", config.EnableIptables)
  652. job.SetenvBool("InterContainerCommunication", config.InterContainerCommunication)
  653. job.SetenvBool("EnableIpForward", config.EnableIpForward)
  654. job.Setenv("BridgeIface", config.BridgeIface)
  655. job.Setenv("BridgeIP", config.BridgeIP)
  656. job.Setenv("DefaultBindingIP", config.DefaultIp.String())
  657. if err := job.Run(); err != nil {
  658. return nil, err
  659. }
  660. }
  661. graphdbPath := path.Join(config.Root, "linkgraph.db")
  662. graph, err := graphdb.NewSqliteConn(graphdbPath)
  663. if err != nil {
  664. return nil, err
  665. }
  666. localCopy := path.Join(config.Root, "init", fmt.Sprintf("dockerinit-%s", dockerversion.VERSION))
  667. sysInitPath := utils.DockerInitPath(localCopy)
  668. if sysInitPath == "" {
  669. return nil, fmt.Errorf("Could not locate dockerinit: This usually means docker was built incorrectly. See http://docs.docker.io/en/latest/contributing/devenvironment for official build instructions.")
  670. }
  671. if sysInitPath != localCopy {
  672. // When we find a suitable dockerinit binary (even if it's our local binary), we copy it into config.Root at localCopy for future use (so that the original can go away without that being a problem, for example during a package upgrade).
  673. if err := os.Mkdir(path.Dir(localCopy), 0700); err != nil && !os.IsExist(err) {
  674. return nil, err
  675. }
  676. if _, err := utils.CopyFile(sysInitPath, localCopy); err != nil {
  677. return nil, err
  678. }
  679. if err := os.Chmod(localCopy, 0700); err != nil {
  680. return nil, err
  681. }
  682. sysInitPath = localCopy
  683. }
  684. sysInfo := sysinfo.New(false)
  685. ed, err := execdrivers.NewDriver(config.ExecDriver, config.Root, sysInitPath, sysInfo)
  686. if err != nil {
  687. return nil, err
  688. }
  689. daemon := &Daemon{
  690. repository: daemonRepo,
  691. containers: list.New(),
  692. graph: g,
  693. repositories: repositories,
  694. idIndex: utils.NewTruncIndex([]string{}),
  695. sysInfo: sysInfo,
  696. volumes: volumes,
  697. config: config,
  698. containerGraph: graph,
  699. driver: driver,
  700. sysInitPath: sysInitPath,
  701. execDriver: ed,
  702. eng: eng,
  703. }
  704. if err := daemon.checkLocaldns(); err != nil {
  705. return nil, err
  706. }
  707. if err := daemon.restore(); err != nil {
  708. return nil, err
  709. }
  710. return daemon, nil
  711. }
  712. func (daemon *Daemon) shutdown() error {
  713. group := sync.WaitGroup{}
  714. utils.Debugf("starting clean shutdown of all containers...")
  715. for _, container := range daemon.List() {
  716. c := container
  717. if c.State.IsRunning() {
  718. utils.Debugf("stopping %s", c.ID)
  719. group.Add(1)
  720. go func() {
  721. defer group.Done()
  722. if err := c.KillSig(15); err != nil {
  723. utils.Debugf("kill 15 error for %s - %s", c.ID, err)
  724. }
  725. c.Wait()
  726. utils.Debugf("container stopped %s", c.ID)
  727. }()
  728. }
  729. }
  730. group.Wait()
  731. return nil
  732. }
  733. func (daemon *Daemon) Close() error {
  734. errorsStrings := []string{}
  735. if err := daemon.shutdown(); err != nil {
  736. utils.Errorf("daemon.shutdown(): %s", err)
  737. errorsStrings = append(errorsStrings, err.Error())
  738. }
  739. if err := portallocator.ReleaseAll(); err != nil {
  740. utils.Errorf("portallocator.ReleaseAll(): %s", err)
  741. errorsStrings = append(errorsStrings, err.Error())
  742. }
  743. if err := daemon.driver.Cleanup(); err != nil {
  744. utils.Errorf("daemon.driver.Cleanup(): %s", err.Error())
  745. errorsStrings = append(errorsStrings, err.Error())
  746. }
  747. if err := daemon.containerGraph.Close(); err != nil {
  748. utils.Errorf("daemon.containerGraph.Close(): %s", err.Error())
  749. errorsStrings = append(errorsStrings, err.Error())
  750. }
  751. if len(errorsStrings) > 0 {
  752. return fmt.Errorf("%s", strings.Join(errorsStrings, ", "))
  753. }
  754. return nil
  755. }
  756. func (daemon *Daemon) Mount(container *Container) error {
  757. dir, err := daemon.driver.Get(container.ID, container.GetMountLabel())
  758. if err != nil {
  759. return fmt.Errorf("Error getting container %s from driver %s: %s", container.ID, daemon.driver, err)
  760. }
  761. if container.basefs == "" {
  762. container.basefs = dir
  763. } else if container.basefs != dir {
  764. return fmt.Errorf("Error: driver %s is returning inconsistent paths for container %s ('%s' then '%s')",
  765. daemon.driver, container.ID, container.basefs, dir)
  766. }
  767. return nil
  768. }
  769. func (daemon *Daemon) Unmount(container *Container) error {
  770. daemon.driver.Put(container.ID)
  771. return nil
  772. }
  773. func (daemon *Daemon) Changes(container *Container) ([]archive.Change, error) {
  774. if differ, ok := daemon.driver.(graphdriver.Differ); ok {
  775. return differ.Changes(container.ID)
  776. }
  777. cDir, err := daemon.driver.Get(container.ID, "")
  778. if err != nil {
  779. return nil, fmt.Errorf("Error getting container rootfs %s from driver %s: %s", container.ID, container.daemon.driver, err)
  780. }
  781. defer daemon.driver.Put(container.ID)
  782. initDir, err := daemon.driver.Get(container.ID+"-init", "")
  783. if err != nil {
  784. return nil, fmt.Errorf("Error getting container init rootfs %s from driver %s: %s", container.ID, container.daemon.driver, err)
  785. }
  786. defer daemon.driver.Put(container.ID + "-init")
  787. return archive.ChangesDirs(cDir, initDir)
  788. }
  789. func (daemon *Daemon) Diff(container *Container) (archive.Archive, error) {
  790. if differ, ok := daemon.driver.(graphdriver.Differ); ok {
  791. return differ.Diff(container.ID)
  792. }
  793. changes, err := daemon.Changes(container)
  794. if err != nil {
  795. return nil, err
  796. }
  797. cDir, err := daemon.driver.Get(container.ID, "")
  798. if err != nil {
  799. return nil, fmt.Errorf("Error getting container rootfs %s from driver %s: %s", container.ID, container.daemon.driver, err)
  800. }
  801. archive, err := archive.ExportChanges(cDir, changes)
  802. if err != nil {
  803. return nil, err
  804. }
  805. return utils.NewReadCloserWrapper(archive, func() error {
  806. err := archive.Close()
  807. daemon.driver.Put(container.ID)
  808. return err
  809. }), nil
  810. }
  811. func (daemon *Daemon) Run(c *Container, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (int, error) {
  812. return daemon.execDriver.Run(c.command, pipes, startCallback)
  813. }
  814. func (daemon *Daemon) Kill(c *Container, sig int) error {
  815. return daemon.execDriver.Kill(c.command, sig)
  816. }
  817. // Nuke kills all containers then removes all content
  818. // from the content root, including images, volumes and
  819. // container filesystems.
  820. // Again: this will remove your entire docker daemon!
  821. func (daemon *Daemon) Nuke() error {
  822. var wg sync.WaitGroup
  823. for _, container := range daemon.List() {
  824. wg.Add(1)
  825. go func(c *Container) {
  826. c.Kill()
  827. wg.Done()
  828. }(container)
  829. }
  830. wg.Wait()
  831. daemon.Close()
  832. return os.RemoveAll(daemon.config.Root)
  833. }
  834. // FIXME: this is a convenience function for integration tests
  835. // which need direct access to daemon.graph.
  836. // Once the tests switch to using engine and jobs, this method
  837. // can go away.
  838. func (daemon *Daemon) Graph() *graph.Graph {
  839. return daemon.graph
  840. }
  841. func (daemon *Daemon) Repositories() *graph.TagStore {
  842. return daemon.repositories
  843. }
  844. func (daemon *Daemon) Config() *daemonconfig.Config {
  845. return daemon.config
  846. }
  847. func (daemon *Daemon) SystemConfig() *sysinfo.SysInfo {
  848. return daemon.sysInfo
  849. }
  850. func (daemon *Daemon) SystemInitPath() string {
  851. return daemon.sysInitPath
  852. }
  853. func (daemon *Daemon) GraphDriver() graphdriver.Driver {
  854. return daemon.driver
  855. }
  856. func (daemon *Daemon) ExecutionDriver() execdriver.Driver {
  857. return daemon.execDriver
  858. }
  859. func (daemon *Daemon) Volumes() *graph.Graph {
  860. return daemon.volumes
  861. }
  862. func (daemon *Daemon) ContainerGraph() *graphdb.Database {
  863. return daemon.containerGraph
  864. }
  865. func (daemon *Daemon) SetServer(server Server) {
  866. daemon.srv = server
  867. }
  868. func (daemon *Daemon) checkLocaldns() error {
  869. resolvConf, err := utils.GetResolvConf()
  870. if err != nil {
  871. return err
  872. }
  873. if len(daemon.config.Dns) == 0 && utils.CheckLocalDns(resolvConf) {
  874. log.Printf("Local (127.0.0.1) DNS resolver found in resolv.conf and containers can't use it. Using default external servers : %v\n", DefaultDns)
  875. daemon.config.Dns = DefaultDns
  876. }
  877. return nil
  878. }