daemon.go 32 KB

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