runtime.go 27 KB

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