changes.go 8.8 KB

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