archive.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. package docker
  2. import (
  3. "bufio"
  4. "errors"
  5. "fmt"
  6. "github.com/dotcloud/docker/utils"
  7. "io"
  8. "io/ioutil"
  9. "os"
  10. "os/exec"
  11. )
  12. type Archive io.Reader
  13. type Compression uint32
  14. const (
  15. Uncompressed Compression = iota
  16. Bzip2
  17. Gzip
  18. Xz
  19. )
  20. func DetectCompression(source []byte) Compression {
  21. for _, c := range source[:10] {
  22. utils.Debugf("%x", c)
  23. }
  24. sourceLen := len(source)
  25. for compression, m := range map[Compression][]byte{
  26. Bzip2: {0x42, 0x5A, 0x68},
  27. Gzip: {0x1F, 0x8B, 0x08},
  28. Xz: {0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00},
  29. } {
  30. fail := false
  31. if len(m) > sourceLen {
  32. utils.Debugf("Len too short")
  33. continue
  34. }
  35. i := 0
  36. for _, b := range m {
  37. if b != source[i] {
  38. fail = true
  39. break
  40. }
  41. i++
  42. }
  43. if !fail {
  44. return compression
  45. }
  46. }
  47. return Uncompressed
  48. }
  49. func (compression *Compression) Flag() string {
  50. switch *compression {
  51. case Bzip2:
  52. return "j"
  53. case Gzip:
  54. return "z"
  55. case Xz:
  56. return "J"
  57. }
  58. return ""
  59. }
  60. func (compression *Compression) Extension() string {
  61. switch *compression {
  62. case Uncompressed:
  63. return "tar"
  64. case Bzip2:
  65. return "tar.bz2"
  66. case Gzip:
  67. return "tar.gz"
  68. case Xz:
  69. return "tar.xz"
  70. }
  71. return ""
  72. }
  73. func Tar(path string, compression Compression) (io.Reader, error) {
  74. return CmdStream(exec.Command("tar", "-f", "-", "-C", path, "-c"+compression.Flag(), "."))
  75. }
  76. // FIXME: specify behavior when target path exists vs. doesn't exist.
  77. func Untar(archive io.Reader, path string) error {
  78. bufferedArchive := bufio.NewReaderSize(archive, 10)
  79. buf, err := bufferedArchive.Peek(10)
  80. if err != nil {
  81. return err
  82. }
  83. compression := DetectCompression(buf)
  84. utils.Debugf("Archive compression detected: %s", compression.Extension())
  85. cmd := exec.Command("tar", "-f", "-", "-C", path, "-x"+compression.Flag())
  86. cmd.Stdin = bufferedArchive
  87. // Hardcode locale environment for predictable outcome regardless of host configuration.
  88. // (see https://github.com/dotcloud/docker/issues/355)
  89. cmd.Env = []string{"LANG=en_US.utf-8", "LC_ALL=en_US.utf-8"}
  90. output, err := cmd.CombinedOutput()
  91. if err != nil {
  92. return fmt.Errorf("%s: %s", err, output)
  93. }
  94. return nil
  95. }
  96. // UntarPath is a convenience function which looks for an archive
  97. // at filesystem path `src`, and unpacks it at `dst`.
  98. func UntarPath(src, dst string) error {
  99. if archive, err := os.Open(src); err != nil {
  100. return err
  101. } else if err := Untar(archive, dst); err != nil {
  102. return err
  103. }
  104. return nil
  105. }
  106. // CopyWithTar creates a tar archive of filesystem path `src`, and
  107. // unpacks it at filesystem path `dst`.
  108. // The archive is streamed directly with fixed buffering and no
  109. // intermediary disk IO.
  110. //
  111. func CopyWithTar(src, dst string) error {
  112. archive, err := Tar(src, Uncompressed)
  113. if err != nil {
  114. return err
  115. }
  116. return Untar(archive, dst)
  117. }
  118. // CmdStream executes a command, and returns its stdout as a stream.
  119. // If the command fails to run or doesn't complete successfully, an error
  120. // will be returned, including anything written on stderr.
  121. func CmdStream(cmd *exec.Cmd) (io.Reader, error) {
  122. stdout, err := cmd.StdoutPipe()
  123. if err != nil {
  124. return nil, err
  125. }
  126. stderr, err := cmd.StderrPipe()
  127. if err != nil {
  128. return nil, err
  129. }
  130. pipeR, pipeW := io.Pipe()
  131. errChan := make(chan []byte)
  132. // Collect stderr, we will use it in case of an error
  133. go func() {
  134. errText, e := ioutil.ReadAll(stderr)
  135. if e != nil {
  136. errText = []byte("(...couldn't fetch stderr: " + e.Error() + ")")
  137. }
  138. errChan <- errText
  139. }()
  140. // Copy stdout to the returned pipe
  141. go func() {
  142. _, err := io.Copy(pipeW, stdout)
  143. if err != nil {
  144. pipeW.CloseWithError(err)
  145. }
  146. errText := <-errChan
  147. if err := cmd.Wait(); err != nil {
  148. pipeW.CloseWithError(errors.New(err.Error() + ": " + string(errText)))
  149. } else {
  150. pipeW.Close()
  151. }
  152. }()
  153. // Run the command and return the pipe
  154. if err := cmd.Start(); err != nil {
  155. return nil, err
  156. }
  157. return pipeR, nil
  158. }
  159. // NewTempArchive reads the content of src into a temporary file, and returns the contents
  160. // of that file as an archive. The archive can only be read once - as soon as reading completes,
  161. // the file will be deleted.
  162. func NewTempArchive(src Archive, dir string) (*TempArchive, error) {
  163. f, err := ioutil.TempFile(dir, "")
  164. if err != nil {
  165. return nil, err
  166. }
  167. if _, err := io.Copy(f, src); err != nil {
  168. return nil, err
  169. }
  170. if _, err := f.Seek(0, 0); err != nil {
  171. return nil, err
  172. }
  173. st, err := f.Stat()
  174. if err != nil {
  175. return nil, err
  176. }
  177. size := st.Size()
  178. return &TempArchive{f, size}, nil
  179. }
  180. type TempArchive struct {
  181. *os.File
  182. Size int64 // Pre-computed from Stat().Size() as a convenience
  183. }
  184. func (archive *TempArchive) Read(data []byte) (int, error) {
  185. n, err := archive.File.Read(data)
  186. if err != nil {
  187. os.Remove(archive.File.Name())
  188. }
  189. return n, err
  190. }