changes.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. package archive
  2. import (
  3. "archive/tar"
  4. "bytes"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "os"
  9. "path/filepath"
  10. "sort"
  11. "strings"
  12. "syscall"
  13. "time"
  14. "github.com/Sirupsen/logrus"
  15. "github.com/docker/docker/pkg/idtools"
  16. "github.com/docker/docker/pkg/pools"
  17. "github.com/docker/docker/pkg/system"
  18. )
  19. // ChangeType represents the change type.
  20. type ChangeType int
  21. const (
  22. // ChangeModify represents the modify operation.
  23. ChangeModify = iota
  24. // ChangeAdd represents the add operation.
  25. ChangeAdd
  26. // ChangeDelete represents the delete operation.
  27. ChangeDelete
  28. )
  29. func (c ChangeType) String() string {
  30. switch c {
  31. case ChangeModify:
  32. return "C"
  33. case ChangeAdd:
  34. return "A"
  35. case ChangeDelete:
  36. return "D"
  37. }
  38. return ""
  39. }
  40. // Change represents a change, it wraps the change type and path.
  41. // It describes changes of the files in the path respect to the
  42. // parent layers. The change could be modify, add, delete.
  43. // This is used for layer diff.
  44. type Change struct {
  45. Path string
  46. Kind ChangeType
  47. }
  48. func (change *Change) String() string {
  49. return fmt.Sprintf("%s %s", change.Kind, change.Path)
  50. }
  51. // for sort.Sort
  52. type changesByPath []Change
  53. func (c changesByPath) Less(i, j int) bool { return c[i].Path < c[j].Path }
  54. func (c changesByPath) Len() int { return len(c) }
  55. func (c changesByPath) Swap(i, j int) { c[j], c[i] = c[i], c[j] }
  56. // Gnu tar and the go tar writer don't have sub-second mtime
  57. // precision, which is problematic when we apply changes via tar
  58. // files, we handle this by comparing for exact times, *or* same
  59. // second count and either a or b having exactly 0 nanoseconds
  60. func sameFsTime(a, b time.Time) bool {
  61. return a == b ||
  62. (a.Unix() == b.Unix() &&
  63. (a.Nanosecond() == 0 || b.Nanosecond() == 0))
  64. }
  65. func sameFsTimeSpec(a, b syscall.Timespec) bool {
  66. return a.Sec == b.Sec &&
  67. (a.Nsec == b.Nsec || a.Nsec == 0 || b.Nsec == 0)
  68. }
  69. // Changes walks the path rw and determines changes for the files in the path,
  70. // with respect to the parent layers
  71. func Changes(layers []string, rw string) ([]Change, error) {
  72. return changes(layers, rw, aufsDeletedFile, aufsMetadataSkip)
  73. }
  74. func aufsMetadataSkip(path string) (skip bool, err error) {
  75. skip, err = filepath.Match(string(os.PathSeparator)+WhiteoutMetaPrefix+"*", path)
  76. if err != nil {
  77. skip = true
  78. }
  79. return
  80. }
  81. func aufsDeletedFile(root, path string, fi os.FileInfo) (string, error) {
  82. f := filepath.Base(path)
  83. // If there is a whiteout, then the file was removed
  84. if strings.HasPrefix(f, WhiteoutPrefix) {
  85. originalFile := f[len(WhiteoutPrefix):]
  86. return filepath.Join(filepath.Dir(path), originalFile), nil
  87. }
  88. return "", nil
  89. }
  90. type skipChange func(string) (bool, error)
  91. type deleteChange func(string, string, os.FileInfo) (string, error)
  92. func changes(layers []string, rw string, dc deleteChange, sc skipChange) ([]Change, error) {
  93. var (
  94. changes []Change
  95. changedDirs = make(map[string]struct{})
  96. )
  97. err := filepath.Walk(rw, func(path string, f os.FileInfo, err error) error {
  98. if err != nil {
  99. return err
  100. }
  101. // Rebase path
  102. path, err = filepath.Rel(rw, path)
  103. if err != nil {
  104. return err
  105. }
  106. // As this runs on the daemon side, file paths are OS specific.
  107. path = filepath.Join(string(os.PathSeparator), path)
  108. // Skip root
  109. if path == string(os.PathSeparator) {
  110. return nil
  111. }
  112. if sc != nil {
  113. if skip, err := sc(path); skip {
  114. return err
  115. }
  116. }
  117. change := Change{
  118. Path: path,
  119. }
  120. deletedFile, err := dc(rw, path, f)
  121. if err != nil {
  122. return err
  123. }
  124. // Find out what kind of modification happened
  125. if deletedFile != "" {
  126. change.Path = deletedFile
  127. change.Kind = ChangeDelete
  128. } else {
  129. // Otherwise, the file was added
  130. change.Kind = ChangeAdd
  131. // ...Unless it already existed in a top layer, in which case, it's a modification
  132. for _, layer := range layers {
  133. stat, err := os.Stat(filepath.Join(layer, path))
  134. if err != nil && !os.IsNotExist(err) {
  135. return err
  136. }
  137. if err == nil {
  138. // The file existed in the top layer, so that's a modification
  139. // However, if it's a directory, maybe it wasn't actually modified.
  140. // If you modify /foo/bar/baz, then /foo will be part of the changed files only because it's the parent of bar
  141. if stat.IsDir() && f.IsDir() {
  142. if f.Size() == stat.Size() && f.Mode() == stat.Mode() && sameFsTime(f.ModTime(), stat.ModTime()) {
  143. // Both directories are the same, don't record the change
  144. return nil
  145. }
  146. }
  147. change.Kind = ChangeModify
  148. break
  149. }
  150. }
  151. }
  152. // If /foo/bar/file.txt is modified, then /foo/bar must be part of the changed files.
  153. // This block is here to ensure the change is recorded even if the
  154. // modify time, mode and size of the parent directory in the rw and ro layers are all equal.
  155. // Check https://github.com/docker/docker/pull/13590 for details.
  156. if f.IsDir() {
  157. changedDirs[path] = struct{}{}
  158. }
  159. if change.Kind == ChangeAdd || change.Kind == ChangeDelete {
  160. parent := filepath.Dir(path)
  161. if _, ok := changedDirs[parent]; !ok && parent != "/" {
  162. changes = append(changes, Change{Path: parent, Kind: ChangeModify})
  163. changedDirs[parent] = struct{}{}
  164. }
  165. }
  166. // Record change
  167. changes = append(changes, change)
  168. return nil
  169. })
  170. if err != nil && !os.IsNotExist(err) {
  171. return nil, err
  172. }
  173. return changes, nil
  174. }
  175. // FileInfo describes the information of a file.
  176. type FileInfo struct {
  177. parent *FileInfo
  178. name string
  179. stat *system.StatT
  180. children map[string]*FileInfo
  181. capability []byte
  182. added bool
  183. }
  184. // LookUp looks up the file information of a file.
  185. func (info *FileInfo) LookUp(path string) *FileInfo {
  186. // As this runs on the daemon side, file paths are OS specific.
  187. parent := info
  188. if path == string(os.PathSeparator) {
  189. return info
  190. }
  191. pathElements := strings.Split(path, string(os.PathSeparator))
  192. for _, elem := range pathElements {
  193. if elem != "" {
  194. child := parent.children[elem]
  195. if child == nil {
  196. return nil
  197. }
  198. parent = child
  199. }
  200. }
  201. return parent
  202. }
  203. func (info *FileInfo) path() string {
  204. if info.parent == nil {
  205. // As this runs on the daemon side, file paths are OS specific.
  206. return string(os.PathSeparator)
  207. }
  208. return filepath.Join(info.parent.path(), info.name)
  209. }
  210. func (info *FileInfo) addChanges(oldInfo *FileInfo, changes *[]Change) {
  211. sizeAtEntry := len(*changes)
  212. if oldInfo == nil {
  213. // add
  214. change := Change{
  215. Path: info.path(),
  216. Kind: ChangeAdd,
  217. }
  218. *changes = append(*changes, change)
  219. info.added = true
  220. }
  221. // We make a copy so we can modify it to detect additions
  222. // also, we only recurse on the old dir if the new info is a directory
  223. // otherwise any previous delete/change is considered recursive
  224. oldChildren := make(map[string]*FileInfo)
  225. if oldInfo != nil && info.isDir() {
  226. for k, v := range oldInfo.children {
  227. oldChildren[k] = v
  228. }
  229. }
  230. for name, newChild := range info.children {
  231. oldChild := oldChildren[name]
  232. if oldChild != nil {
  233. // change?
  234. oldStat := oldChild.stat
  235. newStat := newChild.stat
  236. // Note: We can't compare inode or ctime or blocksize here, because these change
  237. // when copying a file into a container. However, that is not generally a problem
  238. // because any content change will change mtime, and any status change should
  239. // be visible when actually comparing the stat fields. The only time this
  240. // breaks down is if some code intentionally hides a change by setting
  241. // back mtime
  242. if statDifferent(oldStat, newStat) ||
  243. !bytes.Equal(oldChild.capability, newChild.capability) {
  244. change := Change{
  245. Path: newChild.path(),
  246. Kind: ChangeModify,
  247. }
  248. *changes = append(*changes, change)
  249. newChild.added = true
  250. }
  251. // Remove from copy so we can detect deletions
  252. delete(oldChildren, name)
  253. }
  254. newChild.addChanges(oldChild, changes)
  255. }
  256. for _, oldChild := range oldChildren {
  257. // delete
  258. change := Change{
  259. Path: oldChild.path(),
  260. Kind: ChangeDelete,
  261. }
  262. *changes = append(*changes, change)
  263. }
  264. // If there were changes inside this directory, we need to add it, even if the directory
  265. // itself wasn't changed. This is needed to properly save and restore filesystem permissions.
  266. // As this runs on the daemon side, file paths are OS specific.
  267. if len(*changes) > sizeAtEntry && info.isDir() && !info.added && info.path() != string(os.PathSeparator) {
  268. change := Change{
  269. Path: info.path(),
  270. Kind: ChangeModify,
  271. }
  272. // Let's insert the directory entry before the recently added entries located inside this dir
  273. *changes = append(*changes, change) // just to resize the slice, will be overwritten
  274. copy((*changes)[sizeAtEntry+1:], (*changes)[sizeAtEntry:])
  275. (*changes)[sizeAtEntry] = change
  276. }
  277. }
  278. // Changes add changes to file information.
  279. func (info *FileInfo) Changes(oldInfo *FileInfo) []Change {
  280. var changes []Change
  281. info.addChanges(oldInfo, &changes)
  282. return changes
  283. }
  284. func newRootFileInfo() *FileInfo {
  285. // As this runs on the daemon side, file paths are OS specific.
  286. root := &FileInfo{
  287. name: string(os.PathSeparator),
  288. children: make(map[string]*FileInfo),
  289. }
  290. return root
  291. }
  292. // ChangesDirs compares two directories and generates an array of Change objects describing the changes.
  293. // If oldDir is "", then all files in newDir will be Add-Changes.
  294. func ChangesDirs(newDir, oldDir string) ([]Change, error) {
  295. var (
  296. oldRoot, newRoot *FileInfo
  297. )
  298. if oldDir == "" {
  299. emptyDir, err := ioutil.TempDir("", "empty")
  300. if err != nil {
  301. return nil, err
  302. }
  303. defer os.Remove(emptyDir)
  304. oldDir = emptyDir
  305. }
  306. oldRoot, newRoot, err := collectFileInfoForChanges(oldDir, newDir)
  307. if err != nil {
  308. return nil, err
  309. }
  310. return newRoot.Changes(oldRoot), nil
  311. }
  312. // ChangesSize calculates the size in bytes of the provided changes, based on newDir.
  313. func ChangesSize(newDir string, changes []Change) int64 {
  314. var (
  315. size int64
  316. sf = make(map[uint64]struct{})
  317. )
  318. for _, change := range changes {
  319. if change.Kind == ChangeModify || change.Kind == ChangeAdd {
  320. file := filepath.Join(newDir, change.Path)
  321. fileInfo, err := os.Lstat(file)
  322. if err != nil {
  323. logrus.Errorf("Can not stat %q: %s", file, err)
  324. continue
  325. }
  326. if fileInfo != nil && !fileInfo.IsDir() {
  327. if hasHardlinks(fileInfo) {
  328. inode := getIno(fileInfo)
  329. if _, ok := sf[inode]; !ok {
  330. size += fileInfo.Size()
  331. sf[inode] = struct{}{}
  332. }
  333. } else {
  334. size += fileInfo.Size()
  335. }
  336. }
  337. }
  338. }
  339. return size
  340. }
  341. // ExportChanges produces an Archive from the provided changes, relative to dir.
  342. func ExportChanges(dir string, changes []Change, uidMaps, gidMaps []idtools.IDMap) (io.ReadCloser, error) {
  343. reader, writer := io.Pipe()
  344. go func() {
  345. ta := &tarAppender{
  346. TarWriter: tar.NewWriter(writer),
  347. Buffer: pools.BufioWriter32KPool.Get(nil),
  348. SeenFiles: make(map[uint64]string),
  349. UIDMaps: uidMaps,
  350. GIDMaps: gidMaps,
  351. }
  352. // this buffer is needed for the duration of this piped stream
  353. defer pools.BufioWriter32KPool.Put(ta.Buffer)
  354. sort.Sort(changesByPath(changes))
  355. // In general we log errors here but ignore them because
  356. // during e.g. a diff operation the container can continue
  357. // mutating the filesystem and we can see transient errors
  358. // from this
  359. for _, change := range changes {
  360. if change.Kind == ChangeDelete {
  361. whiteOutDir := filepath.Dir(change.Path)
  362. whiteOutBase := filepath.Base(change.Path)
  363. whiteOut := filepath.Join(whiteOutDir, WhiteoutPrefix+whiteOutBase)
  364. timestamp := time.Now()
  365. hdr := &tar.Header{
  366. Name: whiteOut[1:],
  367. Size: 0,
  368. ModTime: timestamp,
  369. AccessTime: timestamp,
  370. ChangeTime: timestamp,
  371. }
  372. if err := ta.TarWriter.WriteHeader(hdr); err != nil {
  373. logrus.Debugf("Can't write whiteout header: %s", err)
  374. }
  375. } else {
  376. path := filepath.Join(dir, change.Path)
  377. if err := ta.addTarFile(path, change.Path[1:]); err != nil {
  378. logrus.Debugf("Can't add file %s to tar: %s", path, err)
  379. }
  380. }
  381. }
  382. // Make sure to check the error on Close.
  383. if err := ta.TarWriter.Close(); err != nil {
  384. logrus.Debugf("Can't close layer: %s", err)
  385. }
  386. if err := writer.Close(); err != nil {
  387. logrus.Debugf("failed close Changes writer: %s", err)
  388. }
  389. }()
  390. return reader, nil
  391. }