daemon.go 32 KB

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