cp.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. package client
  2. import (
  3. "fmt"
  4. "io"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "golang.org/x/net/context"
  9. Cli "github.com/docker/docker/cli"
  10. "github.com/docker/docker/pkg/archive"
  11. flag "github.com/docker/docker/pkg/mflag"
  12. "github.com/docker/docker/pkg/system"
  13. "github.com/docker/engine-api/types"
  14. )
  15. type copyDirection int
  16. const (
  17. fromContainer copyDirection = (1 << iota)
  18. toContainer
  19. acrossContainers = fromContainer | toContainer
  20. )
  21. type cpConfig struct {
  22. followLink bool
  23. }
  24. // CmdCp copies files/folders to or from a path in a container.
  25. //
  26. // When copying from a container, if DEST_PATH is '-' the data is written as a
  27. // tar archive file to STDOUT.
  28. //
  29. // When copying to a container, if SRC_PATH is '-' the data is read as a tar
  30. // archive file from STDIN, and the destination CONTAINER:DEST_PATH, must specify
  31. // a directory.
  32. //
  33. // Usage:
  34. // docker cp CONTAINER:SRC_PATH DEST_PATH|-
  35. // docker cp SRC_PATH|- CONTAINER:DEST_PATH
  36. func (cli *DockerCli) CmdCp(args ...string) error {
  37. cmd := Cli.Subcmd(
  38. "cp",
  39. []string{"CONTAINER:SRC_PATH DEST_PATH|-", "SRC_PATH|- CONTAINER:DEST_PATH"},
  40. strings.Join([]string{
  41. Cli.DockerCommands["cp"].Description,
  42. "\nUse '-' as the source to read a tar archive from stdin\n",
  43. "and extract it to a directory destination in a container.\n",
  44. "Use '-' as the destination to stream a tar archive of a\n",
  45. "container source to stdout.",
  46. }, ""),
  47. true,
  48. )
  49. followLink := cmd.Bool([]string{"L", "-follow-link"}, false, "Always follow symbol link in SRC_PATH")
  50. cmd.Require(flag.Exact, 2)
  51. cmd.ParseFlags(args, true)
  52. if cmd.Arg(0) == "" {
  53. return fmt.Errorf("source can not be empty")
  54. }
  55. if cmd.Arg(1) == "" {
  56. return fmt.Errorf("destination can not be empty")
  57. }
  58. srcContainer, srcPath := splitCpArg(cmd.Arg(0))
  59. dstContainer, dstPath := splitCpArg(cmd.Arg(1))
  60. var direction copyDirection
  61. if srcContainer != "" {
  62. direction |= fromContainer
  63. }
  64. if dstContainer != "" {
  65. direction |= toContainer
  66. }
  67. cpParam := &cpConfig{
  68. followLink: *followLink,
  69. }
  70. ctx := context.Background()
  71. switch direction {
  72. case fromContainer:
  73. return cli.copyFromContainer(ctx, srcContainer, srcPath, dstPath, cpParam)
  74. case toContainer:
  75. return cli.copyToContainer(ctx, srcPath, dstContainer, dstPath, cpParam)
  76. case acrossContainers:
  77. // Copying between containers isn't supported.
  78. return fmt.Errorf("copying between containers is not supported")
  79. default:
  80. // User didn't specify any container.
  81. return fmt.Errorf("must specify at least one container source")
  82. }
  83. }
  84. // We use `:` as a delimiter between CONTAINER and PATH, but `:` could also be
  85. // in a valid LOCALPATH, like `file:name.txt`. We can resolve this ambiguity by
  86. // requiring a LOCALPATH with a `:` to be made explicit with a relative or
  87. // absolute path:
  88. // `/path/to/file:name.txt` or `./file:name.txt`
  89. //
  90. // This is apparently how `scp` handles this as well:
  91. // http://www.cyberciti.biz/faq/rsync-scp-file-name-with-colon-punctuation-in-it/
  92. //
  93. // We can't simply check for a filepath separator because container names may
  94. // have a separator, e.g., "host0/cname1" if container is in a Docker cluster,
  95. // so we have to check for a `/` or `.` prefix. Also, in the case of a Windows
  96. // client, a `:` could be part of an absolute Windows path, in which case it
  97. // is immediately proceeded by a backslash.
  98. func splitCpArg(arg string) (container, path string) {
  99. if system.IsAbs(arg) {
  100. // Explicit local absolute path, e.g., `C:\foo` or `/foo`.
  101. return "", arg
  102. }
  103. parts := strings.SplitN(arg, ":", 2)
  104. if len(parts) == 1 || strings.HasPrefix(parts[0], ".") {
  105. // Either there's no `:` in the arg
  106. // OR it's an explicit local relative path like `./file:name.txt`.
  107. return "", arg
  108. }
  109. return parts[0], parts[1]
  110. }
  111. func (cli *DockerCli) statContainerPath(ctx context.Context, containerName, path string) (types.ContainerPathStat, error) {
  112. return cli.client.ContainerStatPath(ctx, containerName, path)
  113. }
  114. func resolveLocalPath(localPath string) (absPath string, err error) {
  115. if absPath, err = filepath.Abs(localPath); err != nil {
  116. return
  117. }
  118. return archive.PreserveTrailingDotOrSeparator(absPath, localPath), nil
  119. }
  120. func (cli *DockerCli) copyFromContainer(ctx context.Context, srcContainer, srcPath, dstPath string, cpParam *cpConfig) (err error) {
  121. if dstPath != "-" {
  122. // Get an absolute destination path.
  123. dstPath, err = resolveLocalPath(dstPath)
  124. if err != nil {
  125. return err
  126. }
  127. }
  128. // if client requests to follow symbol link, then must decide target file to be copied
  129. var rebaseName string
  130. if cpParam.followLink {
  131. srcStat, err := cli.statContainerPath(ctx, srcContainer, srcPath)
  132. // If the destination is a symbolic link, we should follow it.
  133. if err == nil && srcStat.Mode&os.ModeSymlink != 0 {
  134. linkTarget := srcStat.LinkTarget
  135. if !system.IsAbs(linkTarget) {
  136. // Join with the parent directory.
  137. srcParent, _ := archive.SplitPathDirEntry(srcPath)
  138. linkTarget = filepath.Join(srcParent, linkTarget)
  139. }
  140. linkTarget, rebaseName = archive.GetRebaseName(srcPath, linkTarget)
  141. srcPath = linkTarget
  142. }
  143. }
  144. content, stat, err := cli.client.CopyFromContainer(ctx, srcContainer, srcPath)
  145. if err != nil {
  146. return err
  147. }
  148. defer content.Close()
  149. if dstPath == "-" {
  150. // Send the response to STDOUT.
  151. _, err = io.Copy(os.Stdout, content)
  152. return err
  153. }
  154. // Prepare source copy info.
  155. srcInfo := archive.CopyInfo{
  156. Path: srcPath,
  157. Exists: true,
  158. IsDir: stat.Mode.IsDir(),
  159. RebaseName: rebaseName,
  160. }
  161. preArchive := content
  162. if len(srcInfo.RebaseName) != 0 {
  163. _, srcBase := archive.SplitPathDirEntry(srcInfo.Path)
  164. preArchive = archive.RebaseArchiveEntries(content, srcBase, srcInfo.RebaseName)
  165. }
  166. // See comments in the implementation of `archive.CopyTo` for exactly what
  167. // goes into deciding how and whether the source archive needs to be
  168. // altered for the correct copy behavior.
  169. return archive.CopyTo(preArchive, srcInfo, dstPath)
  170. }
  171. func (cli *DockerCli) copyToContainer(ctx context.Context, srcPath, dstContainer, dstPath string, cpParam *cpConfig) (err error) {
  172. if srcPath != "-" {
  173. // Get an absolute source path.
  174. srcPath, err = resolveLocalPath(srcPath)
  175. if err != nil {
  176. return err
  177. }
  178. }
  179. // In order to get the copy behavior right, we need to know information
  180. // about both the source and destination. The API is a simple tar
  181. // archive/extract API but we can use the stat info header about the
  182. // destination to be more informed about exactly what the destination is.
  183. // Prepare destination copy info by stat-ing the container path.
  184. dstInfo := archive.CopyInfo{Path: dstPath}
  185. dstStat, err := cli.statContainerPath(ctx, dstContainer, dstPath)
  186. // If the destination is a symbolic link, we should evaluate it.
  187. if err == nil && dstStat.Mode&os.ModeSymlink != 0 {
  188. linkTarget := dstStat.LinkTarget
  189. if !system.IsAbs(linkTarget) {
  190. // Join with the parent directory.
  191. dstParent, _ := archive.SplitPathDirEntry(dstPath)
  192. linkTarget = filepath.Join(dstParent, linkTarget)
  193. }
  194. dstInfo.Path = linkTarget
  195. dstStat, err = cli.statContainerPath(ctx, dstContainer, linkTarget)
  196. }
  197. // Ignore any error and assume that the parent directory of the destination
  198. // path exists, in which case the copy may still succeed. If there is any
  199. // type of conflict (e.g., non-directory overwriting an existing directory
  200. // or vice versa) the extraction will fail. If the destination simply did
  201. // not exist, but the parent directory does, the extraction will still
  202. // succeed.
  203. if err == nil {
  204. dstInfo.Exists, dstInfo.IsDir = true, dstStat.Mode.IsDir()
  205. }
  206. var (
  207. content io.Reader
  208. resolvedDstPath string
  209. )
  210. if srcPath == "-" {
  211. // Use STDIN.
  212. content = os.Stdin
  213. resolvedDstPath = dstInfo.Path
  214. if !dstInfo.IsDir {
  215. return fmt.Errorf("destination %q must be a directory", fmt.Sprintf("%s:%s", dstContainer, dstPath))
  216. }
  217. } else {
  218. // Prepare source copy info.
  219. srcInfo, err := archive.CopyInfoSourcePath(srcPath, cpParam.followLink)
  220. if err != nil {
  221. return err
  222. }
  223. srcArchive, err := archive.TarResource(srcInfo)
  224. if err != nil {
  225. return err
  226. }
  227. defer srcArchive.Close()
  228. // With the stat info about the local source as well as the
  229. // destination, we have enough information to know whether we need to
  230. // alter the archive that we upload so that when the server extracts
  231. // it to the specified directory in the container we get the desired
  232. // copy behavior.
  233. // See comments in the implementation of `archive.PrepareArchiveCopy`
  234. // for exactly what goes into deciding how and whether the source
  235. // archive needs to be altered for the correct copy behavior when it is
  236. // extracted. This function also infers from the source and destination
  237. // info which directory to extract to, which may be the parent of the
  238. // destination that the user specified.
  239. dstDir, preparedArchive, err := archive.PrepareArchiveCopy(srcArchive, srcInfo, dstInfo)
  240. if err != nil {
  241. return err
  242. }
  243. defer preparedArchive.Close()
  244. resolvedDstPath = dstDir
  245. content = preparedArchive
  246. }
  247. options := types.CopyToContainerOptions{
  248. AllowOverwriteDirWithFile: false,
  249. }
  250. return cli.client.CopyToContainer(ctx, dstContainer, resolvedDstPath, content, options)
  251. }