daemon.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119
  1. package daemon
  2. import (
  3. "fmt"
  4. "io"
  5. "io/ioutil"
  6. "log"
  7. "os"
  8. "path"
  9. "regexp"
  10. "runtime"
  11. "strings"
  12. "sync"
  13. "time"
  14. "github.com/docker/docker/archive"
  15. "github.com/docker/docker/daemon/execdriver"
  16. "github.com/docker/docker/daemon/execdriver/execdrivers"
  17. "github.com/docker/docker/daemon/execdriver/lxc"
  18. "github.com/docker/docker/daemon/graphdriver"
  19. _ "github.com/docker/docker/daemon/graphdriver/vfs"
  20. _ "github.com/docker/docker/daemon/networkdriver/bridge"
  21. "github.com/docker/docker/daemon/networkdriver/portallocator"
  22. "github.com/docker/docker/dockerversion"
  23. "github.com/docker/docker/engine"
  24. "github.com/docker/docker/graph"
  25. "github.com/docker/docker/image"
  26. "github.com/docker/docker/pkg/broadcastwriter"
  27. "github.com/docker/docker/pkg/graphdb"
  28. "github.com/docker/docker/pkg/namesgenerator"
  29. "github.com/docker/docker/pkg/networkfs/resolvconf"
  30. "github.com/docker/docker/pkg/parsers"
  31. "github.com/docker/docker/pkg/parsers/kernel"
  32. "github.com/docker/docker/pkg/sysinfo"
  33. "github.com/docker/docker/pkg/truncindex"
  34. "github.com/docker/docker/runconfig"
  35. "github.com/docker/docker/utils"
  36. "github.com/docker/libcontainer/label"
  37. )
  38. // Set the max depth to the aufs default that most
  39. // kernels are compiled with
  40. // For more information see: http://sourceforge.net/p/aufs/aufs3-standalone/ci/aufs3.12/tree/config.mk
  41. const MaxImageDepth = 127
  42. var (
  43. DefaultDns = []string{"8.8.8.8", "8.8.4.4"}
  44. validContainerNameChars = `[a-zA-Z0-9_.-]`
  45. validContainerNamePattern = regexp.MustCompile(`^/?` + validContainerNameChars + `+$`)
  46. )
  47. type contStore struct {
  48. s map[string]*Container
  49. sync.Mutex
  50. }
  51. func (c *contStore) Add(id string, cont *Container) {
  52. c.Lock()
  53. c.s[id] = cont
  54. c.Unlock()
  55. }
  56. func (c *contStore) Get(id string) *Container {
  57. c.Lock()
  58. res := c.s[id]
  59. c.Unlock()
  60. return res
  61. }
  62. func (c *contStore) Delete(id string) {
  63. c.Lock()
  64. delete(c.s, id)
  65. c.Unlock()
  66. }
  67. func (c *contStore) List() []*Container {
  68. containers := new(History)
  69. c.Lock()
  70. for _, cont := range c.s {
  71. containers.Add(cont)
  72. }
  73. c.Unlock()
  74. containers.Sort()
  75. return *containers
  76. }
  77. type Daemon struct {
  78. repository string
  79. sysInitPath string
  80. containers *contStore
  81. graph *graph.Graph
  82. repositories *graph.TagStore
  83. idIndex *truncindex.TruncIndex
  84. sysInfo *sysinfo.SysInfo
  85. volumes *graph.Graph
  86. eng *engine.Engine
  87. config *Config
  88. containerGraph *graphdb.Database
  89. driver graphdriver.Driver
  90. execDriver execdriver.Driver
  91. }
  92. // Install installs daemon capabilities to eng.
  93. func (daemon *Daemon) Install(eng *engine.Engine) error {
  94. // FIXME: rename "delete" to "rm" for consistency with the CLI command
  95. // FIXME: rename ContainerDestroy to ContainerRm for consistency with the CLI command
  96. // FIXME: remove ImageDelete's dependency on Daemon, then move to graph/
  97. for name, method := range map[string]engine.Handler{
  98. "attach": daemon.ContainerAttach,
  99. "build": daemon.CmdBuild,
  100. "commit": daemon.ContainerCommit,
  101. "container_changes": daemon.ContainerChanges,
  102. "container_copy": daemon.ContainerCopy,
  103. "container_inspect": daemon.ContainerInspect,
  104. "containers": daemon.Containers,
  105. "create": daemon.ContainerCreate,
  106. "delete": daemon.ContainerDestroy,
  107. "export": daemon.ContainerExport,
  108. "info": daemon.CmdInfo,
  109. "kill": daemon.ContainerKill,
  110. "logs": daemon.ContainerLogs,
  111. "pause": daemon.ContainerPause,
  112. "resize": daemon.ContainerResize,
  113. "restart": daemon.ContainerRestart,
  114. "start": daemon.ContainerStart,
  115. "stop": daemon.ContainerStop,
  116. "top": daemon.ContainerTop,
  117. "unpause": daemon.ContainerUnpause,
  118. "wait": daemon.ContainerWait,
  119. "image_delete": daemon.ImageDelete, // FIXME: see above
  120. } {
  121. if err := eng.Register(name, method); err != nil {
  122. return err
  123. }
  124. }
  125. if err := daemon.Repositories().Install(eng); err != nil {
  126. return err
  127. }
  128. // FIXME: this hack is necessary for legacy integration tests to access
  129. // the daemon object.
  130. eng.Hack_SetGlobalVar("httpapi.daemon", daemon)
  131. return nil
  132. }
  133. // Get looks for a container by the specified ID or name, and returns it.
  134. // If the container is not found, or if an error occurs, nil is returned.
  135. func (daemon *Daemon) Get(name string) *Container {
  136. if id, err := daemon.idIndex.Get(name); err == nil {
  137. return daemon.containers.Get(id)
  138. }
  139. if c, _ := daemon.GetByName(name); c != nil {
  140. return c
  141. }
  142. return nil
  143. }
  144. // Exists returns a true if a container of the specified ID or name exists,
  145. // false otherwise.
  146. func (daemon *Daemon) Exists(id string) bool {
  147. return daemon.Get(id) != nil
  148. }
  149. func (daemon *Daemon) containerRoot(id string) string {
  150. return path.Join(daemon.repository, id)
  151. }
  152. // Load reads the contents of a container from disk
  153. // This is typically done at startup.
  154. func (daemon *Daemon) load(id string) (*Container, error) {
  155. container := &Container{root: daemon.containerRoot(id), State: NewState()}
  156. if err := container.FromDisk(); err != nil {
  157. return nil, err
  158. }
  159. if container.ID != id {
  160. return container, fmt.Errorf("Container %s is stored at %s", container.ID, id)
  161. }
  162. return container, nil
  163. }
  164. // Register makes a container object usable by the daemon as <container.ID>
  165. // This is a wrapper for register
  166. func (daemon *Daemon) Register(container *Container) error {
  167. return daemon.register(container, true, nil)
  168. }
  169. // register makes a container object usable by the daemon as <container.ID>
  170. func (daemon *Daemon) register(container *Container, updateSuffixarray bool, containersToStart *[]*Container) error {
  171. if container.daemon != nil || daemon.Exists(container.ID) {
  172. return fmt.Errorf("Container is already loaded")
  173. }
  174. if err := validateID(container.ID); err != nil {
  175. return err
  176. }
  177. if err := daemon.ensureName(container); err != nil {
  178. return err
  179. }
  180. container.daemon = daemon
  181. // Attach to stdout and stderr
  182. container.stderr = broadcastwriter.New()
  183. container.stdout = broadcastwriter.New()
  184. // Attach to stdin
  185. if container.Config.OpenStdin {
  186. container.stdin, container.stdinPipe = io.Pipe()
  187. } else {
  188. container.stdinPipe = utils.NopWriteCloser(ioutil.Discard) // Silently drop stdin
  189. }
  190. // done
  191. daemon.containers.Add(container.ID, container)
  192. // don't update the Suffixarray if we're starting up
  193. // we'll waste time if we update it for every container
  194. daemon.idIndex.Add(container.ID)
  195. // FIXME: if the container is supposed to be running but is not, auto restart it?
  196. // if so, then we need to restart monitor and init a new lock
  197. // If the container is supposed to be running, make sure of it
  198. if container.State.IsRunning() {
  199. utils.Debugf("killing old running container %s", container.ID)
  200. existingPid := container.State.Pid
  201. container.State.SetStopped(0)
  202. // We only have to handle this for lxc because the other drivers will ensure that
  203. // no processes are left when docker dies
  204. if container.ExecDriver == "" || strings.Contains(container.ExecDriver, "lxc") {
  205. lxc.KillLxc(container.ID, 9)
  206. } else {
  207. // use the current driver and ensure that the container is dead x.x
  208. cmd := &execdriver.Command{
  209. ID: container.ID,
  210. }
  211. var err error
  212. cmd.Process, err = os.FindProcess(existingPid)
  213. if err != nil {
  214. utils.Debugf("cannot find existing process for %d", existingPid)
  215. }
  216. daemon.execDriver.Terminate(cmd)
  217. }
  218. if err := container.Unmount(); err != nil {
  219. utils.Debugf("unmount error %s", err)
  220. }
  221. if err := container.ToDisk(); err != nil {
  222. utils.Debugf("saving stopped state to disk %s", err)
  223. }
  224. info := daemon.execDriver.Info(container.ID)
  225. if !info.IsRunning() {
  226. utils.Debugf("Container %s was supposed to be running but is not.", container.ID)
  227. utils.Debugf("Marking as stopped")
  228. container.State.SetStopped(-127)
  229. if err := container.ToDisk(); err != nil {
  230. return err
  231. }
  232. if daemon.config.AutoRestart {
  233. utils.Debugf("Marking as restarting")
  234. if containersToStart != nil {
  235. *containersToStart = append(*containersToStart, container)
  236. }
  237. }
  238. }
  239. }
  240. return nil
  241. }
  242. func (daemon *Daemon) ensureName(container *Container) error {
  243. if container.Name == "" {
  244. name, err := daemon.generateNewName(container.ID)
  245. if err != nil {
  246. return err
  247. }
  248. container.Name = name
  249. if err := container.ToDisk(); err != nil {
  250. utils.Debugf("Error saving container name %s", err)
  251. }
  252. }
  253. return nil
  254. }
  255. func (daemon *Daemon) LogToDisk(src *broadcastwriter.BroadcastWriter, dst, stream string) error {
  256. log, err := os.OpenFile(dst, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0600)
  257. if err != nil {
  258. return err
  259. }
  260. src.AddWriter(log, stream)
  261. return nil
  262. }
  263. func (daemon *Daemon) restore() error {
  264. var (
  265. debug = (os.Getenv("DEBUG") != "" || os.Getenv("TEST") != "")
  266. containers = make(map[string]*Container)
  267. currentDriver = daemon.driver.String()
  268. containersToStart = []*Container{}
  269. )
  270. if !debug {
  271. fmt.Printf("Loading containers: ")
  272. }
  273. dir, err := ioutil.ReadDir(daemon.repository)
  274. if err != nil {
  275. return err
  276. }
  277. for _, v := range dir {
  278. id := v.Name()
  279. container, err := daemon.load(id)
  280. if !debug {
  281. fmt.Print(".")
  282. }
  283. if err != nil {
  284. utils.Errorf("Failed to load container %v: %v", id, err)
  285. continue
  286. }
  287. // Ignore the container if it does not support the current driver being used by the graph
  288. if container.Driver == "" && currentDriver == "aufs" || container.Driver == currentDriver {
  289. utils.Debugf("Loaded container %v", container.ID)
  290. containers[container.ID] = container
  291. } else {
  292. utils.Debugf("Cannot load container %s because it was created with another graph driver.", container.ID)
  293. }
  294. }
  295. if entities := daemon.containerGraph.List("/", -1); entities != nil {
  296. for _, p := range entities.Paths() {
  297. if !debug {
  298. fmt.Print(".")
  299. }
  300. e := entities[p]
  301. if container, ok := containers[e.ID()]; ok {
  302. if err := daemon.register(container, false, &containersToStart); err != nil {
  303. utils.Debugf("Failed to register container %s: %s", container.ID, err)
  304. }
  305. delete(containers, e.ID())
  306. }
  307. }
  308. }
  309. // Any containers that are left over do not exist in the graph
  310. for _, container := range containers {
  311. // Try to set the default name for a container if it exists prior to links
  312. container.Name, err = daemon.generateNewName(container.ID)
  313. if err != nil {
  314. utils.Debugf("Setting default id - %s", err)
  315. }
  316. if err := daemon.register(container, false, &containersToStart); err != nil {
  317. utils.Debugf("Failed to register container %s: %s", container.ID, err)
  318. }
  319. }
  320. for _, container := range containersToStart {
  321. utils.Debugf("Starting container %d", container.ID)
  322. if err := container.Start(); err != nil {
  323. utils.Debugf("Failed to start container %s: %s", container.ID, err)
  324. }
  325. }
  326. if !debug {
  327. fmt.Printf(": done.\n")
  328. }
  329. return nil
  330. }
  331. func (daemon *Daemon) checkImageDepth(img *image.Image) error {
  332. // We add 2 layers to the depth because the container's rw and
  333. // init layer add to the restriction
  334. depth, err := img.Depth()
  335. if err != nil {
  336. return err
  337. }
  338. if depth+2 >= MaxImageDepth {
  339. return fmt.Errorf("Cannot create container with more than %d parents", MaxImageDepth)
  340. }
  341. return nil
  342. }
  343. func (daemon *Daemon) checkDeprecatedExpose(config *runconfig.Config) bool {
  344. if config != nil {
  345. if config.PortSpecs != nil {
  346. for _, p := range config.PortSpecs {
  347. if strings.Contains(p, ":") {
  348. return true
  349. }
  350. }
  351. }
  352. }
  353. return false
  354. }
  355. func (daemon *Daemon) mergeAndVerifyConfig(config *runconfig.Config, img *image.Image) ([]string, error) {
  356. warnings := []string{}
  357. if daemon.checkDeprecatedExpose(img.Config) || daemon.checkDeprecatedExpose(config) {
  358. 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.")
  359. }
  360. if img.Config != nil {
  361. if err := runconfig.Merge(config, img.Config); err != nil {
  362. return nil, err
  363. }
  364. }
  365. if len(config.Entrypoint) == 0 && len(config.Cmd) == 0 {
  366. return nil, fmt.Errorf("No command specified")
  367. }
  368. return warnings, nil
  369. }
  370. func (daemon *Daemon) generateIdAndName(name string) (string, string, error) {
  371. var (
  372. err error
  373. id = utils.GenerateRandomID()
  374. )
  375. if name == "" {
  376. if name, err = daemon.generateNewName(id); err != nil {
  377. return "", "", err
  378. }
  379. return id, name, nil
  380. }
  381. if name, err = daemon.reserveName(id, name); err != nil {
  382. return "", "", err
  383. }
  384. return id, name, nil
  385. }
  386. func (daemon *Daemon) reserveName(id, name string) (string, error) {
  387. if !validContainerNamePattern.MatchString(name) {
  388. return "", fmt.Errorf("Invalid container name (%s), only %s are allowed", name, validContainerNameChars)
  389. }
  390. if name[0] != '/' {
  391. name = "/" + name
  392. }
  393. if _, err := daemon.containerGraph.Set(name, id); err != nil {
  394. if !graphdb.IsNonUniqueNameError(err) {
  395. return "", err
  396. }
  397. conflictingContainer, err := daemon.GetByName(name)
  398. if err != nil {
  399. if strings.Contains(err.Error(), "Could not find entity") {
  400. return "", err
  401. }
  402. // Remove name and continue starting the container
  403. if err := daemon.containerGraph.Delete(name); err != nil {
  404. return "", err
  405. }
  406. } else {
  407. nameAsKnownByUser := strings.TrimPrefix(name, "/")
  408. return "", fmt.Errorf(
  409. "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,
  410. utils.TruncateID(conflictingContainer.ID), nameAsKnownByUser)
  411. }
  412. }
  413. return name, nil
  414. }
  415. func (daemon *Daemon) generateNewName(id string) (string, error) {
  416. var name string
  417. for i := 0; i < 6; i++ {
  418. name = namesgenerator.GetRandomName(i)
  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. continue
  427. }
  428. return name, nil
  429. }
  430. name = "/" + utils.TruncateID(id)
  431. if _, err := daemon.containerGraph.Set(name, id); err != nil {
  432. return "", err
  433. }
  434. return name, nil
  435. }
  436. func (daemon *Daemon) generateHostname(id string, config *runconfig.Config) {
  437. // Generate default hostname
  438. // FIXME: the lxc template no longer needs to set a default hostname
  439. if config.Hostname == "" {
  440. config.Hostname = id[:12]
  441. }
  442. }
  443. func (daemon *Daemon) getEntrypointAndArgs(config *runconfig.Config) (string, []string) {
  444. var (
  445. entrypoint string
  446. args []string
  447. )
  448. if len(config.Entrypoint) != 0 {
  449. entrypoint = config.Entrypoint[0]
  450. args = append(config.Entrypoint[1:], config.Cmd...)
  451. } else {
  452. entrypoint = config.Cmd[0]
  453. args = config.Cmd[1:]
  454. }
  455. return entrypoint, args
  456. }
  457. func (daemon *Daemon) newContainer(name string, config *runconfig.Config, img *image.Image) (*Container, error) {
  458. var (
  459. id string
  460. err error
  461. )
  462. id, name, err = daemon.generateIdAndName(name)
  463. if err != nil {
  464. return nil, err
  465. }
  466. daemon.generateHostname(id, config)
  467. entrypoint, args := daemon.getEntrypointAndArgs(config)
  468. container := &Container{
  469. // FIXME: we should generate the ID here instead of receiving it as an argument
  470. ID: id,
  471. Created: time.Now().UTC(),
  472. Path: entrypoint,
  473. Args: args, //FIXME: de-duplicate from config
  474. Config: config,
  475. hostConfig: &runconfig.HostConfig{},
  476. Image: img.ID, // Always use the resolved image id
  477. NetworkSettings: &NetworkSettings{},
  478. Name: name,
  479. Driver: daemon.driver.String(),
  480. ExecDriver: daemon.execDriver.Name(),
  481. State: NewState(),
  482. }
  483. container.root = daemon.containerRoot(container.ID)
  484. if container.ProcessLabel, container.MountLabel, err = label.GenLabels(""); err != nil {
  485. return nil, err
  486. }
  487. return container, nil
  488. }
  489. func (daemon *Daemon) createRootfs(container *Container, img *image.Image) error {
  490. // Step 1: create the container directory.
  491. // This doubles as a barrier to avoid race conditions.
  492. if err := os.Mkdir(container.root, 0700); err != nil {
  493. return err
  494. }
  495. initID := fmt.Sprintf("%s-init", container.ID)
  496. if err := daemon.driver.Create(initID, img.ID); err != nil {
  497. return err
  498. }
  499. initPath, err := daemon.driver.Get(initID, "")
  500. if err != nil {
  501. return err
  502. }
  503. defer daemon.driver.Put(initID)
  504. if err := graph.SetupInitLayer(initPath); err != nil {
  505. return err
  506. }
  507. if err := daemon.driver.Create(container.ID, initID); err != nil {
  508. return err
  509. }
  510. return nil
  511. }
  512. func GetFullContainerName(name string) (string, error) {
  513. if name == "" {
  514. return "", fmt.Errorf("Container name cannot be empty")
  515. }
  516. if name[0] != '/' {
  517. name = "/" + name
  518. }
  519. return name, nil
  520. }
  521. func (daemon *Daemon) GetByName(name string) (*Container, error) {
  522. fullName, err := GetFullContainerName(name)
  523. if err != nil {
  524. return nil, err
  525. }
  526. entity := daemon.containerGraph.Get(fullName)
  527. if entity == nil {
  528. return nil, fmt.Errorf("Could not find entity for %s", name)
  529. }
  530. e := daemon.containers.Get(entity.ID())
  531. if e == nil {
  532. return nil, fmt.Errorf("Could not find container for entity id %s", entity.ID())
  533. }
  534. return e, nil
  535. }
  536. func (daemon *Daemon) Children(name string) (map[string]*Container, error) {
  537. name, err := GetFullContainerName(name)
  538. if err != nil {
  539. return nil, err
  540. }
  541. children := make(map[string]*Container)
  542. err = daemon.containerGraph.Walk(name, func(p string, e *graphdb.Entity) error {
  543. c := daemon.Get(e.ID())
  544. if c == nil {
  545. return fmt.Errorf("Could not get container for name %s and id %s", e.ID(), p)
  546. }
  547. children[p] = c
  548. return nil
  549. }, 0)
  550. if err != nil {
  551. return nil, err
  552. }
  553. return children, nil
  554. }
  555. func (daemon *Daemon) RegisterLink(parent, child *Container, alias string) error {
  556. fullName := path.Join(parent.Name, alias)
  557. if !daemon.containerGraph.Exists(fullName) {
  558. _, err := daemon.containerGraph.Set(fullName, child.ID)
  559. return err
  560. }
  561. return nil
  562. }
  563. func (daemon *Daemon) RegisterLinks(container *Container, hostConfig *runconfig.HostConfig) error {
  564. if hostConfig != nil && hostConfig.Links != nil {
  565. for _, l := range hostConfig.Links {
  566. parts, err := parsers.PartParser("name:alias", l)
  567. if err != nil {
  568. return err
  569. }
  570. child, err := daemon.GetByName(parts["name"])
  571. if err != nil {
  572. return err
  573. }
  574. if child == nil {
  575. return fmt.Errorf("Could not get container for %s", parts["name"])
  576. }
  577. if err := daemon.RegisterLink(container, child, parts["alias"]); err != nil {
  578. return err
  579. }
  580. }
  581. // After we load all the links into the daemon
  582. // set them to nil on the hostconfig
  583. hostConfig.Links = nil
  584. if err := container.WriteHostConfig(); err != nil {
  585. return err
  586. }
  587. }
  588. return nil
  589. }
  590. // FIXME: harmonize with NewGraph()
  591. func NewDaemon(config *Config, eng *engine.Engine) (*Daemon, error) {
  592. daemon, err := NewDaemonFromDirectory(config, eng)
  593. if err != nil {
  594. return nil, err
  595. }
  596. return daemon, nil
  597. }
  598. func NewDaemonFromDirectory(config *Config, eng *engine.Engine) (*Daemon, error) {
  599. // Apply configuration defaults
  600. if config.Mtu == 0 {
  601. // FIXME: GetDefaultNetwork Mtu doesn't need to be public anymore
  602. config.Mtu = GetDefaultNetworkMtu()
  603. }
  604. // Check for mutually incompatible config options
  605. if config.BridgeIface != "" && config.BridgeIP != "" {
  606. return nil, fmt.Errorf("You specified -b & --bip, mutually exclusive options. Please specify only one.")
  607. }
  608. if !config.EnableIptables && !config.InterContainerCommunication {
  609. return nil, fmt.Errorf("You specified --iptables=false with --icc=false. ICC uses iptables to function. Please set --icc or --iptables to true.")
  610. }
  611. // FIXME: DisableNetworkBidge doesn't need to be public anymore
  612. config.DisableNetwork = config.BridgeIface == DisableNetworkBridge
  613. // Claim the pidfile first, to avoid any and all unexpected race conditions.
  614. // Some of the init doesn't need a pidfile lock - but let's not try to be smart.
  615. if config.Pidfile != "" {
  616. if err := utils.CreatePidFile(config.Pidfile); err != nil {
  617. return nil, err
  618. }
  619. eng.OnShutdown(func() {
  620. // Always release the pidfile last, just in case
  621. utils.RemovePidFile(config.Pidfile)
  622. })
  623. }
  624. // Check that the system is supported and we have sufficient privileges
  625. // FIXME: return errors instead of calling Fatal
  626. if runtime.GOOS != "linux" {
  627. log.Fatalf("The Docker daemon is only supported on linux")
  628. }
  629. if os.Geteuid() != 0 {
  630. log.Fatalf("The Docker daemon needs to be run as root")
  631. }
  632. if err := checkKernelAndArch(); err != nil {
  633. log.Fatal(err)
  634. }
  635. // set up the TempDir to use a canonical path
  636. tmp, err := utils.TempDir(config.Root)
  637. if err != nil {
  638. log.Fatalf("Unable to get the TempDir under %s: %s", config.Root, err)
  639. }
  640. realTmp, err := utils.ReadSymlinkedDirectory(tmp)
  641. if err != nil {
  642. log.Fatalf("Unable to get the full path to the TempDir (%s): %s", tmp, err)
  643. }
  644. os.Setenv("TMPDIR", realTmp)
  645. if !config.EnableSelinuxSupport {
  646. selinuxSetDisabled()
  647. }
  648. // get the canonical path to the Docker root directory
  649. var realRoot string
  650. if _, err := os.Stat(config.Root); err != nil && os.IsNotExist(err) {
  651. realRoot = config.Root
  652. } else {
  653. realRoot, err = utils.ReadSymlinkedDirectory(config.Root)
  654. if err != nil {
  655. log.Fatalf("Unable to get the full path to root (%s): %s", config.Root, err)
  656. }
  657. }
  658. config.Root = realRoot
  659. // Create the root directory if it doesn't exists
  660. if err := os.MkdirAll(config.Root, 0700); err != nil && !os.IsExist(err) {
  661. return nil, err
  662. }
  663. // Set the default driver
  664. graphdriver.DefaultDriver = config.GraphDriver
  665. // Load storage driver
  666. driver, err := graphdriver.New(config.Root, config.GraphOptions)
  667. if err != nil {
  668. return nil, err
  669. }
  670. utils.Debugf("Using graph driver %s", driver)
  671. // As Docker on btrfs and SELinux are incompatible at present, error on both being enabled
  672. if config.EnableSelinuxSupport && driver.String() == "btrfs" {
  673. return nil, fmt.Errorf("SELinux is not supported with the BTRFS graph driver!")
  674. }
  675. daemonRepo := path.Join(config.Root, "containers")
  676. if err := os.MkdirAll(daemonRepo, 0700); err != nil && !os.IsExist(err) {
  677. return nil, err
  678. }
  679. // Migrate the container if it is aufs and aufs is enabled
  680. if err = migrateIfAufs(driver, config.Root); err != nil {
  681. return nil, err
  682. }
  683. utils.Debugf("Creating images graph")
  684. g, err := graph.NewGraph(path.Join(config.Root, "graph"), driver)
  685. if err != nil {
  686. return nil, err
  687. }
  688. // We don't want to use a complex driver like aufs or devmapper
  689. // for volumes, just a plain filesystem
  690. volumesDriver, err := graphdriver.GetDriver("vfs", config.Root, config.GraphOptions)
  691. if err != nil {
  692. return nil, err
  693. }
  694. utils.Debugf("Creating volumes graph")
  695. volumes, err := graph.NewGraph(path.Join(config.Root, "volumes"), volumesDriver)
  696. if err != nil {
  697. return nil, err
  698. }
  699. utils.Debugf("Creating repository list")
  700. repositories, err := graph.NewTagStore(path.Join(config.Root, "repositories-"+driver.String()), g)
  701. if err != nil {
  702. return nil, fmt.Errorf("Couldn't create Tag store: %s", err)
  703. }
  704. if !config.DisableNetwork {
  705. job := eng.Job("init_networkdriver")
  706. job.SetenvBool("EnableIptables", config.EnableIptables)
  707. job.SetenvBool("InterContainerCommunication", config.InterContainerCommunication)
  708. job.SetenvBool("EnableIpForward", config.EnableIpForward)
  709. job.Setenv("BridgeIface", config.BridgeIface)
  710. job.Setenv("BridgeIP", config.BridgeIP)
  711. job.Setenv("DefaultBindingIP", config.DefaultIp.String())
  712. if err := job.Run(); err != nil {
  713. return nil, err
  714. }
  715. }
  716. graphdbPath := path.Join(config.Root, "linkgraph.db")
  717. graph, err := graphdb.NewSqliteConn(graphdbPath)
  718. if err != nil {
  719. return nil, err
  720. }
  721. localCopy := path.Join(config.Root, "init", fmt.Sprintf("dockerinit-%s", dockerversion.VERSION))
  722. sysInitPath := utils.DockerInitPath(localCopy)
  723. if sysInitPath == "" {
  724. 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.")
  725. }
  726. if sysInitPath != localCopy {
  727. // 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).
  728. if err := os.Mkdir(path.Dir(localCopy), 0700); err != nil && !os.IsExist(err) {
  729. return nil, err
  730. }
  731. if _, err := utils.CopyFile(sysInitPath, localCopy); err != nil {
  732. return nil, err
  733. }
  734. if err := os.Chmod(localCopy, 0700); err != nil {
  735. return nil, err
  736. }
  737. sysInitPath = localCopy
  738. }
  739. sysInfo := sysinfo.New(false)
  740. ed, err := execdrivers.NewDriver(config.ExecDriver, config.Root, sysInitPath, sysInfo)
  741. if err != nil {
  742. return nil, err
  743. }
  744. daemon := &Daemon{
  745. repository: daemonRepo,
  746. containers: &contStore{s: make(map[string]*Container)},
  747. graph: g,
  748. repositories: repositories,
  749. idIndex: truncindex.NewTruncIndex([]string{}),
  750. sysInfo: sysInfo,
  751. volumes: volumes,
  752. config: config,
  753. containerGraph: graph,
  754. driver: driver,
  755. sysInitPath: sysInitPath,
  756. execDriver: ed,
  757. eng: eng,
  758. }
  759. if err := daemon.checkLocaldns(); err != nil {
  760. return nil, err
  761. }
  762. if err := daemon.restore(); err != nil {
  763. return nil, err
  764. }
  765. // Setup shutdown handlers
  766. // FIXME: can these shutdown handlers be registered closer to their source?
  767. eng.OnShutdown(func() {
  768. // FIXME: if these cleanup steps can be called concurrently, register
  769. // them as separate handlers to speed up total shutdown time
  770. // FIXME: use engine logging instead of utils.Errorf
  771. if err := daemon.shutdown(); err != nil {
  772. utils.Errorf("daemon.shutdown(): %s", err)
  773. }
  774. if err := portallocator.ReleaseAll(); err != nil {
  775. utils.Errorf("portallocator.ReleaseAll(): %s", err)
  776. }
  777. if err := daemon.driver.Cleanup(); err != nil {
  778. utils.Errorf("daemon.driver.Cleanup(): %s", err.Error())
  779. }
  780. if err := daemon.containerGraph.Close(); err != nil {
  781. utils.Errorf("daemon.containerGraph.Close(): %s", err.Error())
  782. }
  783. })
  784. return daemon, nil
  785. }
  786. func (daemon *Daemon) shutdown() error {
  787. group := sync.WaitGroup{}
  788. utils.Debugf("starting clean shutdown of all containers...")
  789. for _, container := range daemon.List() {
  790. c := container
  791. if c.State.IsRunning() {
  792. utils.Debugf("stopping %s", c.ID)
  793. group.Add(1)
  794. go func() {
  795. defer group.Done()
  796. if err := c.KillSig(15); err != nil {
  797. utils.Debugf("kill 15 error for %s - %s", c.ID, err)
  798. }
  799. c.State.WaitStop(-1 * time.Second)
  800. utils.Debugf("container stopped %s", c.ID)
  801. }()
  802. }
  803. }
  804. group.Wait()
  805. return nil
  806. }
  807. func (daemon *Daemon) Mount(container *Container) error {
  808. dir, err := daemon.driver.Get(container.ID, container.GetMountLabel())
  809. if err != nil {
  810. return fmt.Errorf("Error getting container %s from driver %s: %s", container.ID, daemon.driver, err)
  811. }
  812. if container.basefs == "" {
  813. container.basefs = dir
  814. } else if container.basefs != dir {
  815. return fmt.Errorf("Error: driver %s is returning inconsistent paths for container %s ('%s' then '%s')",
  816. daemon.driver, container.ID, container.basefs, dir)
  817. }
  818. return nil
  819. }
  820. func (daemon *Daemon) Unmount(container *Container) error {
  821. daemon.driver.Put(container.ID)
  822. return nil
  823. }
  824. func (daemon *Daemon) Changes(container *Container) ([]archive.Change, error) {
  825. if differ, ok := daemon.driver.(graphdriver.Differ); ok {
  826. return differ.Changes(container.ID)
  827. }
  828. cDir, err := daemon.driver.Get(container.ID, "")
  829. if err != nil {
  830. return nil, fmt.Errorf("Error getting container rootfs %s from driver %s: %s", container.ID, container.daemon.driver, err)
  831. }
  832. defer daemon.driver.Put(container.ID)
  833. initDir, err := daemon.driver.Get(container.ID+"-init", "")
  834. if err != nil {
  835. return nil, fmt.Errorf("Error getting container init rootfs %s from driver %s: %s", container.ID, container.daemon.driver, err)
  836. }
  837. defer daemon.driver.Put(container.ID + "-init")
  838. return archive.ChangesDirs(cDir, initDir)
  839. }
  840. func (daemon *Daemon) Diff(container *Container) (archive.Archive, error) {
  841. if differ, ok := daemon.driver.(graphdriver.Differ); ok {
  842. return differ.Diff(container.ID)
  843. }
  844. changes, err := daemon.Changes(container)
  845. if err != nil {
  846. return nil, err
  847. }
  848. cDir, err := daemon.driver.Get(container.ID, "")
  849. if err != nil {
  850. return nil, fmt.Errorf("Error getting container rootfs %s from driver %s: %s", container.ID, container.daemon.driver, err)
  851. }
  852. archive, err := archive.ExportChanges(cDir, changes)
  853. if err != nil {
  854. return nil, err
  855. }
  856. return utils.NewReadCloserWrapper(archive, func() error {
  857. err := archive.Close()
  858. daemon.driver.Put(container.ID)
  859. return err
  860. }), nil
  861. }
  862. func (daemon *Daemon) Run(c *Container, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (int, error) {
  863. return daemon.execDriver.Run(c.command, pipes, startCallback)
  864. }
  865. func (daemon *Daemon) Pause(c *Container) error {
  866. if err := daemon.execDriver.Pause(c.command); err != nil {
  867. return err
  868. }
  869. c.State.SetPaused()
  870. return nil
  871. }
  872. func (daemon *Daemon) Unpause(c *Container) error {
  873. if err := daemon.execDriver.Unpause(c.command); err != nil {
  874. return err
  875. }
  876. c.State.SetUnpaused()
  877. return nil
  878. }
  879. func (daemon *Daemon) Kill(c *Container, sig int) error {
  880. return daemon.execDriver.Kill(c.command, sig)
  881. }
  882. // Nuke kills all containers then removes all content
  883. // from the content root, including images, volumes and
  884. // container filesystems.
  885. // Again: this will remove your entire docker daemon!
  886. // FIXME: this is deprecated, and only used in legacy
  887. // tests. Please remove.
  888. func (daemon *Daemon) Nuke() error {
  889. var wg sync.WaitGroup
  890. for _, container := range daemon.List() {
  891. wg.Add(1)
  892. go func(c *Container) {
  893. c.Kill()
  894. wg.Done()
  895. }(container)
  896. }
  897. wg.Wait()
  898. return os.RemoveAll(daemon.config.Root)
  899. }
  900. // FIXME: this is a convenience function for integration tests
  901. // which need direct access to daemon.graph.
  902. // Once the tests switch to using engine and jobs, this method
  903. // can go away.
  904. func (daemon *Daemon) Graph() *graph.Graph {
  905. return daemon.graph
  906. }
  907. func (daemon *Daemon) Repositories() *graph.TagStore {
  908. return daemon.repositories
  909. }
  910. func (daemon *Daemon) Config() *Config {
  911. return daemon.config
  912. }
  913. func (daemon *Daemon) SystemConfig() *sysinfo.SysInfo {
  914. return daemon.sysInfo
  915. }
  916. func (daemon *Daemon) SystemInitPath() string {
  917. return daemon.sysInitPath
  918. }
  919. func (daemon *Daemon) GraphDriver() graphdriver.Driver {
  920. return daemon.driver
  921. }
  922. func (daemon *Daemon) ExecutionDriver() execdriver.Driver {
  923. return daemon.execDriver
  924. }
  925. func (daemon *Daemon) Volumes() *graph.Graph {
  926. return daemon.volumes
  927. }
  928. func (daemon *Daemon) ContainerGraph() *graphdb.Database {
  929. return daemon.containerGraph
  930. }
  931. func (daemon *Daemon) checkLocaldns() error {
  932. resolvConf, err := resolvconf.Get()
  933. if err != nil {
  934. return err
  935. }
  936. if len(daemon.config.Dns) == 0 && utils.CheckLocalDns(resolvConf) {
  937. 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)
  938. daemon.config.Dns = DefaultDns
  939. }
  940. return nil
  941. }
  942. func (daemon *Daemon) ImageGetCached(imgID string, config *runconfig.Config) (*image.Image, error) {
  943. // Retrieve all images
  944. images, err := daemon.Graph().Map()
  945. if err != nil {
  946. return nil, err
  947. }
  948. // Store the tree in a map of map (map[parentId][childId])
  949. imageMap := make(map[string]map[string]struct{})
  950. for _, img := range images {
  951. if _, exists := imageMap[img.Parent]; !exists {
  952. imageMap[img.Parent] = make(map[string]struct{})
  953. }
  954. imageMap[img.Parent][img.ID] = struct{}{}
  955. }
  956. // Loop on the children of the given image and check the config
  957. var match *image.Image
  958. for elem := range imageMap[imgID] {
  959. img, err := daemon.Graph().Get(elem)
  960. if err != nil {
  961. return nil, err
  962. }
  963. if runconfig.Compare(&img.ContainerConfig, config) {
  964. if match == nil || match.Created.Before(img.Created) {
  965. match = img
  966. }
  967. }
  968. }
  969. return match, nil
  970. }
  971. func checkKernelAndArch() error {
  972. // Check for unsupported architectures
  973. if runtime.GOARCH != "amd64" {
  974. return fmt.Errorf("The Docker runtime currently only supports amd64 (not %s). This will change in the future. Aborting.", runtime.GOARCH)
  975. }
  976. // Check for unsupported kernel versions
  977. // FIXME: it would be cleaner to not test for specific versions, but rather
  978. // test for specific functionalities.
  979. // Unfortunately we can't test for the feature "does not cause a kernel panic"
  980. // without actually causing a kernel panic, so we need this workaround until
  981. // the circumstances of pre-3.8 crashes are clearer.
  982. // For details see http://github.com/docker/docker/issues/407
  983. if k, err := kernel.GetKernelVersion(); err != nil {
  984. log.Printf("WARNING: %s\n", err)
  985. } else {
  986. if kernel.CompareKernelVersion(k, &kernel.KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}) < 0 {
  987. if os.Getenv("DOCKER_NOWARN_KERNEL_VERSION") == "" {
  988. log.Printf("WARNING: You are running linux kernel version %s, which might be unstable running docker. Please upgrade your kernel to 3.8.0.", k.String())
  989. }
  990. }
  991. }
  992. return nil
  993. }