changes.go 11 KB

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