daemon.go 30 KB

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