Debian Codegraph @

tq/transfer_queue.go

raw symbols SCIP
1 package tq
2
3 import (
4 "fmt"
5 "os"
6 "sort"
7 "sync"
8 "time"
9
10 "github.com/git-lfs/git-lfs/v3/errors"
11 "github.com/git-lfs/git-lfs/v3/git"
12 "github.com/git-lfs/git-lfs/v3/lfshttp"
13 "github.com/git-lfs/git-lfs/v3/tools"
14 "github.com/git-lfs/git-lfs/v3/tr"
15 "github.com/rubyist/tracerx"
16 )
17
18 const (
19 defaultBatchSize = 100
20 baseRetryDelayMs = 250
21 )
22
23 type retryCounter struct {
24 MaxRetries int
25 MaxRetryDelay int
26
27 // cmu guards count
28 cmu sync.Mutex
29 // count maps OIDs to number of retry attempts
30 count map[string]int
31 }
32
33 // newRetryCounter instantiates a new *retryCounter.
34 func newRetryCounter() *retryCounter {
35 return &retryCounter{
36 MaxRetries: defaultMaxRetries,
37 MaxRetryDelay: defaultMaxRetryDelay,
38 count: make(map[string]int),
39 }
40 }
41
42 // Increment increments the number of retries for a given OID and returns the
43 // new value. It is safe to call across multiple goroutines.
44 func (r *retryCounter) Increment(oid string) int {
45 r.cmu.Lock()
46 defer r.cmu.Unlock()
47
48 r.count[oid]++
49 return r.count[oid]
50 }
51
52 // CountFor returns the current number of retries for a given OID. It is safe to
53 // call across multiple goroutines.
54 func (r *retryCounter) CountFor(oid string) int {
55 r.cmu.Lock()
56 defer r.cmu.Unlock()
57
58 return r.count[oid]
59 }
60
61 // CanRetry returns the current number of retries, and whether or not it exceeds
62 // the maximum number of retries (see: retryCounter.MaxRetries).
63 func (r *retryCounter) CanRetry(oid string) (int, bool) {
64 count := r.CountFor(oid)
65 return count, count < r.MaxRetries
66 }
67
68 // ReadyTime returns the time from now when the current retry can occur or the
69 // zero time if the retry can occur immediately.
70 func (r *retryCounter) ReadyTime(oid string) time.Time {
71 count := r.CountFor(oid)
72 if count < 1 {
73 return time.Time{}
74 }
75
76 maxDelayMs := 1000 * uint64(r.MaxRetryDelay)
77 delay := uint64(baseRetryDelayMs) * (1 << uint(count-1))
78 if delay == 0 || delay > maxDelayMs {
79 delay = maxDelayMs
80 }
81 return time.Now().Add(time.Duration(delay) * time.Millisecond)
82 }
83
84 // batch implements the sort.Interface interface and enables sorting on a slice
85 // of `*Transfer`s by object size.
86 //
87 // This interface is implemented here so that the largest objects can be
88 // processed first. Since adding a new batch is unable to occur until the
89 // current batch has finished processing, this enables us to reduce the risk of
90 // a single worker getting tied up on a large item at the end of a batch while
91 // all other workers are sitting idle.
92 type batch []*objectTuple
93
94 // Concat concatenates two batches together, returning a single, clamped batch as
95 // "left", and the remainder of elements as "right". If the union of the
96 // receiver and "other" has cardinality less than "size", "right" will be
97 // returned as nil. Any object tuple that is not currently able to be retried
98 // (ie Retry-After response), will also go into the right batch. Also, when object(s)
99 // are returned that are rate-limited, return the minimum duration required to wait until
100 // a object is ready.
101 func (b batch) Concat(other batch, size int) (left, right batch, minWait time.Duration) {
102 u := batch(append(b, other...))
103 for _, ot := range u {
104 if time.Now().After(ot.ReadyTime) {
105 // The current time is past the time the object should
106 // be available.
107 left = append(left, ot)
108 } else {
109 // The time hasn't passed for the object.
110 right = append(right, ot)
111 wait := time.Until(ot.ReadyTime)
112 if minWait == 0 {
113 minWait = wait
114 } else if wait < minWait {
115 minWait = wait
116 }
117 }
118 }
119 if len(left) <= size {
120 // If the size of left fits the given size limit, return with no adjustments.
121 return left, right, minWait
122 }
123 // If left is too large, trip left up to size and append the rest to right.
124 right = append(right, left[size:]...)
125 left = left[:size]
126 return left, right, minWait
127 }
128
129 func (b batch) ToTransfers() []*Transfer {
130 transfers := make([]*Transfer, 0, len(b))
131 for _, t := range b {
132 transfers = append(transfers, &Transfer{Oid: t.Oid, Size: t.Size})
133 }
134 return transfers
135 }
136
137 func (b batch) Len() int { return len(b) }
138 func (b batch) Less(i, j int) bool { return b[i].Size < b[j].Size }
139 func (b batch) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
140
141 type abortableWaitGroup struct {
142 wq sync.WaitGroup
143 counter int
144 mu sync.Mutex
145 abort bool
146 }
147
148 func newAbortableWaitGroup() *abortableWaitGroup {
149 return &abortableWaitGroup{}
150 }
151
152 func (q *abortableWaitGroup) Add(delta int) {
153 q.mu.Lock()
154 defer q.mu.Unlock()
155
156 if !q.abort {
157 q.counter += delta
158 q.wq.Add(delta)
159 }
160 }
161
162 func (q *abortableWaitGroup) Done() {
163 q.mu.Lock()
164 defer q.mu.Unlock()
165
166 if !q.abort {
167 q.counter -= 1
168 q.wq.Done()
169 }
170 }
171
172 func (q *abortableWaitGroup) Abort() {
173 q.mu.Lock()
174 defer q.mu.Unlock()
175
176 q.abort = true
177 q.wq.Add(-q.counter)
178 }
179
180 func (q *abortableWaitGroup) Wait() {
181 q.wq.Wait()
182 }
183
184 // TransferQueue organises the wider process of uploading and downloading,
185 // including calling the API, passing the actual transfer request to transfer
186 // adapters, and dealing with progress, errors and retries.
187 type TransferQueue struct {
188 direction Direction
189 client *tqClient
190 remote string
191 ref *git.Ref
192 adapter Adapter
193 adapterInProgress bool
194 adapterInitMutex sync.Mutex
195 dryRun bool
196 cb tools.CopyCallback
197 meter *Meter
198 errors []error
199 transfers map[string]*objects
200 batchSize int
201 bufferDepth int
202 incoming chan *objectTuple // Channel for processing incoming items
203 errorc chan error // Channel for processing errors
204 watchers []chan *Transfer
205 trMutex *sync.Mutex
206 collectorWait sync.WaitGroup
207 errorwait sync.WaitGroup
208 // wait is used to keep track of pending transfers. It is incremented
209 // once per unique OID on Add(), and is decremented when that transfer
210 // is marked as completed or failed, but not retried.
211 wait *abortableWaitGroup
212 manifest Manifest
213 rc *retryCounter
214
215 // unsupportedContentType indicates whether the transfer queue ever saw
216 // an HTTP 422 response indicating that their upload destination does
217 // not support Content-Type detection.
218 unsupportedContentType bool
219 }
220
221 // objects holds a set of objects.
222 type objects struct {
223 completed bool
224 objects []*objectTuple
225 }
226
227 // All returns all *objectTuple's contained in the *objects set.
228 func (s *objects) All() []*objectTuple {
229 return s.objects
230 }
231
232 // Append returns a new *objects with the given *objectTuple(s) appended to the
233 // end of the known objects.
234 func (s *objects) Append(os ...*objectTuple) *objects {
235 return &objects{
236 completed: s.completed,
237 objects: append(s.objects, os...),
238 }
239 }
240
241 // First returns the first *objectTuple in the chain of objects.
242 func (s *objects) First() *objectTuple {
243 if len(s.objects) == 0 {
244 return nil
245 }
246 return s.objects[0]
247 }
248
249 type objectTuple struct {
250 Name, Path, Oid string
251 Size int64
252 Missing bool
253 ReadyTime time.Time
254 retryLaterTime time.Time
255 }
256
257 func (o *objectTuple) ToTransfer() *Transfer {
258 return &Transfer{
259 Name: o.Name,
260 Path: o.Path,
261 Oid: o.Oid,
262 Size: o.Size,
263 Missing: o.Missing,
264 }
265 }
266
267 type Option func(*TransferQueue)
268
269 func DryRun(dryRun bool) Option {
270 return func(tq *TransferQueue) {
271 tq.dryRun = dryRun
272 }
273 }
274
275 func WithProgress(m *Meter) Option {
276 return func(tq *TransferQueue) {
277 tq.meter = m
278 }
279 }
280
281 func RemoteRef(ref *git.Ref) Option {
282 return func(tq *TransferQueue) {
283 tq.ref = ref
284 }
285 }
286
287 func WithProgressCallback(cb tools.CopyCallback) Option {
288 return func(tq *TransferQueue) {
289 tq.cb = cb
290 }
291 }
292
293 func WithBatchSize(size int) Option {
294 return func(tq *TransferQueue) { tq.batchSize = size }
295 }
296
297 func WithBufferDepth(depth int) Option {
298 return func(tq *TransferQueue) { tq.bufferDepth = depth }
299 }
300
301 // NewTransferQueue builds a TransferQueue, direction and underlying mechanism determined by adapter
302 func NewTransferQueue(dir Direction, manifest Manifest, remote string, options ...Option) *TransferQueue {
303 q := &TransferQueue{
304 direction: dir,
305 remote: remote,
306 errorc: make(chan error),
307 transfers: make(map[string]*objects),
308 trMutex: &sync.Mutex{},
309 manifest: manifest,
310 rc: newRetryCounter(),
311 wait: newAbortableWaitGroup(),
312 }
313
314 for _, opt := range options {
315 opt(q)
316 }
317
318 if q.batchSize <= 0 {
319 q.batchSize = defaultBatchSize
320 }
321 if q.bufferDepth <= 0 {
322 q.bufferDepth = q.batchSize
323 }
324 if q.meter != nil {
325 q.meter.Direction = q.direction
326 }
327
328 q.incoming = make(chan *objectTuple, q.bufferDepth)
329 q.collectorWait.Add(1)
330 q.errorwait.Add(1)
331 q.run()
332
333 return q
334 }
335
336 // Ensure we have a concrete manifest and that certain delayed variables are set
337 // properly.
338 func (q *TransferQueue) Upgrade() {
339 if q.client == nil {
340 manifest := q.manifest.Upgrade()
341 q.client = &tqClient{Client: manifest.APIClient()}
342 q.rc.MaxRetries = manifest.maxRetries
343 q.rc.MaxRetryDelay = manifest.maxRetryDelay
344 q.client.SetMaxRetries(manifest.maxRetries)
345 }
346 }
347
348 // Add adds a *Transfer to the transfer queue. It only increments the amount
349 // of waiting the TransferQueue has to do if the *Transfer "t" is new.
350 //
351 // If another transfer(s) with the same OID has been added to the *TransferQueue
352 // already, the given transfer will not be enqueued, but will be sent to any
353 // channel created by Watch() once the oldest transfer has completed.
354 //
355 // Only one file will be transferred to/from the Path element of the first
356 // transfer.
357 func (q *TransferQueue) Add(name, path, oid string, size int64, missing bool, err error) {
358 q.Upgrade()
359
360 if err != nil {
361 q.errorc <- err
362 return
363 }
364
365 t := &objectTuple{
366 Name: name,
367 Path: path,
368 Oid: oid,
369 Size: size,
370 Missing: missing,
371 }
372
373 if objs := q.remember(t); len(objs.objects) > 1 {
374 if objs.completed {
375 // If there is already a completed transfer chain for
376 // this OID, then this object is already "done", and can
377 // be sent through as completed to the watchers.
378 for _, w := range q.watchers {
379 w <- t.ToTransfer()
380 }
381 }
382
383 // If the chain is not done, there is no reason to enqueue this
384 // transfer into 'q.incoming'.
385 tracerx.Printf("already transferring %q, skipping duplicate", t.Oid)
386 return
387 }
388
389 q.incoming <- t
390 }
391
392 // remember remembers the *Transfer "t" if the *TransferQueue doesn't already
393 // know about a Transfer with the same OID.
394 //
395 // It returns if the value is new or not.
396 func (q *TransferQueue) remember(t *objectTuple) objects {
397 q.Upgrade()
398
399 q.trMutex.Lock()
400 defer q.trMutex.Unlock()
401
402 if _, ok := q.transfers[t.Oid]; !ok {
403 q.wait.Add(1)
404 q.transfers[t.Oid] = &objects{
405 objects: []*objectTuple{t},
406 }
407
408 return *q.transfers[t.Oid]
409 }
410
411 q.transfers[t.Oid] = q.transfers[t.Oid].Append(t)
412
413 return *q.transfers[t.Oid]
414 }
415
416 // collectBatches collects batches in a loop, prioritizing failed items from the
417 // previous before adding new items. The process works as follows:
418 //
419 // 1. Create a new batch, of size `q.batchSize`, and containing no items
420 // 2. While the batch contains less items than `q.batchSize` AND the channel
421 // is open, read one item from the `q.incoming` channel.
422 // a. If the read was a channel close, go to step 4.
423 // b. If the read was a transferable item, go to step 3.
424 // 3. Append the item to the batch.
425 // 4. Sort the batch by descending object size, make a batch API call, send
426 // the items to the `*adapterBase`.
427 // 5. In a separate goroutine, process the worker results, incrementing and
428 // appending retries if possible. On the main goroutine, accept new items
429 // into "pending".
430 // 6. Concat() the "next" and "pending" batches such that no more items than
431 // the maximum allowed per batch are in next, and the rest are in pending.
432 // 7. If the `q.incoming` channel is open, go to step 2.
433 // 8. If the next batch is empty AND the `q.incoming` channel is closed,
434 // terminate immediately.
435 //
436 // collectBatches runs in its own goroutine.
437 func (q *TransferQueue) collectBatches() {
438 defer q.collectorWait.Done()
439
440 var closing bool
441 next := q.makeBatch()
442 pending := q.makeBatch()
443
444 for {
445 for !closing && (len(next) < q.batchSize) {
446 t, ok := <-q.incoming
447 if !ok {
448 closing = true
449 break
450 }
451
452 next = append(next, t)
453 }
454
455 // Before enqueuing the next batch, sort by descending object
456 // size.
457 sort.Sort(sort.Reverse(next))
458
459 done := make(chan struct{})
460
461 var retries batch
462 var err error
463
464 go func() {
465 defer close(done)
466
467 if len(next) == 0 {
468 return
469 }
470
471 retries, err = q.enqueueAndCollectRetriesFor(next)
472 if err != nil {
473 q.errorc <- err
474 }
475 }()
476
477 var collected batch
478 collected, closing = q.collectPendingUntil(done)
479
480 // If we've encountered a serious error here, abort immediately;
481 // don't process further batches. Abort the wait queue so that
482 // we don't deadlock waiting for objects to complete when they
483 // never will.
484 if err != nil && !errors.IsRetriableError(err) {
485 q.wait.Abort()
486 break
487 }
488
489 // Ensure the next batch is filled with, in order:
490 //
491 // - retries from the previous batch,
492 // - new additions that were enqueued behind retries, &
493 // - items collected while the batch was processing.
494 var minWaitTime time.Duration
495 next, pending, minWaitTime = retries.Concat(append(pending, collected...), q.batchSize)
496 if len(next) == 0 && len(pending) != 0 {
497 // There are some pending that could not be queued.
498 // Wait the requested time before resuming loop.
499 tracerx.Printf("tq: rate limited, waiting %s before retrying", minWaitTime)
500 time.Sleep(minWaitTime)
501 } else if len(next) == 0 && len(pending) == 0 && closing {
502 // There are no items remaining, it is safe to break
503 break
504 }
505 }
506 }
507
508 // collectPendingUntil collects items from q.incoming into a "pending" batch
509 // until the given "done" channel is written to, or is closed.
510 //
511 // A "pending" batch is returned, along with whether or not "q.incoming" is
512 // closed.
513 func (q *TransferQueue) collectPendingUntil(done <-chan struct{}) (pending batch, closing bool) {
514 q.Upgrade()
515
516 for {
517 select {
518 case t, ok := <-q.incoming:
519 if !ok {
520 closing = true
521 <-done
522 return
523 }
524
525 pending = append(pending, t)
526 case <-done:
527 return
528 }
529 }
530 }
531
532 // enqueueAndCollectRetriesFor makes a Batch API call and returns a "next" batch
533 // containing all of the objects that failed from the previous batch and had
534 // retries available to them.
535 //
536 // If an error was encountered while making the API request, _all_ of the items
537 // from the previous batch (that have retries available to them) will be
538 // returned immediately, along with the error that was encountered.
539 //
540 // enqueueAndCollectRetriesFor blocks until the entire Batch "batch" has been
541 // processed.
542 func (q *TransferQueue) enqueueAndCollectRetriesFor(batch batch) (batch, error) {
543 q.Upgrade()
544
545 next := q.makeBatch()
546 tracerx.Printf("tq: sending batch of size %d", len(batch))
547
548 enqueueRetry := func(t *objectTuple, err error, readyTime *time.Time) {
549 count := q.rc.Increment(t.Oid)
550
551 if !t.retryLaterTime.IsZero() {
552 t.ReadyTime = t.retryLaterTime
553 t.retryLaterTime = time.Time{}
554 } else if readyTime == nil {
555 t.ReadyTime = q.rc.ReadyTime(t.Oid)
556 } else {
557 t.ReadyTime = *readyTime
558 }
559 delay := time.Until(t.ReadyTime).Seconds()
560
561 var errMsg string
562 if err != nil {
563 errMsg = fmt.Sprintf(": %s", err)
564 }
565 tracerx.Printf("tq: enqueue retry #%d after %.2fs for %q (size: %d)%s", count, delay, t.Oid, t.Size, errMsg)
566 next = append(next, t)
567 }
568
569 q.meter.Pause()
570 var bRes *BatchResponse
571 manifest := q.manifest.Upgrade()
572 if manifest.standaloneTransferAgent != "" {
573 // Trust the external transfer agent can do everything by itself.
574 objects := make([]*Transfer, 0, len(batch))
575 for _, t := range batch {
576 objects = append(objects, &Transfer{Oid: t.Oid, Size: t.Size, Path: t.Path})
577 }
578 bRes = &BatchResponse{
579 Objects: objects,
580 TransferAdapterName: manifest.standaloneTransferAgent,
581 }
582 } else {
583 // Query the Git LFS server for what transfer method to use and
584 // details such as URLs, authentication, etc.
585 var err error
586 bRes, err = Batch(q.manifest, q.direction, q.remote, q.ref, batch.ToTransfers())
587 if err != nil {
588 hasNonRetriableObjects := false
589 // If there was an error making the batch API call, mark all of
590 // the objects for retry if possible. If any should not be retried,
591 // they will be marked as failed.
592 for _, t := range batch {
593 if q.canRetryObject(t.Oid, err) {
594 enqueueRetry(t, err, nil)
595 } else if readyTime, canRetry := q.canRetryObjectLater(t.Oid, err); canRetry {
596 enqueueRetry(t, err, &readyTime)
597 } else {
598 hasNonRetriableObjects = true
599 q.wait.Done()
600 }
601 }
602
603 // Only return error and mark operation as failure if at least one object
604 // was not enqueued for retrial at a later point.
605 // Make sure to return an error which causes all other objects to be retried.
606 if hasNonRetriableObjects {
607 return next, errors.NewRetriableError(err)
608 } else {
609 return next, nil
610 }
611 }
612 }
613
614 if len(bRes.Objects) == 0 {
615 return next, nil
616 }
617
618 // We check first that all of the objects we want to upload are present,
619 // and abort if any are missing. We'll never have any objects marked as
620 // missing except possibly on upload, so just skip iterating over the
621 // objects in that case.
622 if q.direction == Upload {
623 for _, o := range bRes.Objects {
624 // If the server already has the object, the list of
625 // actions will be empty. It's fine if the file is
626 // missing in that case, since we don't need to upload
627 // it.
628 if len(o.Actions) != 0 {
629 q.trMutex.Lock()
630 objects, ok := q.transfers[o.Oid]
631 q.trMutex.Unlock()
632 // We expect only one objectTuple in this list
633 // as the uploadContext methods deduplicate
634 // identical OIDs before adding them to the
635 // transfer queue.
636 if ok && objects.First().Missing {
637 tracerx.Printf("tq: stopping batched queue, object %q missing locally and on remote", o.Oid)
638 return nil, newObjectMissingError(objects.First().Name, o.Oid)
639 }
640 }
641 }
642 }
643
644 q.useAdapter(bRes.TransferAdapterName)
645 q.meter.Start()
646
647 toTransfer := make([]*Transfer, 0, len(bRes.Objects))
648
649 for _, o := range bRes.Objects {
650 if o.Error != nil {
651 q.errorc <- errors.Wrapf(o.Error, "[%v] %v", o.Oid, o.Error.Message)
652 q.Skip(o.Size)
653 q.wait.Done()
654
655 continue
656 }
657
658 q.trMutex.Lock()
659 objects, ok := q.transfers[o.Oid]
660 q.trMutex.Unlock()
661 if !ok {
662 // If we couldn't find any associated
663 // Transfer object, then we give up on the
664 // transfer by telling the progress meter to
665 // skip the number of bytes in "o".
666 q.errorc <- errors.New(tr.Tr.Get("[%v] The server returned an unknown OID.", o.Oid))
667
668 q.Skip(o.Size)
669 q.wait.Done()
670 } else {
671 // Pick t[0], since it will cover all transfers with the
672 // same OID.
673 tr := newTransfer(o, objects.First().Name, objects.First().Path)
674
675 if a, err := tr.Rel(q.direction.String()); err != nil {
676 if q.canRetryObject(tr.Oid, err) {
677 enqueueRetry(objects.First(), err, nil)
678 } else {
679 q.errorc <- errors.Errorf("[%v] %v", tr.Name, err)
680
681 q.Skip(o.Size)
682 q.wait.Done()
683 }
684 } else if a == nil && manifest.standaloneTransferAgent == "" {
685 q.Skip(o.Size)
686 q.wait.Done()
687 } else {
688 q.meter.StartTransfer(objects.First().Name)
689 toTransfer = append(toTransfer, tr)
690 }
691 }
692 }
693
694 retries := q.addToAdapter(bRes.endpoint, toTransfer)
695 for t := range retries {
696 enqueueRetry(t, nil, nil)
697 }
698
699 return next, nil
700 }
701
702 // makeBatch returns a new, empty batch, with a capacity equal to the maximum
703 // batch size designated by the `*TransferQueue`.
704 func (q *TransferQueue) makeBatch() batch { return make(batch, 0, q.batchSize) }
705
706 // addToAdapter adds the given "pending" transfers to the transfer adapters and
707 // returns a channel of Transfers that are to be retried in the next batch.
708 // After all of the items in the batch have been processed, the channel is
709 // closed.
710 //
711 // addToAdapter returns immediately, and does not block.
712 func (q *TransferQueue) addToAdapter(e lfshttp.Endpoint, pending []*Transfer) <-chan *objectTuple {
713 q.Upgrade()
714
715 retries := make(chan *objectTuple, len(pending))
716
717 if err := q.ensureAdapterBegun(e); err != nil {
718 close(retries)
719
720 q.errorc <- err
721 for _, t := range pending {
722 q.Skip(t.Size)
723 q.wait.Done()
724 }
725
726 return retries
727 }
728
729 present, missingResults := q.partitionTransfers(pending)
730
731 go func() {
732 defer close(retries)
733
734 var results <-chan TransferResult
735 if q.dryRun {
736 results = q.makeDryRunResults(present)
737 } else {
738 results = q.adapter.Add(present...)
739 }
740
741 for _, res := range missingResults {
742 q.handleTransferResult(res, retries)
743 }
744 for res := range results {
745 q.handleTransferResult(res, retries)
746 }
747 }()
748
749 return retries
750 }
751
752 func (q *TransferQueue) partitionTransfers(transfers []*Transfer) (present []*Transfer, results []TransferResult) {
753 q.Upgrade()
754
755 if q.direction != Upload {
756 return transfers, nil
757 }
758
759 present = make([]*Transfer, 0, len(transfers))
760 results = make([]TransferResult, 0, len(transfers))
761
762 for _, t := range transfers {
763 var err error
764
765 if t.Size < 0 {
766 err = errors.New(tr.Tr.Get("object %q has invalid size (got: %d)", t.Oid, t.Size))
767 } else {
768 fd, serr := os.Stat(t.Path)
769 if serr != nil {
770 if os.IsNotExist(serr) {
771 err = newObjectMissingError(t.Name, t.Oid)
772 } else {
773 err = serr
774 }
775 } else if t.Size != fd.Size() {
776 err = newCorruptObjectError(t.Name, t.Oid)
777 }
778 }
779
780 if err != nil {
781 results = append(results, TransferResult{
782 Transfer: t,
783 Error: err,
784 })
785 } else {
786 present = append(present, t)
787 }
788 }
789
790 return
791 }
792
793 // makeDryRunResults returns a channel populated immediately with "successful"
794 // results for all of the given transfers in "ts".
795 func (q *TransferQueue) makeDryRunResults(ts []*Transfer) <-chan TransferResult {
796 results := make(chan TransferResult, len(ts))
797 for _, t := range ts {
798 results <- TransferResult{t, nil}
799 }
800
801 close(results)
802
803 return results
804 }
805
806 // handleTransferResult observes the transfer result, sending it on the retries
807 // channel if it was able to be retried.
808 func (q *TransferQueue) handleTransferResult(
809 res TransferResult, retries chan<- *objectTuple,
810 ) {
811 oid := res.Transfer.Oid
812
813 if res.Error != nil {
814 // If there was an error encountered when processing the
815 // transfer (res.Transfer), handle the error as is appropriate:
816 if readyTime, canRetry := q.canRetryObjectLater(oid, res.Error); canRetry {
817 // If the object can't be retried now, but can be
818 // after a certain period of time, send it to
819 // the retry channel with a time when it's ready.
820 tracerx.Printf("tq: retrying object %s after %.2fs", oid, time.Until(readyTime).Seconds())
821 q.trMutex.Lock()
822 objects, ok := q.transfers[oid]
823 q.trMutex.Unlock()
824
825 if ok {
826 t := objects.First()
827 t.retryLaterTime = readyTime
828 retries <- t
829 } else {
830 q.errorc <- res.Error
831 }
832 } else if q.canRetryObject(oid, res.Error) {
833 // If the object can be retried, send it on the retries
834 // channel, where it will be read at the call-site and
835 // its retry count will be incremented.
836 tracerx.Printf("tq: retrying object %s: %s", oid, res.Error)
837
838 q.trMutex.Lock()
839 objects, ok := q.transfers[oid]
840 q.trMutex.Unlock()
841
842 if ok {
843 retries <- objects.First()
844 } else {
845 q.errorc <- res.Error
846 }
847 } else {
848 // If the error wasn't retriable, OR the object has
849 // exceeded its retry budget, it will be NOT be sent to
850 // the retry channel, and the error will be reported
851 // immediately (unless the error is in response to a
852 // HTTP 422).
853 if errors.IsUnprocessableEntityError(res.Error) {
854 q.unsupportedContentType = true
855 } else {
856 q.errorc <- res.Error
857 }
858 q.wait.Done()
859 }
860 } else {
861 q.trMutex.Lock()
862 objects := q.transfers[oid]
863 objects.completed = true
864
865 // Otherwise, if the transfer was successful, notify all of the
866 // watchers, and mark it as finished.
867 for _, c := range q.watchers {
868 // Send one update for each transfer with the
869 // same OID.
870 for _, t := range objects.All() {
871 c <- &Transfer{
872 Name: t.Name,
873 Path: t.Path,
874 Oid: t.Oid,
875 Size: t.Size,
876 Actions: res.Transfer.Actions,
877 Links: res.Transfer.Links,
878 }
879 }
880 }
881
882 q.trMutex.Unlock()
883
884 q.meter.FinishTransfer(res.Transfer.Name)
885 q.wait.Done()
886 }
887 }
888
889 func (q *TransferQueue) useAdapter(name string) {
890 q.adapterInitMutex.Lock()
891 defer q.adapterInitMutex.Unlock()
892
893 // The spec says clients MUST use the basic transfer adapter when
894 // the response omits the transfer property (docs/api/batch.md).
895 // Normalize here to match NewAdapterOrDefault.
896 if name == "" {
897 name = BasicAdapterName
898 }
899
900 if q.adapter != nil {
901 if q.adapter.Name() == name {
902 // re-use, this is the normal path
903 return
904 }
905 // If the adapter we're using isn't the same as the one we've been
906 // told to use now, must wait for the current one to finish then switch
907 // This will probably never happen but is just in case server starts
908 // changing adapter support in between batches
909 q.finishAdapter()
910 }
911 q.adapter = q.manifest.NewAdapterOrDefault(name, q.direction)
912 }
913
914 func (q *TransferQueue) finishAdapter() {
915 if q.adapterInProgress {
916 q.adapter.End()
917 q.adapterInProgress = false
918 q.adapter = nil
919 }
920 }
921
922 // BatchSize returns the batch size of the receiving *TransferQueue, or, the
923 // number of transfers to accept before beginning work on them.
924 func (q *TransferQueue) BatchSize() int {
925 return q.batchSize
926 }
927
928 func (q *TransferQueue) Skip(size int64) {
929 q.meter.Skip(size)
930 }
931
932 func (q *TransferQueue) ensureAdapterBegun(e lfshttp.Endpoint) error {
933 q.Upgrade()
934
935 q.adapterInitMutex.Lock()
936 defer q.adapterInitMutex.Unlock()
937
938 if q.adapterInProgress {
939 return nil
940 }
941
942 // Progress callback - receives byte updates
943 cb := func(name string, total, read int64, current int) error {
944 q.meter.TransferBytes(q.direction.String(), name, read, total, current)
945 if q.cb != nil {
946 // NOTE: this is the mechanism by which the logpath
947 // specified by GIT_LFS_PROGRESS is written to.
948 //
949 // See: lfs.downloadFile() for more.
950 q.cb(total, read, current)
951 }
952 return nil
953 }
954
955 tracerx.Printf("tq: starting transfer adapter %q", q.adapter.Name())
956 err := q.adapter.Begin(q.toAdapterCfg(e), cb)
957 if err != nil {
958 return err
959 }
960 q.adapterInProgress = true
961
962 return nil
963 }
964
965 func (q *TransferQueue) toAdapterCfg(e lfshttp.Endpoint) AdapterConfig {
966 apiClient := q.manifest.APIClient()
967 concurrency := q.manifest.ConcurrentTransfers()
968
969 return &adapterConfig{
970 concurrentTransfers: concurrency,
971 apiClient: apiClient,
972 remote: q.remote,
973 }
974 }
975
976 // Wait waits for the queue to finish processing all transfers. Once Wait is
977 // called, Add will no longer add transfers to the queue. Any failed
978 // transfers will be automatically retried once.
979 func (q *TransferQueue) Wait() {
980 close(q.incoming)
981
982 q.wait.Wait()
983 q.collectorWait.Wait()
984
985 q.finishAdapter()
986 close(q.errorc)
987
988 for _, watcher := range q.watchers {
989 close(watcher)
990 }
991
992 q.meter.Flush()
993 q.errorwait.Wait()
994
995 if q.unsupportedContentType {
996 fmt.Fprintln(os.Stderr, tr.Tr.Get(`info: Uploading failed due to unsupported Content-Type header(s).
997 info: Consider disabling Content-Type detection with:
998 info:
999 info: $ git config lfs.contenttype false`))
1000 }
1001 }
1002
1003 // Watch returns a channel where the queue will write the value of each transfer
1004 // as it completes. If multiple transfers exist with the same OID, they will all
1005 // be recorded here, even though only one actual transfer took place. The
1006 // channel will be closed when the queue finishes processing.
1007 func (q *TransferQueue) Watch() chan *Transfer {
1008 c := make(chan *Transfer, q.batchSize)
1009 q.watchers = append(q.watchers, c)
1010 return c
1011 }
1012
1013 // This goroutine collects errors returned from transfers
1014 func (q *TransferQueue) errorCollector() {
1015 for err := range q.errorc {
1016 q.errors = append(q.errors, err)
1017 }
1018 q.errorwait.Done()
1019 }
1020
1021 // run begins the transfer queue. It transfers files sequentially or
1022 // concurrently depending on the Config.ConcurrentTransfers() value.
1023 func (q *TransferQueue) run() {
1024 tracerx.Printf("tq: running as batched queue, batch size of %d", q.batchSize)
1025
1026 go q.errorCollector()
1027 go q.collectBatches()
1028 }
1029
1030 // canRetry returns whether or not the given error "err" is retriable.
1031 func (q *TransferQueue) canRetry(err error) bool {
1032 return errors.IsRetriableError(err)
1033 }
1034
1035 // canRetryLater returns the number of seconds until an error can be retried and if the error
1036 // is a delayed-retriable error.
1037 func (q *TransferQueue) canRetryLater(err error) (time.Time, bool) {
1038 return errors.IsRetriableLaterError(err)
1039 }
1040
1041 // canRetryObject returns whether the given error is retriable for the object
1042 // given by "oid". If the an OID has met its retry limit, then it will not be
1043 // able to be retried again. If so, canRetryObject returns whether or not that
1044 // given error "err" is retriable.
1045 func (q *TransferQueue) canRetryObject(oid string, err error) bool {
1046 if count, ok := q.rc.CanRetry(oid); !ok {
1047 tracerx.Printf("tq: refusing to retry %q, too many retries (%d)", oid, count)
1048 return false
1049 }
1050
1051 return q.canRetry(err)
1052 }
1053
1054 // canRetryObjectLater returns the time at which the object identified by oid
1055 // may be retried and whether a retry should be done for the object.
1056 // If oid has reached its retry limit or the retry delay exceeds the configured
1057 // maximum, canRetryObjectLater returns false.
1058 func (q *TransferQueue) canRetryObjectLater(oid string, err error) (time.Time, bool) {
1059 if count, ok := q.rc.CanRetry(oid); !ok {
1060 tracerx.Printf("tq: refusing to retry %q, too many retries (%d)", oid, count)
1061 return time.Time{}, false
1062 }
1063
1064 retryAt, canRetry := q.canRetryLater(err)
1065 if !canRetry {
1066 return retryAt, false
1067 }
1068
1069 delay := time.Until(retryAt).Seconds()
1070 maxRetryTime := float64(q.manifest.Upgrade().MaxRetryTime())
1071 if delay > maxRetryTime {
1072 tracerx.Printf(
1073 "tq: refusing to retry %q, retry after %.0fs exceeds maximum %ds",
1074 oid,
1075 delay,
1076 int(maxRetryTime),
1077 )
1078 return time.Time{}, false
1079 }
1080
1081 return retryAt, true
1082 }
1083
1084 // Errors returns any errors encountered during transfer.
1085 func (q *TransferQueue) Errors() []error {
1086 return q.errors
1087 }