graph.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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, 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, 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); 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, true), 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. // getDockerInitLayer returns the path of a layer containing a mountpoint suitable
  169. // for bind-mounting dockerinit into the container. The mountpoint is simply an
  170. // empty file at /.dockerinit
  171. //
  172. // This extra layer is used by all containers as the top-most ro layer. It protects
  173. // the container from unwanted side-effects on the rw layer.
  174. func (graph *Graph) getDockerInitLayer() (string, error) {
  175. tmp, err := graph.tmp()
  176. if err != nil {
  177. return "", err
  178. }
  179. initLayer := tmp.imageRoot("_dockerinit")
  180. if err := os.Mkdir(initLayer, 0755); err != nil && !os.IsExist(err) {
  181. // If directory already existed, keep going.
  182. // For all other errors, abort.
  183. return "", err
  184. }
  185. for pth, typ := range map[string]string{
  186. "/dev/pts": "dir",
  187. "/dev/shm": "dir",
  188. "/proc": "dir",
  189. "/sys": "dir",
  190. "/.dockerinit": "file",
  191. "/etc/resolv.conf": "file",
  192. "/etc/hosts": "file",
  193. "/etc/hostname": "file",
  194. // "var/run": "dir",
  195. // "var/lock": "dir",
  196. } {
  197. if _, err := os.Stat(path.Join(initLayer, pth)); err != nil {
  198. if os.IsNotExist(err) {
  199. switch typ {
  200. case "dir":
  201. if err := os.MkdirAll(path.Join(initLayer, pth), 0755); err != nil {
  202. return "", err
  203. }
  204. case "file":
  205. if err := os.MkdirAll(path.Join(initLayer, path.Dir(pth)), 0755); err != nil {
  206. return "", err
  207. }
  208. if f, err := os.OpenFile(path.Join(initLayer, pth), os.O_CREATE, 0755); err != nil {
  209. return "", err
  210. } else {
  211. f.Close()
  212. }
  213. }
  214. } else {
  215. return "", err
  216. }
  217. }
  218. }
  219. // Layer is ready to use, if it wasn't before.
  220. return initLayer, nil
  221. }
  222. func (graph *Graph) tmp() (*Graph, error) {
  223. // Changed to _tmp from :tmp:, because it messed with ":" separators in aufs branch syntax...
  224. return NewGraph(path.Join(graph.Root, "_tmp"))
  225. }
  226. // Check if given error is "not empty".
  227. // Note: this is the way golang does it internally with os.IsNotExists.
  228. func isNotEmpty(err error) bool {
  229. switch pe := err.(type) {
  230. case nil:
  231. return false
  232. case *os.PathError:
  233. err = pe.Err
  234. case *os.LinkError:
  235. err = pe.Err
  236. }
  237. return strings.Contains(err.Error(), " not empty")
  238. }
  239. // Delete atomically removes an image from the graph.
  240. func (graph *Graph) Delete(name string) error {
  241. id, err := graph.idIndex.Get(name)
  242. if err != nil {
  243. return err
  244. }
  245. tmp, err := graph.Mktemp("")
  246. if err != nil {
  247. return err
  248. }
  249. graph.idIndex.Delete(id)
  250. err = os.Rename(graph.imageRoot(id), tmp)
  251. if err != nil {
  252. return err
  253. }
  254. return os.RemoveAll(tmp)
  255. }
  256. // Map returns a list of all images in the graph, addressable by ID.
  257. func (graph *Graph) Map() (map[string]*Image, error) {
  258. images := make(map[string]*Image)
  259. err := graph.walkAll(func(image *Image) {
  260. images[image.ID] = image
  261. })
  262. if err != nil {
  263. return nil, err
  264. }
  265. return images, nil
  266. }
  267. // walkAll iterates over each image in the graph, and passes it to a handler.
  268. // The walking order is undetermined.
  269. func (graph *Graph) walkAll(handler func(*Image)) error {
  270. files, err := ioutil.ReadDir(graph.Root)
  271. if err != nil {
  272. return err
  273. }
  274. for _, st := range files {
  275. if img, err := graph.Get(st.Name()); err != nil {
  276. // Skip image
  277. continue
  278. } else if handler != nil {
  279. handler(img)
  280. }
  281. }
  282. return nil
  283. }
  284. // ByParent returns a lookup table of images by their parent.
  285. // If an image of id ID has 3 children images, then the value for key ID
  286. // will be a list of 3 images.
  287. // If an image has no children, it will not have an entry in the table.
  288. func (graph *Graph) ByParent() (map[string][]*Image, error) {
  289. byParent := make(map[string][]*Image)
  290. err := graph.walkAll(func(image *Image) {
  291. parent, err := graph.Get(image.Parent)
  292. if err != nil {
  293. return
  294. }
  295. if children, exists := byParent[parent.ID]; exists {
  296. byParent[parent.ID] = append(children, image)
  297. } else {
  298. byParent[parent.ID] = []*Image{image}
  299. }
  300. })
  301. return byParent, err
  302. }
  303. // Heads returns all heads in the graph, keyed by id.
  304. // A head is an image which is not the parent of another image in the graph.
  305. func (graph *Graph) Heads() (map[string]*Image, error) {
  306. heads := make(map[string]*Image)
  307. byParent, err := graph.ByParent()
  308. if err != nil {
  309. return nil, err
  310. }
  311. err = graph.walkAll(func(image *Image) {
  312. // If it's not in the byParent lookup table, then
  313. // it's not a parent -> so it's a head!
  314. if _, exists := byParent[image.ID]; !exists {
  315. heads[image.ID] = image
  316. }
  317. })
  318. return heads, err
  319. }
  320. func (graph *Graph) imageRoot(id string) string {
  321. return path.Join(graph.Root, id)
  322. }