1
0

tar.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. /*
  2. Copyright 2018 The Tilt Dev Authors
  3. Copyright 2023 Docker Compose CLI authors
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. */
  14. package sync
  15. import (
  16. "archive/tar"
  17. "bytes"
  18. "context"
  19. "errors"
  20. "fmt"
  21. "io"
  22. "io/fs"
  23. "os"
  24. "path"
  25. "path/filepath"
  26. "strings"
  27. "github.com/hashicorp/go-multierror"
  28. "github.com/compose-spec/compose-go/v2/types"
  29. moby "github.com/docker/docker/api/types"
  30. "github.com/docker/docker/pkg/archive"
  31. )
  32. type archiveEntry struct {
  33. path string
  34. info os.FileInfo
  35. header *tar.Header
  36. }
  37. type LowLevelClient interface {
  38. ContainersForService(ctx context.Context, projectName string, serviceName string) ([]moby.Container, error)
  39. Exec(ctx context.Context, containerID string, cmd []string, in io.Reader) error
  40. Untar(ctx context.Context, id string, reader io.ReadCloser) error
  41. }
  42. type Tar struct {
  43. client LowLevelClient
  44. projectName string
  45. }
  46. var _ Syncer = &Tar{}
  47. func NewTar(projectName string, client LowLevelClient) *Tar {
  48. return &Tar{
  49. projectName: projectName,
  50. client: client,
  51. }
  52. }
  53. func (t *Tar) Sync(ctx context.Context, service types.ServiceConfig, paths []PathMapping) error {
  54. containers, err := t.client.ContainersForService(ctx, t.projectName, service.Name)
  55. if err != nil {
  56. return err
  57. }
  58. var pathsToCopy []PathMapping
  59. var pathsToDelete []string
  60. for _, p := range paths {
  61. if _, err := os.Stat(p.HostPath); err != nil && errors.Is(err, fs.ErrNotExist) {
  62. pathsToDelete = append(pathsToDelete, p.ContainerPath)
  63. } else {
  64. pathsToCopy = append(pathsToCopy, p)
  65. }
  66. }
  67. var deleteCmd []string
  68. if len(pathsToDelete) != 0 {
  69. deleteCmd = append([]string{"rm", "-rf"}, pathsToDelete...)
  70. }
  71. var eg multierror.Group
  72. for i := range containers {
  73. containerID := containers[i].ID
  74. tarReader := tarArchive(pathsToCopy)
  75. eg.Go(func() error {
  76. if len(deleteCmd) != 0 {
  77. if err := t.client.Exec(ctx, containerID, deleteCmd, nil); err != nil {
  78. return fmt.Errorf("deleting paths in %s: %w", containerID, err)
  79. }
  80. }
  81. if err := t.client.Untar(ctx, containerID, tarReader); err != nil {
  82. return fmt.Errorf("copying files to %s: %w", containerID, err)
  83. }
  84. return nil
  85. })
  86. }
  87. return eg.Wait().ErrorOrNil()
  88. }
  89. type ArchiveBuilder struct {
  90. tw *tar.Writer
  91. // A shared I/O buffer to help with file copying.
  92. copyBuf *bytes.Buffer
  93. }
  94. func NewArchiveBuilder(writer io.Writer) *ArchiveBuilder {
  95. tw := tar.NewWriter(writer)
  96. return &ArchiveBuilder{
  97. tw: tw,
  98. copyBuf: &bytes.Buffer{},
  99. }
  100. }
  101. func (a *ArchiveBuilder) Close() error {
  102. return a.tw.Close()
  103. }
  104. // ArchivePathsIfExist creates a tar archive of all local files in `paths`. It quietly skips any paths that don't exist.
  105. func (a *ArchiveBuilder) ArchivePathsIfExist(paths []PathMapping) error {
  106. // In order to handle overlapping syncs, we
  107. // 1) collect all the entries,
  108. // 2) de-dupe them, with last-one-wins semantics
  109. // 3) write all the entries
  110. //
  111. // It's not obvious that this is the correct behavior. A better approach
  112. // (that's more in-line with how syncs work) might ignore files in earlier
  113. // path mappings when we know they're going to be "synced" over.
  114. // There's a bunch of subtle product decisions about how overlapping path
  115. // mappings work that we're not sure about.
  116. var entries []archiveEntry
  117. for _, p := range paths {
  118. newEntries, err := a.entriesForPath(p.HostPath, p.ContainerPath)
  119. if err != nil {
  120. return fmt.Errorf("inspecting %q: %w", p.HostPath, err)
  121. }
  122. entries = append(entries, newEntries...)
  123. }
  124. entries = dedupeEntries(entries)
  125. for _, entry := range entries {
  126. err := a.writeEntry(entry)
  127. if err != nil {
  128. return fmt.Errorf("archiving %q: %w", entry.path, err)
  129. }
  130. }
  131. return nil
  132. }
  133. func (a *ArchiveBuilder) writeEntry(entry archiveEntry) error {
  134. pathInTar := entry.path
  135. header := entry.header
  136. if header.Typeflag != tar.TypeReg {
  137. // anything other than a regular file (e.g. dir, symlink) just needs the header
  138. if err := a.tw.WriteHeader(header); err != nil {
  139. return fmt.Errorf("writing %q header: %w", pathInTar, err)
  140. }
  141. return nil
  142. }
  143. file, err := os.Open(pathInTar)
  144. if err != nil {
  145. // In case the file has been deleted since we last looked at it.
  146. if os.IsNotExist(err) {
  147. return nil
  148. }
  149. return err
  150. }
  151. defer func() {
  152. _ = file.Close()
  153. }()
  154. // The size header must match the number of contents bytes.
  155. //
  156. // There is room for a race condition here if something writes to the file
  157. // after we've read the file size.
  158. //
  159. // For small files, we avoid this by first copying the file into a buffer,
  160. // and using the size of the buffer to populate the header.
  161. //
  162. // For larger files, we don't want to copy the whole thing into a buffer,
  163. // because that would blow up heap size. There is some danger that this
  164. // will lead to a spurious error when the tar writer validates the sizes.
  165. // That error will be disruptive but will be handled as best as we
  166. // can downstream.
  167. useBuf := header.Size < 5000000
  168. if useBuf {
  169. a.copyBuf.Reset()
  170. _, err = io.Copy(a.copyBuf, file)
  171. if err != nil && !errors.Is(err, io.EOF) {
  172. return fmt.Errorf("copying %q: %w", pathInTar, err)
  173. }
  174. header.Size = int64(len(a.copyBuf.Bytes()))
  175. }
  176. // wait to write the header until _after_ the file is successfully opened
  177. // to avoid generating an invalid tar entry that has a header but no contents
  178. // in the case the file has been deleted
  179. err = a.tw.WriteHeader(header)
  180. if err != nil {
  181. return fmt.Errorf("writing %q header: %w", pathInTar, err)
  182. }
  183. if useBuf {
  184. _, err = io.Copy(a.tw, a.copyBuf)
  185. } else {
  186. _, err = io.Copy(a.tw, file)
  187. }
  188. if err != nil && !errors.Is(err, io.EOF) {
  189. return fmt.Errorf("copying %q: %w", pathInTar, err)
  190. }
  191. // explicitly flush so that if the entry is invalid we will detect it now and
  192. // provide a more meaningful error
  193. if err := a.tw.Flush(); err != nil {
  194. return fmt.Errorf("finalizing %q: %w", pathInTar, err)
  195. }
  196. return nil
  197. }
  198. // tarPath writes the given source path into tarWriter at the given dest (recursively for directories).
  199. // e.g. tarring my_dir --> dest d: d/file_a, d/file_b
  200. // If source path does not exist, quietly skips it and returns no err
  201. func (a *ArchiveBuilder) entriesForPath(localPath, containerPath string) ([]archiveEntry, error) {
  202. localInfo, err := os.Stat(localPath)
  203. if err != nil {
  204. if os.IsNotExist(err) {
  205. return nil, nil
  206. }
  207. return nil, err
  208. }
  209. localPathIsDir := localInfo.IsDir()
  210. if localPathIsDir {
  211. // Make sure we can trim this off filenames to get valid relative filepaths
  212. if !strings.HasSuffix(localPath, string(filepath.Separator)) {
  213. localPath += string(filepath.Separator)
  214. }
  215. }
  216. containerPath = strings.TrimPrefix(containerPath, "/")
  217. result := make([]archiveEntry, 0)
  218. err = filepath.Walk(localPath, func(curLocalPath string, info os.FileInfo, err error) error {
  219. if err != nil {
  220. return fmt.Errorf("walking %q: %w", curLocalPath, err)
  221. }
  222. linkname := ""
  223. if info.Mode()&os.ModeSymlink != 0 {
  224. var err error
  225. linkname, err = os.Readlink(curLocalPath)
  226. if err != nil {
  227. return err
  228. }
  229. }
  230. var name string
  231. //nolint:gocritic
  232. if localPathIsDir {
  233. // Name of file in tar should be relative to source directory...
  234. tmp, err := filepath.Rel(localPath, curLocalPath)
  235. if err != nil {
  236. return fmt.Errorf("making %q relative to %q: %w", curLocalPath, localPath, err)
  237. }
  238. // ...and live inside `dest`
  239. name = path.Join(containerPath, filepath.ToSlash(tmp))
  240. } else if strings.HasSuffix(containerPath, "/") {
  241. name = containerPath + filepath.Base(curLocalPath)
  242. } else {
  243. name = containerPath
  244. }
  245. header, err := archive.FileInfoHeader(name, info, linkname)
  246. if err != nil {
  247. // Not all types of files are allowed in a tarball. That's OK.
  248. // Mimic the Docker behavior and just skip the file.
  249. return nil
  250. }
  251. result = append(result, archiveEntry{
  252. path: curLocalPath,
  253. info: info,
  254. header: header,
  255. })
  256. return nil
  257. })
  258. if err != nil {
  259. return nil, err
  260. }
  261. return result, nil
  262. }
  263. func tarArchive(ops []PathMapping) io.ReadCloser {
  264. pr, pw := io.Pipe()
  265. go func() {
  266. ab := NewArchiveBuilder(pw)
  267. err := ab.ArchivePathsIfExist(ops)
  268. if err != nil {
  269. _ = pw.CloseWithError(fmt.Errorf("adding files to tar: %w", err))
  270. } else {
  271. // propagate errors from the TarWriter::Close() because it performs a final
  272. // Flush() and any errors mean the tar is invalid
  273. if err := ab.Close(); err != nil {
  274. _ = pw.CloseWithError(fmt.Errorf("closing tar: %w", err))
  275. } else {
  276. _ = pw.Close()
  277. }
  278. }
  279. }()
  280. return pr
  281. }
  282. // Dedupe the entries with last-entry-wins semantics.
  283. func dedupeEntries(entries []archiveEntry) []archiveEntry {
  284. seenIndex := make(map[string]int, len(entries))
  285. result := make([]archiveEntry, 0, len(entries))
  286. for i, entry := range entries {
  287. seenIndex[entry.header.Name] = i
  288. }
  289. for i, entry := range entries {
  290. if seenIndex[entry.header.Name] == i {
  291. result = append(result, entry)
  292. }
  293. }
  294. return result
  295. }