runtime.go 27 KB

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