add unloading setting for application

This commit is contained in:
DeniskaRediska committed 2019-11-20 13:41:45 +03:00
1 parent 37c08f4500
commit 8dcb8eef68
6 files changed
+112 -47

No files matched your search

+24 -12
View File
@@ -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 {
+9 -9
View File
@@ -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))
}
}
+29 -22
View File
@@ -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()
}
+46
View File
@@ -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
}
+2 -1
View File
@@ -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:"Настройка ограничений на запросы"`
}
+2 -3
View File
@@ -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)
}