cp.go 9.2 KB

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