cp.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package compose
  14. import (
  15. "context"
  16. "fmt"
  17. "io"
  18. "os"
  19. "path/filepath"
  20. "strings"
  21. "golang.org/x/sync/errgroup"
  22. "github.com/docker/cli/cli/command"
  23. "github.com/docker/compose/v2/pkg/api"
  24. moby "github.com/docker/docker/api/types"
  25. "github.com/docker/docker/pkg/archive"
  26. "github.com/docker/docker/pkg/system"
  27. "github.com/pkg/errors"
  28. )
  29. type copyDirection int
  30. const (
  31. fromService copyDirection = 1 << iota
  32. toService
  33. acrossServices = fromService | toService
  34. )
  35. func (s *composeService) Copy(ctx context.Context, projectName string, options api.CopyOptions) error {
  36. projectName = strings.ToLower(projectName)
  37. srcService, srcPath := splitCpArg(options.Source)
  38. destService, dstPath := splitCpArg(options.Destination)
  39. var direction copyDirection
  40. var serviceName string
  41. if srcService != "" {
  42. direction |= fromService
  43. serviceName = srcService
  44. // copying from multiple containers of a services doesn't make sense.
  45. if options.All {
  46. return errors.New("cannot use the --all flag when copying from a service")
  47. }
  48. }
  49. if destService != "" {
  50. direction |= toService
  51. serviceName = destService
  52. }
  53. containers, err := s.getContainers(ctx, projectName, oneOffExclude, true, serviceName)
  54. if err != nil {
  55. return err
  56. }
  57. if len(containers) < 1 {
  58. return fmt.Errorf("no container found for service %q", serviceName)
  59. }
  60. if !options.All {
  61. containers = containers.filter(indexed(options.Index))
  62. }
  63. g := errgroup.Group{}
  64. for _, container := range containers {
  65. containerID := container.ID
  66. g.Go(func() error {
  67. switch direction {
  68. case fromService:
  69. return s.copyFromContainer(ctx, containerID, srcPath, dstPath, options)
  70. case toService:
  71. return s.copyToContainer(ctx, containerID, srcPath, dstPath, options)
  72. case acrossServices:
  73. return errors.New("copying between services is not supported")
  74. default:
  75. return errors.New("unknown copy direction")
  76. }
  77. })
  78. }
  79. return g.Wait()
  80. }
  81. func (s *composeService) copyToContainer(ctx context.Context, containerID string, srcPath string, dstPath string, opts api.CopyOptions) error {
  82. var err error
  83. if srcPath != "-" {
  84. // Get an absolute source path.
  85. srcPath, err = resolveLocalPath(srcPath)
  86. if err != nil {
  87. return err
  88. }
  89. }
  90. // Prepare destination copy info by stat-ing the container path.
  91. dstInfo := archive.CopyInfo{Path: dstPath}
  92. dstStat, err := s.apiClient().ContainerStatPath(ctx, containerID, dstPath)
  93. // If the destination is a symbolic link, we should evaluate it.
  94. if err == nil && dstStat.Mode&os.ModeSymlink != 0 {
  95. linkTarget := dstStat.LinkTarget
  96. if !system.IsAbs(linkTarget) {
  97. // Join with the parent directory.
  98. dstParent, _ := archive.SplitPathDirEntry(dstPath)
  99. linkTarget = filepath.Join(dstParent, linkTarget)
  100. }
  101. dstInfo.Path = linkTarget
  102. dstStat, err = s.apiClient().ContainerStatPath(ctx, containerID, linkTarget)
  103. }
  104. // Validate the destination path
  105. if err := command.ValidateOutputPathFileMode(dstStat.Mode); err != nil {
  106. return errors.Wrapf(err, `destination "%s:%s" must be a directory or a regular file`, containerID, dstPath)
  107. }
  108. // Ignore any error and assume that the parent directory of the destination
  109. // path exists, in which case the copy may still succeed. If there is any
  110. // type of conflict (e.g., non-directory overwriting an existing directory
  111. // or vice versa) the extraction will fail. If the destination simply did
  112. // not exist, but the parent directory does, the extraction will still
  113. // succeed.
  114. if err == nil {
  115. dstInfo.Exists, dstInfo.IsDir = true, dstStat.Mode.IsDir()
  116. }
  117. var (
  118. content io.Reader
  119. resolvedDstPath string
  120. )
  121. if srcPath == "-" {
  122. content = s.stdin()
  123. resolvedDstPath = dstInfo.Path
  124. if !dstInfo.IsDir {
  125. return errors.Errorf("destination \"%s:%s\" must be a directory", containerID, dstPath)
  126. }
  127. } else {
  128. // Prepare source copy info.
  129. srcInfo, err := archive.CopyInfoSourcePath(srcPath, opts.FollowLink)
  130. if err != nil {
  131. return err
  132. }
  133. srcArchive, err := archive.TarResource(srcInfo)
  134. if err != nil {
  135. return err
  136. }
  137. defer srcArchive.Close() //nolint:errcheck
  138. // With the stat info about the local source as well as the
  139. // destination, we have enough information to know whether we need to
  140. // alter the archive that we upload so that when the server extracts
  141. // it to the specified directory in the container we get the desired
  142. // copy behavior.
  143. // See comments in the implementation of `archive.PrepareArchiveCopy`
  144. // for exactly what goes into deciding how and whether the source
  145. // archive needs to be altered for the correct copy behavior when it is
  146. // extracted. This function also infers from the source and destination
  147. // info which directory to extract to, which may be the parent of the
  148. // destination that the user specified.
  149. dstDir, preparedArchive, err := archive.PrepareArchiveCopy(srcArchive, srcInfo, dstInfo)
  150. if err != nil {
  151. return err
  152. }
  153. defer preparedArchive.Close() //nolint:errcheck
  154. resolvedDstPath = dstDir
  155. content = preparedArchive
  156. }
  157. options := moby.CopyToContainerOptions{
  158. AllowOverwriteDirWithFile: false,
  159. CopyUIDGID: opts.CopyUIDGID,
  160. }
  161. return s.apiClient().CopyToContainer(ctx, containerID, resolvedDstPath, content, options)
  162. }
  163. func (s *composeService) copyFromContainer(ctx context.Context, containerID, srcPath, dstPath string, opts api.CopyOptions) error {
  164. var err error
  165. if dstPath != "-" {
  166. // Get an absolute destination path.
  167. dstPath, err = resolveLocalPath(dstPath)
  168. if err != nil {
  169. return err
  170. }
  171. }
  172. if err := command.ValidateOutputPath(dstPath); err != nil {
  173. return err
  174. }
  175. // if client requests to follow symbol link, then must decide target file to be copied
  176. var rebaseName string
  177. if opts.FollowLink {
  178. srcStat, err := s.apiClient().ContainerStatPath(ctx, containerID, srcPath)
  179. // If the destination is a symbolic link, we should follow it.
  180. if err == nil && srcStat.Mode&os.ModeSymlink != 0 {
  181. linkTarget := srcStat.LinkTarget
  182. if !system.IsAbs(linkTarget) {
  183. // Join with the parent directory.
  184. srcParent, _ := archive.SplitPathDirEntry(srcPath)
  185. linkTarget = filepath.Join(srcParent, linkTarget)
  186. }
  187. linkTarget, rebaseName = archive.GetRebaseName(srcPath, linkTarget)
  188. srcPath = linkTarget
  189. }
  190. }
  191. content, stat, err := s.apiClient().CopyFromContainer(ctx, containerID, srcPath)
  192. if err != nil {
  193. return err
  194. }
  195. defer content.Close() //nolint:errcheck
  196. if dstPath == "-" {
  197. _, err = io.Copy(s.stdout(), content)
  198. return err
  199. }
  200. srcInfo := archive.CopyInfo{
  201. Path: srcPath,
  202. Exists: true,
  203. IsDir: stat.Mode.IsDir(),
  204. RebaseName: rebaseName,
  205. }
  206. preArchive := content
  207. if len(srcInfo.RebaseName) != 0 {
  208. _, srcBase := archive.SplitPathDirEntry(srcInfo.Path)
  209. preArchive = archive.RebaseArchiveEntries(content, srcBase, srcInfo.RebaseName)
  210. }
  211. return archive.CopyTo(preArchive, srcInfo, dstPath)
  212. }
  213. func splitCpArg(arg string) (container, path string) {
  214. if system.IsAbs(arg) {
  215. // Explicit local absolute path, e.g., `C:\foo` or `/foo`.
  216. return "", arg
  217. }
  218. parts := strings.SplitN(arg, ":", 2)
  219. if len(parts) == 1 || strings.HasPrefix(parts[0], ".") {
  220. // Either there's no `:` in the arg
  221. // OR it's an explicit local relative path like `./file:name.txt`.
  222. return "", arg
  223. }
  224. return parts[0], parts[1]
  225. }
  226. func resolveLocalPath(localPath string) (absPath string, err error) {
  227. if absPath, err = filepath.Abs(localPath); err != nil {
  228. return
  229. }
  230. return archive.PreserveTrailingDotOrSeparator(absPath, localPath, filepath.Separator), nil
  231. }