daemon.go 35 KB

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