/
config.go
1447 lines (1287 loc) · 47.7 KB
/
config.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, 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 config
import (
"context"
"crypto/tls"
"crypto/x509"
_ "embed"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"slices"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/go-playground/validator/v10"
"github.com/pelicanplatform/pelican/param"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"golang.org/x/sync/errgroup"
)
// Structs holding the OAuth2 state (and any other OSDF config needed)
type (
ConfigPrefix string
TokenEntry struct {
Expiration int64 `yaml:"expiration"`
AccessToken string `yaml:"access_token"`
RefreshToken string `yaml:"refresh_token,omitempty"`
}
PrefixEntry struct {
// OSDF namespace prefix
Prefix string `yaml:"prefix"`
ClientID string `yaml:"client_id"`
ClientSecret string `yaml:"client_secret"`
Tokens []TokenEntry `yaml:"tokens,omitempty"`
}
OSDFConfig struct {
// Top-level OSDF object
OSDF struct {
// List of OAuth2 client configurations
OauthClient []PrefixEntry `yaml:"oauth_client,omitempty"`
} `yaml:"OSDF"`
}
FederationDiscovery struct {
DirectorEndpoint string `json:"director_endpoint"`
NamespaceRegistrationEndpoint string `json:"namespace_registration_endpoint"`
JwksUri string `json:"jwks_uri"`
BrokerEndpoint string `json:"broker_endpoint"`
}
TokenOperation int
TokenGenerationOpts struct {
Operation TokenOperation
}
ServerType int // ServerType is a bit mask indicating which Pelican server(s) are running in the current process
ContextKey string
MetadataErr struct {
msg string
innerErr error
}
)
const (
PelicanPrefix ConfigPrefix = "PELICAN"
OsdfPrefix ConfigPrefix = "OSDF"
StashPrefix ConfigPrefix = "STASH"
)
const (
CacheType ServerType = 1 << iota
OriginType
DirectorType
RegistryType
BrokerType
LocalCacheType
EgrpKey ContextKey = "egrp"
)
const (
TokenWrite TokenOperation = iota
TokenRead
TokenSharedWrite
TokenSharedRead
)
// This block of variables will be overwritten at build time
var (
commit = "none"
date = "unknown"
builtBy = "unknown"
// Pelican version
version = "dev"
)
var (
// Some of the unit tests probe behavior specific to OSDF vs Pelican. Hence,
// we need a way to override the preferred prefix.
testingPreferredPrefix ConfigPrefix
//go:embed resources/defaults.yaml
defaultsYaml string
//go:embed resources/osdf.yaml
osdfDefaultsYaml string
// Potentially holds a directory to cleanup
tempRunDir string
cleanupOnce sync.Once
// Our global transports that only will get reconfigured if needed
transport *http.Transport
onceTransport sync.Once
// Global discovery info. Using the "once" allows us to delay discovery
// until it's first needed, avoiding a web lookup for invoking configuration
// Note the 'once' object is a pointer so we can reset the client multiple
// times during unit tests
fedDiscoveryOnce *sync.Once
globalFedInfo FederationDiscovery
globalFedErr error
// Global struct validator
validate *validator.Validate
// A variable indicating enabled Pelican servers in the current process
enabledServers ServerType
setServerOnce sync.Once
RestartFlag = make(chan any) // A channel flag to restart the server instance that launcher listens to (including cache)
MetadataTimeoutErr *MetadataErr = &MetadataErr{msg: "Timeout when querying metadata"}
watermarkUnits = []byte{'k', 'm', 'g', 't'}
validPrefixes = map[ConfigPrefix]bool{
PelicanPrefix: true,
OsdfPrefix: true,
StashPrefix: true,
"": true,
}
)
// This function creates a new MetadataError by wrapping the previous error
func NewMetadataError(err error, msg string) *MetadataErr {
return &MetadataErr{
msg: msg,
innerErr: err,
}
}
func (e *MetadataErr) Error() string {
// If the inner error is nil, we don't want to print out "<nil>"
if e.innerErr != nil {
return fmt.Sprintf("%s: %v", e.msg, e.innerErr)
} else {
return e.msg
}
}
func (e *MetadataErr) Is(target error) bool {
// We want to verify we have a timeout error
if target, ok := target.(*MetadataErr); ok {
return e.msg == target.msg
}
return false
}
func (e *MetadataErr) Wrap(err error) error {
return &MetadataErr{
innerErr: err,
msg: e.msg,
}
}
func (e *MetadataErr) Unwrap() error {
return e.innerErr
}
func init() {
validate = validator.New(validator.WithRequiredStructEnabled())
}
// Set sets a list of newServers to ServerType instance
func (sType *ServerType) SetList(newServers []ServerType) {
for _, server := range newServers {
*sType |= server
}
}
// Enable a single server type in the bitmask
func (sType *ServerType) Set(server ServerType) ServerType {
*sType |= server
return *sType
}
// IsEnabled checks if a testServer is in the ServerType instance
func (sType ServerType) IsEnabled(testServer ServerType) bool {
return sType&testServer == testServer
}
// Clear all values in a server type
func (sType *ServerType) Clear() {
*sType = ServerType(0)
}
// setEnabledServer sets the global variable config.EnabledServers to include newServers.
// Since this function should only be called in config package, we mark it "private" to avoid
// reset value in other package
//
// This will only be called once in a single process
func setEnabledServer(newServers ServerType) {
setServerOnce.Do(func() {
// For each process, we only want to set enabled servers once
enabledServers.Set(newServers)
})
}
// IsServerEnabled checks if testServer is enabled in the current process.
//
// Use this function to check which server(s) are running in the current process.
func IsServerEnabled(testServer ServerType) bool {
return enabledServers.IsEnabled(testServer)
}
// Returns the version of the current binary
func GetVersion() string {
return version
}
// Overrides the version of the current binary
//
// Intended mainly for use in unit tests
func SetVersion(newVersion string) {
version = newVersion
}
func GetBuiltCommit() string {
return commit
}
func SetBuiltCommit(newCommit string) {
commit = newCommit
}
func GetBuiltDate() string {
return date
}
func SetBuiltDate(builtDate string) {
date = builtDate
}
func GetBuiltBy() string {
return builtBy
}
func SetBuiltBy(newBuiltBy string) {
builtBy = newBuiltBy
}
func (cp ConfigPrefix) String() string {
return string(cp)
}
// Get a string slice of currently enabled servers, sorted by alphabetical order.
// By default, it calls String method of each enabled server.
// To get strings in lowerCase, set lowerCase = true.
func GetEnabledServerString(lowerCase bool) []string {
servers := make([]string, 0)
if enabledServers.IsEnabled(CacheType) {
servers = append(servers, CacheType.String())
}
if enabledServers.IsEnabled(LocalCacheType) {
servers = append(servers, LocalCacheType.String())
}
if enabledServers.IsEnabled(OriginType) {
servers = append(servers, OriginType.String())
}
if enabledServers.IsEnabled(DirectorType) {
servers = append(servers, DirectorType.String())
}
if enabledServers.IsEnabled(RegistryType) {
servers = append(servers, RegistryType.String())
}
sort.Strings(servers)
if lowerCase {
for i, serverStr := range servers {
servers[i] = strings.ToLower(serverStr)
}
return servers
} else {
return servers
}
}
// Create a new, empty ServerType bitmask
func NewServerType() ServerType {
return ServerType(0)
}
// Get the string representation of a ServerType instance. This is intended
// for getting the string form of a single ServerType contant, such as CacheType
// OriginType, etc. To get a string slice of enabled servers, use EnabledServerString()
func (sType ServerType) String() string {
switch sType {
case CacheType:
return "Cache"
case LocalCacheType:
return "LocalCache"
case OriginType:
return "Origin"
case DirectorType:
return "Director"
case RegistryType:
return "Registry"
case BrokerType:
return "Broker"
}
return "Unknown"
}
func (sType *ServerType) SetString(name string) bool {
switch strings.ToLower(name) {
case "cache":
*sType |= CacheType
return true
case "localcache":
*sType |= LocalCacheType
return true
case "origin":
*sType |= OriginType
return true
case "director":
*sType |= DirectorType
return true
case "registry":
*sType |= RegistryType
return true
case "broker":
*sType |= BrokerType
return true
}
return false
}
// Based on the name of the current binary, determine the preferred "style"
// of behavior. For example, a binary with the "osdf_" prefix should utilize
// the known URLs for OSDF. For "pelican"-style commands, the user will
// need to manually configure the location of the director endpoint.
func GetPreferredPrefix() ConfigPrefix {
// Testing override to programmatically force different behaviors.
if testingPreferredPrefix != "" {
return ConfigPrefix(testingPreferredPrefix)
}
arg0 := strings.ToUpper(filepath.Base(os.Args[0]))
underscore_idx := strings.Index(arg0, "_")
if underscore_idx != -1 {
prefix := string(ConfigPrefix(arg0[0:underscore_idx]))
if prefix == "STASH" {
return OsdfPrefix
}
}
if strings.HasPrefix(arg0, "STASH") || strings.HasPrefix(arg0, "OSDF") {
return OsdfPrefix
}
return PelicanPrefix
}
// Override the auto-detected preferred prefix; mostly meant for unittests.
// Returns the old preferred prefix.
func SetPreferredPrefix(newPref ConfigPrefix) (oldPref ConfigPrefix, err error) {
if _, ok := validPrefixes[newPref]; !ok {
return "", errors.New("Invalid prefix provided")
}
oldPrefix := testingPreferredPrefix
testingPreferredPrefix = newPref
return oldPrefix, nil
}
// Get the list of valid prefixes for this binary. Given there's been so
// many renames of the project (stash -> osdf -> pelican), we allow multiple
// prefixes when searching through environment variables.
func GetAllPrefixes() []ConfigPrefix {
prefixes := []ConfigPrefix{GetPreferredPrefix()}
if prefixes[0] == OsdfPrefix {
prefixes = append(prefixes, StashPrefix, PelicanPrefix)
} else if prefixes[0] == StashPrefix {
prefixes = append(prefixes, OsdfPrefix, PelicanPrefix)
}
return prefixes
}
// This function is for discovering federations as specified by a url during a pelican:// transfer.
// this does not populate global fields and is more temporary per url
func DiscoverUrlFederation(ctx context.Context, federationDiscoveryUrl string) (metadata FederationDiscovery, err error) {
log.Debugln("Performing federation service discovery for specified url against endpoint", federationDiscoveryUrl)
federationUrl, err := url.Parse(federationDiscoveryUrl)
if err != nil {
err = errors.Wrapf(err, "invalid federation value %s:", federationDiscoveryUrl)
return
}
federationUrl.Scheme = "https"
if len(federationUrl.Path) > 0 && len(federationUrl.Host) == 0 {
federationUrl.Host = federationUrl.Path
federationUrl.Path = ""
}
discoveryUrl, err := url.Parse(federationUrl.String())
if err != nil {
err = errors.Wrap(err, "unable to parse federation discovery URL")
return
}
discoveryUrl.Path, err = url.JoinPath(federationUrl.Path, ".well-known/pelican-configuration")
if err != nil {
err = errors.Wrap(err, "Unable to parse federation url because of invalid path")
return
}
httpClient := http.Client{
Transport: GetTransport(),
Timeout: time.Second * 5,
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, discoveryUrl.String(), nil)
if err != nil {
err = errors.Wrapf(err, "Failure when doing federation metadata request creation for %s", discoveryUrl)
return
}
req.Header.Set("User-Agent", "pelican/"+version)
result, err := httpClient.Do(req)
if err != nil {
var netErr net.Error
if errors.As(err, &netErr) && netErr.Timeout() {
err = MetadataTimeoutErr.Wrap(err)
return
} else {
err = NewMetadataError(err, "Error occurred when querying for metadata")
return
}
}
if result.Body != nil {
defer result.Body.Close()
}
body, err := io.ReadAll(result.Body)
if err != nil {
return FederationDiscovery{}, errors.Wrapf(err, "Failure when doing federation metadata read to %s", discoveryUrl)
}
if result.StatusCode != http.StatusOK {
truncatedMessage := string(body)
if len(body) > 1000 {
truncatedMessage = string(body[:1000])
truncatedMessage += " [... remainder truncated ...]"
}
return FederationDiscovery{}, errors.Errorf("Federation metadata discovery failed with HTTP status %d. Error message: %s", result.StatusCode, truncatedMessage)
}
metadata = FederationDiscovery{}
err = json.Unmarshal(body, &metadata)
if err != nil {
return FederationDiscovery{}, errors.Wrapf(err, "Failure when parsing federation metadata at %s", discoveryUrl)
}
log.Debugln("Federation service discovery resulted in director URL", metadata.DirectorEndpoint)
log.Debugln("Federation service discovery resulted in registry URL", metadata.NamespaceRegistrationEndpoint)
log.Debugln("Federation service discovery resulted in JWKS URL", metadata.JwksUri)
log.Debugln("Federation service discovery resulted in broker URL", metadata.BrokerEndpoint)
return metadata, nil
}
// Global implementation of Discover Federation, outside any caching or
// delayed discovery
func discoverFederationImpl(ctx context.Context) (fedInfo FederationDiscovery, err error) {
federationStr := param.Federation_DiscoveryUrl.GetString()
externalUrlStr := param.Server_ExternalWebUrl.GetString()
defer func() {
// Set default guesses if these values are still unset.
if fedInfo.DirectorEndpoint == "" && enabledServers.IsEnabled(DirectorType) {
fedInfo.DirectorEndpoint = externalUrlStr
}
if fedInfo.NamespaceRegistrationEndpoint == "" && enabledServers.IsEnabled(RegistryType) {
fedInfo.NamespaceRegistrationEndpoint = externalUrlStr
}
if fedInfo.JwksUri == "" && enabledServers.IsEnabled(DirectorType) {
fedInfo.JwksUri = externalUrlStr + "/.well-known/issuer.jwks"
}
if fedInfo.BrokerEndpoint == "" && enabledServers.IsEnabled(BrokerType) {
fedInfo.BrokerEndpoint = externalUrlStr
}
}()
log.Debugln("Federation URL:", federationStr)
fedInfo.DirectorEndpoint = viper.GetString("Federation.DirectorUrl")
fedInfo.NamespaceRegistrationEndpoint = viper.GetString("Federation.RegistryUrl")
fedInfo.JwksUri = viper.GetString("Federation.JwkUrl")
fedInfo.BrokerEndpoint = viper.GetString("Federation.BrokerUrl")
if fedInfo.DirectorEndpoint != "" && fedInfo.NamespaceRegistrationEndpoint != "" && fedInfo.JwksUri != "" && fedInfo.BrokerEndpoint != "" {
return
}
federationUrl, err := url.Parse(federationStr)
if err != nil {
err = errors.Wrapf(err, "invalid federation value %s:", federationStr)
return
}
if federationUrl.Path != "" && federationUrl.Host != "" {
// If the host is nothing, then the url is fine, but if we have a host and a path then there is a problem
err = errors.New("Invalid federation discovery url is set. No path allowed for federation discovery url. Provided url: " + federationStr)
return
}
federationUrl.Scheme = "https"
if len(federationUrl.Path) > 0 && len(federationUrl.Host) == 0 {
federationUrl.Host = federationUrl.Path
federationUrl.Path = ""
}
var metadata FederationDiscovery
if federationStr == "" {
log.Debugln("Federation URL is unset; skipping discovery")
} else if federationStr == externalUrlStr {
log.Debugln("Current web engine hosts the federation; skipping auto-discovery of services")
} else {
metadata, err = DiscoverUrlFederation(ctx, federationStr)
if err != nil {
err = errors.Wrapf(err, "invalid federation value (%s)", federationStr)
return
}
}
// Set our globals
if fedInfo.DirectorEndpoint == "" {
log.Debugln("Setting global director url to", metadata.DirectorEndpoint)
fedInfo.DirectorEndpoint = metadata.DirectorEndpoint
}
if fedInfo.NamespaceRegistrationEndpoint == "" {
log.Debugln("Setting global registry url to", metadata.NamespaceRegistrationEndpoint)
fedInfo.NamespaceRegistrationEndpoint = metadata.NamespaceRegistrationEndpoint
}
if fedInfo.JwksUri == "" {
log.Debugln("Setting global jwks url to", metadata.JwksUri)
fedInfo.JwksUri = metadata.JwksUri
}
if fedInfo.BrokerEndpoint == "" && metadata.BrokerEndpoint != "" {
log.Debugln("Setting global broker url to", metadata.BrokerEndpoint)
fedInfo.BrokerEndpoint = metadata.BrokerEndpoint
}
return
}
// Reset the fedDiscoveryOnce to update federation metadata values for GetFederation().
// Should only used for unit tests
func ResetFederationForTest() {
fedDiscoveryOnce = &sync.Once{}
}
// Retrieve the federation service information from the configuration.
//
// The calculation of the federation info is delayed until needed. As
// long as this is invoked after `InitClient` / `InitServer`, it is thread-safe.
// If invoked before things are configured, it must be done from a single-threaded
// context.
func GetFederation(ctx context.Context) (FederationDiscovery, error) {
if fedDiscoveryOnce == nil {
fedDiscoveryOnce = &sync.Once{}
}
fedDiscoveryOnce.Do(func() {
globalFedInfo, globalFedErr = discoverFederationImpl(ctx)
})
return globalFedInfo, globalFedErr
}
// Set the current global federation metadata
func SetFederation(fd FederationDiscovery) {
viper.Set("Federation.DirectorUrl", fd.DirectorEndpoint)
viper.Set("Federation.RegistryUrl", fd.NamespaceRegistrationEndpoint)
viper.Set("Federation.JwkUrl", fd.JwksUri)
}
// TODO: It's not clear that this function works correctly. We should
// pass an errgroup here and ensure that the cleanup is complete before
// the main thread shuts down.
func cleanupDirOnShutdown(ctx context.Context, dir string) {
tempRunDir = dir
egrp, ok := ctx.Value(EgrpKey).(*errgroup.Group)
if !ok {
egrp = &errgroup.Group{}
}
egrp.Go(func() error {
<-ctx.Done()
err := CleanupTempResources()
if err != nil {
log.Infoln("Error when cleaning up temporary directories:", err)
}
return err
})
}
func CleanupTempResources() (err error) {
cleanupOnce.Do(func() {
if tempRunDir != "" {
err = os.RemoveAll(tempRunDir)
tempRunDir = ""
}
})
return
}
func getConfigBase() (string, error) {
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
return filepath.Join(home, ".config", "pelican"), nil
}
func setupTransport() {
//Getting timeouts and other information from defaults.yaml
maxIdleConns := param.Transport_MaxIdleConns.GetInt()
idleConnTimeout := param.Transport_IdleConnTimeout.GetDuration()
transportTLSHandshakeTimeout := param.Transport_TLSHandshakeTimeout.GetDuration()
expectContinueTimeout := param.Transport_ExpectContinueTimeout.GetDuration()
responseHeaderTimeout := param.Transport_ResponseHeaderTimeout.GetDuration()
transportDialerTimeout := param.Transport_DialerTimeout.GetDuration()
transportKeepAlive := param.Transport_DialerKeepAlive.GetDuration()
//Set up the transport
transport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: transportDialerTimeout,
KeepAlive: transportKeepAlive,
}).DialContext,
MaxIdleConns: maxIdleConns,
IdleConnTimeout: idleConnTimeout,
TLSHandshakeTimeout: transportTLSHandshakeTimeout,
ExpectContinueTimeout: expectContinueTimeout,
ResponseHeaderTimeout: responseHeaderTimeout,
}
if param.TLSSkipVerify.GetBool() {
transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
}
if caCert, err := LoadCertficate(param.Server_TLSCACertificateFile.GetString()); err == nil {
systemPool, err := x509.SystemCertPool()
if err == nil {
systemPool.AddCert(caCert)
// Ensure that we don't override the InsecureSkipVerify if it's present
if transport.TLSClientConfig == nil {
transport.TLSClientConfig = &tls.Config{RootCAs: systemPool}
} else {
transport.TLSClientConfig.RootCAs = systemPool
}
}
}
}
// Return an audience string appropriate for the current server
func GetServerAudience() string {
return viper.GetString("Origin.AudienceURL")
}
func GetServerIssuerURL() (string, error) {
if issuerUrl := param.Server_IssuerUrl.GetString(); issuerUrl != "" {
_, err := url.Parse(param.Server_IssuerUrl.GetString())
if err != nil {
return "", errors.Wrapf(err, "Failed to parse the Server.IssuerUrl %s loaded from config", param.Server_IssuerUrl.GetString())
}
return issuerUrl, nil
}
if param.Server_IssuerHostname.GetString() != "" {
if param.Server_IssuerPort.GetInt() != 0 { // Will be the default if not set
// We assume any issuer is running https, otherwise we're crazy
issuerUrl := url.URL{
Scheme: "https",
Host: fmt.Sprintf("%s:%d", param.Server_IssuerHostname.GetString(), param.Server_IssuerPort.GetInt()),
}
return issuerUrl.String(), nil
}
return "", errors.New("If Server.IssuerHostname is configured, you must provide a valid port")
}
issuerUrlStr := param.Server_ExternalWebUrl.GetString()
issuerUrl, err := url.Parse(issuerUrlStr)
log.Debugln("GetServerIssuerURL:", issuerUrlStr)
if err != nil {
return "", errors.Wrap(err, "Failed to parse the issuer URL generated using the parsed Server.ExternalWebUrl")
}
return issuerUrl.String(), nil
}
// function to get/setup the transport (only once)
func GetTransport() *http.Transport {
onceTransport.Do(func() {
setupTransport()
})
return transport
}
// Get singleton global validte method for field validation
func GetValidate() *validator.Validate {
return validate
}
func handleDeprecatedConfig() {
deprecatedMap := param.GetDeprecated()
for deprecated, replacement := range deprecatedMap {
if viper.IsSet(deprecated) {
if len(replacement) == 1 {
if replacement[0] == "none" {
log.Warningf("Deprecated configuration key %s is set. This is being removed in future release", deprecated)
} else {
log.Warningf("Deprecated configuration key %s is set. Please migrate to use %s instead", deprecated, replacement[0])
log.Warningf("Will attempt to use the value of %s as default for %s", deprecated, replacement[0])
value := viper.Get(deprecated)
viper.SetDefault(replacement[0], value)
}
} else {
log.Warningf("Deprecated configuration key %s is set. This is being replaced by %s instead", deprecated, replacement)
log.Warningf("Setting default values of '%s' to the value of %s.", replacement, deprecated)
value := viper.Get(deprecated)
for _, rep := range replacement {
viper.SetDefault(rep, value)
}
}
}
}
}
func checkWatermark(wmStr string) (bool, int64, error) {
wmNum, err := strconv.Atoi(wmStr)
if err == nil {
if wmNum > 100 || wmNum < 0 {
return false, 0, errors.Errorf("watermark value %s must be a integer number in range [0, 100]. Refer to parameter page for details: https://docs.pelicanplatform.org/parameters#Cache-HighWatermark", wmStr)
}
return true, int64(wmNum), nil
// Not an integer number, check if it's in form of <int>k|m|g|t
} else {
if len(wmStr) < 1 {
return false, 0, errors.Errorf("watermark value %s is empty.", wmStr)
}
unit := wmStr[len(wmStr)-1]
if slices.Contains(watermarkUnits, unit) {
byteNum, err := strconv.Atoi(wmStr[:len(wmStr)-1])
// Bytes portion is not an integer
if err != nil {
return false, 0, errors.Errorf("watermark value %s is neither a percentage integer (e.g. 95) or a valid bytes. Refer to parameter page for details: https://docs.pelicanplatform.org/parameters#Cache-HighWatermark", wmStr)
} else {
switch unit {
case 'k':
return true, int64(byteNum) * 1024, nil
case 'm':
return true, int64(byteNum) * 1024 * 1024, nil
case 'g':
return true, int64(byteNum) * 1024 * 1024 * 1024, nil
case 't':
return true, int64(byteNum) * 1024 * 1024 * 1024 * 1024, nil
default:
return false, 0, errors.Errorf("watermark value %s is neither a percentage integer (e.g. 95) or a valid byte. Bytes representation is missing unit (k|m|g|t). Refer to parameter page for details: https://docs.pelicanplatform.org/parameters#Cache-HighWatermark", wmStr)
}
}
} else {
// Doesn't contain k|m|g|t suffix
return false, 0, errors.Errorf("watermark value %s is neither a percentage integer (e.g. 95) or a valid byte. Bytes representation is missing unit (k|m|g|t). Refer to parameter page for details: https://docs.pelicanplatform.org/parameters#Cache-HighWatermark", wmStr)
}
}
}
func InitConfig() {
viper.SetConfigType("yaml")
// 1) Set up defaults.yaml
err := viper.MergeConfig(strings.NewReader(defaultsYaml))
if err != nil {
cobra.CheckErr(err)
}
// 2) Set up osdf.yaml (if needed)
prefix := GetPreferredPrefix()
loadOSDF := prefix == OsdfPrefix
if os.Getenv("STASH_USE_TOPOLOGY") == "" {
loadOSDF = loadOSDF || (prefix == "STASH")
}
if loadOSDF {
err := viper.MergeConfig(strings.NewReader(osdfDefaultsYaml))
if err != nil {
cobra.CheckErr(err)
}
}
if configFile := viper.GetString("config"); configFile != "" {
viper.SetConfigFile(configFile)
} else {
configDir := viper.GetString("ConfigDir")
if configDir == "" {
home, err := os.UserHomeDir()
if err != nil {
log.Warningln("No home directory found for user -- will check for configuration yaml in /etc/pelican/")
} else {
// 3) Set up pelican.yaml (has higher precedence)
viper.AddConfigPath(filepath.Join(home, ".config", "pelican"))
}
viper.AddConfigPath(filepath.Join("/etc", "pelican"))
} else {
viper.AddConfigPath(configDir)
}
viper.SetConfigType("yaml")
viper.SetConfigName("pelican")
}
bindNonPelicanEnv() // Deprecate OSDF env prefix but be compatible for now
viper.SetEnvPrefix("pelican")
viper.AutomaticEnv()
// This line allows viper to use an env var like ORIGIN_VALUE to override the viper string "Origin.Value"
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
if err := viper.MergeInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
cobra.CheckErr(err)
}
}
logLocation := param.Logging_LogLocation.GetString()
if logLocation != "" {
dir := filepath.Dir(logLocation)
if dir != "" {
if err := os.MkdirAll(dir, 0640); err != nil {
log.Errorf("Failed to access/create specified directory. Error: %v", err)
os.Exit(1)
}
}
// Note: do not need to close the file, logrus does it for us
f, err := os.OpenFile(logLocation, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0640)
if err != nil {
log.Errorf("Failed to access specified log file. Error: %v", err)
os.Exit(1)
}
fmt.Fprintf(os.Stderr, "Logging.LogLocation is set to %s. All logs are redirected to the log file.\n", logLocation)
log.SetOutput(f)
}
if param.Debug.GetBool() {
SetLogging(log.DebugLevel)
log.Warnln("Debug is set as a flag or in config, this will override anything set for Logging.Level within your configuration")
} else {
logLevel := param.Logging_Level.GetString()
level, err := log.ParseLevel(logLevel)
cobra.CheckErr(err)
SetLogging(level)
}
if oldNsUrl := viper.GetString("Federation.NamespaceUrl"); oldNsUrl != "" {
log.Errorln("Federation.NamespaceUrl is deprecated and removed from parameters. Please use Federation.RegistryUrl instead")
os.Exit(1)
}
handleDeprecatedConfig()
}
func initConfigDir() error {
configDir := viper.GetString("ConfigDir")
if configDir == "" {
if IsRootExecution() {
configDir = "/etc/pelican"
} else {
configTmp, err := getConfigBase()
if err != nil {
return err
}
configDir = configTmp
}
viper.SetDefault("ConfigDir", configDir)
}
return nil
}
// XRootD RunLocation usage logic:
// - Origin.RunLocation and Cache.RunLocation take precedence for their respective types
// - If neither keys are set and Xrootd.RunLocation is, then use that and emit a warning
// - If neither key is set, Xrootd.Runlocation is, and both modules are enabled, then we don't
// know the next steps -- throw an error
func setXrootdRunLocations(currentServers ServerType, dir string) error {
cacheLocation := viper.GetString("Cache.RunLocation")
originLocation := viper.GetString("Origin.RunLocation")
xrootdLocation := viper.GetString("Xrootd.RunLocation")
xrootdLocationIsSet := viper.IsSet("Xrootd.RunLocation")
cacheLocFallbackToXrootd := false
originLocFallbackToXrootd := false
if currentServers.IsEnabled(CacheType) {
if !viper.IsSet("Cache.RunLocation") {
if xrootdLocationIsSet {
cacheLocFallbackToXrootd = true
cacheLocation = xrootdLocation
} else {
cacheLocation = filepath.Join(dir, "cache")
}
}
}
if currentServers.IsEnabled(OriginType) && !viper.IsSet("Origin.RunLocation") {
if xrootdLocationIsSet {
originLocFallbackToXrootd = true
originLocation = xrootdLocation
} else {
originLocation = filepath.Join(dir, "origin")
}
}
if cacheLocFallbackToXrootd && originLocFallbackToXrootd {
return errors.New("Xrootd.RunLocation is set, but both modules are enabled. Please set Cache.RunLocation and Origin.RunLocation or disable Xrootd.RunLocation so the default location can be used.")
}
if currentServers.IsEnabled(OriginType) {
viper.SetDefault("Origin.RunLocation", originLocation)
}
if currentServers.IsEnabled(CacheType) {
viper.SetDefault("Cache.RunLocation", cacheLocation)
}
return nil
}
func PrintPelicanVersion(out *os.File) {
fmt.Fprintln(out, "Version:", GetVersion())
fmt.Fprintln(out, "Build Date:", GetBuiltDate())
fmt.Fprintln(out, "Build Commit:", GetBuiltCommit())
fmt.Fprintln(out, "Built By:", GetBuiltBy())
}
// Print Pelican configuration to stderr
func PrintConfig() error {
rawConfig, err := param.UnmarshalConfig()
if err != nil {
return err
}
bytes, err := json.MarshalIndent(*rawConfig, "", " ")
if err != nil {
return err
}
fmt.Fprintln(os.Stderr,
"================ Pelican Configuration ================\n",
string(bytes),
"\n",
"============= End of Pelican Configuration ============")
return nil
}
// Initialize Pelican server instance. Pass a bit mask of `currentServers` if you want to enable multiple services.
// Note not all configurations are supported: currently, if you enable both cache and origin then an error
// is thrown
func InitServer(ctx context.Context, currentServers ServerType) error {
if err := initConfigDir(); err != nil {
return errors.Wrap(err, "Failed to initialize the server configuration")
}
setEnabledServer(currentServers)
configDir := viper.GetString("ConfigDir")
viper.SetConfigType("yaml")
viper.SetDefault("Server.TLSCertificate", filepath.Join(configDir, "certificates", "tls.crt"))
viper.SetDefault("Server.TLSKey", filepath.Join(configDir, "certificates", "tls.key"))
viper.SetDefault("Server.TLSCAKey", filepath.Join(configDir, "certificates", "tlsca.key"))