graph.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. package docker
  2. import (
  3. "fmt"
  4. "github.com/dotcloud/docker/archive"
  5. "github.com/dotcloud/docker/graphdriver"
  6. "github.com/dotcloud/docker/utils"
  7. "io"
  8. "io/ioutil"
  9. "os"
  10. "path"
  11. "path/filepath"
  12. "runtime"
  13. "strings"
  14. "syscall"
  15. "time"
  16. )
  17. // A Graph is a store for versioned filesystem images and the relationship between them.
  18. type Graph struct {
  19. Root string
  20. idIndex *utils.TruncIndex
  21. driver graphdriver.Driver
  22. }
  23. // NewGraph instantiates a new graph at the given root path in the filesystem.
  24. // `root` will be created if it doesn't exist.
  25. func NewGraph(root string, driver graphdriver.Driver) (*Graph, error) {
  26. abspath, err := filepath.Abs(root)
  27. if err != nil {
  28. return nil, err
  29. }
  30. // Create the root directory if it doesn't exists
  31. if err := os.MkdirAll(root, 0700); err != nil && !os.IsExist(err) {
  32. return nil, err
  33. }
  34. graph := &Graph{
  35. Root: abspath,
  36. idIndex: utils.NewTruncIndex(),
  37. driver: driver,
  38. }
  39. if err := graph.restore(); err != nil {
  40. return nil, err
  41. }
  42. return graph, nil
  43. }
  44. func (graph *Graph) restore() error {
  45. dir, err := ioutil.ReadDir(graph.Root)
  46. if err != nil {
  47. return err
  48. }
  49. for _, v := range dir {
  50. id := v.Name()
  51. if graph.driver.Exists(id) {
  52. graph.idIndex.Add(id)
  53. }
  54. }
  55. utils.Debugf("Restored %d elements", len(dir))
  56. return nil
  57. }
  58. // FIXME: Implement error subclass instead of looking at the error text
  59. // Note: This is the way golang implements os.IsNotExists on Plan9
  60. func (graph *Graph) IsNotExist(err error) bool {
  61. return err != nil && (strings.Contains(err.Error(), "does not exist") || strings.Contains(err.Error(), "No such"))
  62. }
  63. // Exists returns true if an image is registered at the given id.
  64. // If the image doesn't exist or if an error is encountered, false is returned.
  65. func (graph *Graph) Exists(id string) bool {
  66. if _, err := graph.Get(id); err != nil {
  67. return false
  68. }
  69. return true
  70. }
  71. // Get returns the image with the given id, or an error if the image doesn't exist.
  72. func (graph *Graph) Get(name string) (*Image, error) {
  73. id, err := graph.idIndex.Get(name)
  74. if err != nil {
  75. return nil, err
  76. }
  77. // FIXME: return nil when the image doesn't exist, instead of an error
  78. img, err := LoadImage(graph.imageRoot(id))
  79. if err != nil {
  80. return nil, err
  81. }
  82. if img.ID != id {
  83. return nil, fmt.Errorf("Image stored at '%s' has wrong id '%s'", id, img.ID)
  84. }
  85. img.graph = graph
  86. if img.Size < 0 {
  87. rootfs, err := graph.driver.Get(img.ID)
  88. if err != nil {
  89. return nil, fmt.Errorf("Driver %s failed to get image rootfs %s: %s", graph.driver, img.ID, err)
  90. }
  91. var size int64
  92. if img.Parent == "" {
  93. if size, err = utils.TreeSize(rootfs); err != nil {
  94. return nil, err
  95. }
  96. } else {
  97. parentFs, err := graph.driver.Get(img.Parent)
  98. if err != nil {
  99. return nil, err
  100. }
  101. changes, err := archive.ChangesDirs(rootfs, parentFs)
  102. if err != nil {
  103. return nil, err
  104. }
  105. size = archive.ChangesSize(rootfs, changes)
  106. }
  107. img.Size = size
  108. if err := img.SaveSize(graph.imageRoot(id)); err != nil {
  109. return nil, err
  110. }
  111. }
  112. return img, nil
  113. }
  114. // Create creates a new image and registers it in the graph.
  115. func (graph *Graph) Create(layerData archive.Archive, container *Container, comment, author string, config *Config) (*Image, error) {
  116. img := &Image{
  117. ID: GenerateID(),
  118. Comment: comment,
  119. Created: time.Now().UTC(),
  120. DockerVersion: VERSION,
  121. Author: author,
  122. Config: config,
  123. Architecture: runtime.GOARCH,
  124. OS: runtime.GOOS,
  125. }
  126. if container != nil {
  127. img.Parent = container.Image
  128. img.Container = container.ID
  129. img.ContainerConfig = *container.Config
  130. }
  131. if err := graph.Register(nil, layerData, img); err != nil {
  132. return nil, err
  133. }
  134. return img, nil
  135. }
  136. // Register imports a pre-existing image into the graph.
  137. // FIXME: pass img as first argument
  138. func (graph *Graph) Register(jsonData []byte, layerData archive.Archive, img *Image) (err error) {
  139. defer func() {
  140. // If any error occurs, remove the new dir from the driver.
  141. // Don't check for errors since the dir might not have been created.
  142. // FIXME: this leaves a possible race condition.
  143. if err != nil {
  144. graph.driver.Remove(img.ID)
  145. }
  146. }()
  147. if err := ValidateID(img.ID); err != nil {
  148. return err
  149. }
  150. // (This is a convenience to save time. Race conditions are taken care of by os.Rename)
  151. if graph.Exists(img.ID) {
  152. return fmt.Errorf("Image %s already exists", img.ID)
  153. }
  154. // Ensure that the image root does not exist on the filesystem
  155. // when it is not registered in the graph.
  156. // This is common when you switch from one graph driver to another
  157. if err := os.RemoveAll(graph.imageRoot(img.ID)); err != nil && !os.IsNotExist(err) {
  158. return err
  159. }
  160. // If the driver has this ID but the graph doesn't, remove it from the driver to start fresh.
  161. // (the graph is the source of truth).
  162. // Ignore errors, since we don't know if the driver correctly returns ErrNotExist.
  163. // (FIXME: make that mandatory for drivers).
  164. graph.driver.Remove(img.ID)
  165. tmp, err := graph.Mktemp("")
  166. defer os.RemoveAll(tmp)
  167. if err != nil {
  168. return fmt.Errorf("Mktemp failed: %s", err)
  169. }
  170. // Create root filesystem in the driver
  171. if err := graph.driver.Create(img.ID, img.Parent); err != nil {
  172. return fmt.Errorf("Driver %s failed to create image rootfs %s: %s", graph.driver, img.ID, err)
  173. }
  174. // Mount the root filesystem so we can apply the diff/layer
  175. rootfs, err := graph.driver.Get(img.ID)
  176. if err != nil {
  177. return fmt.Errorf("Driver %s failed to get image rootfs %s: %s", graph.driver, img.ID, err)
  178. }
  179. img.graph = graph
  180. if err := StoreImage(img, jsonData, layerData, tmp, rootfs); err != nil {
  181. return err
  182. }
  183. // Commit
  184. if err := os.Rename(tmp, graph.imageRoot(img.ID)); err != nil {
  185. return err
  186. }
  187. graph.idIndex.Add(img.ID)
  188. return nil
  189. }
  190. // TempLayerArchive creates a temporary archive of the given image's filesystem layer.
  191. // The archive is stored on disk and will be automatically deleted as soon as has been read.
  192. // If output is not nil, a human-readable progress bar will be written to it.
  193. // FIXME: does this belong in Graph? How about MktempFile, let the caller use it for archives?
  194. func (graph *Graph) TempLayerArchive(id string, compression archive.Compression, sf *utils.StreamFormatter, output io.Writer) (*archive.TempArchive, error) {
  195. image, err := graph.Get(id)
  196. if err != nil {
  197. return nil, err
  198. }
  199. tmp, err := graph.Mktemp("")
  200. if err != nil {
  201. return nil, err
  202. }
  203. a, err := image.TarLayer()
  204. if err != nil {
  205. return nil, err
  206. }
  207. return archive.NewTempArchive(utils.ProgressReader(ioutil.NopCloser(a), 0, output, sf, false, utils.TruncateID(id), "Buffering to disk"), tmp)
  208. }
  209. // Mktemp creates a temporary sub-directory inside the graph's filesystem.
  210. func (graph *Graph) Mktemp(id string) (string, error) {
  211. dir := path.Join(graph.Root, "_tmp", GenerateID())
  212. if err := os.MkdirAll(dir, 0700); err != nil {
  213. return "", err
  214. }
  215. return dir, nil
  216. }
  217. // setupInitLayer populates a directory with mountpoints suitable
  218. // for bind-mounting dockerinit into the container. The mountpoint is simply an
  219. // empty file at /.dockerinit
  220. //
  221. // This extra layer is used by all containers as the top-most ro layer. It protects
  222. // the container from unwanted side-effects on the rw layer.
  223. func setupInitLayer(initLayer string) error {
  224. for pth, typ := range map[string]string{
  225. "/dev/pts": "dir",
  226. "/dev/shm": "dir",
  227. "/proc": "dir",
  228. "/sys": "dir",
  229. "/.dockerinit": "file",
  230. "/.dockerenv": "file",
  231. "/etc/resolv.conf": "file",
  232. "/etc/hosts": "file",
  233. "/etc/hostname": "file",
  234. // "var/run": "dir",
  235. // "var/lock": "dir",
  236. } {
  237. parts := strings.Split(pth, "/")
  238. prev := "/"
  239. for _, p := range parts[1:] {
  240. prev = path.Join(prev, p)
  241. syscall.Unlink(path.Join(initLayer, prev))
  242. }
  243. if _, err := os.Stat(path.Join(initLayer, pth)); err != nil {
  244. if os.IsNotExist(err) {
  245. switch typ {
  246. case "dir":
  247. if err := os.MkdirAll(path.Join(initLayer, pth), 0755); err != nil {
  248. return err
  249. }
  250. case "file":
  251. if err := os.MkdirAll(path.Join(initLayer, path.Dir(pth)), 0755); err != nil {
  252. return err
  253. }
  254. f, err := os.OpenFile(path.Join(initLayer, pth), os.O_CREATE, 0755)
  255. if err != nil {
  256. return err
  257. }
  258. f.Close()
  259. }
  260. } else {
  261. return err
  262. }
  263. }
  264. }
  265. // Layer is ready to use, if it wasn't before.
  266. return nil
  267. }
  268. // Check if given error is "not empty".
  269. // Note: this is the way golang does it internally with os.IsNotExists.
  270. func isNotEmpty(err error) bool {
  271. switch pe := err.(type) {
  272. case nil:
  273. return false
  274. case *os.PathError:
  275. err = pe.Err
  276. case *os.LinkError:
  277. err = pe.Err
  278. }
  279. return strings.Contains(err.Error(), " not empty")
  280. }
  281. // Delete atomically removes an image from the graph.
  282. func (graph *Graph) Delete(name string) error {
  283. id, err := graph.idIndex.Get(name)
  284. if err != nil {
  285. return err
  286. }
  287. tmp, err := graph.Mktemp("")
  288. if err != nil {
  289. return err
  290. }
  291. graph.idIndex.Delete(id)
  292. err = os.Rename(graph.imageRoot(id), tmp)
  293. if err != nil {
  294. return err
  295. }
  296. // Remove rootfs data from the driver
  297. graph.driver.Remove(id)
  298. // Remove the trashed image directory
  299. return os.RemoveAll(tmp)
  300. }
  301. // Map returns a list of all images in the graph, addressable by ID.
  302. func (graph *Graph) Map() (map[string]*Image, error) {
  303. images := make(map[string]*Image)
  304. err := graph.walkAll(func(image *Image) {
  305. images[image.ID] = image
  306. })
  307. if err != nil {
  308. return nil, err
  309. }
  310. return images, nil
  311. }
  312. // walkAll iterates over each image in the graph, and passes it to a handler.
  313. // The walking order is undetermined.
  314. func (graph *Graph) walkAll(handler func(*Image)) error {
  315. files, err := ioutil.ReadDir(graph.Root)
  316. if err != nil {
  317. return err
  318. }
  319. for _, st := range files {
  320. if img, err := graph.Get(st.Name()); err != nil {
  321. // Skip image
  322. continue
  323. } else if handler != nil {
  324. handler(img)
  325. }
  326. }
  327. return nil
  328. }
  329. // ByParent returns a lookup table of images by their parent.
  330. // If an image of id ID has 3 children images, then the value for key ID
  331. // will be a list of 3 images.
  332. // If an image has no children, it will not have an entry in the table.
  333. func (graph *Graph) ByParent() (map[string][]*Image, error) {
  334. byParent := make(map[string][]*Image)
  335. err := graph.walkAll(func(image *Image) {
  336. parent, err := graph.Get(image.Parent)
  337. if err != nil {
  338. return
  339. }
  340. if children, exists := byParent[parent.ID]; exists {
  341. byParent[parent.ID] = append(children, image)
  342. } else {
  343. byParent[parent.ID] = []*Image{image}
  344. }
  345. })
  346. return byParent, err
  347. }
  348. // Heads returns all heads in the graph, keyed by id.
  349. // A head is an image which is not the parent of another image in the graph.
  350. func (graph *Graph) Heads() (map[string]*Image, error) {
  351. heads := make(map[string]*Image)
  352. byParent, err := graph.ByParent()
  353. if err != nil {
  354. return nil, err
  355. }
  356. err = graph.walkAll(func(image *Image) {
  357. // If it's not in the byParent lookup table, then
  358. // it's not a parent -> so it's a head!
  359. if _, exists := byParent[image.ID]; !exists {
  360. heads[image.ID] = image
  361. }
  362. })
  363. return heads, err
  364. }
  365. func (graph *Graph) imageRoot(id string) string {
  366. return path.Join(graph.Root, id)
  367. }
  368. func (graph *Graph) Driver() graphdriver.Driver {
  369. return graph.driver
  370. }