forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
1410 lines (1181 loc) · 38.9 KB
/
main.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 (
"crypto/tls"
"fmt"
"html/template"
"io/ioutil"
"log/syslog"
"net"
"net/http"
"os"
"path"
"path/filepath"
"runtime/pprof"
"strconv"
"strings"
"time"
"github.com/TykTechnologies/goagain"
"github.com/TykTechnologies/logrus"
"github.com/TykTechnologies/logrus-logstash-hook"
logrus_syslog "github.com/TykTechnologies/logrus/hooks/syslog"
"github.com/TykTechnologies/logrus_sentry"
"github.com/TykTechnologies/tykcommon"
logger "github.com/TykTechnologies/tykcommon-logger"
"github.com/docopt/docopt.go"
"github.com/facebookgo/pidfile"
"github.com/gorilla/mux"
"github.com/justinas/alice"
"github.com/lonelycode/logrus-graylog-hook"
osin "github.com/lonelycode/osin"
"github.com/rs/cors"
"rsc.io/letsencrypt"
)
var log = logger.GetLogger()
var config = Config{}
var templates = &template.Template{}
var analytics = RedisAnalyticsHandler{}
var profileFile = &os.File{}
var GlobalEventsJSVM = &JSVM{}
var doMemoryProfile bool
var doCpuProfile bool
var Policies = make(map[string]Policy)
var MainNotifier = RedisNotifier{}
var DefaultOrgStore = DefaultSessionManager{}
var DefaultQuotaStore = DefaultSessionManager{}
var FallbackKeySesionManager SessionHandler = &DefaultSessionManager{}
var MonitoringHandler TykEventHandler
var RPCListener = RPCStorageHandler{}
var argumentsBackup map[string]interface{}
var DashService DashboardServiceSender
var ApiSpecRegister *map[string]*APISpec //make(map[string]*APISpec)
var keyGen = DefaultKeyGenerator{}
var mainRouter *mux.Router
var defaultRouter *mux.Router
var LE_MANAGER letsencrypt.Manager
var LE_FIRSTRUN bool
var NodeID string
// Generic system error
const (
E_SYSTEM_ERROR string = "{\"status\": \"system error, please contact administrator\"}"
OAUTH_AUTH_CODE_TIMEOUT int = 60 * 60
OAUTH_PREFIX string = "oauth-data."
)
// Display configuration options
func displayConfig() {
address := config.ListenAddress
if config.ListenAddress == "" {
address = "(open interface)"
}
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("--> Listening on address: ", address)
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("--> Listening on port: ", config.ListenPort)
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("--> PID: ", HostDetails.PID)
}
func getHostName() string {
hName := config.HostName
if config.HostName == "" {
hName = ""
}
return hName
}
func pingTest(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello Tiki")
}
// Create all globals and init connection handlers
func setupGlobals() {
mainRouter = mux.NewRouter()
if getHostName() != "" {
defaultRouter = mainRouter.Host(getHostName()).Subrouter()
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("Hostname set: ", getHostName())
} else {
defaultRouter = mainRouter
}
if (config.EnableAnalytics == true) && (config.Storage.Type != "redis") {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Panic("Analytics requires Redis Storage backend, please enable Redis in the tyk.conf file.")
}
// Initialise our Host Checker
HealthCheckStore := &RedisClusterStorageManager{KeyPrefix: "host-checker:"}
InitHostCheckManager(HealthCheckStore)
if config.EnableAnalytics {
config.loadIgnoredIPs()
AnalyticsStore := RedisClusterStorageManager{KeyPrefix: "analytics-"}
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Setting up analytics DB connection")
analytics = RedisAnalyticsHandler{
Store: &AnalyticsStore,
}
analytics.Init()
if config.AnalyticsConfig.Type == "rpc" {
log.Debug("Using RPC cache purge")
thisPurger := RPCPurger{Store: &AnalyticsStore, Address: config.SlaveOptions.ConnectionString}
thisPurger.Connect()
analytics.Clean = &thisPurger
go analytics.Clean.StartPurgeLoop(10)
}
}
//genericOsinStorage = MakeNewOsinServer()
// Load all the files that have the "error" prefix.
templatesDir := filepath.Join(config.TemplatePath, "error*")
templates = template.Must(template.ParseGlob(templatesDir))
// Set up global JSVM
if config.EnableJSVM {
GlobalEventsJSVM.Init(config.TykJSPath)
}
if config.CoProcessOptions.EnableCoProcess {
CoProcessInit()
}
// Get the notifier ready
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Notifier will not work in hybrid mode")
MainNotifierStore := RedisClusterStorageManager{}
MainNotifierStore.Connect()
MainNotifier = RedisNotifier{&MainNotifierStore, RedisPubSubChannel}
if config.Monitor.EnableTriggerMonitors {
var monitorErr error
MonitoringHandler, monitorErr = WebHookHandler{}.New(config.Monitor.Config)
if monitorErr != nil {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Error("Failed to initialise monitor! ", monitorErr)
}
}
if config.AnalyticsConfig.NormaliseUrls.Enabled {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("Setting up analytics normaliser")
config.AnalyticsConfig.NormaliseUrls.compiledPatternSet = InitNormalisationPatterns()
}
}
func waitForZeroConf() {
if config.DBAppConfOptions.ConnectionString == "" {
time.Sleep(1 * time.Second)
waitForZeroConf()
}
}
func buildConnStr(resource string) string {
if config.DBAppConfOptions.ConnectionString == "" && config.DisableDashboardZeroConf {
log.Fatal("Connection string is empty, failing.")
return ""
}
if config.DisableDashboardZeroConf == false && config.DBAppConfOptions.ConnectionString == "" {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("Waiting for zeroconf signal...")
waitForZeroConf()
}
connStr := config.DBAppConfOptions.ConnectionString
connStr = connStr + resource
return connStr
}
// Pull API Specs from configuration
var APILoader APIDefinitionLoader = APIDefinitionLoader{}
func getAPISpecs() *[]*APISpec {
var APISpecs *[]*APISpec
if config.UseDBAppConfigs {
connStr := buildConnStr("/system/apis")
APISpecs = APILoader.LoadDefinitionsFromDashboardService(connStr, config.NodeSecret)
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Downloading API Configurations from Dashboard Service")
} else if config.SlaveOptions.UseRPC {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Using RPC Configuration")
APISpecs = APILoader.LoadDefinitionsFromRPC(config.SlaveOptions.RPCKey)
} else {
APISpecs = APILoader.LoadDefinitions(config.AppPath)
}
log.WithFields(logrus.Fields{
"prefix": "main",
}).Printf("Detected %v APIs", len(*APISpecs))
if config.AuthOverride.ForceAuthProvider {
for i, _ := range *APISpecs {
(*APISpecs)[i].AuthProvider = config.AuthOverride.AuthProvider
}
}
if config.AuthOverride.ForceSessionProvider {
for i, _ := range *APISpecs {
(*APISpecs)[i].SessionProvider = config.AuthOverride.SessionProvider
}
}
return APISpecs
}
func getPolicies() {
thesePolicies := make(map[string]Policy)
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("Loading policies")
if config.Policies.PolicySource == "service" {
if config.Policies.PolicyConnectionString != "" {
connStr := config.Policies.PolicyConnectionString
connStr = connStr + "/system/policies"
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("Using Policies from Dashboard Service")
thesePolicies = LoadPoliciesFromDashboard(connStr, config.NodeSecret, config.Policies.AllowExplicitPolicyID)
} else {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Fatal("No connection string or node ID present. Failing.")
}
} else if config.Policies.PolicySource == "rpc" {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Using Policies from RPC")
thesePolicies = LoadPoliciesFromRPC(config.SlaveOptions.RPCKey)
} else {
// this is the only case now where we need a policy record name
if config.Policies.PolicyRecordName == "" {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("No policy record name defined, skipping...")
return
}
thesePolicies = LoadPoliciesFromFile(config.Policies.PolicyRecordName)
}
if len(thesePolicies) > 0 {
Policies = thesePolicies
return
}
}
// Set up default Tyk control API endpoints - these are global, so need to be added first
func loadAPIEndpoints(Muxer *mux.Router) {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("Initialising Tyk REST API Endpoints")
var ApiMuxer *mux.Router
ApiMuxer = Muxer
if config.EnableAPISegregation {
if config.ControlAPIHostname != "" {
ApiMuxer = Muxer.Host(config.ControlAPIHostname).Subrouter()
}
}
// set up main API handlers
ApiMuxer.HandleFunc("/tyk/reload/group", CheckIsAPIOwner(groupResetHandler))
ApiMuxer.HandleFunc("/tyk/reload/", CheckIsAPIOwner(resetHandler))
if !IsRPCMode() {
ApiMuxer.HandleFunc("/tyk/org/keys/"+"{rest:.*}", CheckIsAPIOwner(orgHandler))
ApiMuxer.HandleFunc("/tyk/keys/policy/"+"{rest:.*}", CheckIsAPIOwner(policyUpdateHandler))
ApiMuxer.HandleFunc("/tyk/keys/create", CheckIsAPIOwner(createKeyHandler))
ApiMuxer.HandleFunc("/tyk/apis/"+"{rest:.*}", CheckIsAPIOwner(apiHandler))
ApiMuxer.HandleFunc("/tyk/health/", CheckIsAPIOwner(healthCheckhandler))
ApiMuxer.HandleFunc("/tyk/oauth/clients/create", CheckIsAPIOwner(createOauthClient))
ApiMuxer.HandleFunc("/tyk/oauth/refresh/"+"{rest:.*}", CheckIsAPIOwner(invalidateOauthRefresh))
ApiMuxer.HandleFunc("/tyk/cache/"+"{rest:.*}", CheckIsAPIOwner(invalidateCacheHandler))
} else {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("Node is slaved, REST API minimised")
}
ApiMuxer.HandleFunc("/tyk/keys/"+"{rest:.*}", CheckIsAPIOwner(keyHandler))
ApiMuxer.HandleFunc("/tyk/oauth/clients/"+"{rest:.*}", CheckIsAPIOwner(oAuthClientHandler))
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Loaded API Endpoints")
}
func generateOAuthPrefix(apiID string) string {
return OAUTH_PREFIX + apiID + "."
}
// Create API-specific OAuth handlers and respective auth servers
func addOAuthHandlers(spec *APISpec, Muxer *mux.Router, test bool) *OAuthManager {
apiAuthorizePath := spec.Proxy.ListenPath + "tyk/oauth/authorize-client/"
clientAuthPath := spec.Proxy.ListenPath + "oauth/authorize/"
clientAccessPath := spec.Proxy.ListenPath + "oauth/token/"
serverConfig := osin.NewServerConfig()
serverConfig.ErrorStatusCode = 403
serverConfig.AllowedAccessTypes = spec.Oauth2Meta.AllowedAccessTypes
serverConfig.AllowedAuthorizeTypes = spec.Oauth2Meta.AllowedAuthorizeTypes
serverConfig.RedirectUriSeparator = config.OauthRedirectUriSeparator
OAuthPrefix := generateOAuthPrefix(spec.APIID)
//storageManager := RedisClusterStorageManager{KeyPrefix: OAuthPrefix}
storageManager := GetGlobalStorageHandler(OAuthPrefix, false)
storageManager.Connect()
osinStorage := RedisOsinStorageInterface{storageManager, spec.SessionManager} //TODO: Needs storage manager from APISpec
if test {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Warning("Adding test clients")
testPolicy := Policy{}
testPolicy.Rate = 100
testPolicy.Per = 1
testPolicy.QuotaMax = -1
testPolicy.QuotaRenewalRate = 1000000000
Policies["TEST-4321"] = testPolicy
var redirectURI string
// If separator is not set that means multiple redirect uris not supported
if config.OauthRedirectUriSeparator == "" {
redirectURI = "http://client.oauth.com"
// If separator config is set that means multiple redirect uris are supported
} else {
redirectURI = strings.Join([]string{"http://client.oauth.com", "http://client2.oauth.com", "http://client3.oauth.com"}, config.OauthRedirectUriSeparator)
}
testClient := OAuthClient{
ClientID: "1234",
ClientSecret: "aabbccdd",
ClientRedirectURI: redirectURI,
PolicyID: "TEST-4321",
}
osinStorage.SetClient(testClient.ClientID, &testClient, false)
log.WithFields(logrus.Fields{
"prefix": "main",
}).Warning("Test client added")
}
osinServer := TykOsinNewServer(serverConfig, osinStorage)
// osinServer.AccessTokenGen = &AccessTokenGenTyk{}
oauthManager := OAuthManager{spec, osinServer}
oauthHandlers := OAuthHandlers{oauthManager}
Muxer.HandleFunc(apiAuthorizePath, CheckIsAPIOwner(oauthHandlers.HandleGenerateAuthCodeData))
Muxer.HandleFunc(clientAuthPath, oauthHandlers.HandleAuthorizePassthrough)
Muxer.HandleFunc(clientAccessPath, oauthHandlers.HandleAccessRequest)
return &oauthManager
}
func addBatchEndpoint(spec *APISpec, Muxer *mux.Router) {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Batch requests enabled for API")
apiBatchPath := spec.Proxy.ListenPath + "tyk/batch/"
thisBatchHandler := BatchRequestHandler{API: spec}
Muxer.HandleFunc(apiBatchPath, thisBatchHandler.HandleBatchRequest)
}
func loadCustomMiddleware(referenceSpec *APISpec) ([]string, tykcommon.MiddlewareDefinition, []tykcommon.MiddlewareDefinition, []tykcommon.MiddlewareDefinition, []tykcommon.MiddlewareDefinition, tykcommon.MiddlewareDriver) {
mwPaths := []string{}
var mwAuthCheckFunc tykcommon.MiddlewareDefinition
mwPreFuncs := []tykcommon.MiddlewareDefinition{}
mwPostFuncs := []tykcommon.MiddlewareDefinition{}
mwPostKeyAuthFuncs := []tykcommon.MiddlewareDefinition{}
mwDriver := tykcommon.OttoDriver
// Set AuthCheck hook
if referenceSpec.APIDefinition.CustomMiddleware.AuthCheck.Name != "" {
mwAuthCheckFunc = referenceSpec.APIDefinition.CustomMiddleware.AuthCheck
if referenceSpec.APIDefinition.CustomMiddleware.AuthCheck.Path != "" {
// Feed a JS file to Otto
mwPaths = append(mwPaths, referenceSpec.APIDefinition.CustomMiddleware.AuthCheck.Path)
}
}
// Load from the configuration
for _, mwObj := range referenceSpec.APIDefinition.CustomMiddleware.Pre {
mwPaths = append(mwPaths, mwObj.Path)
mwPreFuncs = append(mwPreFuncs, mwObj)
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Loading custom PRE-PROCESSOR middleware: ", mwObj.Name)
}
for _, mwObj := range referenceSpec.APIDefinition.CustomMiddleware.Post {
mwPaths = append(mwPaths, mwObj.Path)
mwPostFuncs = append(mwPostFuncs, mwObj)
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Loading custom POST-PROCESSOR middleware: ", mwObj.Name)
}
// Load from folder
// Get PRE folder path
middlwareFolderPath := path.Join(config.MiddlewarePath, referenceSpec.APIDefinition.APIID, "pre")
files, _ := ioutil.ReadDir(middlwareFolderPath)
for _, f := range files {
if strings.Contains(f.Name(), ".js") {
filePath := filepath.Join(middlwareFolderPath, f.Name())
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Loading PRE-PROCESSOR file middleware from ", filePath)
middlewareObjectName := strings.Split(f.Name(), ".")[0]
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("-- Middleware name ", middlewareObjectName)
requiresSession := strings.Contains(middlewareObjectName, "_with_session")
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("-- Middleware requires session: ", requiresSession)
thisMWDef := tykcommon.MiddlewareDefinition{}
thisMWDef.Name = middlewareObjectName
thisMWDef.Path = filePath
thisMWDef.RequireSession = requiresSession
mwPaths = append(mwPaths, filePath)
mwPreFuncs = append(mwPreFuncs, thisMWDef)
}
}
// Get Auth folder path
middlewareAuthFolderPath := path.Join(config.MiddlewarePath, referenceSpec.APIDefinition.APIID, "auth")
mwAuthFiles, _ := ioutil.ReadDir(middlewareAuthFolderPath)
for _, f := range mwAuthFiles {
if strings.Contains(f.Name(), ".js") {
filePath := filepath.Join(middlewareAuthFolderPath, f.Name())
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Loading Auth file middleware from ", filePath)
middlewareObjectName := strings.Split(f.Name(), ".")[0]
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("-- Middleware name ", middlewareObjectName)
thisMWDef := tykcommon.MiddlewareDefinition{}
thisMWDef.Name = middlewareObjectName
thisMWDef.Path = filePath
thisMWDef.RequireSession = false
mwPaths = append(mwPaths, filePath)
mwAuthCheckFunc = thisMWDef
// only one allowed!
break
}
}
// Get POSTKeyAuth folder path
middlewarePostKeyAuthFolderPath := path.Join(config.MiddlewarePath, referenceSpec.APIDefinition.APIID, "post_auth")
mwPostKeyAuthFiles, _ := ioutil.ReadDir(middlewarePostKeyAuthFolderPath)
for _, f := range mwPostKeyAuthFiles {
if strings.Contains(f.Name(), ".js") {
filePath := filepath.Join(middlewarePostKeyAuthFolderPath, f.Name())
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Loading POST-KEY-AUTH-PROCESSOR file middleware from ", filePath)
middlewareObjectName := strings.Split(f.Name(), ".")[0]
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("-- Middleware name ", middlewareObjectName)
requiresSession := strings.Contains(middlewareObjectName, "_with_session")
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("-- Middleware requires session: ", requiresSession)
thisMWDef := tykcommon.MiddlewareDefinition{}
thisMWDef.Name = middlewareObjectName
thisMWDef.Path = filePath
thisMWDef.RequireSession = requiresSession
mwPaths = append(mwPaths, filePath)
mwPostKeyAuthFuncs = append(mwPostFuncs, thisMWDef)
}
}
// Get POST folder path
middlewarePostFolderPath := path.Join(config.MiddlewarePath, referenceSpec.APIDefinition.APIID, "post")
mwPostFiles, _ := ioutil.ReadDir(middlewarePostFolderPath)
for _, f := range mwPostFiles {
if strings.Contains(f.Name(), ".js") {
filePath := filepath.Join(middlewarePostFolderPath, f.Name())
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Loading POST-PROCESSOR file middleware from ", filePath)
middlewareObjectName := strings.Split(f.Name(), ".")[0]
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("-- Middleware name ", middlewareObjectName)
requiresSession := strings.Contains(middlewareObjectName, "_with_session")
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("-- Middleware requires session: ", requiresSession)
thisMWDef := tykcommon.MiddlewareDefinition{}
thisMWDef.Name = middlewareObjectName
thisMWDef.Path = filePath
thisMWDef.RequireSession = requiresSession
mwPaths = append(mwPaths, filePath)
mwPostFuncs = append(mwPostFuncs, thisMWDef)
}
}
// Set middleware driver, defaults to OttoDriver
if referenceSpec.APIDefinition.CustomMiddleware.Driver != "" {
mwDriver = referenceSpec.APIDefinition.CustomMiddleware.Driver
}
// Load PostAuthCheck hooks
for _, mwObj := range referenceSpec.APIDefinition.CustomMiddleware.PostKeyAuth {
if mwObj.Path != "" {
// Otto files are specified here
mwPaths = append(mwPaths, mwObj.Path)
}
mwPostKeyAuthFuncs = append(mwPostKeyAuthFuncs, mwObj)
}
return mwPaths, mwAuthCheckFunc, mwPreFuncs, mwPostFuncs, mwPostKeyAuthFuncs, mwDriver
}
func creeateResponseMiddlewareChain(referenceSpec *APISpec) {
// Create the response processors
responseChain := make([]TykResponseHandler, len(referenceSpec.APIDefinition.ResponseProcessors))
for i, processorDetail := range referenceSpec.APIDefinition.ResponseProcessors {
processorType, err := GetResponseProcessorByName(processorDetail.Name)
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Error("Failed to load processor! ", err)
return
}
thisProcessor, _ := processorType.New(processorDetail.Options, referenceSpec)
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Loading Response processor: ", processorDetail.Name)
responseChain[i] = thisProcessor
}
referenceSpec.ResponseChain = &responseChain
if len(responseChain) > 0 {
referenceSpec.ResponseHandlersActive = true
}
}
func handleCORS(chain *[]alice.Constructor, spec *APISpec) {
if spec.CORS.Enable {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("CORS ENABLED")
c := cors.New(cors.Options{
AllowedOrigins: spec.CORS.AllowedOrigins,
AllowedMethods: spec.CORS.AllowedMethods,
AllowedHeaders: spec.CORS.AllowedHeaders,
ExposedHeaders: spec.CORS.ExposedHeaders,
AllowCredentials: spec.CORS.AllowCredentials,
MaxAge: spec.CORS.MaxAge,
OptionsPassthrough: spec.CORS.OptionsPassthrough,
Debug: spec.CORS.Debug,
})
*chain = append(*chain, c.Handler)
}
}
func IsRPCMode() bool {
if config.AuthOverride.ForceAuthProvider {
if config.AuthOverride.AuthProvider.StorageEngine == RPCStorageEngine {
return true
}
}
return false
}
func doCopy(from *APISpec, to *APISpec) {
*to = *from
}
type SortableAPISpecListByListen []*APISpec
func (s SortableAPISpecListByListen) Len() int {
return len(s)
}
func (s SortableAPISpecListByListen) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s SortableAPISpecListByListen) Less(i, j int) bool {
return len(s[i].Proxy.ListenPath) > len(s[j].Proxy.ListenPath)
}
type SortableAPISpecListByHost []*APISpec
func (s SortableAPISpecListByHost) Len() int {
return len(s)
}
func (s SortableAPISpecListByHost) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s SortableAPISpecListByHost) Less(i, j int) bool {
return len(s[i].Domain) > len(s[j].Domain)
}
func notifyAPILoaded(spec *APISpec) {
if config.UseRedisLog {
log.WithFields(logrus.Fields{
"prefix": "gateway",
"user_ip": "--",
"server_name": "--",
"user_id": "--",
"org_id": spec.APIDefinition.OrgID,
"api_id": spec.APIDefinition.APIID,
}).Info("Loaded: ", spec.APIDefinition.Name)
}
}
func RPCReloadLoop(RPCKey string) {
for {
RPCListener.CheckForReload(config.SlaveOptions.RPCKey)
}
}
func doReload() {
time.Sleep(10 * time.Second)
// Load the API Policies
getPolicies()
// load the specs
specs := getAPISpecs()
if len(*specs) == 0 {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Warning("No API Definitions found, not reloading")
reloadScheduled = false
return
}
// We have updated specs, lets load those...
// Kill RPC if available
if config.SlaveOptions.UseRPC {
ClearRPCClients()
}
// Reset the JSVM
if config.EnableJSVM {
GlobalEventsJSVM.Init(config.TykJSPath)
}
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("Preparing new router")
newRouter := mux.NewRouter()
mainRouter = newRouter
var newMuxes *mux.Router
if getHostName() != "" {
newMuxes = newRouter.Host(getHostName()).Subrouter()
} else {
newMuxes = newRouter
}
loadAPIEndpoints(newMuxes)
loadApps(specs, newMuxes)
newServeMux := http.NewServeMux()
newServeMux.Handle("/", mainRouter)
http.DefaultServeMux = newServeMux
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("API reload complete")
// Unset these
RPC_EmergencyModeLoaded = false
RPC_EmergencyMode = false
reloadScheduled = false
}
var reloadScheduled bool
func checkReloadTimeout() {
if reloadScheduled {
wait := config.ReloadWaitTime
if config.ReloadWaitTime == 0 {
wait = 10
}
time.Sleep(time.Duration(wait) * time.Second)
if reloadScheduled {
log.Warning("Reloader timed out! Removing sentinel")
reloadScheduled = false
}
}
}
// ReloadURLStructure will create a new muxer, reload all the app configs for an
// instance and then replace the DefaultServeMux with the new one, this enables a
// reconfiguration to take place without stopping any requests from being handled.
func ReloadURLStructure() {
if !reloadScheduled {
reloadScheduled = true
log.Info("Initiating reload")
go doReload()
log.Info("Initiating coprocess reload")
go doCoprocessReload()
log.Info("Starting reload monitor...")
go checkReloadTimeout()
}
}
func setupLogger() {
if config.UseSentry {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Enabling Sentry support")
hook, err := logrus_sentry.NewSentryHook(config.SentryCode, []logrus.Level{
logrus.PanicLevel,
logrus.FatalLevel,
logrus.ErrorLevel,
})
hook.Timeout = 0
if err == nil {
log.Hooks.Add(hook)
}
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Sentry hook active")
}
if config.UseSyslog {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Enabling Syslog support")
hook, err := logrus_syslog.NewSyslogHook(config.SyslogTransport,
config.SyslogNetworkAddr,
syslog.LOG_INFO, "")
if err == nil {
log.Hooks.Add(hook)
}
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Syslog hook active")
}
if config.UseGraylog {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Enabling Graylog support")
hook := graylog.NewGraylogHook(config.GraylogNetworkAddr,
map[string]interface{}{"tyk-module": "gateway"})
log.Hooks.Add(hook)
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Graylog hook active")
}
if config.UseLogstash {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Enabling Logstash support")
hook, err := logrus_logstash.NewHook(config.LogstashTransport,
config.LogstashNetworkAddr,
"tyk-gateway")
if err == nil {
log.Hooks.Add(hook)
}
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Logstash hook active")
}
if config.UseRedisLog {
redisHook := NewRedisHook()
log.Hooks.Add(redisHook)
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Redis log hook active")
}
}
func initialiseSystem(arguments map[string]interface{}) {
// Enable command mode
for k, _ := range CommandModeOptions {
v := arguments[k]
if v == true {
HandleCommandModeArgs(arguments)
os.Exit(0)
}
if v != nil && v != false {
HandleCommandModeArgs(arguments)
os.Exit(0)
}
}
filename := "/etc/tyk/tyk.conf"
value, _ := arguments["--conf"]
if value != nil {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug(fmt.Sprintf("Using %s for configuration", value.(string)))
filename = arguments["--conf"].(string)
} else {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("No configuration file defined, will try to use default (./tyk.conf)")
}
loadConfig(filename, &config)
if config.Storage.Type != "redis" {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Fatal("Redis connection details not set, please ensure that the storage type is set to Redis and that the connection parameters are correct.")
}
setupGlobals()
port, _ := arguments["--port"]
if port != nil {
portNum, err := strconv.Atoi(port.(string))
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Error("Port specified in flags must be a number!")
log.WithFields(logrus.Fields{
"prefix": "main",
}).Error(err)
} else {
config.ListenPort = portNum
}
}
doMemoryProfile, _ = arguments["--memprofile"].(bool)
doCpuProfile, _ = arguments["--cpuprofile"].(bool)
doDebug, _ := arguments["--debug"]
log.Level = logrus.InfoLevel
if doDebug == true {
log.Level = logrus.DebugLevel
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Enabling debug-level output")
}
// Enable all the loggers
setupLogger()
if config.PIDFileLocation == "" {
config.PIDFileLocation = "/var/run/tyk-gateway.pid"
}
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("PIDFile location set to: ", config.PIDFileLocation)
pidfile.SetPidfilePath(config.PIDFileLocation)
pfErr := pidfile.Write()
if pfErr != nil {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Error("Failed to write PIDFile: ", pfErr)
}
GetHostDetails()
go StartPeriodicStateBackup(&LE_MANAGER)
}
func getCmdArguments() map[string]interface{} {
usage := `Tyk API Gateway.
Usage:
tyk [options]
Options:
-h --help Show this screen
--conf=FILE Load a named configuration file
--port=PORT Listen on PORT (overrides confg file)
--memprofile Generate a memory profile
--cpuprofile Generate a cpu profile
--debug Enable Debug output
--import-blueprint=<file> Import an API Blueprint file
--import-swagger=<file> Import a Swagger file
--create-api Creates a new API Definition from the blueprint
--org-id=><id> Assign the API Defintition to this org_id (required with create)
--upstream-target=<url> Set the upstream target for the definition
--as-mock Creates the API as a mock based on example fields
--for-api=<path> Adds blueprint to existing API Defintition as version
--as-version=<version> The version number to use when inserting
`
arguments, err := docopt.Parse(usage, nil, true, VERSION, false, false)
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Warning("Error while parsing arguments: ", err)
}
argumentsBackup = arguments
return arguments
}
var KeepaliveRunning bool
func StartRPCKeepaliveWatcher(engine *RPCStorageHandler) {
if KeepaliveRunning {
return
}
go func() {
log.WithFields(logrus.Fields{
"prefix": "RPC Conn Mgr",
}).Info("[RPC Conn Mgr] Starting keepalive watcher...")
for {
KeepaliveRunning = true
RPCKeepAliveCheck(engine)
if engine == nil {