changes.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. package archive // import "github.com/docker/docker/pkg/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/docker/docker/pkg/idtools"
  15. "github.com/docker/docker/pkg/pools"
  16. "github.com/docker/docker/pkg/system"
  17. "github.com/sirupsen/logrus"
  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 skipChange func(string) (bool, error)
  95. type deleteChange func(string, string, os.FileInfo) (string, error)
  96. func changes(layers []string, rw string, dc deleteChange, sc skipChange) ([]Change, error) {
  97. var (
  98. changes []Change
  99. changedDirs = make(map[string]struct{})
  100. )
  101. err := filepath.Walk(rw, func(path string, f os.FileInfo, err error) error {
  102. if err != nil {
  103. return err
  104. }
  105. // Rebase path
  106. path, err = filepath.Rel(rw, path)
  107. if err != nil {
  108. return err
  109. }
  110. // As this runs on the daemon side, file paths are OS specific.
  111. path = filepath.Join(string(os.PathSeparator), path)
  112. // Skip root
  113. if path == string(os.PathSeparator) {
  114. return nil
  115. }
  116. if sc != nil {
  117. if skip, err := sc(path); skip {
  118. return err
  119. }
  120. }
  121. change := Change{
  122. Path: path,
  123. }
  124. deletedFile, err := dc(rw, path, f)
  125. if err != nil {
  126. return err
  127. }
  128. // Find out what kind of modification happened
  129. if deletedFile != "" {
  130. change.Path = deletedFile
  131. change.Kind = ChangeDelete
  132. } else {
  133. // Otherwise, the file was added
  134. change.Kind = ChangeAdd
  135. // ...Unless it already existed in a top layer, in which case, it's a modification
  136. for _, layer := range layers {
  137. stat, err := os.Stat(filepath.Join(layer, path))
  138. if err != nil && !os.IsNotExist(err) {
  139. return err
  140. }
  141. if err == nil {
  142. // The file existed in the top layer, so that's a modification
  143. // However, if it's a directory, maybe it wasn't actually modified.
  144. // If you modify /foo/bar/baz, then /foo will be part of the changed files only because it's the parent of bar
  145. if stat.IsDir() && f.IsDir() {
  146. if f.Size() == stat.Size() && f.Mode() == stat.Mode() && sameFsTime(f.ModTime(), stat.ModTime()) {
  147. // Both directories are the same, don't record the change
  148. return nil
  149. }
  150. }
  151. change.Kind = ChangeModify
  152. break
  153. }
  154. }
  155. }
  156. // If /foo/bar/file.txt is modified, then /foo/bar must be part of the changed files.
  157. // This block is here to ensure the change is recorded even if the
  158. // modify time, mode and size of the parent directory in the rw and ro layers are all equal.
  159. // Check https://github.com/docker/docker/pull/13590 for details.
  160. if f.IsDir() {
  161. changedDirs[path] = struct{}{}
  162. }
  163. if change.Kind == ChangeAdd || change.Kind == ChangeDelete {
  164. parent := filepath.Dir(path)
  165. if _, ok := changedDirs[parent]; !ok && parent != "/" {
  166. changes = append(changes, Change{Path: parent, Kind: ChangeModify})
  167. changedDirs[parent] = struct{}{}
  168. }
  169. }
  170. // Record change
  171. changes = append(changes, change)
  172. return nil
  173. })
  174. if err != nil && !os.IsNotExist(err) {
  175. return nil, err
  176. }
  177. return changes, nil
  178. }
  179. // FileInfo describes the information of a file.
  180. type FileInfo struct {
  181. parent *FileInfo
  182. name string
  183. stat *system.StatT
  184. children map[string]*FileInfo
  185. capability []byte
  186. added bool
  187. }
  188. // LookUp looks up the file information of a file.
  189. func (info *FileInfo) LookUp(path string) *FileInfo {
  190. // As this runs on the daemon side, file paths are OS specific.
  191. parent := info
  192. if path == string(os.PathSeparator) {
  193. return info
  194. }
  195. pathElements := strings.Split(path, string(os.PathSeparator))
  196. for _, elem := range pathElements {
  197. if elem != "" {
  198. child := parent.children[elem]
  199. if child == nil {
  200. return nil
  201. }
  202. parent = child
  203. }
  204. }
  205. return parent
  206. }
  207. func (info *FileInfo) path() string {
  208. if info.parent == nil {
  209. // As this runs on the daemon side, file paths are OS specific.
  210. return string(os.PathSeparator)
  211. }
  212. return filepath.Join(info.parent.path(), info.name)
  213. }
  214. func (info *FileInfo) addChanges(oldInfo *FileInfo, changes *[]Change) {
  215. sizeAtEntry := len(*changes)
  216. if oldInfo == nil {
  217. // add
  218. change := Change{
  219. Path: info.path(),
  220. Kind: ChangeAdd,
  221. }
  222. *changes = append(*changes, change)
  223. info.added = true
  224. }
  225. // We make a copy so we can modify it to detect additions
  226. // also, we only recurse on the old dir if the new info is a directory
  227. // otherwise any previous delete/change is considered recursive
  228. oldChildren := make(map[string]*FileInfo)
  229. if oldInfo != nil && info.isDir() {
  230. for k, v := range oldInfo.children {
  231. oldChildren[k] = v
  232. }
  233. }
  234. for name, newChild := range info.children {
  235. oldChild := oldChildren[name]
  236. if oldChild != nil {
  237. // change?
  238. oldStat := oldChild.stat
  239. newStat := newChild.stat
  240. // Note: We can't compare inode or ctime or blocksize here, because these change
  241. // when copying a file into a container. However, that is not generally a problem
  242. // because any content change will change mtime, and any status change should
  243. // be visible when actually comparing the stat fields. The only time this
  244. // breaks down is if some code intentionally hides a change by setting
  245. // back mtime
  246. if statDifferent(oldStat, newStat) ||
  247. !bytes.Equal(oldChild.capability, newChild.capability) {
  248. change := Change{
  249. Path: newChild.path(),
  250. Kind: ChangeModify,
  251. }
  252. *changes = append(*changes, change)
  253. newChild.added = true
  254. }
  255. // Remove from copy so we can detect deletions
  256. delete(oldChildren, name)
  257. }
  258. newChild.addChanges(oldChild, changes)
  259. }
  260. for _, oldChild := range oldChildren {
  261. // delete
  262. change := Change{
  263. Path: oldChild.path(),
  264. Kind: ChangeDelete,
  265. }
  266. *changes = append(*changes, change)
  267. }
  268. // If there were changes inside this directory, we need to add it, even if the directory
  269. // itself wasn't changed. This is needed to properly save and restore filesystem permissions.
  270. // As this runs on the daemon side, file paths are OS specific.
  271. if len(*changes) > sizeAtEntry && info.isDir() && !info.added && info.path() != string(os.PathSeparator) {
  272. change := Change{
  273. Path: info.path(),
  274. Kind: ChangeModify,
  275. }
  276. // Let's insert the directory entry before the recently added entries located inside this dir
  277. *changes = append(*changes, change) // just to resize the slice, will be overwritten
  278. copy((*changes)[sizeAtEntry+1:], (*changes)[sizeAtEntry:])
  279. (*changes)[sizeAtEntry] = change
  280. }
  281. }
  282. // Changes add changes to file information.
  283. func (info *FileInfo) Changes(oldInfo *FileInfo) []Change {
  284. var changes []Change
  285. info.addChanges(oldInfo, &changes)
  286. return changes
  287. }
  288. func newRootFileInfo() *FileInfo {
  289. // As this runs on the daemon side, file paths are OS specific.
  290. root := &FileInfo{
  291. name: string(os.PathSeparator),
  292. children: make(map[string]*FileInfo),
  293. }
  294. return root
  295. }
  296. // ChangesDirs compares two directories and generates an array of Change objects describing the changes.
  297. // If oldDir is "", then all files in newDir will be Add-Changes.
  298. func ChangesDirs(newDir, oldDir string) ([]Change, error) {
  299. var (
  300. oldRoot, newRoot *FileInfo
  301. )
  302. if oldDir == "" {
  303. emptyDir, err := ioutil.TempDir("", "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. logrus.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, uidMaps, gidMaps []idtools.IDMap) (io.ReadCloser, error) {
  347. reader, writer := io.Pipe()
  348. go func() {
  349. ta := newTarAppender(idtools.NewIDMappingsFromMaps(uidMaps, gidMaps), 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. logrus.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. logrus.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. logrus.Debugf("Can't close layer: %s", err)
  383. }
  384. if err := writer.Close(); err != nil {
  385. logrus.Debugf("failed close Changes writer: %s", err)
  386. }
  387. }()
  388. return reader, nil
  389. }