daemon.go 36 KB

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