daemon.go 30 KB

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