forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
1463 lines (1250 loc) · 41.4 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"
stdlog "log"
"log/syslog"
"net"
"net/http"
pprof_http "net/http/pprof"
"os"
"path/filepath"
"runtime/pprof"
"strconv"
"strings"
"sync"
"time"
"github.com/Sirupsen/logrus"
logrus_syslog "github.com/Sirupsen/logrus/hooks/syslog"
"github.com/bshuster-repo/logrus-logstash-hook"
"github.com/evalphobia/logrus_sentry"
"github.com/facebookgo/pidfile"
"github.com/gemnasium/logrus-graylog-hook"
"github.com/gorilla/mux"
"github.com/justinas/alice"
"github.com/lonelycode/gorpc"
"github.com/lonelycode/osin"
"github.com/rs/cors"
uuid "github.com/satori/go.uuid"
"gopkg.in/alecthomas/kingpin.v2"
"rsc.io/letsencrypt"
"github.com/TykTechnologies/goagain"
"github.com/TykTechnologies/tyk/apidef"
"github.com/TykTechnologies/tyk/certs"
"github.com/TykTechnologies/tyk/config"
"github.com/TykTechnologies/tyk/lint"
logger "github.com/TykTechnologies/tyk/log"
"github.com/TykTechnologies/tyk/storage"
"github.com/TykTechnologies/tyk/user"
)
var (
log = logger.Get()
rawLog = logger.GetRaw()
templates *template.Template
analytics RedisAnalyticsHandler
GlobalEventsJSVM JSVM
memProfFile *os.File
MainNotifier RedisNotifier
DefaultOrgStore DefaultSessionManager
DefaultQuotaStore DefaultSessionManager
FallbackKeySesionManager = SessionHandler(&DefaultSessionManager{})
MonitoringHandler config.TykEventHandler
RPCListener RPCStorageHandler
DashService DashboardServiceSender
CertificateManager *certs.CertificateManager
apisMu sync.RWMutex
apiSpecs []*APISpec
apisByID = map[string]*APISpec{}
keyGen DefaultKeyGenerator
policiesMu sync.RWMutex
policiesByID = map[string]user.Policy{}
mainRouter *mux.Router
controlRouter *mux.Router
LE_MANAGER letsencrypt.Manager
LE_FIRSTRUN bool
NodeID string
runningTests = false
version = kingpin.Version(VERSION)
help = kingpin.CommandLine.HelpFlag.Short('h')
conf = kingpin.Flag("conf", "load a named configuration file").PlaceHolder("FILE").String()
port = kingpin.Flag("port", "listen on PORT (overrides config file)").String()
memProfile = kingpin.Flag("memprofile", "generate a memory profile").Bool()
cpuProfile = kingpin.Flag("cpuprofile", "generate a cpu profile").Bool()
httpProfile = kingpin.Flag("httpprofile", "expose runtime profiling data via HTTP").Bool()
debugMode = kingpin.Flag("debug", "enable debug mode").Bool()
importBlueprint = kingpin.Flag("import-blueprint", "import an API Blueprint file").PlaceHolder("FILE").String()
importSwagger = kingpin.Flag("import-swagger", "import a Swagger file").PlaceHolder("FILE").String()
createAPI = kingpin.Flag("create-api", "creates a new API definition from the blueprint").Bool()
orgID = kingpin.Flag("org-id", "assign the API Definition to this org_id (required with create-api").String()
upstreamTarget = kingpin.Flag("upstream-target", "set the upstream target for the definition").PlaceHolder("URL").String()
asMock = kingpin.Flag("as-mock", "creates the API as a mock based on example fields").Bool()
forAPI = kingpin.Flag("for-api", "adds blueprint to existing API Definition as version").PlaceHolder("PATH").String()
asVersion = kingpin.Flag("as-version", "the version number to use when inserting").PlaceHolder("VERSION").String()
logInstrumentation = kingpin.Flag("log-intrumentation", "output intrumentation output to stdout").Bool()
subcmd = kingpin.Arg("subcmd", "run a Tyk subcommand i.e. lint").String()
// confPaths is the series of paths to try to use as config files. The
// first one to exist will be used. If none exists, a default config
// will be written to the first path in the list.
//
// When --conf=foo is used, this will be replaced by []string{"foo"}.
confPaths = []string{
"tyk.conf",
// TODO: add ~/.config/tyk/tyk.conf here?
"/etc/tyk/tyk.conf",
}
)
func getApiSpec(apiID string) *APISpec {
apisMu.RLock()
spec := apisByID[apiID]
apisMu.RUnlock()
return spec
}
func apisByIDLen() int {
apisMu.RLock()
defer apisMu.RUnlock()
return len(apisByID)
}
// Create all globals and init connection handlers
func setupGlobals() {
mainRouter = mux.NewRouter()
controlRouter = mux.NewRouter()
if config.Global.EnableAnalytics && config.Global.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 := storage.RedisCluster{KeyPrefix: "host-checker:"}
InitHostCheckManager(healthCheckStore)
if config.Global.EnableAnalytics && analytics.Store == nil {
config.Global.LoadIgnoredIPs()
analyticsStore := storage.RedisCluster{KeyPrefix: "analytics-"}
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Setting up analytics DB connection")
analytics.Store = &analyticsStore
analytics.Init()
if config.Global.AnalyticsConfig.Type == "rpc" {
log.Debug("Using RPC cache purge")
purger := RPCPurger{Store: &analyticsStore}
purger.Connect()
analytics.Clean = &purger
go analytics.Clean.PurgeLoop(10 * time.Second)
}
}
// Load all the files that have the "error" prefix.
templatesDir := filepath.Join(config.Global.TemplatePath, "error*")
templates = template.Must(template.ParseGlob(templatesDir))
// Set up global JSVM
if config.Global.EnableJSVM {
GlobalEventsJSVM.Init(nil)
}
if config.Global.CoProcessOptions.EnableCoProcess {
CoProcessInit()
}
// Get the notifier ready
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Notifier will not work in hybrid mode")
mainNotifierStore := storage.RedisCluster{}
mainNotifierStore.Connect()
MainNotifier = RedisNotifier{mainNotifierStore, RedisPubSubChannel}
if config.Global.Monitor.EnableTriggerMonitors {
h := &WebHookHandler{}
if err := h.Init(config.Global.Monitor.Config); err != nil {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Error("Failed to initialise monitor! ", err)
} else {
MonitoringHandler = h
}
}
if config.Global.AnalyticsConfig.NormaliseUrls.Enabled {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("Setting up analytics normaliser")
config.Global.AnalyticsConfig.NormaliseUrls.CompiledPatternSet = initNormalisationPatterns()
}
certificateSecret := config.Global.Secret
if config.Global.Security.PrivateCertificateEncodingSecret != "" {
certificateSecret = config.Global.Security.PrivateCertificateEncodingSecret
}
CertificateManager = certs.NewCertificateManager(getGlobalStorageHandler("cert-", false), certificateSecret, log)
}
func buildConnStr(resource string) string {
if config.Global.DBAppConfOptions.ConnectionString == "" && config.Global.DisableDashboardZeroConf {
log.Fatal("Connection string is empty, failing.")
}
if !config.Global.DisableDashboardZeroConf && config.Global.DBAppConfOptions.ConnectionString == "" {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("Waiting for zeroconf signal...")
for config.Global.DBAppConfOptions.ConnectionString == "" {
time.Sleep(1 * time.Second)
}
}
return config.Global.DBAppConfOptions.ConnectionString + resource
}
func syncAPISpecs() int {
loader := APIDefinitionLoader{}
apisMu.Lock()
defer apisMu.Unlock()
if config.Global.UseDBAppConfigs {
connStr := buildConnStr("/system/apis")
apiSpecs = loader.FromDashboardService(connStr, config.Global.NodeSecret)
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Downloading API Configurations from Dashboard Service")
} else if config.Global.SlaveOptions.UseRPC {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Using RPC Configuration")
apiSpecs = loader.FromRPC(config.Global.SlaveOptions.RPCKey)
} else {
apiSpecs = loader.FromDir(config.Global.AppPath)
}
log.WithFields(logrus.Fields{
"prefix": "main",
}).Printf("Detected %v APIs", len(apiSpecs))
if config.Global.AuthOverride.ForceAuthProvider {
for i := range apiSpecs {
apiSpecs[i].AuthProvider = config.Global.AuthOverride.AuthProvider
}
}
if config.Global.AuthOverride.ForceSessionProvider {
for i := range apiSpecs {
apiSpecs[i].SessionProvider = config.Global.AuthOverride.SessionProvider
}
}
return len(apiSpecs)
}
func syncPolicies() {
var pols map[string]user.Policy
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("Loading policies")
switch config.Global.Policies.PolicySource {
case "service":
if config.Global.Policies.PolicyConnectionString == "" {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Fatal("No connection string or node ID present. Failing.")
}
connStr := config.Global.Policies.PolicyConnectionString
connStr = connStr + "/system/policies"
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("Using Policies from Dashboard Service")
pols = LoadPoliciesFromDashboard(connStr, config.Global.NodeSecret, config.Global.Policies.AllowExplicitPolicyID)
case "rpc":
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Using Policies from RPC")
pols = LoadPoliciesFromRPC(config.Global.SlaveOptions.RPCKey)
default:
// this is the only case now where we need a policy record name
if config.Global.Policies.PolicyRecordName == "" {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("No policy record name defined, skipping...")
return
}
pols = LoadPoliciesFromFile(config.Global.Policies.PolicyRecordName)
}
log.WithFields(logrus.Fields{
"prefix": "main",
}).Infof("Policies found (%d total):", len(pols))
for id := range pols {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Infof(" - %s", id)
}
if len(pols) > 0 {
policiesMu.Lock()
policiesByID = pols
policiesMu.Unlock()
}
}
// stripSlashes removes any trailing slashes from the request's URL
// path.
func stripSlashes(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
if trim := strings.TrimRight(path, "/"); trim != path {
r2 := *r
r2.URL.Path = trim
r = &r2
}
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
func controlAPICheckClientCertificate(certLevel string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if config.Global.Security.ControlAPIUseMutualTLS {
if err := CertificateManager.ValidateRequestCertificate(config.Global.Security.Certificates.ControlAPI, r); err != nil {
doJSONWrite(w, 403, apiError(err.Error()))
return
}
}
next.ServeHTTP(w, r)
})
}
// Set up default Tyk control API endpoints - these are global, so need to be added first
func loadAPIEndpoints(muxer *mux.Router) {
hostname := config.Global.HostName
if config.Global.ControlAPIHostname != "" {
hostname = config.Global.ControlAPIHostname
}
r := mux.NewRouter()
muxer.PathPrefix("/tyk/").Handler(http.StripPrefix("/tyk",
stripSlashes(checkIsAPIOwner(controlAPICheckClientCertificate("/gateway/client", InstrumentationMW(r)))),
))
if hostname != "" {
muxer = muxer.Host(hostname).Subrouter()
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("Control API hostname set: ", hostname)
}
if *httpProfile {
muxer.HandleFunc("/debug/pprof/{_:.*}", pprof_http.Index)
}
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("Initialising Tyk REST API Endpoints")
// set up main API handlers
r.HandleFunc("/reload/group", allowMethods(groupResetHandler, "GET"))
r.HandleFunc("/reload", allowMethods(resetHandler(nil), "GET"))
if !isRPCMode() {
r.HandleFunc("/org/keys", allowMethods(orgHandler, "POST", "PUT", "GET", "DELETE"))
r.HandleFunc("/org/keys/{keyName:[^/]*}", allowMethods(orgHandler, "POST", "PUT", "GET", "DELETE"))
r.HandleFunc("/keys/policy/{keyName}", allowMethods(policyUpdateHandler, "POST"))
r.HandleFunc("/keys/create", allowMethods(createKeyHandler, "POST"))
r.HandleFunc("/apis", allowMethods(apiHandler, "GET", "POST", "PUT", "DELETE"))
r.HandleFunc("/apis/{apiID}", allowMethods(apiHandler, "GET", "POST", "PUT", "DELETE"))
r.HandleFunc("/health", allowMethods(healthCheckhandler, "GET"))
r.HandleFunc("/oauth/clients/create", allowMethods(createOauthClient, "POST"))
r.HandleFunc("/oauth/refresh/{keyName}", allowMethods(invalidateOauthRefresh, "DELETE"))
r.HandleFunc("/cache/{apiID}", allowMethods(invalidateCacheHandler, "DELETE"))
} else {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("Node is slaved, REST API minimised")
}
r.HandleFunc("/keys", allowMethods(keyHandler, "POST", "PUT", "GET", "DELETE"))
r.HandleFunc("/keys/{keyName:[^/]*}", allowMethods(keyHandler, "POST", "PUT", "GET", "DELETE"))
r.HandleFunc("/certs", allowMethods(certHandler, "POST", "GET"))
r.HandleFunc("/certs/{certID:[^/]*}", allowMethods(certHandler, "POST", "GET", "DELETE"))
r.HandleFunc("/oauth/clients/{apiID}", allowMethods(oAuthClientHandler, "GET", "DELETE"))
r.HandleFunc("/oauth/clients/{apiID}/{keyName:[^/]*}", allowMethods(oAuthClientHandler, "GET", "DELETE"))
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Loaded API Endpoints")
}
// checkIsAPIOwner will ensure that the accessor of the tyk API has the
// correct security credentials - this is a shared secret between the
// client and the owner and is set in the tyk.conf file. This should
// never be made public!
func checkIsAPIOwner(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tykAuthKey := r.Header.Get("X-Tyk-Authorization")
if tykAuthKey != config.Global.Secret {
// Error
log.Warning("Attempted administrative access with invalid or missing key!")
doJSONWrite(w, 403, apiError("Forbidden"))
return
}
next.ServeHTTP(w, r)
})
}
func generateOAuthPrefix(apiID string) string {
return "oauth-data." + apiID + "."
}
// Create API-specific OAuth handlers and respective auth servers
func addOAuthHandlers(spec *APISpec, muxer *mux.Router) *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.Global.OauthRedirectUriSeparator
prefix := generateOAuthPrefix(spec.APIID)
storageManager := getGlobalStorageHandler(prefix, false)
storageManager.Connect()
osinStorage := &RedisOsinStorageInterface{storageManager, spec.SessionManager} //TODO: Needs storage manager from APISpec
osinServer := TykOsinNewServer(serverConfig, osinStorage)
oauthManager := OAuthManager{spec, osinServer}
oauthHandlers := OAuthHandlers{oauthManager}
muxer.Handle(apiAuthorizePath, checkIsAPIOwner(allowMethods(oauthHandlers.HandleGenerateAuthCodeData, "POST")))
muxer.HandleFunc(clientAuthPath, allowMethods(oauthHandlers.HandleAuthorizePassthrough, "GET", "POST"))
muxer.HandleFunc(clientAccessPath, allowMethods(oauthHandlers.HandleAccessRequest, "GET", "POST"))
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/"
batchHandler := BatchRequestHandler{API: spec}
muxer.HandleFunc(apiBatchPath, batchHandler.HandleBatchRequest)
}
func loadCustomMiddleware(spec *APISpec) ([]string, apidef.MiddlewareDefinition, []apidef.MiddlewareDefinition, []apidef.MiddlewareDefinition, []apidef.MiddlewareDefinition, apidef.MiddlewareDriver) {
mwPaths := []string{}
var mwAuthCheckFunc apidef.MiddlewareDefinition
mwPreFuncs := []apidef.MiddlewareDefinition{}
mwPostFuncs := []apidef.MiddlewareDefinition{}
mwPostKeyAuthFuncs := []apidef.MiddlewareDefinition{}
mwDriver := apidef.OttoDriver
// Set AuthCheck hook
if spec.CustomMiddleware.AuthCheck.Name != "" {
mwAuthCheckFunc = spec.CustomMiddleware.AuthCheck
if spec.CustomMiddleware.AuthCheck.Path != "" {
// Feed a JS file to Otto
mwPaths = append(mwPaths, spec.CustomMiddleware.AuthCheck.Path)
}
}
// Load from the configuration
for _, mwObj := range spec.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 spec.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 folders
for _, folder := range [...]struct {
name string
single *apidef.MiddlewareDefinition
slice *[]apidef.MiddlewareDefinition
}{
{name: "pre", slice: &mwPreFuncs},
{name: "auth", single: &mwAuthCheckFunc},
{name: "post_auth", slice: &mwPostKeyAuthFuncs},
{name: "post", slice: &mwPostFuncs},
} {
globPath := filepath.Join(config.Global.MiddlewarePath, spec.APIID, folder.name, "*.js")
paths, _ := filepath.Glob(globPath)
for _, path := range paths {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Loading file middleware from ", path)
mwDef := apidef.MiddlewareDefinition{
Name: strings.Split(filepath.Base(path), ".")[0],
Path: path,
}
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("-- Middleware name ", mwDef.Name)
mwDef.RequireSession = strings.HasSuffix(mwDef.Name, "_with_session")
if mwDef.RequireSession {
switch folder.name {
case "post_auth", "post":
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("-- Middleware requires session")
default:
log.WithFields(logrus.Fields{
"prefix": "main",
}).Warning("Middleware requires session, but isn't post-auth: ", mwDef.Name)
}
}
mwPaths = append(mwPaths, path)
if folder.single != nil {
*folder.single = mwDef
} else {
*folder.slice = append(*folder.slice, mwDef)
}
}
}
// Set middleware driver, defaults to OttoDriver
if spec.CustomMiddleware.Driver != "" {
mwDriver = spec.CustomMiddleware.Driver
}
// Load PostAuthCheck hooks
for _, mwObj := range spec.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(spec *APISpec) {
// Create the response processors
responseChain := make([]TykResponseHandler, len(spec.ResponseProcessors))
for i, processorDetail := range spec.ResponseProcessors {
processor := responseProcessorByName(processorDetail.Name)
if processor == nil {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Error("No such processor: ", processorDetail.Name)
return
}
if err := processor.Init(processorDetail.Options, spec); err != nil {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Failed to init processor: ", err)
}
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Loading Response processor: ", processorDetail.Name)
responseChain[i] = processor
}
spec.ResponseChain = responseChain
}
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 {
return config.Global.AuthOverride.ForceAuthProvider &&
config.Global.AuthOverride.AuthProvider.StorageEngine == RPCStorageEngine
}
func rpcReloadLoop(rpcKey string) {
for {
RPCListener.CheckForReload(rpcKey)
}
}
var reloadMu sync.Mutex
func doReload() {
reloadMu.Lock()
defer reloadMu.Unlock()
// Load the API Policies
syncPolicies()
// load the specs
count := syncAPISpecs()
// skip re-loading only if dashboard service reported 0 APIs
// and current registry had 0 APIs
if count == 0 && apisByIDLen() == 0 {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Warning("No API Definitions found, not reloading")
return
}
// We have updated specs, lets load those...
// Reset the JSVM
if config.Global.EnableJSVM {
GlobalEventsJSVM.Init(nil)
}
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("Preparing new router")
mainRouter = mux.NewRouter()
if config.Global.HttpServerOptions.OverrideDefaults {
mainRouter.SkipClean(config.Global.HttpServerOptions.SkipURLCleaning)
}
if config.Global.ControlAPIPort == 0 {
loadAPIEndpoints(mainRouter)
}
loadGlobalApps()
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("API reload complete")
// Unset these
rpcEmergencyModeLoaded = false
rpcEmergencyMode = false
}
// startReloadChan and reloadDoneChan are used by the two reload loops
// running in separate goroutines to talk. reloadQueueLoop will use
// startReloadChan to signal to reloadLoop to start a reload, and
// reloadLoop will use reloadDoneChan to signal back that it's done with
// the reload. Buffered simply to not make the goroutines block each
// other.
var startReloadChan = make(chan struct{}, 1)
var reloadDoneChan = make(chan struct{}, 1)
func reloadLoop(tick <-chan time.Time) {
<-tick
for range startReloadChan {
log.Info("Initiating reload")
doReload()
log.Info("Initiating coprocess reload")
doCoprocessReload()
reloadDoneChan <- struct{}{}
<-tick
}
}
// reloadQueue is used by reloadURLStructure to queue a reload. It's not
// buffered, as reloadQueueLoop should pick these up immediately.
var reloadQueue = make(chan func())
func reloadQueueLoop() {
reloading := false
var fns []func()
for {
select {
case <-reloadDoneChan:
for _, fn := range fns {
fn()
}
fns = fns[:0]
reloading = false
case fn := <-reloadQueue:
if fn != nil {
fns = append(fns, fn)
}
if !reloading {
log.Info("Reload queued")
startReloadChan <- struct{}{}
reloading = true
} else {
log.Info("Reload already queued")
}
}
}
}
// reloadURLStructure will queue an API reload. The reload will
// eventually 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.
//
// done will be called when the reload is finished. Note that if a
// reload is already queued, another won't be queued, but done will
// still be called when said queued reload is finished.
func reloadURLStructure(done func()) {
reloadQueue <- done
}
func setupLogger() {
if config.Global.UseSentry {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Enabling Sentry support")
hook, err := logrus_sentry.NewSentryHook(config.Global.SentryCode, []logrus.Level{
logrus.PanicLevel,
logrus.FatalLevel,
logrus.ErrorLevel,
})
hook.Timeout = 0
if err == nil {
log.Hooks.Add(hook)
rawLog.Hooks.Add(hook)
}
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Sentry hook active")
}
if config.Global.UseSyslog {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Enabling Syslog support")
hook, err := logrus_syslog.NewSyslogHook(config.Global.SyslogTransport,
config.Global.SyslogNetworkAddr,
syslog.LOG_INFO, "")
if err == nil {
log.Hooks.Add(hook)
rawLog.Hooks.Add(hook)
}
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Syslog hook active")
}
if config.Global.UseGraylog {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Enabling Graylog support")
hook := graylog.NewGraylogHook(config.Global.GraylogNetworkAddr,
map[string]interface{}{"tyk-module": "gateway"})
log.Hooks.Add(hook)
rawLog.Hooks.Add(hook)
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Graylog hook active")
}
if config.Global.UseLogstash {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Enabling Logstash support")
hook, err := logrus_logstash.NewHook(config.Global.LogstashTransport,
config.Global.LogstashNetworkAddr,
"tyk-gateway")
if err == nil {
log.Hooks.Add(hook)
rawLog.Hooks.Add(hook)
}
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Logstash hook active")
}
if config.Global.UseRedisLog {
hook := newRedisHook()
log.Hooks.Add(hook)
rawLog.Hooks.Add(hook)
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Redis log hook active")
}
}
var configMu sync.Mutex
func initialiseSystem() error {
// Enable command mode
for _, opt := range commandModeOptions {
switch x := opt.(type) {
case *string:
if *x == "" {
continue
}
case *bool:
if !*x {
continue
}
default:
panic("unexpected type")
}
handleCommandModeArgs()
os.Exit(0)
}
if runningTests && os.Getenv("TYK_LOGLEVEL") == "" {
// `go test` without TYK_LOGLEVEL set defaults to no log
// output
log.Level = logrus.ErrorLevel
log.Out = ioutil.Discard
gorpc.SetErrorLogger(func(string, ...interface{}) {})
stdlog.SetOutput(ioutil.Discard)
} else if *debugMode {
log.Level = logrus.DebugLevel
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Enabling debug-level output")
}
if *conf != "" {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debugf("Using %s for configuration", *conf)
confPaths = []string{*conf}
} else {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("No configuration file defined, will try to use default (tyk.conf)")
}
if !runningTests {
if err := config.Load(confPaths, &config.Global); err != nil {
return err
}
afterConfSetup(&config.Global)
}
if os.Getenv("TYK_LOGLEVEL") == "" && !*debugMode {
level := strings.ToLower(config.Global.LogLevel)
switch level {
case "", "info":
// default, do nothing
case "error":
log.Level = logrus.ErrorLevel
case "warn":
log.Level = logrus.WarnLevel
case "debug":
log.Level = logrus.DebugLevel
default:
log.WithFields(logrus.Fields{
"prefix": "main",
}).Fatalf("Invalid log level %q specified in config, must be error, warn, debug or info. ", level)
}
}
if config.Global.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()
if *port != "" {
portNum, err := strconv.Atoi(*port)
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Error("Port specified in flags must be a number: ", err)
} else {
config.Global.ListenPort = portNum
}
}
// Enable all the loggers
setupLogger()
if config.Global.PIDFileLocation == "" {
config.Global.PIDFileLocation = "/var/run/tyk/tyk-gateway.pid"
}
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("PIDFile location set to: ", config.Global.PIDFileLocation)
pidfile.SetPidfilePath(config.Global.PIDFileLocation)
if err := pidfile.Write(); err != nil {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Error("Failed to write PIDFile: ", err)
}
getHostDetails()
setupInstrumentation()
if config.Global.HttpServerOptions.UseLE_SSL {
go StartPeriodicStateBackup(&LE_MANAGER)
}
return nil
}
// afterConfSetup takes care of non-sensical config values (such as zero
// timeouts) and sets up a few globals that depend on the config.
func afterConfSetup(conf *config.Config) {
if conf.SlaveOptions.CallTimeout == 0 {
conf.SlaveOptions.CallTimeout = 30
}
if conf.SlaveOptions.PingTimeout == 0 {
conf.SlaveOptions.PingTimeout = 60
}
GlobalRPCPingTimeout = time.Second * time.Duration(conf.SlaveOptions.PingTimeout)
GlobalRPCCallTimeout = time.Second * time.Duration(conf.SlaveOptions.CallTimeout)
conf.EventTriggers = InitGenericEventHandlers(conf.EventHandlers)
}
var hostDetails struct {
Hostname string
PID int
}
func getHostDetails() {
var err error
if hostDetails.PID, err = pidfile.Read(); err != nil {
log.Error("Failed ot get host pid: ", err)
}
if hostDetails.Hostname, err = os.Hostname(); err != nil {
log.Error("Failed ot get hostname: ", err)
}
}
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 {
log.WithFields(logrus.Fields{
"prefix": "RPC Conn Mgr",
}).Info("No engine, break")
KeepaliveRunning = false
break
}
if engine.Killed {
log.WithFields(logrus.Fields{
"prefix": "RPC Conn Mgr",
}).Debug("[RPC Conn Mgr] this connection killed")
KeepaliveRunning = false
break
}
}
}()
}
func getGlobalStorageHandler(keyPrefix string, hashKeys bool) storage.Handler {