graph.go 12 KB

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