graph.go 11 KB

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