runtime.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  1. package docker
  2. import (
  3. "container/list"
  4. "fmt"
  5. "github.com/dotcloud/docker/archive"
  6. "github.com/dotcloud/docker/dockerversion"
  7. "github.com/dotcloud/docker/engine"
  8. "github.com/dotcloud/docker/execdriver"
  9. "github.com/dotcloud/docker/execdriver/lxc"
  10. "github.com/dotcloud/docker/execdriver/native"
  11. "github.com/dotcloud/docker/graphdriver"
  12. "github.com/dotcloud/docker/graphdriver/aufs"
  13. _ "github.com/dotcloud/docker/graphdriver/btrfs"
  14. _ "github.com/dotcloud/docker/graphdriver/devmapper"
  15. _ "github.com/dotcloud/docker/graphdriver/vfs"
  16. _ "github.com/dotcloud/docker/networkdriver/lxc"
  17. "github.com/dotcloud/docker/networkdriver/portallocator"
  18. "github.com/dotcloud/docker/pkg/graphdb"
  19. "github.com/dotcloud/docker/pkg/sysinfo"
  20. "github.com/dotcloud/docker/runconfig"
  21. "github.com/dotcloud/docker/utils"
  22. "io"
  23. "io/ioutil"
  24. "os"
  25. "path"
  26. "regexp"
  27. "sort"
  28. "strings"
  29. "sync"
  30. "time"
  31. )
  32. // Set the max depth to the aufs default that most
  33. // kernels are compiled with
  34. // For more information see: http://sourceforge.net/p/aufs/aufs3-standalone/ci/aufs3.12/tree/config.mk
  35. const MaxImageDepth = 127
  36. var (
  37. defaultDns = []string{"8.8.8.8", "8.8.4.4"}
  38. validContainerNameChars = `[a-zA-Z0-9_.-]`
  39. validContainerNamePattern = regexp.MustCompile(`^/?` + validContainerNameChars + `+$`)
  40. )
  41. type Runtime struct {
  42. repository string
  43. sysInitPath string
  44. containers *list.List
  45. graph *Graph
  46. repositories *TagStore
  47. idIndex *utils.TruncIndex
  48. sysInfo *sysinfo.SysInfo
  49. volumes *Graph
  50. srv *Server
  51. eng *engine.Engine
  52. config *DaemonConfig
  53. containerGraph *graphdb.Database
  54. driver graphdriver.Driver
  55. execDriver execdriver.Driver
  56. }
  57. // List returns an array of all containers registered in the runtime.
  58. func (runtime *Runtime) List() []*Container {
  59. containers := new(History)
  60. for e := runtime.containers.Front(); e != nil; e = e.Next() {
  61. containers.Add(e.Value.(*Container))
  62. }
  63. return *containers
  64. }
  65. func (runtime *Runtime) getContainerElement(id string) *list.Element {
  66. for e := runtime.containers.Front(); e != nil; e = e.Next() {
  67. container := e.Value.(*Container)
  68. if container.ID == id {
  69. return e
  70. }
  71. }
  72. return nil
  73. }
  74. // Get looks for a container by the specified ID or name, and returns it.
  75. // If the container is not found, or if an error occurs, nil is returned.
  76. func (runtime *Runtime) Get(name string) *Container {
  77. if c, _ := runtime.GetByName(name); c != nil {
  78. return c
  79. }
  80. id, err := runtime.idIndex.Get(name)
  81. if err != nil {
  82. return nil
  83. }
  84. e := runtime.getContainerElement(id)
  85. if e == nil {
  86. return nil
  87. }
  88. return e.Value.(*Container)
  89. }
  90. // Exists returns a true if a container of the specified ID or name exists,
  91. // false otherwise.
  92. func (runtime *Runtime) Exists(id string) bool {
  93. return runtime.Get(id) != nil
  94. }
  95. func (runtime *Runtime) containerRoot(id string) string {
  96. return path.Join(runtime.repository, id)
  97. }
  98. // Load reads the contents of a container from disk
  99. // This is typically done at startup.
  100. func (runtime *Runtime) load(id string) (*Container, error) {
  101. container := &Container{root: runtime.containerRoot(id)}
  102. if err := container.FromDisk(); err != nil {
  103. return nil, err
  104. }
  105. if container.ID != id {
  106. return container, fmt.Errorf("Container %s is stored at %s", container.ID, id)
  107. }
  108. if container.State.IsRunning() {
  109. container.State.SetGhost(true)
  110. }
  111. return container, nil
  112. }
  113. // Register makes a container object usable by the runtime as <container.ID>
  114. func (runtime *Runtime) Register(container *Container) error {
  115. if container.runtime != nil || runtime.Exists(container.ID) {
  116. return fmt.Errorf("Container is already loaded")
  117. }
  118. if err := validateID(container.ID); err != nil {
  119. return err
  120. }
  121. if err := runtime.ensureName(container); err != nil {
  122. return err
  123. }
  124. container.runtime = runtime
  125. // Attach to stdout and stderr
  126. container.stderr = utils.NewWriteBroadcaster()
  127. container.stdout = utils.NewWriteBroadcaster()
  128. // Attach to stdin
  129. if container.Config.OpenStdin {
  130. container.stdin, container.stdinPipe = io.Pipe()
  131. } else {
  132. container.stdinPipe = utils.NopWriteCloser(ioutil.Discard) // Silently drop stdin
  133. }
  134. // done
  135. runtime.containers.PushBack(container)
  136. runtime.idIndex.Add(container.ID)
  137. // FIXME: if the container is supposed to be running but is not, auto restart it?
  138. // if so, then we need to restart monitor and init a new lock
  139. // If the container is supposed to be running, make sure of it
  140. if container.State.IsRunning() {
  141. if container.State.IsGhost() {
  142. utils.Debugf("killing ghost %s", container.ID)
  143. existingPid := container.State.Pid
  144. container.State.SetGhost(false)
  145. container.State.SetStopped(0)
  146. if container.ExecDriver == "" || strings.Contains(container.ExecDriver, "lxc") {
  147. lxc.KillLxc(container.ID, 9)
  148. } else {
  149. command := &execdriver.Command{
  150. ID: container.ID,
  151. }
  152. command.Process = &os.Process{Pid: existingPid}
  153. runtime.execDriver.Kill(command, 9)
  154. }
  155. // ensure that the filesystem is also unmounted
  156. unmountVolumesForContainer(container)
  157. if err := container.Unmount(); err != nil {
  158. utils.Debugf("ghost unmount error %s", err)
  159. }
  160. }
  161. info := runtime.execDriver.Info(container.ID)
  162. if !info.IsRunning() {
  163. utils.Debugf("Container %s was supposed to be running but is not.", container.ID)
  164. if runtime.config.AutoRestart {
  165. utils.Debugf("Restarting")
  166. unmountVolumesForContainer(container)
  167. if err := container.Unmount(); err != nil {
  168. utils.Debugf("restart unmount error %s", err)
  169. }
  170. container.State.SetGhost(false)
  171. container.State.SetStopped(0)
  172. if err := container.Start(); err != nil {
  173. return err
  174. }
  175. } else {
  176. utils.Debugf("Marking as stopped")
  177. container.State.SetStopped(-127)
  178. if err := container.ToDisk(); err != nil {
  179. return err
  180. }
  181. }
  182. }
  183. } else {
  184. // When the container is not running, we still initialize the waitLock
  185. // chan and close it. Receiving on nil chan blocks whereas receiving on a
  186. // closed chan does not. In this case we do not want to block.
  187. container.waitLock = make(chan struct{})
  188. close(container.waitLock)
  189. }
  190. return nil
  191. }
  192. func (runtime *Runtime) ensureName(container *Container) error {
  193. if container.Name == "" {
  194. name, err := generateRandomName(runtime)
  195. if err != nil {
  196. name = utils.TruncateID(container.ID)
  197. }
  198. container.Name = name
  199. if err := container.ToDisk(); err != nil {
  200. utils.Debugf("Error saving container name %s", err)
  201. }
  202. if !runtime.containerGraph.Exists(name) {
  203. if _, err := runtime.containerGraph.Set(name, container.ID); err != nil {
  204. utils.Debugf("Setting default id - %s", err)
  205. }
  206. }
  207. }
  208. return nil
  209. }
  210. func (runtime *Runtime) LogToDisk(src *utils.WriteBroadcaster, dst, stream string) error {
  211. log, err := os.OpenFile(dst, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0600)
  212. if err != nil {
  213. return err
  214. }
  215. src.AddWriter(log, stream)
  216. return nil
  217. }
  218. // Destroy unregisters a container from the runtime and cleanly removes its contents from the filesystem.
  219. func (runtime *Runtime) Destroy(container *Container) error {
  220. if container == nil {
  221. return fmt.Errorf("The given container is <nil>")
  222. }
  223. element := runtime.getContainerElement(container.ID)
  224. if element == nil {
  225. return fmt.Errorf("Container %v not found - maybe it was already destroyed?", container.ID)
  226. }
  227. if err := container.Stop(3); err != nil {
  228. return err
  229. }
  230. if err := runtime.driver.Remove(container.ID); err != nil {
  231. return fmt.Errorf("Driver %s failed to remove root filesystem %s: %s", runtime.driver, container.ID, err)
  232. }
  233. initID := fmt.Sprintf("%s-init", container.ID)
  234. if err := runtime.driver.Remove(initID); err != nil {
  235. return fmt.Errorf("Driver %s failed to remove init filesystem %s: %s", runtime.driver, initID, err)
  236. }
  237. if _, err := runtime.containerGraph.Purge(container.ID); err != nil {
  238. utils.Debugf("Unable to remove container from link graph: %s", err)
  239. }
  240. // Deregister the container before removing its directory, to avoid race conditions
  241. runtime.idIndex.Delete(container.ID)
  242. runtime.containers.Remove(element)
  243. if err := os.RemoveAll(container.root); err != nil {
  244. return fmt.Errorf("Unable to remove filesystem for %v: %v", container.ID, err)
  245. }
  246. return nil
  247. }
  248. func (runtime *Runtime) restore() error {
  249. if os.Getenv("DEBUG") == "" && os.Getenv("TEST") == "" {
  250. fmt.Printf("Loading containers: ")
  251. }
  252. dir, err := ioutil.ReadDir(runtime.repository)
  253. if err != nil {
  254. return err
  255. }
  256. containers := make(map[string]*Container)
  257. currentDriver := runtime.driver.String()
  258. for _, v := range dir {
  259. id := v.Name()
  260. container, err := runtime.load(id)
  261. if os.Getenv("DEBUG") == "" && os.Getenv("TEST") == "" {
  262. fmt.Print(".")
  263. }
  264. if err != nil {
  265. utils.Errorf("Failed to load container %v: %v", id, err)
  266. continue
  267. }
  268. // Ignore the container if it does not support the current driver being used by the graph
  269. if container.Driver == "" && currentDriver == "aufs" || container.Driver == currentDriver {
  270. utils.Debugf("Loaded container %v", container.ID)
  271. containers[container.ID] = container
  272. } else {
  273. utils.Debugf("Cannot load container %s because it was created with another graph driver.", container.ID)
  274. }
  275. }
  276. register := func(container *Container) {
  277. if err := runtime.Register(container); err != nil {
  278. utils.Debugf("Failed to register container %s: %s", container.ID, err)
  279. }
  280. }
  281. if entities := runtime.containerGraph.List("/", -1); entities != nil {
  282. for _, p := range entities.Paths() {
  283. if os.Getenv("DEBUG") == "" && os.Getenv("TEST") == "" {
  284. fmt.Print(".")
  285. }
  286. e := entities[p]
  287. if container, ok := containers[e.ID()]; ok {
  288. register(container)
  289. delete(containers, e.ID())
  290. }
  291. }
  292. }
  293. // Any containers that are left over do not exist in the graph
  294. for _, container := range containers {
  295. // Try to set the default name for a container if it exists prior to links
  296. container.Name, err = generateRandomName(runtime)
  297. if err != nil {
  298. container.Name = utils.TruncateID(container.ID)
  299. }
  300. if _, err := runtime.containerGraph.Set(container.Name, container.ID); err != nil {
  301. utils.Debugf("Setting default id - %s", err)
  302. }
  303. register(container)
  304. }
  305. if os.Getenv("DEBUG") == "" && os.Getenv("TEST") == "" {
  306. fmt.Printf(": done.\n")
  307. }
  308. return nil
  309. }
  310. // Create creates a new container from the given configuration with a given name.
  311. func (runtime *Runtime) Create(config *runconfig.Config, name string) (*Container, []string, error) {
  312. // Lookup image
  313. img, err := runtime.repositories.LookupImage(config.Image)
  314. if err != nil {
  315. return nil, nil, err
  316. }
  317. // We add 2 layers to the depth because the container's rw and
  318. // init layer add to the restriction
  319. depth, err := img.Depth()
  320. if err != nil {
  321. return nil, nil, err
  322. }
  323. if depth+2 >= MaxImageDepth {
  324. return nil, nil, fmt.Errorf("Cannot create container with more than %d parents", MaxImageDepth)
  325. }
  326. checkDeprecatedExpose := func(config *runconfig.Config) bool {
  327. if config != nil {
  328. if config.PortSpecs != nil {
  329. for _, p := range config.PortSpecs {
  330. if strings.Contains(p, ":") {
  331. return true
  332. }
  333. }
  334. }
  335. }
  336. return false
  337. }
  338. warnings := []string{}
  339. if checkDeprecatedExpose(img.Config) || checkDeprecatedExpose(config) {
  340. 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.")
  341. }
  342. if img.Config != nil {
  343. if err := runconfig.Merge(config, img.Config); err != nil {
  344. return nil, nil, err
  345. }
  346. }
  347. if len(config.Entrypoint) == 0 && len(config.Cmd) == 0 {
  348. return nil, nil, fmt.Errorf("No command specified")
  349. }
  350. // Generate id
  351. id := GenerateID()
  352. if name == "" {
  353. name, err = generateRandomName(runtime)
  354. if err != nil {
  355. name = utils.TruncateID(id)
  356. }
  357. } else {
  358. if !validContainerNamePattern.MatchString(name) {
  359. return nil, nil, fmt.Errorf("Invalid container name (%s), only %s are allowed", name, validContainerNameChars)
  360. }
  361. }
  362. if name[0] != '/' {
  363. name = "/" + name
  364. }
  365. // Set the enitity in the graph using the default name specified
  366. if _, err := runtime.containerGraph.Set(name, id); err != nil {
  367. if !graphdb.IsNonUniqueNameError(err) {
  368. return nil, nil, err
  369. }
  370. conflictingContainer, err := runtime.GetByName(name)
  371. if err != nil {
  372. if strings.Contains(err.Error(), "Could not find entity") {
  373. return nil, nil, err
  374. }
  375. // Remove name and continue starting the container
  376. if err := runtime.containerGraph.Delete(name); err != nil {
  377. return nil, nil, err
  378. }
  379. } else {
  380. nameAsKnownByUser := strings.TrimPrefix(name, "/")
  381. return nil, nil, fmt.Errorf(
  382. "Conflict, The name %s is already assigned to %s. You have to delete (or rename) that container to be able to assign %s to a container again.", nameAsKnownByUser,
  383. utils.TruncateID(conflictingContainer.ID), nameAsKnownByUser)
  384. }
  385. }
  386. // Generate default hostname
  387. // FIXME: the lxc template no longer needs to set a default hostname
  388. if config.Hostname == "" {
  389. config.Hostname = id[:12]
  390. }
  391. var args []string
  392. var entrypoint string
  393. if len(config.Entrypoint) != 0 {
  394. entrypoint = config.Entrypoint[0]
  395. args = append(config.Entrypoint[1:], config.Cmd...)
  396. } else {
  397. entrypoint = config.Cmd[0]
  398. args = config.Cmd[1:]
  399. }
  400. container := &Container{
  401. // FIXME: we should generate the ID here instead of receiving it as an argument
  402. ID: id,
  403. Created: time.Now().UTC(),
  404. Path: entrypoint,
  405. Args: args, //FIXME: de-duplicate from config
  406. Config: config,
  407. hostConfig: &runconfig.HostConfig{},
  408. Image: img.ID, // Always use the resolved image id
  409. NetworkSettings: &NetworkSettings{},
  410. Name: name,
  411. Driver: runtime.driver.String(),
  412. ExecDriver: runtime.execDriver.Name(),
  413. }
  414. container.root = runtime.containerRoot(container.ID)
  415. // Step 1: create the container directory.
  416. // This doubles as a barrier to avoid race conditions.
  417. if err := os.Mkdir(container.root, 0700); err != nil {
  418. return nil, nil, err
  419. }
  420. initID := fmt.Sprintf("%s-init", container.ID)
  421. if err := runtime.driver.Create(initID, img.ID); err != nil {
  422. return nil, nil, err
  423. }
  424. initPath, err := runtime.driver.Get(initID)
  425. if err != nil {
  426. return nil, nil, err
  427. }
  428. defer runtime.driver.Put(initID)
  429. if err := setupInitLayer(initPath); err != nil {
  430. return nil, nil, err
  431. }
  432. if err := runtime.driver.Create(container.ID, initID); err != nil {
  433. return nil, nil, err
  434. }
  435. resolvConf, err := utils.GetResolvConf()
  436. if err != nil {
  437. return nil, nil, err
  438. }
  439. if len(config.Dns) == 0 && len(runtime.config.Dns) == 0 && utils.CheckLocalDns(resolvConf) {
  440. //"WARNING: Docker detected local DNS server on resolv.conf. Using default external servers: %v", defaultDns
  441. runtime.config.Dns = defaultDns
  442. }
  443. // If custom dns exists, then create a resolv.conf for the container
  444. if len(config.Dns) > 0 || len(runtime.config.Dns) > 0 {
  445. var dns []string
  446. if len(config.Dns) > 0 {
  447. dns = config.Dns
  448. } else {
  449. dns = runtime.config.Dns
  450. }
  451. container.ResolvConfPath = path.Join(container.root, "resolv.conf")
  452. f, err := os.Create(container.ResolvConfPath)
  453. if err != nil {
  454. return nil, nil, err
  455. }
  456. defer f.Close()
  457. for _, dns := range dns {
  458. if _, err := f.Write([]byte("nameserver " + dns + "\n")); err != nil {
  459. return nil, nil, err
  460. }
  461. }
  462. } else {
  463. container.ResolvConfPath = "/etc/resolv.conf"
  464. }
  465. // Step 2: save the container json
  466. if err := container.ToDisk(); err != nil {
  467. return nil, nil, err
  468. }
  469. // Step 3: register the container
  470. if err := runtime.Register(container); err != nil {
  471. return nil, nil, err
  472. }
  473. return container, warnings, nil
  474. }
  475. // Commit creates a new filesystem image from the current state of a container.
  476. // The image can optionally be tagged into a repository
  477. func (runtime *Runtime) Commit(container *Container, repository, tag, comment, author string, config *runconfig.Config) (*Image, error) {
  478. // FIXME: freeze the container before copying it to avoid data corruption?
  479. // FIXME: this shouldn't be in commands.
  480. if err := container.Mount(); err != nil {
  481. return nil, err
  482. }
  483. defer container.Unmount()
  484. rwTar, err := container.ExportRw()
  485. if err != nil {
  486. return nil, err
  487. }
  488. defer rwTar.Close()
  489. // Create a new image from the container's base layers + a new layer from container changes
  490. img, err := runtime.graph.Create(rwTar, container, comment, author, config)
  491. if err != nil {
  492. return nil, err
  493. }
  494. // Register the image if needed
  495. if repository != "" {
  496. if err := runtime.repositories.Set(repository, tag, img.ID, true); err != nil {
  497. return img, err
  498. }
  499. }
  500. return img, nil
  501. }
  502. func getFullName(name string) (string, error) {
  503. if name == "" {
  504. return "", fmt.Errorf("Container name cannot be empty")
  505. }
  506. if name[0] != '/' {
  507. name = "/" + name
  508. }
  509. return name, nil
  510. }
  511. func (runtime *Runtime) GetByName(name string) (*Container, error) {
  512. fullName, err := getFullName(name)
  513. if err != nil {
  514. return nil, err
  515. }
  516. entity := runtime.containerGraph.Get(fullName)
  517. if entity == nil {
  518. return nil, fmt.Errorf("Could not find entity for %s", name)
  519. }
  520. e := runtime.getContainerElement(entity.ID())
  521. if e == nil {
  522. return nil, fmt.Errorf("Could not find container for entity id %s", entity.ID())
  523. }
  524. return e.Value.(*Container), nil
  525. }
  526. func (runtime *Runtime) Children(name string) (map[string]*Container, error) {
  527. name, err := getFullName(name)
  528. if err != nil {
  529. return nil, err
  530. }
  531. children := make(map[string]*Container)
  532. err = runtime.containerGraph.Walk(name, func(p string, e *graphdb.Entity) error {
  533. c := runtime.Get(e.ID())
  534. if c == nil {
  535. return fmt.Errorf("Could not get container for name %s and id %s", e.ID(), p)
  536. }
  537. children[p] = c
  538. return nil
  539. }, 0)
  540. if err != nil {
  541. return nil, err
  542. }
  543. return children, nil
  544. }
  545. func (runtime *Runtime) RegisterLink(parent, child *Container, alias string) error {
  546. fullName := path.Join(parent.Name, alias)
  547. if !runtime.containerGraph.Exists(fullName) {
  548. _, err := runtime.containerGraph.Set(fullName, child.ID)
  549. return err
  550. }
  551. return nil
  552. }
  553. // FIXME: harmonize with NewGraph()
  554. func NewRuntime(config *DaemonConfig, eng *engine.Engine) (*Runtime, error) {
  555. runtime, err := NewRuntimeFromDirectory(config, eng)
  556. if err != nil {
  557. return nil, err
  558. }
  559. return runtime, nil
  560. }
  561. func NewRuntimeFromDirectory(config *DaemonConfig, eng *engine.Engine) (*Runtime, error) {
  562. // Set the default driver
  563. graphdriver.DefaultDriver = config.GraphDriver
  564. // Load storage driver
  565. driver, err := graphdriver.New(config.Root)
  566. if err != nil {
  567. return nil, err
  568. }
  569. utils.Debugf("Using graph driver %s", driver)
  570. runtimeRepo := path.Join(config.Root, "containers")
  571. if err := os.MkdirAll(runtimeRepo, 0700); err != nil && !os.IsExist(err) {
  572. return nil, err
  573. }
  574. if ad, ok := driver.(*aufs.Driver); ok {
  575. utils.Debugf("Migrating existing containers")
  576. if err := ad.Migrate(config.Root, setupInitLayer); err != nil {
  577. return nil, err
  578. }
  579. }
  580. utils.Debugf("Creating images graph")
  581. g, err := NewGraph(path.Join(config.Root, "graph"), driver)
  582. if err != nil {
  583. return nil, err
  584. }
  585. // We don't want to use a complex driver like aufs or devmapper
  586. // for volumes, just a plain filesystem
  587. volumesDriver, err := graphdriver.GetDriver("vfs", config.Root)
  588. if err != nil {
  589. return nil, err
  590. }
  591. utils.Debugf("Creating volumes graph")
  592. volumes, err := NewGraph(path.Join(config.Root, "volumes"), volumesDriver)
  593. if err != nil {
  594. return nil, err
  595. }
  596. utils.Debugf("Creating repository list")
  597. repositories, err := NewTagStore(path.Join(config.Root, "repositories-"+driver.String()), g)
  598. if err != nil {
  599. return nil, fmt.Errorf("Couldn't create Tag store: %s", err)
  600. }
  601. if !config.DisableNetwork {
  602. job := eng.Job("init_networkdriver")
  603. job.SetenvBool("EnableIptables", config.EnableIptables)
  604. job.SetenvBool("InterContainerCommunication", config.InterContainerCommunication)
  605. job.SetenvBool("EnableIpForward", config.EnableIpForward)
  606. job.Setenv("BridgeIface", config.BridgeIface)
  607. job.Setenv("BridgeIP", config.BridgeIP)
  608. job.Setenv("DefaultBindingIP", config.DefaultIp.String())
  609. if err := job.Run(); err != nil {
  610. return nil, err
  611. }
  612. }
  613. graphdbPath := path.Join(config.Root, "linkgraph.db")
  614. graph, err := graphdb.NewSqliteConn(graphdbPath)
  615. if err != nil {
  616. return nil, err
  617. }
  618. localCopy := path.Join(config.Root, "init", fmt.Sprintf("dockerinit-%s", dockerversion.VERSION))
  619. sysInitPath := utils.DockerInitPath(localCopy)
  620. if sysInitPath == "" {
  621. return nil, fmt.Errorf("Could not locate dockerinit: This usually means docker was built incorrectly. See http://docs.docker.io/en/latest/contributing/devenvironment for official build instructions.")
  622. }
  623. if sysInitPath != localCopy {
  624. // 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).
  625. if err := os.Mkdir(path.Dir(localCopy), 0700); err != nil && !os.IsExist(err) {
  626. return nil, err
  627. }
  628. if _, err := utils.CopyFile(sysInitPath, localCopy); err != nil {
  629. return nil, err
  630. }
  631. if err := os.Chmod(localCopy, 0700); err != nil {
  632. return nil, err
  633. }
  634. sysInitPath = localCopy
  635. }
  636. var (
  637. ed execdriver.Driver
  638. sysInfo = sysinfo.New(false)
  639. )
  640. switch config.ExecDriver {
  641. case "lxc":
  642. // we want to five the lxc driver the full docker root because it needs
  643. // to access and write config and template files in /var/lib/docker/containers/*
  644. // to be backwards compatible
  645. ed, err = lxc.NewDriver(config.Root, sysInfo.AppArmor)
  646. case "native":
  647. ed, err = native.NewDriver(path.Join(config.Root, "execdriver", "native"))
  648. default:
  649. return nil, fmt.Errorf("unknown exec driver %s", config.ExecDriver)
  650. }
  651. if err != nil {
  652. return nil, err
  653. }
  654. runtime := &Runtime{
  655. repository: runtimeRepo,
  656. containers: list.New(),
  657. graph: g,
  658. repositories: repositories,
  659. idIndex: utils.NewTruncIndex(),
  660. sysInfo: sysInfo,
  661. volumes: volumes,
  662. config: config,
  663. containerGraph: graph,
  664. driver: driver,
  665. sysInitPath: sysInitPath,
  666. execDriver: ed,
  667. eng: eng,
  668. }
  669. if err := runtime.restore(); err != nil {
  670. return nil, err
  671. }
  672. return runtime, nil
  673. }
  674. func (runtime *Runtime) Close() error {
  675. errorsStrings := []string{}
  676. if err := portallocator.ReleaseAll(); err != nil {
  677. utils.Errorf("portallocator.ReleaseAll(): %s", err)
  678. errorsStrings = append(errorsStrings, err.Error())
  679. }
  680. if err := runtime.driver.Cleanup(); err != nil {
  681. utils.Errorf("runtime.driver.Cleanup(): %s", err.Error())
  682. errorsStrings = append(errorsStrings, err.Error())
  683. }
  684. if err := runtime.containerGraph.Close(); err != nil {
  685. utils.Errorf("runtime.containerGraph.Close(): %s", err.Error())
  686. errorsStrings = append(errorsStrings, err.Error())
  687. }
  688. if len(errorsStrings) > 0 {
  689. return fmt.Errorf("%s", strings.Join(errorsStrings, ", "))
  690. }
  691. return nil
  692. }
  693. func (runtime *Runtime) Mount(container *Container) error {
  694. dir, err := runtime.driver.Get(container.ID)
  695. if err != nil {
  696. return fmt.Errorf("Error getting container %s from driver %s: %s", container.ID, runtime.driver, err)
  697. }
  698. if container.basefs == "" {
  699. container.basefs = dir
  700. } else if container.basefs != dir {
  701. return fmt.Errorf("Error: driver %s is returning inconsistent paths for container %s ('%s' then '%s')",
  702. runtime.driver, container.ID, container.basefs, dir)
  703. }
  704. return nil
  705. }
  706. func (runtime *Runtime) Unmount(container *Container) error {
  707. runtime.driver.Put(container.ID)
  708. return nil
  709. }
  710. func (runtime *Runtime) Changes(container *Container) ([]archive.Change, error) {
  711. if differ, ok := runtime.driver.(graphdriver.Differ); ok {
  712. return differ.Changes(container.ID)
  713. }
  714. cDir, err := runtime.driver.Get(container.ID)
  715. if err != nil {
  716. return nil, fmt.Errorf("Error getting container rootfs %s from driver %s: %s", container.ID, container.runtime.driver, err)
  717. }
  718. defer runtime.driver.Put(container.ID)
  719. initDir, err := runtime.driver.Get(container.ID + "-init")
  720. if err != nil {
  721. return nil, fmt.Errorf("Error getting container init rootfs %s from driver %s: %s", container.ID, container.runtime.driver, err)
  722. }
  723. defer runtime.driver.Put(container.ID + "-init")
  724. return archive.ChangesDirs(cDir, initDir)
  725. }
  726. func (runtime *Runtime) Diff(container *Container) (archive.Archive, error) {
  727. if differ, ok := runtime.driver.(graphdriver.Differ); ok {
  728. return differ.Diff(container.ID)
  729. }
  730. changes, err := runtime.Changes(container)
  731. if err != nil {
  732. return nil, err
  733. }
  734. cDir, err := runtime.driver.Get(container.ID)
  735. if err != nil {
  736. return nil, fmt.Errorf("Error getting container rootfs %s from driver %s: %s", container.ID, container.runtime.driver, err)
  737. }
  738. archive, err := archive.ExportChanges(cDir, changes)
  739. if err != nil {
  740. return nil, err
  741. }
  742. return utils.NewReadCloserWrapper(archive, func() error {
  743. err := archive.Close()
  744. runtime.driver.Put(container.ID)
  745. return err
  746. }), nil
  747. }
  748. func (runtime *Runtime) Run(c *Container, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (int, error) {
  749. return runtime.execDriver.Run(c.command, pipes, startCallback)
  750. }
  751. func (runtime *Runtime) Kill(c *Container, sig int) error {
  752. return runtime.execDriver.Kill(c.command, sig)
  753. }
  754. // Nuke kills all containers then removes all content
  755. // from the content root, including images, volumes and
  756. // container filesystems.
  757. // Again: this will remove your entire docker runtime!
  758. func (runtime *Runtime) Nuke() error {
  759. var wg sync.WaitGroup
  760. for _, container := range runtime.List() {
  761. wg.Add(1)
  762. go func(c *Container) {
  763. c.Kill()
  764. wg.Done()
  765. }(container)
  766. }
  767. wg.Wait()
  768. runtime.Close()
  769. return os.RemoveAll(runtime.config.Root)
  770. }
  771. // FIXME: this is a convenience function for integration tests
  772. // which need direct access to runtime.graph.
  773. // Once the tests switch to using engine and jobs, this method
  774. // can go away.
  775. func (runtime *Runtime) Graph() *Graph {
  776. return runtime.graph
  777. }
  778. // History is a convenience type for storing a list of containers,
  779. // ordered by creation date.
  780. type History []*Container
  781. func (history *History) Len() int {
  782. return len(*history)
  783. }
  784. func (history *History) Less(i, j int) bool {
  785. containers := *history
  786. return containers[j].When().Before(containers[i].When())
  787. }
  788. func (history *History) Swap(i, j int) {
  789. containers := *history
  790. tmp := containers[i]
  791. containers[i] = containers[j]
  792. containers[j] = tmp
  793. }
  794. func (history *History) Add(container *Container) {
  795. *history = append(*history, container)
  796. sort.Sort(history)
  797. }