changes.go 10 KB

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