archive.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  1. package archive
  2. import (
  3. "bufio"
  4. "bytes"
  5. "compress/bzip2"
  6. "compress/gzip"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "io/ioutil"
  11. "os"
  12. "os/exec"
  13. "path"
  14. "path/filepath"
  15. "strings"
  16. "syscall"
  17. "github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
  18. log "github.com/Sirupsen/logrus"
  19. "github.com/docker/docker/pkg/fileutils"
  20. "github.com/docker/docker/pkg/pools"
  21. "github.com/docker/docker/pkg/promise"
  22. "github.com/docker/docker/pkg/system"
  23. )
  24. type (
  25. Archive io.ReadCloser
  26. ArchiveReader io.Reader
  27. Compression int
  28. TarOptions struct {
  29. Includes []string
  30. Excludes []string
  31. Compression Compression
  32. NoLchown bool
  33. Name string
  34. }
  35. // Archiver allows the reuse of most utility functions of this package
  36. // with a pluggable Untar function.
  37. Archiver struct {
  38. Untar func(io.Reader, string, *TarOptions) error
  39. }
  40. )
  41. var (
  42. ErrNotImplemented = errors.New("Function not implemented")
  43. defaultArchiver = &Archiver{Untar}
  44. )
  45. const (
  46. Uncompressed Compression = iota
  47. Bzip2
  48. Gzip
  49. Xz
  50. )
  51. func IsArchive(header []byte) bool {
  52. compression := DetectCompression(header)
  53. if compression != Uncompressed {
  54. return true
  55. }
  56. r := tar.NewReader(bytes.NewBuffer(header))
  57. _, err := r.Next()
  58. return err == nil
  59. }
  60. func DetectCompression(source []byte) Compression {
  61. for compression, m := range map[Compression][]byte{
  62. Bzip2: {0x42, 0x5A, 0x68},
  63. Gzip: {0x1F, 0x8B, 0x08},
  64. Xz: {0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00},
  65. } {
  66. if len(source) < len(m) {
  67. log.Debugf("Len too short")
  68. continue
  69. }
  70. if bytes.Compare(m, source[:len(m)]) == 0 {
  71. return compression
  72. }
  73. }
  74. return Uncompressed
  75. }
  76. func xzDecompress(archive io.Reader) (io.ReadCloser, error) {
  77. args := []string{"xz", "-d", "-c", "-q"}
  78. return CmdStream(exec.Command(args[0], args[1:]...), archive)
  79. }
  80. func DecompressStream(archive io.Reader) (io.ReadCloser, error) {
  81. p := pools.BufioReader32KPool
  82. buf := p.Get(archive)
  83. bs, err := buf.Peek(10)
  84. if err != nil {
  85. return nil, err
  86. }
  87. log.Debugf("[tar autodetect] n: %v", bs)
  88. compression := DetectCompression(bs)
  89. switch compression {
  90. case Uncompressed:
  91. readBufWrapper := p.NewReadCloserWrapper(buf, buf)
  92. return readBufWrapper, nil
  93. case Gzip:
  94. gzReader, err := gzip.NewReader(buf)
  95. if err != nil {
  96. return nil, err
  97. }
  98. readBufWrapper := p.NewReadCloserWrapper(buf, gzReader)
  99. return readBufWrapper, nil
  100. case Bzip2:
  101. bz2Reader := bzip2.NewReader(buf)
  102. readBufWrapper := p.NewReadCloserWrapper(buf, bz2Reader)
  103. return readBufWrapper, nil
  104. case Xz:
  105. xzReader, err := xzDecompress(buf)
  106. if err != nil {
  107. return nil, err
  108. }
  109. readBufWrapper := p.NewReadCloserWrapper(buf, xzReader)
  110. return readBufWrapper, nil
  111. default:
  112. return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension())
  113. }
  114. }
  115. func CompressStream(dest io.WriteCloser, compression Compression) (io.WriteCloser, error) {
  116. p := pools.BufioWriter32KPool
  117. buf := p.Get(dest)
  118. switch compression {
  119. case Uncompressed:
  120. writeBufWrapper := p.NewWriteCloserWrapper(buf, buf)
  121. return writeBufWrapper, nil
  122. case Gzip:
  123. gzWriter := gzip.NewWriter(dest)
  124. writeBufWrapper := p.NewWriteCloserWrapper(buf, gzWriter)
  125. return writeBufWrapper, nil
  126. case Bzip2, Xz:
  127. // archive/bzip2 does not support writing, and there is no xz support at all
  128. // However, this is not a problem as docker only currently generates gzipped tars
  129. return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension())
  130. default:
  131. return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension())
  132. }
  133. }
  134. func (compression *Compression) Extension() string {
  135. switch *compression {
  136. case Uncompressed:
  137. return "tar"
  138. case Bzip2:
  139. return "tar.bz2"
  140. case Gzip:
  141. return "tar.gz"
  142. case Xz:
  143. return "tar.xz"
  144. }
  145. return ""
  146. }
  147. type tarAppender struct {
  148. TarWriter *tar.Writer
  149. Buffer *bufio.Writer
  150. // for hardlink mapping
  151. SeenFiles map[uint64]string
  152. }
  153. func (ta *tarAppender) addTarFile(path, name string) error {
  154. fi, err := os.Lstat(path)
  155. if err != nil {
  156. return err
  157. }
  158. link := ""
  159. if fi.Mode()&os.ModeSymlink != 0 {
  160. if link, err = os.Readlink(path); err != nil {
  161. return err
  162. }
  163. }
  164. hdr, err := tar.FileInfoHeader(fi, link)
  165. if err != nil {
  166. return err
  167. }
  168. if fi.IsDir() && !strings.HasSuffix(name, "/") {
  169. name = name + "/"
  170. }
  171. hdr.Name = name
  172. nlink, inode, err := setHeaderForSpecialDevice(hdr, ta, name, fi.Sys())
  173. if err != nil {
  174. return err
  175. }
  176. // if it's a regular file and has more than 1 link,
  177. // it's hardlinked, so set the type flag accordingly
  178. if fi.Mode().IsRegular() && nlink > 1 {
  179. // a link should have a name that it links too
  180. // and that linked name should be first in the tar archive
  181. if oldpath, ok := ta.SeenFiles[inode]; ok {
  182. hdr.Typeflag = tar.TypeLink
  183. hdr.Linkname = oldpath
  184. hdr.Size = 0 // This Must be here for the writer math to add up!
  185. } else {
  186. ta.SeenFiles[inode] = name
  187. }
  188. }
  189. capability, _ := system.Lgetxattr(path, "security.capability")
  190. if capability != nil {
  191. hdr.Xattrs = make(map[string]string)
  192. hdr.Xattrs["security.capability"] = string(capability)
  193. }
  194. if err := ta.TarWriter.WriteHeader(hdr); err != nil {
  195. return err
  196. }
  197. if hdr.Typeflag == tar.TypeReg {
  198. file, err := os.Open(path)
  199. if err != nil {
  200. return err
  201. }
  202. ta.Buffer.Reset(ta.TarWriter)
  203. defer ta.Buffer.Reset(nil)
  204. _, err = io.Copy(ta.Buffer, file)
  205. file.Close()
  206. if err != nil {
  207. return err
  208. }
  209. err = ta.Buffer.Flush()
  210. if err != nil {
  211. return err
  212. }
  213. }
  214. return nil
  215. }
  216. func createTarFile(path, extractDir string, hdr *tar.Header, reader io.Reader, Lchown bool) error {
  217. // hdr.Mode is in linux format, which we can use for sycalls,
  218. // but for os.Foo() calls we need the mode converted to os.FileMode,
  219. // so use hdrInfo.Mode() (they differ for e.g. setuid bits)
  220. hdrInfo := hdr.FileInfo()
  221. switch hdr.Typeflag {
  222. case tar.TypeDir:
  223. // Create directory unless it exists as a directory already.
  224. // In that case we just want to merge the two
  225. if fi, err := os.Lstat(path); !(err == nil && fi.IsDir()) {
  226. if err := os.Mkdir(path, hdrInfo.Mode()); err != nil {
  227. return err
  228. }
  229. }
  230. case tar.TypeReg, tar.TypeRegA:
  231. // Source is regular file
  232. file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, hdrInfo.Mode())
  233. if err != nil {
  234. return err
  235. }
  236. if _, err := io.Copy(file, reader); err != nil {
  237. file.Close()
  238. return err
  239. }
  240. file.Close()
  241. case tar.TypeBlock, tar.TypeChar, tar.TypeFifo:
  242. mode := uint32(hdr.Mode & 07777)
  243. switch hdr.Typeflag {
  244. case tar.TypeBlock:
  245. mode |= syscall.S_IFBLK
  246. case tar.TypeChar:
  247. mode |= syscall.S_IFCHR
  248. case tar.TypeFifo:
  249. mode |= syscall.S_IFIFO
  250. }
  251. if err := system.Mknod(path, mode, int(system.Mkdev(hdr.Devmajor, hdr.Devminor))); err != nil {
  252. return err
  253. }
  254. case tar.TypeLink:
  255. if err := os.Link(filepath.Join(extractDir, hdr.Linkname), path); err != nil {
  256. return err
  257. }
  258. case tar.TypeSymlink:
  259. if err := os.Symlink(hdr.Linkname, path); err != nil {
  260. return err
  261. }
  262. case tar.TypeXGlobalHeader:
  263. log.Debugf("PAX Global Extended Headers found and ignored")
  264. return nil
  265. default:
  266. return fmt.Errorf("Unhandled tar header type %d\n", hdr.Typeflag)
  267. }
  268. if err := os.Lchown(path, hdr.Uid, hdr.Gid); err != nil && Lchown {
  269. return err
  270. }
  271. for key, value := range hdr.Xattrs {
  272. if err := system.Lsetxattr(path, key, []byte(value), 0); err != nil {
  273. return err
  274. }
  275. }
  276. // There is no LChmod, so ignore mode for symlink. Also, this
  277. // must happen after chown, as that can modify the file mode
  278. if hdr.Typeflag != tar.TypeSymlink {
  279. if err := os.Chmod(path, hdrInfo.Mode()); err != nil {
  280. return err
  281. }
  282. }
  283. ts := []syscall.Timespec{timeToTimespec(hdr.AccessTime), timeToTimespec(hdr.ModTime)}
  284. // syscall.UtimesNano doesn't support a NOFOLLOW flag atm, and
  285. if hdr.Typeflag != tar.TypeSymlink {
  286. if err := system.UtimesNano(path, ts); err != nil && err != system.ErrNotSupportedPlatform {
  287. return err
  288. }
  289. } else {
  290. if err := system.LUtimesNano(path, ts); err != nil && err != system.ErrNotSupportedPlatform {
  291. return err
  292. }
  293. }
  294. return nil
  295. }
  296. // Tar creates an archive from the directory at `path`, and returns it as a
  297. // stream of bytes.
  298. func Tar(path string, compression Compression) (io.ReadCloser, error) {
  299. return TarWithOptions(path, &TarOptions{Compression: compression})
  300. }
  301. func escapeName(name string) string {
  302. escaped := make([]byte, 0)
  303. for i, c := range []byte(name) {
  304. if i == 0 && c == '/' {
  305. continue
  306. }
  307. // all printable chars except "-" which is 0x2d
  308. if (0x20 <= c && c <= 0x7E) && c != 0x2d {
  309. escaped = append(escaped, c)
  310. } else {
  311. escaped = append(escaped, fmt.Sprintf("\\%03o", c)...)
  312. }
  313. }
  314. return string(escaped)
  315. }
  316. // TarWithOptions creates an archive from the directory at `path`, only including files whose relative
  317. // paths are included in `options.Includes` (if non-nil) or not in `options.Excludes`.
  318. func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error) {
  319. pipeReader, pipeWriter := io.Pipe()
  320. compressWriter, err := CompressStream(pipeWriter, options.Compression)
  321. if err != nil {
  322. return nil, err
  323. }
  324. go func() {
  325. ta := &tarAppender{
  326. TarWriter: tar.NewWriter(compressWriter),
  327. Buffer: pools.BufioWriter32KPool.Get(nil),
  328. SeenFiles: make(map[uint64]string),
  329. }
  330. // this buffer is needed for the duration of this piped stream
  331. defer pools.BufioWriter32KPool.Put(ta.Buffer)
  332. // In general we log errors here but ignore them because
  333. // during e.g. a diff operation the container can continue
  334. // mutating the filesystem and we can see transient errors
  335. // from this
  336. if options.Includes == nil {
  337. options.Includes = []string{"."}
  338. }
  339. var renamedRelFilePath string // For when tar.Options.Name is set
  340. for _, include := range options.Includes {
  341. filepath.Walk(filepath.Join(srcPath, include), func(filePath string, f os.FileInfo, err error) error {
  342. if err != nil {
  343. log.Debugf("Tar: Can't stat file %s to tar: %s", srcPath, err)
  344. return nil
  345. }
  346. relFilePath, err := filepath.Rel(srcPath, filePath)
  347. if err != nil || (relFilePath == "." && f.IsDir()) {
  348. // Error getting relative path OR we are looking
  349. // at the root path. Skip in both situations.
  350. return nil
  351. }
  352. skip, err := fileutils.Matches(relFilePath, options.Excludes)
  353. if err != nil {
  354. log.Debugf("Error matching %s", relFilePath, err)
  355. return err
  356. }
  357. if skip {
  358. if f.IsDir() {
  359. return filepath.SkipDir
  360. }
  361. return nil
  362. }
  363. // Rename the base resource
  364. if options.Name != "" && filePath == srcPath+"/"+filepath.Base(relFilePath) {
  365. renamedRelFilePath = relFilePath
  366. }
  367. // Set this to make sure the items underneath also get renamed
  368. if options.Name != "" {
  369. relFilePath = strings.Replace(relFilePath, renamedRelFilePath, options.Name, 1)
  370. }
  371. if err := ta.addTarFile(filePath, relFilePath); err != nil {
  372. log.Debugf("Can't add file %s to tar: %s", srcPath, err)
  373. }
  374. return nil
  375. })
  376. }
  377. // Make sure to check the error on Close.
  378. if err := ta.TarWriter.Close(); err != nil {
  379. log.Debugf("Can't close tar writer: %s", err)
  380. }
  381. if err := compressWriter.Close(); err != nil {
  382. log.Debugf("Can't close compress writer: %s", err)
  383. }
  384. if err := pipeWriter.Close(); err != nil {
  385. log.Debugf("Can't close pipe writer: %s", err)
  386. }
  387. }()
  388. return pipeReader, nil
  389. }
  390. // Untar reads a stream of bytes from `archive`, parses it as a tar archive,
  391. // and unpacks it into the directory at `dest`.
  392. // The archive may be compressed with one of the following algorithms:
  393. // identity (uncompressed), gzip, bzip2, xz.
  394. // FIXME: specify behavior when target path exists vs. doesn't exist.
  395. func Untar(archive io.Reader, dest string, options *TarOptions) error {
  396. if options == nil {
  397. options = &TarOptions{}
  398. }
  399. if archive == nil {
  400. return fmt.Errorf("Empty archive")
  401. }
  402. if options.Excludes == nil {
  403. options.Excludes = []string{}
  404. }
  405. decompressedArchive, err := DecompressStream(archive)
  406. if err != nil {
  407. return err
  408. }
  409. defer decompressedArchive.Close()
  410. tr := tar.NewReader(decompressedArchive)
  411. trBuf := pools.BufioReader32KPool.Get(nil)
  412. defer pools.BufioReader32KPool.Put(trBuf)
  413. var dirs []*tar.Header
  414. // Iterate through the files in the archive.
  415. loop:
  416. for {
  417. hdr, err := tr.Next()
  418. if err == io.EOF {
  419. // end of tar archive
  420. break
  421. }
  422. if err != nil {
  423. return err
  424. }
  425. // Normalize name, for safety and for a simple is-root check
  426. hdr.Name = filepath.Clean(hdr.Name)
  427. for _, exclude := range options.Excludes {
  428. if strings.HasPrefix(hdr.Name, exclude) {
  429. continue loop
  430. }
  431. }
  432. if !strings.HasSuffix(hdr.Name, "/") {
  433. // Not the root directory, ensure that the parent directory exists
  434. parent := filepath.Dir(hdr.Name)
  435. parentPath := filepath.Join(dest, parent)
  436. if _, err := os.Lstat(parentPath); err != nil && os.IsNotExist(err) {
  437. err = os.MkdirAll(parentPath, 0777)
  438. if err != nil {
  439. return err
  440. }
  441. }
  442. }
  443. path := filepath.Join(dest, hdr.Name)
  444. // If path exits we almost always just want to remove and replace it
  445. // The only exception is when it is a directory *and* the file from
  446. // the layer is also a directory. Then we want to merge them (i.e.
  447. // just apply the metadata from the layer).
  448. if fi, err := os.Lstat(path); err == nil {
  449. if fi.IsDir() && hdr.Name == "." {
  450. continue
  451. }
  452. if !(fi.IsDir() && hdr.Typeflag == tar.TypeDir) {
  453. if err := os.RemoveAll(path); err != nil {
  454. return err
  455. }
  456. }
  457. }
  458. trBuf.Reset(tr)
  459. if err := createTarFile(path, dest, hdr, trBuf, !options.NoLchown); err != nil {
  460. return err
  461. }
  462. // Directory mtimes must be handled at the end to avoid further
  463. // file creation in them to modify the directory mtime
  464. if hdr.Typeflag == tar.TypeDir {
  465. dirs = append(dirs, hdr)
  466. }
  467. }
  468. for _, hdr := range dirs {
  469. path := filepath.Join(dest, hdr.Name)
  470. ts := []syscall.Timespec{timeToTimespec(hdr.AccessTime), timeToTimespec(hdr.ModTime)}
  471. if err := syscall.UtimesNano(path, ts); err != nil {
  472. return err
  473. }
  474. }
  475. return nil
  476. }
  477. func (archiver *Archiver) TarUntar(src, dst string) error {
  478. log.Debugf("TarUntar(%s %s)", src, dst)
  479. archive, err := TarWithOptions(src, &TarOptions{Compression: Uncompressed})
  480. if err != nil {
  481. return err
  482. }
  483. defer archive.Close()
  484. return archiver.Untar(archive, dst, nil)
  485. }
  486. // TarUntar is a convenience function which calls Tar and Untar, with the output of one piped into the other.
  487. // If either Tar or Untar fails, TarUntar aborts and returns the error.
  488. func TarUntar(src, dst string) error {
  489. return defaultArchiver.TarUntar(src, dst)
  490. }
  491. func (archiver *Archiver) UntarPath(src, dst string) error {
  492. archive, err := os.Open(src)
  493. if err != nil {
  494. return err
  495. }
  496. defer archive.Close()
  497. if err := archiver.Untar(archive, dst, nil); err != nil {
  498. return err
  499. }
  500. return nil
  501. }
  502. // UntarPath is a convenience function which looks for an archive
  503. // at filesystem path `src`, and unpacks it at `dst`.
  504. func UntarPath(src, dst string) error {
  505. return defaultArchiver.UntarPath(src, dst)
  506. }
  507. func (archiver *Archiver) CopyWithTar(src, dst string) error {
  508. srcSt, err := os.Stat(src)
  509. if err != nil {
  510. return err
  511. }
  512. if !srcSt.IsDir() {
  513. return archiver.CopyFileWithTar(src, dst)
  514. }
  515. // Create dst, copy src's content into it
  516. log.Debugf("Creating dest directory: %s", dst)
  517. if err := os.MkdirAll(dst, 0755); err != nil && !os.IsExist(err) {
  518. return err
  519. }
  520. log.Debugf("Calling TarUntar(%s, %s)", src, dst)
  521. return archiver.TarUntar(src, dst)
  522. }
  523. // CopyWithTar creates a tar archive of filesystem path `src`, and
  524. // unpacks it at filesystem path `dst`.
  525. // The archive is streamed directly with fixed buffering and no
  526. // intermediary disk IO.
  527. func CopyWithTar(src, dst string) error {
  528. return defaultArchiver.CopyWithTar(src, dst)
  529. }
  530. func (archiver *Archiver) CopyFileWithTar(src, dst string) (err error) {
  531. log.Debugf("CopyFileWithTar(%s, %s)", src, dst)
  532. srcSt, err := os.Stat(src)
  533. if err != nil {
  534. return err
  535. }
  536. if srcSt.IsDir() {
  537. return fmt.Errorf("Can't copy a directory")
  538. }
  539. // Clean up the trailing /
  540. if dst[len(dst)-1] == '/' {
  541. dst = path.Join(dst, filepath.Base(src))
  542. }
  543. // Create the holding directory if necessary
  544. if err := os.MkdirAll(filepath.Dir(dst), 0700); err != nil && !os.IsExist(err) {
  545. return err
  546. }
  547. r, w := io.Pipe()
  548. errC := promise.Go(func() error {
  549. defer w.Close()
  550. srcF, err := os.Open(src)
  551. if err != nil {
  552. return err
  553. }
  554. defer srcF.Close()
  555. hdr, err := tar.FileInfoHeader(srcSt, "")
  556. if err != nil {
  557. return err
  558. }
  559. hdr.Name = filepath.Base(dst)
  560. tw := tar.NewWriter(w)
  561. defer tw.Close()
  562. if err := tw.WriteHeader(hdr); err != nil {
  563. return err
  564. }
  565. if _, err := io.Copy(tw, srcF); err != nil {
  566. return err
  567. }
  568. return nil
  569. })
  570. defer func() {
  571. if er := <-errC; err != nil {
  572. err = er
  573. }
  574. }()
  575. return archiver.Untar(r, filepath.Dir(dst), nil)
  576. }
  577. // CopyFileWithTar emulates the behavior of the 'cp' command-line
  578. // for a single file. It copies a regular file from path `src` to
  579. // path `dst`, and preserves all its metadata.
  580. //
  581. // If `dst` ends with a trailing slash '/', the final destination path
  582. // will be `dst/base(src)`.
  583. func CopyFileWithTar(src, dst string) (err error) {
  584. return defaultArchiver.CopyFileWithTar(src, dst)
  585. }
  586. // CmdStream executes a command, and returns its stdout as a stream.
  587. // If the command fails to run or doesn't complete successfully, an error
  588. // will be returned, including anything written on stderr.
  589. func CmdStream(cmd *exec.Cmd, input io.Reader) (io.ReadCloser, error) {
  590. if input != nil {
  591. stdin, err := cmd.StdinPipe()
  592. if err != nil {
  593. return nil, err
  594. }
  595. // Write stdin if any
  596. go func() {
  597. io.Copy(stdin, input)
  598. stdin.Close()
  599. }()
  600. }
  601. stdout, err := cmd.StdoutPipe()
  602. if err != nil {
  603. return nil, err
  604. }
  605. stderr, err := cmd.StderrPipe()
  606. if err != nil {
  607. return nil, err
  608. }
  609. pipeR, pipeW := io.Pipe()
  610. errChan := make(chan []byte)
  611. // Collect stderr, we will use it in case of an error
  612. go func() {
  613. errText, e := ioutil.ReadAll(stderr)
  614. if e != nil {
  615. errText = []byte("(...couldn't fetch stderr: " + e.Error() + ")")
  616. }
  617. errChan <- errText
  618. }()
  619. // Copy stdout to the returned pipe
  620. go func() {
  621. _, err := io.Copy(pipeW, stdout)
  622. if err != nil {
  623. pipeW.CloseWithError(err)
  624. }
  625. errText := <-errChan
  626. if err := cmd.Wait(); err != nil {
  627. pipeW.CloseWithError(fmt.Errorf("%s: %s", err, errText))
  628. } else {
  629. pipeW.Close()
  630. }
  631. }()
  632. // Run the command and return the pipe
  633. if err := cmd.Start(); err != nil {
  634. return nil, err
  635. }
  636. return pipeR, nil
  637. }
  638. // NewTempArchive reads the content of src into a temporary file, and returns the contents
  639. // of that file as an archive. The archive can only be read once - as soon as reading completes,
  640. // the file will be deleted.
  641. func NewTempArchive(src Archive, dir string) (*TempArchive, error) {
  642. f, err := ioutil.TempFile(dir, "")
  643. if err != nil {
  644. return nil, err
  645. }
  646. if _, err := io.Copy(f, src); err != nil {
  647. return nil, err
  648. }
  649. if err = f.Sync(); err != nil {
  650. return nil, err
  651. }
  652. if _, err := f.Seek(0, 0); err != nil {
  653. return nil, err
  654. }
  655. st, err := f.Stat()
  656. if err != nil {
  657. return nil, err
  658. }
  659. size := st.Size()
  660. return &TempArchive{f, size, 0}, nil
  661. }
  662. type TempArchive struct {
  663. *os.File
  664. Size int64 // Pre-computed from Stat().Size() as a convenience
  665. read int64
  666. }
  667. func (archive *TempArchive) Read(data []byte) (int, error) {
  668. n, err := archive.File.Read(data)
  669. archive.read += int64(n)
  670. if err != nil || archive.read == archive.Size {
  671. archive.File.Close()
  672. os.Remove(archive.File.Name())
  673. }
  674. return n, err
  675. }