archive.go 9.0 KB

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