graph.go 11 KB

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