daemon.go 36 KB

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