daemon.go 30 KB

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