forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api_definition_manager.go
1347 lines (1108 loc) · 40.8 KB
/
api_definition_manager.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
package main
import (
b64 "encoding/base64"
"encoding/json"
"errors"
"github.com/Sirupsen/logrus"
"github.com/gorilla/context"
"github.com/TykTechnologies/tykcommon"
"github.com/rubyist/circuitbreaker"
"gopkg.in/mgo.v2"
"io/ioutil"
"net/http"
"net/url"
"path/filepath"
"regexp"
"strings"
"sync"
textTemplate "text/template"
"time"
)
const (
DefaultAuthProvider tykcommon.AuthProviderCode = "default"
DefaultSessionProvider tykcommon.SessionProviderCode = "default"
DefaultStorageEngine tykcommon.StorageEngineCode = "redis"
LDAPStorageEngine tykcommon.StorageEngineCode = "ldap"
RPCStorageEngine tykcommon.StorageEngineCode = "rpc"
)
// URLStatus is a custom enum type to avoid collisions
type URLStatus int
// Enums representing the various statuses for a VersionInfo Path match during a
// proxy request
const (
Ignored URLStatus = 1
WhiteList URLStatus = 2
BlackList URLStatus = 3
Cached URLStatus = 4
Transformed URLStatus = 5
HeaderInjected URLStatus = 6
HeaderInjectedResponse URLStatus = 7
TransformedResponse URLStatus = 8
HardTimeout URLStatus = 9
CircuitBreaker URLStatus = 10
URLRewrite URLStatus = 11
VirtualPath URLStatus = 12
RequestSizeLimit URLStatus = 13
MethodTransformed URLStatus = 14
)
// RequestStatus is a custom type to avoid collisions
type RequestStatus string
// Statuses of the request, all are false-y except StatusOk and StatusOkAndIgnore
const (
VersionNotFound RequestStatus = "Version information not found"
VersionDoesNotExist RequestStatus = "This API version does not seem to exist"
VersionPathsNotFound RequestStatus = "Path information could not be found for version"
VersionWhiteListStatusNotFound = "WhiteListStatus for path not found"
VersionExpired RequestStatus = "Api Version has expired, please check documentation or contact administrator"
EndPointNotAllowed RequestStatus = "Requested endpoint is forbidden"
GeneralFailure RequestStatus = "An error occured that should have not been possible"
StatusOkAndIgnore RequestStatus = "Everything OK, passing and not filtering"
StatusOk RequestStatus = "Everything OK, passing"
StatusCached RequestStatus = "Cached path"
StatusTransform RequestStatus = "Transformed path"
StatusTransformResponse RequestStatus = "Transformed response"
StatusHeaderInjected RequestStatus = "Header injected"
StatusMethodTransformed RequestStatus = "Method Transformed"
StatusHeaderInjectedResponse RequestStatus = "Header injected on response"
StatusActionRedirect RequestStatus = "Found an Action, changing route"
StatusRedirectFlowByReply RequestStatus = "Exceptional action requested, redirecting flow!"
StatusHardTimeout RequestStatus = "Hard Timeout enforced on path"
StatusCircuitBreaker RequestStatus = "Circuit breaker enforced"
StatusURLRewrite RequestStatus = "URL Rewritten"
StatusVirtualPath RequestStatus = "Virtual Endpoint"
StatusRequestSizeControlled RequestStatus = "Request Size Limited"
)
// URLSpec represents a flattened specification for URLs, used to check if a proxy URL
// path is on any of the white, plack or ignored lists. This is generated as part of the
// configuration init
type URLSpec struct {
Spec *regexp.Regexp
Status URLStatus
MethodActions map[string]tykcommon.EndpointMethodMeta
TransformAction TransformSpec
TransformResponseAction TransformSpec
InjectHeaders tykcommon.HeaderInjectionMeta
InjectHeadersResponse tykcommon.HeaderInjectionMeta
HardTimeout tykcommon.HardTimeoutMeta
CircuitBreaker ExtendedCircuitBreakerMeta
URLRewrite tykcommon.URLRewriteMeta
VirtualPathSpec tykcommon.VirtualMeta
RequestSize tykcommon.RequestSizeMeta
MethodTransform tykcommon.MethodTransformMeta
}
type TransformSpec struct {
tykcommon.TemplateMeta
Template *textTemplate.Template
}
type ExtendedCircuitBreakerMeta struct {
tykcommon.CircuitBreakerMeta
CB *circuit.Breaker
}
// APISpec represents a path specification for an API, to avoid enumerating multiple nested lists, a single
// flattened URL list is checked for matching paths and then it's status evaluated if found.
type APISpec struct {
tykcommon.APIDefinition
RxPaths map[string][]URLSpec
WhiteListEnabled map[string]bool
target *url.URL
AuthManager AuthorisationHandler
SessionManager SessionHandler
OAuthManager *OAuthManager
OrgSessionManager SessionHandler
EventPaths map[tykcommon.TykEvent][]TykEventHandler
Health HealthChecker
JSVM *JSVM
ResponseChain *[]TykResponseHandler
RoundRobin *RoundRobin
LastGoodHostList *tykcommon.HostList
HasRun bool
ServiceRefreshInProgress bool
}
// APIDefinitionLoader will load an Api definition from a storage system. It has two methods LoadDefinitionsFromMongo()
// and LoadDefinitions(), each will pull api specifications from different locations.
type APIDefinitionLoader struct {
dbSession *mgo.Session
}
// Nonce to use when interacting with the dashboard service
var ServiceNonceMutex = &sync.Mutex{}
var ServiceNonce string
// Connect connects to the storage engine - can be null
func (a *APIDefinitionLoader) Connect() {
log.Warning("MongoDB Driver no longer implemented")
}
// Connect connects to the storage engine - can be null
func (a *APIDefinitionLoader) Disconnect() {
if a.dbSession != nil {
a.dbSession.Close()
}
}
// MakeSpec will generate a flattened URLSpec from and APIDefinitions' VersionInfo data. paths are
// keyed to the Api version name, which is determined during routing to speed up lookups
func (a *APIDefinitionLoader) MakeSpec(thisAppConfig tykcommon.APIDefinition) APISpec {
newAppSpec := APISpec{}
newAppSpec.APIDefinition = thisAppConfig
// We'll push the default HealthChecker:
newAppSpec.Health = &DefaultHealthChecker{
APIID: newAppSpec.APIID,
}
// Add any new session managers or auth handlers here
if newAppSpec.APIDefinition.AuthProvider.Name != "" {
switch newAppSpec.APIDefinition.AuthProvider.Name {
case DefaultAuthProvider:
newAppSpec.AuthManager = &DefaultAuthorisationManager{}
default:
newAppSpec.AuthManager = &DefaultAuthorisationManager{}
}
} else {
newAppSpec.AuthManager = &DefaultAuthorisationManager{}
}
if newAppSpec.APIDefinition.SessionProvider.Name != "" {
switch newAppSpec.APIDefinition.SessionProvider.Name {
case DefaultSessionProvider:
newAppSpec.SessionManager = &DefaultSessionManager{}
newAppSpec.OrgSessionManager = &DefaultSessionManager{}
default:
newAppSpec.SessionManager = &DefaultSessionManager{}
newAppSpec.OrgSessionManager = &DefaultSessionManager{}
}
} else {
newAppSpec.SessionManager = &DefaultSessionManager{}
newAppSpec.OrgSessionManager = &DefaultSessionManager{}
}
// Create and init the virtual Machine
if config.EnableJSVM {
newAppSpec.JSVM = &JSVM{}
newAppSpec.JSVM.Init(config.TykJSPath)
}
// Set up Event Handlers
log.Debug("INITIALISING EVENT HANDLERS")
newAppSpec.EventPaths = make(map[tykcommon.TykEvent][]TykEventHandler)
for eventName, eventHandlerConfs := range thisAppConfig.EventHandlers.Events {
log.Debug("FOUND EVENTS TO INIT")
for _, handlerConf := range eventHandlerConfs {
log.Debug("CREATING EVENT HANDLERS")
thisEventHandlerInstance, getHandlerErr := GetEventHandlerByName(handlerConf, &newAppSpec)
if getHandlerErr != nil {
log.Error("Failed to init event handler: ", getHandlerErr)
} else {
log.Debug("Init Event Handler: ", eventName)
newAppSpec.EventPaths[eventName] = append(newAppSpec.EventPaths[eventName], thisEventHandlerInstance)
}
}
}
newAppSpec.RxPaths = make(map[string][]URLSpec)
newAppSpec.WhiteListEnabled = make(map[string]bool)
for _, v := range thisAppConfig.VersionData.Versions {
var pathSpecs []URLSpec
var whiteListSpecs bool
// If we have transitioned to extended path specifications, we should use these now
if v.UseExtendedPaths {
pathSpecs, whiteListSpecs = a.getExtendedPathSpecs(v, &newAppSpec)
} else {
log.Warning("Legacy path detected! Upgrade to extended.")
pathSpecs, whiteListSpecs = a.getPathSpecs(v)
}
newAppSpec.RxPaths[v.Name] = pathSpecs
newAppSpec.WhiteListEnabled[v.Name] = whiteListSpecs
}
return newAppSpec
}
func (a *APIDefinitionLoader) readBody(response *http.Response) ([]byte, error) {
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
if err != nil {
return []byte(""), err
}
return contents, nil
}
func ReLogin() {
connStr := config.DBAppConfOptions.ConnectionString
if connStr == "" {
log.Fatal("Connection string is empty, failing.")
}
connStr = connStr + "/register/node"
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("Registering node.")
RegisterNodeWithDashboard(connStr, config.NodeSecret)
}
func RegisterNodeWithDashboard(endpoint string, secret string) error {
// Get the definitions
log.Debug("Calling: ", endpoint)
newRequest, err := http.NewRequest("GET", endpoint, nil)
if err != nil {
log.Error("Failed to create request: ", err)
}
newRequest.Header.Add("authorization", secret)
c := &http.Client{
Timeout: 5*time.Second,
}
response, reqErr := c.Do(newRequest)
if reqErr != nil {
log.Error("Request failed: ", reqErr)
time.Sleep(time.Second * 5)
return RegisterNodeWithDashboard(endpoint, secret)
}
defer response.Body.Close()
retBody, err := ioutil.ReadAll(response.Body)
if response.StatusCode != 200 {
log.Error("Failed to register node, retrying in 5s")
log.Debug("Response was: ", string(retBody))
time.Sleep(time.Second * 5)
return RegisterNodeWithDashboard(endpoint, secret)
}
if err != nil {
return err
}
// Extract tagged APIs#
type NodeResponseOK struct {
Status string
Message map[string]string
Nonce string
}
thisVal := NodeResponseOK{}
decErr := json.Unmarshal(retBody, &thisVal)
if decErr != nil {
log.Error("Failed to decode body: ", decErr)
return decErr
}
// Set the NodeID
var found bool
NodeID, found = thisVal.Message["NodeID"]
if !found {
log.Error("Failed to register node, retrying in 5s")
time.Sleep(time.Second * 5)
return RegisterNodeWithDashboard(endpoint, secret)
}
log.WithFields(logrus.Fields{
"prefix": "dashboard",
"id": NodeID,
}).Info("Node registered")
// Set the nonce
ServiceNonceMutex.Lock()
defer ServiceNonceMutex.Unlock()
ServiceNonce = thisVal.Nonce
log.Debug("Registration Finished: Nonce Set: ", ServiceNonce)
return nil
}
func StartBeating(endpoint, secret string) {
for {
failure := SendHeartBeat(endpoint, secret)
if failure != nil {
log.Warning(failure)
}
time.Sleep(time.Second * 5)
}
}
func SendHeartBeat(endpoint string, secret string) error {
// Get the definitions
log.Debug("Calling: ", endpoint)
newRequest, err := http.NewRequest("GET", endpoint, nil)
if err != nil {
log.Error("Failed to create request: ", err)
}
newRequest.Header.Add("authorization", secret)
newRequest.Header.Add("x-tyk-nodeid", NodeID)
log.Debug("Sending Heartbeat as: ", NodeID)
ServiceNonceMutex.Lock()
defer ServiceNonceMutex.Unlock()
newRequest.Header.Add("x-tyk-nonce", ServiceNonce)
c := &http.Client{
Timeout: 5*time.Second,
}
response, reqErr := c.Do(newRequest)
if reqErr != nil {
return errors.New("Dashboard is down? Heartbeat is failing.")
}
if response.StatusCode != 200 {
return errors.New("Dashboard is down? Heartbeat is failing.")
}
defer response.Body.Close()
retBody, err := ioutil.ReadAll(response.Body)
if err != nil {
return err
}
// Extract tagged APIs#
type NodeResponseOK struct {
Status string
Message map[string]string
Nonce string
}
thisVal := NodeResponseOK{}
decErr := json.Unmarshal(retBody, &thisVal)
if decErr != nil {
log.Error("Failed to decode body: ", decErr)
return decErr
}
// Set the nonce
ServiceNonce = thisVal.Nonce
log.Debug("Hearbeat Finished: Nonce Set: ", ServiceNonce)
return nil
}
// LoadDefinitionsFromDashboardService will connect and download ApiDefintions from a Tyk Dashboard instance.
func (a *APIDefinitionLoader) LoadDefinitionsFromDashboardService(endpoint string, secret string) *[]*APISpec {
var APISpecs = []*APISpec{}
// Get the definitions
log.Debug("Calling: ", endpoint)
newRequest, err := http.NewRequest("GET", endpoint, nil)
if err != nil {
log.Error("Failed to create request: ", err)
}
newRequest.Header.Add("authorization", secret)
log.Debug("Using: NodeID: ", NodeID)
newRequest.Header.Add("x-tyk-nodeid", NodeID)
ServiceNonceMutex.Lock()
defer ServiceNonceMutex.Unlock()
newRequest.Header.Add("x-tyk-nonce", ServiceNonce)
c := &http.Client{
Timeout: 5*time.Second,
}
response, reqErr := c.Do(newRequest)
if reqErr != nil {
log.Error("Request failed: ", reqErr)
return &APISpecs
}
retBody, bErr := a.readBody(response)
if bErr != nil {
log.Error("Failed to read body: ", bErr)
return &APISpecs
}
// Extract tagged APIs#
type ResponseStruct struct {
ApiDefinition tykcommon.APIDefinition `bson:"api_definition" json:"api_definition"`
}
type NodeResponseOK struct {
Status string
Message []ResponseStruct
Nonce string
}
thisList := NodeResponseOK{}
decErr := json.Unmarshal(retBody, &thisList)
if decErr != nil {
log.Error("Failed to decode body: ", decErr)
log.Debug("Response was: ", string(retBody))
log.Info("--> Retrying in 20s")
time.Sleep(time.Second * 20)
ReLogin()
return a.LoadDefinitionsFromDashboardService(endpoint, secret)
// return &APISpecs
}
thisRawList := make(map[string]interface{})
rawdecErr := json.Unmarshal(retBody, &thisRawList)
if rawdecErr != nil {
log.Error("Failed to decode body (raw): ", rawdecErr)
return &APISpecs
}
// Extract tagged entries only
APIDefinitions := make([]tykcommon.APIDefinition, 0)
if config.DBAppConfOptions.NodeIsSegmented {
APIDefinitions = make([]tykcommon.APIDefinition, 0)
tagList := make(map[string]bool)
toLoad := make(map[string]tykcommon.APIDefinition)
for _, mt := range config.DBAppConfOptions.Tags {
tagList[mt] = true
}
for index, apiEntry := range thisList.Message {
for _, t := range apiEntry.ApiDefinition.Tags {
_, ok := tagList[t]
if ok {
apiEntry.ApiDefinition.RawData = thisRawList["Message"].([]interface{})[index].(map[string]interface{})["api_definition"].(map[string]interface{})
toLoad[apiEntry.ApiDefinition.APIID] = apiEntry.ApiDefinition
}
}
}
for _, apiDef := range toLoad {
APIDefinitions = append(APIDefinitions, apiDef)
}
} else {
for index, apiEntry := range thisList.Message {
apiEntry.ApiDefinition.RawData = thisRawList["Message"].([]interface{})[index].(map[string]interface{})["api_definition"].(map[string]interface{})
APIDefinitions = append(APIDefinitions, apiEntry.ApiDefinition)
}
}
// Process
for _, thisAppConfig := range APIDefinitions {
newAppSpec := a.MakeSpec(thisAppConfig)
APISpecs = append(APISpecs, &newAppSpec)
}
// Set the nonce
ServiceNonce = thisList.Nonce
log.Debug("Loading APIS Finished: Nonce Set: ", ServiceNonce)
return &APISpecs
}
// LoadDefinitionsFromCloud will connect and download ApiDefintions from a Mongo DB instance.
func (a *APIDefinitionLoader) LoadDefinitionsFromRPC(orgId string) *[]*APISpec {
store := RPCStorageHandler{UserKey: config.SlaveOptions.APIKey, Address: config.SlaveOptions.ConnectionString}
store.Connect()
// enable segments
var tags []string
if config.DBAppConfOptions.NodeIsSegmented {
log.Info("Segmented node, loading: ", config.DBAppConfOptions.Tags)
tags = config.DBAppConfOptions.Tags
} else {
tags = make([]string, 0)
}
apiCollection := store.GetApiDefinitions(orgId, tags)
store.Disconnect()
if RPC_LoadCount > 0 {
SaveRPCDefinitionsBackup(apiCollection)
}
return a.processRPCDefinitions(apiCollection)
}
func (a *APIDefinitionLoader) processRPCDefinitions(apiCollection string) *[]*APISpec {
var APISpecs = []*APISpec{}
var APIDefinitions = []tykcommon.APIDefinition{}
var StringDefs = make([]map[string]interface{}, 0)
jErr1 := json.Unmarshal([]byte(apiCollection), &APIDefinitions)
if jErr1 != nil {
log.Error("Failed decode: ", jErr1)
return nil
}
jErr2 := json.Unmarshal([]byte(apiCollection), &StringDefs)
if jErr2 != nil {
log.Error("Failed decode: ", jErr2)
return nil
}
for i, thisAppConfig := range APIDefinitions {
thisAppConfig.DecodeFromDB()
thisAppConfig.RawData = StringDefs[i] // Lets keep a copy for plugable modules
if config.SlaveOptions.BindToSlugsInsteadOfListenPaths {
newListenPath := "/" + thisAppConfig.Slug //+ "/"
log.Warning("Binding to ",
newListenPath,
" instead of ",
thisAppConfig.Proxy.ListenPath)
thisAppConfig.Proxy.ListenPath = newListenPath
}
newAppSpec := a.MakeSpec(thisAppConfig)
APISpecs = append(APISpecs, &newAppSpec)
}
return &APISpecs
}
func (a *APIDefinitionLoader) ParseDefinition(apiDef []byte) (tykcommon.APIDefinition, map[string]interface{}) {
thisAppConfig := tykcommon.APIDefinition{}
err := json.Unmarshal(apiDef, &thisAppConfig)
if err != nil {
log.Error("[RPC] --> Couldn't unmarshal api configuration")
log.Error(err)
}
// Got the structured version - now lets get a raw copy for modules
thisRawConfig := make(map[string]interface{})
json.Unmarshal(apiDef, &thisRawConfig)
return thisAppConfig, thisRawConfig
}
// LoadDefinitions will load APIDefinitions from a directory on the filesystem. Definitions need
// to be the JSON representation of APIDefinition object
func (a *APIDefinitionLoader) LoadDefinitions(dir string) *[]*APISpec {
var APISpecs = []*APISpec{}
// Grab json files from directory
files, _ := ioutil.ReadDir(dir)
for _, f := range files {
if strings.Contains(f.Name(), ".json") {
filePath := filepath.Join(dir, f.Name())
log.Info("Loading API Specification from ", filePath)
appConfig, err := ioutil.ReadFile(filePath)
thisAppConfig, thisRawConfig := a.ParseDefinition(appConfig)
if err != nil {
log.Error("Couldn't load app configuration file")
log.Error(err)
}
thisAppConfig.RawData = thisRawConfig // Lets keep a copy for plugable modules
newAppSpec := a.MakeSpec(thisAppConfig)
APISpecs = append(APISpecs, &newAppSpec)
}
}
return &APISpecs
}
func (a *APIDefinitionLoader) getPathSpecs(apiVersionDef tykcommon.VersionInfo) ([]URLSpec, bool) {
ignoredPaths := a.compilePathSpec(apiVersionDef.Paths.Ignored, Ignored)
blackListPaths := a.compilePathSpec(apiVersionDef.Paths.BlackList, BlackList)
whiteListPaths := a.compilePathSpec(apiVersionDef.Paths.WhiteList, WhiteList)
combinedPath := []URLSpec{}
combinedPath = append(combinedPath, ignoredPaths...)
combinedPath = append(combinedPath, blackListPaths...)
combinedPath = append(combinedPath, whiteListPaths...)
if len(whiteListPaths) > 0 {
return combinedPath, true
}
return combinedPath, false
}
func (a *APIDefinitionLoader) generateRegex(stringSpec string, newSpec *URLSpec, specType URLStatus) {
apiLangIDsRegex, _ := regexp.Compile("{(.*?)}")
asRegexStr := apiLangIDsRegex.ReplaceAllString(stringSpec, "(.*?)")
asRegex, _ := regexp.Compile(asRegexStr)
newSpec.Status = specType
newSpec.Spec = asRegex
}
func (a *APIDefinitionLoader) compilePathSpec(paths []string, specType URLStatus) []URLSpec {
// transform a configuration URL into an array of URLSpecs
// This way we can iterate the whole array once, on match we break with status
thisURLSpec := []URLSpec{}
for _, stringSpec := range paths {
newSpec := URLSpec{}
a.generateRegex(stringSpec, &newSpec, specType)
thisURLSpec = append(thisURLSpec, newSpec)
}
return thisURLSpec
}
func (a *APIDefinitionLoader) compileExtendedPathSpec(paths []tykcommon.EndPointMeta, specType URLStatus) []URLSpec {
// transform an extended configuration URL into an array of URLSpecs
// This way we can iterate the whole array once, on match we break with status
thisURLSpec := []URLSpec{}
for _, stringSpec := range paths {
newSpec := URLSpec{}
a.generateRegex(stringSpec.Path, &newSpec, specType)
// Extend with method actions
newSpec.MethodActions = stringSpec.MethodActions
thisURLSpec = append(thisURLSpec, newSpec)
}
return thisURLSpec
}
func (a *APIDefinitionLoader) compileCachedPathSpec(paths []string) []URLSpec {
// transform an extended configuration URL into an array of URLSpecs
// This way we can iterate the whole array once, on match we break with status
thisURLSpec := []URLSpec{}
for _, stringSpec := range paths {
newSpec := URLSpec{}
a.generateRegex(stringSpec, &newSpec, Cached)
// Extend with method actions
thisURLSpec = append(thisURLSpec, newSpec)
}
return thisURLSpec
}
func (a *APIDefinitionLoader) loadFileTemplate(path string) (*textTemplate.Template, error) {
log.Debug("-- Loading template: ", path)
thisT, tErr := textTemplate.ParseFiles(path)
return thisT, tErr
}
func (a *APIDefinitionLoader) loadBlobTemplate(blob string) (*textTemplate.Template, error) {
log.Debug("-- Loading blob")
uDec, decErr := b64.StdEncoding.DecodeString(blob)
if decErr != nil {
return nil, decErr
}
thisT, tErr := textTemplate.New("blob").Parse(string(uDec))
return thisT, tErr
}
func (a *APIDefinitionLoader) compileTransformPathSpec(paths []tykcommon.TemplateMeta, stat URLStatus) []URLSpec {
// transform an extended configuration URL into an array of URLSpecs
// This way we can iterate the whole array once, on match we break with status
thisURLSpec := []URLSpec{}
log.Debug("Checking for transform paths...")
for _, stringSpec := range paths {
log.Debug("-- Generating path")
newSpec := URLSpec{}
a.generateRegex(stringSpec.Path, &newSpec, stat)
// Extend with template actions
newTransformSpec := TransformSpec{TemplateMeta: stringSpec}
// Load the templates
var templErr error
switch stringSpec.TemplateData.Mode {
case tykcommon.UseFile:
log.Debug("-- Using File mode")
newTransformSpec.Template, templErr = a.loadFileTemplate(stringSpec.TemplateData.TemplateSource)
case tykcommon.UseBlob:
log.Debug("-- Blob mode")
newTransformSpec.Template, templErr = a.loadBlobTemplate(stringSpec.TemplateData.TemplateSource)
default:
log.Warning("[Transform Templates] No tempalte mode defined! Found: ", stringSpec.TemplateData.Mode)
templErr = errors.New("No valid template mode defined, must be either 'file' or 'blob'.")
}
if stat == Transformed {
newSpec.TransformAction = newTransformSpec
} else {
newSpec.TransformResponseAction = newTransformSpec
}
if templErr == nil {
thisURLSpec = append(thisURLSpec, newSpec)
log.Debug("-- Loaded")
} else {
log.Error("Template load failure! Skipping transformation: ", templErr)
}
}
return thisURLSpec
}
func (a *APIDefinitionLoader) compileInjectedHeaderSpec(paths []tykcommon.HeaderInjectionMeta, stat URLStatus) []URLSpec {
// transform an extended configuration URL into an array of URLSpecs
// This way we can iterate the whole array once, on match we break with status
thisURLSpec := []URLSpec{}
for _, stringSpec := range paths {
newSpec := URLSpec{}
a.generateRegex(stringSpec.Path, &newSpec, stat)
// Extend with method actions
if stat == HeaderInjected {
newSpec.InjectHeaders = stringSpec
} else {
newSpec.InjectHeadersResponse = stringSpec
}
thisURLSpec = append(thisURLSpec, newSpec)
}
return thisURLSpec
}
func (a *APIDefinitionLoader) compileMethodTransformSpec(paths []tykcommon.MethodTransformMeta, stat URLStatus) []URLSpec {
// transform an extended configuration URL into an array of URLSpecs
// This way we can iterate the whole array once, on match we break with status
thisURLSpec := []URLSpec{}
for _, stringSpec := range paths {
newSpec := URLSpec{}
a.generateRegex(stringSpec.Path, &newSpec, stat)
newSpec.MethodTransform = stringSpec
thisURLSpec = append(thisURLSpec, newSpec)
}
return thisURLSpec
}
func (a *APIDefinitionLoader) compileTimeoutPathSpec(paths []tykcommon.HardTimeoutMeta, stat URLStatus) []URLSpec {
// transform an extended configuration URL into an array of URLSpecs
// This way we can iterate the whole array once, on match we break with status
thisURLSpec := []URLSpec{}
for _, stringSpec := range paths {
newSpec := URLSpec{}
a.generateRegex(stringSpec.Path, &newSpec, stat)
// Extend with method actions
newSpec.HardTimeout = stringSpec
thisURLSpec = append(thisURLSpec, newSpec)
}
return thisURLSpec
}
func (a *APIDefinitionLoader) compileRequestSizePathSpec(paths []tykcommon.RequestSizeMeta, stat URLStatus) []URLSpec {
// transform an extended configuration URL into an array of URLSpecs
// This way we can iterate the whole array once, on match we break with status
thisURLSpec := []URLSpec{}
for _, stringSpec := range paths {
newSpec := URLSpec{}
a.generateRegex(stringSpec.Path, &newSpec, stat)
// Extend with method actions
newSpec.RequestSize = stringSpec
thisURLSpec = append(thisURLSpec, newSpec)
}
return thisURLSpec
}
func (a *APIDefinitionLoader) compileCircuitBreakerPathSpec(paths []tykcommon.CircuitBreakerMeta, stat URLStatus, apiSpec *APISpec) []URLSpec {
// transform an extended configuration URL into an array of URLSpecs
// This way we can iterate the whole array once, on match we break with status
thisURLSpec := []URLSpec{}
for _, stringSpec := range paths {
newSpec := URLSpec{}
a.generateRegex(stringSpec.Path, &newSpec, stat)
// Extend with method actions
newSpec.CircuitBreaker = ExtendedCircuitBreakerMeta{CircuitBreakerMeta: stringSpec}
log.Debug("Initialising circuit breaker for: ", stringSpec.Path)
newSpec.CircuitBreaker.CB = circuit.NewRateBreaker(stringSpec.ThresholdPercent, stringSpec.Samples)
events := newSpec.CircuitBreaker.CB.Subscribe()
go func() {
path := stringSpec.Path
spec := apiSpec
breakerPtr := newSpec.CircuitBreaker.CB
timerActive := false
for {
e := <-events
switch e {
case circuit.BreakerTripped:
log.Warning("[PROXY] [CIRCUIT BREKER] Breaker tripped for path: ", path)
log.Debug("Breaker tripped: ", e)
// Start a timer function
if !timerActive {
go func(timeout int, breaker *circuit.Breaker) {
log.Debug("-- Sleeping for (s): ", timeout)
time.Sleep(time.Duration(timeout) * time.Second)
log.Debug("-- Resetting breaker")
breaker.Reset()
timerActive = false
}(newSpec.CircuitBreaker.ReturnToServiceAfter, breakerPtr)
timerActive = true
}
if spec.Proxy.ServiceDiscovery.UseDiscoveryService {
if ServiceCache != nil {
log.Warning("[PROXY] [CIRCUIT BREKER] Refreshing host list")
ServiceCache.Delete(spec.APIID)
}
}
spec.FireEvent(EVENT_BreakerTriggered,
EVENT_CurcuitBreakerMeta{
EventMetaDefault: EventMetaDefault{Message: "Breaker Tripped"},
CircuitEvent: e,
Path: path,
APIID: spec.APIID,
})
case circuit.BreakerReset:
spec.FireEvent(EVENT_BreakerTriggered,
EVENT_CurcuitBreakerMeta{
EventMetaDefault: EventMetaDefault{Message: "Breaker Reset"},
CircuitEvent: e,
Path: path,
APIID: spec.APIID,
})
}
}
}()
thisURLSpec = append(thisURLSpec, newSpec)
}
return thisURLSpec
}
func (a *APIDefinitionLoader) compileURLRewritesPathSpec(paths []tykcommon.URLRewriteMeta, stat URLStatus) []URLSpec {
// transform an extended configuration URL into an array of URLSpecs
// This way we can iterate the whole array once, on match we break with status
thisURLSpec := []URLSpec{}
for _, stringSpec := range paths {
newSpec := URLSpec{}
a.generateRegex(stringSpec.Path, &newSpec, stat)
// Extend with method actions
newSpec.URLRewrite = stringSpec
thisURLSpec = append(thisURLSpec, newSpec)
}
return thisURLSpec
}
func (a *APIDefinitionLoader) compileVirtualPathspathSpec(paths []tykcommon.VirtualMeta, stat URLStatus, apiSpec *APISpec) []URLSpec {
// transform an extended configuration URL into an array of URLSpecs
// This way we can iterate the whole array once, on match we break with status
thisURLSpec := []URLSpec{}
if !config.EnableJSVM {
return thisURLSpec
}
for _, stringSpec := range paths {
newSpec := URLSpec{}
a.generateRegex(stringSpec.Path, &newSpec, stat)
// Extend with method actions
newSpec.VirtualPathSpec = stringSpec
PreLoadVirtualMetaCode(&newSpec.VirtualPathSpec, apiSpec.JSVM)
thisURLSpec = append(thisURLSpec, newSpec)
}
return thisURLSpec
}
func (a *APIDefinitionLoader) getExtendedPathSpecs(apiVersionDef tykcommon.VersionInfo, apiSpec *APISpec) ([]URLSpec, bool) {
// TODO: New compiler here, needs to put data into a different structure
ignoredPaths := a.compileExtendedPathSpec(apiVersionDef.ExtendedPaths.Ignored, Ignored)
blackListPaths := a.compileExtendedPathSpec(apiVersionDef.ExtendedPaths.BlackList, BlackList)
whiteListPaths := a.compileExtendedPathSpec(apiVersionDef.ExtendedPaths.WhiteList, WhiteList)
cachedPaths := a.compileCachedPathSpec(apiVersionDef.ExtendedPaths.Cached)
transformPaths := a.compileTransformPathSpec(apiVersionDef.ExtendedPaths.Transform, Transformed)
transformResponsePaths := a.compileTransformPathSpec(apiVersionDef.ExtendedPaths.TransformResponse, TransformedResponse)
headerTransformPaths := a.compileInjectedHeaderSpec(apiVersionDef.ExtendedPaths.TransformHeader, HeaderInjected)
headerTransformPathsOnResponse := a.compileInjectedHeaderSpec(apiVersionDef.ExtendedPaths.TransformResponseHeader, HeaderInjectedResponse)
hardTimeouts := a.compileTimeoutPathSpec(apiVersionDef.ExtendedPaths.HardTimeouts, HardTimeout)
circuitBreakers := a.compileCircuitBreakerPathSpec(apiVersionDef.ExtendedPaths.CircuitBreaker, CircuitBreaker, apiSpec)
urlRewrites := a.compileURLRewritesPathSpec(apiVersionDef.ExtendedPaths.URLRewrite, URLRewrite)
virtualPaths := a.compileVirtualPathspathSpec(apiVersionDef.ExtendedPaths.Virtual, VirtualPath, apiSpec)
requestSizes := a.compileRequestSizePathSpec(apiVersionDef.ExtendedPaths.SizeLimit, RequestSizeLimit)
methodTransforms := a.compileMethodTransformSpec(apiVersionDef.ExtendedPaths.MethodTransforms, MethodTransformed)
combinedPath := []URLSpec{}
combinedPath = append(combinedPath, ignoredPaths...)
combinedPath = append(combinedPath, blackListPaths...)
combinedPath = append(combinedPath, whiteListPaths...)
combinedPath = append(combinedPath, cachedPaths...)
combinedPath = append(combinedPath, transformPaths...)
combinedPath = append(combinedPath, transformResponsePaths...)
combinedPath = append(combinedPath, headerTransformPaths...)
combinedPath = append(combinedPath, headerTransformPathsOnResponse...)
combinedPath = append(combinedPath, hardTimeouts...)
combinedPath = append(combinedPath, circuitBreakers...)
combinedPath = append(combinedPath, urlRewrites...)
combinedPath = append(combinedPath, requestSizes...)
combinedPath = append(combinedPath, virtualPaths...)
combinedPath = append(combinedPath, methodTransforms...)
if len(whiteListPaths) > 0 {
return combinedPath, true
}
return combinedPath, false
}
func (a *APISpec) Init(AuthStore StorageHandler, SessionStore StorageHandler, healthStorageHandler StorageHandler, orgStorageHandler StorageHandler) {
a.AuthManager.Init(AuthStore)
a.SessionManager.Init(SessionStore)