filesync.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. package filesync
  2. import (
  3. "context"
  4. "fmt"
  5. io "io"
  6. "os"
  7. "strings"
  8. "github.com/moby/buildkit/session"
  9. "github.com/pkg/errors"
  10. "github.com/tonistiigi/fsutil"
  11. "google.golang.org/grpc"
  12. "google.golang.org/grpc/codes"
  13. "google.golang.org/grpc/metadata"
  14. "google.golang.org/grpc/status"
  15. )
  16. const (
  17. keyOverrideExcludes = "override-excludes"
  18. keyIncludePatterns = "include-patterns"
  19. keyExcludePatterns = "exclude-patterns"
  20. keyFollowPaths = "followpaths"
  21. keyDirName = "dir-name"
  22. )
  23. type fsSyncProvider struct {
  24. dirs map[string]SyncedDir
  25. p progressCb
  26. doneCh chan error
  27. }
  28. type SyncedDir struct {
  29. Name string
  30. Dir string
  31. Excludes []string
  32. Map func(*fsutil.Stat) bool
  33. }
  34. // NewFSSyncProvider creates a new provider for sending files from client
  35. func NewFSSyncProvider(dirs []SyncedDir) session.Attachable {
  36. p := &fsSyncProvider{
  37. dirs: map[string]SyncedDir{},
  38. }
  39. for _, d := range dirs {
  40. p.dirs[d.Name] = d
  41. }
  42. return p
  43. }
  44. func (sp *fsSyncProvider) Register(server *grpc.Server) {
  45. RegisterFileSyncServer(server, sp)
  46. }
  47. func (sp *fsSyncProvider) DiffCopy(stream FileSync_DiffCopyServer) error {
  48. return sp.handle("diffcopy", stream)
  49. }
  50. func (sp *fsSyncProvider) TarStream(stream FileSync_TarStreamServer) error {
  51. return sp.handle("tarstream", stream)
  52. }
  53. func (sp *fsSyncProvider) handle(method string, stream grpc.ServerStream) (retErr error) {
  54. var pr *protocol
  55. for _, p := range supportedProtocols {
  56. if method == p.name && isProtoSupported(p.name) {
  57. pr = &p
  58. break
  59. }
  60. }
  61. if pr == nil {
  62. return errors.New("failed to negotiate protocol")
  63. }
  64. opts, _ := metadata.FromIncomingContext(stream.Context()) // if no metadata continue with empty object
  65. dirName := ""
  66. name, ok := opts[keyDirName]
  67. if ok && len(name) > 0 {
  68. dirName = name[0]
  69. }
  70. dir, ok := sp.dirs[dirName]
  71. if !ok {
  72. return status.Errorf(codes.NotFound, "no access allowed to dir %q", dirName)
  73. }
  74. excludes := opts[keyExcludePatterns]
  75. if len(dir.Excludes) != 0 && (len(opts[keyOverrideExcludes]) == 0 || opts[keyOverrideExcludes][0] != "true") {
  76. excludes = dir.Excludes
  77. }
  78. includes := opts[keyIncludePatterns]
  79. followPaths := opts[keyFollowPaths]
  80. var progress progressCb
  81. if sp.p != nil {
  82. progress = sp.p
  83. sp.p = nil
  84. }
  85. var doneCh chan error
  86. if sp.doneCh != nil {
  87. doneCh = sp.doneCh
  88. sp.doneCh = nil
  89. }
  90. err := pr.sendFn(stream, fsutil.NewFS(dir.Dir, &fsutil.WalkOpt{
  91. ExcludePatterns: excludes,
  92. IncludePatterns: includes,
  93. FollowPaths: followPaths,
  94. Map: dir.Map,
  95. }), progress)
  96. if doneCh != nil {
  97. if err != nil {
  98. doneCh <- err
  99. }
  100. close(doneCh)
  101. }
  102. return err
  103. }
  104. func (sp *fsSyncProvider) SetNextProgressCallback(f func(int, bool), doneCh chan error) {
  105. sp.p = f
  106. sp.doneCh = doneCh
  107. }
  108. type progressCb func(int, bool)
  109. type protocol struct {
  110. name string
  111. sendFn func(stream grpc.Stream, fs fsutil.FS, progress progressCb) error
  112. recvFn func(stream grpc.Stream, destDir string, cu CacheUpdater, progress progressCb) error
  113. }
  114. func isProtoSupported(p string) bool {
  115. // TODO: this should be removed after testing if stability is confirmed
  116. if override := os.Getenv("BUILD_STREAM_PROTOCOL"); override != "" {
  117. return strings.EqualFold(p, override)
  118. }
  119. return true
  120. }
  121. var supportedProtocols = []protocol{
  122. {
  123. name: "diffcopy",
  124. sendFn: sendDiffCopy,
  125. recvFn: recvDiffCopy,
  126. },
  127. }
  128. // FSSendRequestOpt defines options for FSSend request
  129. type FSSendRequestOpt struct {
  130. Name string
  131. IncludePatterns []string
  132. ExcludePatterns []string
  133. FollowPaths []string
  134. OverrideExcludes bool // deprecated: this is used by docker/cli for automatically loading .dockerignore from the directory
  135. DestDir string
  136. CacheUpdater CacheUpdater
  137. ProgressCb func(int, bool)
  138. }
  139. // CacheUpdater is an object capable of sending notifications for the cache hash changes
  140. type CacheUpdater interface {
  141. MarkSupported(bool)
  142. HandleChange(fsutil.ChangeKind, string, os.FileInfo, error) error
  143. ContentHasher() fsutil.ContentHasher
  144. }
  145. // FSSync initializes a transfer of files
  146. func FSSync(ctx context.Context, c session.Caller, opt FSSendRequestOpt) error {
  147. var pr *protocol
  148. for _, p := range supportedProtocols {
  149. if isProtoSupported(p.name) && c.Supports(session.MethodURL(_FileSync_serviceDesc.ServiceName, p.name)) {
  150. pr = &p
  151. break
  152. }
  153. }
  154. if pr == nil {
  155. return errors.New("no local sources enabled")
  156. }
  157. opts := make(map[string][]string)
  158. if opt.OverrideExcludes {
  159. opts[keyOverrideExcludes] = []string{"true"}
  160. }
  161. if opt.IncludePatterns != nil {
  162. opts[keyIncludePatterns] = opt.IncludePatterns
  163. }
  164. if opt.ExcludePatterns != nil {
  165. opts[keyExcludePatterns] = opt.ExcludePatterns
  166. }
  167. if opt.FollowPaths != nil {
  168. opts[keyFollowPaths] = opt.FollowPaths
  169. }
  170. opts[keyDirName] = []string{opt.Name}
  171. ctx, cancel := context.WithCancel(ctx)
  172. defer cancel()
  173. client := NewFileSyncClient(c.Conn())
  174. var stream grpc.ClientStream
  175. ctx = metadata.NewOutgoingContext(ctx, opts)
  176. switch pr.name {
  177. case "tarstream":
  178. cc, err := client.TarStream(ctx)
  179. if err != nil {
  180. return err
  181. }
  182. stream = cc
  183. case "diffcopy":
  184. cc, err := client.DiffCopy(ctx)
  185. if err != nil {
  186. return err
  187. }
  188. stream = cc
  189. default:
  190. panic(fmt.Sprintf("invalid protocol: %q", pr.name))
  191. }
  192. return pr.recvFn(stream, opt.DestDir, opt.CacheUpdater, opt.ProgressCb)
  193. }
  194. // NewFSSyncTargetDir allows writing into a directory
  195. func NewFSSyncTargetDir(outdir string) session.Attachable {
  196. p := &fsSyncTarget{
  197. outdir: outdir,
  198. }
  199. return p
  200. }
  201. // NewFSSyncTarget allows writing into an io.WriteCloser
  202. func NewFSSyncTarget(w io.WriteCloser) session.Attachable {
  203. p := &fsSyncTarget{
  204. outfile: w,
  205. }
  206. return p
  207. }
  208. type fsSyncTarget struct {
  209. outdir string
  210. outfile io.WriteCloser
  211. }
  212. func (sp *fsSyncTarget) Register(server *grpc.Server) {
  213. RegisterFileSendServer(server, sp)
  214. }
  215. func (sp *fsSyncTarget) DiffCopy(stream FileSend_DiffCopyServer) error {
  216. if sp.outdir != "" {
  217. return syncTargetDiffCopy(stream, sp.outdir)
  218. }
  219. if sp.outfile == nil {
  220. return errors.New("empty outfile and outdir")
  221. }
  222. defer sp.outfile.Close()
  223. return writeTargetFile(stream, sp.outfile)
  224. }
  225. func CopyToCaller(ctx context.Context, fs fsutil.FS, c session.Caller, progress func(int, bool)) error {
  226. method := session.MethodURL(_FileSend_serviceDesc.ServiceName, "diffcopy")
  227. if !c.Supports(method) {
  228. return errors.Errorf("method %s not supported by the client", method)
  229. }
  230. client := NewFileSendClient(c.Conn())
  231. cc, err := client.DiffCopy(ctx)
  232. if err != nil {
  233. return err
  234. }
  235. return sendDiffCopy(cc, fs, progress)
  236. }
  237. func CopyFileWriter(ctx context.Context, c session.Caller) (io.WriteCloser, error) {
  238. method := session.MethodURL(_FileSend_serviceDesc.ServiceName, "diffcopy")
  239. if !c.Supports(method) {
  240. return nil, errors.Errorf("method %s not supported by the client", method)
  241. }
  242. client := NewFileSendClient(c.Conn())
  243. cc, err := client.DiffCopy(ctx)
  244. if err != nil {
  245. return nil, err
  246. }
  247. return newStreamWriter(cc), nil
  248. }