From b29f3c6dcd6a444bbdd92a4cd8c16bc97164eedb Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Tue, 22 Oct 2019 12:40:21 +0300 Subject: [PATCH] add server route --- .version | 2 +- conf/config.yml | 6 ++-- conf/default_remote_config.json | 23 +++++++++++-- main.go | 59 ++++++++++++++++++++++++--------- proxy/description.go | 19 ++++++++++- proxy/grpc/client.go | 10 +++--- service/metrics.go | 56 ++++++++++++++++++------------- 7 files changed, 125 insertions(+), 50 deletions(-) diff --git a/.version b/.version index 8acdd82..4e379d2 100644 --- a/.version +++ b/.version @@ -1 +1 @@ -0.0.1 +0.0.2 diff --git a/conf/config.yml b/conf/config.yml index 2fb628f..e65171f 100644 --- a/conf/config.yml +++ b/conf/config.yml @@ -1,12 +1,12 @@ configServiceAddress: - ip: 127.0.0.1 + ip: 10.250.9.40 port: 9001 httpOuterAddress: ip: http:// - port: 9003 + port: 9028 httpInnerAddress: ip: 0.0.0.0 - port: 9003 + port: 9028 moduleName: isp-gate instanceUuid: ec183598-746a-425f-b5e5-27b7fa8bc6af locations: diff --git a/conf/default_remote_config.json b/conf/default_remote_config.json index 0e0dcd2..559493e 100644 --- a/conf/default_remote_config.json +++ b/conf/default_remote_config.json @@ -1,3 +1,22 @@ { - -} \ No newline at end of file + "enableOriginalProtoErrors": false, + "proxyGrpcErrorDetails": false, + "metrics": { + "address": { + "ip": "0.0.0.0", + "path": "/metrics", + "port": "9553" + }, + "gc": true, + "memory": true + }, + "journal": { + "enableRemoteTransfer": true, + "enable": false, + "compress": true, + "filename": "/var/log/isp-gate-service/runtime.log", + "maxSizeMb": 512, + "bufferSize": 4096, + "rotateTimeoutMs": 86400000 + } +} diff --git a/main.go b/main.go index ea2d0b4..c8ce0f6 100644 --- a/main.go +++ b/main.go @@ -2,6 +2,9 @@ package main import ( "context" + "github.com/valyala/fasthttp" + "sync" + "time" "github.com/integration-system/isp-lib/bootstrap" "github.com/integration-system/isp-lib/config" @@ -21,47 +24,49 @@ import ( var ( version = "0.1.0" date = "undefined" + + srvLock = sync.Mutex{} + httpSrv *fasthttp.Server ) func main() { - - cfg := config.InitConfig(&conf.Configuration{}).(conf.Configuration) + cfg := config.InitConfig(&conf.Configuration{}).(*conf.Configuration) bs := bootstrap. ServiceBootstrap(&conf.Configuration{}, &conf.RemoteConfig{}). OnLocalConfigLoad(onLocalConfigLoad). DefaultRemoteConfigPath(schema.ResolveDefaultConfigPath("default_remote_config.json")). - RequireModule(journal.RequiredModule()). //todo - SocketConfiguration(socketConfiguration). DeclareMe(makeDeclaration). - OnRemoteConfigReceive(onRemoteConfigReceive). - OnShutdown(onShutdown) + SocketConfiguration(socketConfiguration). + RequireModule(journal.RequiredModule()) for _, location := range cfg.Locations { if p, err := proxy.Init(location); err != nil { - log.Fatal(log_code.ErrorLocalConfig, err) // todo + log.Fatal(log_code.ErrorLocalConfig, err) } else { - bs.RequireModule(cfg.ModuleName, p.Consumer, false) + bs.RequireModule(location.TargetModule, p.Consumer, true) } } - bs.Run() + bs.OnShutdown(onShutdown). + OnRemoteConfigReceive(onRemoteConfigReceive). + Run() } func onLocalConfigLoad(cfg *conf.Configuration) { log.Infof(log_code.InfoOnLocalConfigLoad, "Outer http address is %s", cfg.HttpOuterAddress.GetAddress()) } -func onRemoteConfigReceive(cfg, oldRemoteConfig *conf.RemoteConfig) { +func onRemoteConfigReceive(remoteConfig, oldRemoteConfig *conf.RemoteConfig) { localCfg := config.Get().(*conf.Configuration) - journal.Client.ReceiveConfiguration(cfg.Journal, localCfg.ModuleName) + journal.Client.ReceiveConfiguration(remoteConfig.Journal, localCfg.ModuleName) - service.JournalMethodsMatcher = service.NewCacheableMethodMatcher(cfg.JournalingMethodsPatterns) + service.JournalMethodsMatcher = service.NewCacheableMethodMatcher(remoteConfig.JournalingMethodsPatterns) - // - metric.InitCollectors(cfg.Metrics, oldRemoteConfig.Metrics) - metric.InitHttpServer(cfg.Metrics) + createServer(remoteConfig) + metric.InitCollectors(remoteConfig.Metrics, oldRemoteConfig.Metrics) + metric.InitHttpServer(remoteConfig.Metrics) //metric.InitStatusChecker("router-grpc", helper.GetRoutersAndStatus) service.Metrics.Init() } @@ -94,3 +99,27 @@ func makeDeclaration(localConfig interface{}) bootstrap.ModuleInfo { Handlers: []interface{}{}, } } + +func createServer(remoteConfig *conf.RemoteConfig) { + srvLock.Lock() + if httpSrv != nil { + if err := httpSrv.Shutdown(); err != nil { + log.Warn(log_code.WarnCreateRestServerHttpSrvShutdown, err) + } + } + maxRequestBodySize := remoteConfig.GetMaxRequestBodySize() + localConfig := config.Get().(*conf.Configuration) + restAddress := localConfig.HttpInnerAddress.GetAddress() + httpSrv = &fasthttp.Server{ + Handler: proxy.Handle, + WriteTimeout: time.Second * 60, + ReadTimeout: time.Second * 60, + MaxRequestBodySize: int(maxRequestBodySize), + } + go func() { + if err := httpSrv.ListenAndServe(restAddress); err != nil { + log.Error(log_code.ErrorCreateRestServerHttpSrvListenAndServe, err) + } + }() + srvLock.Unlock() +} diff --git a/proxy/description.go b/proxy/description.go index ad65db0..f9cab36 100644 --- a/proxy/description.go +++ b/proxy/description.go @@ -1,12 +1,15 @@ package proxy import ( - "errors" "github.com/integration-system/isp-lib/structure" + "github.com/pkg/errors" "github.com/valyala/fasthttp" + "google.golang.org/grpc/codes" "isp-gate-service/conf" "isp-gate-service/proxy/grpc" + "isp-gate-service/proxy/grpc/utils" "isp-gate-service/proxy/http" + "strings" ) var ProxyStore = make(map[string]Proxy) @@ -23,6 +26,9 @@ type Proxy interface { } func Init(location conf.Location) (Proxy, error) { + if location.PathPrefix[0] != '/' { + return nil, errors.Errorf("path must begin with '/' in path '%s'", location.PathPrefix) + } switch location.Protocol { case httpProtocol: proxy := http.NewProxy() @@ -36,3 +42,14 @@ func Init(location conf.Location) (Proxy, error) { return nil, errors.New("unknown protocol") } } + +func Handle(ctx *fasthttp.RequestCtx) { + path := string(ctx.Path()) + for pathPrefix, proxy := range ProxyStore { + if strings.HasPrefix(path, pathPrefix) { + proxy.ProxyRequest(ctx) + return + } + } + utils.SendError("unknown path", codes.Internal, []interface{}{map[string]string{"path": path}}, ctx) +} diff --git a/proxy/grpc/client.go b/proxy/grpc/client.go index a304d45..3924ac3 100644 --- a/proxy/grpc/client.go +++ b/proxy/grpc/client.go @@ -17,8 +17,8 @@ type grpcProxy struct { client *backend.RxGrpcClient } -func NewProxy() grpcProxy { - return grpcProxy{client: backend.NewRxGrpcClient( +func NewProxy() *grpcProxy { + return &grpcProxy{client: backend.NewRxGrpcClient( backend.WithDialOptions( grpc.WithInsecure(), grpc.WithBlock(), grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(int(conf.DefaultMaxResponseBodySize))), @@ -30,7 +30,7 @@ func NewProxy() grpcProxy { )} } -func (p grpcProxy) ProxyRequest(ctx *fasthttp.RequestCtx) { +func (p *grpcProxy) ProxyRequest(ctx *fasthttp.RequestCtx) { currentTime := time.Now() uri := string(ctx.RequestURI()) @@ -45,10 +45,10 @@ func (p grpcProxy) ProxyRequest(ctx *fasthttp.RequestCtx) { } } -func (p grpcProxy) Consumer(addr []structure.AddressConfiguration) bool { +func (p *grpcProxy) Consumer(addr []structure.AddressConfiguration) bool { return p.client.ReceiveAddressList(addr) } -func (p grpcProxy) Close() { +func (p *grpcProxy) Close() { p.client.Close() } diff --git a/service/metrics.go b/service/metrics.go index 47e79fd..a087917 100644 --- a/service/metrics.go +++ b/service/metrics.go @@ -12,7 +12,7 @@ const ( defaultSampleSize = 2048 ) -var Metrics = metricService{mh: nil} +var Metrics = &metricService{mh: nil} type ( metricService struct { @@ -29,38 +29,44 @@ type ( } ) -func (m metricService) Init() { - if m.mh == nil { - m.mh = &metricHolder{ - methodHistograms: make(map[string]metrics.Histogram), - statusCounters: make(map[int]metrics.Counter), - responseTime: metrics.GetOrRegisterHistogram( - "http.response.time", metric.GetRegistry(), metrics.NewUniformSample(defaultSampleSize), - ), - routerResponseTime: metrics.GetOrRegisterHistogram( - "grpc.router.response.time", metric.GetRegistry(), metrics.NewUniformSample(defaultSampleSize), - ), - } +func (m *metricService) Init() { + m.mh = &metricHolder{ + methodHistograms: make(map[string]metrics.Histogram), + statusCounters: make(map[int]metrics.Counter), + responseTime: metrics.GetOrRegisterHistogram( + "http.response.time", metric.GetRegistry(), metrics.NewUniformSample(defaultSampleSize), + ), + routerResponseTime: metrics.GetOrRegisterHistogram( + "grpc.router.response.time", metric.GetRegistry(), metrics.NewUniformSample(defaultSampleSize), + ), } } -func (m metricService) UpdateMethodResponseTime(uri string, time time.Duration) { - m.getOrRegisterHistogram(uri).Update(int64(time)) +func (m *metricService) UpdateMethodResponseTime(uri string, time time.Duration) { + if m.notEmptyHolder() { + m.getOrRegisterHistogram(uri).Update(int64(time)) + } } -func (m metricService) UpdateResponseTime(time time.Duration) { - m.mh.responseTime.Update(int64(time)) +func (m *metricService) UpdateResponseTime(time time.Duration) { + if m.notEmptyHolder() { + m.mh.responseTime.Update(int64(time)) + } } -func (m metricService) UpdateRouterResponseTime(time time.Duration) { - m.mh.routerResponseTime.Update(int64(time)) +func (m *metricService) UpdateRouterResponseTime(time time.Duration) { + if m.notEmptyHolder() { + m.mh.routerResponseTime.Update(int64(time)) + } } -func (m metricService) UpdateStatusCounter(status int) { - m.getOrRegisterCounter(status).Inc(1) +func (m *metricService) UpdateStatusCounter(status int) { + if m.notEmptyHolder() { + m.getOrRegisterCounter(status).Inc(1) + } } -func (m metricService) getOrRegisterHistogram(uri string) metrics.Histogram { +func (m *metricService) getOrRegisterHistogram(uri string) metrics.Histogram { m.mh.methodLock.RLock() histogram, ok := m.mh.methodHistograms[uri] m.mh.methodLock.RUnlock() @@ -82,7 +88,7 @@ func (m metricService) getOrRegisterHistogram(uri string) metrics.Histogram { return histogram } -func (m metricService) getOrRegisterCounter(status int) metrics.Counter { +func (m *metricService) getOrRegisterCounter(status int) metrics.Counter { m.mh.statusLock.RLock() d, ok := m.mh.statusCounters[status] m.mh.statusLock.RUnlock() @@ -99,3 +105,7 @@ func (m metricService) getOrRegisterCounter(status int) metrics.Counter { m.mh.statusCounters[status] = d return d } + +func (m *metricService) notEmptyHolder() bool { + return m.mh != nil +}