graph.go 8.7 KB

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