tar.go 9.1 KB

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