-
Notifications
You must be signed in to change notification settings - Fork 18
/
director.go
1022 lines (924 loc) · 37.2 KB
/
director.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 director
import (
"context"
"fmt"
"net/http"
"net/netip"
"net/url"
"path"
"regexp"
"strconv"
"strings"
"sync"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/hashicorp/go-version"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
log "github.com/sirupsen/logrus"
"golang.org/x/sync/errgroup"
"github.com/pelicanplatform/pelican/metrics"
"github.com/pelicanplatform/pelican/param"
"github.com/pelicanplatform/pelican/server_structs"
"github.com/pelicanplatform/pelican/token"
"github.com/pelicanplatform/pelican/token_scopes"
)
type (
// status of director-based health tests to origins and caches
HealthTestStatus string
// Prometheus HTTP discovery endpoint struct, used by director
// to dynamically return available origin/cache servers for Prometheus to scrape
PromDiscoveryItem struct {
Targets []string `json:"targets"`
Labels map[string]string `json:"labels"`
}
// Util struct to keep track of director-based health tests it created
healthTestUtil struct {
ErrGrp *errgroup.Group
ErrGrpContext context.Context
Cancel context.CancelFunc
Status HealthTestStatus
}
// Util struct to keep track of `stat` call the director made to the origins
originStatUtil struct {
Context context.Context
Cancel context.CancelFunc
Errgroup *errgroup.Group
}
)
const (
HealthStatusUnknown HealthTestStatus = "Unknown"
HealthStatusInit HealthTestStatus = "Initializing"
HealthStatusOK HealthTestStatus = "OK"
HealthStatusError HealthTestStatus = "Error"
)
var (
minClientVersion, _ = version.NewVersion("7.0.0")
minOriginVersion, _ = version.NewVersion("7.0.0")
minCacheVersion, _ = version.NewVersion("7.3.0")
healthTestUtils = make(map[server_structs.ServerAd]*healthTestUtil)
healthTestUtilsMutex = sync.RWMutex{}
originStatUtils = make(map[string]originStatUtil)
originStatUtilsMutex = sync.RWMutex{}
// The number of caches to send in the Link header. As discussed in issue
// https://github.com/PelicanPlatform/pelican/issues/1247, the client stops
// after three attempts, so there's really no need to send every cache we know
cachesToSend = 6
)
func getRedirectURL(reqPath string, ad server_structs.ServerAd, requiresAuth bool) (redirectURL url.URL) {
var serverURL url.URL
if requiresAuth && ad.AuthURL.String() != "" {
serverURL = ad.AuthURL
if ad.AuthURL == (url.URL{}) {
serverURL = ad.URL
}
} else {
serverURL = ad.URL
}
reqPath = path.Clean("/" + reqPath)
if requiresAuth {
redirectURL.Scheme = "https"
} else {
redirectURL.Scheme = "https"
if ad.FromTopology {
redirectURL.Scheme = "http"
}
}
redirectURL.Host = serverURL.Host
redirectURL.Path = reqPath
return
}
func getRealIP(ginCtx *gin.Context) (ipAddr netip.Addr, err error) {
ip_addr_list := ginCtx.Request.Header["X-Real-Ip"]
if len(ip_addr_list) == 0 {
ipAddr, err = netip.ParseAddr(ginCtx.RemoteIP())
return
} else {
ipAddr, err = netip.ParseAddr(ip_addr_list[0])
return
}
}
// Calculate the depth attribute of Link header given the path to the file
// and the prefix of the namespace that can serve the file
//
// Ref: https://www.rfc-editor.org/rfc/rfc6249.html#section-3.4
func getLinkDepth(filepath, prefix string) (int, error) {
if filepath == "" || prefix == "" {
return 0, errors.New("either filepath or prefix is an empty path")
}
if !strings.HasPrefix(filepath, prefix) {
return 0, errors.New("filepath does not contain the prefix")
}
// We want to remove shared prefix between filepath and prefix, then split the remaining string by slash.
// To make the final calculation easier, we also remove the head slash from the file path.
// e.g. filepath = /foo/bar/barz.txt prefix = /foo
// we want commonPath = bar/barz.txt
if !strings.HasSuffix(prefix, "/") && prefix != "/" {
prefix += "/"
}
commonPath := strings.TrimPrefix(filepath, prefix)
pathDepth := len(strings.Split(commonPath, "/"))
return pathDepth, nil
}
func getAuthzEscaped(req *http.Request) (authzEscaped string) {
if authzQuery := req.URL.Query()["authz"]; len(authzQuery) > 0 {
authzEscaped = authzQuery[0]
// if the authz URL query is coming from XRootD, it probably has a "Bearer " tacked in front
// even though it's coming via a URL
authzEscaped = strings.TrimPrefix(authzEscaped, "Bearer ")
} else if authzHeader := req.Header["Authorization"]; len(authzHeader) > 0 {
authzEscaped = strings.TrimPrefix(authzHeader[0], "Bearer ")
authzEscaped = url.QueryEscape(authzEscaped)
}
return
}
func getFinalRedirectURL(rurl url.URL, authzEscaped string) string {
if len(authzEscaped) > 0 {
if len(rurl.RawQuery) > 0 {
rurl.RawQuery += "&"
}
rurl.RawQuery += "authz=" + authzEscaped
}
return rurl.String()
}
func versionCompatCheck(ginCtx *gin.Context) error {
// Check that the version of whichever service (eg client, origin, etc) is talking to the Director
// is actually something the Director thinks it can communicate with
// The service/version is sent via User-Agent header in the form "pelican-<service>/<version>"
userAgentSlc := ginCtx.Request.Header["User-Agent"]
if len(userAgentSlc) < 1 {
return errors.New("No user agent could be found")
}
// gin gives us a slice of user agents. Since pelican services should only ever
// send one UA, assume that it is the 0-th element of the slice.
userAgent := userAgentSlc[0]
// Make sure we're working with something that's formatted the way we expect. If we
// don't match, then we're definitely not coming from one of the services, so we
// let things go without an error. Maybe someone is using curl?
uaRegExp := regexp.MustCompile(`^pelican-[^\/]+\/\d+\.\d+\.\d+`)
if matches := uaRegExp.MatchString(userAgent); !matches {
return nil
}
userAgentSplit := strings.Split(userAgent, "/")
// Grab the actual service/version that's using the Director. There may be different versioning
// requirements between origins, clients, and other services.
service := (strings.Split(userAgentSplit[0], "-"))[1]
reqVerStr := userAgentSplit[1]
reqVer, err := version.NewVersion(reqVerStr)
if err != nil {
return errors.Wrapf(err, "Could not parse service version as a semantic version: %s\n", reqVerStr)
}
var minCompatVer *version.Version
switch service {
case "client":
minCompatVer = minClientVersion
case "origin":
minCompatVer = minOriginVersion
case "cache":
minCompatVer = minCacheVersion
default:
return errors.Errorf("Invalid version format. The director does not support your %s version (%s).", service, reqVer.String())
}
if reqVer.LessThan(minCompatVer) {
return errors.Errorf("The director does not support your %s version (%s). Please update to %s or newer.", service, reqVer.String(), minCompatVer.String())
}
return nil
}
func redirectToCache(ginCtx *gin.Context) {
err := versionCompatCheck(ginCtx)
if err != nil {
log.Warningf("A version incompatibility was encountered while redirecting to a cache and no response was served: %v", err)
ginCtx.JSON(http.StatusInternalServerError, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Incompatible versions detected: " + fmt.Sprintf("%v", err),
})
return
}
reqPath := path.Clean("/" + ginCtx.Request.URL.Path)
reqPath = strings.TrimPrefix(reqPath, "/api/v1.0/director/object")
ipAddr, err := getRealIP(ginCtx)
if err != nil {
log.Errorln("Error in getRealIP:", err)
ginCtx.String(http.StatusInternalServerError, "Internal error: Unable to determine client IP")
return
}
authzBearerEscaped := getAuthzEscaped(ginCtx.Request)
namespaceAd, originAds, cacheAds := getAdsForPath(reqPath)
// if GetAdsForPath doesn't find any ads because the prefix doesn't exist, we should
// report the lack of path first -- this is most important for the user because it tells them
// they're trying to get an object that simply doesn't exist
if namespaceAd.Path == "" {
ginCtx.String(404, "No namespace found for path. Either it doesn't exist, or the Director is experiencing problems")
return
}
// if err != nil, depth == 0, which is the default value for depth
// so we can use it as the value for the header even with err
depth, err := getLinkDepth(reqPath, namespaceAd.Path)
if err != nil {
log.Errorf("Failed to get depth attribute for the redirecting request to %q, with best match namespace prefix %q", reqPath, namespaceAd.Path)
}
// If the namespace prefix DOES exist, then it makes sense to say we couldn't find a valid cache.
if len(cacheAds) == 0 {
for _, originAd := range originAds {
if originAd.DirectReads {
cacheAds = append(cacheAds, originAd)
break
}
}
if len(cacheAds) == 0 {
ginCtx.String(http.StatusNotFound, "No cache found for path")
return
}
} else {
cacheAds, err = sortServerAdsByIP(ipAddr, cacheAds)
if err != nil {
log.Error("Error determining server ordering for cacheAds: ", err)
ginCtx.String(http.StatusInternalServerError, "Failed to determine server ordering")
return
}
}
redirectURL := getRedirectURL(reqPath, cacheAds[0], !namespaceAd.Caps.PublicReads)
linkHeader := ""
first := true
if numCAds := len(cacheAds); numCAds < cachesToSend {
cachesToSend = numCAds
}
for idx, ad := range cacheAds[:cachesToSend] {
if first {
first = false
} else {
linkHeader += ", "
}
redirectURL := getRedirectURL(reqPath, ad, !namespaceAd.Caps.PublicReads)
linkHeader += fmt.Sprintf(`<%s>; rel="duplicate"; pri=%d; depth=%d`, redirectURL.String(), idx+1, depth)
}
ginCtx.Writer.Header()["Link"] = []string{linkHeader}
if len(namespaceAd.Issuer) != 0 {
issStrings := []string{}
for _, tokIss := range namespaceAd.Issuer {
issStrings = append(issStrings, "issuer="+tokIss.IssuerUrl.String())
}
ginCtx.Writer.Header()["X-Pelican-Authorization"] = issStrings
}
if len(namespaceAd.Generation) != 0 {
tokenGen := ""
first := true
hdrVals := []string{namespaceAd.Generation[0].CredentialIssuer.String(), fmt.Sprint(namespaceAd.Generation[0].MaxScopeDepth), string(namespaceAd.Generation[0].Strategy)}
for idx, hdrKey := range []string{"issuer", "max-scope-depth", "strategy"} {
hdrVal := hdrVals[idx]
if hdrVal == "" {
continue
}
if !first {
tokenGen += ", "
}
first = false
tokenGen += hdrKey + "=" + hdrVal
}
if tokenGen != "" {
ginCtx.Writer.Header()["X-Pelican-Token-Generation"] = []string{tokenGen}
}
}
var colUrl string
// If the namespace or the origin does not allow directory listings, then we should not advertise a collections-url.
// This is because the configuration of the origin/namespace should override the inclusion of "dirlisthost" for that origin.
// Listings is true by default so if it is ever set to false we should accept that config over the dirlisthost.
if namespaceAd.Caps.Listings && originAds[0].Listings {
if !namespaceAd.PublicRead && originAds[0].AuthURL != (url.URL{}) {
colUrl = originAds[0].AuthURL.String()
} else {
colUrl = originAds[0].URL.String()
}
}
ginCtx.Writer.Header()["X-Pelican-Namespace"] = []string{fmt.Sprintf("namespace=%s, require-token=%v, collections-url=%s",
namespaceAd.Path, !namespaceAd.PublicRead, colUrl)}
// Note we only append the `authz` query parameter in the case of the redirect response and not the
// duplicate link metadata above. This is purposeful: the Link header might get too long if we repeat
// the token 20 times for 20 caches. This means a "normal HTTP client" will correctly redirect but
// anything parsing the `Link` header for metalinks will need logic for redirecting appropriately.
ginCtx.Redirect(307, getFinalRedirectURL(redirectURL, authzBearerEscaped))
}
func redirectToOrigin(ginCtx *gin.Context) {
err := versionCompatCheck(ginCtx)
if err != nil {
log.Warningf("A version incompatibility was encountered while redirecting to an origin and no response was served: %v", err)
ginCtx.JSON(http.StatusInternalServerError, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Incompatible versions detected: " + fmt.Sprintf("%v", err),
})
return
}
reqPath := path.Clean("/" + ginCtx.Request.URL.Path)
reqPath = strings.TrimPrefix(reqPath, "/api/v1.0/director/origin")
// /pelican/monitoring is the path for director-based health test
// where we have /director/healthTest API to mock a file for the cache to get
if strings.HasPrefix(reqPath, "/pelican/monitoring/") {
ginCtx.Redirect(http.StatusTemporaryRedirect, param.Server_ExternalWebUrl.GetString()+"/api/v1.0/director/healthTest"+reqPath)
return
}
// Each namespace may be exported by several origins, so we must still
// do the geolocation song and dance if we want to get the closest origin...
ipAddr, err := getRealIP(ginCtx)
if err != nil {
return
}
authzBearerEscaped := getAuthzEscaped(ginCtx.Request)
namespaceAd, originAds, _ := getAdsForPath(reqPath)
// if GetAdsForPath doesn't find any ads because the prefix doesn't exist, we should
// report the lack of path first -- this is most important for the user because it tells them
// they're trying to get an object that simply doesn't exist
if namespaceAd.Path == "" {
ginCtx.String(http.StatusNotFound, "No namespace found for path. Either it doesn't exist, or the Director is experiencing problems")
return
}
// If the namespace prefix DOES exist, then it makes sense to say we couldn't find the origin.
if len(originAds) == 0 {
ginCtx.String(http.StatusNotFound, "There are currently no origins exporting the provided namespace prefix")
return
}
// if err != nil, depth == 0, which is the default value for depth
// so we can use it as the value for the header even with err
depth, err := getLinkDepth(reqPath, namespaceAd.Path)
if err != nil {
log.Errorf("Failed to get depth attribute for the redirecting request to %q, with best match namespace prefix %q", reqPath, namespaceAd.Path)
}
originAds, err = sortServerAdsByIP(ipAddr, originAds)
if err != nil {
log.Error("Error determining server ordering for originAds: ", err)
ginCtx.String(http.StatusInternalServerError, "Failed to determine origin ordering")
return
}
linkHeader := ""
first := true
for idx, ad := range originAds {
if first {
first = false
} else {
linkHeader += ", "
}
redirectURL := getRedirectURL(reqPath, ad, !namespaceAd.PublicRead)
linkHeader += fmt.Sprintf(`<%s>; rel="duplicate"; pri=%d; depth=%d`, redirectURL.String(), idx+1, depth)
}
ginCtx.Writer.Header()["Link"] = []string{linkHeader}
var colUrl string
// If the namespace or the origin does not allow directory listings, then we should not advertise a collections-url.
// This is because the configuration of the origin/namespace should override the inclusion of "dirlisthost" for that origin.
// Listings is true by default so if it is ever set to false we should accept that config over the dirlisthost.
if namespaceAd.Caps.Listings && originAds[0].Listings {
if !namespaceAd.PublicRead && originAds[0].AuthURL != (url.URL{}) {
colUrl = originAds[0].AuthURL.String()
} else {
colUrl = originAds[0].URL.String()
}
}
ginCtx.Writer.Header()["X-Pelican-Namespace"] = []string{fmt.Sprintf("namespace=%s, require-token=%v, collections-url=%s",
namespaceAd.Path, !namespaceAd.PublicRead, colUrl)}
var redirectURL url.URL
// If we are doing a PROPFIND, check if origins enable dirlistings
if ginCtx.Request.Method == "PROPFIND" {
for idx, ad := range originAds {
if ad.Listings && namespaceAd.Caps.Listings {
redirectURL = getRedirectURL(reqPath, originAds[idx], !namespaceAd.PublicRead)
if brokerUrl := originAds[idx].BrokerURL; brokerUrl.String() != "" {
ginCtx.Header("X-Pelican-Broker", brokerUrl.String())
}
ginCtx.Redirect(http.StatusTemporaryRedirect, getFinalRedirectURL(redirectURL, authzBearerEscaped))
return
}
}
ginCtx.JSON(http.StatusMethodNotAllowed, gin.H{"error": "No origins on specified endpoint allow directory listings"})
}
// We know this can be easily bypassed, we need to eventually enforce this
// Origin should only be redirected to if it allows direct reads or the cache is the one it is talking to.
// Any client that uses this api that doesn't set directreads can talk directly to an origin
// Check if we are doing a DirectRead and if it is allowed
if ginCtx.Request.URL.Query().Has("directread") {
for idx, originAd := range originAds {
if originAd.DirectReads && namespaceAd.Caps.DirectReads {
redirectURL = getRedirectURL(reqPath, originAds[idx], !namespaceAd.PublicRead)
if brokerUrl := originAds[idx].BrokerURL; brokerUrl.String() != "" {
ginCtx.Header("X-Pelican-Broker", brokerUrl.String())
}
ginCtx.Redirect(http.StatusTemporaryRedirect, getFinalRedirectURL(redirectURL, authzBearerEscaped))
return
}
}
ginCtx.JSON(http.StatusMethodNotAllowed, gin.H{"error": "No origins on specified endpoint have direct reads enabled"})
return
}
// If we are doing a PUT, check to see if any origins are writeable
if ginCtx.Request.Method == "PUT" {
for idx, ad := range originAds {
if ad.Writes {
redirectURL = getRedirectURL(reqPath, originAds[idx], !namespaceAd.PublicRead)
if brokerUrl := originAds[idx].BrokerURL; brokerUrl.String() != "" {
ginCtx.Header("X-Pelican-Broker", brokerUrl.String())
}
ginCtx.Redirect(http.StatusTemporaryRedirect, getFinalRedirectURL(redirectURL, authzBearerEscaped))
return
}
}
ginCtx.JSON(http.StatusMethodNotAllowed, gin.H{"error": "No origins on specified endpoint have direct reads enabled"})
return
} else { // Otherwise, we are doing a GET
redirectURL := getRedirectURL(reqPath, originAds[0], !namespaceAd.PublicRead)
if brokerUrl := originAds[0].BrokerURL; brokerUrl.String() != "" {
ginCtx.Header("X-Pelican-Broker", brokerUrl.String())
}
// See note in RedirectToCache as to why we only add the authz query parameter to this URL,
// not those in the `Link`.
ginCtx.Redirect(http.StatusTemporaryRedirect, getFinalRedirectURL(redirectURL, authzBearerEscaped))
}
}
func checkHostnameRedirects(c *gin.Context, incomingHost string) {
oRedirectHosts := param.Director_OriginResponseHostnames.GetStringSlice()
cRedirectHosts := param.Director_CacheResponseHostnames.GetStringSlice()
for _, hostname := range oRedirectHosts {
if hostname == incomingHost {
if !strings.HasPrefix(c.Request.URL.Path, "/api/v1.0/director/") {
c.Request.URL.Path = "/api/v1.0/director/origin" + c.Request.URL.Path
redirectToOrigin(c)
c.Abort()
log.Debugln("Director is serving an origin based on incoming 'Host' header value of '" + hostname + "'")
return
}
}
}
for _, hostname := range cRedirectHosts {
if hostname == incomingHost {
if !strings.HasPrefix(c.Request.URL.Path, "/api/v1.0/director/") {
c.Request.URL.Path = "/api/v1.0/director/object" + c.Request.URL.Path
redirectToCache(c)
c.Abort()
log.Debugln("Director is serving a cache based on incoming 'Host' header value of '" + hostname + "'")
return
}
}
}
}
// Middleware sends GET /foo/bar to the RedirectToCache function, as if the
// original request had been made to /api/v1.0/director/object/foo/bar
func ShortcutMiddleware(defaultResponse string) gin.HandlerFunc {
return func(c *gin.Context) {
// If this is a request for getting public key, don't modify the path
// If this is a request to the Prometheus API, don't modify the path
if strings.HasPrefix(c.Request.URL.Path, "/.well-known/") ||
(strings.HasPrefix(c.Request.URL.Path, "/api/v1.0/") && !strings.HasPrefix(c.Request.URL.Path, "/api/v1.0/director/")) {
c.Next()
return
}
// Regardless of the remainder of the settings, we currently handle a PUT as a query to the origin endpoint
if c.Request.Method == "PUT" {
c.Request.URL.Path = "/api/v1.0/director/origin" + c.Request.URL.Path
redirectToOrigin(c)
c.Abort()
return
}
// We grab the host and x-forwarded-host headers, which can be set by a client with the intent of changing the
// Director's default behavior (eg the director normally forwards to caches, but if it receives a request with
// a pre-configured hostname in its x-forwarded-host header, that indicates we should actually serve an origin.)
host, hostPresent := c.Request.Header["Host"]
xForwardedHost, xForwardedHostPresent := c.Request.Header["X-Forwarded-Host"]
if hostPresent {
checkHostnameRedirects(c, host[0])
} else if xForwardedHostPresent {
checkHostnameRedirects(c, xForwardedHost[0])
}
// If we are doing a PROPFIND, we should always redirect to the origin
if c.Request.Method == "PROPFIND" {
if !strings.HasPrefix(c.Request.URL.Path, "/api/v1.0/director/") && (c.Request.Method == "PROPFIND" || c.Request.Method == "HEAD") {
c.Request.URL.Path = "/api/v1.0/director/origin" + c.Request.URL.Path
redirectToOrigin(c)
c.Abort()
return
}
}
// Check for the DirectRead query paramater and redirect to the origin if it's set if the origin allows DirectReads
if c.Request.URL.Query().Has("directread") {
log.Debugln("directread query parameter detected, redirecting to origin")
// We'll redirect to origin here and the origin will decide if it can serve the request (if direct reads are enabled)
redirectToOrigin(c)
c.Abort()
return
}
// If we're configured for cache mode or we haven't set the flag,
// we should use cache middleware
if defaultResponse == "cache" {
if !strings.HasPrefix(c.Request.URL.Path, "/api/v1.0/director/") && (c.Request.Method == "GET" || c.Request.Method == "HEAD") {
c.Request.URL.Path = "/api/v1.0/director/object" + c.Request.URL.Path
redirectToCache(c)
c.Abort()
return
}
// If the path starts with the correct prefix, continue with the next handler
c.Next()
} else if defaultResponse == "origin" {
if !strings.HasPrefix(c.Request.URL.Path, "/api/v1.0/director/") && (c.Request.Method == "GET" || c.Request.Method == "HEAD") {
c.Request.URL.Path = "/api/v1.0/director/origin" + c.Request.URL.Path
redirectToOrigin(c)
c.Abort()
return
}
c.Next()
}
}
}
func registerServeAd(engineCtx context.Context, ctx *gin.Context, sType server_structs.ServerType) {
ctx.Set("serverType", string(sType))
tokens, present := ctx.Request.Header["Authorization"]
if !present || len(tokens) == 0 {
ctx.JSON(http.StatusForbidden, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Bearer token not present in the 'Authorization' header",
})
return
}
err := versionCompatCheck(ctx)
if err != nil {
log.Warningf("A version incompatibility was encountered while registering %s and no response was served: %v", sType, err)
ctx.JSON(http.StatusInternalServerError, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Incompatible versions detected: " + fmt.Sprintf("%v", err),
})
return
}
ad := server_structs.OriginAdvertiseV1{}
adV2 := server_structs.OriginAdvertiseV2{}
err = ctx.ShouldBindBodyWith(&ad, binding.JSON)
if err != nil {
// Failed binding to a V1 type, so should now check to see if it's a V2 type
adV2 = server_structs.OriginAdvertiseV2{}
err = ctx.ShouldBindBodyWith(&adV2, binding.JSON)
if err != nil {
ctx.JSON(http.StatusBadRequest, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: fmt.Sprintf("Invalid %s registration", sType),
})
return
}
} else {
// If the OriginAdvertisement is a V1 type, convert to a V2 type
adV2 = server_structs.ConvertOriginAdV1ToV2(ad)
}
// Set to ctx for metrics handler downstream
ctx.Set("serverName", adV2.Name)
ctx.Set("serverWebUrl", adV2.WebURL)
adUrl, err := url.Parse(adV2.DataURL)
if err != nil {
log.Warningf("Failed to parse %s URL %v: %v\n", sType, adV2.DataURL, err)
ctx.JSON(http.StatusBadRequest, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: fmt.Sprintf("Invalid %s registration. %s.URL %s is not a valid URL", sType, sType, adV2.DataURL), // Origin.URL / Cache.URL
})
return
}
adWebUrl, err := url.Parse(adV2.WebURL)
if err != nil && adV2.WebURL != "" { // We allow empty WebURL string for backward compatibility
log.Warningf("Failed to parse server Web URL %v: %v\n", adV2.WebURL, err)
ctx.JSON(http.StatusBadRequest, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: fmt.Sprintf("Invalid %s registration. Server.ExternalWebUrl %s is not a valid URL", sType, adV2.WebURL),
})
return
}
brokerUrl, err := url.Parse(adV2.BrokerURL)
if err != nil {
log.Warningf("Failed to parse broker URL %s: %s", adV2.BrokerURL, err)
ctx.JSON(http.StatusBadRequest, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: fmt.Sprintf("Invalid %s registration. BrokerURL %s is not a valid URL", sType, adV2.BrokerURL),
})
}
if sType == server_structs.OriginType {
for _, namespace := range adV2.Namespaces {
// We're assuming there's only one token in the slice
token := strings.TrimPrefix(tokens[0], "Bearer ")
ok, err := verifyAdvertiseToken(engineCtx, token, namespace.Path)
if err != nil {
if err == adminApprovalErr {
log.Warningf("Failed to verify advertise token. Namespace %q requires administrator approval", namespace.Path)
ctx.JSON(http.StatusForbidden, gin.H{"approval_error": true, "error": fmt.Sprintf("The namespace %q was not approved by an administrator", namespace.Path)})
return
} else {
log.Warningln("Failed to verify token:", err)
ctx.JSON(http.StatusForbidden, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: fmt.Sprintf("Authorization token verification failed: %v", err),
})
return
}
}
if !ok {
log.Warningf("%s %v advertised to namespace %v without valid token scope\n",
sType, adV2.Name, namespace.Path)
ctx.JSON(http.StatusForbidden, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Authorization token verification failed. Token missing required scope",
})
return
}
}
} else {
token := strings.TrimPrefix(tokens[0], "Bearer ")
registryPrefix := adV2.RegistryPrefix
if registryPrefix == "" { // For caches <= 7.8.1
registryPrefix = path.Join("/caches", adV2.Name)
}
ok, err := verifyAdvertiseToken(engineCtx, token, registryPrefix)
if err != nil {
if err == adminApprovalErr {
log.Warningf("Failed to verify token. Cache %q was not approved", adV2.Name)
ctx.JSON(http.StatusForbidden, gin.H{"approval_error": true, "error": fmt.Sprintf("Cache %q was not approved by an administrator", ad.Name)})
return
} else {
log.Warningln("Failed to verify token:", err)
ctx.JSON(http.StatusForbidden, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: fmt.Sprintf("Authorization token verification failed %v", err),
})
return
}
}
if !ok {
log.Warningf("%s %v advertised without valid token scope\n", sType, adV2.Name)
ctx.JSON(http.StatusForbidden, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Authorization token verification failed. Token missing required scope",
})
return
}
}
sAd := server_structs.ServerAd{
Name: adV2.Name,
URL: *adUrl,
WebURL: *adWebUrl,
BrokerURL: *brokerUrl,
Type: sType,
Writes: adV2.Caps.Writes,
DirectReads: adV2.Caps.DirectReads,
Listings: adV2.Caps.Listings,
}
recordAd(sAd, &adV2.Namespaces)
// Start director periodic test of origin's health status if origin AD
// has WebURL field AND it's not already been registered
healthTestUtilsMutex.Lock()
defer healthTestUtilsMutex.Unlock()
if adV2.WebURL != "" {
if existingUtil, ok := healthTestUtils[sAd]; ok {
// Existing registration
if existingUtil != nil {
if existingUtil.ErrGrp != nil {
if existingUtil.ErrGrpContext.Err() != nil {
// ErrGroup has been Done. Start a new one
errgrp, errgrpCtx := errgroup.WithContext(engineCtx)
cancelCtx, cancel := context.WithCancel(errgrpCtx)
errgrp.SetLimit(1)
healthTestUtils[sAd] = &healthTestUtil{
Cancel: cancel,
ErrGrp: errgrp,
ErrGrpContext: errgrpCtx,
Status: HealthStatusInit,
}
errgrp.Go(func() error {
LaunchPeriodicDirectorTest(cancelCtx, sAd)
return nil
})
log.Debugf("New director test suite issued for %s %s. Errgroup was evicted", string(sType), sAd.URL.String())
} else {
cancelCtx, cancel := context.WithCancel(existingUtil.ErrGrpContext)
started := existingUtil.ErrGrp.TryGo(func() error {
LaunchPeriodicDirectorTest(cancelCtx, sAd)
return nil
})
if !started {
cancel()
log.Debugf("New director test suite blocked for %s %s, existing test has been running", string(sType), sAd.URL.String())
} else {
log.Debugf("New director test suite issued for %s %s. Existing registration", string(sType), sAd.URL.String())
existingUtil.Cancel()
existingUtil.Cancel = cancel
}
}
} else {
log.Errorf("%s %s registration didn't start a new director test cycle: errgroup is nil", string(sType), &sAd.URL)
}
} else {
log.Errorf("%s %s registration didn't start a new director test cycle: healthTestUtils item is nil", string(sType), &sAd.URL)
}
} else { // No healthTestUtils found, new registration
errgrp, errgrpCtx := errgroup.WithContext(engineCtx)
cancelCtx, cancel := context.WithCancel(errgrpCtx)
errgrp.SetLimit(1)
healthTestUtils[sAd] = &healthTestUtil{
Cancel: cancel,
ErrGrp: errgrp,
ErrGrpContext: errgrpCtx,
Status: HealthStatusUnknown,
}
errgrp.Go(func() error {
LaunchPeriodicDirectorTest(cancelCtx, sAd)
return nil
})
}
}
if sType == server_structs.OriginType {
originStatUtilsMutex.Lock()
defer originStatUtilsMutex.Unlock()
statUtil, ok := originStatUtils[sAd.URL.String()]
if !ok || statUtil.Errgroup == nil {
baseCtx, cancel := context.WithCancel(engineCtx)
concLimit := param.Director_StatConcurrencyLimit.GetInt()
statErrGrp := errgroup.Group{}
statErrGrp.SetLimit(concLimit)
newUtil := originStatUtil{
Errgroup: &statErrGrp,
Cancel: cancel,
Context: baseCtx,
}
originStatUtils[sAd.URL.String()] = newUtil
}
}
ctx.JSON(http.StatusOK, server_structs.SimpleApiResp{Status: server_structs.RespOK, Msg: "Successful registration"})
}
func serverAdMetricMiddleware(ctx *gin.Context) {
ctx.Next()
serverName := "Unknown"
serverWebUrl := ctx.ClientIP()
statusCode := ctx.Writer.Status()
if ctx.GetString("serverName") != "" {
serverName = ctx.GetString("serverName")
}
if ctx.GetString("serverWebUrl") != "" {
serverWebUrl = ctx.GetString("serverWebUrl")
}
metrics.PelicanDirectorTotalAdvertisementsReceived.With(
prometheus.Labels{
"server_name": serverName,
"server_web_url": serverWebUrl,
"server_type": ctx.GetString("serverType"),
"status_code": strconv.Itoa(statusCode),
}).Inc()
}
// Return a list of registered origins and caches in Prometheus HTTP SD format
// for director's Prometheus service discovery
func discoverOriginCache(ctx *gin.Context) {
authOption := token.AuthOption{
Sources: []token.TokenSource{token.Header},
Issuers: []token.TokenIssuer{token.LocalIssuer},
Scopes: []token_scopes.TokenScope{token_scopes.Pelican_DirectorServiceDiscovery},
}
status, ok, err := token.Verify(ctx, authOption)
if !ok {
log.Warningf("Cannot verify token for accessing director's service discovery: %v", err)
ctx.JSON(status, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: err.Error(),
})
return
}
promDiscoveryRes := make([]PromDiscoveryItem, 0)
for _, ad := range serverAds.Items() {
serverAd := ad.Value()
if serverAd.WebURL.String() == "" {
// Origins and caches fetched from topology can't be scraped as they
// don't have a WebURL
continue
}
var auth_url string
if serverAd.AuthURL == (url.URL{}) {
auth_url = serverAd.URL.String()
} else {
auth_url = serverAd.AuthURL.String()
}
promDiscoveryRes = append(promDiscoveryRes, PromDiscoveryItem{
Targets: []string{serverAd.WebURL.Hostname() + ":" + serverAd.WebURL.Port()},
Labels: map[string]string{
"server_type": string(serverAd.Type),
"server_name": serverAd.Name,
"server_auth_url": auth_url,
"server_url": serverAd.URL.String(),
"server_web_url": serverAd.WebURL.String(),
"server_lat": fmt.Sprintf("%.4f", serverAd.Latitude),
"server_long": fmt.Sprintf("%.4f", serverAd.Longitude),
},
})
}
ctx.JSON(200, promDiscoveryRes)
}
func listNamespacesV1(ctx *gin.Context) {
namespaceAdsV2 := listNamespacesFromOrigins()
namespaceAdsV1 := server_structs.ConvertNamespaceAdsV2ToV1(namespaceAdsV2)
ctx.JSON(http.StatusOK, namespaceAdsV1)
}
func listNamespacesV2(ctx *gin.Context) {
namespacesAdsV2 := listNamespacesFromOrigins()
namespacesAdsV2 = append(namespacesAdsV2, server_structs.NamespaceAdV2{
PublicRead: true,
Caps: server_structs.Capabilities{
PublicReads: true,
Reads: true,
},
Path: "/pelican/monitoring",
})
ctx.JSON(http.StatusOK, namespacesAdsV2)
}
func getPrefixByPath(ctx *gin.Context) {
pathParam := ctx.Param("path")
if pathParam == "" || pathParam == "/" {
ctx.AbortWithStatusJSON(http.StatusBadRequest, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Bad request. Path is empty or '/' ",
})
return
}
originNs, _, _ := getAdsForPath(pathParam)
// If originNs.Path is an empty value, then the namespace is not found
if originNs.Path == "" {
ctx.AbortWithStatusJSON(http.StatusNotFound, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Namespace prefix not found for " + pathParam,
})
return
}
res := server_structs.GetPrefixByPathRes{Prefix: originNs.Path}
ctx.JSON(http.StatusOK, res)
}
// Generate a mock file for caches to fetch. This is for director-based health tests for caches
// So that we don't require an origin to feed the test file to the cache
func getHealthTestFile(ctx *gin.Context) {
// Expected path: /pelican/monitoring/2006-01-02T15:04:05Z07:00.txt
pathParam := ctx.Param("path")
cleanedPath := path.Clean(pathParam)
if cleanedPath == "" || !strings.HasPrefix(cleanedPath, cacheMonitroingBasePath+"/") {
ctx.JSON(http.StatusBadRequest, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Path parameter is not a valid health test path: " + cleanedPath})
return
}
fileName := strings.TrimPrefix(cleanedPath, cacheMonitroingBasePath+"/")
if fileName == "" {
ctx.JSON(http.StatusBadRequest, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Path parameter is not a valid health test path: " + cleanedPath})
return
}
fileNameSplit := strings.SplitN(fileName, ".", 2)
if len(fileNameSplit) != 2 {
ctx.JSON(http.StatusBadRequest, server_structs.SimpleApiResp{Status: server_structs.RespFailed, Msg: "Test file name is missing file extension: " + cleanedPath})
return
}
filenameWoExt := fileNameSplit[0]
fileContent := fmt.Sprintf("%s%s\n", testFileContent, filenameWoExt)
if ctx.Request.Method == "HEAD" {
ctx.Header("Content-Length", strconv.Itoa(len(fileContent)))
} else {
ctx.String(http.StatusOK, fileContent)
}
}
func RegisterDirectorAPI(ctx context.Context, router *gin.RouterGroup) {
directorAPIV1 := router.Group("/api/v1.0/director")
{
// Establish the routes used for cache/origin redirection
directorAPIV1.GET("/object/*any", redirectToCache)
directorAPIV1.HEAD("/object/*any", redirectToCache)
directorAPIV1.GET("/origin/*any", redirectToOrigin)
directorAPIV1.HEAD("/origin/*any", redirectToOrigin)
directorAPIV1.PUT("/origin/*any", redirectToOrigin)
directorAPIV1.POST("/registerOrigin", serverAdMetricMiddleware, func(gctx *gin.Context) { registerServeAd(ctx, gctx, server_structs.OriginType) })