graph.go 6.5 KB

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