daemon.go 32 KB

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