cp.go 9.2 KB

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