cp.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. "errors"
  17. "fmt"
  18. "io"
  19. "os"
  20. "path/filepath"
  21. "strings"
  22. "github.com/docker/compose/v2/pkg/progress"
  23. "golang.org/x/sync/errgroup"
  24. "github.com/docker/cli/cli/command"
  25. "github.com/docker/compose/v2/pkg/api"
  26. "github.com/docker/docker/api/types/container"
  27. "github.com/moby/go-archive"
  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. return progress.Run(ctx, func(ctx context.Context) error {
  37. return s.copy(ctx, projectName, options)
  38. }, "copy", s.events)
  39. }
  40. func (s *composeService) copy(ctx context.Context, projectName string, options api.CopyOptions) error {
  41. projectName = strings.ToLower(projectName)
  42. srcService, srcPath := splitCpArg(options.Source)
  43. destService, dstPath := splitCpArg(options.Destination)
  44. var direction copyDirection
  45. var serviceName string
  46. var copyFunc func(ctx context.Context, containerID string, srcPath string, dstPath string, opts api.CopyOptions) error
  47. if srcService != "" {
  48. direction |= fromService
  49. serviceName = srcService
  50. copyFunc = s.copyFromContainer
  51. }
  52. if destService != "" {
  53. direction |= toService
  54. serviceName = destService
  55. copyFunc = s.copyToContainer
  56. }
  57. if direction == acrossServices {
  58. return errors.New("copying between services is not supported")
  59. }
  60. if direction == 0 {
  61. return errors.New("unknown copy direction")
  62. }
  63. containers, err := s.listContainersTargetedForCopy(ctx, projectName, options, direction, serviceName)
  64. if err != nil {
  65. return err
  66. }
  67. g := errgroup.Group{}
  68. for _, cont := range containers {
  69. ctr := cont
  70. g.Go(func() error {
  71. name := getCanonicalContainerName(ctr)
  72. var msg string
  73. if direction == fromService {
  74. msg = fmt.Sprintf("copy %s:%s to %s", name, srcPath, dstPath)
  75. } else {
  76. msg = fmt.Sprintf("copy %s to %s:%s", srcPath, name, dstPath)
  77. }
  78. s.events.On(progress.Event{
  79. ID: name,
  80. Text: msg,
  81. Status: progress.Working,
  82. StatusText: "Copying",
  83. })
  84. if err := copyFunc(ctx, ctr.ID, srcPath, dstPath, options); err != nil {
  85. return err
  86. }
  87. s.events.On(progress.Event{
  88. ID: name,
  89. Text: msg,
  90. Status: progress.Done,
  91. StatusText: "Copied",
  92. })
  93. return nil
  94. })
  95. }
  96. return g.Wait()
  97. }
  98. func (s *composeService) listContainersTargetedForCopy(ctx context.Context, projectName string, options api.CopyOptions, direction copyDirection, serviceName string) (Containers, error) {
  99. var containers Containers
  100. var err error
  101. switch {
  102. case options.Index > 0:
  103. ctr, err := s.getSpecifiedContainer(ctx, projectName, oneOffExclude, true, serviceName, options.Index)
  104. if err != nil {
  105. return nil, err
  106. }
  107. return append(containers, ctr), nil
  108. default:
  109. withOneOff := oneOffExclude
  110. if options.All {
  111. withOneOff = oneOffInclude
  112. }
  113. containers, err = s.getContainers(ctx, projectName, withOneOff, true, serviceName)
  114. if err != nil {
  115. return nil, err
  116. }
  117. if len(containers) < 1 {
  118. return nil, fmt.Errorf("no container found for service %q", serviceName)
  119. }
  120. if direction == fromService {
  121. return containers[:1], err
  122. }
  123. return containers, err
  124. }
  125. }
  126. func (s *composeService) copyToContainer(ctx context.Context, containerID string, srcPath string, dstPath string, opts api.CopyOptions) error {
  127. var err error
  128. if srcPath != "-" {
  129. // Get an absolute source path.
  130. srcPath, err = resolveLocalPath(srcPath)
  131. if err != nil {
  132. return err
  133. }
  134. }
  135. // Prepare destination copy info by stat-ing the container path.
  136. dstInfo := archive.CopyInfo{Path: dstPath}
  137. dstStat, err := s.apiClient().ContainerStatPath(ctx, containerID, dstPath)
  138. // If the destination is a symbolic link, we should evaluate it.
  139. if err == nil && dstStat.Mode&os.ModeSymlink != 0 {
  140. linkTarget := dstStat.LinkTarget
  141. if !isAbs(linkTarget) {
  142. // Join with the parent directory.
  143. dstParent, _ := archive.SplitPathDirEntry(dstPath)
  144. linkTarget = filepath.Join(dstParent, linkTarget)
  145. }
  146. dstInfo.Path = linkTarget
  147. dstStat, err = s.apiClient().ContainerStatPath(ctx, containerID, linkTarget)
  148. }
  149. // Validate the destination path
  150. if err := command.ValidateOutputPathFileMode(dstStat.Mode); err != nil {
  151. return fmt.Errorf(`destination "%s:%s" must be a directory or a regular file: %w`, containerID, dstPath, err)
  152. }
  153. // Ignore any error and assume that the parent directory of the destination
  154. // path exists, in which case the copy may still succeed. If there is any
  155. // type of conflict (e.g., non-directory overwriting an existing directory
  156. // or vice versa) the extraction will fail. If the destination simply did
  157. // not exist, but the parent directory does, the extraction will still
  158. // succeed.
  159. if err == nil {
  160. dstInfo.Exists, dstInfo.IsDir = true, dstStat.Mode.IsDir()
  161. }
  162. var (
  163. content io.Reader
  164. resolvedDstPath string
  165. )
  166. if srcPath == "-" {
  167. content = s.stdin()
  168. resolvedDstPath = dstInfo.Path
  169. if !dstInfo.IsDir {
  170. return fmt.Errorf("destination \"%s:%s\" must be a directory", containerID, dstPath)
  171. }
  172. } else {
  173. // Prepare source copy info.
  174. srcInfo, err := archive.CopyInfoSourcePath(srcPath, opts.FollowLink)
  175. if err != nil {
  176. return err
  177. }
  178. srcArchive, err := archive.TarResource(srcInfo)
  179. if err != nil {
  180. return err
  181. }
  182. defer srcArchive.Close() //nolint:errcheck
  183. // With the stat info about the local source as well as the
  184. // destination, we have enough information to know whether we need to
  185. // alter the archive that we upload so that when the server extracts
  186. // it to the specified directory in the container we get the desired
  187. // copy behavior.
  188. // See comments in the implementation of `archive.PrepareArchiveCopy`
  189. // for exactly what goes into deciding how and whether the source
  190. // archive needs to be altered for the correct copy behavior when it is
  191. // extracted. This function also infers from the source and destination
  192. // info which directory to extract to, which may be the parent of the
  193. // destination that the user specified.
  194. // Don't create the archive if running in Dry Run mode
  195. if !s.dryRun {
  196. dstDir, preparedArchive, err := archive.PrepareArchiveCopy(srcArchive, srcInfo, dstInfo)
  197. if err != nil {
  198. return err
  199. }
  200. defer preparedArchive.Close() //nolint:errcheck
  201. resolvedDstPath = dstDir
  202. content = preparedArchive
  203. }
  204. }
  205. options := container.CopyToContainerOptions{
  206. AllowOverwriteDirWithFile: false,
  207. CopyUIDGID: opts.CopyUIDGID,
  208. }
  209. return s.apiClient().CopyToContainer(ctx, containerID, resolvedDstPath, content, options)
  210. }
  211. func (s *composeService) copyFromContainer(ctx context.Context, containerID, srcPath, dstPath string, opts api.CopyOptions) error {
  212. var err error
  213. if dstPath != "-" {
  214. // Get an absolute destination path.
  215. dstPath, err = resolveLocalPath(dstPath)
  216. if err != nil {
  217. return err
  218. }
  219. }
  220. if err := command.ValidateOutputPath(dstPath); err != nil {
  221. return err
  222. }
  223. // if client requests to follow symbol link, then must decide target file to be copied
  224. var rebaseName string
  225. if opts.FollowLink {
  226. srcStat, err := s.apiClient().ContainerStatPath(ctx, containerID, srcPath)
  227. // If the destination is a symbolic link, we should follow it.
  228. if err == nil && srcStat.Mode&os.ModeSymlink != 0 {
  229. linkTarget := srcStat.LinkTarget
  230. if !isAbs(linkTarget) {
  231. // Join with the parent directory.
  232. srcParent, _ := archive.SplitPathDirEntry(srcPath)
  233. linkTarget = filepath.Join(srcParent, linkTarget)
  234. }
  235. linkTarget, rebaseName = archive.GetRebaseName(srcPath, linkTarget)
  236. srcPath = linkTarget
  237. }
  238. }
  239. content, stat, err := s.apiClient().CopyFromContainer(ctx, containerID, srcPath)
  240. if err != nil {
  241. return err
  242. }
  243. defer content.Close() //nolint:errcheck
  244. if dstPath == "-" {
  245. _, err = io.Copy(s.stdout(), content)
  246. return err
  247. }
  248. srcInfo := archive.CopyInfo{
  249. Path: srcPath,
  250. Exists: true,
  251. IsDir: stat.Mode.IsDir(),
  252. RebaseName: rebaseName,
  253. }
  254. preArchive := content
  255. if srcInfo.RebaseName != "" {
  256. _, srcBase := archive.SplitPathDirEntry(srcInfo.Path)
  257. preArchive = archive.RebaseArchiveEntries(content, srcBase, srcInfo.RebaseName)
  258. }
  259. return archive.CopyTo(preArchive, srcInfo, dstPath)
  260. }
  261. // IsAbs is a platform-agnostic wrapper for filepath.IsAbs.
  262. //
  263. // On Windows, golang filepath.IsAbs does not consider a path \windows\system32
  264. // as absolute as it doesn't start with a drive-letter/colon combination. However,
  265. // in docker we need to verify things such as WORKDIR /windows/system32 in
  266. // a Dockerfile (which gets translated to \windows\system32 when being processed
  267. // by the daemon). This SHOULD be treated as absolute from a docker processing
  268. // perspective.
  269. func isAbs(path string) bool {
  270. return filepath.IsAbs(path) || strings.HasPrefix(path, string(os.PathSeparator))
  271. }
  272. func splitCpArg(arg string) (ctr, path string) {
  273. if isAbs(arg) {
  274. // Explicit local absolute path, e.g., `C:\foo` or `/foo`.
  275. return "", arg
  276. }
  277. parts := strings.SplitN(arg, ":", 2)
  278. if len(parts) == 1 || strings.HasPrefix(parts[0], ".") {
  279. // Either there's no `:` in the arg
  280. // OR it's an explicit local relative path like `./file:name.txt`.
  281. return "", arg
  282. }
  283. return parts[0], parts[1]
  284. }
  285. func resolveLocalPath(localPath string) (absPath string, err error) {
  286. if absPath, err = filepath.Abs(localPath); err != nil {
  287. return
  288. }
  289. return archive.PreserveTrailingDotOrSeparator(absPath, localPath), nil
  290. }