changes.go 12 KB

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