From 8dcb8eef68b1f614bc398613d992c76e234e29e3 Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Wed, 20 Nov 2019 13:41:45 +0300 Subject: [PATCH] add unloading setting for application --- accounting/accounting.go | 36 ++++++++++++++++--------- accounting/accounting_test.go | 18 ++++++------- accounting/unload.go | 51 ++++++++++++++++++++--------------- accounting/unload_test.go | 46 +++++++++++++++++++++++++++++++ conf/remote_config.go | 3 ++- handler/handler.go | 5 ++-- 6 files changed, 112 insertions(+), 47 deletions(-) create mode 100644 accounting/unload_test.go diff --git a/accounting/accounting.go b/accounting/accounting.go index 364c34a..ac88932 100644 --- a/accounting/accounting.go +++ b/accounting/accounting.go @@ -14,8 +14,9 @@ import ( ) var ( - accountingStorage = make(map[int32]Accounting) accountingWorking = false + accountingStorage = make(map[int32]Accounting) + unloadingStorage = make(map[int32]bool) ) type Accounting interface { @@ -24,16 +25,18 @@ type Accounting interface { } func ReceiveConfiguration(conf conf.Accounting) { - snapshot.Stop() - Unload.Stop() - newAccountingByApplicationId := make(map[int32]Accounting) + Close() + newAccountingStorage := make(map[int32]Accounting) + newUnloadingStorage := make(map[int32]bool) if conf.Enable { - if err := Unload.Init(conf.Unload); err != nil { + if err := unload.Init(conf.Unload); err != nil { log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err) } for _, s := range conf.Setting { + newUnloadingStorage[s.ApplicationId] = s.EnableUnload + limitStates, patternArray, err := state.InitLimitState(s.Limits) if err != nil { log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err) @@ -41,7 +44,7 @@ func ReceiveConfiguration(conf conf.Accounting) { recoveryLimitState(s.ApplicationId, limitStates) - newAccountingByApplicationId[s.ApplicationId] = &accountant{ + newAccountingStorage[s.ApplicationId] = &accountant{ matcher: matcher.NewCacheableMatcher(patternArray), limitStates: limitStates, mx: sync.Mutex{}, @@ -59,16 +62,25 @@ func ReceiveConfiguration(conf conf.Accounting) { accountingWorking = false } - accountingStorage = newAccountingByApplicationId + unloadingStorage = newUnloadingStorage + accountingStorage = newAccountingStorage +} + +func Accept(appId int32, path string) bool { + if unloadingStorage[appId] { + unload.TakeRequest(appId, path, time.Now()) + } + + if accouter, ok := accountingStorage[appId]; !ok { + return true + } else { + return accouter.Accept(path) + } } func Close() { snapshot.Stop() - Unload.Stop() -} - -func GetAccounting(appId int32) Accounting { - return accountingStorage[appId] + unload.Stop() } func takeSnapshot() []entity.Snapshot { diff --git a/accounting/accounting_test.go b/accounting/accounting_test.go index b9a675d..50fd95b 100644 --- a/accounting/accounting_test.go +++ b/accounting/accounting_test.go @@ -13,10 +13,10 @@ import ( var ( accountingSetting = conf.Accounting{ Enable: true, - SnapshotTimeout: "890ms", + SnapshotTimeout: "290ms", Setting: []conf.AccountingSetting{ {ApplicationId: 1, Limits: []conf.LimitSetting{ - {Pattern: "mdm-master/group/method", MaxCount: 1, Timeout: "290ms"}, + {Pattern: "mdm-master/group/method", MaxCount: 1, Timeout: "90ms"}, {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"}, @@ -67,41 +67,41 @@ func TestAccounting(t *testing.T) { req := reqExample[4] for _, path := range req.path { - a.True(GetAccounting(req.appId).Accept(path)) + a.True(Accept(req.appId, path)) } expected := true req = reqExample[0] for _, path := range req.path { - a.Equal(expected, GetAccounting(req.appId).Accept(path)) + a.Equal(expected, Accept(req.appId, path)) expected = !expected - time.Sleep(150 * time.Millisecond) + time.Sleep(50 * time.Millisecond) } //expected == true req = reqExample[1] for _, path := range req.path { - a.Equal(expected, GetAccounting(req.appId).Accept(path)) + a.Equal(expected, Accept(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], GetAccounting(req.appId).Accept(path)) + a.Equal(expectedArray[key], Accept(req.appId, path)) } //expected == true req = reqExample[3] for _, path := range req.path { - a.Equal(expected, GetAccounting(req.appId).Accept(path)) + a.Equal(expected, Accept(req.appId, path)) } ReceiveConfiguration(accountingSetting) req = reqExample[4] for _, path := range req.path { - a.False(GetAccounting(req.appId).Accept(path)) + a.False(Accept(req.appId, path)) } } diff --git a/accounting/unload.go b/accounting/unload.go index f253a26..dc8b762 100644 --- a/accounting/unload.go +++ b/accounting/unload.go @@ -10,12 +10,12 @@ import ( "time" ) -var Unload = &unloadingTask{ +var unload = &unloadingTask{ mx: sync.Mutex{}, counter: 0, process: false, chanTimeout: make(chan time.Time), - chanCounter: make(chan bool), + chanCounter: make(chan []entity.Unload), chanClose: make(chan bool), } @@ -25,7 +25,7 @@ type unloadingTask struct { process bool chanTimeout <-chan time.Time - chanCounter chan bool + chanCounter chan []entity.Unload chanClose chan bool mx sync.Mutex @@ -47,11 +47,12 @@ func (u *unloadingTask) Init(setting conf.UnloadSetting) error { } func (u *unloadingTask) TakeRequest(appId int32, method string, date time.Time) { + u.mx.Lock() if !u.process { + u.mx.Unlock() return } - u.mx.Lock() u.cache[u.counter] = entity.Unload{ AppId: appId, Method: method, @@ -60,7 +61,11 @@ func (u *unloadingTask) TakeRequest(appId int32, method string, date time.Time) u.counter++ if u.counter == len(u.cache) { - u.chanCounter <- true + u.chanCounter <- u.cache + + oldLen := len(u.cache) + u.counter = 0 + u.cache = make([]entity.Unload, oldLen) } u.mx.Unlock() @@ -69,7 +74,9 @@ func (u *unloadingTask) TakeRequest(appId int32, method string, date time.Time) func (u *unloadingTask) Stop() { u.mx.Lock() if u.process { - defer u.unload() + if u.counter != 0 { + defer u.unload(u.cache[:u.counter]) + } u.chanClose <- true u.process = false } @@ -82,29 +89,29 @@ func (u *unloadingTask) run(timeout time.Duration) { select { case <-u.chanClose: return - case <-u.chanCounter: - u.unload() + case cache := <-u.chanCounter: + u.unload(cache) u.chanTimeout = time.After(timeout) case <-u.chanTimeout: - u.unload() + u.mx.Lock() + if u.counter != 0 { + cache := u.cache[:u.counter] + oldLen := len(u.cache) + u.counter = 0 + u.cache = make([]entity.Unload, oldLen) + u.mx.Unlock() + + u.unload(cache) + } else { + u.mx.Unlock() + } u.chanTimeout = time.After(timeout) } } } -func (u *unloadingTask) unload() { - u.mx.Lock() - if u.counter == 0 { - u.mx.Unlock() - return - } - - oldLen := len(u.cache) - if err := model.UnloadRep.Insert(u.cache[:u.counter]); err != nil { +func (u *unloadingTask) unload(cache []entity.Unload) { + if err := model.UnloadRep.Insert(cache); err != nil { log.Error(log_code.ErrorUnloadAccounting, err) } - u.counter = 0 - u.cache = make([]entity.Unload, oldLen) - - u.mx.Unlock() } diff --git a/accounting/unload_test.go b/accounting/unload_test.go new file mode 100644 index 0000000..127265a --- /dev/null +++ b/accounting/unload_test.go @@ -0,0 +1,46 @@ +package accounting + +import ( + "github.com/stretchr/testify/assert" + "isp-gate-service/conf" + "isp-gate-service/entity" + "isp-gate-service/model" + "testing" + "time" +) + +var unloadingSetting = conf.UnloadSetting{ + Count: 3, + Timeout: "50ms", +} + +func TestUnloadingTask(t *testing.T) { + a := assert.New(t) + repository := &unloadRepository{cache: make([]entity.Unload, 0)} + model.UnloadRep = repository + + err := unload.Init(unloadingSetting) + a.NoError(err) + + for i, j := range []string{"1", "2", "3", "4", "5"} { + unload.TakeRequest(int32(i), j, time.Now()) + } + a.Len(repository.cache, 3) + time.Sleep(time.Millisecond * 60) + a.Len(repository.cache, 5) + + for i, j := range []string{"1", "2", "3", "4", "5"} { + unload.TakeRequest(int32(i), j, time.Now()) + } + unload.Stop() + a.Len(repository.cache, 10) +} + +type unloadRepository struct { + cache []entity.Unload +} + +func (r *unloadRepository) Insert(model []entity.Unload) error { + r.cache = append(r.cache, model...) + return nil +} diff --git a/conf/remote_config.go b/conf/remote_config.go index 6f423c1..9747ac7 100644 --- a/conf/remote_config.go +++ b/conf/remote_config.go @@ -51,11 +51,12 @@ type ( Enable bool `schema:"Статус работы учета,включает/отключает учет запросов"` SnapshotTimeout string `schema:"Время частоты выгрузки учтенных запросов" valid:"required~Required"` Setting []AccountingSetting `schema:"Настройка учета для приложений"` - Unload UnloadSetting `schema:"Настройка выгрзуки всех запросов"` + Unload UnloadSetting `schema:"Настройка общей выгрзуки запросов"` } AccountingSetting struct { ApplicationId int32 `valid:"required~Required" schema:"Идентификатор приложения"` + EnableUnload bool `schema:"Включает в общую выгрузку запросы для этого приложения"` Limits []LimitSetting `schema:"Настройка ограничений на запросы"` } diff --git a/handler/handler.go b/handler/handler.go index 3f1a602..2bf4c99 100644 --- a/handler/handler.go +++ b/handler/handler.go @@ -77,12 +77,11 @@ func (handlerHelper) AuthenticateAccountingProxy(ctx *fasthttp.RequestCtx) domai return domain.Create().SetError(err) } - if account := accounting.GetAccounting(applicationId); account != nil && !account.Accept(path) { + if !accounting.Accept(applicationId, path) { err := errors.New("accounting error") - utils.WriteError(ctx, "forbidden", codes.ResourceExhausted, nil) + utils.WriteError(ctx, "too many requests", codes.ResourceExhausted, nil) return domain.Create().SetError(err) } - go accounting.Unload.TakeRequest(applicationId, path, time.Now()) return p.ProxyRequest(ctx) }