changes_test.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. package archive // import "github.com/docker/docker/pkg/archive"
  2. import (
  3. "io/ioutil"
  4. "os"
  5. "os/exec"
  6. "path"
  7. "path/filepath"
  8. "runtime"
  9. "sort"
  10. "syscall"
  11. "testing"
  12. "time"
  13. "github.com/docker/docker/pkg/system"
  14. "gotest.tools/assert"
  15. "gotest.tools/skip"
  16. )
  17. func max(x, y int) int {
  18. if x >= y {
  19. return x
  20. }
  21. return y
  22. }
  23. func copyDir(src, dst string) error {
  24. if runtime.GOOS != "windows" {
  25. return exec.Command("cp", "-a", src, dst).Run()
  26. }
  27. // Could have used xcopy src dst /E /I /H /Y /B. However, xcopy has the
  28. // unfortunate side effect of not preserving timestamps of newly created
  29. // directories in the target directory, so we don't get accurate changes.
  30. // Use robocopy instead. Note this isn't available in microsoft/nanoserver.
  31. // But it has gotchas. See https://weblogs.sqlteam.com/robv/archive/2010/02/17/61106.aspx
  32. err := exec.Command("robocopy", filepath.FromSlash(src), filepath.FromSlash(dst), "/SL", "/COPYALL", "/MIR").Run()
  33. if exiterr, ok := err.(*exec.ExitError); ok {
  34. if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
  35. if status.ExitStatus()&24 == 0 {
  36. return nil
  37. }
  38. }
  39. }
  40. return err
  41. }
  42. type FileType uint32
  43. const (
  44. Regular FileType = iota
  45. Dir
  46. Symlink
  47. )
  48. type FileData struct {
  49. filetype FileType
  50. path string
  51. contents string
  52. permissions os.FileMode
  53. }
  54. func createSampleDir(t *testing.T, root string) {
  55. files := []FileData{
  56. {filetype: Regular, path: "file1", contents: "file1\n", permissions: 0600},
  57. {filetype: Regular, path: "file2", contents: "file2\n", permissions: 0666},
  58. {filetype: Regular, path: "file3", contents: "file3\n", permissions: 0404},
  59. {filetype: Regular, path: "file4", contents: "file4\n", permissions: 0600},
  60. {filetype: Regular, path: "file5", contents: "file5\n", permissions: 0600},
  61. {filetype: Regular, path: "file6", contents: "file6\n", permissions: 0600},
  62. {filetype: Regular, path: "file7", contents: "file7\n", permissions: 0600},
  63. {filetype: Dir, path: "dir1", contents: "", permissions: 0740},
  64. {filetype: Regular, path: "dir1/file1-1", contents: "file1-1\n", permissions: 01444},
  65. {filetype: Regular, path: "dir1/file1-2", contents: "file1-2\n", permissions: 0666},
  66. {filetype: Dir, path: "dir2", contents: "", permissions: 0700},
  67. {filetype: Regular, path: "dir2/file2-1", contents: "file2-1\n", permissions: 0666},
  68. {filetype: Regular, path: "dir2/file2-2", contents: "file2-2\n", permissions: 0666},
  69. {filetype: Dir, path: "dir3", contents: "", permissions: 0700},
  70. {filetype: Regular, path: "dir3/file3-1", contents: "file3-1\n", permissions: 0666},
  71. {filetype: Regular, path: "dir3/file3-2", contents: "file3-2\n", permissions: 0666},
  72. {filetype: Dir, path: "dir4", contents: "", permissions: 0700},
  73. {filetype: Regular, path: "dir4/file3-1", contents: "file4-1\n", permissions: 0666},
  74. {filetype: Regular, path: "dir4/file3-2", contents: "file4-2\n", permissions: 0666},
  75. {filetype: Symlink, path: "symlink1", contents: "target1", permissions: 0666},
  76. {filetype: Symlink, path: "symlink2", contents: "target2", permissions: 0666},
  77. {filetype: Symlink, path: "symlink3", contents: root + "/file1", permissions: 0666},
  78. {filetype: Symlink, path: "symlink4", contents: root + "/symlink3", permissions: 0666},
  79. {filetype: Symlink, path: "dirSymlink", contents: root + "/dir1", permissions: 0740},
  80. }
  81. provisionSampleDir(t, root, files)
  82. }
  83. func provisionSampleDir(t *testing.T, root string, files []FileData) {
  84. now := time.Now()
  85. for _, info := range files {
  86. p := path.Join(root, info.path)
  87. if info.filetype == Dir {
  88. err := os.MkdirAll(p, info.permissions)
  89. assert.NilError(t, err)
  90. } else if info.filetype == Regular {
  91. err := ioutil.WriteFile(p, []byte(info.contents), info.permissions)
  92. assert.NilError(t, err)
  93. } else if info.filetype == Symlink {
  94. err := os.Symlink(info.contents, p)
  95. assert.NilError(t, err)
  96. }
  97. if info.filetype != Symlink {
  98. // Set a consistent ctime, atime for all files and dirs
  99. err := system.Chtimes(p, now, now)
  100. assert.NilError(t, err)
  101. }
  102. }
  103. }
  104. func TestChangeString(t *testing.T) {
  105. modifyChange := Change{"change", ChangeModify}
  106. toString := modifyChange.String()
  107. if toString != "C change" {
  108. t.Fatalf("String() of a change with ChangeModify Kind should have been %s but was %s", "C change", toString)
  109. }
  110. addChange := Change{"change", ChangeAdd}
  111. toString = addChange.String()
  112. if toString != "A change" {
  113. t.Fatalf("String() of a change with ChangeAdd Kind should have been %s but was %s", "A change", toString)
  114. }
  115. deleteChange := Change{"change", ChangeDelete}
  116. toString = deleteChange.String()
  117. if toString != "D change" {
  118. t.Fatalf("String() of a change with ChangeDelete Kind should have been %s but was %s", "D change", toString)
  119. }
  120. }
  121. func TestChangesWithNoChanges(t *testing.T) {
  122. rwLayer, err := ioutil.TempDir("", "docker-changes-test")
  123. assert.NilError(t, err)
  124. defer os.RemoveAll(rwLayer)
  125. layer, err := ioutil.TempDir("", "docker-changes-test-layer")
  126. assert.NilError(t, err)
  127. defer os.RemoveAll(layer)
  128. createSampleDir(t, layer)
  129. changes, err := Changes([]string{layer}, rwLayer)
  130. assert.NilError(t, err)
  131. if len(changes) != 0 {
  132. t.Fatalf("Changes with no difference should have detect no changes, but detected %d", len(changes))
  133. }
  134. }
  135. func TestChangesWithChanges(t *testing.T) {
  136. // Mock the readonly layer
  137. layer, err := ioutil.TempDir("", "docker-changes-test-layer")
  138. assert.NilError(t, err)
  139. defer os.RemoveAll(layer)
  140. createSampleDir(t, layer)
  141. os.MkdirAll(path.Join(layer, "dir1/subfolder"), 0740)
  142. // Mock the RW layer
  143. rwLayer, err := ioutil.TempDir("", "docker-changes-test")
  144. assert.NilError(t, err)
  145. defer os.RemoveAll(rwLayer)
  146. // Create a folder in RW layer
  147. dir1 := path.Join(rwLayer, "dir1")
  148. os.MkdirAll(dir1, 0740)
  149. deletedFile := path.Join(dir1, ".wh.file1-2")
  150. ioutil.WriteFile(deletedFile, []byte{}, 0600)
  151. modifiedFile := path.Join(dir1, "file1-1")
  152. ioutil.WriteFile(modifiedFile, []byte{0x00}, 01444)
  153. // Let's add a subfolder for a newFile
  154. subfolder := path.Join(dir1, "subfolder")
  155. os.MkdirAll(subfolder, 0740)
  156. newFile := path.Join(subfolder, "newFile")
  157. ioutil.WriteFile(newFile, []byte{}, 0740)
  158. changes, err := Changes([]string{layer}, rwLayer)
  159. assert.NilError(t, err)
  160. expectedChanges := []Change{
  161. {filepath.FromSlash("/dir1"), ChangeModify},
  162. {filepath.FromSlash("/dir1/file1-1"), ChangeModify},
  163. {filepath.FromSlash("/dir1/file1-2"), ChangeDelete},
  164. {filepath.FromSlash("/dir1/subfolder"), ChangeModify},
  165. {filepath.FromSlash("/dir1/subfolder/newFile"), ChangeAdd},
  166. }
  167. checkChanges(expectedChanges, changes, t)
  168. }
  169. // See https://github.com/docker/docker/pull/13590
  170. func TestChangesWithChangesGH13590(t *testing.T) {
  171. // TODO Windows. Needs further investigation to identify the failure
  172. if runtime.GOOS == "windows" {
  173. t.Skip("needs more investigation")
  174. }
  175. baseLayer, err := ioutil.TempDir("", "docker-changes-test.")
  176. assert.NilError(t, err)
  177. defer os.RemoveAll(baseLayer)
  178. dir3 := path.Join(baseLayer, "dir1/dir2/dir3")
  179. os.MkdirAll(dir3, 07400)
  180. file := path.Join(dir3, "file.txt")
  181. ioutil.WriteFile(file, []byte("hello"), 0666)
  182. layer, err := ioutil.TempDir("", "docker-changes-test2.")
  183. assert.NilError(t, err)
  184. defer os.RemoveAll(layer)
  185. // Test creating a new file
  186. if err := copyDir(baseLayer+"/dir1", layer+"/"); err != nil {
  187. t.Fatalf("Cmd failed: %q", err)
  188. }
  189. os.Remove(path.Join(layer, "dir1/dir2/dir3/file.txt"))
  190. file = path.Join(layer, "dir1/dir2/dir3/file1.txt")
  191. ioutil.WriteFile(file, []byte("bye"), 0666)
  192. changes, err := Changes([]string{baseLayer}, layer)
  193. assert.NilError(t, err)
  194. expectedChanges := []Change{
  195. {"/dir1/dir2/dir3", ChangeModify},
  196. {"/dir1/dir2/dir3/file1.txt", ChangeAdd},
  197. }
  198. checkChanges(expectedChanges, changes, t)
  199. // Now test changing a file
  200. layer, err = ioutil.TempDir("", "docker-changes-test3.")
  201. assert.NilError(t, err)
  202. defer os.RemoveAll(layer)
  203. if err := copyDir(baseLayer+"/dir1", layer+"/"); err != nil {
  204. t.Fatalf("Cmd failed: %q", err)
  205. }
  206. file = path.Join(layer, "dir1/dir2/dir3/file.txt")
  207. ioutil.WriteFile(file, []byte("bye"), 0666)
  208. changes, err = Changes([]string{baseLayer}, layer)
  209. assert.NilError(t, err)
  210. expectedChanges = []Change{
  211. {"/dir1/dir2/dir3/file.txt", ChangeModify},
  212. }
  213. checkChanges(expectedChanges, changes, t)
  214. }
  215. // Create a directory, copy it, make sure we report no changes between the two
  216. func TestChangesDirsEmpty(t *testing.T) {
  217. src, err := ioutil.TempDir("", "docker-changes-test")
  218. assert.NilError(t, err)
  219. defer os.RemoveAll(src)
  220. createSampleDir(t, src)
  221. dst := src + "-copy"
  222. err = copyDir(src, dst)
  223. assert.NilError(t, err)
  224. defer os.RemoveAll(dst)
  225. changes, err := ChangesDirs(dst, src)
  226. assert.NilError(t, err)
  227. if len(changes) != 0 {
  228. t.Fatalf("Reported changes for identical dirs: %v", changes)
  229. }
  230. os.RemoveAll(src)
  231. os.RemoveAll(dst)
  232. }
  233. func mutateSampleDir(t *testing.T, root string) {
  234. // Remove a regular file
  235. err := os.RemoveAll(path.Join(root, "file1"))
  236. assert.NilError(t, err)
  237. // Remove a directory
  238. err = os.RemoveAll(path.Join(root, "dir1"))
  239. assert.NilError(t, err)
  240. // Remove a symlink
  241. err = os.RemoveAll(path.Join(root, "symlink1"))
  242. assert.NilError(t, err)
  243. // Rewrite a file
  244. err = ioutil.WriteFile(path.Join(root, "file2"), []byte("fileNN\n"), 0777)
  245. assert.NilError(t, err)
  246. // Replace a file
  247. err = os.RemoveAll(path.Join(root, "file3"))
  248. assert.NilError(t, err)
  249. err = ioutil.WriteFile(path.Join(root, "file3"), []byte("fileMM\n"), 0404)
  250. assert.NilError(t, err)
  251. // Touch file
  252. err = system.Chtimes(path.Join(root, "file4"), time.Now().Add(time.Second), time.Now().Add(time.Second))
  253. assert.NilError(t, err)
  254. // Replace file with dir
  255. err = os.RemoveAll(path.Join(root, "file5"))
  256. assert.NilError(t, err)
  257. err = os.MkdirAll(path.Join(root, "file5"), 0666)
  258. assert.NilError(t, err)
  259. // Create new file
  260. err = ioutil.WriteFile(path.Join(root, "filenew"), []byte("filenew\n"), 0777)
  261. assert.NilError(t, err)
  262. // Create new dir
  263. err = os.MkdirAll(path.Join(root, "dirnew"), 0766)
  264. assert.NilError(t, err)
  265. // Create a new symlink
  266. err = os.Symlink("targetnew", path.Join(root, "symlinknew"))
  267. assert.NilError(t, err)
  268. // Change a symlink
  269. err = os.RemoveAll(path.Join(root, "symlink2"))
  270. assert.NilError(t, err)
  271. err = os.Symlink("target2change", path.Join(root, "symlink2"))
  272. assert.NilError(t, err)
  273. // Replace dir with file
  274. err = os.RemoveAll(path.Join(root, "dir2"))
  275. assert.NilError(t, err)
  276. err = ioutil.WriteFile(path.Join(root, "dir2"), []byte("dir2\n"), 0777)
  277. assert.NilError(t, err)
  278. // Touch dir
  279. err = system.Chtimes(path.Join(root, "dir3"), time.Now().Add(time.Second), time.Now().Add(time.Second))
  280. assert.NilError(t, err)
  281. }
  282. func TestChangesDirsMutated(t *testing.T) {
  283. src, err := ioutil.TempDir("", "docker-changes-test")
  284. assert.NilError(t, err)
  285. createSampleDir(t, src)
  286. dst := src + "-copy"
  287. err = copyDir(src, dst)
  288. assert.NilError(t, err)
  289. defer os.RemoveAll(src)
  290. defer os.RemoveAll(dst)
  291. mutateSampleDir(t, dst)
  292. changes, err := ChangesDirs(dst, src)
  293. assert.NilError(t, err)
  294. sort.Sort(changesByPath(changes))
  295. expectedChanges := []Change{
  296. {filepath.FromSlash("/dir1"), ChangeDelete},
  297. {filepath.FromSlash("/dir2"), ChangeModify},
  298. }
  299. // Note there is slight difference between the Linux and Windows
  300. // implementations here. Due to https://github.com/moby/moby/issues/9874,
  301. // and the fix at https://github.com/moby/moby/pull/11422, Linux does not
  302. // consider a change to the directory time as a change. Windows on NTFS
  303. // does. See https://github.com/moby/moby/pull/37982 for more information.
  304. //
  305. // Note also: https://github.com/moby/moby/pull/37982#discussion_r223523114
  306. // that differences are ordered in the way the test is currently written, hence
  307. // this is in the middle of the list of changes rather than at the start or
  308. // end. Potentially can be addressed later.
  309. if runtime.GOOS == "windows" {
  310. expectedChanges = append(expectedChanges, Change{filepath.FromSlash("/dir3"), ChangeModify})
  311. }
  312. expectedChanges = append(expectedChanges, []Change{
  313. {filepath.FromSlash("/dirnew"), ChangeAdd},
  314. {filepath.FromSlash("/file1"), ChangeDelete},
  315. {filepath.FromSlash("/file2"), ChangeModify},
  316. {filepath.FromSlash("/file3"), ChangeModify},
  317. {filepath.FromSlash("/file4"), ChangeModify},
  318. {filepath.FromSlash("/file5"), ChangeModify},
  319. {filepath.FromSlash("/filenew"), ChangeAdd},
  320. {filepath.FromSlash("/symlink1"), ChangeDelete},
  321. {filepath.FromSlash("/symlink2"), ChangeModify},
  322. {filepath.FromSlash("/symlinknew"), ChangeAdd},
  323. }...)
  324. for i := 0; i < max(len(changes), len(expectedChanges)); i++ {
  325. if i >= len(expectedChanges) {
  326. t.Fatalf("unexpected change %s\n", changes[i].String())
  327. }
  328. if i >= len(changes) {
  329. t.Fatalf("no change for expected change %s\n", expectedChanges[i].String())
  330. }
  331. if changes[i].Path == expectedChanges[i].Path {
  332. if changes[i] != expectedChanges[i] {
  333. t.Fatalf("Wrong change for %s, expected %s, got %s\n", changes[i].Path, changes[i].String(), expectedChanges[i].String())
  334. }
  335. } else if changes[i].Path < expectedChanges[i].Path {
  336. t.Fatalf("unexpected change %q %q\n", changes[i].String(), expectedChanges[i].Path)
  337. } else {
  338. t.Fatalf("no change for expected change %s != %s\n", expectedChanges[i].String(), changes[i].String())
  339. }
  340. }
  341. }
  342. func TestApplyLayer(t *testing.T) {
  343. // TODO Windows. This is very close to working, but it fails with changes
  344. // to \symlinknew and \symlink2. The destination has an updated
  345. // Access/Modify/Change/Birth date to the source (~3/100th sec different).
  346. // Needs further investigation as to why, but I currently believe this is
  347. // just the way NTFS works. I don't think it's a bug in this test or archive.
  348. if runtime.GOOS == "windows" {
  349. t.Skip("needs further investigation")
  350. }
  351. src, err := ioutil.TempDir("", "docker-changes-test")
  352. assert.NilError(t, err)
  353. createSampleDir(t, src)
  354. defer os.RemoveAll(src)
  355. dst := src + "-copy"
  356. err = copyDir(src, dst)
  357. assert.NilError(t, err)
  358. mutateSampleDir(t, dst)
  359. defer os.RemoveAll(dst)
  360. changes, err := ChangesDirs(dst, src)
  361. assert.NilError(t, err)
  362. layer, err := ExportChanges(dst, changes, nil, nil)
  363. assert.NilError(t, err)
  364. layerCopy, err := NewTempArchive(layer, "")
  365. assert.NilError(t, err)
  366. _, err = ApplyLayer(src, layerCopy)
  367. assert.NilError(t, err)
  368. changes2, err := ChangesDirs(src, dst)
  369. assert.NilError(t, err)
  370. if len(changes2) != 0 {
  371. t.Fatalf("Unexpected differences after reapplying mutation: %v", changes2)
  372. }
  373. }
  374. func TestChangesSizeWithHardlinks(t *testing.T) {
  375. // TODO Windows. Needs further investigation. Likely in ChangeSizes not
  376. // coping correctly with hardlinks on Windows.
  377. if runtime.GOOS == "windows" {
  378. t.Skip("needs further investigation")
  379. }
  380. srcDir, err := ioutil.TempDir("", "docker-test-srcDir")
  381. assert.NilError(t, err)
  382. defer os.RemoveAll(srcDir)
  383. destDir, err := ioutil.TempDir("", "docker-test-destDir")
  384. assert.NilError(t, err)
  385. defer os.RemoveAll(destDir)
  386. creationSize, err := prepareUntarSourceDirectory(100, destDir, true)
  387. assert.NilError(t, err)
  388. changes, err := ChangesDirs(destDir, srcDir)
  389. assert.NilError(t, err)
  390. got := ChangesSize(destDir, changes)
  391. if got != int64(creationSize) {
  392. t.Errorf("Expected %d bytes of changes, got %d", creationSize, got)
  393. }
  394. }
  395. func TestChangesSizeWithNoChanges(t *testing.T) {
  396. size := ChangesSize("/tmp", nil)
  397. if size != 0 {
  398. t.Fatalf("ChangesSizes with no changes should be 0, was %d", size)
  399. }
  400. }
  401. func TestChangesSizeWithOnlyDeleteChanges(t *testing.T) {
  402. changes := []Change{
  403. {Path: "deletedPath", Kind: ChangeDelete},
  404. }
  405. size := ChangesSize("/tmp", changes)
  406. if size != 0 {
  407. t.Fatalf("ChangesSizes with only delete changes should be 0, was %d", size)
  408. }
  409. }
  410. func TestChangesSize(t *testing.T) {
  411. parentPath, err := ioutil.TempDir("", "docker-changes-test")
  412. assert.NilError(t, err)
  413. defer os.RemoveAll(parentPath)
  414. addition := path.Join(parentPath, "addition")
  415. err = ioutil.WriteFile(addition, []byte{0x01, 0x01, 0x01}, 0744)
  416. assert.NilError(t, err)
  417. modification := path.Join(parentPath, "modification")
  418. err = ioutil.WriteFile(modification, []byte{0x01, 0x01, 0x01}, 0744)
  419. assert.NilError(t, err)
  420. changes := []Change{
  421. {Path: "addition", Kind: ChangeAdd},
  422. {Path: "modification", Kind: ChangeModify},
  423. }
  424. size := ChangesSize(parentPath, changes)
  425. if size != 6 {
  426. t.Fatalf("Expected 6 bytes of changes, got %d", size)
  427. }
  428. }
  429. func checkChanges(expectedChanges, changes []Change, t *testing.T) {
  430. skip.If(t, runtime.GOOS != "windows" && os.Getuid() != 0, "skipping test that requires root")
  431. sort.Sort(changesByPath(expectedChanges))
  432. sort.Sort(changesByPath(changes))
  433. for i := 0; i < max(len(changes), len(expectedChanges)); i++ {
  434. if i >= len(expectedChanges) {
  435. t.Fatalf("unexpected change %s\n", changes[i].String())
  436. }
  437. if i >= len(changes) {
  438. t.Fatalf("no change for expected change %s\n", expectedChanges[i].String())
  439. }
  440. if changes[i].Path == expectedChanges[i].Path {
  441. if changes[i] != expectedChanges[i] {
  442. t.Fatalf("Wrong change for %s, expected %s, got %s\n", changes[i].Path, changes[i].String(), expectedChanges[i].String())
  443. }
  444. } else if changes[i].Path < expectedChanges[i].Path {
  445. t.Fatalf("unexpected change %s\n", changes[i].String())
  446. } else {
  447. t.Fatalf("no change for expected change %s != %s\n", expectedChanges[i].String(), changes[i].String())
  448. }
  449. }
  450. }