filesync.go 6.7 KB

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