cp.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. var copyFunc func(ctx context.Context, containerID string, srcPath string, dstPath string, opts api.CopyOptions) error
  42. if srcService != "" {
  43. direction |= fromService
  44. serviceName = srcService
  45. copyFunc = s.copyFromContainer
  46. // copying from multiple containers of a services doesn't make sense.
  47. if options.All {
  48. return errors.New("cannot use the --all flag when copying from a service")
  49. }
  50. }
  51. if destService != "" {
  52. direction |= toService
  53. serviceName = destService
  54. copyFunc = s.copyToContainer
  55. }
  56. if direction == acrossServices {
  57. return errors.New("copying between services is not supported")
  58. }
  59. if direction == 0 {
  60. return errors.New("unknown copy direction")
  61. }
  62. containers, err := s.listContainersTargetedForCopy(ctx, projectName, options.Index, direction, serviceName)
  63. if err != nil {
  64. return err
  65. }
  66. g := errgroup.Group{}
  67. for _, container := range containers {
  68. containerID := container.ID
  69. g.Go(func() error {
  70. return copyFunc(ctx, containerID, srcPath, dstPath, options)
  71. })
  72. }
  73. return g.Wait()
  74. }
  75. func (s *composeService) listContainersTargetedForCopy(ctx context.Context, projectName string, index int, direction copyDirection, serviceName string) (Containers, error) {
  76. var containers Containers
  77. var err error
  78. switch {
  79. case index > 0:
  80. container, err := s.getSpecifiedContainer(ctx, projectName, oneOffExclude, true, serviceName, index)
  81. if err != nil {
  82. return nil, err
  83. }
  84. return append(containers, container), nil
  85. default:
  86. containers, err = s.getContainers(ctx, projectName, oneOffExclude, true, serviceName)
  87. if err != nil {
  88. return nil, err
  89. }
  90. if len(containers) < 1 {
  91. return nil, fmt.Errorf("no container found for service %q", serviceName)
  92. }
  93. if direction == fromService {
  94. return containers[:1], err
  95. }
  96. return containers, err
  97. }
  98. }
  99. func (s *composeService) copyToContainer(ctx context.Context, containerID string, srcPath string, dstPath string, opts api.CopyOptions) error {
  100. var err error
  101. if srcPath != "-" {
  102. // Get an absolute source path.
  103. srcPath, err = resolveLocalPath(srcPath)
  104. if err != nil {
  105. return err
  106. }
  107. }
  108. // Prepare destination copy info by stat-ing the container path.
  109. dstInfo := archive.CopyInfo{Path: dstPath}
  110. dstStat, err := s.apiClient().ContainerStatPath(ctx, containerID, dstPath)
  111. // If the destination is a symbolic link, we should evaluate it.
  112. if err == nil && dstStat.Mode&os.ModeSymlink != 0 {
  113. linkTarget := dstStat.LinkTarget
  114. if !system.IsAbs(linkTarget) {
  115. // Join with the parent directory.
  116. dstParent, _ := archive.SplitPathDirEntry(dstPath)
  117. linkTarget = filepath.Join(dstParent, linkTarget)
  118. }
  119. dstInfo.Path = linkTarget
  120. dstStat, err = s.apiClient().ContainerStatPath(ctx, containerID, linkTarget)
  121. }
  122. // Validate the destination path
  123. if err := command.ValidateOutputPathFileMode(dstStat.Mode); err != nil {
  124. return errors.Wrapf(err, `destination "%s:%s" must be a directory or a regular file`, containerID, dstPath)
  125. }
  126. // Ignore any error and assume that the parent directory of the destination
  127. // path exists, in which case the copy may still succeed. If there is any
  128. // type of conflict (e.g., non-directory overwriting an existing directory
  129. // or vice versa) the extraction will fail. If the destination simply did
  130. // not exist, but the parent directory does, the extraction will still
  131. // succeed.
  132. if err == nil {
  133. dstInfo.Exists, dstInfo.IsDir = true, dstStat.Mode.IsDir()
  134. }
  135. var (
  136. content io.Reader
  137. resolvedDstPath string
  138. )
  139. if srcPath == "-" {
  140. content = s.stdin()
  141. resolvedDstPath = dstInfo.Path
  142. if !dstInfo.IsDir {
  143. return errors.Errorf("destination \"%s:%s\" must be a directory", containerID, dstPath)
  144. }
  145. } else {
  146. // Prepare source copy info.
  147. srcInfo, err := archive.CopyInfoSourcePath(srcPath, opts.FollowLink)
  148. if err != nil {
  149. return err
  150. }
  151. srcArchive, err := archive.TarResource(srcInfo)
  152. if err != nil {
  153. return err
  154. }
  155. defer srcArchive.Close() //nolint:errcheck
  156. // With the stat info about the local source as well as the
  157. // destination, we have enough information to know whether we need to
  158. // alter the archive that we upload so that when the server extracts
  159. // it to the specified directory in the container we get the desired
  160. // copy behavior.
  161. // See comments in the implementation of `archive.PrepareArchiveCopy`
  162. // for exactly what goes into deciding how and whether the source
  163. // archive needs to be altered for the correct copy behavior when it is
  164. // extracted. This function also infers from the source and destination
  165. // info which directory to extract to, which may be the parent of the
  166. // destination that the user specified.
  167. dstDir, preparedArchive, err := archive.PrepareArchiveCopy(srcArchive, srcInfo, dstInfo)
  168. if err != nil {
  169. return err
  170. }
  171. defer preparedArchive.Close() //nolint:errcheck
  172. resolvedDstPath = dstDir
  173. content = preparedArchive
  174. }
  175. options := moby.CopyToContainerOptions{
  176. AllowOverwriteDirWithFile: false,
  177. CopyUIDGID: opts.CopyUIDGID,
  178. }
  179. return s.apiClient().CopyToContainer(ctx, containerID, resolvedDstPath, content, options)
  180. }
  181. func (s *composeService) copyFromContainer(ctx context.Context, containerID, srcPath, dstPath string, opts api.CopyOptions) error {
  182. var err error
  183. if dstPath != "-" {
  184. // Get an absolute destination path.
  185. dstPath, err = resolveLocalPath(dstPath)
  186. if err != nil {
  187. return err
  188. }
  189. }
  190. if err := command.ValidateOutputPath(dstPath); err != nil {
  191. return err
  192. }
  193. // if client requests to follow symbol link, then must decide target file to be copied
  194. var rebaseName string
  195. if opts.FollowLink {
  196. srcStat, err := s.apiClient().ContainerStatPath(ctx, containerID, srcPath)
  197. // If the destination is a symbolic link, we should follow it.
  198. if err == nil && srcStat.Mode&os.ModeSymlink != 0 {
  199. linkTarget := srcStat.LinkTarget
  200. if !system.IsAbs(linkTarget) {
  201. // Join with the parent directory.
  202. srcParent, _ := archive.SplitPathDirEntry(srcPath)
  203. linkTarget = filepath.Join(srcParent, linkTarget)
  204. }
  205. linkTarget, rebaseName = archive.GetRebaseName(srcPath, linkTarget)
  206. srcPath = linkTarget
  207. }
  208. }
  209. content, stat, err := s.apiClient().CopyFromContainer(ctx, containerID, srcPath)
  210. if err != nil {
  211. return err
  212. }
  213. defer content.Close() //nolint:errcheck
  214. if dstPath == "-" {
  215. _, err = io.Copy(s.stdout(), content)
  216. return err
  217. }
  218. srcInfo := archive.CopyInfo{
  219. Path: srcPath,
  220. Exists: true,
  221. IsDir: stat.Mode.IsDir(),
  222. RebaseName: rebaseName,
  223. }
  224. preArchive := content
  225. if len(srcInfo.RebaseName) != 0 {
  226. _, srcBase := archive.SplitPathDirEntry(srcInfo.Path)
  227. preArchive = archive.RebaseArchiveEntries(content, srcBase, srcInfo.RebaseName)
  228. }
  229. return archive.CopyTo(preArchive, srcInfo, dstPath)
  230. }
  231. func splitCpArg(arg string) (container, path string) {
  232. if system.IsAbs(arg) {
  233. // Explicit local absolute path, e.g., `C:\foo` or `/foo`.
  234. return "", arg
  235. }
  236. parts := strings.SplitN(arg, ":", 2)
  237. if len(parts) == 1 || strings.HasPrefix(parts[0], ".") {
  238. // Either there's no `:` in the arg
  239. // OR it's an explicit local relative path like `./file:name.txt`.
  240. return "", arg
  241. }
  242. return parts[0], parts[1]
  243. }
  244. func resolveLocalPath(localPath string) (absPath string, err error) {
  245. if absPath, err = filepath.Abs(localPath); err != nil {
  246. return
  247. }
  248. return archive.PreserveTrailingDotOrSeparator(absPath, localPath, filepath.Separator), nil
  249. }