From 244d8fbdc267a2c906a3dc2ecc929f352d30841e Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Mon, 25 Nov 2019 15:44:03 +0300 Subject: [PATCH 1/9] fix proxy path & add skip auth --- .version | 2 +- CHANGELOG.md | 3 ++ Gopkg.lock | 10 +++--- authenticate/authenticate.go | 27 ++------------- conf/local_config.go | 18 ++++++++++ handler/handler.go | 53 +++++++++++++++++------------- main.go | 18 ++++++---- proxy/description.go | 29 ++++++++++++---- proxy/grpc/client.go | 36 +++++++++++--------- proxy/grpc/handlers/common.go | 2 +- proxy/grpc/handlers/handle_json.go | 7 ---- proxy/health_check/health_check.go | 13 ++++++-- proxy/http/client.go | 14 +++++--- 13 files changed, 137 insertions(+), 95 deletions(-) diff --git a/.version b/.version index 227cea2..7ec1d6d 100644 --- a/.version +++ b/.version @@ -1 +1 @@ -2.0.0 +2.1.0 diff --git a/CHANGELOG.md b/CHANGELOG.md index 460f468..18a0c53 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,6 @@ +## 2.1.0 +* fix proxy path +* add skip authenticate ## 2.0.0 * add integration with isp-config-service 2.0 ## 1.3.0 diff --git a/Gopkg.lock b/Gopkg.lock index 52df29f..19e8d15 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -18,12 +18,12 @@ version = "v0.1.1" [[projects]] - digest = "1:c1100fc71e23b6a32b2c68a5202a848fd13811d5a10b12edb8019c3667d1cd9a" + digest = "1:44f56f927970ceccb0a28eccbea0cde48e56f04619ddbb70198036407f14cd0e" name = "github.com/cenkalti/backoff" packages = ["."] pruneopts = "UT" - revision = "4b4cebaf850ec58f1bb1fec5bdebdf8501c2bc3f" - version = "v3.0.0" + revision = "1ff1c09ea627d2be64cea605afa999c582c7cd01" + version = "v3.1.1" [[projects]] digest = "1:ffe9824d294da03b391f44e1ae8281281b4afc1bdaa9588c9097785e3af10cec" @@ -490,7 +490,7 @@ "ssh/terminal", ] pruneopts = "UT" - revision = "4f8c1d86b1ba699e7a66cd649947ed270a74e0bb" + revision = "ac88ee75c92c889b97e05591e9a39b6480c538b3" [[projects]] branch = "master" @@ -506,7 +506,7 @@ "trace", ] pruneopts = "UT" - revision = "fc4aabc6c91483155dade6fbb627cc953a723260" + revision = "ffdde105785063a81acd95bdf89ea53f6e0aac2d" [[projects]] branch = "master" diff --git a/authenticate/authenticate.go b/authenticate/authenticate.go index 88407ac..40027df 100644 --- a/authenticate/authenticate.go +++ b/authenticate/authenticate.go @@ -38,14 +38,7 @@ func ReceiveConfiguration(conf conf.Cache) { } } -func Do(ctx *fasthttp.RequestCtx) (int32, error) { - path := ctx.Path() - pathStr := getPathWithoutPrefix(path) - - if _, ok := routing.AllMethods[pathStr]; !ok { - return 0, createError("not implemented", codes.Unimplemented) - } - +func Do(ctx *fasthttp.RequestCtx, path string) (int32, error) { for _, notExpectedHeader := range notExpectedHeaders { ctx.Request.Header.Del(notExpectedHeader) } @@ -86,7 +79,7 @@ func Do(ctx *fasthttp.RequestCtx) (int32, error) { verifiableKeys[utils.UserTokenHeader] = string(ctx.Request.Header.Peek(utils.UserTokenHeader)) permittedToCall := false - verifiableKeys, permittedToCall, err = auth.verify.Identity(verifiableKeys, pathStr) + verifiableKeys, permittedToCall, err = auth.verify.Identity(verifiableKeys, path) if err != nil { log.Error(log_code.ErrorAuthenticate, err) return 0, createError("internal Server error", codes.Internal) @@ -101,7 +94,7 @@ func Do(ctx *fasthttp.RequestCtx) (int32, error) { } } - if _, ok := routing.InnerMethods[pathStr]; ok { + if _, ok := routing.InnerMethods[path]; ok { adminToken := ctx.Request.Header.Peek("x-auth-admin") //todo const key if verifyToken.Admin(string(adminToken)) != nil { return 0, createError("forbidden", codes.PermissionDenied) @@ -114,17 +107,3 @@ func Do(ctx *fasthttp.RequestCtx) (int32, error) { return appId, nil } - -func getPathWithoutPrefix(path []byte) string { - firstFound := false - for i, value := range path { - if value == '/' { - if firstFound { - return string(path[i+1:]) - } else { - firstFound = true - } - } - } - return "" -} diff --git a/conf/local_config.go b/conf/local_config.go index aec087f..e6dbd69 100644 --- a/conf/local_config.go +++ b/conf/local_config.go @@ -13,8 +13,26 @@ type ( } Location struct { + SkipAuth bool PathPrefix string `valid:"required~Required"` Protocol string `valid:"required~Required"` TargetModule string `valid:"required~Required"` } ) + +func GetRequiredModules(locations []Location) map[string][]Location { + requiredModules := make(map[string][]Location) + + for _, location := range locations { + if location.TargetModule == "" { + continue + } + if loc, ok := requiredModules[location.TargetModule]; ok { + requiredModules[location.TargetModule] = append(loc, location) + } else { + requiredModules[location.TargetModule] = []Location{location} + } + } + + return requiredModules +} diff --git a/handler/handler.go b/handler/handler.go index 840b9c9..613088e 100644 --- a/handler/handler.go +++ b/handler/handler.go @@ -13,6 +13,7 @@ import ( "isp-gate-service/journal" "isp-gate-service/log_code" "isp-gate-service/proxy" + "isp-gate-service/routing" "isp-gate-service/service" "isp-gate-service/service/matcher" "isp-gate-service/utils" @@ -55,36 +56,44 @@ func CompleteRequest(ctx *fasthttp.RequestCtx) { } func (handlerHelper) AuthenticateAccountingProxy(ctx *fasthttp.RequestCtx) domain.ProxyResponse { - path := string(ctx.Path()) - - p := proxy.Find(path) + initialPath := string(ctx.Path()) + p, path := proxy.Find(initialPath) if p == nil { - err := errors.Errorf("unknown path %s", path) + err := errors.Errorf("unknown path %s", initialPath) utils.WriteError(ctx, "not found", codes.NotFound, nil) return domain.Create().SetError(err) } - applicationId, err := authenticate.Do(ctx) - if err != nil { - message := "unknown error" - status := codes.Unknown - details := make([]interface{}, 0) - switch e := err.(type) { - case authenticate.ErrorDescription: - message = e.Message() - status = e.ConvertToGrpcStatus() - details = e.Details() - } - utils.WriteError(ctx, message, status, details) - return domain.Create().SetError(err) + if _, ok := routing.AllMethods[path]; !ok { + msg := "not implemented" + utils.WriteError(ctx, msg, codes.Unimplemented, nil) + return domain.Create().SetError(errors.New(msg)) } - if !accounting.Accept(applicationId, path) { - err := errors.New("accounting error") - utils.WriteError(ctx, "too many requests", codes.ResourceExhausted, nil) - return domain.Create().SetError(err) + if !p.SkipAuth() { + applicationId, err := authenticate.Do(ctx, path) + if err != nil { + message := "unknown error" + status := codes.Unknown + details := make([]interface{}, 0) + switch e := err.(type) { + case authenticate.ErrorDescription: + message = e.Message() + status = e.ConvertToGrpcStatus() + details = e.Details() + } + utils.WriteError(ctx, message, status, details) + return domain.Create().SetError(err) + } + + if !accounting.Accept(applicationId, path) { + err := errors.New("accounting error") + utils.WriteError(ctx, "too many requests", codes.ResourceExhausted, nil) + return domain.Create().SetError(err) + } } - return p.ProxyRequest(ctx) + + return p.ProxyRequest(ctx, path) } func (handlerHelper) SetMetricStatus(statusCode int) string { diff --git a/main.go b/main.go index 8b818e1..b1f4f89 100644 --- a/main.go +++ b/main.go @@ -40,12 +40,18 @@ func main() { RequireRoutes(handleRouteUpdate). RequireModule(journal.RequiredModule()) - for _, location := range cfg.Locations { - if p, err := proxy.Init(location); err != nil { - log.Fatal(stdcodes.ModuleInvalidLocalConfig, err) - } else if location.TargetModule != "" { - bs.RequireModule(location.TargetModule, p.Consumer, false) - } + requiredModules := conf.GetRequiredModules(cfg.Locations) + for targetModule, locations := range requiredModules { + bs.RequireModule(targetModule, func(list []structure.AddressConfiguration) bool { + for _, location := range locations { + if p, err := proxy.Init(location); err != nil { + log.Fatal(stdcodes.ModuleInvalidLocalConfig, err) + } else if !p.Consumer(list) { + return false + } + } + return true + }, false) } bs.OnShutdown(onShutdown). diff --git a/proxy/description.go b/proxy/description.go index cb7fc16..3ab81d1 100644 --- a/proxy/description.go +++ b/proxy/description.go @@ -22,8 +22,9 @@ const ( type ( Proxy interface { - ProxyRequest(ctx *fasthttp.RequestCtx) domain.ProxyResponse + ProxyRequest(ctx *fasthttp.RequestCtx, path string) domain.ProxyResponse Consumer([]structure.AddressConfiguration) bool + SkipAuth() bool Close() } ) @@ -34,15 +35,15 @@ func Init(location conf.Location) (Proxy, error) { } switch location.Protocol { case httpProtocol: - proxy := http.NewProxy() + proxy := http.NewProxy(location.SkipAuth) store[location.PathPrefix] = proxy return proxy, nil case grpcProtocol: - proxy := grpc.NewProxy() + proxy := grpc.NewProxy(location.SkipAuth) store[location.PathPrefix] = proxy return proxy, nil case healthCheckProtocol: - proxy := health_check.NewProxy() + proxy := health_check.NewProxy(location.SkipAuth) store[location.PathPrefix] = proxy return proxy, nil default: @@ -50,13 +51,13 @@ func Init(location conf.Location) (Proxy, error) { } } -func Find(path string) Proxy { +func Find(path string) (Proxy, string) { for pathPrefix, proxy := range store { if strings.HasPrefix(path, pathPrefix) { - return proxy + return proxy, getPathWithoutPrefix(path) } } - return nil + return nil, "" } func Close() { @@ -64,3 +65,17 @@ func Close() { p.Close() } } + +func getPathWithoutPrefix(path string) string { + firstFound := false + for i, value := range path { + if value == '/' { + if firstFound { + return path[i+1:] + } else { + firstFound = true + } + } + } + return "" +} diff --git a/proxy/grpc/client.go b/proxy/grpc/client.go index 51231fa..a615521 100644 --- a/proxy/grpc/client.go +++ b/proxy/grpc/client.go @@ -16,23 +16,26 @@ import ( ) type grpcProxy struct { - client *backend.RxGrpcClient + client *backend.RxGrpcClient + skipAuth bool } -func NewProxy() *grpcProxy { - return &grpcProxy{client: backend.NewRxGrpcClient( - backend.WithDialOptions( - grpc.WithInsecure(), grpc.WithBlock(), - grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(int(conf.DefaultMaxResponseBodySize))), - grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(int(conf.DefaultMaxResponseBodySize))), - ), - backend.WithDialingErrorHandler(func(err error) { - log.Errorf(log_code.ErrorClientGrpc, "dialing err: %v", err) - }), - )} +func NewProxy(skiAuth bool) *grpcProxy { + return &grpcProxy{ + client: backend.NewRxGrpcClient( + backend.WithDialOptions( + grpc.WithInsecure(), grpc.WithBlock(), + grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(int(conf.DefaultMaxResponseBodySize))), + grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(int(conf.DefaultMaxResponseBodySize))), + ), + backend.WithDialingErrorHandler(func(err error) { + log.Errorf(log_code.ErrorClientGrpc, "dialing err: %v", err) + })), + skipAuth: skiAuth, + } } -func (p *grpcProxy) ProxyRequest(ctx *fasthttp.RequestCtx) domain.ProxyResponse { +func (p *grpcProxy) ProxyRequest(ctx *fasthttp.RequestCtx, path string) domain.ProxyResponse { if p.client.InternalGrpcClient == nil { msg := "client undefined" log.Error(log_code.ErrorClientGrpc, msg) @@ -43,14 +46,17 @@ func (p *grpcProxy) ProxyRequest(ctx *fasthttp.RequestCtx) domain.ProxyResponse SetError(errors.New(msg)) } - uri := string(ctx.RequestURI()) - return handlers.Handler.Get(ctx).Complete(ctx, uri, p.client) + return handlers.Handler.Get(ctx).Complete(ctx, path, p.client) } func (p *grpcProxy) Consumer(addr []structure.AddressConfiguration) bool { return p.client.ReceiveAddressList(addr) } +func (p *grpcProxy) SkipAuth() bool { + return p.skipAuth +} + func (p *grpcProxy) Close() { p.client.Close() } diff --git a/proxy/grpc/handlers/common.go b/proxy/grpc/handlers/common.go index fc5a132..060d8f3 100644 --- a/proxy/grpc/handlers/common.go +++ b/proxy/grpc/handlers/common.go @@ -128,7 +128,7 @@ func openStream(headers *fasthttp.RequestHeader, method string, timeout time.Dur } func makeMetadata(r *fasthttp.RequestHeader, method string) (metadata.MD, string) { - method = strings.TrimPrefix(method, "/api/") + //method = strings.TrimPrefix(method, "/api/") md := metadata.Pairs(utils.ProxyMethodNameHeader, method) r.VisitAll(func(key, v []byte) { lowerHeader := strings.ToLower(string(key)) diff --git a/proxy/grpc/handlers/handle_json.go b/proxy/grpc/handlers/handle_json.go index 4484c2e..6a74992 100644 --- a/proxy/grpc/handlers/handle_json.go +++ b/proxy/grpc/handlers/handle_json.go @@ -19,13 +19,7 @@ var handleJson handleJsonDesc type handleJsonDesc struct{} func (p handleJsonDesc) Complete(c *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) domain.ProxyResponse { - //body, err := utils.ReadJsonBody(c) body := c.Request.Body() - /*if err != nil { - streaming.LogError(log_code.TypeData.JsonContent, method, err) - streaming.SendError(err.Error(), codes.InvalidArgument, []interface{}{err.Error()}, c) - return - }*/ md, methodName := makeMetadata(&c.Request.Header, method) ctx := metadata.NewOutgoingContext(context.Background(), md) @@ -40,7 +34,6 @@ func (p handleJsonDesc) Complete(c *fasthttp.RequestCtx, method string, client * return domain.Create().SetError(err) } - //structBody := u.ConvertInterfaceToGrpcStruct(body) resp, invokerErr := cli.Request( ctx, &isp.Message{ diff --git a/proxy/health_check/health_check.go b/proxy/health_check/health_check.go index da064c8..d09872d 100644 --- a/proxy/health_check/health_check.go +++ b/proxy/health_check/health_check.go @@ -7,20 +7,27 @@ import ( ) type healthCheckProxy struct { + skipAuth bool } -func NewProxy() *healthCheckProxy { - return &healthCheckProxy{} +func NewProxy(skipAuth bool) *healthCheckProxy { + return &healthCheckProxy{skipAuth: skipAuth} } func (p *healthCheckProxy) Consumer(addressList []structure.AddressConfiguration) bool { return true } -func (p *healthCheckProxy) ProxyRequest(ctx *fasthttp.RequestCtx) domain.ProxyResponse { +func (p *healthCheckProxy) ProxyRequest(ctx *fasthttp.RequestCtx, path string) domain.ProxyResponse { + ctx.Response.SetBody(ctx.Request.Body()) + ctx.Request.SetRequestURI(path) return domain.Create() } +func (p *healthCheckProxy) SkipAuth() bool { + return p.skipAuth +} + func (p *healthCheckProxy) Close() { } diff --git a/proxy/http/client.go b/proxy/http/client.go index 480feed..3743362 100644 --- a/proxy/http/client.go +++ b/proxy/http/client.go @@ -14,11 +14,12 @@ import ( ) type httpProxy struct { - client *fasthttp.HostClient + client *fasthttp.HostClient + skipAuth bool } -func NewProxy() *httpProxy { - return &httpProxy{client: nil} +func NewProxy(skipAuth bool) *httpProxy { + return &httpProxy{client: nil, skipAuth: skipAuth} } func (p *httpProxy) Consumer(addressList []structure.AddressConfiguration) bool { @@ -33,7 +34,7 @@ func (p *httpProxy) Consumer(addressList []structure.AddressConfiguration) bool return true } -func (p *httpProxy) ProxyRequest(ctx *fasthttp.RequestCtx) domain.ProxyResponse { +func (p *httpProxy) ProxyRequest(ctx *fasthttp.RequestCtx, path string) domain.ProxyResponse { if p.client == nil { msg := "client undefined" log.Error(log_code.ErrorClientHttp, msg) @@ -46,6 +47,7 @@ func (p *httpProxy) ProxyRequest(ctx *fasthttp.RequestCtx) domain.ProxyResponse req := &ctx.Request res := &ctx.Response + req.SetRequestURI(path) if addr, _, err := net.SplitHostPort(ctx.RemoteAddr().String()); err == nil { req.Header.Add("X-Forwarded-For", addr) @@ -61,6 +63,10 @@ func (p *httpProxy) ProxyRequest(ctx *fasthttp.RequestCtx) domain.ProxyResponse SetError(err) } +func (p *httpProxy) SkipAuth() bool { + return p.skipAuth +} + func (p *httpProxy) Close() { p.client = nil } From 4c7e96813c49936f3408a622ac267688729a0103 Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Tue, 26 Nov 2019 12:11:13 +0300 Subject: [PATCH 2/9] add accounting version & fix proxy consumer --- accounting/accountant.go | 8 ++++ accounting/accounting.go | 22 +++++++-- accounting/accounting_test.go | 4 +- authenticate/authenticate.go | 1 + conf/local_config.go | 6 ++- entity/entity.go | 1 + handler/handler.go | 8 ++-- main.go | 47 +++++++++++++------ .../00003_2019-11-25_update_snapshot.sql | 6 +++ model/snapshot.go | 2 +- proxy/description.go | 25 +++++----- 11 files changed, 92 insertions(+), 38 deletions(-) create mode 100644 migrations/00003_2019-11-25_update_snapshot.sql diff --git a/accounting/accountant.go b/accounting/accountant.go index cde93b0..1dbafd4 100644 --- a/accounting/accountant.go +++ b/accounting/accountant.go @@ -4,12 +4,14 @@ import ( "isp-gate-service/accounting/state" "isp-gate-service/service/matcher" "sync" + "sync/atomic" ) type accountant struct { mx sync.Mutex matcher matcher.Matcher limitStates map[string]state.LimitState + version int64 } func (app *accountant) Accept(method string) bool { @@ -21,6 +23,8 @@ func (app *accountant) Accept(method string) bool { app.mx.Lock() resp := state.Update(stateStorage) + //only true or every request todo + atomic.AddInt64(&app.version, 1) app.mx.Unlock() return resp } @@ -34,3 +38,7 @@ func (app *accountant) Snapshot() map[string]state.Snapshot { app.mx.Unlock() return snapshotLimitState } + +func (app *accountant) GetVersion() int64 { + return atomic.LoadInt64(&app.version) +} diff --git a/accounting/accounting.go b/accounting/accounting.go index 71699a6..ab61bde 100644 --- a/accounting/accounting.go +++ b/accounting/accounting.go @@ -1,6 +1,8 @@ package accounting import ( + "github.com/integration-system/isp-lib/config" + "github.com/integration-system/isp-lib/structure" log "github.com/integration-system/isp-log" "github.com/integration-system/isp-log/stdcodes" "isp-gate-service/accounting/state" @@ -22,10 +24,18 @@ var ( type Accounting interface { Accept(string) bool Snapshot() map[string]state.Snapshot + GetVersion() int64 } -func ReceiveConfiguration(conf conf.Accounting) { +func Consumer(list []structure.AddressConfiguration) bool { + accountingSetting := config.GetRemote().(*conf.RemoteConfig).AccountingSetting + receiveConfiguration(accountingSetting) + return true +} + +func receiveConfiguration(conf conf.Accounting) { Close() + newAccountingStorage := make(map[int32]Accounting) newRequestsStoring := make(map[int32]bool) @@ -42,9 +52,10 @@ func ReceiveConfiguration(conf conf.Accounting) { log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err) } - recoveryLimitState(s.ApplicationId, limitStates) + version := recoveryAccounting(s.ApplicationId, limitStates) newAccountingStorage[s.ApplicationId] = &accountant{ + version: version, matcher: matcher.NewCacheableMatcher(patternArray), limitStates: limitStates, mx: sync.Mutex{}, @@ -94,14 +105,17 @@ func takeSnapshot() []entity.Snapshot { response = append(response, entity.Snapshot{ AppId: appId, LimitState: account.Snapshot(), + Version: account.GetVersion(), }) } return response } -func recoveryLimitState(appId int32, limitStates map[string]state.LimitState) { +func recoveryAccounting(appId int32, limitStates map[string]state.LimitState) int64 { + version := int64(0) if accountingWorking { if acc, ok := accountingStorage[appId]; ok { + version = acc.GetVersion() snapshot := acc.Snapshot() importLimitState(limitStates, snapshot) } @@ -109,9 +123,11 @@ func recoveryLimitState(appId int32, limitStates map[string]state.LimitState) { if snapshot, err := model.SnapshotRep.GetByApplication(appId); err != nil { log.Warn(log_code.ErrorSnapshotAccounting, err) } else if snapshot != nil { + version = snapshot.Version importLimitState(limitStates, snapshot.LimitState) } } + return version } func importLimitState(limitStates map[string]state.LimitState, snapshot map[string]state.Snapshot) { diff --git a/accounting/accounting_test.go b/accounting/accounting_test.go index 1389f83..4eb9da4 100644 --- a/accounting/accounting_test.go +++ b/accounting/accounting_test.go @@ -63,7 +63,7 @@ var ( func TestAccounting(t *testing.T) { a := assert.New(t) model.SnapshotRep = &snapshotRepository{cache: make(map[int32]map[string]state.Snapshot)} - ReceiveConfiguration(accountingSetting) + receiveConfiguration(accountingSetting) req := reqExample[4] for _, path := range req.path { @@ -97,7 +97,7 @@ func TestAccounting(t *testing.T) { a.Equal(expected, Accept(req.appId, path)) } - ReceiveConfiguration(accountingSetting) + receiveConfiguration(accountingSetting) req = reqExample[4] for _, path := range req.path { diff --git a/authenticate/authenticate.go b/authenticate/authenticate.go index 40027df..18c2499 100644 --- a/authenticate/authenticate.go +++ b/authenticate/authenticate.go @@ -49,6 +49,7 @@ func Do(ctx *fasthttp.RequestCtx, path string) (int32, error) { err error appId int32 = -1 ) + if len(appToken) == 0 { return 0, createError("unauthorized", codes.Unauthenticated) } else if config.GetRemote().(*conf.RemoteConfig).TokensSetting.ApplicationVerify { diff --git a/conf/local_config.go b/conf/local_config.go index e6dbd69..6b980ec 100644 --- a/conf/local_config.go +++ b/conf/local_config.go @@ -1,6 +1,8 @@ package conf -import "github.com/integration-system/isp-lib/structure" +import ( + "github.com/integration-system/isp-lib/structure" +) type ( Configuration struct { @@ -20,7 +22,7 @@ type ( } ) -func GetRequiredModules(locations []Location) map[string][]Location { +func GetLocationsByTargetModule(locations []Location) map[string][]Location { requiredModules := make(map[string][]Location) for _, location := range locations { diff --git a/entity/entity.go b/entity/entity.go index 36b6f96..682725b 100644 --- a/entity/entity.go +++ b/entity/entity.go @@ -9,6 +9,7 @@ type Snapshot struct { TableName string `sql:"?db_schema.snapshot" json:"-"` AppId int32 `sql:",pk"` LimitState map[string]state.Snapshot + Version int64 } type Request struct { diff --git a/handler/handler.go b/handler/handler.go index 613088e..4afb09d 100644 --- a/handler/handler.go +++ b/handler/handler.go @@ -1,6 +1,7 @@ package handler import ( + "fmt" "github.com/integration-system/isp-lib/config" log "github.com/integration-system/isp-log" "github.com/pkg/errors" @@ -57,11 +58,12 @@ func CompleteRequest(ctx *fasthttp.RequestCtx) { func (handlerHelper) AuthenticateAccountingProxy(ctx *fasthttp.RequestCtx) domain.ProxyResponse { initialPath := string(ctx.Path()) + p, path := proxy.Find(initialPath) if p == nil { - err := errors.Errorf("unknown path %s", initialPath) - utils.WriteError(ctx, "not found", codes.NotFound, nil) - return domain.Create().SetError(err) + msg := fmt.Sprintf("unknown proxy for '%s'", path) + utils.WriteError(ctx, msg, codes.NotFound, nil) + return domain.Create().SetError(errors.New(msg)) } if _, ok := routing.AllMethods[path]; !ok { diff --git a/main.go b/main.go index b1f4f89..5257386 100644 --- a/main.go +++ b/main.go @@ -40,21 +40,13 @@ func main() { RequireRoutes(handleRouteUpdate). RequireModule(journal.RequiredModule()) - requiredModules := conf.GetRequiredModules(cfg.Locations) - for targetModule, locations := range requiredModules { - bs.RequireModule(targetModule, func(list []structure.AddressConfiguration) bool { - for _, location := range locations { - if p, err := proxy.Init(location); err != nil { - log.Fatal(stdcodes.ModuleInvalidLocalConfig, err) - } else if !p.Consumer(list) { - return false - } - } - return true - }, false) + requiredModules := getRequiredModulesByLocations(cfg.Locations) + for module, consumer := range requiredModules { + bs.RequireModule(module, consumer, false) } - bs.OnShutdown(onShutdown). + bs.RequireModule(cfg.ModuleName, accounting.Consumer, false). + OnShutdown(onShutdown). OnRemoteConfigReceive(onRemoteConfigReceive). Run() } @@ -71,7 +63,6 @@ func onRemoteConfigReceive(remoteConfig, oldRemoteConfig *conf.RemoteConfig) { matcher.JournalMethods = matcher.NewAtLeastOneMatcher(remoteConfig.JournalSetting.MethodsPatterns) redis.Client.ReceiveConfiguration(remoteConfig.Redis) - accounting.ReceiveConfiguration(remoteConfig.AccountingSetting) authenticate.ReceiveConfiguration(remoteConfig.AuthCacheSetting) metric.InitCollectors(remoteConfig.Metrics, oldRemoteConfig.Metrics) @@ -115,3 +106,31 @@ func makeDeclaration(localConfig interface{}) bootstrap.ModuleInfo { Handlers: []interface{}{}, } } + +func getRequiredModulesByLocations(locations []conf.Location) map[string]func([]structure.AddressConfiguration) bool { + locationsByTargetModule := conf.GetLocationsByTargetModule(locations) + requiredModules := make(map[string]func([]structure.AddressConfiguration) bool) + + for targetModule, locations := range locationsByTargetModule { + consumerStorage := make([]func([]structure.AddressConfiguration) bool, len(locations)) + for i, location := range locations { + if p, err := proxy.Init(location.Protocol, location.PathPrefix, location.SkipAuth); err != nil { + log.Fatal(stdcodes.ModuleInvalidLocalConfig, err) + } else { + consumerStorage[i] = p.Consumer + } + } + requiredModules[targetModule] = aggregateConsumers(consumerStorage...) + } + + return requiredModules +} + +func aggregateConsumers(consumers ...func([]structure.AddressConfiguration) bool) func([]structure.AddressConfiguration) bool { + return func(list []structure.AddressConfiguration) bool { + for _, consumer := range consumers { + consumer(list) + } + return true + } +} diff --git a/migrations/00003_2019-11-25_update_snapshot.sql b/migrations/00003_2019-11-25_update_snapshot.sql new file mode 100644 index 0000000..e69a04b --- /dev/null +++ b/migrations/00003_2019-11-25_update_snapshot.sql @@ -0,0 +1,6 @@ +-- +goose Up + +ALTER TABLE snapshot + ADD version BIGINT NOT NULL DEFAULT 0; + +-- +goose Down \ No newline at end of file diff --git a/model/snapshot.go b/model/snapshot.go index 6950f2f..54b21f4 100644 --- a/model/snapshot.go +++ b/model/snapshot.go @@ -21,7 +21,7 @@ type ( ) func (r snapshotRepository) Update(list []entity.Snapshot) error { - _, err := r.getDb().Model(&list).OnConflict("(app_id) DO UPDATE").Insert() + _, err := r.getDb().Model(&list).OnConflict("(app_id) DO UPDATE WHERE EXCLUDED.version > version").Insert() return err } diff --git a/proxy/description.go b/proxy/description.go index 3ab81d1..381ab4c 100644 --- a/proxy/description.go +++ b/proxy/description.go @@ -4,7 +4,6 @@ import ( "github.com/integration-system/isp-lib/structure" "github.com/pkg/errors" "github.com/valyala/fasthttp" - "isp-gate-service/conf" "isp-gate-service/domain" "isp-gate-service/proxy/grpc" "isp-gate-service/proxy/health_check" @@ -29,25 +28,25 @@ type ( } ) -func Init(location conf.Location) (Proxy, error) { - if location.PathPrefix[0] != '/' { - return nil, errors.Errorf("path must begin with '/' in path '%s'", location.PathPrefix) +func Init(protocol, pathPrefix string, skipAuth bool) (Proxy, error) { + if pathPrefix[0] != '/' { + return nil, errors.Errorf("path must begin with '/' in path '%s'", pathPrefix) } - switch location.Protocol { + switch protocol { case httpProtocol: - proxy := http.NewProxy(location.SkipAuth) - store[location.PathPrefix] = proxy + proxy := http.NewProxy(skipAuth) + store[pathPrefix] = proxy return proxy, nil case grpcProtocol: - proxy := grpc.NewProxy(location.SkipAuth) - store[location.PathPrefix] = proxy + proxy := grpc.NewProxy(skipAuth) + store[pathPrefix] = proxy return proxy, nil case healthCheckProtocol: - proxy := health_check.NewProxy(location.SkipAuth) - store[location.PathPrefix] = proxy + proxy := health_check.NewProxy(skipAuth) + store[pathPrefix] = proxy return proxy, nil default: - return nil, errors.Errorf("unknown protocol '%s'", location.Protocol) + return nil, errors.Errorf("unknown protocol '%s'", protocol) } } @@ -57,7 +56,7 @@ func Find(path string) (Proxy, string) { return proxy, getPathWithoutPrefix(path) } } - return nil, "" + return nil, getPathWithoutPrefix(path) } func Close() { From 909ff91b2b1ff07097574edc8531d1ffac13b044 Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Tue, 26 Nov 2019 17:28:22 +0300 Subject: [PATCH 3/9] add snapshot version --- CHANGELOG.md | 1 + accounting/accountant.go | 5 +++-- accounting/accounting.go | 4 ++-- accounting/accounting_test.go | 4 ++-- conf/remote_config.go | 6 +++--- main.go | 1 + ...19_add_unload.sql => 00002_2019-11-19_add_requests.sql} | 0 model/snapshot.go | 7 ++++++- 8 files changed, 18 insertions(+), 10 deletions(-) rename migrations/{00002_2019-11-19_add_unload.sql => 00002_2019-11-19_add_requests.sql} (100%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 18a0c53..4764613 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,7 @@ ## 2.1.0 * fix proxy path * add skip authenticate +* add snapshot version ## 2.0.0 * add integration with isp-config-service 2.0 ## 1.3.0 diff --git a/accounting/accountant.go b/accounting/accountant.go index 1dbafd4..19675c4 100644 --- a/accounting/accountant.go +++ b/accounting/accountant.go @@ -23,8 +23,9 @@ func (app *accountant) Accept(method string) bool { app.mx.Lock() resp := state.Update(stateStorage) - //only true or every request todo - atomic.AddInt64(&app.version, 1) + if resp { + atomic.AddInt64(&app.version, 1) + } app.mx.Unlock() return resp } diff --git a/accounting/accounting.go b/accounting/accounting.go index ab61bde..6449a3c 100644 --- a/accounting/accounting.go +++ b/accounting/accounting.go @@ -29,11 +29,11 @@ type Accounting interface { func Consumer(list []structure.AddressConfiguration) bool { accountingSetting := config.GetRemote().(*conf.RemoteConfig).AccountingSetting - receiveConfiguration(accountingSetting) + ReceiveConfiguration(accountingSetting) return true } -func receiveConfiguration(conf conf.Accounting) { +func ReceiveConfiguration(conf conf.Accounting) { Close() newAccountingStorage := make(map[int32]Accounting) diff --git a/accounting/accounting_test.go b/accounting/accounting_test.go index 4eb9da4..1389f83 100644 --- a/accounting/accounting_test.go +++ b/accounting/accounting_test.go @@ -63,7 +63,7 @@ var ( func TestAccounting(t *testing.T) { a := assert.New(t) model.SnapshotRep = &snapshotRepository{cache: make(map[int32]map[string]state.Snapshot)} - receiveConfiguration(accountingSetting) + ReceiveConfiguration(accountingSetting) req := reqExample[4] for _, path := range req.path { @@ -97,7 +97,7 @@ func TestAccounting(t *testing.T) { a.Equal(expected, Accept(req.appId, path)) } - receiveConfiguration(accountingSetting) + ReceiveConfiguration(accountingSetting) req = reqExample[4] for _, path := range req.path { diff --git a/conf/remote_config.go b/conf/remote_config.go index 7a70ecf..767ae1f 100644 --- a/conf/remote_config.go +++ b/conf/remote_config.go @@ -49,9 +49,9 @@ type ( Accounting struct { Enable bool `schema:"Учет запросов,включает/отключает учет запросов"` - SnapshotTimeout string `schema:"Частота выгрузки данных учета в БД" valid:"required~Required"` + SnapshotTimeout string `schema:"Частота выгрузки ограничений для приложений" valid:"required~Required"` Setting []AccountingSetting `schema:"Настройка учета для приложений"` - Storing StoringSetting `schema:"Настройка хранения запросов"` + Storing StoringSetting `schema:"Настройка хранения всех запросов"` } AccountingSetting struct { @@ -68,7 +68,7 @@ type ( StoringSetting struct { Size int `schema:"Размер буфера,размер буфера,при достижении которого данные сбрасываются в БД" valid:"required,range(1|1000000)"` - Timeout string `schema:"Частота сброса,периодичность сброса данных в БД" valid:"required~Required"` + Timeout string `schema:"Частота выгрузки всех учтенных запросов,периодичность сброса данных в БД" valid:"required~Required"` } HttpSetting struct { diff --git a/main.go b/main.go index 5257386..2e992b5 100644 --- a/main.go +++ b/main.go @@ -64,6 +64,7 @@ func onRemoteConfigReceive(remoteConfig, oldRemoteConfig *conf.RemoteConfig) { redis.Client.ReceiveConfiguration(remoteConfig.Redis) authenticate.ReceiveConfiguration(remoteConfig.AuthCacheSetting) + accounting.ReceiveConfiguration(remoteConfig.AccountingSetting) metric.InitCollectors(remoteConfig.Metrics, oldRemoteConfig.Metrics) metric.InitHttpServer(remoteConfig.Metrics) diff --git a/migrations/00002_2019-11-19_add_unload.sql b/migrations/00002_2019-11-19_add_requests.sql similarity index 100% rename from migrations/00002_2019-11-19_add_unload.sql rename to migrations/00002_2019-11-19_add_requests.sql diff --git a/model/snapshot.go b/model/snapshot.go index 54b21f4..dcd583e 100644 --- a/model/snapshot.go +++ b/model/snapshot.go @@ -21,7 +21,12 @@ type ( ) func (r snapshotRepository) Update(list []entity.Snapshot) error { - _, err := r.getDb().Model(&list).OnConflict("(app_id) DO UPDATE WHERE EXCLUDED.version > version").Insert() + _, err := r.getDb().Model(&list).OnConflict("(app_id) DO UPDATE"). + Set("version = EXCLUDED.version"). + Set("app_id = EXCLUDED.app_id"). + Set("limit_state = EXCLUDED.limit_state"). + Where("snapshot.version < EXCLUDED.version"). + Insert() return err } From 1ffe9e4a628163bee98477d27bc9dbb0047bfe3a Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Wed, 27 Nov 2019 13:46:46 +0300 Subject: [PATCH 4/9] fix recovery accounting --- accounting/accountant.go | 9 +-- accounting/accounting.go | 103 +++++++++++++++++++++------------- accounting/accounting_test.go | 92 ++++++++++++++++++++++++------ accounting/snapshot.go | 2 +- handler/handler.go | 2 +- main.go | 6 +- 6 files changed, 148 insertions(+), 66 deletions(-) diff --git a/accounting/accountant.go b/accounting/accountant.go index 19675c4..8c07950 100644 --- a/accounting/accountant.go +++ b/accounting/accountant.go @@ -30,16 +30,13 @@ func (app *accountant) Accept(method string) bool { return resp } -func (app *accountant) Snapshot() map[string]state.Snapshot { +func (app *accountant) Snapshot() (map[string]state.Snapshot, int64) { app.mx.Lock() + version := atomic.LoadInt64(&app.version) snapshotLimitState := make(map[string]state.Snapshot, len(app.limitStates)) for method, limitState := range app.limitStates { snapshotLimitState[method] = limitState.Export() } app.mx.Unlock() - return snapshotLimitState -} - -func (app *accountant) GetVersion() int64 { - return atomic.LoadInt64(&app.version) + return snapshotLimitState, version } diff --git a/accounting/accounting.go b/accounting/accounting.go index 6449a3c..da84642 100644 --- a/accounting/accounting.go +++ b/accounting/accounting.go @@ -15,29 +15,38 @@ import ( "time" ) -var ( - accountingWorking = false - accountingStorage = make(map[int32]Accounting) - requestsStoring = make(map[int32]bool) -) - -type Accounting interface { - Accept(string) bool - Snapshot() map[string]state.Snapshot - GetVersion() int64 +var Worker = &worker{ + process: false, + accountingStorage: make(map[int32]Accounting), + requestsStoring: make(map[int32]bool), } -func Consumer(list []structure.AddressConfiguration) bool { +type ( + Accounting interface { + Accept(string) bool + Snapshot() (map[string]state.Snapshot, int64) + } + + worker struct { + mx sync.RWMutex + process bool + accountingStorage map[int32]Accounting + requestsStoring map[int32]bool + } +) + +func (w *worker) Consumer(list []structure.AddressConfiguration) bool { accountingSetting := config.GetRemote().(*conf.RemoteConfig).AccountingSetting - ReceiveConfiguration(accountingSetting) + w.ReceiveConfiguration(accountingSetting) return true } -func ReceiveConfiguration(conf conf.Accounting) { - Close() +func (w *worker) ReceiveConfiguration(conf conf.Accounting) { + w.Close() newAccountingStorage := make(map[int32]Accounting) newRequestsStoring := make(map[int32]bool) + process := false if conf.Enable { if err := InitStoringTask(conf.Storing); err != nil { @@ -52,7 +61,7 @@ func ReceiveConfiguration(conf conf.Accounting) { log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err) } - version := recoveryAccounting(s.ApplicationId, limitStates) + version := w.recoveryAccounting(s.ApplicationId, limitStates) newAccountingStorage[s.ApplicationId] = &accountant{ version: version, @@ -68,69 +77,87 @@ func ReceiveConfiguration(conf conf.Accounting) { go snapshot.Start(snapshotTimeout) } - accountingWorking = true - } else { - accountingWorking = false + process = true } - requestsStoring = newRequestsStoring - accountingStorage = newAccountingStorage + w.mx.Lock() + w.requestsStoring = newRequestsStoring + w.accountingStorage = newAccountingStorage + w.process = process + w.mx.Unlock() } -func Accept(appId int32, path string) bool { - if accouter, ok := accountingStorage[appId]; !ok { - if requestsStoring[appId] { +func (w *worker) AcceptRequest(appId int32, path string) bool { + w.mx.RLock() + defer w.mx.RUnlock() + if accouter, ok := w.accountingStorage[appId]; !ok { + if w.requestsStoring[appId] { storage.TakeRequest(appId, path, time.Now()) } return true } else { ok := accouter.Accept(path) - if ok && requestsStoring[appId] { + if ok && w.requestsStoring[appId] { storage.TakeRequest(appId, path, time.Now()) } return ok } } -func Close() { +func (w *worker) Close() { snapshot.Stop() if storage != nil { storage.Stop() } } -func takeSnapshot() []entity.Snapshot { - response := make([]entity.Snapshot, 0, len(accountingStorage)) - for appId, account := range accountingStorage { +func (w *worker) takeSnapshot() []entity.Snapshot { + w.mx.RLock() + response := make([]entity.Snapshot, 0, len(w.accountingStorage)) + for appId, account := range w.accountingStorage { + + limitState, version := account.Snapshot() + response = append(response, entity.Snapshot{ AppId: appId, - LimitState: account.Snapshot(), - Version: account.GetVersion(), + LimitState: limitState, + Version: version, }) } + w.mx.RUnlock() return response } -func recoveryAccounting(appId int32, limitStates map[string]state.LimitState) int64 { +func (w *worker) recoveryAccounting(appId int32, limitStates map[string]state.LimitState) int64 { version := int64(0) - if accountingWorking { - if acc, ok := accountingStorage[appId]; ok { - version = acc.GetVersion() - snapshot := acc.Snapshot() - importLimitState(limitStates, snapshot) + w.mx.RLock() + if w.process { + if acc, ok := w.accountingStorage[appId]; ok { + cashLimitState, cashVersion := acc.Snapshot() + dbSnapshot, err := model.SnapshotRep.GetByApplication(appId) + if err != nil { + log.Warn(log_code.ErrorSnapshotAccounting, err) + } + + if dbSnapshot != nil && dbSnapshot.Version > cashVersion { + w.importLimitState(limitStates, dbSnapshot.LimitState) + } else { + w.importLimitState(limitStates, cashLimitState) + } } } else { if snapshot, err := model.SnapshotRep.GetByApplication(appId); err != nil { log.Warn(log_code.ErrorSnapshotAccounting, err) } else if snapshot != nil { version = snapshot.Version - importLimitState(limitStates, snapshot.LimitState) + w.importLimitState(limitStates, snapshot.LimitState) } } + w.mx.RUnlock() return version } -func importLimitState(limitStates map[string]state.LimitState, snapshot map[string]state.Snapshot) { +func (w *worker) importLimitState(limitStates map[string]state.LimitState, snapshot map[string]state.Snapshot) { for method, limitState := range limitStates { if oldState, ok := snapshot[method]; ok { limitState.Import(oldState) diff --git a/accounting/accounting_test.go b/accounting/accounting_test.go index 1389f83..664151c 100644 --- a/accounting/accounting_test.go +++ b/accounting/accounting_test.go @@ -2,10 +2,10 @@ package accounting import ( "github.com/stretchr/testify/assert" - "isp-gate-service/accounting/state" "isp-gate-service/conf" "isp-gate-service/entity" "isp-gate-service/model" + "sync" "testing" "time" ) @@ -21,6 +21,7 @@ var ( {Pattern: "mdm-master/group3/*", MaxCount: 5, Timeout: "10s"}, {Pattern: "mdm-master/group4/method", MaxCount: 2, Timeout: "0s"}, {Pattern: "mdm-master/group5/method", MaxCount: 3, Timeout: "10s"}, + {Pattern: "mdm-master/group6/method", MaxCount: 5, Timeout: "10s"}, }}, {ApplicationId: 2, Limits: []conf.LimitSetting{ {Pattern: "mdm-master/group/method", MaxCount: 0, Timeout: "10s"}, @@ -62,18 +63,18 @@ var ( func TestAccounting(t *testing.T) { a := assert.New(t) - model.SnapshotRep = &snapshotRepository{cache: make(map[int32]map[string]state.Snapshot)} - ReceiveConfiguration(accountingSetting) + model.SnapshotRep = newSnapshotRepository(false) + Worker.ReceiveConfiguration(accountingSetting) req := reqExample[4] for _, path := range req.path { - a.True(Accept(req.appId, path)) + a.True(Worker.AcceptRequest(req.appId, path)) } expected := true req = reqExample[0] for _, path := range req.path { - a.Equal(expected, Accept(req.appId, path)) + a.Equal(expected, Worker.AcceptRequest(req.appId, path)) expected = !expected time.Sleep(50 * time.Millisecond) } @@ -81,49 +82,106 @@ func TestAccounting(t *testing.T) { //expected == true req = reqExample[1] for _, path := range req.path { - a.Equal(expected, Accept(req.appId, path)) + a.Equal(expected, Worker.AcceptRequest(req.appId, path)) expected = !expected } req = reqExample[2] expectedArray := []bool{true, true, true, true, true, false} for key, path := range req.path { - a.Equal(expectedArray[key], Accept(req.appId, path)) + a.Equal(expectedArray[key], Worker.AcceptRequest(req.appId, path)) } //expected == true req = reqExample[3] for _, path := range req.path { - a.Equal(expected, Accept(req.appId, path)) + a.Equal(expected, Worker.AcceptRequest(req.appId, path)) } - ReceiveConfiguration(accountingSetting) + Worker.ReceiveConfiguration(accountingSetting) req = reqExample[4] for _, path := range req.path { - a.False(Accept(req.appId, path)) + a.False(Worker.AcceptRequest(req.appId, path)) + } +} + +func TestWorker_recoveryAccounting(t *testing.T) { + a := assert.New(t) + snapshotRep := newSnapshotRepository(true) + model.SnapshotRep = snapshotRep + + oldWorker := &worker{ + process: false, + accountingStorage: make(map[int32]Accounting), + requestsStoring: make(map[int32]bool), } + Worker.ReceiveConfiguration(accountingSetting) + oldWorker.ReceiveConfiguration(accountingSetting) + + request := "1_3_5" + for range request { + a.True(Worker.AcceptRequest(1, "mdm-master/group6/method")) + } + a.False(Worker.AcceptRequest(1, "mdm-master/group6/method")) + + time.Sleep(time.Millisecond * 300) + a.True(snapshotRep.Wait()) + snapshot, err := model.SnapshotRep.GetByApplication(1) + a.NoError(err) + a.NotNil(snapshot) + a.Equal(len(request), int(snapshot.Version)) + + Worker = oldWorker + Worker.ReceiveConfiguration(accountingSetting) + a.False(Worker.AcceptRequest(1, "mdm-master/group6/method")) } type snapshotRepository struct { - cache map[int32]map[string]state.Snapshot + enableWaitGroup bool + wg sync.WaitGroup + cache map[int32]entity.Snapshot +} + +func newSnapshotRepository(enableUpdate bool) *snapshotRepository { + return &snapshotRepository{ + enableWaitGroup: enableUpdate, + wg: sync.WaitGroup{}, + cache: make(map[int32]entity.Snapshot), + } +} + +func (r *snapshotRepository) Wait() bool { + done := make(chan struct{}) + go func() { + r.wg.Wait() + close(done) + }() + select { + case <-done: + return true + case <-time.After(time.Second): + return false + } } func (r *snapshotRepository) GetByApplication(appId int32) (*entity.Snapshot, error) { - if limitState, ok := r.cache[appId]; ok { - return &entity.Snapshot{ - AppId: appId, - LimitState: limitState, - }, nil + if snapshot, ok := r.cache[appId]; ok { + return &snapshot, nil } else { return nil, nil } } func (r *snapshotRepository) Update(list []entity.Snapshot) error { + if r.enableWaitGroup { + r.wg.Add(1) + defer r.wg.Done() + } + for _, s := range list { - r.cache[s.AppId] = s.LimitState + r.cache[s.AppId] = s } return nil } diff --git a/accounting/snapshot.go b/accounting/snapshot.go index 6e63173..505f423 100644 --- a/accounting/snapshot.go +++ b/accounting/snapshot.go @@ -52,6 +52,6 @@ func (s *snapshotTask) Stop() { } func (s *snapshotTask) saveSnapshot() error { - snapshotList := takeSnapshot() + snapshotList := Worker.takeSnapshot() return model.SnapshotRep.Update(snapshotList) } diff --git a/handler/handler.go b/handler/handler.go index 4afb09d..94b98b6 100644 --- a/handler/handler.go +++ b/handler/handler.go @@ -88,7 +88,7 @@ func (handlerHelper) AuthenticateAccountingProxy(ctx *fasthttp.RequestCtx) domai return domain.Create().SetError(err) } - if !accounting.Accept(applicationId, path) { + if !accounting.Worker.AcceptRequest(applicationId, path) { err := errors.New("accounting error") utils.WriteError(ctx, "too many requests", codes.ResourceExhausted, nil) return domain.Create().SetError(err) diff --git a/main.go b/main.go index 2e992b5..5a935d7 100644 --- a/main.go +++ b/main.go @@ -45,7 +45,7 @@ func main() { bs.RequireModule(module, consumer, false) } - bs.RequireModule(cfg.ModuleName, accounting.Consumer, false). + bs.RequireModule(cfg.ModuleName, accounting.Worker.Consumer, false). OnShutdown(onShutdown). OnRemoteConfigReceive(onRemoteConfigReceive). Run() @@ -64,7 +64,7 @@ func onRemoteConfigReceive(remoteConfig, oldRemoteConfig *conf.RemoteConfig) { redis.Client.ReceiveConfiguration(remoteConfig.Redis) authenticate.ReceiveConfiguration(remoteConfig.AuthCacheSetting) - accounting.ReceiveConfiguration(remoteConfig.AccountingSetting) + accounting.Worker.ReceiveConfiguration(remoteConfig.AccountingSetting) metric.InitCollectors(remoteConfig.Metrics, oldRemoteConfig.Metrics) metric.InitHttpServer(remoteConfig.Metrics) @@ -88,7 +88,7 @@ func socketConfiguration(cfg interface{}) structure.SocketConfiguration { func onShutdown(_ context.Context, _ os.Signal) { server.Http.Close() - accounting.Close() + accounting.Worker.Close() proxy.Close() redis.Client.Close() } From 909a26eace9180e9036a7f4274b9b72c261f4088 Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Wed, 27 Nov 2019 15:28:36 +0300 Subject: [PATCH 5/9] refactoring --- accounting/accounting.go | 148 ++++++++++++++++------------------ accounting/accounting_test.go | 33 ++++---- accounting/snapshot.go | 2 +- handler/handler.go | 2 +- main.go | 6 +- 5 files changed, 90 insertions(+), 101 deletions(-) diff --git a/accounting/accounting.go b/accounting/accounting.go index da84642..29e6cd3 100644 --- a/accounting/accounting.go +++ b/accounting/accounting.go @@ -15,8 +15,7 @@ import ( "time" ) -var Worker = &worker{ - process: false, +var worker = &accountingWorker{ accountingStorage: make(map[int32]Accounting), requestsStoring: make(map[int32]bool), } @@ -27,33 +26,56 @@ type ( Snapshot() (map[string]state.Snapshot, int64) } - worker struct { - mx sync.RWMutex - process bool + accountingWorker struct { accountingStorage map[int32]Accounting requestsStoring map[int32]bool } ) -func (w *worker) Consumer(list []structure.AddressConfiguration) bool { +func NewConnectionConsumer(list []structure.AddressConfiguration) bool { accountingSetting := config.GetRemote().(*conf.RemoteConfig).AccountingSetting - w.ReceiveConfiguration(accountingSetting) + worker.init(accountingSetting) return true } -func (w *worker) ReceiveConfiguration(conf conf.Accounting) { - w.Close() +func ReceiveConfiguration(accountingSetting conf.Accounting) { + worker.init(accountingSetting) +} + +func AcceptRequest(appId int32, path string) bool { + if accouter, ok := worker.accountingStorage[appId]; ok { + ok := accouter.Accept(path) + if ok && worker.requestsStoring[appId] { + storage.TakeRequest(appId, path, time.Now()) + } + return ok + } else { + if worker.requestsStoring[appId] { + storage.TakeRequest(appId, path, time.Now()) + } + return true + } +} + +func Close() { + snapshot.Stop() + if storage != nil { + storage.Stop() + } +} + +func (w *accountingWorker) init(accountingSetting conf.Accounting) { + Close() newAccountingStorage := make(map[int32]Accounting) newRequestsStoring := make(map[int32]bool) - process := false - if conf.Enable { - if err := InitStoringTask(conf.Storing); err != nil { + if accountingSetting.Enable { + if err := InitStoringTask(accountingSetting.Storing); err != nil { log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err) } - for _, s := range conf.Setting { + for _, s := range accountingSetting.Setting { newRequestsStoring[s.ApplicationId] = s.EnableStoring limitStates, patternArray, err := state.InitLimitState(s.Limits) @@ -61,58 +83,22 @@ func (w *worker) ReceiveConfiguration(conf conf.Accounting) { log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err) } - version := w.recoveryAccounting(s.ApplicationId, limitStates) - - newAccountingStorage[s.ApplicationId] = &accountant{ - version: version, - matcher: matcher.NewCacheableMatcher(patternArray), - limitStates: limitStates, - mx: sync.Mutex{}, - } + accounting := w.recoveryAccounting(s.ApplicationId, limitStates, patternArray) + newAccountingStorage[s.ApplicationId] = accounting } - if snapshotTimeout, err := time.ParseDuration(conf.SnapshotTimeout); err != nil { + if snapshotTimeout, err := time.ParseDuration(accountingSetting.SnapshotTimeout); err != nil { log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err) } else { go snapshot.Start(snapshotTimeout) } - - process = true } - w.mx.Lock() w.requestsStoring = newRequestsStoring w.accountingStorage = newAccountingStorage - w.process = process - w.mx.Unlock() } -func (w *worker) AcceptRequest(appId int32, path string) bool { - w.mx.RLock() - defer w.mx.RUnlock() - if accouter, ok := w.accountingStorage[appId]; !ok { - if w.requestsStoring[appId] { - storage.TakeRequest(appId, path, time.Now()) - } - return true - } else { - ok := accouter.Accept(path) - if ok && w.requestsStoring[appId] { - storage.TakeRequest(appId, path, time.Now()) - } - return ok - } -} - -func (w *worker) Close() { - snapshot.Stop() - if storage != nil { - storage.Stop() - } -} - -func (w *worker) takeSnapshot() []entity.Snapshot { - w.mx.RLock() +func (w *accountingWorker) takeSnapshot() []entity.Snapshot { response := make([]entity.Snapshot, 0, len(w.accountingStorage)) for appId, account := range w.accountingStorage { @@ -124,40 +110,44 @@ func (w *worker) takeSnapshot() []entity.Snapshot { Version: version, }) } - w.mx.RUnlock() return response } -func (w *worker) recoveryAccounting(appId int32, limitStates map[string]state.LimitState) int64 { - version := int64(0) - w.mx.RLock() - if w.process { - if acc, ok := w.accountingStorage[appId]; ok { - cashLimitState, cashVersion := acc.Snapshot() - dbSnapshot, err := model.SnapshotRep.GetByApplication(appId) - if err != nil { - log.Warn(log_code.ErrorSnapshotAccounting, err) - } +func (w *accountingWorker) recoveryAccounting(appId int32, limitStates map[string]state.LimitState, patternArray []string) *accountant { + var ( + version = int64(0) + importNotComplete = true + ) - if dbSnapshot != nil && dbSnapshot.Version > cashVersion { - w.importLimitState(limitStates, dbSnapshot.LimitState) - } else { - w.importLimitState(limitStates, cashLimitState) - } - } - } else { - if snapshot, err := model.SnapshotRep.GetByApplication(appId); err != nil { - log.Warn(log_code.ErrorSnapshotAccounting, err) - } else if snapshot != nil { - version = snapshot.Version - w.importLimitState(limitStates, snapshot.LimitState) + dbSnapshot, err := model.SnapshotRep.GetByApplication(appId) + if err != nil { + log.Warn(log_code.ErrorSnapshotAccounting, err) + } + + if cash, ok := w.accountingStorage[appId]; ok { + cashLimitState, cashVersion := cash.Snapshot() + + if dbSnapshot != nil && dbSnapshot.Version < cashVersion { + version = cashVersion + w.importLimitState(limitStates, cashLimitState) + importNotComplete = false } } - w.mx.RUnlock() - return version + + if dbSnapshot != nil && importNotComplete { + version = dbSnapshot.Version + w.importLimitState(limitStates, dbSnapshot.LimitState) + } + + return &accountant{ + mx: sync.Mutex{}, + matcher: matcher.NewCacheableMatcher(patternArray), + limitStates: limitStates, + version: version, + } } -func (w *worker) importLimitState(limitStates map[string]state.LimitState, snapshot map[string]state.Snapshot) { +func (w *accountingWorker) importLimitState(limitStates map[string]state.LimitState, snapshot map[string]state.Snapshot) { for method, limitState := range limitStates { if oldState, ok := snapshot[method]; ok { limitState.Import(oldState) diff --git a/accounting/accounting_test.go b/accounting/accounting_test.go index 664151c..e0f62f2 100644 --- a/accounting/accounting_test.go +++ b/accounting/accounting_test.go @@ -64,17 +64,17 @@ var ( func TestAccounting(t *testing.T) { a := assert.New(t) model.SnapshotRep = newSnapshotRepository(false) - Worker.ReceiveConfiguration(accountingSetting) + ReceiveConfiguration(accountingSetting) req := reqExample[4] for _, path := range req.path { - a.True(Worker.AcceptRequest(req.appId, path)) + a.True(AcceptRequest(req.appId, path)) } expected := true req = reqExample[0] for _, path := range req.path { - a.Equal(expected, Worker.AcceptRequest(req.appId, path)) + a.Equal(expected, AcceptRequest(req.appId, path)) expected = !expected time.Sleep(50 * time.Millisecond) } @@ -82,27 +82,27 @@ func TestAccounting(t *testing.T) { //expected == true req = reqExample[1] for _, path := range req.path { - a.Equal(expected, Worker.AcceptRequest(req.appId, path)) + a.Equal(expected, AcceptRequest(req.appId, path)) expected = !expected } req = reqExample[2] expectedArray := []bool{true, true, true, true, true, false} for key, path := range req.path { - a.Equal(expectedArray[key], Worker.AcceptRequest(req.appId, path)) + a.Equal(expectedArray[key], AcceptRequest(req.appId, path)) } //expected == true req = reqExample[3] for _, path := range req.path { - a.Equal(expected, Worker.AcceptRequest(req.appId, path)) + a.Equal(expected, AcceptRequest(req.appId, path)) } - Worker.ReceiveConfiguration(accountingSetting) + ReceiveConfiguration(accountingSetting) req = reqExample[4] for _, path := range req.path { - a.False(Worker.AcceptRequest(req.appId, path)) + a.False(AcceptRequest(req.appId, path)) } } @@ -111,20 +111,19 @@ func TestWorker_recoveryAccounting(t *testing.T) { snapshotRep := newSnapshotRepository(true) model.SnapshotRep = snapshotRep - oldWorker := &worker{ - process: false, + oldWorker := &accountingWorker{ accountingStorage: make(map[int32]Accounting), requestsStoring: make(map[int32]bool), } - Worker.ReceiveConfiguration(accountingSetting) - oldWorker.ReceiveConfiguration(accountingSetting) + worker.init(accountingSetting) + oldWorker.init(accountingSetting) request := "1_3_5" for range request { - a.True(Worker.AcceptRequest(1, "mdm-master/group6/method")) + a.True(AcceptRequest(1, "mdm-master/group6/method")) } - a.False(Worker.AcceptRequest(1, "mdm-master/group6/method")) + a.False(AcceptRequest(1, "mdm-master/group6/method")) time.Sleep(time.Millisecond * 300) a.True(snapshotRep.Wait()) @@ -133,9 +132,9 @@ func TestWorker_recoveryAccounting(t *testing.T) { a.NotNil(snapshot) a.Equal(len(request), int(snapshot.Version)) - Worker = oldWorker - Worker.ReceiveConfiguration(accountingSetting) - a.False(Worker.AcceptRequest(1, "mdm-master/group6/method")) + worker = oldWorker + ReceiveConfiguration(accountingSetting) + a.False(AcceptRequest(1, "mdm-master/group6/method")) } type snapshotRepository struct { diff --git a/accounting/snapshot.go b/accounting/snapshot.go index 505f423..a5d4f5c 100644 --- a/accounting/snapshot.go +++ b/accounting/snapshot.go @@ -52,6 +52,6 @@ func (s *snapshotTask) Stop() { } func (s *snapshotTask) saveSnapshot() error { - snapshotList := Worker.takeSnapshot() + snapshotList := worker.takeSnapshot() return model.SnapshotRep.Update(snapshotList) } diff --git a/handler/handler.go b/handler/handler.go index 94b98b6..4468a9d 100644 --- a/handler/handler.go +++ b/handler/handler.go @@ -88,7 +88,7 @@ func (handlerHelper) AuthenticateAccountingProxy(ctx *fasthttp.RequestCtx) domai return domain.Create().SetError(err) } - if !accounting.Worker.AcceptRequest(applicationId, path) { + if !accounting.AcceptRequest(applicationId, path) { err := errors.New("accounting error") utils.WriteError(ctx, "too many requests", codes.ResourceExhausted, nil) return domain.Create().SetError(err) diff --git a/main.go b/main.go index 5a935d7..5b203c8 100644 --- a/main.go +++ b/main.go @@ -45,7 +45,7 @@ func main() { bs.RequireModule(module, consumer, false) } - bs.RequireModule(cfg.ModuleName, accounting.Worker.Consumer, false). + bs.RequireModule(cfg.ModuleName, accounting.NewConnectionConsumer, false). OnShutdown(onShutdown). OnRemoteConfigReceive(onRemoteConfigReceive). Run() @@ -64,7 +64,7 @@ func onRemoteConfigReceive(remoteConfig, oldRemoteConfig *conf.RemoteConfig) { redis.Client.ReceiveConfiguration(remoteConfig.Redis) authenticate.ReceiveConfiguration(remoteConfig.AuthCacheSetting) - accounting.Worker.ReceiveConfiguration(remoteConfig.AccountingSetting) + accounting.ReceiveConfiguration(remoteConfig.AccountingSetting) metric.InitCollectors(remoteConfig.Metrics, oldRemoteConfig.Metrics) metric.InitHttpServer(remoteConfig.Metrics) @@ -88,7 +88,7 @@ func socketConfiguration(cfg interface{}) structure.SocketConfiguration { func onShutdown(_ context.Context, _ os.Signal) { server.Http.Close() - accounting.Worker.Close() + accounting.Close() proxy.Close() redis.Client.Close() } From a3415470f7b7a96cd5cdb6c9e20ccac9043c64bd Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Wed, 27 Nov 2019 18:42:35 +0300 Subject: [PATCH 6/9] ref --- accounting/accounting.go | 2 +- accounting/accounting_test.go | 33 +++++++++++++++++++-------------- 2 files changed, 20 insertions(+), 15 deletions(-) diff --git a/accounting/accounting.go b/accounting/accounting.go index 29e6cd3..534f9b7 100644 --- a/accounting/accounting.go +++ b/accounting/accounting.go @@ -127,7 +127,7 @@ func (w *accountingWorker) recoveryAccounting(appId int32, limitStates map[strin if cash, ok := w.accountingStorage[appId]; ok { cashLimitState, cashVersion := cash.Snapshot() - if dbSnapshot != nil && dbSnapshot.Version < cashVersion { + if dbSnapshot == nil || dbSnapshot.Version < cashVersion { version = cashVersion w.importLimitState(limitStates, cashLimitState) importNotComplete = false diff --git a/accounting/accounting_test.go b/accounting/accounting_test.go index e0f62f2..d6295fb 100644 --- a/accounting/accounting_test.go +++ b/accounting/accounting_test.go @@ -26,6 +26,9 @@ var ( {ApplicationId: 2, Limits: []conf.LimitSetting{ {Pattern: "mdm-master/group/method", MaxCount: 0, Timeout: "10s"}, }}, + {ApplicationId: 3, Limits: []conf.LimitSetting{ + {Pattern: "mdm-master/group6/method", MaxCount: 5, Timeout: "10s"}, + }}, }, Storing: conf.StoringSetting{ Size: 100, @@ -63,8 +66,9 @@ var ( func TestAccounting(t *testing.T) { a := assert.New(t) - model.SnapshotRep = newSnapshotRepository(false) - ReceiveConfiguration(accountingSetting) + snapshotRep := newSnapshotRepository(true) + model.SnapshotRep = snapshotRep + worker.init(accountingSetting) req := reqExample[4] for _, path := range req.path { @@ -98,7 +102,7 @@ func TestAccounting(t *testing.T) { a.Equal(expected, AcceptRequest(req.appId, path)) } - ReceiveConfiguration(accountingSetting) + worker.init(accountingSetting) req = reqExample[4] for _, path := range req.path { @@ -119,22 +123,24 @@ func TestWorker_recoveryAccounting(t *testing.T) { worker.init(accountingSetting) oldWorker.init(accountingSetting) + appId := int32(3) request := "1_3_5" for range request { - a.True(AcceptRequest(1, "mdm-master/group6/method")) + a.True(AcceptRequest(appId, "mdm-master/group6/method")) } - a.False(AcceptRequest(1, "mdm-master/group6/method")) + a.False(AcceptRequest(appId, "mdm-master/group6/method")) time.Sleep(time.Millisecond * 300) a.True(snapshotRep.Wait()) - snapshot, err := model.SnapshotRep.GetByApplication(1) + snapshot, err := model.SnapshotRep.GetByApplication(appId) a.NoError(err) a.NotNil(snapshot) a.Equal(len(request), int(snapshot.Version)) + Close() worker = oldWorker - ReceiveConfiguration(accountingSetting) - a.False(AcceptRequest(1, "mdm-master/group6/method")) + worker.init(accountingSetting) + a.False(AcceptRequest(appId, "mdm-master/group6/method")) } type snapshotRepository struct { @@ -143,12 +149,11 @@ type snapshotRepository struct { cache map[int32]entity.Snapshot } -func newSnapshotRepository(enableUpdate bool) *snapshotRepository { - return &snapshotRepository{ - enableWaitGroup: enableUpdate, - wg: sync.WaitGroup{}, - cache: make(map[int32]entity.Snapshot), - } +func newSnapshotRepository(enableWaitGroup bool) *snapshotRepository { + resp := new(snapshotRepository) + resp.enableWaitGroup = enableWaitGroup + resp.cache = make(map[int32]entity.Snapshot) + return resp } func (r *snapshotRepository) Wait() bool { From 5a462ef158bcb831110acbcc15833200cecb2050 Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Thu, 28 Nov 2019 12:01:28 +0300 Subject: [PATCH 7/9] fix snapshot recovery --- accounting/accounting.go | 29 ++++------- accounting/accounting_test.go | 30 ++++++----- accounting/snapshot.go | 77 ++++++++++++++++++---------- accounting/state/limit_state.go | 10 ++-- accounting/storing.go | 89 +++++++++++++++++---------------- accounting/storing_test.go | 18 +++---- 6 files changed, 136 insertions(+), 117 deletions(-) diff --git a/accounting/accounting.go b/accounting/accounting.go index 534f9b7..b5d9469 100644 --- a/accounting/accounting.go +++ b/accounting/accounting.go @@ -4,7 +4,6 @@ import ( "github.com/integration-system/isp-lib/config" "github.com/integration-system/isp-lib/structure" log "github.com/integration-system/isp-log" - "github.com/integration-system/isp-log/stdcodes" "isp-gate-service/accounting/state" "isp-gate-service/conf" "isp-gate-service/entity" @@ -58,7 +57,9 @@ func AcceptRequest(appId int32, path string) bool { } func Close() { - snapshot.Stop() + if snapshot != nil { + snapshot.Stop() + } if storage != nil { storage.Stop() } @@ -68,33 +69,23 @@ func (w *accountingWorker) init(accountingSetting conf.Accounting) { Close() newAccountingStorage := make(map[int32]Accounting) - newRequestsStoring := make(map[int32]bool) + newRequestsStoringStorage := make(map[int32]bool) if accountingSetting.Enable { - if err := InitStoringTask(accountingSetting.Storing); err != nil { - log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err) - } + InitStoringTask(accountingSetting.Storing) for _, s := range accountingSetting.Setting { - newRequestsStoring[s.ApplicationId] = s.EnableStoring - - limitStates, patternArray, err := state.InitLimitState(s.Limits) - if err != nil { - log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err) - } - + limitStates, patternArray := state.InitLimitState(s.Limits) accounting := w.recoveryAccounting(s.ApplicationId, limitStates, patternArray) + newAccountingStorage[s.ApplicationId] = accounting + newRequestsStoringStorage[s.ApplicationId] = s.EnableStoring } - if snapshotTimeout, err := time.ParseDuration(accountingSetting.SnapshotTimeout); err != nil { - log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err) - } else { - go snapshot.Start(snapshotTimeout) - } + InitSnapshotTask(accountingSetting.SnapshotTimeout) } - w.requestsStoring = newRequestsStoring + w.requestsStoring = newRequestsStoringStorage w.accountingStorage = newAccountingStorage } diff --git a/accounting/accounting_test.go b/accounting/accounting_test.go index d6295fb..4689ad8 100644 --- a/accounting/accounting_test.go +++ b/accounting/accounting_test.go @@ -26,9 +26,6 @@ var ( {ApplicationId: 2, Limits: []conf.LimitSetting{ {Pattern: "mdm-master/group/method", MaxCount: 0, Timeout: "10s"}, }}, - {ApplicationId: 3, Limits: []conf.LimitSetting{ - {Pattern: "mdm-master/group6/method", MaxCount: 5, Timeout: "10s"}, - }}, }, Storing: conf.StoringSetting{ Size: 100, @@ -66,8 +63,12 @@ var ( func TestAccounting(t *testing.T) { a := assert.New(t) - snapshotRep := newSnapshotRepository(true) + snapshotRep := newSnapshotRepository(false) model.SnapshotRep = snapshotRep + worker = &accountingWorker{ + accountingStorage: make(map[int32]Accounting), + requestsStoring: make(map[int32]bool), + } worker.init(accountingSetting) req := reqExample[4] @@ -115,15 +116,19 @@ func TestWorker_recoveryAccounting(t *testing.T) { snapshotRep := newSnapshotRepository(true) model.SnapshotRep = snapshotRep - oldWorker := &accountingWorker{ + worker = &accountingWorker{ + accountingStorage: make(map[int32]Accounting), + requestsStoring: make(map[int32]bool), + } + secondWorker := &accountingWorker{ accountingStorage: make(map[int32]Accounting), requestsStoring: make(map[int32]bool), } worker.init(accountingSetting) - oldWorker.init(accountingSetting) + secondWorker.init(accountingSetting) - appId := int32(3) + appId := int32(1) request := "1_3_5" for range request { a.True(AcceptRequest(appId, "mdm-master/group6/method")) @@ -138,7 +143,7 @@ func TestWorker_recoveryAccounting(t *testing.T) { a.Equal(len(request), int(snapshot.Version)) Close() - worker = oldWorker + worker = secondWorker worker.init(accountingSetting) a.False(AcceptRequest(appId, "mdm-master/group6/method")) } @@ -150,10 +155,11 @@ type snapshotRepository struct { } func newSnapshotRepository(enableWaitGroup bool) *snapshotRepository { - resp := new(snapshotRepository) - resp.enableWaitGroup = enableWaitGroup - resp.cache = make(map[int32]entity.Snapshot) - return resp + return &snapshotRepository{ + enableWaitGroup: enableWaitGroup, + wg: sync.WaitGroup{}, + cache: make(map[int32]entity.Snapshot), + } } func (r *snapshotRepository) Wait() bool { diff --git a/accounting/snapshot.go b/accounting/snapshot.go index a5d4f5c..73b9a34 100644 --- a/accounting/snapshot.go +++ b/accounting/snapshot.go @@ -2,56 +2,79 @@ package accounting import ( log "github.com/integration-system/isp-log" + "github.com/integration-system/isp-log/stdcodes" + "isp-gate-service/entity" "isp-gate-service/log_code" "isp-gate-service/model" "sync" "time" ) -var snapshot = &snapshotTask{ - process: false, - timeout: make(chan time.Time), - close: make(chan bool), -} +var snapshot *snapshotTask type snapshotTask struct { - mx sync.Mutex + mx sync.Mutex + wg sync.WaitGroup + process bool timeout <-chan time.Time close chan bool } -func (s *snapshotTask) Start(timeout time.Duration) { - s.Stop() +func InitSnapshotTask(snapshotTimeout string) { + timeout, err := time.ParseDuration(snapshotTimeout) + if err != nil { + log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err) + } - s.mx.Lock() - s.process = true - s.timeout = time.After(timeout) - s.mx.Unlock() + snapshot = newSnapshotTask(timeout) +} +func (t *snapshotTask) Stop() { + t.mx.Lock() + if t.process { + snapshotList := worker.takeSnapshot() + defer func() { + t.unload(snapshotList) + t.wg.Wait() + }() + t.process = false + t.close <- true + } + t.mx.Unlock() +} + +func (t *snapshotTask) run(timeout time.Duration) { + defer t.wg.Done() + t.timeout = time.After(timeout) for { select { - case <-s.close: + case <-t.close: return - case <-s.timeout: - if err := s.saveSnapshot(); err != nil { - log.Error(log_code.ErrorSnapshotAccounting, err) - } - s.timeout = time.After(timeout) + case <-t.timeout: + list := worker.takeSnapshot() + go t.unload(list) + t.timeout = time.After(timeout) } } } -func (s *snapshotTask) Stop() { - s.mx.Lock() - if s.process { - s.process = false - s.close <- true +func (t *snapshotTask) unload(list []entity.Snapshot) { + t.wg.Add(1) + if err := model.SnapshotRep.Update(list); err != nil { + log.Error(log_code.ErrorSnapshotAccounting, err) } - s.mx.Unlock() + t.wg.Done() } -func (s *snapshotTask) saveSnapshot() error { - snapshotList := worker.takeSnapshot() - return model.SnapshotRep.Update(snapshotList) +func newSnapshotTask(timeout time.Duration) *snapshotTask { + task := &snapshotTask{ + process: true, + timeout: make(chan time.Time), + close: make(chan bool), + } + + task.wg.Add(1) + go task.run(timeout) + return task } diff --git a/accounting/state/limit_state.go b/accounting/state/limit_state.go index 7d4acaf..4995553 100644 --- a/accounting/state/limit_state.go +++ b/accounting/state/limit_state.go @@ -1,6 +1,8 @@ package state import ( + log "github.com/integration-system/isp-log" + "github.com/integration-system/isp-log/stdcodes" "isp-gate-service/conf" "time" ) @@ -26,19 +28,19 @@ type ( } ) -func InitLimitState(limits []conf.LimitSetting) (map[string]LimitState, []string, error) { +func InitLimitState(limits []conf.LimitSetting) (map[string]LimitState, []string) { limitStates := make(map[string]LimitState) patternArray := make([]string, len(limits)) for i, limit := range limits { timeout, err := time.ParseDuration(limit.Timeout) if err != nil { - return nil, nil, err + log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err) } + if timeout == 0 && limit.MaxCount != 0 { limit.MaxCount = 1 } - patternArray[i] = limit.Pattern limitStates[limit.Pattern] = &limiter{ timeout: timeout, @@ -47,7 +49,7 @@ func InitLimitState(limits []conf.LimitSetting) (map[string]LimitState, []string pointer: -1, } } - return limitStates, patternArray, nil + return limitStates, patternArray } func Update(states []LimitState) bool { diff --git a/accounting/storing.go b/accounting/storing.go index 859c953..881cf02 100644 --- a/accounting/storing.go +++ b/accounting/storing.go @@ -2,6 +2,7 @@ package accounting import ( log "github.com/integration-system/isp-log" + "github.com/integration-system/isp-log/stdcodes" "isp-gate-service/conf" "isp-gate-service/entity" "isp-gate-service/log_code" @@ -25,88 +26,88 @@ type storingTask struct { wg sync.WaitGroup } -func InitStoringTask(setting conf.StoringSetting) error { +func InitStoringTask(setting conf.StoringSetting) { timeout, err := time.ParseDuration(setting.Timeout) if err != nil { - return err + log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err) } storage = newStoringTask(timeout, setting.Size) - - return nil } -func (u *storingTask) TakeRequest(appId int32, method string, date time.Time) { - u.mx.Lock() - if !u.process { - u.mx.Unlock() +func (t *storingTask) TakeRequest(appId int32, method string, date time.Time) { + t.mx.Lock() + if !t.process { + t.mx.Unlock() return } - u.buffer[u.counter] = entity.Request{ + t.buffer[t.counter] = entity.Request{ AppId: appId, Method: method, CreatedAt: date, } - u.counter++ - if u.counter == len(u.buffer) { - u.chanCounter <- u.buffer - u.clearBuffer() + t.counter++ + if t.counter == len(t.buffer) { + t.chanCounter <- t.buffer + t.clearBuffer() } - u.mx.Unlock() + t.mx.Unlock() } -func (u *storingTask) Stop() { - u.mx.Lock() - if u.process { - if u.counter != 0 { - buffer := u.clearBuffer() +func (t *storingTask) Stop() { + t.mx.Lock() + if t.process { + if t.counter != 0 { + buffer := t.clearBuffer() defer func() { - u.unload(buffer) - u.wg.Wait() + t.unload(buffer) + t.wg.Wait() }() } - u.chanClose <- true - u.process = false + t.chanClose <- true + t.process = false } - u.mx.Unlock() + t.mx.Unlock() } -func (u *storingTask) run(timeout time.Duration) { - defer u.wg.Done() - u.chanTimeout = time.After(timeout) +func (t *storingTask) run(timeout time.Duration) { + defer t.wg.Done() + t.chanTimeout = time.After(timeout) for { select { - case <-u.chanClose: + case <-t.chanClose: return - case cache := <-u.chanCounter: - go u.unload(cache) - u.chanTimeout = time.After(timeout) - case <-u.chanTimeout: - u.mx.Lock() - if u.counter != 0 { - buffer := u.clearBuffer() - go u.unload(buffer) + case cache := <-t.chanCounter: + go t.unload(cache) + t.chanTimeout = time.After(timeout) + case <-t.chanTimeout: + t.mx.Lock() + if t.counter != 0 { + buffer := t.clearBuffer() + go t.unload(buffer) } - u.mx.Unlock() - u.chanTimeout = time.After(timeout) + t.mx.Unlock() + t.chanTimeout = time.After(timeout) } } } -func (u *storingTask) unload(cache []entity.Request) { +func (t *storingTask) unload(cache []entity.Request) { + t.wg.Add(1) if err := model.RequestsRep.Insert(cache); err != nil { log.Error(log_code.ErrorUnloadAccounting, err) } + t.wg.Done() } -func (u *storingTask) clearBuffer() []entity.Request { - oldBuffer := u.buffer[:u.counter] - oldLen := len(u.buffer) - u.counter = 0 - u.buffer = make([]entity.Request, oldLen) +func (t *storingTask) clearBuffer() []entity.Request { + oldBuffer := t.buffer[:t.counter] + oldLen := len(t.buffer) + t.counter = 0 + t.buffer = make([]entity.Request, oldLen) return oldBuffer } diff --git a/accounting/storing_test.go b/accounting/storing_test.go index 29e297b..f791002 100644 --- a/accounting/storing_test.go +++ b/accounting/storing_test.go @@ -27,11 +27,11 @@ var ( } ) -func initStoring(setting conf.StoringSetting) (*requestsRepository, error) { +func initStoring(setting conf.StoringSetting) *requestsRepository { repository := &requestsRepository{cache: make([]entity.Request, 0), wg: &sync.WaitGroup{}} model.RequestsRep = repository - err := InitStoringTask(setting) - return repository, err + InitStoringTask(setting) + return repository } func wait(wg *sync.WaitGroup) bool { @@ -50,8 +50,7 @@ func wait(wg *sync.WaitGroup) bool { func TestStoringTask_Stop(t *testing.T) { a := assert.New(t) - rep, err := initStoring(bufferSetting) - a.NoError(err) + rep := initStoring(bufferSetting) rep.wg.Add(2) for i, j := range []string{"Stop_1", "Stop_2", "Stop_3", "Stop_4", "Stop_5"} { @@ -63,8 +62,7 @@ func TestStoringTask_Stop(t *testing.T) { func TestStoringTask_Buffer(t *testing.T) { a := assert.New(t) - rep, err := initStoring(bufferSetting) - a.NoError(err) + rep := initStoring(bufferSetting) rep.wg.Add(1) for i, j := range []string{"Buffer_1", "Buffer_2", "Buffer_3", "Buffer_4", "Buffer_5"} { @@ -76,8 +74,7 @@ func TestStoringTask_Buffer(t *testing.T) { func TestStoringTask_Timeout(t *testing.T) { a := assert.New(t) - rep, err := initStoring(timeoutSetting) - a.NoError(err) + rep := initStoring(timeoutSetting) rep.wg.Add(1) for i, j := range []string{"Timeout_1", "Timeout_2"} { @@ -89,8 +86,7 @@ func TestStoringTask_Timeout(t *testing.T) { func TestStoringTask_Unload(t *testing.T) { a := assert.New(t) - rep, err := initStoring(unloadSetting) - a.NoError(err) + rep := initStoring(unloadSetting) rep.wg.Add(2) for i, j := range []string{"Unload_1", "Unload_2", "Unload_3", "Unload_4", "Unload_5"} { From 6e1770273e929df0e91cccbe0521a9d0a6c8b7ac Mon Sep 17 00:00:00 2001 From: ykomissarov Date: Thu, 28 Nov 2019 12:23:03 +0300 Subject: [PATCH 8/9] ref --- accounting/snapshot.go | 17 +++++++++++------ accounting/storing.go | 4 +++- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/accounting/snapshot.go b/accounting/snapshot.go index 73b9a34..4ba4e89 100644 --- a/accounting/snapshot.go +++ b/accounting/snapshot.go @@ -34,10 +34,13 @@ func (t *snapshotTask) Stop() { t.mx.Lock() if t.process { snapshotList := worker.takeSnapshot() - defer func() { - t.unload(snapshotList) - t.wg.Wait() - }() + if len(snapshotList) != 0 { + defer func() { + t.wg.Add(1) + t.unload(snapshotList) + t.wg.Wait() + }() + } t.process = false t.close <- true } @@ -53,14 +56,16 @@ func (t *snapshotTask) run(timeout time.Duration) { return case <-t.timeout: list := worker.takeSnapshot() - go t.unload(list) + if len(list) > 0 { + t.wg.Add(1) + go t.unload(list) + } t.timeout = time.After(timeout) } } } func (t *snapshotTask) unload(list []entity.Snapshot) { - t.wg.Add(1) if err := model.SnapshotRep.Update(list); err != nil { log.Error(log_code.ErrorSnapshotAccounting, err) } diff --git a/accounting/storing.go b/accounting/storing.go index 881cf02..1beb3eb 100644 --- a/accounting/storing.go +++ b/accounting/storing.go @@ -63,6 +63,7 @@ func (t *storingTask) Stop() { if t.counter != 0 { buffer := t.clearBuffer() defer func() { + t.wg.Add(1) t.unload(buffer) t.wg.Wait() }() @@ -81,12 +82,14 @@ func (t *storingTask) run(timeout time.Duration) { case <-t.chanClose: return case cache := <-t.chanCounter: + t.wg.Add(1) go t.unload(cache) t.chanTimeout = time.After(timeout) case <-t.chanTimeout: t.mx.Lock() if t.counter != 0 { buffer := t.clearBuffer() + t.wg.Add(1) go t.unload(buffer) } t.mx.Unlock() @@ -96,7 +99,6 @@ func (t *storingTask) run(timeout time.Duration) { } func (t *storingTask) unload(cache []entity.Request) { - t.wg.Add(1) if err := model.RequestsRep.Insert(cache); err != nil { log.Error(log_code.ErrorUnloadAccounting, err) } From ed91071557b774601563992d0f9ea348ddde88bb Mon Sep 17 00:00:00 2001 From: ykomissarov Date: Thu, 28 Nov 2019 12:27:36 +0300 Subject: [PATCH 9/9] remove atomic --- accounting/accountant.go | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/accounting/accountant.go b/accounting/accountant.go index 8c07950..fec042d 100644 --- a/accounting/accountant.go +++ b/accounting/accountant.go @@ -4,7 +4,6 @@ import ( "isp-gate-service/accounting/state" "isp-gate-service/service/matcher" "sync" - "sync/atomic" ) type accountant struct { @@ -24,7 +23,7 @@ func (app *accountant) Accept(method string) bool { app.mx.Lock() resp := state.Update(stateStorage) if resp { - atomic.AddInt64(&app.version, 1) + app.version++ } app.mx.Unlock() return resp @@ -32,7 +31,7 @@ func (app *accountant) Accept(method string) bool { func (app *accountant) Snapshot() (map[string]state.Snapshot, int64) { app.mx.Lock() - version := atomic.LoadInt64(&app.version) + version := app.version snapshotLimitState := make(map[string]state.Snapshot, len(app.limitStates)) for method, limitState := range app.limitStates { snapshotLimitState[method] = limitState.Export()