daemon.go 32 KB

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