runtime.go 15 KB

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