runtime.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  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. checkDeprecatedExpose := func(config *Config) bool {
  282. if config != nil {
  283. if config.PortSpecs != nil {
  284. for _, p := range config.PortSpecs {
  285. if strings.Contains(p, ":") {
  286. return true
  287. }
  288. }
  289. }
  290. }
  291. return false
  292. }
  293. warnings := []string{}
  294. if checkDeprecatedExpose(img.Config) || checkDeprecatedExpose(config) {
  295. warnings = append(warnings, "The mapping to public ports on your host has been deprecated. Use -p to publish the ports.")
  296. }
  297. if img.Config != nil {
  298. if err := MergeConfig(config, img.Config); err != nil {
  299. return nil, nil, err
  300. }
  301. }
  302. if len(config.Entrypoint) != 0 && config.Cmd == nil {
  303. config.Cmd = []string{}
  304. } else if config.Cmd == nil || len(config.Cmd) == 0 {
  305. return nil, nil, fmt.Errorf("No command specified")
  306. }
  307. sysInitPath := utils.DockerInitPath()
  308. if sysInitPath == "" {
  309. 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.")
  310. }
  311. // Generate id
  312. id := GenerateID()
  313. if name == "" {
  314. name = generateRandomName(runtime)
  315. }
  316. if name[0] != '/' {
  317. name = "/" + name
  318. }
  319. // Set the enitity in the graph using the default name specified
  320. if _, err := runtime.containerGraph.Set(name, id); err != nil {
  321. if strings.HasSuffix(err.Error(), "name are not unique") {
  322. return nil, nil, fmt.Errorf("Conflict, %s already exists.", name)
  323. }
  324. return nil, nil, err
  325. }
  326. // Generate default hostname
  327. // FIXME: the lxc template no longer needs to set a default hostname
  328. if config.Hostname == "" {
  329. config.Hostname = id[:12]
  330. }
  331. var args []string
  332. var entrypoint string
  333. if len(config.Entrypoint) != 0 {
  334. entrypoint = config.Entrypoint[0]
  335. args = append(config.Entrypoint[1:], config.Cmd...)
  336. } else {
  337. entrypoint = config.Cmd[0]
  338. args = config.Cmd[1:]
  339. }
  340. container := &Container{
  341. // FIXME: we should generate the ID here instead of receiving it as an argument
  342. ID: id,
  343. Created: time.Now(),
  344. Path: entrypoint,
  345. Args: args, //FIXME: de-duplicate from config
  346. Config: config,
  347. Image: img.ID, // Always use the resolved image id
  348. NetworkSettings: &NetworkSettings{},
  349. // FIXME: do we need to store this in the container?
  350. SysInitPath: sysInitPath,
  351. Name: name,
  352. }
  353. container.root = runtime.containerRoot(container.ID)
  354. // Step 1: create the container directory.
  355. // This doubles as a barrier to avoid race conditions.
  356. if err := os.Mkdir(container.root, 0700); err != nil {
  357. return nil, nil, err
  358. }
  359. resolvConf, err := utils.GetResolvConf()
  360. if err != nil {
  361. return nil, nil, err
  362. }
  363. if len(config.Dns) == 0 && len(runtime.config.Dns) == 0 && utils.CheckLocalDns(resolvConf) {
  364. //"WARNING: Docker detected local DNS server on resolv.conf. Using default external servers: %v", defaultDns
  365. runtime.config.Dns = defaultDns
  366. }
  367. // If custom dns exists, then create a resolv.conf for the container
  368. if len(config.Dns) > 0 || len(runtime.config.Dns) > 0 {
  369. var dns []string
  370. if len(config.Dns) > 0 {
  371. dns = config.Dns
  372. } else {
  373. dns = runtime.config.Dns
  374. }
  375. container.ResolvConfPath = path.Join(container.root, "resolv.conf")
  376. f, err := os.Create(container.ResolvConfPath)
  377. if err != nil {
  378. return nil, nil, err
  379. }
  380. defer f.Close()
  381. for _, dns := range dns {
  382. if _, err := f.Write([]byte("nameserver " + dns + "\n")); err != nil {
  383. return nil, nil, err
  384. }
  385. }
  386. } else {
  387. container.ResolvConfPath = "/etc/resolv.conf"
  388. }
  389. // Step 2: save the container json
  390. if err := container.ToDisk(); err != nil {
  391. return nil, nil, err
  392. }
  393. // Step 3: if hostname, build hostname and hosts files
  394. container.HostnamePath = path.Join(container.root, "hostname")
  395. ioutil.WriteFile(container.HostnamePath, []byte(container.Config.Hostname+"\n"), 0644)
  396. hostsContent := []byte(`
  397. 127.0.0.1 localhost
  398. ::1 localhost ip6-localhost ip6-loopback
  399. fe00::0 ip6-localnet
  400. ff00::0 ip6-mcastprefix
  401. ff02::1 ip6-allnodes
  402. ff02::2 ip6-allrouters
  403. `)
  404. container.HostsPath = path.Join(container.root, "hosts")
  405. if container.Config.Domainname != "" {
  406. hostsContent = append([]byte(fmt.Sprintf("::1\t\t%s.%s %s\n", container.Config.Hostname, container.Config.Domainname, container.Config.Hostname)), hostsContent...)
  407. hostsContent = append([]byte(fmt.Sprintf("127.0.0.1\t%s.%s %s\n", container.Config.Hostname, container.Config.Domainname, container.Config.Hostname)), hostsContent...)
  408. } else {
  409. hostsContent = append([]byte(fmt.Sprintf("::1\t\t%s\n", container.Config.Hostname)), hostsContent...)
  410. hostsContent = append([]byte(fmt.Sprintf("127.0.0.1\t%s\n", container.Config.Hostname)), hostsContent...)
  411. }
  412. ioutil.WriteFile(container.HostsPath, hostsContent, 0644)
  413. // Step 4: register the container
  414. if err := runtime.Register(container); err != nil {
  415. return nil, nil, err
  416. }
  417. return container, warnings, nil
  418. }
  419. // Commit creates a new filesystem image from the current state of a container.
  420. // The image can optionally be tagged into a repository
  421. func (runtime *Runtime) Commit(container *Container, repository, tag, comment, author string, config *Config) (*Image, error) {
  422. // FIXME: freeze the container before copying it to avoid data corruption?
  423. // FIXME: this shouldn't be in commands.
  424. if err := container.EnsureMounted(); err != nil {
  425. return nil, err
  426. }
  427. rwTar, err := container.ExportRw()
  428. if err != nil {
  429. return nil, err
  430. }
  431. // Create a new image from the container's base layers + a new layer from container changes
  432. img, err := runtime.graph.Create(rwTar, container, comment, author, config)
  433. if err != nil {
  434. return nil, err
  435. }
  436. // Register the image if needed
  437. if repository != "" {
  438. if err := runtime.repositories.Set(repository, tag, img.ID, true); err != nil {
  439. return img, err
  440. }
  441. }
  442. return img, nil
  443. }
  444. func (runtime *Runtime) getFullName(name string) string {
  445. if name[0] != '/' {
  446. name = "/" + name
  447. }
  448. return name
  449. }
  450. func (runtime *Runtime) GetByName(name string) (*Container, error) {
  451. entity := runtime.containerGraph.Get(runtime.getFullName(name))
  452. if entity == nil {
  453. return nil, fmt.Errorf("Could not find entity for %s", name)
  454. }
  455. e := runtime.getContainerElement(entity.ID())
  456. if e == nil {
  457. return nil, fmt.Errorf("Could not find container for entity id %s", entity.ID())
  458. }
  459. return e.Value.(*Container), nil
  460. }
  461. func (runtime *Runtime) Children(name string) (map[string]*Container, error) {
  462. name = runtime.getFullName(name)
  463. children := make(map[string]*Container)
  464. err := runtime.containerGraph.Walk(name, func(p string, e *gograph.Entity) error {
  465. c := runtime.Get(e.ID())
  466. if c == nil {
  467. return fmt.Errorf("Could not get container for name %s and id %s", e.ID(), p)
  468. }
  469. children[p] = c
  470. return nil
  471. }, 0)
  472. if err != nil {
  473. return nil, err
  474. }
  475. return children, nil
  476. }
  477. func (runtime *Runtime) RegisterLink(parent, child *Container, alias string) error {
  478. fullName := path.Join(parent.Name, alias)
  479. if !runtime.containerGraph.Exists(fullName) {
  480. _, err := runtime.containerGraph.Set(fullName, child.ID)
  481. return err
  482. }
  483. return nil
  484. }
  485. // FIXME: harmonize with NewGraph()
  486. func NewRuntime(config *DaemonConfig) (*Runtime, error) {
  487. runtime, err := NewRuntimeFromDirectory(config)
  488. if err != nil {
  489. return nil, err
  490. }
  491. if k, err := utils.GetKernelVersion(); err != nil {
  492. log.Printf("WARNING: %s\n", err)
  493. } else {
  494. if utils.CompareKernelVersion(k, &utils.KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}) < 0 {
  495. 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())
  496. }
  497. }
  498. runtime.UpdateCapabilities(false)
  499. return runtime, nil
  500. }
  501. func NewRuntimeFromDirectory(config *DaemonConfig) (*Runtime, error) {
  502. runtimeRepo := path.Join(config.GraphPath, "containers")
  503. if err := os.MkdirAll(runtimeRepo, 0700); err != nil && !os.IsExist(err) {
  504. return nil, err
  505. }
  506. g, err := NewGraph(path.Join(config.GraphPath, "graph"))
  507. if err != nil {
  508. return nil, err
  509. }
  510. volumes, err := NewGraph(path.Join(config.GraphPath, "volumes"))
  511. if err != nil {
  512. return nil, err
  513. }
  514. repositories, err := NewTagStore(path.Join(config.GraphPath, "repositories"), g)
  515. if err != nil {
  516. return nil, fmt.Errorf("Couldn't create Tag store: %s", err)
  517. }
  518. if config.BridgeIface == "" {
  519. config.BridgeIface = DefaultNetworkBridge
  520. }
  521. netManager, err := newNetworkManager(config)
  522. if err != nil {
  523. return nil, err
  524. }
  525. gographPath := path.Join(config.GraphPath, "linkgraph.db")
  526. initDatabase := false
  527. if _, err := os.Stat(gographPath); err != nil {
  528. if os.IsNotExist(err) {
  529. initDatabase = true
  530. } else {
  531. return nil, err
  532. }
  533. }
  534. conn, err := sql.Open("sqlite3", gographPath)
  535. if err != nil {
  536. return nil, err
  537. }
  538. graph, err := gograph.NewDatabase(conn, initDatabase)
  539. if err != nil {
  540. return nil, err
  541. }
  542. runtime := &Runtime{
  543. repository: runtimeRepo,
  544. containers: list.New(),
  545. networkManager: netManager,
  546. graph: g,
  547. repositories: repositories,
  548. idIndex: utils.NewTruncIndex(),
  549. capabilities: &Capabilities{},
  550. volumes: volumes,
  551. config: config,
  552. containerGraph: graph,
  553. }
  554. if err := runtime.restore(); err != nil {
  555. return nil, err
  556. }
  557. return runtime, nil
  558. }
  559. func (runtime *Runtime) Close() error {
  560. runtime.networkManager.Close()
  561. return runtime.containerGraph.Close()
  562. }
  563. // History is a convenience type for storing a list of containers,
  564. // ordered by creation date.
  565. type History []*Container
  566. func (history *History) Len() int {
  567. return len(*history)
  568. }
  569. func (history *History) Less(i, j int) bool {
  570. containers := *history
  571. return containers[j].When().Before(containers[i].When())
  572. }
  573. func (history *History) Swap(i, j int) {
  574. containers := *history
  575. tmp := containers[i]
  576. containers[i] = containers[j]
  577. containers[j] = tmp
  578. }
  579. func (history *History) Add(container *Container) {
  580. *history = append(*history, container)
  581. sort.Sort(history)
  582. }