runtime.go 18 KB

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