graph.go 11 KB

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