runtime.go 7.7 KB

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