graph.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. package docker
  2. import (
  3. "fmt"
  4. "github.com/dotcloud/docker/utils"
  5. "io"
  6. "io/ioutil"
  7. "os"
  8. "path"
  9. "path/filepath"
  10. "strings"
  11. "time"
  12. )
  13. // A Graph is a store for versioned filesystem images and the relationship between them.
  14. type Graph struct {
  15. Root string
  16. idIndex *utils.TruncIndex
  17. }
  18. // NewGraph instantiates a new graph at the given root path in the filesystem.
  19. // `root` will be created if it doesn't exist.
  20. func NewGraph(root string) (*Graph, error) {
  21. abspath, err := filepath.Abs(root)
  22. if err != nil {
  23. return nil, err
  24. }
  25. // Create the root directory if it doesn't exists
  26. if err := os.MkdirAll(root, 0700); err != nil && !os.IsExist(err) {
  27. return nil, err
  28. }
  29. graph := &Graph{
  30. Root: abspath,
  31. idIndex: utils.NewTruncIndex(),
  32. }
  33. if err := graph.restore(); err != nil {
  34. return nil, err
  35. }
  36. return graph, nil
  37. }
  38. func (graph *Graph) restore() error {
  39. dir, err := ioutil.ReadDir(graph.Root)
  40. if err != nil {
  41. return err
  42. }
  43. for _, v := range dir {
  44. id := v.Name()
  45. graph.idIndex.Add(id)
  46. }
  47. return nil
  48. }
  49. // FIXME: Implement error subclass instead of looking at the error text
  50. // Note: This is the way golang implements os.IsNotExists on Plan9
  51. func (graph *Graph) IsNotExist(err error) bool {
  52. return err != nil && (strings.Contains(err.Error(), "does not exist") || strings.Contains(err.Error(), "No such"))
  53. }
  54. // Exists returns true if an image is registered at the given id.
  55. // If the image doesn't exist or if an error is encountered, false is returned.
  56. func (graph *Graph) Exists(id string) bool {
  57. if _, err := graph.Get(id); err != nil {
  58. return false
  59. }
  60. return true
  61. }
  62. // Get returns the image with the given id, or an error if the image doesn't exist.
  63. func (graph *Graph) Get(name string) (*Image, error) {
  64. id, err := graph.idIndex.Get(name)
  65. if err != nil {
  66. return nil, err
  67. }
  68. // FIXME: return nil when the image doesn't exist, instead of an error
  69. img, err := LoadImage(graph.imageRoot(id))
  70. if err != nil {
  71. return nil, err
  72. }
  73. if img.ID != id {
  74. return nil, fmt.Errorf("Image stored at '%s' has wrong id '%s'", id, img.ID)
  75. }
  76. img.graph = graph
  77. if img.Size == 0 {
  78. root, err := img.root()
  79. if err != nil {
  80. return nil, err
  81. }
  82. if err := StoreSize(img, root); err != nil {
  83. return nil, err
  84. }
  85. }
  86. return img, nil
  87. }
  88. // Create creates a new image and registers it in the graph.
  89. func (graph *Graph) Create(layerData Archive, container *Container, comment, author string, config *Config) (*Image, error) {
  90. img := &Image{
  91. ID: GenerateID(),
  92. Comment: comment,
  93. Created: time.Now(),
  94. DockerVersion: VERSION,
  95. Author: author,
  96. Config: config,
  97. Architecture: "x86_64",
  98. }
  99. if container != nil {
  100. img.Parent = container.Image
  101. img.Container = container.ID
  102. img.ContainerConfig = *container.Config
  103. }
  104. if err := graph.Register(nil, layerData, layerData != nil, img); err != nil {
  105. return nil, err
  106. }
  107. return img, nil
  108. }
  109. // Register imports a pre-existing image into the graph.
  110. // FIXME: pass img as first argument
  111. func (graph *Graph) Register(jsonData []byte, layerData Archive, store bool, img *Image) error {
  112. if err := ValidateID(img.ID); err != nil {
  113. return err
  114. }
  115. // (This is a convenience to save time. Race conditions are taken care of by os.Rename)
  116. if graph.Exists(img.ID) {
  117. return fmt.Errorf("Image %s already exists", img.ID)
  118. }
  119. tmp, err := graph.Mktemp("")
  120. defer os.RemoveAll(tmp)
  121. if err != nil {
  122. return fmt.Errorf("Mktemp failed: %s", err)
  123. }
  124. if err := StoreImage(img, jsonData, layerData, tmp, store); err != nil {
  125. return err
  126. }
  127. // Commit
  128. if err := os.Rename(tmp, graph.imageRoot(img.ID)); err != nil {
  129. return err
  130. }
  131. img.graph = graph
  132. graph.idIndex.Add(img.ID)
  133. return nil
  134. }
  135. // TempLayerArchive creates a temporary archive of the given image's filesystem layer.
  136. // The archive is stored on disk and will be automatically deleted as soon as has been read.
  137. // If output is not nil, a human-readable progress bar will be written to it.
  138. // FIXME: does this belong in Graph? How about MktempFile, let the caller use it for archives?
  139. func (graph *Graph) TempLayerArchive(id string, compression Compression, sf *utils.StreamFormatter, output io.Writer) (*TempArchive, error) {
  140. image, err := graph.Get(id)
  141. if err != nil {
  142. return nil, err
  143. }
  144. tmp, err := graph.tmp()
  145. if err != nil {
  146. return nil, err
  147. }
  148. archive, err := image.TarLayer(compression)
  149. if err != nil {
  150. return nil, err
  151. }
  152. return NewTempArchive(utils.ProgressReader(ioutil.NopCloser(archive), 0, output, sf.FormatProgress("Buffering to disk", "%v/%v (%v)"), sf), tmp.Root)
  153. }
  154. // Mktemp creates a temporary sub-directory inside the graph's filesystem.
  155. func (graph *Graph) Mktemp(id string) (string, error) {
  156. if id == "" {
  157. id = GenerateID()
  158. }
  159. tmp, err := graph.tmp()
  160. if err != nil {
  161. return "", fmt.Errorf("Couldn't create temp: %s", err)
  162. }
  163. if tmp.Exists(id) {
  164. return "", fmt.Errorf("Image %s already exists", id)
  165. }
  166. return tmp.imageRoot(id), nil
  167. }
  168. func (graph *Graph) tmp() (*Graph, error) {
  169. return NewGraph(path.Join(graph.Root, ":tmp:"))
  170. }
  171. // Check if given error is "not empty".
  172. // Note: this is the way golang does it internally with os.IsNotExists.
  173. func isNotEmpty(err error) bool {
  174. switch pe := err.(type) {
  175. case nil:
  176. return false
  177. case *os.PathError:
  178. err = pe.Err
  179. case *os.LinkError:
  180. err = pe.Err
  181. }
  182. return strings.Contains(err.Error(), " not empty")
  183. }
  184. // Delete atomically removes an image from the graph.
  185. func (graph *Graph) Delete(name string) error {
  186. id, err := graph.idIndex.Get(name)
  187. if err != nil {
  188. return err
  189. }
  190. tmp, err := graph.Mktemp("")
  191. if err != nil {
  192. return err
  193. }
  194. graph.idIndex.Delete(id)
  195. err = os.Rename(graph.imageRoot(id), tmp)
  196. if err != nil {
  197. return err
  198. }
  199. return os.RemoveAll(tmp)
  200. }
  201. // Map returns a list of all images in the graph, addressable by ID.
  202. func (graph *Graph) Map() (map[string]*Image, error) {
  203. // FIXME: this should replace All()
  204. all, err := graph.All()
  205. if err != nil {
  206. return nil, err
  207. }
  208. images := make(map[string]*Image, len(all))
  209. for _, image := range all {
  210. images[image.ID] = image
  211. }
  212. return images, nil
  213. }
  214. // All returns a list of all images in the graph.
  215. func (graph *Graph) All() ([]*Image, error) {
  216. var images []*Image
  217. err := graph.WalkAll(func(image *Image) {
  218. images = append(images, image)
  219. })
  220. return images, err
  221. }
  222. // WalkAll iterates over each image in the graph, and passes it to a handler.
  223. // The walking order is undetermined.
  224. func (graph *Graph) WalkAll(handler func(*Image)) error {
  225. files, err := ioutil.ReadDir(graph.Root)
  226. if err != nil {
  227. return err
  228. }
  229. for _, st := range files {
  230. if img, err := graph.Get(st.Name()); err != nil {
  231. // Skip image
  232. continue
  233. } else if handler != nil {
  234. handler(img)
  235. }
  236. }
  237. return nil
  238. }
  239. // ByParent returns a lookup table of images by their parent.
  240. // If an image of id ID has 3 children images, then the value for key ID
  241. // will be a list of 3 images.
  242. // If an image has no children, it will not have an entry in the table.
  243. func (graph *Graph) ByParent() (map[string][]*Image, error) {
  244. byParent := make(map[string][]*Image)
  245. err := graph.WalkAll(func(image *Image) {
  246. parent, err := graph.Get(image.Parent)
  247. if err != nil {
  248. return
  249. }
  250. if children, exists := byParent[parent.ID]; exists {
  251. byParent[parent.ID] = []*Image{image}
  252. } else {
  253. byParent[parent.ID] = append(children, image)
  254. }
  255. })
  256. return byParent, err
  257. }
  258. // Heads returns all heads in the graph, keyed by id.
  259. // A head is an image which is not the parent of another image in the graph.
  260. func (graph *Graph) Heads() (map[string]*Image, error) {
  261. heads := make(map[string]*Image)
  262. byParent, err := graph.ByParent()
  263. if err != nil {
  264. return nil, err
  265. }
  266. err = graph.WalkAll(func(image *Image) {
  267. // If it's not in the byParent lookup table, then
  268. // it's not a parent -> so it's a head!
  269. if _, exists := byParent[image.ID]; !exists {
  270. heads[image.ID] = image
  271. }
  272. })
  273. return heads, err
  274. }
  275. func (graph *Graph) imageRoot(id string) string {
  276. return path.Join(graph.Root, id)
  277. }