runtime.go 20 KB

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