From 4c7e96813c49936f3408a622ac267688729a0103 Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Tue, 26 Nov 2019 12:11:13 +0300 Subject: [PATCH] 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() {