changes.go 11 KB

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