-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathhandle_http.go
More file actions
4241 lines (3928 loc) · 146 KB
/
handle_http.go
File metadata and controls
4241 lines (3928 loc) · 146 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************
*
* Copyright (C) 2025, Pelican Project, Morgridge Institute for Research
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************/
package client
import (
"bytes"
"context"
"crypto/md5"
"crypto/sha1"
"encoding/base64"
"encoding/hex"
"fmt"
"hash"
"hash/crc32"
"io"
"io/fs"
"math"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"path"
"path/filepath"
"reflect"
"regexp"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/VividCortex/ewma"
"github.com/google/uuid"
"github.com/lestrrat-go/option"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/studio-b12/gowebdav"
"github.com/vbauerster/mpb/v8"
"golang.org/x/sync/errgroup"
"golang.org/x/time/rate"
"github.com/pelicanplatform/pelican/config"
"github.com/pelicanplatform/pelican/error_codes"
"github.com/pelicanplatform/pelican/param"
"github.com/pelicanplatform/pelican/pelican_url"
"github.com/pelicanplatform/pelican/server_structs"
)
var (
progressCtrOnce sync.Once
progressCtr *mpb.Progress
stoppedTransferDebugLine sync.Once
PelicanError error_codes.PelicanError
// Regex to match the class ad lines
adLineRegex *regexp.Regexp = regexp.MustCompile(`^\s*([A-Za-z0-9]+)\s=\s"(.*)"\n?$`)
// Indicates the origin responded too slowly after the cache tried to download from it
CacheTimedOutReadingFromOrigin = errors.New("cache timed out waiting on origin")
// ErrObjectNotFound is returned when the requested remote object does not exist.
ErrObjectNotFound = errors.New("remote object not found")
)
type (
logFields string
classAdAttr string
transferType int
ChecksumType int
// Value of one checksum calculation
ChecksumInfo struct {
Algorithm ChecksumType
Value []byte
}
// Error type for when the transfer started to return data then completely stopped
StoppedTransferError struct {
BytesTransferred int64
StoppedTime time.Duration
CacheHit bool
Upload bool
}
// SlowTransferError is an error that is returned when a transfer takes longer than the configured timeout
SlowTransferError struct {
BytesTransferred int64
BytesPerSecond int64
BytesTotal int64
Duration time.Duration
CacheAge time.Duration
}
// ConnectionSetupError is an error that is returned when a connection to the remote server fails
ConnectionSetupError struct {
URL string
Err error
}
// Represents a mismatched checksum
ChecksumMismatchError struct {
Info ChecksumInfo // The checksum that was calculated by the client
ServerValue []byte // The checksum value that was calculated by the server
}
HeaderTimeoutError struct{}
InvalidByteInChunkLengthError struct {
Err error
}
NetworkResetError struct{}
UnexpectedEOFError struct {
Err error
}
allocateMemoryError struct {
Err error
}
dirListingNotSupportedError struct {
Err error
}
// A writer that discards all data written to it at a provided rate limit
rateLimitWriter struct {
ctx context.Context
rateLimiter *rate.Limiter
writer io.Writer
}
// Transfer attempt error wraps an error with information about the service/proxy used
TransferAttemptError struct {
serviceHost string
proxyHost string
isUpload bool
isProxyErr bool
err error
}
// StatusCodeError indicates the server returned a non-200 code.
//
// The wrapper is done to provide a Pelican-based error hierarchy in case we ever decide to have
// a different underlying download package.
StatusCodeError int
// Represents the results of a single object transfer,
// potentially across multiple attempts / retries.
TransferResults struct {
JobId uuid.UUID `json:"jobId"` // The job ID this result corresponds to
job *TransferJob
Error error `json:"error"`
TransferredBytes int64 `json:"transferredBytes"`
ServerChecksums []ChecksumInfo `json:"serverChecksums"` // Checksums returned by the server
ClientChecksums []ChecksumInfo `json:"clientChecksums"` // Checksums calculated by the client
TransferStartTime time.Time `json:"transferStartTime"`
Scheme string `json:"scheme"`
Source string `json:"source"`
Attempts []TransferResult `json:"attempts"`
}
TransferResult struct {
Number int `json:"attemptNumber"` // indicates which attempt this is
TransferFileBytes int64 `json:"transferFileBytes"` // how much each attempt downloaded
TimeToFirstByte time.Duration `json:"timeToFirstByte"` // how long it took to download the first byte
TransferEndTime time.Time `json:"transferEndTime"` // when the transfer ends
TransferTime time.Duration `json:"transferTime"` // amount of time we were transferring per attempt (in seconds)
CacheAge time.Duration `json:"cacheAge"` // age of the data reported by the cache
Endpoint string `json:"endpoint"` // which origin did it use
ServerVersion string `json:"serverVersion"` // version of the server
Error error `json:"error"` // what error the attempt returned (if any)
}
clientTransferResults struct {
id uuid.UUID // ID of the client that created the job
results TransferResults // Actual transfer results
}
// A structure representing a single endpoint we will attempt a transfer against.
transferAttemptDetails struct {
// Url of the server's hostname and port
Url *url.URL
// Proxy specifies if a proxy should be used
Proxy bool
// If the Url scheme is unix, this is the path to connect to
UnixSocket string
// Specifies the pack option in the transfer URL
PackOption string
// Cache age, if known
CacheAge time.Duration
// Whether or not the cache has been queried
CacheQuery bool
}
// A structure representing a single file to transfer.
transferFile struct {
ctx context.Context
engine *TransferEngine
job *TransferJob
callback TransferCallbackFunc
remoteURL *url.URL
localPath string
token *tokenGenerator
xferType transferType
packOption string
attempts []transferAttemptDetails
project string
requireChecksum bool
requestedChecksums []ChecksumType
err error
}
// A representation of a "transfer job". The job
// can be submitted to the client library, resulting
// in one or more transfers (if recursive is true).
// We assume the transfer job is potentially queued for a
// long time and all the transfers generated by this job will
// use the same namespace and token.
TransferJob struct {
ctx context.Context
cancel context.CancelFunc
callback TransferCallbackFunc
uuid uuid.UUID
remoteURL *pelican_url.PelicanURL
lookupDone atomic.Bool
lookupErr error
activeXfer atomic.Int64
totalXfer int
localPath string
xferType transferType
requestedChecksums []ChecksumType
requireChecksum bool
recursive bool
skipAcquire bool
dryRun bool // Enable dry-run mode to display what would be transferred without actually doing it
syncLevel SyncLevel // Policy for handling synchronization when the destination exists
prefObjServers []*url.URL // holds any client-requested caches/origins
dirResp server_structs.DirectorResponse
directorUrl string
token *tokenGenerator
project string
}
// A TransferJob associated with a client's request
clientTransferJob struct {
uuid uuid.UUID
job *TransferJob
}
// A transferFile associated with a client request
clientTransferFile struct {
uuid uuid.UUID
jobId uuid.UUID
file *transferFile
}
// Different types of synchronization for recursize transfers
SyncLevel int
// An object able to process transfer jobs.
TransferEngine struct {
ctx context.Context // The context provided upon creation of the engine.
cancel context.CancelFunc
egrp *errgroup.Group // The errgroup for the worker goroutines
work chan *clientTransferJob
files chan *clientTransferFile
results chan *clientTransferResults
jobLookupDone chan *clientTransferJob // Indicates the job lookup handler is done with the job
workersActive int
resultsMap map[uuid.UUID]chan *TransferResults
workMap map[uuid.UUID]chan *TransferJob
notifyChan chan bool
closeChan chan bool
closeDoneChan chan bool
ewmaTick *time.Ticker
ewma ewma.MovingAverage
ewmaVal atomic.Int64
ewmaCtr atomic.Int64
clientLock sync.RWMutex
pelicanUrlCache *pelican_url.Cache
}
TransferCallbackFunc = func(path string, downloaded int64, totalSize int64, completed bool)
// A client to the transfer engine.
TransferClient struct {
id uuid.UUID
ctx context.Context
cancel context.CancelFunc
callback TransferCallbackFunc
engine *TransferEngine
skipAcquire bool // Enable/disable the token acquisition logic. Defaults to acquiring a token
syncLevel SyncLevel // Policy for the client to synchronize data
tokenLocation string // Location of a token file to use for transfers
token string // Token that should be used for transfers
dryRun bool // Enable dry-run mode to display what would be transferred without actually doing it
work chan *TransferJob
closed bool
prefObjServers []*url.URL // holds any client-requested caches/origins
results chan *TransferResults
finalResults chan TransferResults
setupResults sync.Once
}
TransferOption = option.Interface
identTransferOptionCaches struct{}
identTransferOptionCallback struct{}
identTransferOptionTokenLocation struct{}
identTransferOptionAcquireToken struct{}
identTransferOptionToken struct{}
identTransferOptionSynchronize struct{}
identTransferOptionCollectionsUrl struct{}
identTransferOptionChecksums struct{}
identTransferOptionRequireChecksum struct{}
identTransferOptionRecursive struct{}
identTransferOptionDepth struct{}
identTransferOptionDryRun struct{}
transferDetailsOptions struct {
NeedsToken bool
PackOption string
}
// progressWriter is the same idea as ProgressReader but in reverse
// -- periodically updates the byte count such that it can be used
// by the main go routine doing the download
progressWriter struct {
writer io.Writer
bytesWritten atomic.Int64
firstByteTime time.Time
closed atomic.Bool
bytesPerSecond atomic.Int64
lastRateSample time.Time
}
)
const (
// The EWMA library we use assumes there's a single tick per second
ewmaInterval = time.Second
attrProjectName classAdAttr = "ProjectName"
attrJobId classAdAttr = "GlobalJobId"
// The checksum algorithms supported by the client
//
// Note we have a helper function, KnownChecksumTypes, that returns a list
// of all the elements enumerated below; do not skip integers in this list
// or that functionality will break.
//
AlgMD5 ChecksumType = iota // Checksum is using the MD5 algorithm
AlgCRC32C // Checksum is using the CRC32C algorithm
AlgCRC32 // Checksum is using the CRC32 algorithm
AlgSHA1 // Checksum is using the SHA-1 algorithm
AlgUnknown // Unknown checksum algorithm. Always a "trailer" indicating the last known algorithm.
AlgDefault = AlgCRC32C // Default checksum algorithm is CRC32C if the client doesn't specify one.
algFirst = AlgMD5
algLast = AlgUnknown
SyncNone = iota // When synchronizing, always re-transfer, regardless of existence at destination.
SyncExist // Skip synchronization transfer if the destination exists
SyncSize // Skip synchronization transfer if the destination exists and matches the current source size
transferTypeDownload transferType = iota // Transfer is downloading from the federation
transferTypeUpload // Transfer is uploading to the federation
transferTypePrestage // Transfer is staging at a federation cache
)
var (
jobAdOnce sync.Once // Synchronize access to the process's job ad
jobAd map[string]string // String version of the key/values of job ad
// The parameter table for crc32c
crc32cTable *crc32.Table = crc32.MakeTable(crc32.Castagnoli)
// Error condition indicating that the progress writer was externally closed
// before the transfer was completed
progressWriterClosed error = errors.New("progress writer closed")
ErrServerChecksumMissing = errors.New("no checksum information was returned by server but checksums were required by the client")
)
func ChecksumFromHttpDigest(httpDigest string) ChecksumType {
switch httpDigest {
case "md5":
return AlgMD5
case "crc32c":
return AlgCRC32C
case "crc32":
return AlgCRC32
case "sha":
return AlgSHA1
}
return AlgUnknown
}
// List all the checksum types known to the client
func KnownChecksumTypes() (result []ChecksumType) {
result = make([]ChecksumType, algLast-algFirst)
for idx := algFirst; idx < algLast; idx++ {
result[idx-algFirst] = idx
}
return
}
// List all the checksum types known as HTTP digest strings
func KnownChecksumTypesAsHttpDigest() (result []string) {
known := KnownChecksumTypes()
result = make([]string, len(known))
for idx, checksumType := range known {
result[idx] = HttpDigestFromChecksum(checksumType)
}
return
}
func HttpDigestFromChecksum(checksumType ChecksumType) string {
switch checksumType {
case AlgCRC32:
return "crc32"
case AlgCRC32C:
return "crc32c"
case AlgMD5:
return "md5"
case AlgSHA1:
return "sha"
}
return ""
}
// Convert a checksum value to a human-readable string matching the encoding
// specified in RFC 3230
func checksumValueToHttpDigest(checksumType ChecksumType, checksumValue []byte) string {
switch checksumType {
case AlgCRC32:
fallthrough
case AlgCRC32C:
return hex.EncodeToString(checksumValue)
case AlgMD5:
fallthrough
case AlgSHA1:
return base64.StdEncoding.EncodeToString(checksumValue)
}
return "(unknown checksum type)"
}
// Reset the memory-cached copy of the HTCondor job ad
//
// The client will search through the process's environment to find
// a HTCondor "job ad" and cache its contents in memory; the job ad
// is used to determine the project name and job ID for the transfer
// headers.
//
// This function is used to reset the job ad and is intended for use
// in unit tests that need to reset things from outside the cache package.
func ResetJobAd() {
jobAdOnce = sync.Once{}
}
// Write data to the rateLimitDiscarder; after applying the built-in
// rate limit, it'll ignore the written data
func (r *rateLimitWriter) Write(p []byte) (n int, err error) {
bytesSoFar := 0
if r.rateLimiter == nil {
return r.writer.Write(p)
}
for len(p) > 0 {
if len(p) > 64*1024 {
if err = r.rateLimiter.WaitN(r.ctx, 64*1024); err != nil {
return bytesSoFar, err
}
if n, err = r.writer.Write(p[:64*1024]); err != nil {
return n, err
}
p = p[64*1024:]
bytesSoFar += n
} else {
if err = r.rateLimiter.WaitN(r.ctx, len(p)); err != nil {
return bytesSoFar, err
}
n, err = r.writer.Write(p)
bytesSoFar += n
return bytesSoFar, err
}
}
return bytesSoFar, nil
}
// The progress container object creates several
// background goroutines. Instead of creating the object
// globally, create it on first use. This avoids having
// the progress container routines launch in the server.
func getProgressContainer() *mpb.Progress {
progressCtrOnce.Do(func() {
progressCtr = mpb.New()
})
return progressCtr
}
// mergeCancel combines two contexts and returns a new context with a unified cancel function.
func mergeCancel(ctx1, ctx2 context.Context) (context.Context, context.CancelFunc) {
newCtx, cancel := context.WithCancel(ctx1)
stop := context.AfterFunc(ctx2, func() {
cancel()
})
return newCtx, func() {
stop()
cancel()
}
}
// Determines whether or not we can interact with the site HTTP proxy
func isProxyEnabled() bool {
if _, isSet := os.LookupEnv("http_proxy"); !isSet {
return false
}
if param.Client_DisableHttpProxy.GetBool() {
return false
}
return true
}
// Determine whether we are allowed to skip the proxy as a fallback
func CanDisableProxy() bool {
return !param.Client_DisableProxyFallback.GetBool()
}
func compatToDuration(dur time.Duration, paramName string) (result time.Duration) {
// Backward compat: some parameters were previously integers, in seconds.
// If you give viper an integer without a suffix then it interprets it as a
// number in *nanoseconds*. We assume that's not the intent and, if under a
// microsecond, assume that the user really meant seconds.
if dur < time.Microsecond {
log.Warningf("%s must be given as a duration, not an integer; try setting it as '%ds'", paramName, dur.Nanoseconds())
result = time.Duration(dur.Nanoseconds()) * time.Second
} else {
result = dur
}
return
}
// Create a new transfer results object
func newTransferResults(job *TransferJob) TransferResults {
return TransferResults{
job: job,
JobId: job.uuid,
Attempts: make([]TransferResult, 0),
Source: job.remoteURL.String(),
}
}
func (tr TransferResults) ID() string {
return tr.JobId.String()
}
// Returns a new transfer engine object whose lifetime is tied
// to the provided context. Will launcher worker goroutines to
// handle the underlying transfers
func NewTransferEngine(ctx context.Context) (te *TransferEngine, err error) {
// If we did not initClient yet, we should fail to avoid unexpected/undesired behavior
if !config.IsClientInitialized() {
return nil, errors.New("client has not been initialized, unable to create transfer engine")
}
ctx, cancel := context.WithCancel(ctx)
egrp, _ := errgroup.WithContext(ctx)
work := make(chan *clientTransferJob, 5)
files := make(chan *clientTransferFile)
results := make(chan *clientTransferResults, 5)
// Start the URL cache to avoid repeated metadata queries
pelicanUrlCache := pelican_url.StartCache(ctx, egrp)
te = &TransferEngine{
ctx: ctx,
cancel: cancel,
egrp: egrp,
work: work,
files: files,
results: results,
resultsMap: make(map[uuid.UUID]chan *TransferResults),
workMap: make(map[uuid.UUID]chan *TransferJob),
jobLookupDone: make(chan *clientTransferJob, 5),
notifyChan: make(chan bool),
closeChan: make(chan bool),
closeDoneChan: make(chan bool),
ewmaTick: time.NewTicker(ewmaInterval),
ewma: ewma.NewMovingAverage(20), // By explicitly setting the age to 20s, the first 10 seconds will use an average of historical samples instead of EWMA
pelicanUrlCache: pelicanUrlCache,
}
workerCount := param.Client_WorkerCount.GetInt()
if workerCount <= 0 {
return nil, errors.New("worker count must be a positive integer")
}
for idx := 0; idx < workerCount; idx++ {
egrp.Go(func() error {
return runTransferWorker(ctx, te.files, te.results)
})
}
te.workersActive = workerCount
egrp.Go(te.runMux)
egrp.Go(te.runJobHandler)
return
}
// Create an option that provides a callback for a TransferClient
//
// The callback is invoked periodically by one of the transfer workers,
// with inputs of the local path (e.g., source on upload), the current
// bytes transferred, and the total object size
func WithCallback(callback TransferCallbackFunc) TransferOption {
return option.New(identTransferOptionCallback{}, callback)
}
// Override collections URL to be used by the TransferClient
func WithCollectionsUrl(url string) TransferOption {
return option.New(identTransferOptionCollectionsUrl{}, url)
}
// Create an option to override the cache list
func WithCaches(caches ...*url.URL) TransferOption {
return option.New(identTransferOptionCaches{}, caches)
}
// Create an option to override the token locating logic
//
// This will force the transfer to use a specific file for the token
// contents instead of doing any sort of auto-detection
func WithTokenLocation(location string) TransferOption {
return option.New(identTransferOptionTokenLocation{}, location)
}
// Create an option to provide a specific token to the transfer
//
// The contents of the token will be used as part of the HTTP request
func WithToken(token string) TransferOption {
return option.New(identTransferOptionToken{}, token)
}
// Create an option to specify the checksums to request for a given
// transfer
func WithRequestChecksums(types []ChecksumType) TransferOption {
return option.New(identTransferOptionChecksums{}, types)
}
// Indicate that checksum verification is required
func WithRequireChecksum() TransferOption {
return option.New(identTransferOptionRequireChecksum{}, true)
}
// Create an option to specify the token acquisition logic
//
// Token acquisition (e.g., using OAuth2 to get a token when one
// isn't found in the environment) defaults to `true` but can be
// disabled with this options
func WithAcquireToken(enable bool) TransferOption {
return option.New(identTransferOptionAcquireToken{}, enable)
}
// Create an option to specify the object synchronization level
//
// The synchronization level specifies what to do if the destination
// object already exists.
func WithSynchronize(level SyncLevel) TransferOption {
return option.New(identTransferOptionSynchronize{}, level)
}
// Create an option to enable recursive listing
//
// When enabled, the list operation will recursively traverse all subdirectories
func WithRecursive(recursive bool) TransferOption {
return option.New(identTransferOptionRecursive{}, recursive)
}
// Create an option to specify the maximum depth for recursive listing
//
// The depth parameter controls how deep the recursive listing will go.
// A depth of 0 means only the specified directory, 1 means one level deep, etc.
// A depth of -1 means unlimited depth.
func WithDepth(depth int) TransferOption {
return option.New(identTransferOptionDepth{}, depth)
}
// Create an option to enable dry-run mode
//
// When enabled, the transfer will display what would be copied without actually
// modifying the destination. Useful for verifying paths and sources before
// performing actual transfers.
func WithDryRun(enable bool) TransferOption {
return option.New(identTransferOptionDryRun{}, enable)
}
// Create a new client to work with an engine
func (te *TransferEngine) NewClient(options ...TransferOption) (client *TransferClient, err error) {
log.Debugln("Making new clients")
id, err := uuid.NewV7()
if err != nil {
err = errors.Wrap(err, "Unable to create new UUID for client")
return
}
client = &TransferClient{
engine: te,
id: id,
results: make(chan *TransferResults),
work: make(chan *TransferJob),
}
client.ctx, client.cancel = context.WithCancel(te.ctx)
for _, option := range options {
switch option.Ident() {
case identTransferOptionCaches{}:
client.prefObjServers = option.Value().([]*url.URL)
case identTransferOptionCallback{}:
client.callback = option.Value().(TransferCallbackFunc)
case identTransferOptionTokenLocation{}:
client.tokenLocation = option.Value().(string)
case identTransferOptionAcquireToken{}:
client.skipAcquire = !option.Value().(bool)
case identTransferOptionToken{}:
client.token = option.Value().(string)
case identTransferOptionSynchronize{}:
client.syncLevel = option.Value().(SyncLevel)
case identTransferOptionDryRun{}:
client.dryRun = option.Value().(bool)
}
}
func() {
te.clientLock.Lock()
defer te.clientLock.Unlock()
te.resultsMap[id] = client.results
te.workMap[id] = client.work
}()
log.Debugln("Created new client", id.String())
select {
case <-te.ctx.Done():
log.Debugln("New client unable to start; transfer engine has been canceled")
err = te.ctx.Err()
case te.notifyChan <- true:
}
return
}
// Initiates a shutdown of the transfer engine.
// Waits until all workers have finished
func (te *TransferEngine) Shutdown() error {
te.Close()
<-te.closeDoneChan
te.ewmaTick.Stop()
te.cancel()
err := te.egrp.Wait()
if err != nil && err != context.Canceled {
return err
}
return nil
}
// Closes the TransferEngine. No new work may
// be submitted. Any ongoing work will continue
func (te *TransferEngine) Close() {
select {
case <-te.ctx.Done():
case te.closeChan <- true:
}
}
// If we've detected a job is done, clean up the active job state map
func (te *TransferEngine) finishJob(activeJobs *map[uuid.UUID][]*TransferJob, job *TransferJob, id uuid.UUID) {
if len((*activeJobs)[id]) == 1 {
log.Debugln("Job", job.ID(), "is done for client", id.String(), "which has no active jobs remaining")
// Delete the job from the list of active jobs
delete(*activeJobs, id)
func() {
te.clientLock.Lock()
defer te.clientLock.Unlock()
// If the client is closed and there are no remaining
// jobs for that client, we can close the results channel
// for the client -- a clean shutdown of the client.
if te.workMap[id] == nil {
close(te.resultsMap[id])
log.Debugln("Client", id.String(), "has no more work and is finished shutting down")
}
}()
} else {
// Scan through the list of active jobs, removing the recently
// completed one and saving the updated list.
newJobList := make([]*TransferJob, 0, len((*activeJobs)[id]))
for _, oldJob := range (*activeJobs)[id] {
if oldJob.uuid != job.uuid {
newJobList = append(newJobList, oldJob)
}
}
(*activeJobs)[id] = newJobList
log.Debugln("Job", job.ID(), "is done for client", id.String(), " which has", len(newJobList), "jobs remaining")
}
}
// Launches a helper goroutine that ensures completed
// transfer results are routed back to their requesting
// channels
func (te *TransferEngine) runMux() error {
tmpResults := make(map[uuid.UUID][]*TransferResults)
activeJobs := make(map[uuid.UUID][]*TransferJob)
var clientJob *clientTransferJob
closing := false
closedWorkChan := false
// The main body of the routine; continuously select on one of the channels,
// which indicate some event occurs, until an exit condition is met.
for {
// The channels we interact with on depend on how many clients and how many results we have.
// Since this is dynamic, we can't do a fixed-size case statement and instead need to use reflect.Select.
// This helper function iterates through the TransferEngine's internals with a read-lock held, building up
// the list of work.
cases, workMap, workKeys, resultsMap, resultsKeys := func() (cases []reflect.SelectCase, workMap map[uuid.UUID]chan *TransferJob, workKeys []uuid.UUID, resultsMap map[uuid.UUID]chan *TransferResults, resultsKeys []uuid.UUID) {
te.clientLock.RLock()
defer te.clientLock.RUnlock()
workMap = make(map[uuid.UUID]chan *TransferJob, len(te.workMap))
ctr := 0
workKeys = make(uuid.UUIDs, 0)
for key, val := range te.workMap {
if val != nil {
workKeys = append(workKeys, key)
}
}
cases = make([]reflect.SelectCase, len(workKeys)+len(tmpResults)+7)
sortFunc := func(a, b uuid.UUID) int {
return bytes.Compare(a[:], b[:])
}
// Only listen for more incoming work if we're not waiting to send a client job to the
// jobs-to-objects worker
slices.SortFunc(workKeys, sortFunc)
for _, key := range workKeys {
workMap[key] = te.workMap[key]
cases[ctr].Dir = reflect.SelectRecv
if clientJob == nil {
cases[ctr].Chan = reflect.ValueOf(workMap[key])
} else {
cases[ctr].Chan = reflect.ValueOf(nil)
}
ctr++
}
resultsMap = make(map[uuid.UUID]chan *TransferResults, len(tmpResults))
resultsKeys = make([]uuid.UUID, 0)
for key := range tmpResults {
resultsKeys = append(resultsKeys, key)
}
slices.SortFunc(resultsKeys, sortFunc)
for _, key := range resultsKeys {
resultsMap[key] = te.resultsMap[key]
cases[ctr].Dir = reflect.SelectSend
cases[ctr].Chan = reflect.ValueOf(resultsMap[key])
cases[ctr].Send = reflect.ValueOf(tmpResults[key][0])
ctr++
}
// Notification a new client has been started; recompute the channels
cases[ctr].Dir = reflect.SelectRecv
cases[ctr].Chan = reflect.ValueOf(te.notifyChan)
// Notification that a transfer has finished.
cases[ctr+1].Dir = reflect.SelectRecv
cases[ctr+1].Chan = reflect.ValueOf(te.results)
// Buffer the jobs to send to the job-to-objects worker.
if clientJob == nil {
cases[ctr+2].Dir = reflect.SelectRecv
cases[ctr+2].Chan = reflect.ValueOf(nil)
} else {
cases[ctr+2].Dir = reflect.SelectSend
cases[ctr+2].Chan = reflect.ValueOf(te.work)
cases[ctr+2].Send = reflect.ValueOf(clientJob)
}
// Notification that the TransferEngine has been cancelled; shutdown immediately
cases[ctr+3].Dir = reflect.SelectRecv
cases[ctr+3].Chan = reflect.ValueOf(te.ctx.Done())
// Notification the translation from job-to-file has been completed.
cases[ctr+4].Dir = reflect.SelectRecv
cases[ctr+4].Chan = reflect.ValueOf(te.jobLookupDone)
// Notification the transfer engine has been "closed". No more jobs will come in
// and shutdown can start.
cases[ctr+5].Dir = reflect.SelectRecv
cases[ctr+5].Chan = reflect.ValueOf(te.closeChan)
// The transfer engine keeps statistics on the number of concurrent transfers occur
// (this is later used to normalize the minimum transfer rate); this ticker periodically
// will recalculate the average.
cases[ctr+6].Dir = reflect.SelectRecv
cases[ctr+6].Chan = reflect.ValueOf(te.ewmaTick.C)
return
}()
if closing && len(workMap) == 0 && !closedWorkChan {
// If there's no more incoming work, we can safely close the work channel
// which will cause the job-to-file worker to shutdown.
close(te.work)
closedWorkChan = true
}
// Statement purposely left commented out; too heavyweight/noisy to leave in at runtime but useful for developer debugging.
//log.Debugf("runMux running with %d active client channels and sending %d client responses", len(workMap), len(resultsMap))
chosen, recv, ok := reflect.Select(cases)
if chosen < len(workMap) {
// One of the clients has produced work. Send it to the central queue.
id := workKeys[chosen]
if !ok {
// Client has closed its input channels. See if we're done.
func() {
te.clientLock.Lock()
defer te.clientLock.Unlock()
te.workMap[id] = nil
}()
if activeJobs[id] == nil {
close(te.resultsMap[id])
}
continue
}
job := recv.Interface().(*TransferJob)
clientJob = &clientTransferJob{job: job, uuid: id}
clientJobs := activeJobs[id]
if clientJobs == nil {
clientJobs = make([]*TransferJob, 0)
}
clientJobs = append(clientJobs, job)
activeJobs[id] = clientJobs
} else if chosen < len(workMap)+len(resultsMap) {
// One of the "write" channels has been sent some results.
id := resultsKeys[chosen-len(workMap)]
clientJob := tmpResults[id][0]
job := clientJob.job
job.activeXfer.Add(-1)
// Test to see if the transfer job is done (true if job-to-file translation
// has completed and there are no remaining active transfers)
if job.lookupDone.Load() && job.activeXfer.Load() == 0 {
te.finishJob(&activeJobs, job, id)
}
if len(tmpResults[id]) == 1 {
// The last result back to this client has been sent; delete the
// slice from the map and check if the overall job is done.
delete(tmpResults, id)
} else {
tmpResults[id] = tmpResults[id][1:]
}
} else if chosen == len(workMap)+len(resultsMap) {
// The notify channel is meant to let the engine know
// a new client has joined. We should restart the for loop,
// recalculating the channels with the new entry.
continue
} else if chosen == len(workMap)+len(resultsMap)+1 {
// Receive transfer results from one of the engine's workers
result := recv.Interface().(*clientTransferResults)
if result == nil {
te.workersActive--
if te.workersActive == 0 {
te.closeDoneChan <- true
close(te.closeDoneChan)
return nil
}
} else {
resultBuffer := tmpResults[result.id]
if resultBuffer == nil {
resultBuffer = make([]*TransferResults, 0)
}
tmpResults[result.id] = append(resultBuffer, &result.results)
}
} else if chosen == len(workMap)+len(resultsMap)+2 {
// Sent the buffered job to the job-to-objects worker. Clear
// out the buffer so that we can pull in more work.
clientJob = nil
} else if chosen == len(workMap)+len(resultsMap)+3 {
// Engine's context has been cancelled; immediately exit.
log.Debugln("Transfer engine has been cancelled")
close(te.closeDoneChan)
return te.ctx.Err()
} else if chosen == len(workMap)+len(resultsMap)+4 {
// Notification that a job has been processed into files (or failed)
job := recv.Interface().(*clientTransferJob)
job.job.lookupDone.Store(true)