-
Notifications
You must be signed in to change notification settings - Fork 18
/
handle_http.go
2594 lines (2394 loc) · 80.2 KB
/
handle_http.go
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) 2024, University of Nebraska-Lincoln
*
* 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"
"fmt"
"io"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"path"
"reflect"
"regexp"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/VividCortex/ewma"
"github.com/google/uuid"
"github.com/jellydator/ttlcache/v3"
"github.com/lestrrat-go/option"
"github.com/opensaucerer/grab/v3"
"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/sync/singleflight"
"golang.org/x/time/rate"
"github.com/pelicanplatform/pelican/config"
"github.com/pelicanplatform/pelican/namespaces"
"github.com/pelicanplatform/pelican/param"
)
var (
progressCtrOnce sync.Once
progressCtr *mpb.Progress
successTTL = ttlcache.DefaultTTL
failureTTL = 5 * time.Minute
loader = ttlcache.LoaderFunc[string, cacheItem](
func(c *ttlcache.Cache[string, cacheItem], key string) *ttlcache.Item[string, cacheItem] {
ctx := context.Background()
// Note: setting this timeout mostly for unit tests
ctx, cancel := context.WithTimeout(ctx, param.Transport_ResponseHeaderTimeout.GetDuration())
defer cancel()
urlFederation, err := config.DiscoverUrlFederation(ctx, key)
if err != nil {
// Set a shorter TTL for failures
item := c.Set(key, cacheItem{err: err}, failureTTL)
return item
}
// Set a longer TTL for successes
item := c.Set(key, cacheItem{
url: pelicanUrl{
directorUrl: urlFederation.DirectorEndpoint,
},
}, successTTL)
return item
},
)
)
type (
classAd string
cacheItem struct {
url pelicanUrl
err error
}
// Error type for when the transfer started to return data then completely stopped
StoppedTransferError struct {
Err error
}
// 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
}
// ConnectionSetupError is an error that is returned when a connection to the remote server fails
ConnectionSetupError struct {
URL string
Err error
}
allocateMemoryError struct {
Err error
}
dirListingNotSupportedError struct {
Err error
}
// 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 is a wrapper around grab.StatusCodeErorr that 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 grab.StatusCodeError
// Represents the results of a single object transfer,
// potentially across multiple attempts / retries.
TransferResults struct {
jobId uuid.UUID // The job ID this result corresponds to
job *TransferJob
Error error
TransferredBytes int64
Scheme string
Attempts []TransferResult
}
TransferResult struct {
Number int // indicates which attempt this is
TransferFileBytes int64 // how much each attempt downloaded
TimeToFirstByte time.Duration // how long it took to download the first byte
TransferEndTime time.Time // when the transfer ends
TransferTime time.Duration // amount of time we were transferring per attempt (in seconds)
Endpoint string // which origin did it use
ServerVersion string // version of the server
Error 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
}
// 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 string
upload bool
packOption string
attempts []transferAttemptDetails
project string
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 *url.URL
lookupDone atomic.Bool
lookupErr error
activeXfer atomic.Int64
totalXfer int
localPath string
upload bool
recursive bool
skipAcquire bool
caches []*url.URL
useDirector bool
directorUrl string
tokenLocation string
token string
project string
namespace namespaces.Namespace
}
// 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
}
// 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 *ttlcache.Cache[string, cacheItem]
}
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
tokenLocation string // Location of a token file to use for transfers
token string // Token that should be used for transfers
work chan *TransferJob
closed bool
caches []*url.URL
results chan *TransferResults
finalResults chan TransferResults
setupResults sync.Once
}
TransferOption = option.Interface
identTransferOptionCaches struct{}
identTransferOptionCallback struct{}
identTransferOptionTokenLocation struct{}
identTransferOptionAcquireToken struct{}
identTransferOptionToken struct{}
transferDetailsOptions struct {
NeedsToken bool
PackOption string
}
pelicanUrl struct {
directorUrl string
}
)
const (
ewmaInterval = 15 * time.Second
projectName classAd = "ProjectName"
jobId classAd = "GlobalJobId"
)
// 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
}
func (e *StoppedTransferError) Error() string {
return e.Err.Error()
}
func (e *StoppedTransferError) Unwrap() error {
return e.Err
}
func (e *StoppedTransferError) Is(target error) bool {
_, ok := target.(*StoppedTransferError)
return ok
}
func (e *allocateMemoryError) Error() string {
return e.Err.Error()
}
func (e *allocateMemoryError) Unwrap() error {
return e.Err
}
func (e *allocateMemoryError) Is(target error) bool {
_, ok := target.(*allocateMemoryError)
return ok
}
func (e *dirListingNotSupportedError) Error() string {
return e.Err.Error()
}
func (e *dirListingNotSupportedError) Unwrap() error {
return e.Err
}
func (e *dirListingNotSupportedError) Is(target error) bool {
_, ok := target.(*dirListingNotSupportedError)
return ok
}
type HttpErrResp struct {
Code int
Err string
}
func (e *HttpErrResp) Error() string {
return e.Err
}
func (e *SlowTransferError) Error() string {
return "cancelled transfer, too slow. Detected speed: " +
ByteCountSI(e.BytesPerSecond) +
"/s, total transferred: " +
ByteCountSI(e.BytesTransferred) +
", total transfer time: " +
e.Duration.String()
}
func (e *SlowTransferError) Is(target error) bool {
_, ok := target.(*SlowTransferError)
return ok
}
// 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 (e *ConnectionSetupError) Error() string {
if e.Err != nil {
if len(e.URL) > 0 {
return "failed connection setup to " + e.URL + ": " + e.Err.Error()
} else {
return "failed connection setup: " + e.Err.Error()
}
} else {
return "Connection to remote server failed"
}
}
func (e *ConnectionSetupError) Unwrap() error {
return e.Err
}
func (e *ConnectionSetupError) Is(target error) bool {
_, ok := target.(*ConnectionSetupError)
return ok
}
func (e *StatusCodeError) Error() string {
return (*grab.StatusCodeError)(e).Error()
}
func (e *StatusCodeError) Is(target error) bool {
sce, ok := target.(*StatusCodeError)
if !ok {
return false
}
return int(*sce) == int(*e)
}
func (tae *TransferAttemptError) Error() (errMsg string) {
errMsg = "failed download from "
if tae.isUpload {
errMsg = "failed upload to "
}
if tae.serviceHost == "" {
errMsg += "unknown host"
} else {
errMsg += tae.serviceHost
}
if tae.isProxyErr {
if tae.proxyHost == "" {
errMsg += " due to unknown proxy"
} else {
errMsg += " due to proxy " + tae.proxyHost
}
} else if tae.proxyHost != "" {
errMsg += "+proxy=" + tae.proxyHost
}
if tae.err != nil {
errMsg += ": " + tae.err.Error()
}
return
}
func (tae *TransferAttemptError) Unwrap() error {
return tae.err
}
func (tae *TransferAttemptError) Is(target error) bool {
other, ok := target.(*TransferAttemptError)
if !ok {
return false
}
return tae.isUpload == other.isUpload && tae.serviceHost == other.serviceHost && tae.isProxyErr == other.isProxyErr && tae.proxyHost == other.proxyHost
}
func newTransferAttemptError(service string, proxy string, isProxyErr bool, isUpload bool, err error) (tae *TransferAttemptError) {
tae = &TransferAttemptError{
serviceHost: service,
proxyHost: proxy,
isProxyErr: isProxyErr,
isUpload: isUpload,
err: err,
}
return
}
// hasPort test the host if it includes a port
func hasPort(host string) bool {
var checkPort = regexp.MustCompile("^.*:[0-9]+$")
return checkPort.MatchString(host)
}
// Create a new transfer results object
func newTransferResults(job *TransferJob) TransferResults {
return TransferResults{
job: job,
jobId: job.uuid,
Attempts: make([]TransferResult, 0),
}
}
func (tr TransferResults) ID() string {
return tr.jobId.String()
}
func (te *TransferEngine) newPelicanURL(remoteUrl *url.URL) (pelicanURL pelicanUrl, err error) {
scheme := remoteUrl.Scheme
if remoteUrl.Host != "" {
if scheme == "osdf" || scheme == "stash" {
// in the osdf/stash case, fix url's that have a hostname
joinedPath, err := url.JoinPath(remoteUrl.Host, remoteUrl.Path)
// Prefix with a / just in case
remoteUrl.Path = path.Join("/", joinedPath)
if err != nil {
log.Errorln("Failed to join remote destination url path:", err)
return pelicanUrl{}, err
}
} else if scheme == "pelican" {
// If we have a host and url is pelican, we need to extract federation data from the host
log.Debugln("Detected pelican:// url, getting federation metadata from specified host", remoteUrl.Host)
federationUrl := &url.URL{}
// federationUrl, _ := url.Parse(remoteUrl.String())
federationUrl.Scheme = "https"
federationUrl.Path = ""
federationUrl.Host = remoteUrl.Host
// Check if cache has key of federationURL, if not, loader will add it:
pelicanUrlItem := te.pelicanURLCache.Get(federationUrl.String())
if pelicanUrlItem.Value().err != nil {
return pelicanUrl{}, pelicanUrlItem.Value().err
} else {
pelicanURL = pelicanUrlItem.Value().url
}
}
}
// With an osdf:// url scheme, we assume the user will be using the OSDF so load in our osdf metadata for our url
if scheme == "osdf" {
// If we are using an osdf/stash binary, we discovered the federation already --> load into local url metadata
if config.GetPreferredPrefix() == config.OsdfPrefix {
log.Debugln("In OSDF mode with osdf:// url; populating metadata with OSDF defaults")
fedInfo, err := config.GetFederation(te.ctx)
if fedInfo.DirectorEndpoint == "" {
if err != nil {
return pelicanUrl{}, errors.Wrap(err, "no OSDF metadata available")
}
return pelicanUrl{}, fmt.Errorf("OSDF default metadata is not populated in config")
} else {
pelicanURL.directorUrl = fedInfo.DirectorEndpoint
}
} else if config.GetPreferredPrefix() == config.PelicanPrefix {
// We hit this case when we are using a pelican binary but an osdf:// url, therefore we need to discover the osdf federation
log.Debugln("In Pelican mode with an osdf:// url, populating metadata with OSDF defaults")
// Check if cache has key of federationURL, if not, loader will add it:
pelicanUrlItem := te.pelicanURLCache.Get("osg-htc.org")
if pelicanUrlItem.Value().err != nil {
err = pelicanUrlItem.Value().err
return
} else {
pelicanURL = pelicanUrlItem.Value().url
}
}
} else if scheme == "pelican" && remoteUrl.Host == "" {
// We hit this case when we do not have a hostname with a pelican:// url
if param.Federation_DiscoveryUrl.GetString() == "" {
return pelicanUrl{}, errors.Errorf("pelican url scheme without discovery-url detected, please provide a federation discovery-url " +
"(e.g. pelican://<federation-url-in-hostname.org></namespace></path/to/file>) within the hostname or with the -f flag")
}
// Check if cache has key of federationURL, if not, loader will add it:
pelicanUrlItem := te.pelicanURLCache.Get(param.Federation_DiscoveryUrl.GetString())
if pelicanUrlItem != nil {
pelicanURL = pelicanUrlItem.Value().url
} else {
return pelicanUrl{}, errors.Errorf("issue getting metadata information from cache")
}
} else if scheme == "" {
// If we don't have a url scheme, then our metadata information should be in the config
log.Debugln("No url scheme detected, getting metadata information from configuration")
if fedInfo, err := config.GetFederation(te.ctx); err == nil {
pelicanURL.directorUrl = fedInfo.DirectorEndpoint
} else {
return pelicanUrl{}, errors.Wrap(err, "failed to lookup pelican metadata from configuration")
}
// If the values do not exist, exit with failure
if pelicanURL.directorUrl == "" {
return pelicanUrl{}, fmt.Errorf("Missing metadata information in config, ensure Federation DirectorUrl, RegistryUrl, and DiscoverUrl are all set")
}
}
return
}
// 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) *TransferEngine {
ctx, cancel := context.WithCancel(ctx)
egrp, _ := errgroup.WithContext(ctx)
work := make(chan *clientTransferJob, 5)
files := make(chan *clientTransferFile)
results := make(chan *clientTransferResults, 5)
suppressedLoader := ttlcache.NewSuppressedLoader(loader, new(singleflight.Group))
pelicanURLCache := ttlcache.New(
ttlcache.WithTTL[string, cacheItem](30*time.Minute),
ttlcache.WithLoader(suppressedLoader),
)
// Start our cache for url metadata
// This is stopped in the `Shutdown` method
go pelicanURLCache.Start()
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(),
pelicanURLCache: pelicanURLCache,
}
workerCount := param.Client_WorkerCount.GetInt()
if workerCount <= 0 {
log.Errorln("Worker count must be a positive integer")
return nil
}
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 te
}
// 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)
}
// 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 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 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.caches = 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)
}
}
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.pelicanURLCache.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:
}
}
// 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)
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)
// 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 {
log.Debugln("Job is done")
if len(activeJobs[id]) == 1 {
// 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])
}
}()
} 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
}
}
} 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)
// If no transfers were created and we have an error, the job is no
// longer active
if job.job.lookupErr != nil && job.job.totalXfer == 0 {
// Remove this job from the list of active jobs for the client.
activeJobs[job.uuid] = slices.DeleteFunc(activeJobs[job.uuid], func(oldJob *TransferJob) bool {
return oldJob.uuid == job.job.uuid
})
if len(activeJobs[job.uuid]) == 0 {
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.
if te.workMap[job.uuid] == nil {
close(te.resultsMap[job.uuid])
}
}()
}
}
} else if chosen == len(workMap)+len(resultsMap)+5 {
// Notification that the engine should shut down
closing = true
log.Debugln("Shutting down transfer engine")
func() {
te.clientLock.Lock()
defer te.clientLock.Unlock()
for _, channel := range te.workMap {
if channel != nil {
close(channel)
}
}
}()
} else {
// EWMA tick.
newVals := te.ewmaCtr.Swap(0)
te.ewma.Add(float64(newVals))
te.ewmaVal.Store(int64(te.ewma.Value()))
}
}
}
// Listen for new jobs on the engine's work queue and
// turn them into transferFile objects.
//
// Meant to be run as a standalone goroutine
func (te *TransferEngine) runJobHandler() error {
for {
select {
case <-te.ctx.Done():
log.Debugln("Job handler has been cancelled")
return te.ctx.Err()
case job, ok := <-te.work:
if !ok {
log.Debugln("Job handler has been shutdown")
close(te.files)
return nil
}