daemon.go 36 KB

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