changes.go 11 KB

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