daemon.go 34 KB

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