runtime.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. package docker
  2. import (
  3. "container/list"
  4. "fmt"
  5. "github.com/dotcloud/docker/auth"
  6. "io"
  7. "io/ioutil"
  8. "os"
  9. "os/exec"
  10. "path"
  11. "sort"
  12. "strings"
  13. "time"
  14. )
  15. type Runtime struct {
  16. root string
  17. repository string
  18. containers *list.List
  19. networkManager *NetworkManager
  20. graph *Graph
  21. repositories *TagStore
  22. authConfig *auth.AuthConfig
  23. idIndex *TruncIndex
  24. }
  25. var sysInitPath string
  26. func init() {
  27. sysInitPath = SelfPath()
  28. }
  29. func (runtime *Runtime) List() []*Container {
  30. containers := new(History)
  31. for e := runtime.containers.Front(); e != nil; e = e.Next() {
  32. containers.Add(e.Value.(*Container))
  33. }
  34. return *containers
  35. }
  36. func (runtime *Runtime) getContainerElement(id string) *list.Element {
  37. for e := runtime.containers.Front(); e != nil; e = e.Next() {
  38. container := e.Value.(*Container)
  39. if container.Id == id {
  40. return e
  41. }
  42. }
  43. return nil
  44. }
  45. func (runtime *Runtime) Get(name string) *Container {
  46. id, err := runtime.idIndex.Get(name)
  47. if err != nil {
  48. return nil
  49. }
  50. e := runtime.getContainerElement(id)
  51. if e == nil {
  52. return nil
  53. }
  54. return e.Value.(*Container)
  55. }
  56. func (runtime *Runtime) Exists(id string) bool {
  57. return runtime.Get(id) != nil
  58. }
  59. func (runtime *Runtime) containerRoot(id string) string {
  60. return path.Join(runtime.repository, id)
  61. }
  62. func (runtime *Runtime) Create(config *Config) (*Container, error) {
  63. // Lookup image
  64. img, err := runtime.repositories.LookupImage(config.Image)
  65. if err != nil {
  66. return nil, err
  67. }
  68. // Generate id
  69. id := GenerateId()
  70. // Generate default hostname
  71. // FIXME: the lxc template no longer needs to set a default hostname
  72. if config.Hostname == "" {
  73. config.Hostname = id[:12]
  74. }
  75. container := &Container{
  76. // FIXME: we should generate the ID here instead of receiving it as an argument
  77. Id: id,
  78. Created: time.Now(),
  79. Path: config.Cmd[0],
  80. Args: config.Cmd[1:], //FIXME: de-duplicate from config
  81. Config: config,
  82. Image: img.Id, // Always use the resolved image id
  83. NetworkSettings: &NetworkSettings{},
  84. // FIXME: do we need to store this in the container?
  85. SysInitPath: sysInitPath,
  86. }
  87. container.root = runtime.containerRoot(container.Id)
  88. // Step 1: create the container directory.
  89. // This doubles as a barrier to avoid race conditions.
  90. if err := os.Mkdir(container.root, 0700); err != nil {
  91. return nil, err
  92. }
  93. // If custom dns exists, then create a resolv.conf for the container
  94. if len(config.Dns) > 0 {
  95. container.ResolvConfPath = path.Join(container.root, "resolv.conf")
  96. f, err := os.Create(container.ResolvConfPath)
  97. if err != nil {
  98. return nil, err
  99. }
  100. defer f.Close()
  101. for _, dns := range config.Dns {
  102. if _, err := f.Write([]byte("nameserver " + dns + "\n")); err != nil {
  103. return nil, err
  104. }
  105. }
  106. } else {
  107. container.ResolvConfPath = "/etc/resolv.conf"
  108. }
  109. // Step 2: save the container json
  110. if err := container.ToDisk(); err != nil {
  111. return nil, err
  112. }
  113. // Step 3: register the container
  114. if err := runtime.Register(container); err != nil {
  115. return nil, err
  116. }
  117. return container, nil
  118. }
  119. func (runtime *Runtime) Load(id string) (*Container, error) {
  120. container := &Container{root: runtime.containerRoot(id)}
  121. if err := container.FromDisk(); err != nil {
  122. return nil, err
  123. }
  124. if container.Id != id {
  125. return container, fmt.Errorf("Container %s is stored at %s", container.Id, id)
  126. }
  127. if container.State.Running {
  128. container.State.Ghost = true
  129. }
  130. if err := runtime.Register(container); err != nil {
  131. return nil, err
  132. }
  133. return container, nil
  134. }
  135. // Register makes a container object usable by the runtime as <container.Id>
  136. func (runtime *Runtime) Register(container *Container) error {
  137. if container.runtime != nil || runtime.Exists(container.Id) {
  138. return fmt.Errorf("Container is already loaded")
  139. }
  140. if err := validateId(container.Id); err != nil {
  141. return err
  142. }
  143. // init the wait lock
  144. container.waitLock = make(chan struct{})
  145. // FIXME: if the container is supposed to be running but is not, auto restart it?
  146. // if so, then we need to restart monitor and init a new lock
  147. // If the container is supposed to be running, make sure of it
  148. if container.State.Running {
  149. if output, err := exec.Command("lxc-info", "-n", container.Id).CombinedOutput(); err != nil {
  150. return err
  151. } else {
  152. if !strings.Contains(string(output), "RUNNING") {
  153. Debugf("Container %s was supposed to be running be is not.", container.Id)
  154. container.State.setStopped(-127)
  155. if err := container.ToDisk(); err != nil {
  156. return err
  157. }
  158. }
  159. }
  160. }
  161. // If the container is not running or just has been flagged not running
  162. // then close the wait lock chan (will be reset upon start)
  163. if !container.State.Running {
  164. close(container.waitLock)
  165. }
  166. // Even if not running, we init the lock (prevents races in start/stop/kill)
  167. container.State.initLock()
  168. container.runtime = runtime
  169. // Attach to stdout and stderr
  170. container.stderr = newWriteBroadcaster()
  171. container.stdout = newWriteBroadcaster()
  172. // Attach to stdin
  173. if container.Config.OpenStdin {
  174. container.stdin, container.stdinPipe = io.Pipe()
  175. } else {
  176. container.stdinPipe = NopWriteCloser(ioutil.Discard) // Silently drop stdin
  177. }
  178. // done
  179. runtime.containers.PushBack(container)
  180. runtime.idIndex.Add(container.Id)
  181. return nil
  182. }
  183. func (runtime *Runtime) LogToDisk(src *writeBroadcaster, dst string) error {
  184. log, err := os.OpenFile(dst, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0600)
  185. if err != nil {
  186. return err
  187. }
  188. src.AddWriter(log)
  189. return nil
  190. }
  191. func (runtime *Runtime) Destroy(container *Container) error {
  192. element := runtime.getContainerElement(container.Id)
  193. if element == nil {
  194. return fmt.Errorf("Container %v not found - maybe it was already destroyed?", container.Id)
  195. }
  196. if err := container.Stop(); err != nil {
  197. return err
  198. }
  199. if mounted, err := container.Mounted(); err != nil {
  200. return err
  201. } else if mounted {
  202. if err := container.Unmount(); err != nil {
  203. return fmt.Errorf("Unable to unmount container %v: %v", container.Id, err)
  204. }
  205. }
  206. // Deregister the container before removing its directory, to avoid race conditions
  207. runtime.idIndex.Delete(container.Id)
  208. runtime.containers.Remove(element)
  209. if err := os.RemoveAll(container.root); err != nil {
  210. return fmt.Errorf("Unable to remove filesystem for %v: %v", container.Id, err)
  211. }
  212. return nil
  213. }
  214. // Commit creates a new filesystem image from the current state of a container.
  215. // The image can optionally be tagged into a repository
  216. func (runtime *Runtime) Commit(id, repository, tag, comment string) (*Image, error) {
  217. container := runtime.Get(id)
  218. if container == nil {
  219. return nil, fmt.Errorf("No such container: %s", id)
  220. }
  221. // FIXME: freeze the container before copying it to avoid data corruption?
  222. // FIXME: this shouldn't be in commands.
  223. rwTar, err := container.ExportRw()
  224. if err != nil {
  225. return nil, err
  226. }
  227. // Create a new image from the container's base layers + a new layer from container changes
  228. img, err := runtime.graph.Create(rwTar, container, comment)
  229. if err != nil {
  230. return nil, err
  231. }
  232. // Register the image if needed
  233. if repository != "" {
  234. if err := runtime.repositories.Set(repository, tag, img.Id, true); err != nil {
  235. return img, err
  236. }
  237. }
  238. return img, nil
  239. }
  240. func (runtime *Runtime) restore() error {
  241. dir, err := ioutil.ReadDir(runtime.repository)
  242. if err != nil {
  243. return err
  244. }
  245. for _, v := range dir {
  246. id := v.Name()
  247. container, err := runtime.Load(id)
  248. if err != nil {
  249. Debugf("Failed to load container %v: %v", id, err)
  250. continue
  251. }
  252. Debugf("Loaded container %v", container.Id)
  253. }
  254. return nil
  255. }
  256. // FIXME: harmonize with NewGraph()
  257. func NewRuntime() (*Runtime, error) {
  258. return NewRuntimeFromDirectory("/var/lib/docker")
  259. }
  260. func NewRuntimeFromDirectory(root string) (*Runtime, error) {
  261. runtimeRepo := path.Join(root, "containers")
  262. if err := os.MkdirAll(runtimeRepo, 0700); err != nil && !os.IsExist(err) {
  263. return nil, err
  264. }
  265. g, err := NewGraph(path.Join(root, "graph"))
  266. if err != nil {
  267. return nil, err
  268. }
  269. repositories, err := NewTagStore(path.Join(root, "repositories"), g)
  270. if err != nil {
  271. return nil, fmt.Errorf("Couldn't create Tag store: %s", err)
  272. }
  273. if NetworkBridgeIface == "" {
  274. NetworkBridgeIface = DefaultNetworkBridge
  275. }
  276. netManager, err := newNetworkManager(NetworkBridgeIface)
  277. if err != nil {
  278. return nil, err
  279. }
  280. authConfig, err := auth.LoadConfig(root)
  281. if err != nil && authConfig == nil {
  282. // If the auth file does not exist, keep going
  283. return nil, err
  284. }
  285. runtime := &Runtime{
  286. root: root,
  287. repository: runtimeRepo,
  288. containers: list.New(),
  289. networkManager: netManager,
  290. graph: g,
  291. repositories: repositories,
  292. authConfig: authConfig,
  293. idIndex: NewTruncIndex(),
  294. }
  295. if err := runtime.restore(); err != nil {
  296. return nil, err
  297. }
  298. return runtime, nil
  299. }
  300. type History []*Container
  301. func (history *History) Len() int {
  302. return len(*history)
  303. }
  304. func (history *History) Less(i, j int) bool {
  305. containers := *history
  306. return containers[j].When().Before(containers[i].When())
  307. }
  308. func (history *History) Swap(i, j int) {
  309. containers := *history
  310. tmp := containers[i]
  311. containers[i] = containers[j]
  312. containers[j] = tmp
  313. }
  314. func (history *History) Add(container *Container) {
  315. *history = append(*history, container)
  316. sort.Sort(history)
  317. }