runtime.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. package docker
  2. import (
  3. "container/list"
  4. "fmt"
  5. "github.com/dotcloud/docker/auth"
  6. "io"
  7. "io/ioutil"
  8. "log"
  9. "os"
  10. "os/exec"
  11. "path"
  12. "sort"
  13. "strings"
  14. )
  15. type Capabilities struct {
  16. MemoryLimit bool
  17. SwapLimit bool
  18. }
  19. type Runtime struct {
  20. root string
  21. repository string
  22. containers *list.List
  23. networkManager *NetworkManager
  24. graph *Graph
  25. repositories *TagStore
  26. authConfig *auth.AuthConfig
  27. idIndex *TruncIndex
  28. capabilities *Capabilities
  29. kernelVersion *KernelVersionInfo
  30. autoRestart bool
  31. volumes *Graph
  32. }
  33. var sysInitPath string
  34. func init() {
  35. sysInitPath = SelfPath()
  36. }
  37. func (runtime *Runtime) List() []*Container {
  38. containers := new(History)
  39. for e := runtime.containers.Front(); e != nil; e = e.Next() {
  40. containers.Add(e.Value.(*Container))
  41. }
  42. return *containers
  43. }
  44. func (runtime *Runtime) getContainerElement(id string) *list.Element {
  45. for e := runtime.containers.Front(); e != nil; e = e.Next() {
  46. container := e.Value.(*Container)
  47. if container.Id == id {
  48. return e
  49. }
  50. }
  51. return nil
  52. }
  53. func (runtime *Runtime) Get(name string) *Container {
  54. id, err := runtime.idIndex.Get(name)
  55. if err != nil {
  56. return nil
  57. }
  58. e := runtime.getContainerElement(id)
  59. if e == nil {
  60. return nil
  61. }
  62. return e.Value.(*Container)
  63. }
  64. func (runtime *Runtime) Exists(id string) bool {
  65. return runtime.Get(id) != nil
  66. }
  67. func (runtime *Runtime) containerRoot(id string) string {
  68. return path.Join(runtime.repository, id)
  69. }
  70. func (runtime *Runtime) Load(id string) (*Container, error) {
  71. container := &Container{root: runtime.containerRoot(id)}
  72. if err := container.FromDisk(); err != nil {
  73. return nil, err
  74. }
  75. if container.Id != id {
  76. return container, fmt.Errorf("Container %s is stored at %s", container.Id, id)
  77. }
  78. if container.State.Running {
  79. container.State.Ghost = true
  80. }
  81. if err := runtime.Register(container); err != nil {
  82. return nil, err
  83. }
  84. return container, nil
  85. }
  86. // Register makes a container object usable by the runtime as <container.Id>
  87. func (runtime *Runtime) Register(container *Container) error {
  88. if container.runtime != nil || runtime.Exists(container.Id) {
  89. return fmt.Errorf("Container is already loaded")
  90. }
  91. if err := validateId(container.Id); err != nil {
  92. return err
  93. }
  94. // init the wait lock
  95. container.waitLock = make(chan struct{})
  96. // Even if not running, we init the lock (prevents races in start/stop/kill)
  97. container.State.initLock()
  98. container.runtime = runtime
  99. // Attach to stdout and stderr
  100. container.stderr = newWriteBroadcaster()
  101. container.stdout = newWriteBroadcaster()
  102. // Attach to stdin
  103. if container.Config.OpenStdin {
  104. container.stdin, container.stdinPipe = io.Pipe()
  105. } else {
  106. container.stdinPipe = NopWriteCloser(ioutil.Discard) // Silently drop stdin
  107. }
  108. // done
  109. runtime.containers.PushBack(container)
  110. runtime.idIndex.Add(container.Id)
  111. // When we actually restart, Start() do the monitoring.
  112. // However, when we simply 'reattach', we have to restart a monitor
  113. nomonitor := false
  114. // FIXME: if the container is supposed to be running but is not, auto restart it?
  115. // if so, then we need to restart monitor and init a new lock
  116. // If the container is supposed to be running, make sure of it
  117. if container.State.Running {
  118. if output, err := exec.Command("lxc-info", "-n", container.Id).CombinedOutput(); err != nil {
  119. return err
  120. } else {
  121. if !strings.Contains(string(output), "RUNNING") {
  122. Debugf("Container %s was supposed to be running be is not.", container.Id)
  123. if runtime.autoRestart {
  124. Debugf("Restarting")
  125. container.State.Ghost = false
  126. container.State.setStopped(0)
  127. if err := container.Start(); err != nil {
  128. return err
  129. }
  130. nomonitor = true
  131. } else {
  132. Debugf("Marking as stopped")
  133. container.State.setStopped(-127)
  134. if err := container.ToDisk(); err != nil {
  135. return err
  136. }
  137. }
  138. }
  139. }
  140. }
  141. // If the container is not running or just has been flagged not running
  142. // then close the wait lock chan (will be reset upon start)
  143. if !container.State.Running {
  144. close(container.waitLock)
  145. } else if !nomonitor {
  146. container.allocateNetwork()
  147. go container.monitor()
  148. }
  149. return nil
  150. }
  151. func (runtime *Runtime) LogToDisk(src *writeBroadcaster, dst string) error {
  152. log, err := os.OpenFile(dst, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0600)
  153. if err != nil {
  154. return err
  155. }
  156. src.AddWriter(log)
  157. return nil
  158. }
  159. func (runtime *Runtime) Destroy(container *Container) error {
  160. if container == nil {
  161. return fmt.Errorf("The given container is <nil>")
  162. }
  163. element := runtime.getContainerElement(container.Id)
  164. if element == nil {
  165. return fmt.Errorf("Container %v not found - maybe it was already destroyed?", container.Id)
  166. }
  167. if err := container.Stop(10); err != nil {
  168. return err
  169. }
  170. if mounted, err := container.Mounted(); err != nil {
  171. return err
  172. } else if mounted {
  173. if err := container.Unmount(); err != nil {
  174. return fmt.Errorf("Unable to unmount container %v: %v", container.Id, err)
  175. }
  176. }
  177. // Deregister the container before removing its directory, to avoid race conditions
  178. runtime.idIndex.Delete(container.Id)
  179. runtime.containers.Remove(element)
  180. if err := os.RemoveAll(container.root); err != nil {
  181. return fmt.Errorf("Unable to remove filesystem for %v: %v", container.Id, err)
  182. }
  183. return nil
  184. }
  185. func (runtime *Runtime) restore() error {
  186. dir, err := ioutil.ReadDir(runtime.repository)
  187. if err != nil {
  188. return err
  189. }
  190. for _, v := range dir {
  191. id := v.Name()
  192. container, err := runtime.Load(id)
  193. if err != nil {
  194. Debugf("Failed to load container %v: %v", id, err)
  195. continue
  196. }
  197. Debugf("Loaded container %v", container.Id)
  198. }
  199. return nil
  200. }
  201. func (runtime *Runtime) UpdateCapabilities(quiet bool) {
  202. if cgroupMemoryMountpoint, err := FindCgroupMountpoint("memory"); err != nil {
  203. if !quiet {
  204. log.Printf("WARNING: %s\n", err)
  205. }
  206. } else {
  207. _, err1 := ioutil.ReadFile(path.Join(cgroupMemoryMountpoint, "memory.limit_in_bytes"))
  208. _, err2 := ioutil.ReadFile(path.Join(cgroupMemoryMountpoint, "memory.soft_limit_in_bytes"))
  209. runtime.capabilities.MemoryLimit = err1 == nil && err2 == nil
  210. if !runtime.capabilities.MemoryLimit && !quiet {
  211. log.Printf("WARNING: Your kernel does not support cgroup memory limit.")
  212. }
  213. _, err = ioutil.ReadFile(path.Join(cgroupMemoryMountpoint, "memory.memsw.limit_in_bytes"))
  214. runtime.capabilities.SwapLimit = err == nil
  215. if !runtime.capabilities.SwapLimit && !quiet {
  216. log.Printf("WARNING: Your kernel does not support cgroup swap limit.")
  217. }
  218. }
  219. }
  220. // FIXME: harmonize with NewGraph()
  221. func NewRuntime(autoRestart bool) (*Runtime, error) {
  222. runtime, err := NewRuntimeFromDirectory("/var/lib/docker", autoRestart)
  223. if err != nil {
  224. return nil, err
  225. }
  226. if k, err := GetKernelVersion(); err != nil {
  227. log.Printf("WARNING: %s\n", err)
  228. } else {
  229. runtime.kernelVersion = k
  230. if CompareKernelVersion(k, &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}) < 0 {
  231. 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())
  232. }
  233. }
  234. runtime.UpdateCapabilities(false)
  235. return runtime, nil
  236. }
  237. func NewRuntimeFromDirectory(root string, autoRestart bool) (*Runtime, error) {
  238. runtimeRepo := path.Join(root, "containers")
  239. if err := os.MkdirAll(runtimeRepo, 0700); err != nil && !os.IsExist(err) {
  240. return nil, err
  241. }
  242. g, err := NewGraph(path.Join(root, "graph"))
  243. if err != nil {
  244. return nil, err
  245. }
  246. volumes, err := NewGraph(path.Join(root, "volumes"))
  247. if err != nil {
  248. return nil, err
  249. }
  250. repositories, err := NewTagStore(path.Join(root, "repositories"), g)
  251. if err != nil {
  252. return nil, fmt.Errorf("Couldn't create Tag store: %s", err)
  253. }
  254. if NetworkBridgeIface == "" {
  255. NetworkBridgeIface = DefaultNetworkBridge
  256. }
  257. netManager, err := newNetworkManager(NetworkBridgeIface)
  258. if err != nil {
  259. return nil, err
  260. }
  261. authConfig, err := auth.LoadConfig(root)
  262. if err != nil && authConfig == nil {
  263. // If the auth file does not exist, keep going
  264. return nil, err
  265. }
  266. runtime := &Runtime{
  267. root: root,
  268. repository: runtimeRepo,
  269. containers: list.New(),
  270. networkManager: netManager,
  271. graph: g,
  272. repositories: repositories,
  273. authConfig: authConfig,
  274. idIndex: NewTruncIndex(),
  275. capabilities: &Capabilities{},
  276. autoRestart: autoRestart,
  277. volumes: volumes,
  278. }
  279. if err := runtime.restore(); err != nil {
  280. return nil, err
  281. }
  282. return runtime, nil
  283. }
  284. type History []*Container
  285. func (history *History) Len() int {
  286. return len(*history)
  287. }
  288. func (history *History) Less(i, j int) bool {
  289. containers := *history
  290. return containers[j].When().Before(containers[i].When())
  291. }
  292. func (history *History) Swap(i, j int) {
  293. containers := *history
  294. tmp := containers[i]
  295. containers[i] = containers[j]
  296. containers[j] = tmp
  297. }
  298. func (history *History) Add(container *Container) {
  299. *history = append(*history, container)
  300. sort.Sort(history)
  301. }