cp.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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. switch direction {
  71. case fromContainer:
  72. return cli.copyFromContainer(srcContainer, srcPath, dstPath, cpParam)
  73. case toContainer:
  74. return cli.copyToContainer(srcPath, dstContainer, dstPath, cpParam)
  75. case acrossContainers:
  76. // Copying between containers isn't supported.
  77. return fmt.Errorf("copying between containers is not supported")
  78. default:
  79. // User didn't specify any container.
  80. return fmt.Errorf("must specify at least one container source")
  81. }
  82. }
  83. // We use `:` as a delimiter between CONTAINER and PATH, but `:` could also be
  84. // in a valid LOCALPATH, like `file:name.txt`. We can resolve this ambiguity by
  85. // requiring a LOCALPATH with a `:` to be made explicit with a relative or
  86. // absolute path:
  87. // `/path/to/file:name.txt` or `./file:name.txt`
  88. //
  89. // This is apparently how `scp` handles this as well:
  90. // http://www.cyberciti.biz/faq/rsync-scp-file-name-with-colon-punctuation-in-it/
  91. //
  92. // We can't simply check for a filepath separator because container names may
  93. // have a separator, e.g., "host0/cname1" if container is in a Docker cluster,
  94. // so we have to check for a `/` or `.` prefix. Also, in the case of a Windows
  95. // client, a `:` could be part of an absolute Windows path, in which case it
  96. // is immediately proceeded by a backslash.
  97. func splitCpArg(arg string) (container, path string) {
  98. if system.IsAbs(arg) {
  99. // Explicit local absolute path, e.g., `C:\foo` or `/foo`.
  100. return "", arg
  101. }
  102. parts := strings.SplitN(arg, ":", 2)
  103. if len(parts) == 1 || strings.HasPrefix(parts[0], ".") {
  104. // Either there's no `:` in the arg
  105. // OR it's an explicit local relative path like `./file:name.txt`.
  106. return "", arg
  107. }
  108. return parts[0], parts[1]
  109. }
  110. func (cli *DockerCli) statContainerPath(containerName, path string) (types.ContainerPathStat, error) {
  111. return cli.client.ContainerStatPath(containerName, path)
  112. }
  113. func resolveLocalPath(localPath string) (absPath string, err error) {
  114. if absPath, err = filepath.Abs(localPath); err != nil {
  115. return
  116. }
  117. return archive.PreserveTrailingDotOrSeparator(absPath, localPath), nil
  118. }
  119. func (cli *DockerCli) copyFromContainer(srcContainer, srcPath, dstPath string, cpParam *cpConfig) (err error) {
  120. if dstPath != "-" {
  121. // Get an absolute destination path.
  122. dstPath, err = resolveLocalPath(dstPath)
  123. if err != nil {
  124. return err
  125. }
  126. }
  127. // if client requests to follow symbol link, then must decide target file to be copied
  128. var rebaseName string
  129. if cpParam.followLink {
  130. srcStat, err := cli.statContainerPath(srcContainer, srcPath)
  131. // If the destination is a symbolic link, we should follow it.
  132. if err == nil && srcStat.Mode&os.ModeSymlink != 0 {
  133. linkTarget := srcStat.LinkTarget
  134. if !system.IsAbs(linkTarget) {
  135. // Join with the parent directory.
  136. srcParent, _ := archive.SplitPathDirEntry(srcPath)
  137. linkTarget = filepath.Join(srcParent, linkTarget)
  138. }
  139. linkTarget, rebaseName = archive.GetRebaseName(srcPath, linkTarget)
  140. srcPath = linkTarget
  141. }
  142. }
  143. content, stat, err := cli.client.CopyFromContainer(context.Background(), srcContainer, srcPath)
  144. if err != nil {
  145. return err
  146. }
  147. defer content.Close()
  148. if dstPath == "-" {
  149. // Send the response to STDOUT.
  150. _, err = io.Copy(os.Stdout, content)
  151. return err
  152. }
  153. // Prepare source copy info.
  154. srcInfo := archive.CopyInfo{
  155. Path: srcPath,
  156. Exists: true,
  157. IsDir: stat.Mode.IsDir(),
  158. RebaseName: rebaseName,
  159. }
  160. preArchive := content
  161. if len(srcInfo.RebaseName) != 0 {
  162. _, srcBase := archive.SplitPathDirEntry(srcInfo.Path)
  163. preArchive = archive.RebaseArchiveEntries(content, srcBase, srcInfo.RebaseName)
  164. }
  165. // See comments in the implementation of `archive.CopyTo` for exactly what
  166. // goes into deciding how and whether the source archive needs to be
  167. // altered for the correct copy behavior.
  168. return archive.CopyTo(preArchive, srcInfo, dstPath)
  169. }
  170. func (cli *DockerCli) copyToContainer(srcPath, dstContainer, dstPath string, cpParam *cpConfig) (err error) {
  171. if srcPath != "-" {
  172. // Get an absolute source path.
  173. srcPath, err = resolveLocalPath(srcPath)
  174. if err != nil {
  175. return err
  176. }
  177. }
  178. // In order to get the copy behavior right, we need to know information
  179. // about both the source and destination. The API is a simple tar
  180. // archive/extract API but we can use the stat info header about the
  181. // destination to be more informed about exactly what the destination is.
  182. // Prepare destination copy info by stat-ing the container path.
  183. dstInfo := archive.CopyInfo{Path: dstPath}
  184. dstStat, err := cli.statContainerPath(dstContainer, dstPath)
  185. // If the destination is a symbolic link, we should evaluate it.
  186. if err == nil && dstStat.Mode&os.ModeSymlink != 0 {
  187. linkTarget := dstStat.LinkTarget
  188. if !system.IsAbs(linkTarget) {
  189. // Join with the parent directory.
  190. dstParent, _ := archive.SplitPathDirEntry(dstPath)
  191. linkTarget = filepath.Join(dstParent, linkTarget)
  192. }
  193. dstInfo.Path = linkTarget
  194. dstStat, err = cli.statContainerPath(dstContainer, linkTarget)
  195. }
  196. // Ignore any error and assume that the parent directory of the destination
  197. // path exists, in which case the copy may still succeed. If there is any
  198. // type of conflict (e.g., non-directory overwriting an existing directory
  199. // or vice versa) the extraction will fail. If the destination simply did
  200. // not exist, but the parent directory does, the extraction will still
  201. // succeed.
  202. if err == nil {
  203. dstInfo.Exists, dstInfo.IsDir = true, dstStat.Mode.IsDir()
  204. }
  205. var (
  206. content io.Reader
  207. resolvedDstPath string
  208. )
  209. if srcPath == "-" {
  210. // Use STDIN.
  211. content = os.Stdin
  212. resolvedDstPath = dstInfo.Path
  213. if !dstInfo.IsDir {
  214. return fmt.Errorf("destination %q must be a directory", fmt.Sprintf("%s:%s", dstContainer, dstPath))
  215. }
  216. } else {
  217. // Prepare source copy info.
  218. srcInfo, err := archive.CopyInfoSourcePath(srcPath, cpParam.followLink)
  219. if err != nil {
  220. return err
  221. }
  222. srcArchive, err := archive.TarResource(srcInfo)
  223. if err != nil {
  224. return err
  225. }
  226. defer srcArchive.Close()
  227. // With the stat info about the local source as well as the
  228. // destination, we have enough information to know whether we need to
  229. // alter the archive that we upload so that when the server extracts
  230. // it to the specified directory in the container we get the desired
  231. // copy behavior.
  232. // See comments in the implementation of `archive.PrepareArchiveCopy`
  233. // for exactly what goes into deciding how and whether the source
  234. // archive needs to be altered for the correct copy behavior when it is
  235. // extracted. This function also infers from the source and destination
  236. // info which directory to extract to, which may be the parent of the
  237. // destination that the user specified.
  238. dstDir, preparedArchive, err := archive.PrepareArchiveCopy(srcArchive, srcInfo, dstInfo)
  239. if err != nil {
  240. return err
  241. }
  242. defer preparedArchive.Close()
  243. resolvedDstPath = dstDir
  244. content = preparedArchive
  245. }
  246. options := types.CopyToContainerOptions{
  247. ContainerID: dstContainer,
  248. Path: resolvedDstPath,
  249. Content: content,
  250. AllowOverwriteDirWithFile: false,
  251. }
  252. return cli.client.CopyToContainer(context.Background(), options)
  253. }