daemon.go 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207
  1. package daemon
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "os"
  8. "path"
  9. "path/filepath"
  10. "regexp"
  11. "runtime"
  12. "strings"
  13. "sync"
  14. "time"
  15. "github.com/docker/libcontainer/label"
  16. "github.com/Sirupsen/logrus"
  17. "github.com/docker/docker/api"
  18. "github.com/docker/docker/autogen/dockerversion"
  19. "github.com/docker/docker/daemon/events"
  20. "github.com/docker/docker/daemon/execdriver"
  21. "github.com/docker/docker/daemon/execdriver/execdrivers"
  22. "github.com/docker/docker/daemon/execdriver/lxc"
  23. "github.com/docker/docker/daemon/graphdriver"
  24. _ "github.com/docker/docker/daemon/graphdriver/vfs"
  25. "github.com/docker/docker/daemon/network"
  26. "github.com/docker/docker/daemon/networkdriver/bridge"
  27. "github.com/docker/docker/graph"
  28. "github.com/docker/docker/image"
  29. "github.com/docker/docker/pkg/archive"
  30. "github.com/docker/docker/pkg/broadcastwriter"
  31. "github.com/docker/docker/pkg/fileutils"
  32. "github.com/docker/docker/pkg/graphdb"
  33. "github.com/docker/docker/pkg/ioutils"
  34. "github.com/docker/docker/pkg/namesgenerator"
  35. "github.com/docker/docker/pkg/parsers"
  36. "github.com/docker/docker/pkg/parsers/kernel"
  37. "github.com/docker/docker/pkg/resolvconf"
  38. "github.com/docker/docker/pkg/stringid"
  39. "github.com/docker/docker/pkg/sysinfo"
  40. "github.com/docker/docker/pkg/truncindex"
  41. "github.com/docker/docker/registry"
  42. "github.com/docker/docker/runconfig"
  43. "github.com/docker/docker/trust"
  44. "github.com/docker/docker/utils"
  45. "github.com/docker/docker/volumes"
  46. "github.com/go-fsnotify/fsnotify"
  47. )
  48. var (
  49. validContainerNameChars = `[a-zA-Z0-9][a-zA-Z0-9_.-]`
  50. validContainerNamePattern = regexp.MustCompile(`^/?` + validContainerNameChars + `+$`)
  51. )
  52. type contStore struct {
  53. s map[string]*Container
  54. sync.Mutex
  55. }
  56. func (c *contStore) Add(id string, cont *Container) {
  57. c.Lock()
  58. c.s[id] = cont
  59. c.Unlock()
  60. }
  61. func (c *contStore) Get(id string) *Container {
  62. c.Lock()
  63. res := c.s[id]
  64. c.Unlock()
  65. return res
  66. }
  67. func (c *contStore) Delete(id string) {
  68. c.Lock()
  69. delete(c.s, id)
  70. c.Unlock()
  71. }
  72. func (c *contStore) List() []*Container {
  73. containers := new(History)
  74. c.Lock()
  75. for _, cont := range c.s {
  76. containers.Add(cont)
  77. }
  78. c.Unlock()
  79. containers.Sort()
  80. return *containers
  81. }
  82. type Daemon struct {
  83. ID string
  84. repository string
  85. sysInitPath string
  86. containers *contStore
  87. execCommands *execStore
  88. graph *graph.Graph
  89. repositories *graph.TagStore
  90. idIndex *truncindex.TruncIndex
  91. sysInfo *sysinfo.SysInfo
  92. volumes *volumes.Repository
  93. config *Config
  94. containerGraph *graphdb.Database
  95. driver graphdriver.Driver
  96. execDriver execdriver.Driver
  97. statsCollector *statsCollector
  98. defaultLogConfig runconfig.LogConfig
  99. RegistryService *registry.Service
  100. EventsService *events.Events
  101. }
  102. // Get looks for a container using the provided information, which could be
  103. // one of the following inputs from the caller:
  104. // - A full container ID, which will exact match a container in daemon's list
  105. // - A container name, which will only exact match via the GetByName() function
  106. // - A partial container ID prefix (e.g. short ID) of any length that is
  107. // unique enough to only return a single container object
  108. // If none of these searches succeed, an error is returned
  109. func (daemon *Daemon) Get(prefixOrName string) (*Container, error) {
  110. if containerByID := daemon.containers.Get(prefixOrName); containerByID != nil {
  111. // prefix is an exact match to a full container ID
  112. return containerByID, nil
  113. }
  114. // GetByName will match only an exact name provided; we ignore errors
  115. containerByName, _ := daemon.GetByName(prefixOrName)
  116. containerId, indexError := daemon.idIndex.Get(prefixOrName)
  117. if containerByName != nil {
  118. // prefix is an exact match to a full container Name
  119. return containerByName, nil
  120. }
  121. if containerId != "" {
  122. // prefix is a fuzzy match to a container ID
  123. return daemon.containers.Get(containerId), nil
  124. }
  125. return nil, indexError
  126. }
  127. // Exists returns a true if a container of the specified ID or name exists,
  128. // false otherwise.
  129. func (daemon *Daemon) Exists(id string) bool {
  130. c, _ := daemon.Get(id)
  131. return c != nil
  132. }
  133. func (daemon *Daemon) containerRoot(id string) string {
  134. return path.Join(daemon.repository, id)
  135. }
  136. // Load reads the contents of a container from disk
  137. // This is typically done at startup.
  138. func (daemon *Daemon) load(id string) (*Container, error) {
  139. container := &Container{
  140. root: daemon.containerRoot(id),
  141. State: NewState(),
  142. execCommands: newExecStore(),
  143. }
  144. if err := container.FromDisk(); err != nil {
  145. return nil, err
  146. }
  147. if container.ID != id {
  148. return container, fmt.Errorf("Container %s is stored at %s", container.ID, id)
  149. }
  150. return container, nil
  151. }
  152. // Register makes a container object usable by the daemon as <container.ID>
  153. // This is a wrapper for register
  154. func (daemon *Daemon) Register(container *Container) error {
  155. return daemon.register(container, true)
  156. }
  157. // register makes a container object usable by the daemon as <container.ID>
  158. func (daemon *Daemon) register(container *Container, updateSuffixarray bool) error {
  159. if container.daemon != nil || daemon.Exists(container.ID) {
  160. return fmt.Errorf("Container is already loaded")
  161. }
  162. if err := validateID(container.ID); err != nil {
  163. return err
  164. }
  165. if err := daemon.ensureName(container); err != nil {
  166. return err
  167. }
  168. container.daemon = daemon
  169. // Attach to stdout and stderr
  170. container.stderr = broadcastwriter.New()
  171. container.stdout = broadcastwriter.New()
  172. // Attach to stdin
  173. if container.Config.OpenStdin {
  174. container.stdin, container.stdinPipe = io.Pipe()
  175. } else {
  176. container.stdinPipe = ioutils.NopWriteCloser(ioutil.Discard) // Silently drop stdin
  177. }
  178. // done
  179. daemon.containers.Add(container.ID, container)
  180. // don't update the Suffixarray if we're starting up
  181. // we'll waste time if we update it for every container
  182. daemon.idIndex.Add(container.ID)
  183. container.registerVolumes()
  184. // FIXME: if the container is supposed to be running but is not, auto restart it?
  185. // if so, then we need to restart monitor and init a new lock
  186. // If the container is supposed to be running, make sure of it
  187. if container.IsRunning() {
  188. logrus.Debugf("killing old running container %s", container.ID)
  189. container.SetStopped(&execdriver.ExitStatus{ExitCode: 0})
  190. // We only have to handle this for lxc because the other drivers will ensure that
  191. // no processes are left when docker dies
  192. if container.ExecDriver == "" || strings.Contains(container.ExecDriver, "lxc") {
  193. lxc.KillLxc(container.ID, 9)
  194. } else {
  195. // use the current driver and ensure that the container is dead x.x
  196. cmd := &execdriver.Command{
  197. ID: container.ID,
  198. }
  199. daemon.execDriver.Terminate(cmd)
  200. }
  201. if err := container.Unmount(); err != nil {
  202. logrus.Debugf("unmount error %s", err)
  203. }
  204. if err := container.ToDisk(); err != nil {
  205. logrus.Debugf("saving stopped state to disk %s", err)
  206. }
  207. }
  208. return nil
  209. }
  210. func (daemon *Daemon) ensureName(container *Container) error {
  211. if container.Name == "" {
  212. name, err := daemon.generateNewName(container.ID)
  213. if err != nil {
  214. return err
  215. }
  216. container.Name = name
  217. if err := container.ToDisk(); err != nil {
  218. logrus.Debugf("Error saving container name %s", err)
  219. }
  220. }
  221. return nil
  222. }
  223. func (daemon *Daemon) restore() error {
  224. var (
  225. debug = (os.Getenv("DEBUG") != "" || os.Getenv("TEST") != "")
  226. containers = make(map[string]*Container)
  227. currentDriver = daemon.driver.String()
  228. )
  229. if !debug {
  230. logrus.Info("Loading containers: start.")
  231. }
  232. dir, err := ioutil.ReadDir(daemon.repository)
  233. if err != nil {
  234. return err
  235. }
  236. for _, v := range dir {
  237. id := v.Name()
  238. container, err := daemon.load(id)
  239. if !debug && logrus.GetLevel() == logrus.InfoLevel {
  240. fmt.Print(".")
  241. }
  242. if err != nil {
  243. logrus.Errorf("Failed to load container %v: %v", id, err)
  244. continue
  245. }
  246. // Ignore the container if it does not support the current driver being used by the graph
  247. if (container.Driver == "" && currentDriver == "aufs") || container.Driver == currentDriver {
  248. logrus.Debugf("Loaded container %v", container.ID)
  249. containers[container.ID] = container
  250. } else {
  251. logrus.Debugf("Cannot load container %s because it was created with another graph driver.", container.ID)
  252. }
  253. }
  254. registeredContainers := []*Container{}
  255. if entities := daemon.containerGraph.List("/", -1); entities != nil {
  256. for _, p := range entities.Paths() {
  257. if !debug && logrus.GetLevel() == logrus.InfoLevel {
  258. fmt.Print(".")
  259. }
  260. e := entities[p]
  261. if container, ok := containers[e.ID()]; ok {
  262. if err := daemon.register(container, false); err != nil {
  263. logrus.Debugf("Failed to register container %s: %s", container.ID, err)
  264. }
  265. registeredContainers = append(registeredContainers, container)
  266. // delete from the map so that a new name is not automatically generated
  267. delete(containers, e.ID())
  268. }
  269. }
  270. }
  271. // Any containers that are left over do not exist in the graph
  272. for _, container := range containers {
  273. // Try to set the default name for a container if it exists prior to links
  274. container.Name, err = daemon.generateNewName(container.ID)
  275. if err != nil {
  276. logrus.Debugf("Setting default id - %s", err)
  277. }
  278. if err := daemon.register(container, false); err != nil {
  279. logrus.Debugf("Failed to register container %s: %s", container.ID, err)
  280. }
  281. registeredContainers = append(registeredContainers, container)
  282. }
  283. // check the restart policy on the containers and restart any container with
  284. // the restart policy of "always"
  285. if daemon.config.AutoRestart {
  286. logrus.Debug("Restarting containers...")
  287. for _, container := range registeredContainers {
  288. if container.hostConfig.RestartPolicy.Name == "always" ||
  289. (container.hostConfig.RestartPolicy.Name == "on-failure" && container.ExitCode != 0) {
  290. logrus.Debugf("Starting container %s", container.ID)
  291. if err := container.Start(); err != nil {
  292. logrus.Debugf("Failed to start container %s: %s", container.ID, err)
  293. }
  294. }
  295. }
  296. }
  297. if !debug {
  298. if logrus.GetLevel() == logrus.InfoLevel {
  299. fmt.Println()
  300. }
  301. logrus.Info("Loading containers: done.")
  302. }
  303. return nil
  304. }
  305. // set up the watch on the host's /etc/resolv.conf so that we can update container's
  306. // live resolv.conf when the network changes on the host
  307. func (daemon *Daemon) setupResolvconfWatcher() error {
  308. watcher, err := fsnotify.NewWatcher()
  309. if err != nil {
  310. return err
  311. }
  312. //this goroutine listens for the events on the watch we add
  313. //on the resolv.conf file on the host
  314. go func() {
  315. for {
  316. select {
  317. case event := <-watcher.Events:
  318. if event.Name == "/etc/resolv.conf" &&
  319. (event.Op&(fsnotify.Write|fsnotify.Create) != 0) {
  320. // verify a real change happened before we go further--a file write may have happened
  321. // without an actual change to the file
  322. updatedResolvConf, newResolvConfHash, err := resolvconf.GetIfChanged()
  323. if err != nil {
  324. logrus.Debugf("Error retrieving updated host resolv.conf: %v", err)
  325. } else if updatedResolvConf != nil {
  326. // because the new host resolv.conf might have localhost nameservers..
  327. updatedResolvConf, modified := resolvconf.FilterResolvDns(updatedResolvConf, daemon.config.Bridge.EnableIPv6)
  328. if modified {
  329. // changes have occurred during localhost cleanup: generate an updated hash
  330. newHash, err := ioutils.HashData(bytes.NewReader(updatedResolvConf))
  331. if err != nil {
  332. logrus.Debugf("Error generating hash of new resolv.conf: %v", err)
  333. } else {
  334. newResolvConfHash = newHash
  335. }
  336. }
  337. logrus.Debug("host network resolv.conf changed--walking container list for updates")
  338. contList := daemon.containers.List()
  339. for _, container := range contList {
  340. if err := container.updateResolvConf(updatedResolvConf, newResolvConfHash); err != nil {
  341. logrus.Debugf("Error on resolv.conf update check for container ID: %s: %v", container.ID, err)
  342. }
  343. }
  344. }
  345. }
  346. case err := <-watcher.Errors:
  347. logrus.Debugf("host resolv.conf notify error: %v", err)
  348. }
  349. }
  350. }()
  351. if err := watcher.Add("/etc"); err != nil {
  352. return err
  353. }
  354. return nil
  355. }
  356. func (daemon *Daemon) checkDeprecatedExpose(config *runconfig.Config) bool {
  357. if config != nil {
  358. if config.PortSpecs != nil {
  359. for _, p := range config.PortSpecs {
  360. if strings.Contains(p, ":") {
  361. return true
  362. }
  363. }
  364. }
  365. }
  366. return false
  367. }
  368. func (daemon *Daemon) mergeAndVerifyConfig(config *runconfig.Config, img *image.Image) ([]string, error) {
  369. warnings := []string{}
  370. if (img != nil && daemon.checkDeprecatedExpose(img.Config)) || daemon.checkDeprecatedExpose(config) {
  371. 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.")
  372. }
  373. if img != nil && img.Config != nil {
  374. if err := runconfig.Merge(config, img.Config); err != nil {
  375. return nil, err
  376. }
  377. }
  378. if config.Entrypoint.Len() == 0 && config.Cmd.Len() == 0 {
  379. return nil, fmt.Errorf("No command specified")
  380. }
  381. return warnings, nil
  382. }
  383. func (daemon *Daemon) generateIdAndName(name string) (string, string, error) {
  384. var (
  385. err error
  386. id = stringid.GenerateRandomID()
  387. )
  388. if name == "" {
  389. if name, err = daemon.generateNewName(id); err != nil {
  390. return "", "", err
  391. }
  392. return id, name, nil
  393. }
  394. if name, err = daemon.reserveName(id, name); err != nil {
  395. return "", "", err
  396. }
  397. return id, name, nil
  398. }
  399. func (daemon *Daemon) reserveName(id, name string) (string, error) {
  400. if !validContainerNamePattern.MatchString(name) {
  401. return "", fmt.Errorf("Invalid container name (%s), only %s are allowed", name, validContainerNameChars)
  402. }
  403. if name[0] != '/' {
  404. name = "/" + name
  405. }
  406. if _, err := daemon.containerGraph.Set(name, id); err != nil {
  407. if !graphdb.IsNonUniqueNameError(err) {
  408. return "", err
  409. }
  410. conflictingContainer, err := daemon.GetByName(name)
  411. if err != nil {
  412. if strings.Contains(err.Error(), "Could not find entity") {
  413. return "", err
  414. }
  415. // Remove name and continue starting the container
  416. if err := daemon.containerGraph.Delete(name); err != nil {
  417. return "", err
  418. }
  419. } else {
  420. nameAsKnownByUser := strings.TrimPrefix(name, "/")
  421. return "", fmt.Errorf(
  422. "Conflict. The name %q is already in use by container %s. You have to delete (or rename) that container to be able to reuse that name.", nameAsKnownByUser,
  423. stringid.TruncateID(conflictingContainer.ID))
  424. }
  425. }
  426. return name, nil
  427. }
  428. func (daemon *Daemon) generateNewName(id string) (string, error) {
  429. var name string
  430. for i := 0; i < 6; i++ {
  431. name = namesgenerator.GetRandomName(i)
  432. if name[0] != '/' {
  433. name = "/" + name
  434. }
  435. if _, err := daemon.containerGraph.Set(name, id); err != nil {
  436. if !graphdb.IsNonUniqueNameError(err) {
  437. return "", err
  438. }
  439. continue
  440. }
  441. return name, nil
  442. }
  443. name = "/" + stringid.TruncateID(id)
  444. if _, err := daemon.containerGraph.Set(name, id); err != nil {
  445. return "", err
  446. }
  447. return name, nil
  448. }
  449. func (daemon *Daemon) generateHostname(id string, config *runconfig.Config) {
  450. // Generate default hostname
  451. // FIXME: the lxc template no longer needs to set a default hostname
  452. if config.Hostname == "" {
  453. config.Hostname = id[:12]
  454. }
  455. }
  456. func (daemon *Daemon) getEntrypointAndArgs(configEntrypoint *runconfig.Entrypoint, configCmd *runconfig.Command) (string, []string) {
  457. var (
  458. entrypoint string
  459. args []string
  460. )
  461. cmdSlice := configCmd.Slice()
  462. if configEntrypoint.Len() != 0 {
  463. eSlice := configEntrypoint.Slice()
  464. entrypoint = eSlice[0]
  465. args = append(eSlice[1:], cmdSlice...)
  466. } else {
  467. entrypoint = cmdSlice[0]
  468. args = cmdSlice[1:]
  469. }
  470. return entrypoint, args
  471. }
  472. func parseSecurityOpt(container *Container, config *runconfig.HostConfig) error {
  473. var (
  474. labelOpts []string
  475. err error
  476. )
  477. for _, opt := range config.SecurityOpt {
  478. con := strings.SplitN(opt, ":", 2)
  479. if len(con) == 1 {
  480. return fmt.Errorf("Invalid --security-opt: %q", opt)
  481. }
  482. switch con[0] {
  483. case "label":
  484. labelOpts = append(labelOpts, con[1])
  485. case "apparmor":
  486. container.AppArmorProfile = con[1]
  487. default:
  488. return fmt.Errorf("Invalid --security-opt: %q", opt)
  489. }
  490. }
  491. container.ProcessLabel, container.MountLabel, err = label.InitLabels(labelOpts)
  492. return err
  493. }
  494. func (daemon *Daemon) newContainer(name string, config *runconfig.Config, imgID string) (*Container, error) {
  495. var (
  496. id string
  497. err error
  498. )
  499. id, name, err = daemon.generateIdAndName(name)
  500. if err != nil {
  501. return nil, err
  502. }
  503. daemon.generateHostname(id, config)
  504. entrypoint, args := daemon.getEntrypointAndArgs(config.Entrypoint, config.Cmd)
  505. container := &Container{
  506. // FIXME: we should generate the ID here instead of receiving it as an argument
  507. ID: id,
  508. Created: time.Now().UTC(),
  509. Path: entrypoint,
  510. Args: args, //FIXME: de-duplicate from config
  511. Config: config,
  512. hostConfig: &runconfig.HostConfig{},
  513. ImageID: imgID,
  514. NetworkSettings: &network.Settings{},
  515. Name: name,
  516. Driver: daemon.driver.String(),
  517. ExecDriver: daemon.execDriver.Name(),
  518. State: NewState(),
  519. execCommands: newExecStore(),
  520. }
  521. container.root = daemon.containerRoot(container.ID)
  522. return container, err
  523. }
  524. func (daemon *Daemon) createRootfs(container *Container) error {
  525. // Step 1: create the container directory.
  526. // This doubles as a barrier to avoid race conditions.
  527. if err := os.Mkdir(container.root, 0700); err != nil {
  528. return err
  529. }
  530. initID := fmt.Sprintf("%s-init", container.ID)
  531. if err := daemon.driver.Create(initID, container.ImageID); err != nil {
  532. return err
  533. }
  534. initPath, err := daemon.driver.Get(initID, "")
  535. if err != nil {
  536. return err
  537. }
  538. defer daemon.driver.Put(initID)
  539. if err := graph.SetupInitLayer(initPath); err != nil {
  540. return err
  541. }
  542. if err := daemon.driver.Create(container.ID, initID); err != nil {
  543. return err
  544. }
  545. return nil
  546. }
  547. func GetFullContainerName(name string) (string, error) {
  548. if name == "" {
  549. return "", fmt.Errorf("Container name cannot be empty")
  550. }
  551. if name[0] != '/' {
  552. name = "/" + name
  553. }
  554. return name, nil
  555. }
  556. func (daemon *Daemon) GetByName(name string) (*Container, error) {
  557. fullName, err := GetFullContainerName(name)
  558. if err != nil {
  559. return nil, err
  560. }
  561. entity := daemon.containerGraph.Get(fullName)
  562. if entity == nil {
  563. return nil, fmt.Errorf("Could not find entity for %s", name)
  564. }
  565. e := daemon.containers.Get(entity.ID())
  566. if e == nil {
  567. return nil, fmt.Errorf("Could not find container for entity id %s", entity.ID())
  568. }
  569. return e, nil
  570. }
  571. func (daemon *Daemon) Children(name string) (map[string]*Container, error) {
  572. name, err := GetFullContainerName(name)
  573. if err != nil {
  574. return nil, err
  575. }
  576. children := make(map[string]*Container)
  577. err = daemon.containerGraph.Walk(name, func(p string, e *graphdb.Entity) error {
  578. c, err := daemon.Get(e.ID())
  579. if err != nil {
  580. return err
  581. }
  582. children[p] = c
  583. return nil
  584. }, 0)
  585. if err != nil {
  586. return nil, err
  587. }
  588. return children, nil
  589. }
  590. func (daemon *Daemon) Parents(name string) ([]string, error) {
  591. name, err := GetFullContainerName(name)
  592. if err != nil {
  593. return nil, err
  594. }
  595. return daemon.containerGraph.Parents(name)
  596. }
  597. func (daemon *Daemon) RegisterLink(parent, child *Container, alias string) error {
  598. fullName := path.Join(parent.Name, alias)
  599. if !daemon.containerGraph.Exists(fullName) {
  600. _, err := daemon.containerGraph.Set(fullName, child.ID)
  601. return err
  602. }
  603. return nil
  604. }
  605. func (daemon *Daemon) RegisterLinks(container *Container, hostConfig *runconfig.HostConfig) error {
  606. if hostConfig != nil && hostConfig.Links != nil {
  607. for _, l := range hostConfig.Links {
  608. parts, err := parsers.PartParser("name:alias", l)
  609. if err != nil {
  610. return err
  611. }
  612. child, err := daemon.Get(parts["name"])
  613. if err != nil {
  614. //An error from daemon.Get() means this name could not be found
  615. return fmt.Errorf("Could not get container for %s", parts["name"])
  616. }
  617. for child.hostConfig.NetworkMode.IsContainer() {
  618. parts := strings.SplitN(string(child.hostConfig.NetworkMode), ":", 2)
  619. child, err = daemon.Get(parts[1])
  620. if err != nil {
  621. return fmt.Errorf("Could not get container for %s", parts[1])
  622. }
  623. }
  624. if child.hostConfig.NetworkMode.IsHost() {
  625. return runconfig.ErrConflictHostNetworkAndLinks
  626. }
  627. if err := daemon.RegisterLink(container, child, parts["alias"]); err != nil {
  628. return err
  629. }
  630. }
  631. // After we load all the links into the daemon
  632. // set them to nil on the hostconfig
  633. hostConfig.Links = nil
  634. if err := container.WriteHostConfig(); err != nil {
  635. return err
  636. }
  637. }
  638. return nil
  639. }
  640. func NewDaemon(config *Config, registryService *registry.Service) (daemon *Daemon, err error) {
  641. if config.Mtu == 0 {
  642. config.Mtu = getDefaultNetworkMtu()
  643. }
  644. // Check for mutually incompatible config options
  645. if config.Bridge.Iface != "" && config.Bridge.IP != "" {
  646. return nil, fmt.Errorf("You specified -b & --bip, mutually exclusive options. Please specify only one.")
  647. }
  648. if !config.Bridge.EnableIptables && !config.Bridge.InterContainerCommunication {
  649. return nil, fmt.Errorf("You specified --iptables=false with --icc=false. ICC uses iptables to function. Please set --icc or --iptables to true.")
  650. }
  651. if !config.Bridge.EnableIptables && config.Bridge.EnableIpMasq {
  652. config.Bridge.EnableIpMasq = false
  653. }
  654. config.DisableNetwork = config.Bridge.Iface == disableNetworkBridge
  655. // Check that the system is supported and we have sufficient privileges
  656. if runtime.GOOS != "linux" {
  657. return nil, fmt.Errorf("The Docker daemon is only supported on linux")
  658. }
  659. if os.Geteuid() != 0 {
  660. return nil, fmt.Errorf("The Docker daemon needs to be run as root")
  661. }
  662. if err := checkKernel(); err != nil {
  663. return nil, err
  664. }
  665. // set up the tmpDir to use a canonical path
  666. tmp, err := tempDir(config.Root)
  667. if err != nil {
  668. return nil, fmt.Errorf("Unable to get the TempDir under %s: %s", config.Root, err)
  669. }
  670. realTmp, err := fileutils.ReadSymlinkedDirectory(tmp)
  671. if err != nil {
  672. return nil, fmt.Errorf("Unable to get the full path to the TempDir (%s): %s", tmp, err)
  673. }
  674. os.Setenv("TMPDIR", realTmp)
  675. // get the canonical path to the Docker root directory
  676. var realRoot string
  677. if _, err := os.Stat(config.Root); err != nil && os.IsNotExist(err) {
  678. realRoot = config.Root
  679. } else {
  680. realRoot, err = fileutils.ReadSymlinkedDirectory(config.Root)
  681. if err != nil {
  682. return nil, fmt.Errorf("Unable to get the full path to root (%s): %s", config.Root, err)
  683. }
  684. }
  685. config.Root = realRoot
  686. // Create the root directory if it doesn't exists
  687. if err := os.MkdirAll(config.Root, 0700); err != nil && !os.IsExist(err) {
  688. return nil, err
  689. }
  690. // Set the default driver
  691. graphdriver.DefaultDriver = config.GraphDriver
  692. // Load storage driver
  693. driver, err := graphdriver.New(config.Root, config.GraphOptions)
  694. if err != nil {
  695. return nil, fmt.Errorf("error initializing graphdriver: %v", err)
  696. }
  697. logrus.Debugf("Using graph driver %s", driver)
  698. d := &Daemon{}
  699. d.driver = driver
  700. defer func() {
  701. if err != nil {
  702. if err := d.Shutdown(); err != nil {
  703. logrus.Error(err)
  704. }
  705. }
  706. }()
  707. if config.EnableSelinuxSupport {
  708. if selinuxEnabled() {
  709. // As Docker on btrfs and SELinux are incompatible at present, error on both being enabled
  710. if d.driver.String() == "btrfs" {
  711. return nil, fmt.Errorf("SELinux is not supported with the BTRFS graph driver")
  712. }
  713. logrus.Debug("SELinux enabled successfully")
  714. } else {
  715. logrus.Warn("Docker could not enable SELinux on the host system")
  716. }
  717. } else {
  718. selinuxSetDisabled()
  719. }
  720. daemonRepo := path.Join(config.Root, "containers")
  721. if err := os.MkdirAll(daemonRepo, 0700); err != nil && !os.IsExist(err) {
  722. return nil, err
  723. }
  724. // Migrate the container if it is aufs and aufs is enabled
  725. if err := migrateIfAufs(d.driver, config.Root); err != nil {
  726. return nil, err
  727. }
  728. logrus.Debug("Creating images graph")
  729. g, err := graph.NewGraph(path.Join(config.Root, "graph"), d.driver)
  730. if err != nil {
  731. return nil, err
  732. }
  733. volumesDriver, err := graphdriver.GetDriver("vfs", config.Root, config.GraphOptions)
  734. if err != nil {
  735. return nil, err
  736. }
  737. volumes, err := volumes.NewRepository(filepath.Join(config.Root, "volumes"), volumesDriver)
  738. if err != nil {
  739. return nil, err
  740. }
  741. trustKey, err := api.LoadOrCreateTrustKey(config.TrustKeyPath)
  742. if err != nil {
  743. return nil, err
  744. }
  745. trustDir := path.Join(config.Root, "trust")
  746. if err := os.MkdirAll(trustDir, 0700); err != nil && !os.IsExist(err) {
  747. return nil, err
  748. }
  749. trustService, err := trust.NewTrustStore(trustDir)
  750. if err != nil {
  751. return nil, fmt.Errorf("could not create trust store: %s", err)
  752. }
  753. eventsService := events.New()
  754. logrus.Debug("Creating repository list")
  755. tagCfg := &graph.TagStoreConfig{
  756. Graph: g,
  757. Key: trustKey,
  758. Registry: registryService,
  759. Events: eventsService,
  760. Trust: trustService,
  761. }
  762. repositories, err := graph.NewTagStore(path.Join(config.Root, "repositories-"+d.driver.String()), tagCfg)
  763. if err != nil {
  764. return nil, fmt.Errorf("Couldn't create Tag store: %s", err)
  765. }
  766. if !config.DisableNetwork {
  767. if err := bridge.InitDriver(&config.Bridge); err != nil {
  768. return nil, fmt.Errorf("Error initializing Bridge: %v", err)
  769. }
  770. }
  771. graphdbPath := path.Join(config.Root, "linkgraph.db")
  772. graph, err := graphdb.NewSqliteConn(graphdbPath)
  773. if err != nil {
  774. return nil, err
  775. }
  776. d.containerGraph = graph
  777. localCopy := path.Join(config.Root, "init", fmt.Sprintf("dockerinit-%s", dockerversion.VERSION))
  778. sysInitPath := utils.DockerInitPath(localCopy)
  779. if sysInitPath == "" {
  780. return nil, fmt.Errorf("Could not locate dockerinit: This usually means docker was built incorrectly. See https://docs.docker.com/contributing/devenvironment for official build instructions.")
  781. }
  782. if sysInitPath != localCopy {
  783. // 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).
  784. if err := os.Mkdir(path.Dir(localCopy), 0700); err != nil && !os.IsExist(err) {
  785. return nil, err
  786. }
  787. if _, err := fileutils.CopyFile(sysInitPath, localCopy); err != nil {
  788. return nil, err
  789. }
  790. if err := os.Chmod(localCopy, 0700); err != nil {
  791. return nil, err
  792. }
  793. sysInitPath = localCopy
  794. }
  795. sysInfo := sysinfo.New(false)
  796. const runDir = "/var/run/docker"
  797. ed, err := execdrivers.NewDriver(config.ExecDriver, config.ExecOptions, runDir, config.Root, sysInitPath, sysInfo)
  798. if err != nil {
  799. return nil, err
  800. }
  801. d.ID = trustKey.PublicKey().KeyID()
  802. d.repository = daemonRepo
  803. d.containers = &contStore{s: make(map[string]*Container)}
  804. d.execCommands = newExecStore()
  805. d.graph = g
  806. d.repositories = repositories
  807. d.idIndex = truncindex.NewTruncIndex([]string{})
  808. d.sysInfo = sysInfo
  809. d.volumes = volumes
  810. d.config = config
  811. d.sysInitPath = sysInitPath
  812. d.execDriver = ed
  813. d.statsCollector = newStatsCollector(1 * time.Second)
  814. d.defaultLogConfig = config.LogConfig
  815. d.RegistryService = registryService
  816. d.EventsService = eventsService
  817. if err := d.restore(); err != nil {
  818. return nil, err
  819. }
  820. // set up filesystem watch on resolv.conf for network changes
  821. if err := d.setupResolvconfWatcher(); err != nil {
  822. return nil, err
  823. }
  824. return d, nil
  825. }
  826. func (daemon *Daemon) Shutdown() error {
  827. if daemon.containerGraph != nil {
  828. if err := daemon.containerGraph.Close(); err != nil {
  829. logrus.Errorf("Error during container graph.Close(): %v", err)
  830. }
  831. }
  832. if daemon.driver != nil {
  833. if err := daemon.driver.Cleanup(); err != nil {
  834. logrus.Errorf("Error during graph storage driver.Cleanup(): %v", err)
  835. }
  836. }
  837. if daemon.containers != nil {
  838. group := sync.WaitGroup{}
  839. logrus.Debug("starting clean shutdown of all containers...")
  840. for _, container := range daemon.List() {
  841. c := container
  842. if c.IsRunning() {
  843. logrus.Debugf("stopping %s", c.ID)
  844. group.Add(1)
  845. go func() {
  846. defer group.Done()
  847. if err := c.KillSig(15); err != nil {
  848. logrus.Debugf("kill 15 error for %s - %s", c.ID, err)
  849. }
  850. c.WaitStop(-1 * time.Second)
  851. logrus.Debugf("container stopped %s", c.ID)
  852. }()
  853. }
  854. }
  855. group.Wait()
  856. }
  857. return nil
  858. }
  859. func (daemon *Daemon) Mount(container *Container) error {
  860. dir, err := daemon.driver.Get(container.ID, container.GetMountLabel())
  861. if err != nil {
  862. return fmt.Errorf("Error getting container %s from driver %s: %s", container.ID, daemon.driver, err)
  863. }
  864. if container.basefs == "" {
  865. container.basefs = dir
  866. } else if container.basefs != dir {
  867. daemon.driver.Put(container.ID)
  868. return fmt.Errorf("Error: driver %s is returning inconsistent paths for container %s ('%s' then '%s')",
  869. daemon.driver, container.ID, container.basefs, dir)
  870. }
  871. return nil
  872. }
  873. func (daemon *Daemon) Unmount(container *Container) error {
  874. daemon.driver.Put(container.ID)
  875. return nil
  876. }
  877. func (daemon *Daemon) Changes(container *Container) ([]archive.Change, error) {
  878. initID := fmt.Sprintf("%s-init", container.ID)
  879. return daemon.driver.Changes(container.ID, initID)
  880. }
  881. func (daemon *Daemon) Diff(container *Container) (archive.Archive, error) {
  882. initID := fmt.Sprintf("%s-init", container.ID)
  883. return daemon.driver.Diff(container.ID, initID)
  884. }
  885. func (daemon *Daemon) Run(c *Container, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (execdriver.ExitStatus, error) {
  886. return daemon.execDriver.Run(c.command, pipes, startCallback)
  887. }
  888. func (daemon *Daemon) Pause(c *Container) error {
  889. if err := daemon.execDriver.Pause(c.command); err != nil {
  890. return err
  891. }
  892. c.SetPaused()
  893. return nil
  894. }
  895. func (daemon *Daemon) Unpause(c *Container) error {
  896. if err := daemon.execDriver.Unpause(c.command); err != nil {
  897. return err
  898. }
  899. c.SetUnpaused()
  900. return nil
  901. }
  902. func (daemon *Daemon) Kill(c *Container, sig int) error {
  903. return daemon.execDriver.Kill(c.command, sig)
  904. }
  905. func (daemon *Daemon) Stats(c *Container) (*execdriver.ResourceStats, error) {
  906. return daemon.execDriver.Stats(c.ID)
  907. }
  908. func (daemon *Daemon) SubscribeToContainerStats(name string) (chan interface{}, error) {
  909. c, err := daemon.Get(name)
  910. if err != nil {
  911. return nil, err
  912. }
  913. ch := daemon.statsCollector.collect(c)
  914. return ch, nil
  915. }
  916. func (daemon *Daemon) UnsubscribeToContainerStats(name string, ch chan interface{}) error {
  917. c, err := daemon.Get(name)
  918. if err != nil {
  919. return err
  920. }
  921. daemon.statsCollector.unsubscribe(c, ch)
  922. return nil
  923. }
  924. // FIXME: this is a convenience function for integration tests
  925. // which need direct access to daemon.graph.
  926. // Once the tests switch to using engine and jobs, this method
  927. // can go away.
  928. func (daemon *Daemon) Graph() *graph.Graph {
  929. return daemon.graph
  930. }
  931. func (daemon *Daemon) Repositories() *graph.TagStore {
  932. return daemon.repositories
  933. }
  934. func (daemon *Daemon) Config() *Config {
  935. return daemon.config
  936. }
  937. func (daemon *Daemon) SystemConfig() *sysinfo.SysInfo {
  938. return daemon.sysInfo
  939. }
  940. func (daemon *Daemon) SystemInitPath() string {
  941. return daemon.sysInitPath
  942. }
  943. func (daemon *Daemon) GraphDriver() graphdriver.Driver {
  944. return daemon.driver
  945. }
  946. func (daemon *Daemon) ExecutionDriver() execdriver.Driver {
  947. return daemon.execDriver
  948. }
  949. func (daemon *Daemon) ContainerGraph() *graphdb.Database {
  950. return daemon.containerGraph
  951. }
  952. func (daemon *Daemon) ImageGetCached(imgID string, config *runconfig.Config) (*image.Image, error) {
  953. // Retrieve all images
  954. images, err := daemon.Graph().Map()
  955. if err != nil {
  956. return nil, err
  957. }
  958. // Store the tree in a map of map (map[parentId][childId])
  959. imageMap := make(map[string]map[string]struct{})
  960. for _, img := range images {
  961. if _, exists := imageMap[img.Parent]; !exists {
  962. imageMap[img.Parent] = make(map[string]struct{})
  963. }
  964. imageMap[img.Parent][img.ID] = struct{}{}
  965. }
  966. // Loop on the children of the given image and check the config
  967. var match *image.Image
  968. for elem := range imageMap[imgID] {
  969. img, ok := images[elem]
  970. if !ok {
  971. return nil, fmt.Errorf("unable to find image %q", elem)
  972. }
  973. if runconfig.Compare(&img.ContainerConfig, config) {
  974. if match == nil || match.Created.Before(img.Created) {
  975. match = img
  976. }
  977. }
  978. }
  979. return match, nil
  980. }
  981. // tempDir returns the default directory to use for temporary files.
  982. func tempDir(rootDir string) (string, error) {
  983. var tmpDir string
  984. if tmpDir = os.Getenv("DOCKER_TMPDIR"); tmpDir == "" {
  985. tmpDir = filepath.Join(rootDir, "tmp")
  986. }
  987. return tmpDir, os.MkdirAll(tmpDir, 0700)
  988. }
  989. func checkKernel() error {
  990. // Check for unsupported kernel versions
  991. // FIXME: it would be cleaner to not test for specific versions, but rather
  992. // test for specific functionalities.
  993. // Unfortunately we can't test for the feature "does not cause a kernel panic"
  994. // without actually causing a kernel panic, so we need this workaround until
  995. // the circumstances of pre-3.8 crashes are clearer.
  996. // For details see https://github.com/docker/docker/issues/407
  997. if k, err := kernel.GetKernelVersion(); err != nil {
  998. logrus.Warnf("%s", err)
  999. } else {
  1000. if kernel.CompareKernelVersion(k, &kernel.KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}) < 0 {
  1001. if os.Getenv("DOCKER_NOWARN_KERNEL_VERSION") == "" {
  1002. logrus.Warnf("You are running linux kernel version %s, which might be unstable running docker. Please upgrade your kernel to 3.8.0.", k.String())
  1003. }
  1004. }
  1005. }
  1006. return nil
  1007. }
  1008. func (daemon *Daemon) verifyHostConfig(hostConfig *runconfig.HostConfig) ([]string, error) {
  1009. var warnings []string
  1010. if hostConfig == nil {
  1011. return warnings, nil
  1012. }
  1013. if hostConfig.LxcConf.Len() > 0 && !strings.Contains(daemon.ExecutionDriver().Name(), "lxc") {
  1014. return warnings, fmt.Errorf("Cannot use --lxc-conf with execdriver: %s", daemon.ExecutionDriver().Name())
  1015. }
  1016. if hostConfig.Memory != 0 && hostConfig.Memory < 4194304 {
  1017. return warnings, fmt.Errorf("Minimum memory limit allowed is 4MB")
  1018. }
  1019. if hostConfig.Memory > 0 && !daemon.SystemConfig().MemoryLimit {
  1020. warnings = append(warnings, "Your kernel does not support memory limit capabilities. Limitation discarded.")
  1021. hostConfig.Memory = 0
  1022. }
  1023. if hostConfig.Memory > 0 && hostConfig.MemorySwap != -1 && !daemon.SystemConfig().SwapLimit {
  1024. warnings = append(warnings, "Your kernel does not support swap limit capabilities, memory limited without swap.")
  1025. hostConfig.MemorySwap = -1
  1026. }
  1027. if hostConfig.Memory > 0 && hostConfig.MemorySwap > 0 && hostConfig.MemorySwap < hostConfig.Memory {
  1028. return warnings, fmt.Errorf("Minimum memoryswap limit should be larger than memory limit, see usage.")
  1029. }
  1030. if hostConfig.Memory == 0 && hostConfig.MemorySwap > 0 {
  1031. return warnings, fmt.Errorf("You should always set the Memory limit when using Memoryswap limit, see usage.")
  1032. }
  1033. if hostConfig.CpuQuota > 0 && !daemon.SystemConfig().CpuCfsQuota {
  1034. warnings = append(warnings, "Your kernel does not support CPU cfs quota. Quota discarded.")
  1035. hostConfig.CpuQuota = 0
  1036. }
  1037. return warnings, nil
  1038. }
  1039. func (daemon *Daemon) setHostConfig(container *Container, hostConfig *runconfig.HostConfig) error {
  1040. container.Lock()
  1041. defer container.Unlock()
  1042. if err := parseSecurityOpt(container, hostConfig); err != nil {
  1043. return err
  1044. }
  1045. // Register any links from the host config before starting the container
  1046. if err := daemon.RegisterLinks(container, hostConfig); err != nil {
  1047. return err
  1048. }
  1049. container.hostConfig = hostConfig
  1050. container.toDisk()
  1051. return nil
  1052. }