runtime.go 22 KB

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