archive_test.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272
  1. package archive
  2. import (
  3. "archive/tar"
  4. "bytes"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "os"
  9. "os/exec"
  10. "path/filepath"
  11. "runtime"
  12. "strings"
  13. "testing"
  14. "time"
  15. "github.com/docker/docker/pkg/testutil/assert"
  16. )
  17. var tmp string
  18. func init() {
  19. tmp = "/tmp/"
  20. if runtime.GOOS == "windows" {
  21. tmp = os.Getenv("TEMP") + `\`
  22. }
  23. }
  24. func TestIsArchiveNilHeader(t *testing.T) {
  25. out := IsArchive(nil)
  26. if out {
  27. t.Fatalf("isArchive should return false as nil is not a valid archive header")
  28. }
  29. }
  30. func TestIsArchiveInvalidHeader(t *testing.T) {
  31. header := []byte{0x00, 0x01, 0x02}
  32. out := IsArchive(header)
  33. if out {
  34. t.Fatalf("isArchive should return false as %s is not a valid archive header", header)
  35. }
  36. }
  37. func TestIsArchiveBzip2(t *testing.T) {
  38. header := []byte{0x42, 0x5A, 0x68}
  39. out := IsArchive(header)
  40. if !out {
  41. t.Fatalf("isArchive should return true as %s is a bz2 header", header)
  42. }
  43. }
  44. func TestIsArchive7zip(t *testing.T) {
  45. header := []byte{0x50, 0x4b, 0x03, 0x04}
  46. out := IsArchive(header)
  47. if out {
  48. t.Fatalf("isArchive should return false as %s is a 7z header and it is not supported", header)
  49. }
  50. }
  51. func TestIsArchivePathDir(t *testing.T) {
  52. cmd := exec.Command("sh", "-c", "mkdir -p /tmp/archivedir")
  53. output, err := cmd.CombinedOutput()
  54. if err != nil {
  55. t.Fatalf("Fail to create an archive file for test : %s.", output)
  56. }
  57. if IsArchivePath(tmp + "archivedir") {
  58. t.Fatalf("Incorrectly recognised directory as an archive")
  59. }
  60. }
  61. func TestIsArchivePathInvalidFile(t *testing.T) {
  62. cmd := exec.Command("sh", "-c", "dd if=/dev/zero bs=1024 count=1 of=/tmp/archive && gzip --stdout /tmp/archive > /tmp/archive.gz")
  63. output, err := cmd.CombinedOutput()
  64. if err != nil {
  65. t.Fatalf("Fail to create an archive file for test : %s.", output)
  66. }
  67. if IsArchivePath(tmp + "archive") {
  68. t.Fatalf("Incorrectly recognised invalid tar path as archive")
  69. }
  70. if IsArchivePath(tmp + "archive.gz") {
  71. t.Fatalf("Incorrectly recognised invalid compressed tar path as archive")
  72. }
  73. }
  74. func TestIsArchivePathTar(t *testing.T) {
  75. var whichTar string
  76. if runtime.GOOS == "solaris" {
  77. whichTar = "gtar"
  78. } else {
  79. whichTar = "tar"
  80. }
  81. cmdStr := fmt.Sprintf("touch /tmp/archivedata && %s -cf /tmp/archive /tmp/archivedata && gzip --stdout /tmp/archive > /tmp/archive.gz", whichTar)
  82. cmd := exec.Command("sh", "-c", cmdStr)
  83. output, err := cmd.CombinedOutput()
  84. if err != nil {
  85. t.Fatalf("Fail to create an archive file for test : %s.", output)
  86. }
  87. if !IsArchivePath(tmp + "/archive") {
  88. t.Fatalf("Did not recognise valid tar path as archive")
  89. }
  90. if !IsArchivePath(tmp + "archive.gz") {
  91. t.Fatalf("Did not recognise valid compressed tar path as archive")
  92. }
  93. }
  94. func testDecompressStream(t *testing.T, ext, compressCommand string) {
  95. cmd := exec.Command("sh", "-c",
  96. fmt.Sprintf("touch /tmp/archive && %s /tmp/archive", compressCommand))
  97. output, err := cmd.CombinedOutput()
  98. if err != nil {
  99. t.Fatalf("Failed to create an archive file for test : %s.", output)
  100. }
  101. filename := "archive." + ext
  102. archive, err := os.Open(tmp + filename)
  103. if err != nil {
  104. t.Fatalf("Failed to open file %s: %v", filename, err)
  105. }
  106. defer archive.Close()
  107. r, err := DecompressStream(archive)
  108. if err != nil {
  109. t.Fatalf("Failed to decompress %s: %v", filename, err)
  110. }
  111. if _, err = ioutil.ReadAll(r); err != nil {
  112. t.Fatalf("Failed to read the decompressed stream: %v ", err)
  113. }
  114. if err = r.Close(); err != nil {
  115. t.Fatalf("Failed to close the decompressed stream: %v ", err)
  116. }
  117. }
  118. func TestDecompressStreamGzip(t *testing.T) {
  119. testDecompressStream(t, "gz", "gzip -f")
  120. }
  121. func TestDecompressStreamBzip2(t *testing.T) {
  122. testDecompressStream(t, "bz2", "bzip2 -f")
  123. }
  124. func TestDecompressStreamXz(t *testing.T) {
  125. if runtime.GOOS == "windows" {
  126. t.Skip("Xz not present in msys2")
  127. }
  128. testDecompressStream(t, "xz", "xz -f")
  129. }
  130. func TestCompressStreamXzUnsupported(t *testing.T) {
  131. dest, err := os.Create(tmp + "dest")
  132. if err != nil {
  133. t.Fatalf("Fail to create the destination file")
  134. }
  135. defer dest.Close()
  136. _, err = CompressStream(dest, Xz)
  137. if err == nil {
  138. t.Fatalf("Should fail as xz is unsupported for compression format.")
  139. }
  140. }
  141. func TestCompressStreamBzip2Unsupported(t *testing.T) {
  142. dest, err := os.Create(tmp + "dest")
  143. if err != nil {
  144. t.Fatalf("Fail to create the destination file")
  145. }
  146. defer dest.Close()
  147. _, err = CompressStream(dest, Xz)
  148. if err == nil {
  149. t.Fatalf("Should fail as xz is unsupported for compression format.")
  150. }
  151. }
  152. func TestCompressStreamInvalid(t *testing.T) {
  153. dest, err := os.Create(tmp + "dest")
  154. if err != nil {
  155. t.Fatalf("Fail to create the destination file")
  156. }
  157. defer dest.Close()
  158. _, err = CompressStream(dest, -1)
  159. if err == nil {
  160. t.Fatalf("Should fail as xz is unsupported for compression format.")
  161. }
  162. }
  163. func TestExtensionInvalid(t *testing.T) {
  164. compression := Compression(-1)
  165. output := compression.Extension()
  166. if output != "" {
  167. t.Fatalf("The extension of an invalid compression should be an empty string.")
  168. }
  169. }
  170. func TestExtensionUncompressed(t *testing.T) {
  171. compression := Uncompressed
  172. output := compression.Extension()
  173. if output != "tar" {
  174. t.Fatalf("The extension of an uncompressed archive should be 'tar'.")
  175. }
  176. }
  177. func TestExtensionBzip2(t *testing.T) {
  178. compression := Bzip2
  179. output := compression.Extension()
  180. if output != "tar.bz2" {
  181. t.Fatalf("The extension of a bzip2 archive should be 'tar.bz2'")
  182. }
  183. }
  184. func TestExtensionGzip(t *testing.T) {
  185. compression := Gzip
  186. output := compression.Extension()
  187. if output != "tar.gz" {
  188. t.Fatalf("The extension of a bzip2 archive should be 'tar.gz'")
  189. }
  190. }
  191. func TestExtensionXz(t *testing.T) {
  192. compression := Xz
  193. output := compression.Extension()
  194. if output != "tar.xz" {
  195. t.Fatalf("The extension of a bzip2 archive should be 'tar.xz'")
  196. }
  197. }
  198. func TestCmdStreamLargeStderr(t *testing.T) {
  199. cmd := exec.Command("sh", "-c", "dd if=/dev/zero bs=1k count=1000 of=/dev/stderr; echo hello")
  200. out, _, err := cmdStream(cmd, nil)
  201. if err != nil {
  202. t.Fatalf("Failed to start command: %s", err)
  203. }
  204. errCh := make(chan error)
  205. go func() {
  206. _, err := io.Copy(ioutil.Discard, out)
  207. errCh <- err
  208. }()
  209. select {
  210. case err := <-errCh:
  211. if err != nil {
  212. t.Fatalf("Command should not have failed (err=%.100s...)", err)
  213. }
  214. case <-time.After(5 * time.Second):
  215. t.Fatalf("Command did not complete in 5 seconds; probable deadlock")
  216. }
  217. }
  218. func TestCmdStreamBad(t *testing.T) {
  219. // TODO Windows: Figure out why this is failing in CI but not locally
  220. if runtime.GOOS == "windows" {
  221. t.Skip("Failing on Windows CI machines")
  222. }
  223. badCmd := exec.Command("sh", "-c", "echo hello; echo >&2 error couldn\\'t reverse the phase pulser; exit 1")
  224. out, _, err := cmdStream(badCmd, nil)
  225. if err != nil {
  226. t.Fatalf("Failed to start command: %s", err)
  227. }
  228. if output, err := ioutil.ReadAll(out); err == nil {
  229. t.Fatalf("Command should have failed")
  230. } else if err.Error() != "exit status 1: error couldn't reverse the phase pulser\n" {
  231. t.Fatalf("Wrong error value (%s)", err)
  232. } else if s := string(output); s != "hello\n" {
  233. t.Fatalf("Command output should be '%s', not '%s'", "hello\\n", output)
  234. }
  235. }
  236. func TestCmdStreamGood(t *testing.T) {
  237. cmd := exec.Command("sh", "-c", "echo hello; exit 0")
  238. out, _, err := cmdStream(cmd, nil)
  239. if err != nil {
  240. t.Fatal(err)
  241. }
  242. if output, err := ioutil.ReadAll(out); err != nil {
  243. t.Fatalf("Command should not have failed (err=%s)", err)
  244. } else if s := string(output); s != "hello\n" {
  245. t.Fatalf("Command output should be '%s', not '%s'", "hello\\n", output)
  246. }
  247. }
  248. func TestUntarPathWithInvalidDest(t *testing.T) {
  249. tempFolder, err := ioutil.TempDir("", "docker-archive-test")
  250. if err != nil {
  251. t.Fatal(err)
  252. }
  253. defer os.RemoveAll(tempFolder)
  254. invalidDestFolder := filepath.Join(tempFolder, "invalidDest")
  255. // Create a src file
  256. srcFile := filepath.Join(tempFolder, "src")
  257. tarFile := filepath.Join(tempFolder, "src.tar")
  258. os.Create(srcFile)
  259. os.Create(invalidDestFolder) // being a file (not dir) should cause an error
  260. // Translate back to Unix semantics as next exec.Command is run under sh
  261. srcFileU := srcFile
  262. tarFileU := tarFile
  263. if runtime.GOOS == "windows" {
  264. tarFileU = "/tmp/" + filepath.Base(filepath.Dir(tarFile)) + "/src.tar"
  265. srcFileU = "/tmp/" + filepath.Base(filepath.Dir(srcFile)) + "/src"
  266. }
  267. cmd := exec.Command("sh", "-c", "tar cf "+tarFileU+" "+srcFileU)
  268. _, err = cmd.CombinedOutput()
  269. if err != nil {
  270. t.Fatal(err)
  271. }
  272. err = UntarPath(tarFile, invalidDestFolder)
  273. if err == nil {
  274. t.Fatalf("UntarPath with invalid destination path should throw an error.")
  275. }
  276. }
  277. func TestUntarPathWithInvalidSrc(t *testing.T) {
  278. dest, err := ioutil.TempDir("", "docker-archive-test")
  279. if err != nil {
  280. t.Fatalf("Fail to create the destination file")
  281. }
  282. defer os.RemoveAll(dest)
  283. err = UntarPath("/invalid/path", dest)
  284. if err == nil {
  285. t.Fatalf("UntarPath with invalid src path should throw an error.")
  286. }
  287. }
  288. func TestUntarPath(t *testing.T) {
  289. tmpFolder, err := ioutil.TempDir("", "docker-archive-test")
  290. if err != nil {
  291. t.Fatal(err)
  292. }
  293. defer os.RemoveAll(tmpFolder)
  294. srcFile := filepath.Join(tmpFolder, "src")
  295. tarFile := filepath.Join(tmpFolder, "src.tar")
  296. os.Create(filepath.Join(tmpFolder, "src"))
  297. destFolder := filepath.Join(tmpFolder, "dest")
  298. err = os.MkdirAll(destFolder, 0740)
  299. if err != nil {
  300. t.Fatalf("Fail to create the destination file")
  301. }
  302. // Translate back to Unix semantics as next exec.Command is run under sh
  303. srcFileU := srcFile
  304. tarFileU := tarFile
  305. if runtime.GOOS == "windows" {
  306. tarFileU = "/tmp/" + filepath.Base(filepath.Dir(tarFile)) + "/src.tar"
  307. srcFileU = "/tmp/" + filepath.Base(filepath.Dir(srcFile)) + "/src"
  308. }
  309. cmd := exec.Command("sh", "-c", "tar cf "+tarFileU+" "+srcFileU)
  310. _, err = cmd.CombinedOutput()
  311. if err != nil {
  312. t.Fatal(err)
  313. }
  314. err = UntarPath(tarFile, destFolder)
  315. if err != nil {
  316. t.Fatalf("UntarPath shouldn't throw an error, %s.", err)
  317. }
  318. expectedFile := filepath.Join(destFolder, srcFileU)
  319. _, err = os.Stat(expectedFile)
  320. if err != nil {
  321. t.Fatalf("Destination folder should contain the source file but did not.")
  322. }
  323. }
  324. // Do the same test as above but with the destination as file, it should fail
  325. func TestUntarPathWithDestinationFile(t *testing.T) {
  326. tmpFolder, err := ioutil.TempDir("", "docker-archive-test")
  327. if err != nil {
  328. t.Fatal(err)
  329. }
  330. defer os.RemoveAll(tmpFolder)
  331. srcFile := filepath.Join(tmpFolder, "src")
  332. tarFile := filepath.Join(tmpFolder, "src.tar")
  333. os.Create(filepath.Join(tmpFolder, "src"))
  334. // Translate back to Unix semantics as next exec.Command is run under sh
  335. srcFileU := srcFile
  336. tarFileU := tarFile
  337. if runtime.GOOS == "windows" {
  338. tarFileU = "/tmp/" + filepath.Base(filepath.Dir(tarFile)) + "/src.tar"
  339. srcFileU = "/tmp/" + filepath.Base(filepath.Dir(srcFile)) + "/src"
  340. }
  341. cmd := exec.Command("sh", "-c", "tar cf "+tarFileU+" "+srcFileU)
  342. _, err = cmd.CombinedOutput()
  343. if err != nil {
  344. t.Fatal(err)
  345. }
  346. destFile := filepath.Join(tmpFolder, "dest")
  347. _, err = os.Create(destFile)
  348. if err != nil {
  349. t.Fatalf("Fail to create the destination file")
  350. }
  351. err = UntarPath(tarFile, destFile)
  352. if err == nil {
  353. t.Fatalf("UntarPath should throw an error if the destination if a file")
  354. }
  355. }
  356. // Do the same test as above but with the destination folder already exists
  357. // and the destination file is a directory
  358. // It's working, see https://github.com/docker/docker/issues/10040
  359. func TestUntarPathWithDestinationSrcFileAsFolder(t *testing.T) {
  360. tmpFolder, err := ioutil.TempDir("", "docker-archive-test")
  361. if err != nil {
  362. t.Fatal(err)
  363. }
  364. defer os.RemoveAll(tmpFolder)
  365. srcFile := filepath.Join(tmpFolder, "src")
  366. tarFile := filepath.Join(tmpFolder, "src.tar")
  367. os.Create(srcFile)
  368. // Translate back to Unix semantics as next exec.Command is run under sh
  369. srcFileU := srcFile
  370. tarFileU := tarFile
  371. if runtime.GOOS == "windows" {
  372. tarFileU = "/tmp/" + filepath.Base(filepath.Dir(tarFile)) + "/src.tar"
  373. srcFileU = "/tmp/" + filepath.Base(filepath.Dir(srcFile)) + "/src"
  374. }
  375. cmd := exec.Command("sh", "-c", "tar cf "+tarFileU+" "+srcFileU)
  376. _, err = cmd.CombinedOutput()
  377. if err != nil {
  378. t.Fatal(err)
  379. }
  380. destFolder := filepath.Join(tmpFolder, "dest")
  381. err = os.MkdirAll(destFolder, 0740)
  382. if err != nil {
  383. t.Fatalf("Fail to create the destination folder")
  384. }
  385. // Let's create a folder that will has the same path as the extracted file (from tar)
  386. destSrcFileAsFolder := filepath.Join(destFolder, srcFileU)
  387. err = os.MkdirAll(destSrcFileAsFolder, 0740)
  388. if err != nil {
  389. t.Fatal(err)
  390. }
  391. err = UntarPath(tarFile, destFolder)
  392. if err != nil {
  393. t.Fatalf("UntarPath should throw not throw an error if the extracted file already exists and is a folder")
  394. }
  395. }
  396. func TestCopyWithTarInvalidSrc(t *testing.T) {
  397. tempFolder, err := ioutil.TempDir("", "docker-archive-test")
  398. if err != nil {
  399. t.Fatal(nil)
  400. }
  401. destFolder := filepath.Join(tempFolder, "dest")
  402. invalidSrc := filepath.Join(tempFolder, "doesnotexists")
  403. err = os.MkdirAll(destFolder, 0740)
  404. if err != nil {
  405. t.Fatal(err)
  406. }
  407. err = CopyWithTar(invalidSrc, destFolder)
  408. if err == nil {
  409. t.Fatalf("archiver.CopyWithTar with invalid src path should throw an error.")
  410. }
  411. }
  412. func TestCopyWithTarInexistentDestWillCreateIt(t *testing.T) {
  413. tempFolder, err := ioutil.TempDir("", "docker-archive-test")
  414. if err != nil {
  415. t.Fatal(nil)
  416. }
  417. srcFolder := filepath.Join(tempFolder, "src")
  418. inexistentDestFolder := filepath.Join(tempFolder, "doesnotexists")
  419. err = os.MkdirAll(srcFolder, 0740)
  420. if err != nil {
  421. t.Fatal(err)
  422. }
  423. err = CopyWithTar(srcFolder, inexistentDestFolder)
  424. if err != nil {
  425. t.Fatalf("CopyWithTar with an inexistent folder shouldn't fail.")
  426. }
  427. _, err = os.Stat(inexistentDestFolder)
  428. if err != nil {
  429. t.Fatalf("CopyWithTar with an inexistent folder should create it.")
  430. }
  431. }
  432. // Test CopyWithTar with a file as src
  433. func TestCopyWithTarSrcFile(t *testing.T) {
  434. folder, err := ioutil.TempDir("", "docker-archive-test")
  435. if err != nil {
  436. t.Fatal(err)
  437. }
  438. defer os.RemoveAll(folder)
  439. dest := filepath.Join(folder, "dest")
  440. srcFolder := filepath.Join(folder, "src")
  441. src := filepath.Join(folder, filepath.Join("src", "src"))
  442. err = os.MkdirAll(srcFolder, 0740)
  443. if err != nil {
  444. t.Fatal(err)
  445. }
  446. err = os.MkdirAll(dest, 0740)
  447. if err != nil {
  448. t.Fatal(err)
  449. }
  450. ioutil.WriteFile(src, []byte("content"), 0777)
  451. err = CopyWithTar(src, dest)
  452. if err != nil {
  453. t.Fatalf("archiver.CopyWithTar shouldn't throw an error, %s.", err)
  454. }
  455. _, err = os.Stat(dest)
  456. // FIXME Check the content
  457. if err != nil {
  458. t.Fatalf("Destination file should be the same as the source.")
  459. }
  460. }
  461. // Test CopyWithTar with a folder as src
  462. func TestCopyWithTarSrcFolder(t *testing.T) {
  463. folder, err := ioutil.TempDir("", "docker-archive-test")
  464. if err != nil {
  465. t.Fatal(err)
  466. }
  467. defer os.RemoveAll(folder)
  468. dest := filepath.Join(folder, "dest")
  469. src := filepath.Join(folder, filepath.Join("src", "folder"))
  470. err = os.MkdirAll(src, 0740)
  471. if err != nil {
  472. t.Fatal(err)
  473. }
  474. err = os.MkdirAll(dest, 0740)
  475. if err != nil {
  476. t.Fatal(err)
  477. }
  478. ioutil.WriteFile(filepath.Join(src, "file"), []byte("content"), 0777)
  479. err = CopyWithTar(src, dest)
  480. if err != nil {
  481. t.Fatalf("archiver.CopyWithTar shouldn't throw an error, %s.", err)
  482. }
  483. _, err = os.Stat(dest)
  484. // FIXME Check the content (the file inside)
  485. if err != nil {
  486. t.Fatalf("Destination folder should contain the source file but did not.")
  487. }
  488. }
  489. func TestCopyFileWithTarInvalidSrc(t *testing.T) {
  490. tempFolder, err := ioutil.TempDir("", "docker-archive-test")
  491. if err != nil {
  492. t.Fatal(err)
  493. }
  494. defer os.RemoveAll(tempFolder)
  495. destFolder := filepath.Join(tempFolder, "dest")
  496. err = os.MkdirAll(destFolder, 0740)
  497. if err != nil {
  498. t.Fatal(err)
  499. }
  500. invalidFile := filepath.Join(tempFolder, "doesnotexists")
  501. err = CopyFileWithTar(invalidFile, destFolder)
  502. if err == nil {
  503. t.Fatalf("archiver.CopyWithTar with invalid src path should throw an error.")
  504. }
  505. }
  506. func TestCopyFileWithTarInexistentDestWillCreateIt(t *testing.T) {
  507. tempFolder, err := ioutil.TempDir("", "docker-archive-test")
  508. if err != nil {
  509. t.Fatal(nil)
  510. }
  511. defer os.RemoveAll(tempFolder)
  512. srcFile := filepath.Join(tempFolder, "src")
  513. inexistentDestFolder := filepath.Join(tempFolder, "doesnotexists")
  514. _, err = os.Create(srcFile)
  515. if err != nil {
  516. t.Fatal(err)
  517. }
  518. err = CopyFileWithTar(srcFile, inexistentDestFolder)
  519. if err != nil {
  520. t.Fatalf("CopyWithTar with an inexistent folder shouldn't fail.")
  521. }
  522. _, err = os.Stat(inexistentDestFolder)
  523. if err != nil {
  524. t.Fatalf("CopyWithTar with an inexistent folder should create it.")
  525. }
  526. // FIXME Test the src file and content
  527. }
  528. func TestCopyFileWithTarSrcFolder(t *testing.T) {
  529. folder, err := ioutil.TempDir("", "docker-archive-copyfilewithtar-test")
  530. if err != nil {
  531. t.Fatal(err)
  532. }
  533. defer os.RemoveAll(folder)
  534. dest := filepath.Join(folder, "dest")
  535. src := filepath.Join(folder, "srcfolder")
  536. err = os.MkdirAll(src, 0740)
  537. if err != nil {
  538. t.Fatal(err)
  539. }
  540. err = os.MkdirAll(dest, 0740)
  541. if err != nil {
  542. t.Fatal(err)
  543. }
  544. err = CopyFileWithTar(src, dest)
  545. if err == nil {
  546. t.Fatalf("CopyFileWithTar should throw an error with a folder.")
  547. }
  548. }
  549. func TestCopyFileWithTarSrcFile(t *testing.T) {
  550. folder, err := ioutil.TempDir("", "docker-archive-test")
  551. if err != nil {
  552. t.Fatal(err)
  553. }
  554. defer os.RemoveAll(folder)
  555. dest := filepath.Join(folder, "dest")
  556. srcFolder := filepath.Join(folder, "src")
  557. src := filepath.Join(folder, filepath.Join("src", "src"))
  558. err = os.MkdirAll(srcFolder, 0740)
  559. if err != nil {
  560. t.Fatal(err)
  561. }
  562. err = os.MkdirAll(dest, 0740)
  563. if err != nil {
  564. t.Fatal(err)
  565. }
  566. ioutil.WriteFile(src, []byte("content"), 0777)
  567. err = CopyWithTar(src, dest+"/")
  568. if err != nil {
  569. t.Fatalf("archiver.CopyFileWithTar shouldn't throw an error, %s.", err)
  570. }
  571. _, err = os.Stat(dest)
  572. if err != nil {
  573. t.Fatalf("Destination folder should contain the source file but did not.")
  574. }
  575. }
  576. func TestTarFiles(t *testing.T) {
  577. // TODO Windows: Figure out how to port this test.
  578. if runtime.GOOS == "windows" {
  579. t.Skip("Failing on Windows")
  580. }
  581. // try without hardlinks
  582. if err := checkNoChanges(1000, false); err != nil {
  583. t.Fatal(err)
  584. }
  585. // try with hardlinks
  586. if err := checkNoChanges(1000, true); err != nil {
  587. t.Fatal(err)
  588. }
  589. }
  590. func checkNoChanges(fileNum int, hardlinks bool) error {
  591. srcDir, err := ioutil.TempDir("", "docker-test-srcDir")
  592. if err != nil {
  593. return err
  594. }
  595. defer os.RemoveAll(srcDir)
  596. destDir, err := ioutil.TempDir("", "docker-test-destDir")
  597. if err != nil {
  598. return err
  599. }
  600. defer os.RemoveAll(destDir)
  601. _, err = prepareUntarSourceDirectory(fileNum, srcDir, hardlinks)
  602. if err != nil {
  603. return err
  604. }
  605. err = TarUntar(srcDir, destDir)
  606. if err != nil {
  607. return err
  608. }
  609. changes, err := ChangesDirs(destDir, srcDir)
  610. if err != nil {
  611. return err
  612. }
  613. if len(changes) > 0 {
  614. return fmt.Errorf("with %d files and %v hardlinks: expected 0 changes, got %d", fileNum, hardlinks, len(changes))
  615. }
  616. return nil
  617. }
  618. func tarUntar(t *testing.T, origin string, options *TarOptions) ([]Change, error) {
  619. archive, err := TarWithOptions(origin, options)
  620. if err != nil {
  621. t.Fatal(err)
  622. }
  623. defer archive.Close()
  624. buf := make([]byte, 10)
  625. if _, err := archive.Read(buf); err != nil {
  626. return nil, err
  627. }
  628. wrap := io.MultiReader(bytes.NewReader(buf), archive)
  629. detectedCompression := DetectCompression(buf)
  630. compression := options.Compression
  631. if detectedCompression.Extension() != compression.Extension() {
  632. return nil, fmt.Errorf("Wrong compression detected. Actual compression: %s, found %s", compression.Extension(), detectedCompression.Extension())
  633. }
  634. tmp, err := ioutil.TempDir("", "docker-test-untar")
  635. if err != nil {
  636. return nil, err
  637. }
  638. defer os.RemoveAll(tmp)
  639. if err := Untar(wrap, tmp, nil); err != nil {
  640. return nil, err
  641. }
  642. if _, err := os.Stat(tmp); err != nil {
  643. return nil, err
  644. }
  645. return ChangesDirs(origin, tmp)
  646. }
  647. func TestTarUntar(t *testing.T) {
  648. // TODO Windows: Figure out how to fix this test.
  649. if runtime.GOOS == "windows" {
  650. t.Skip("Failing on Windows")
  651. }
  652. origin, err := ioutil.TempDir("", "docker-test-untar-origin")
  653. if err != nil {
  654. t.Fatal(err)
  655. }
  656. defer os.RemoveAll(origin)
  657. if err := ioutil.WriteFile(filepath.Join(origin, "1"), []byte("hello world"), 0700); err != nil {
  658. t.Fatal(err)
  659. }
  660. if err := ioutil.WriteFile(filepath.Join(origin, "2"), []byte("welcome!"), 0700); err != nil {
  661. t.Fatal(err)
  662. }
  663. if err := ioutil.WriteFile(filepath.Join(origin, "3"), []byte("will be ignored"), 0700); err != nil {
  664. t.Fatal(err)
  665. }
  666. for _, c := range []Compression{
  667. Uncompressed,
  668. Gzip,
  669. } {
  670. changes, err := tarUntar(t, origin, &TarOptions{
  671. Compression: c,
  672. ExcludePatterns: []string{"3"},
  673. })
  674. if err != nil {
  675. t.Fatalf("Error tar/untar for compression %s: %s", c.Extension(), err)
  676. }
  677. if len(changes) != 1 || changes[0].Path != "/3" {
  678. t.Fatalf("Unexpected differences after tarUntar: %v", changes)
  679. }
  680. }
  681. }
  682. func TestTarWithOptions(t *testing.T) {
  683. // TODO Windows: Figure out how to fix this test.
  684. if runtime.GOOS == "windows" {
  685. t.Skip("Failing on Windows")
  686. }
  687. origin, err := ioutil.TempDir("", "docker-test-untar-origin")
  688. if err != nil {
  689. t.Fatal(err)
  690. }
  691. if _, err := ioutil.TempDir(origin, "folder"); err != nil {
  692. t.Fatal(err)
  693. }
  694. defer os.RemoveAll(origin)
  695. if err := ioutil.WriteFile(filepath.Join(origin, "1"), []byte("hello world"), 0700); err != nil {
  696. t.Fatal(err)
  697. }
  698. if err := ioutil.WriteFile(filepath.Join(origin, "2"), []byte("welcome!"), 0700); err != nil {
  699. t.Fatal(err)
  700. }
  701. cases := []struct {
  702. opts *TarOptions
  703. numChanges int
  704. }{
  705. {&TarOptions{IncludeFiles: []string{"1"}}, 2},
  706. {&TarOptions{ExcludePatterns: []string{"2"}}, 1},
  707. {&TarOptions{ExcludePatterns: []string{"1", "folder*"}}, 2},
  708. {&TarOptions{IncludeFiles: []string{"1", "1"}}, 2},
  709. {&TarOptions{IncludeFiles: []string{"1"}, RebaseNames: map[string]string{"1": "test"}}, 4},
  710. }
  711. for _, testCase := range cases {
  712. changes, err := tarUntar(t, origin, testCase.opts)
  713. if err != nil {
  714. t.Fatalf("Error tar/untar when testing inclusion/exclusion: %s", err)
  715. }
  716. if len(changes) != testCase.numChanges {
  717. t.Errorf("Expected %d changes, got %d for %+v:",
  718. testCase.numChanges, len(changes), testCase.opts)
  719. }
  720. }
  721. }
  722. // Some tar archives such as http://haproxy.1wt.eu/download/1.5/src/devel/haproxy-1.5-dev21.tar.gz
  723. // use PAX Global Extended Headers.
  724. // Failing prevents the archives from being uncompressed during ADD
  725. func TestTypeXGlobalHeaderDoesNotFail(t *testing.T) {
  726. hdr := tar.Header{Typeflag: tar.TypeXGlobalHeader}
  727. tmpDir, err := ioutil.TempDir("", "docker-test-archive-pax-test")
  728. if err != nil {
  729. t.Fatal(err)
  730. }
  731. defer os.RemoveAll(tmpDir)
  732. err = createTarFile(filepath.Join(tmpDir, "pax_global_header"), tmpDir, &hdr, nil, true, nil, false)
  733. if err != nil {
  734. t.Fatal(err)
  735. }
  736. }
  737. // Some tar have both GNU specific (huge uid) and Ustar specific (long name) things.
  738. // Not supposed to happen (should use PAX instead of Ustar for long name) but it does and it should still work.
  739. func TestUntarUstarGnuConflict(t *testing.T) {
  740. f, err := os.Open("testdata/broken.tar")
  741. if err != nil {
  742. t.Fatal(err)
  743. }
  744. defer f.Close()
  745. found := false
  746. tr := tar.NewReader(f)
  747. // Iterate through the files in the archive.
  748. for {
  749. hdr, err := tr.Next()
  750. if err == io.EOF {
  751. // end of tar archive
  752. break
  753. }
  754. if err != nil {
  755. t.Fatal(err)
  756. }
  757. if hdr.Name == "root/.cpanm/work/1395823785.24209/Plack-1.0030/blib/man3/Plack::Middleware::LighttpdScriptNameFix.3pm" {
  758. found = true
  759. break
  760. }
  761. }
  762. if !found {
  763. t.Fatalf("%s not found in the archive", "root/.cpanm/work/1395823785.24209/Plack-1.0030/blib/man3/Plack::Middleware::LighttpdScriptNameFix.3pm")
  764. }
  765. }
  766. func prepareUntarSourceDirectory(numberOfFiles int, targetPath string, makeLinks bool) (int, error) {
  767. fileData := []byte("fooo")
  768. for n := 0; n < numberOfFiles; n++ {
  769. fileName := fmt.Sprintf("file-%d", n)
  770. if err := ioutil.WriteFile(filepath.Join(targetPath, fileName), fileData, 0700); err != nil {
  771. return 0, err
  772. }
  773. if makeLinks {
  774. if err := os.Link(filepath.Join(targetPath, fileName), filepath.Join(targetPath, fileName+"-link")); err != nil {
  775. return 0, err
  776. }
  777. }
  778. }
  779. totalSize := numberOfFiles * len(fileData)
  780. return totalSize, nil
  781. }
  782. func BenchmarkTarUntar(b *testing.B) {
  783. origin, err := ioutil.TempDir("", "docker-test-untar-origin")
  784. if err != nil {
  785. b.Fatal(err)
  786. }
  787. tempDir, err := ioutil.TempDir("", "docker-test-untar-destination")
  788. if err != nil {
  789. b.Fatal(err)
  790. }
  791. target := filepath.Join(tempDir, "dest")
  792. n, err := prepareUntarSourceDirectory(100, origin, false)
  793. if err != nil {
  794. b.Fatal(err)
  795. }
  796. defer os.RemoveAll(origin)
  797. defer os.RemoveAll(tempDir)
  798. b.ResetTimer()
  799. b.SetBytes(int64(n))
  800. for n := 0; n < b.N; n++ {
  801. err := TarUntar(origin, target)
  802. if err != nil {
  803. b.Fatal(err)
  804. }
  805. os.RemoveAll(target)
  806. }
  807. }
  808. func BenchmarkTarUntarWithLinks(b *testing.B) {
  809. origin, err := ioutil.TempDir("", "docker-test-untar-origin")
  810. if err != nil {
  811. b.Fatal(err)
  812. }
  813. tempDir, err := ioutil.TempDir("", "docker-test-untar-destination")
  814. if err != nil {
  815. b.Fatal(err)
  816. }
  817. target := filepath.Join(tempDir, "dest")
  818. n, err := prepareUntarSourceDirectory(100, origin, true)
  819. if err != nil {
  820. b.Fatal(err)
  821. }
  822. defer os.RemoveAll(origin)
  823. defer os.RemoveAll(tempDir)
  824. b.ResetTimer()
  825. b.SetBytes(int64(n))
  826. for n := 0; n < b.N; n++ {
  827. err := TarUntar(origin, target)
  828. if err != nil {
  829. b.Fatal(err)
  830. }
  831. os.RemoveAll(target)
  832. }
  833. }
  834. func TestUntarInvalidFilenames(t *testing.T) {
  835. // TODO Windows: Figure out how to fix this test.
  836. if runtime.GOOS == "windows" {
  837. t.Skip("Passes but hits breakoutError: platform and architecture is not supported")
  838. }
  839. for i, headers := range [][]*tar.Header{
  840. {
  841. {
  842. Name: "../victim/dotdot",
  843. Typeflag: tar.TypeReg,
  844. Mode: 0644,
  845. },
  846. },
  847. {
  848. {
  849. // Note the leading slash
  850. Name: "/../victim/slash-dotdot",
  851. Typeflag: tar.TypeReg,
  852. Mode: 0644,
  853. },
  854. },
  855. } {
  856. if err := testBreakout("untar", "docker-TestUntarInvalidFilenames", headers); err != nil {
  857. t.Fatalf("i=%d. %v", i, err)
  858. }
  859. }
  860. }
  861. func TestUntarHardlinkToSymlink(t *testing.T) {
  862. // TODO Windows. There may be a way of running this, but turning off for now
  863. if runtime.GOOS == "windows" {
  864. t.Skip("hardlinks on Windows")
  865. }
  866. for i, headers := range [][]*tar.Header{
  867. {
  868. {
  869. Name: "symlink1",
  870. Typeflag: tar.TypeSymlink,
  871. Linkname: "regfile",
  872. Mode: 0644,
  873. },
  874. {
  875. Name: "symlink2",
  876. Typeflag: tar.TypeLink,
  877. Linkname: "symlink1",
  878. Mode: 0644,
  879. },
  880. {
  881. Name: "regfile",
  882. Typeflag: tar.TypeReg,
  883. Mode: 0644,
  884. },
  885. },
  886. } {
  887. if err := testBreakout("untar", "docker-TestUntarHardlinkToSymlink", headers); err != nil {
  888. t.Fatalf("i=%d. %v", i, err)
  889. }
  890. }
  891. }
  892. func TestUntarInvalidHardlink(t *testing.T) {
  893. // TODO Windows. There may be a way of running this, but turning off for now
  894. if runtime.GOOS == "windows" {
  895. t.Skip("hardlinks on Windows")
  896. }
  897. for i, headers := range [][]*tar.Header{
  898. { // try reading victim/hello (../)
  899. {
  900. Name: "dotdot",
  901. Typeflag: tar.TypeLink,
  902. Linkname: "../victim/hello",
  903. Mode: 0644,
  904. },
  905. },
  906. { // try reading victim/hello (/../)
  907. {
  908. Name: "slash-dotdot",
  909. Typeflag: tar.TypeLink,
  910. // Note the leading slash
  911. Linkname: "/../victim/hello",
  912. Mode: 0644,
  913. },
  914. },
  915. { // try writing victim/file
  916. {
  917. Name: "loophole-victim",
  918. Typeflag: tar.TypeLink,
  919. Linkname: "../victim",
  920. Mode: 0755,
  921. },
  922. {
  923. Name: "loophole-victim/file",
  924. Typeflag: tar.TypeReg,
  925. Mode: 0644,
  926. },
  927. },
  928. { // try reading victim/hello (hardlink, symlink)
  929. {
  930. Name: "loophole-victim",
  931. Typeflag: tar.TypeLink,
  932. Linkname: "../victim",
  933. Mode: 0755,
  934. },
  935. {
  936. Name: "symlink",
  937. Typeflag: tar.TypeSymlink,
  938. Linkname: "loophole-victim/hello",
  939. Mode: 0644,
  940. },
  941. },
  942. { // Try reading victim/hello (hardlink, hardlink)
  943. {
  944. Name: "loophole-victim",
  945. Typeflag: tar.TypeLink,
  946. Linkname: "../victim",
  947. Mode: 0755,
  948. },
  949. {
  950. Name: "hardlink",
  951. Typeflag: tar.TypeLink,
  952. Linkname: "loophole-victim/hello",
  953. Mode: 0644,
  954. },
  955. },
  956. { // Try removing victim directory (hardlink)
  957. {
  958. Name: "loophole-victim",
  959. Typeflag: tar.TypeLink,
  960. Linkname: "../victim",
  961. Mode: 0755,
  962. },
  963. {
  964. Name: "loophole-victim",
  965. Typeflag: tar.TypeReg,
  966. Mode: 0644,
  967. },
  968. },
  969. } {
  970. if err := testBreakout("untar", "docker-TestUntarInvalidHardlink", headers); err != nil {
  971. t.Fatalf("i=%d. %v", i, err)
  972. }
  973. }
  974. }
  975. func TestUntarInvalidSymlink(t *testing.T) {
  976. // TODO Windows. There may be a way of running this, but turning off for now
  977. if runtime.GOOS == "windows" {
  978. t.Skip("hardlinks on Windows")
  979. }
  980. for i, headers := range [][]*tar.Header{
  981. { // try reading victim/hello (../)
  982. {
  983. Name: "dotdot",
  984. Typeflag: tar.TypeSymlink,
  985. Linkname: "../victim/hello",
  986. Mode: 0644,
  987. },
  988. },
  989. { // try reading victim/hello (/../)
  990. {
  991. Name: "slash-dotdot",
  992. Typeflag: tar.TypeSymlink,
  993. // Note the leading slash
  994. Linkname: "/../victim/hello",
  995. Mode: 0644,
  996. },
  997. },
  998. { // try writing victim/file
  999. {
  1000. Name: "loophole-victim",
  1001. Typeflag: tar.TypeSymlink,
  1002. Linkname: "../victim",
  1003. Mode: 0755,
  1004. },
  1005. {
  1006. Name: "loophole-victim/file",
  1007. Typeflag: tar.TypeReg,
  1008. Mode: 0644,
  1009. },
  1010. },
  1011. { // try reading victim/hello (symlink, symlink)
  1012. {
  1013. Name: "loophole-victim",
  1014. Typeflag: tar.TypeSymlink,
  1015. Linkname: "../victim",
  1016. Mode: 0755,
  1017. },
  1018. {
  1019. Name: "symlink",
  1020. Typeflag: tar.TypeSymlink,
  1021. Linkname: "loophole-victim/hello",
  1022. Mode: 0644,
  1023. },
  1024. },
  1025. { // try reading victim/hello (symlink, hardlink)
  1026. {
  1027. Name: "loophole-victim",
  1028. Typeflag: tar.TypeSymlink,
  1029. Linkname: "../victim",
  1030. Mode: 0755,
  1031. },
  1032. {
  1033. Name: "hardlink",
  1034. Typeflag: tar.TypeLink,
  1035. Linkname: "loophole-victim/hello",
  1036. Mode: 0644,
  1037. },
  1038. },
  1039. { // try removing victim directory (symlink)
  1040. {
  1041. Name: "loophole-victim",
  1042. Typeflag: tar.TypeSymlink,
  1043. Linkname: "../victim",
  1044. Mode: 0755,
  1045. },
  1046. {
  1047. Name: "loophole-victim",
  1048. Typeflag: tar.TypeReg,
  1049. Mode: 0644,
  1050. },
  1051. },
  1052. { // try writing to victim/newdir/newfile with a symlink in the path
  1053. {
  1054. // this header needs to be before the next one, or else there is an error
  1055. Name: "dir/loophole",
  1056. Typeflag: tar.TypeSymlink,
  1057. Linkname: "../../victim",
  1058. Mode: 0755,
  1059. },
  1060. {
  1061. Name: "dir/loophole/newdir/newfile",
  1062. Typeflag: tar.TypeReg,
  1063. Mode: 0644,
  1064. },
  1065. },
  1066. } {
  1067. if err := testBreakout("untar", "docker-TestUntarInvalidSymlink", headers); err != nil {
  1068. t.Fatalf("i=%d. %v", i, err)
  1069. }
  1070. }
  1071. }
  1072. func TestTempArchiveCloseMultipleTimes(t *testing.T) {
  1073. reader := ioutil.NopCloser(strings.NewReader("hello"))
  1074. tempArchive, err := NewTempArchive(reader, "")
  1075. buf := make([]byte, 10)
  1076. n, err := tempArchive.Read(buf)
  1077. if n != 5 {
  1078. t.Fatalf("Expected to read 5 bytes. Read %d instead", n)
  1079. }
  1080. for i := 0; i < 3; i++ {
  1081. if err = tempArchive.Close(); err != nil {
  1082. t.Fatalf("i=%d. Unexpected error closing temp archive: %v", i, err)
  1083. }
  1084. }
  1085. }
  1086. func TestReplaceFileTarWrapper(t *testing.T) {
  1087. filesInArchive := 20
  1088. testcases := []struct {
  1089. doc string
  1090. filename string
  1091. modifier TarModifierFunc
  1092. expected string
  1093. fileCount int
  1094. }{
  1095. {
  1096. doc: "Modifier creates a new file",
  1097. filename: "newfile",
  1098. modifier: createModifier(t),
  1099. expected: "the new content",
  1100. fileCount: filesInArchive + 1,
  1101. },
  1102. {
  1103. doc: "Modifier replaces a file",
  1104. filename: "file-2",
  1105. modifier: createOrReplaceModifier,
  1106. expected: "the new content",
  1107. fileCount: filesInArchive,
  1108. },
  1109. {
  1110. doc: "Modifier replaces the last file",
  1111. filename: fmt.Sprintf("file-%d", filesInArchive-1),
  1112. modifier: createOrReplaceModifier,
  1113. expected: "the new content",
  1114. fileCount: filesInArchive,
  1115. },
  1116. {
  1117. doc: "Modifier appends to a file",
  1118. filename: "file-3",
  1119. modifier: appendModifier,
  1120. expected: "fooo\nnext line",
  1121. fileCount: filesInArchive,
  1122. },
  1123. }
  1124. for _, testcase := range testcases {
  1125. sourceArchive, cleanup := buildSourceArchive(t, filesInArchive)
  1126. defer cleanup()
  1127. resultArchive := ReplaceFileTarWrapper(
  1128. sourceArchive,
  1129. map[string]TarModifierFunc{testcase.filename: testcase.modifier})
  1130. actual := readFileFromArchive(t, resultArchive, testcase.filename, testcase.fileCount, testcase.doc)
  1131. assert.Equal(t, actual, testcase.expected, testcase.doc)
  1132. }
  1133. }
  1134. func buildSourceArchive(t *testing.T, numberOfFiles int) (io.ReadCloser, func()) {
  1135. srcDir, err := ioutil.TempDir("", "docker-test-srcDir")
  1136. assert.NilError(t, err)
  1137. _, err = prepareUntarSourceDirectory(numberOfFiles, srcDir, false)
  1138. assert.NilError(t, err)
  1139. sourceArchive, err := TarWithOptions(srcDir, &TarOptions{})
  1140. assert.NilError(t, err)
  1141. return sourceArchive, func() {
  1142. os.RemoveAll(srcDir)
  1143. sourceArchive.Close()
  1144. }
  1145. }
  1146. func createOrReplaceModifier(path string, header *tar.Header, content io.Reader) (*tar.Header, []byte, error) {
  1147. return &tar.Header{
  1148. Mode: 0600,
  1149. Typeflag: tar.TypeReg,
  1150. }, []byte("the new content"), nil
  1151. }
  1152. func createModifier(t *testing.T) TarModifierFunc {
  1153. return func(path string, header *tar.Header, content io.Reader) (*tar.Header, []byte, error) {
  1154. assert.Nil(t, content)
  1155. return createOrReplaceModifier(path, header, content)
  1156. }
  1157. }
  1158. func appendModifier(path string, header *tar.Header, content io.Reader) (*tar.Header, []byte, error) {
  1159. buffer := bytes.Buffer{}
  1160. if content != nil {
  1161. if _, err := buffer.ReadFrom(content); err != nil {
  1162. return nil, nil, err
  1163. }
  1164. }
  1165. buffer.WriteString("\nnext line")
  1166. return &tar.Header{Mode: 0600, Typeflag: tar.TypeReg}, buffer.Bytes(), nil
  1167. }
  1168. func readFileFromArchive(t *testing.T, archive io.ReadCloser, name string, expectedCount int, doc string) string {
  1169. destDir, err := ioutil.TempDir("", "docker-test-destDir")
  1170. assert.NilError(t, err)
  1171. defer os.RemoveAll(destDir)
  1172. err = Untar(archive, destDir, nil)
  1173. assert.NilError(t, err)
  1174. files, _ := ioutil.ReadDir(destDir)
  1175. assert.Equal(t, len(files), expectedCount, doc)
  1176. content, err := ioutil.ReadFile(filepath.Join(destDir, name))
  1177. assert.NilError(t, err)
  1178. return string(content)
  1179. }