archive.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. package docker
  2. import (
  3. "archive/tar"
  4. "bufio"
  5. "bytes"
  6. "errors"
  7. "fmt"
  8. "github.com/dotcloud/docker/utils"
  9. "io"
  10. "io/ioutil"
  11. "os"
  12. "os/exec"
  13. "path"
  14. "path/filepath"
  15. )
  16. type Archive io.Reader
  17. type Compression uint32
  18. const (
  19. Uncompressed Compression = iota
  20. Bzip2
  21. Gzip
  22. Xz
  23. )
  24. func DetectCompression(source []byte) Compression {
  25. for _, c := range source[:10] {
  26. utils.Debugf("%x", c)
  27. }
  28. sourceLen := len(source)
  29. for compression, m := range map[Compression][]byte{
  30. Bzip2: {0x42, 0x5A, 0x68},
  31. Gzip: {0x1F, 0x8B, 0x08},
  32. Xz: {0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00},
  33. } {
  34. fail := false
  35. if len(m) > sourceLen {
  36. utils.Debugf("Len too short")
  37. continue
  38. }
  39. i := 0
  40. for _, b := range m {
  41. if b != source[i] {
  42. fail = true
  43. break
  44. }
  45. i++
  46. }
  47. if !fail {
  48. return compression
  49. }
  50. }
  51. return Uncompressed
  52. }
  53. func (compression *Compression) Flag() string {
  54. switch *compression {
  55. case Bzip2:
  56. return "j"
  57. case Gzip:
  58. return "z"
  59. case Xz:
  60. return "J"
  61. }
  62. return ""
  63. }
  64. func (compression *Compression) Extension() string {
  65. switch *compression {
  66. case Uncompressed:
  67. return "tar"
  68. case Bzip2:
  69. return "tar.bz2"
  70. case Gzip:
  71. return "tar.gz"
  72. case Xz:
  73. return "tar.xz"
  74. }
  75. return ""
  76. }
  77. // Tar creates an archive from the directory at `path`, and returns it as a
  78. // stream of bytes.
  79. func Tar(path string, compression Compression) (io.Reader, error) {
  80. return TarFilter(path, compression, nil)
  81. }
  82. // Tar creates an archive from the directory at `path`, only including files whose relative
  83. // paths are included in `filter`. If `filter` is nil, then all files are included.
  84. func TarFilter(path string, compression Compression, filter []string) (io.Reader, error) {
  85. args := []string{"tar", "-f", "-", "-C", path}
  86. if filter == nil {
  87. filter = []string{"."}
  88. }
  89. for _, f := range filter {
  90. args = append(args, "-c"+compression.Flag(), f)
  91. }
  92. return CmdStream(exec.Command(args[0], args[1:]...))
  93. }
  94. // Untar reads a stream of bytes from `archive`, parses it as a tar archive,
  95. // and unpacks it into the directory at `path`.
  96. // The archive may be compressed with one of the following algorithgms:
  97. // identity (uncompressed), gzip, bzip2, xz.
  98. // FIXME: specify behavior when target path exists vs. doesn't exist.
  99. func Untar(archive io.Reader, path string) error {
  100. bufferedArchive := bufio.NewReaderSize(archive, 10)
  101. buf, err := bufferedArchive.Peek(10)
  102. if err != nil {
  103. return err
  104. }
  105. compression := DetectCompression(buf)
  106. utils.Debugf("Archive compression detected: %s", compression.Extension())
  107. cmd := exec.Command("tar", "-f", "-", "-C", path, "-x"+compression.Flag())
  108. cmd.Stdin = bufferedArchive
  109. // Hardcode locale environment for predictable outcome regardless of host configuration.
  110. // (see https://github.com/dotcloud/docker/issues/355)
  111. cmd.Env = []string{"LANG=en_US.utf-8", "LC_ALL=en_US.utf-8"}
  112. output, err := cmd.CombinedOutput()
  113. if err != nil {
  114. return fmt.Errorf("%s: %s", err, output)
  115. }
  116. return nil
  117. }
  118. // TarUntar is a convenience function which calls Tar and Untar, with
  119. // the output of one piped into the other. If either Tar or Untar fails,
  120. // TarUntar aborts and returns the error.
  121. func TarUntar(src string, filter []string, dst string) error {
  122. utils.Debugf("TarUntar(%s %s %s)", src, filter, dst)
  123. archive, err := TarFilter(src, Uncompressed, filter)
  124. if err != nil {
  125. return err
  126. }
  127. return Untar(archive, dst)
  128. }
  129. // UntarPath is a convenience function which looks for an archive
  130. // at filesystem path `src`, and unpacks it at `dst`.
  131. func UntarPath(src, dst string) error {
  132. if archive, err := os.Open(src); err != nil {
  133. return err
  134. } else if err := Untar(archive, dst); err != nil {
  135. return err
  136. }
  137. return nil
  138. }
  139. // CopyWithTar creates a tar archive of filesystem path `src`, and
  140. // unpacks it at filesystem path `dst`.
  141. // The archive is streamed directly with fixed buffering and no
  142. // intermediary disk IO.
  143. //
  144. func CopyWithTar(src, dst string) error {
  145. srcSt, err := os.Stat(src)
  146. if err != nil {
  147. return err
  148. }
  149. if !srcSt.IsDir() {
  150. return CopyFileWithTar(src, dst)
  151. }
  152. // Create dst, copy src's content into it
  153. utils.Debugf("Creating dest directory: %s", dst)
  154. if err := os.MkdirAll(dst, 0700); err != nil && !os.IsExist(err) {
  155. return err
  156. }
  157. utils.Debugf("Calling TarUntar(%s, %s)", src, dst)
  158. return TarUntar(src, nil, dst)
  159. }
  160. // CopyFileWithTar emulates the behavior of the 'cp' command-line
  161. // for a single file. It copies a regular file from path `src` to
  162. // path `dst`, and preserves all its metadata.
  163. //
  164. // If `dst` ends with a trailing slash '/', the final destination path
  165. // will be `dst/base(src)`.
  166. func CopyFileWithTar(src, dst string) error {
  167. utils.Debugf("CopyFileWithTar(%s, %s)", src, dst)
  168. srcSt, err := os.Stat(src)
  169. if err != nil {
  170. return err
  171. }
  172. if srcSt.IsDir() {
  173. return fmt.Errorf("Can't copy a directory")
  174. }
  175. // Clean up the trailing /
  176. if dst[len(dst)-1] == '/' {
  177. dst = path.Join(dst, filepath.Base(src))
  178. }
  179. // Create the holding directory if necessary
  180. if err := os.MkdirAll(filepath.Dir(dst), 0700); err != nil && !os.IsExist(err) {
  181. return err
  182. }
  183. buf := new(bytes.Buffer)
  184. tw := tar.NewWriter(buf)
  185. hdr, err := tar.FileInfoHeader(srcSt, "")
  186. if err != nil {
  187. return err
  188. }
  189. hdr.Name = filepath.Base(dst)
  190. if err := tw.WriteHeader(hdr); err != nil {
  191. return err
  192. }
  193. srcF, err := os.Open(src)
  194. if err != nil {
  195. return err
  196. }
  197. if _, err := io.Copy(tw, srcF); err != nil {
  198. return err
  199. }
  200. tw.Close()
  201. return Untar(buf, filepath.Dir(dst))
  202. }
  203. // CmdStream executes a command, and returns its stdout as a stream.
  204. // If the command fails to run or doesn't complete successfully, an error
  205. // will be returned, including anything written on stderr.
  206. func CmdStream(cmd *exec.Cmd) (io.Reader, error) {
  207. stdout, err := cmd.StdoutPipe()
  208. if err != nil {
  209. return nil, err
  210. }
  211. stderr, err := cmd.StderrPipe()
  212. if err != nil {
  213. return nil, err
  214. }
  215. pipeR, pipeW := io.Pipe()
  216. errChan := make(chan []byte)
  217. // Collect stderr, we will use it in case of an error
  218. go func() {
  219. errText, e := ioutil.ReadAll(stderr)
  220. if e != nil {
  221. errText = []byte("(...couldn't fetch stderr: " + e.Error() + ")")
  222. }
  223. errChan <- errText
  224. }()
  225. // Copy stdout to the returned pipe
  226. go func() {
  227. _, err := io.Copy(pipeW, stdout)
  228. if err != nil {
  229. pipeW.CloseWithError(err)
  230. }
  231. errText := <-errChan
  232. if err := cmd.Wait(); err != nil {
  233. pipeW.CloseWithError(errors.New(err.Error() + ": " + string(errText)))
  234. } else {
  235. pipeW.Close()
  236. }
  237. }()
  238. // Run the command and return the pipe
  239. if err := cmd.Start(); err != nil {
  240. return nil, err
  241. }
  242. return pipeR, nil
  243. }
  244. // NewTempArchive reads the content of src into a temporary file, and returns the contents
  245. // of that file as an archive. The archive can only be read once - as soon as reading completes,
  246. // the file will be deleted.
  247. func NewTempArchive(src Archive, dir string) (*TempArchive, error) {
  248. f, err := ioutil.TempFile(dir, "")
  249. if err != nil {
  250. return nil, err
  251. }
  252. if _, err := io.Copy(f, src); err != nil {
  253. return nil, err
  254. }
  255. if _, err := f.Seek(0, 0); err != nil {
  256. return nil, err
  257. }
  258. st, err := f.Stat()
  259. if err != nil {
  260. return nil, err
  261. }
  262. size := st.Size()
  263. return &TempArchive{f, size}, nil
  264. }
  265. type TempArchive struct {
  266. *os.File
  267. Size int64 // Pre-computed from Stat().Size() as a convenience
  268. }
  269. func (archive *TempArchive) Read(data []byte) (int, error) {
  270. n, err := archive.File.Read(data)
  271. if err != nil {
  272. os.Remove(archive.File.Name())
  273. }
  274. return n, err
  275. }