runtime.go 26 KB

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