changes.go 10.0 KB

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