From 4d81fe7a265d241746a6f5cd21d70c59c755e402 Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Mon, 18 Nov 2019 15:48:50 +0300 Subject: [PATCH] add accounting snapshot --- CHANGELOG.md | 2 + accounting/accounting.go | 6 +-- accounting/accounting_test.go | 41 ++++++++++++++----- accounting/snapshot.go | 16 ++++---- accounting/state/limit_state.go | 11 ++++- accounting/state/limiter.go | 23 +++++++---- accounting/state/limiter_test.go | 6 +-- entity/entity.go | 4 +- handler/handler.go | 6 +-- ...-14_init.sql => 00001_2019-11-14_init.sql} | 4 +- 10 files changed, 74 insertions(+), 45 deletions(-) rename migrations/{00002_2019-11-14_init.sql => 00001_2019-11-14_init.sql} (85%) diff --git a/CHANGELOG.md b/CHANGELOG.md index a29424f..e9977b3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,5 @@ +## 1.2.0 +* add snapshot account ## 1.1.0 * add token verification via JWT * add accounting for applications diff --git a/accounting/accounting.go b/accounting/accounting.go index a9c6d82..3c9bd5d 100644 --- a/accounting/accounting.go +++ b/accounting/accounting.go @@ -34,10 +34,8 @@ func ReceiveConfiguration(conf conf.Accounting) { log.Warn(log_code.ErrorSnapshotAccounting, err) } else if snapshot != nil { for method, limitState := range limitStates { - if oldLimitState, ok := snapshot.LimitState[method]; ok { - if err := limitState.Import(oldLimitState); err != nil { - log.Warn(log_code.ErrorSnapshotAccounting, err) - } + if value, ok := snapshot.LimitState[method]; ok { + limitState.Import(value) } } } diff --git a/accounting/accounting_test.go b/accounting/accounting_test.go index 92aaed0..6ecf500 100644 --- a/accounting/accounting_test.go +++ b/accounting/accounting_test.go @@ -2,6 +2,7 @@ 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" @@ -10,15 +11,16 @@ import ( ) var ( - approveSetting = conf.Accounting{ + accountingSetting = conf.Accounting{ Enable: true, - SnapshotTimeout: "2s", + SnapshotTimeout: "890ms", Setting: []conf.AccountingSetting{ {ApplicationId: 1, Limits: []conf.LimitSetting{ {Pattern: "mdm-master/group/method", MaxCount: 1, Timeout: "290ms"}, {Pattern: "mdm-master/group3/method", MaxCount: 10, Timeout: "10s"}, {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"}, }}, {ApplicationId: 2, Limits: []conf.LimitSetting{ {Pattern: "mdm-master/group/method", MaxCount: 0, Timeout: "10s"}, @@ -48,13 +50,16 @@ var ( "mdm-master/group4/method", "mdm-master/group4/method", "mdm-master/group4/method", "mdm-master/group4/method", "mdm-master/group4/method", "mdm-master/group4/method", }}, + 4: {appId: 1, path: []string{ + "mdm-master/group5/method", "mdm-master/group5/method", "mdm-master/group5/method", + }}, } ) -func TestApprove(t *testing.T) { +func TestAccounting(t *testing.T) { a := assert.New(t) - ReceiveConfiguration(approveSetting) - model.SnapshotRep = &snapshotRepository{cache: make(map[int32]map[string]interface{})} + model.SnapshotRep = &snapshotRepository{cache: make(map[int32]map[string]state.Snapshot)} + ReceiveConfiguration(accountingSetting) expected := true req := reqExample[0] @@ -82,17 +87,33 @@ func TestApprove(t *testing.T) { for _, path := range req.path { a.Equal(expected, GetAccounting(req.appId).Check(path)) } + + req = reqExample[4] + for _, path := range req.path { + a.True(GetAccounting(req.appId).Check(path)) + } + + ReceiveConfiguration(accountingSetting) + + for _, path := range req.path { + a.False(GetAccounting(req.appId).Check(path)) + } + } type snapshotRepository struct { - cache map[int32]map[string]interface{} + cache map[int32]map[string]state.Snapshot } func (r *snapshotRepository) GetByApplication(appId int32) (*entity.Snapshot, error) { - return &entity.Snapshot{ - AppId: appId, - LimitState: r.cache[appId], - }, nil + if limitState, ok := r.cache[appId]; ok { + return &entity.Snapshot{ + AppId: appId, + LimitState: limitState, + }, nil + } else { + return nil, nil + } } func (r *snapshotRepository) Update(list []entity.Snapshot) error { diff --git a/accounting/snapshot.go b/accounting/snapshot.go index 27b916c..33e80ae 100644 --- a/accounting/snapshot.go +++ b/accounting/snapshot.go @@ -2,6 +2,7 @@ package accounting import ( log "github.com/integration-system/isp-log" + "isp-gate-service/accounting/state" "isp-gate-service/entity" "isp-gate-service/log_code" "isp-gate-service/model" @@ -23,26 +24,23 @@ type snapshotStruct struct { } func (s *snapshotStruct) Start(timeout time.Duration) { - if s.process { - s.close <- true - s.wg.Wait() - } - + s.Stop() s.process = true - s.wg.Add(1) s.timeout = time.After(timeout) for { select { case <-s.close: - s.wg.Done() + s.wg.Wait() return case <-s.timeout: + s.wg.Add(1) applicationAccounting := accountingByApplicationId if err := s.complete(applicationAccounting); err != nil { log.Error(log_code.ErrorSnapshotAccounting, err) } s.timeout = time.After(timeout) + s.wg.Done() } } } @@ -51,14 +49,14 @@ func (s *snapshotStruct) Stop() { if s.process { s.process = false s.close <- true - s.wg.Wait() } + s.wg.Wait() } func (s *snapshotStruct) complete(applicationAccounting map[int32]Accounting) error { snapshot := make([]entity.Snapshot, 0) for application, account := range applicationAccounting { - snapshotLimitState := make(map[string]interface{}) + snapshotLimitState := make(map[string]state.Snapshot) limitStates := account.getLimitState() for method, limitState := range limitStates { snapshotLimitState[method] = limitState.Export() diff --git a/accounting/state/limit_state.go b/accounting/state/limit_state.go index 46c7085..7d4acaf 100644 --- a/accounting/state/limit_state.go +++ b/accounting/state/limit_state.go @@ -7,12 +7,19 @@ import ( type ( LimitState interface { - Import(interface{}) error - Export() interface{} + Import(Snapshot) + Export() Snapshot check() (bool, int, time.Time) update(int, time.Time) } + Snapshot struct { + Timeout time.Duration + Datetime []time.Time + Pattern string + Pointer int + } + updateRequest struct { pointer int requestTime time.Time diff --git a/accounting/state/limiter.go b/accounting/state/limiter.go index 2ff318d..ba10e72 100644 --- a/accounting/state/limiter.go +++ b/accounting/state/limiter.go @@ -1,7 +1,6 @@ package state import ( - "github.com/pkg/errors" "time" ) @@ -12,15 +11,22 @@ type limiter struct { pointer int } -func (lim *limiter) Export() interface{} { - limitState := *lim - return limitState +func (lim *limiter) Export() Snapshot { + ls := *lim + return Snapshot{ + Timeout: ls.timeout, + Datetime: ls.datetime, + Pattern: ls.pattern, + Pointer: ls.pointer, + } } -func (lim *limiter) Import(data interface{}) error { - importLim, ok := data.(limiter) - if !ok { - return errors.New("invalid limit state") +func (lim *limiter) Import(data Snapshot) { + importLim := limiter{ + timeout: data.Timeout, + datetime: data.Datetime, + pattern: data.Pattern, + pointer: data.Pointer, } lenImportDatetime := len(importLim.datetime) @@ -55,7 +61,6 @@ func (lim *limiter) Import(data interface{}) error { lim.datetime[i] = importLim.datetime[importLim.pointer] } } - return nil } func (lim *limiter) check() (bool, int, time.Time) { diff --git a/accounting/state/limiter_test.go b/accounting/state/limiter_test.go index 253c824..77c8ec2 100644 --- a/accounting/state/limiter_test.go +++ b/accounting/state/limiter_test.go @@ -30,10 +30,8 @@ func TestLimiter(t *testing.T) { expectedFalse, _, _ := store7.check() a.False(expectedFalse) - err := store12.Import(store7.Export()) - a.NoError(err) - err = store5.Import(store10.Export()) - a.NoError(err) + store12.Import(store7.Export()) + store5.Import(store10.Export()) a.Equal(store5.datetime[0], store10.datetime[store10.pointer+1]) a.Equal(store12.datetime[0], store7.datetime[0]) diff --git a/entity/entity.go b/entity/entity.go index 20c55b7..5d47761 100644 --- a/entity/entity.go +++ b/entity/entity.go @@ -1,7 +1,9 @@ package entity +import "isp-gate-service/accounting/state" + type Snapshot struct { TableName string `sql:"gate_service.snapshot" json:"-"` AppId int32 `sql:",pk"` - LimitState map[string]interface{} + LimitState map[string]state.Snapshot } diff --git a/handler/handler.go b/handler/handler.go index 16cf58d..512df20 100644 --- a/handler/handler.go +++ b/handler/handler.go @@ -28,7 +28,7 @@ func CompleteRequest(ctx *fasthttp.RequestCtx) { currentTime := time.Now() uri := string(ctx.RequestURI()) - resp := helper.AuthenticateApproveProxy(ctx) + resp := helper.AuthenticateAccountingProxy(ctx) executionTime := time.Since(currentTime) / 1e6 @@ -54,7 +54,7 @@ func CompleteRequest(ctx *fasthttp.RequestCtx) { } } -func (handlerHelper) AuthenticateApproveProxy(ctx *fasthttp.RequestCtx) domain.ProxyResponse { +func (handlerHelper) AuthenticateAccountingProxy(ctx *fasthttp.RequestCtx) domain.ProxyResponse { path := string(ctx.Path()) p := proxy.Find(path) @@ -77,7 +77,7 @@ func (handlerHelper) AuthenticateApproveProxy(ctx *fasthttp.RequestCtx) domain.P return domain.Create().SetError(err) } - if approver := accounting.GetAccounting(applicationId); approver != nil && !approver.Check(path) { + if account := accounting.GetAccounting(applicationId); account != nil && !account.Check(path) { err := errors.New("accounting error") utils.WriteError(ctx, "forbidden", codes.ResourceExhausted, nil) return domain.Create().SetError(err) diff --git a/migrations/00002_2019-11-14_init.sql b/migrations/00001_2019-11-14_init.sql similarity index 85% rename from migrations/00002_2019-11-14_init.sql rename to migrations/00001_2019-11-14_init.sql index 886e04e..5a1c2c4 100644 --- a/migrations/00002_2019-11-14_init.sql +++ b/migrations/00001_2019-11-14_init.sql @@ -1,11 +1,9 @@ -- +goose Up - CREATE TABLE snapshot( app_id INTEGER PRIMARY KEY, - limit_state jsonb + limit_state JSONB ); - -- +goose Down DROP SCHEMA IF EXISTS gate_service CASCADE; \ No newline at end of file