tar.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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. "sync"
  28. "github.com/docker/docker/api/types/container"
  29. "github.com/moby/go-archive"
  30. "golang.org/x/sync/errgroup"
  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) ([]container.Summary, 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 string, paths []*PathMapping) error {
  54. containers, err := t.client.ContainersForService(ctx, t.projectName, service)
  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 (
  72. eg errgroup.Group
  73. errMu sync.Mutex
  74. errs = make([]error, 0, len(containers)*2) // max 2 errs per container
  75. )
  76. eg.SetLimit(16) // arbitrary limit, adjust to taste :D
  77. for i := range containers {
  78. containerID := containers[i].ID
  79. tarReader := tarArchive(pathsToCopy)
  80. eg.Go(func() error {
  81. if len(deleteCmd) != 0 {
  82. if err := t.client.Exec(ctx, containerID, deleteCmd, nil); err != nil {
  83. errMu.Lock()
  84. errs = append(errs, fmt.Errorf("deleting paths in %s: %w", containerID, err))
  85. errMu.Unlock()
  86. }
  87. }
  88. if err := t.client.Untar(ctx, containerID, tarReader); err != nil {
  89. errMu.Lock()
  90. errs = append(errs, fmt.Errorf("copying files to %s: %w", containerID, err))
  91. errMu.Unlock()
  92. }
  93. return nil // don't fail-fast; collect all errors
  94. })
  95. }
  96. _ = eg.Wait()
  97. return errors.Join(errs...)
  98. }
  99. type ArchiveBuilder struct {
  100. tw *tar.Writer
  101. // A shared I/O buffer to help with file copying.
  102. copyBuf *bytes.Buffer
  103. }
  104. func NewArchiveBuilder(writer io.Writer) *ArchiveBuilder {
  105. tw := tar.NewWriter(writer)
  106. return &ArchiveBuilder{
  107. tw: tw,
  108. copyBuf: &bytes.Buffer{},
  109. }
  110. }
  111. func (a *ArchiveBuilder) Close() error {
  112. return a.tw.Close()
  113. }
  114. // ArchivePathsIfExist creates a tar archive of all local files in `paths`. It quietly skips any paths that don't exist.
  115. func (a *ArchiveBuilder) ArchivePathsIfExist(paths []PathMapping) error {
  116. // In order to handle overlapping syncs, we
  117. // 1) collect all the entries,
  118. // 2) de-dupe them, with last-one-wins semantics
  119. // 3) write all the entries
  120. //
  121. // It's not obvious that this is the correct behavior. A better approach
  122. // (that's more in-line with how syncs work) might ignore files in earlier
  123. // path mappings when we know they're going to be "synced" over.
  124. // There's a bunch of subtle product decisions about how overlapping path
  125. // mappings work that we're not sure about.
  126. var entries []archiveEntry
  127. for _, p := range paths {
  128. newEntries, err := a.entriesForPath(p.HostPath, p.ContainerPath)
  129. if err != nil {
  130. return fmt.Errorf("inspecting %q: %w", p.HostPath, err)
  131. }
  132. entries = append(entries, newEntries...)
  133. }
  134. entries = dedupeEntries(entries)
  135. for _, entry := range entries {
  136. err := a.writeEntry(entry)
  137. if err != nil {
  138. return fmt.Errorf("archiving %q: %w", entry.path, err)
  139. }
  140. }
  141. return nil
  142. }
  143. func (a *ArchiveBuilder) writeEntry(entry archiveEntry) error {
  144. pathInTar := entry.path
  145. header := entry.header
  146. if header.Typeflag != tar.TypeReg {
  147. // anything other than a regular file (e.g. dir, symlink) just needs the header
  148. if err := a.tw.WriteHeader(header); err != nil {
  149. return fmt.Errorf("writing %q header: %w", pathInTar, err)
  150. }
  151. return nil
  152. }
  153. file, err := os.Open(pathInTar)
  154. if err != nil {
  155. // In case the file has been deleted since we last looked at it.
  156. if os.IsNotExist(err) {
  157. return nil
  158. }
  159. return err
  160. }
  161. defer func() {
  162. _ = file.Close()
  163. }()
  164. // The size header must match the number of contents bytes.
  165. //
  166. // There is room for a race condition here if something writes to the file
  167. // after we've read the file size.
  168. //
  169. // For small files, we avoid this by first copying the file into a buffer,
  170. // and using the size of the buffer to populate the header.
  171. //
  172. // For larger files, we don't want to copy the whole thing into a buffer,
  173. // because that would blow up heap size. There is some danger that this
  174. // will lead to a spurious error when the tar writer validates the sizes.
  175. // That error will be disruptive but will be handled as best as we
  176. // can downstream.
  177. useBuf := header.Size < 5000000
  178. if useBuf {
  179. a.copyBuf.Reset()
  180. _, err = io.Copy(a.copyBuf, file)
  181. if err != nil && !errors.Is(err, io.EOF) {
  182. return fmt.Errorf("copying %q: %w", pathInTar, err)
  183. }
  184. header.Size = int64(len(a.copyBuf.Bytes()))
  185. }
  186. // wait to write the header until _after_ the file is successfully opened
  187. // to avoid generating an invalid tar entry that has a header but no contents
  188. // in the case the file has been deleted
  189. err = a.tw.WriteHeader(header)
  190. if err != nil {
  191. return fmt.Errorf("writing %q header: %w", pathInTar, err)
  192. }
  193. if useBuf {
  194. _, err = io.Copy(a.tw, a.copyBuf)
  195. } else {
  196. _, err = io.Copy(a.tw, file)
  197. }
  198. if err != nil && !errors.Is(err, io.EOF) {
  199. return fmt.Errorf("copying %q: %w", pathInTar, err)
  200. }
  201. // explicitly flush so that if the entry is invalid we will detect it now and
  202. // provide a more meaningful error
  203. if err := a.tw.Flush(); err != nil {
  204. return fmt.Errorf("finalizing %q: %w", pathInTar, err)
  205. }
  206. return nil
  207. }
  208. // entriesForPath writes the given source path into tarWriter at the given dest (recursively for directories).
  209. // e.g. tarring my_dir --> dest d: d/file_a, d/file_b
  210. // If source path does not exist, quietly skips it and returns no err
  211. func (a *ArchiveBuilder) entriesForPath(localPath, containerPath string) ([]archiveEntry, error) {
  212. localInfo, err := os.Stat(localPath)
  213. if err != nil {
  214. if os.IsNotExist(err) {
  215. return nil, nil
  216. }
  217. return nil, err
  218. }
  219. localPathIsDir := localInfo.IsDir()
  220. if localPathIsDir {
  221. // Make sure we can trim this off filenames to get valid relative filepaths
  222. if !strings.HasSuffix(localPath, string(filepath.Separator)) {
  223. localPath += string(filepath.Separator)
  224. }
  225. }
  226. containerPath = strings.TrimPrefix(containerPath, "/")
  227. result := make([]archiveEntry, 0)
  228. err = filepath.Walk(localPath, func(curLocalPath string, info os.FileInfo, err error) error {
  229. if err != nil {
  230. return fmt.Errorf("walking %q: %w", curLocalPath, err)
  231. }
  232. linkname := ""
  233. if info.Mode()&os.ModeSymlink != 0 {
  234. var err error
  235. linkname, err = os.Readlink(curLocalPath)
  236. if err != nil {
  237. return err
  238. }
  239. }
  240. var name string
  241. //nolint:gocritic
  242. if localPathIsDir {
  243. // Name of file in tar should be relative to source directory...
  244. tmp, err := filepath.Rel(localPath, curLocalPath)
  245. if err != nil {
  246. return fmt.Errorf("making %q relative to %q: %w", curLocalPath, localPath, err)
  247. }
  248. // ...and live inside `dest`
  249. name = path.Join(containerPath, filepath.ToSlash(tmp))
  250. } else if strings.HasSuffix(containerPath, "/") {
  251. name = containerPath + filepath.Base(curLocalPath)
  252. } else {
  253. name = containerPath
  254. }
  255. header, err := archive.FileInfoHeader(name, info, linkname)
  256. if err != nil {
  257. // Not all types of files are allowed in a tarball. That's OK.
  258. // Mimic the Docker behavior and just skip the file.
  259. return nil
  260. }
  261. result = append(result, archiveEntry{
  262. path: curLocalPath,
  263. info: info,
  264. header: header,
  265. })
  266. return nil
  267. })
  268. if err != nil {
  269. return nil, err
  270. }
  271. return result, nil
  272. }
  273. func tarArchive(ops []PathMapping) io.ReadCloser {
  274. pr, pw := io.Pipe()
  275. go func() {
  276. ab := NewArchiveBuilder(pw)
  277. err := ab.ArchivePathsIfExist(ops)
  278. if err != nil {
  279. _ = pw.CloseWithError(fmt.Errorf("adding files to tar: %w", err))
  280. } else {
  281. // propagate errors from the TarWriter::Close() because it performs a final
  282. // Flush() and any errors mean the tar is invalid
  283. if err := ab.Close(); err != nil {
  284. _ = pw.CloseWithError(fmt.Errorf("closing tar: %w", err))
  285. } else {
  286. _ = pw.Close()
  287. }
  288. }
  289. }()
  290. return pr
  291. }
  292. // Dedupe the entries with last-entry-wins semantics.
  293. func dedupeEntries(entries []archiveEntry) []archiveEntry {
  294. seenIndex := make(map[string]int, len(entries))
  295. result := make([]archiveEntry, 0, len(entries))
  296. for i, entry := range entries {
  297. seenIndex[entry.header.Name] = i
  298. }
  299. for i, entry := range entries {
  300. if seenIndex[entry.header.Name] == i {
  301. result = append(result, entry)
  302. }
  303. }
  304. return result
  305. }