add unloading all requests

This commit is contained in:
DeniskaRediska committed 2019-11-19 19:02:17 +03:00
1 parent 8af97e56d7
commit 37c08f4500
13 files changed
+191 -6

No files matched your search

+7 -1
View File
@@ -25,9 +25,14 @@ type Accounting interface {
func ReceiveConfiguration(conf conf.Accounting) {
snapshot.Stop()
Unload.Stop()
newAccountingByApplicationId := make(map[int32]Accounting)
if conf.Enable {
if err := Unload.Init(conf.Unload); err != nil {
log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err)
}
for _, s := range conf.Setting {
limitStates, patternArray, err := state.InitLimitState(s.Limits)
if err != nil {
@@ -59,13 +64,14 @@ func ReceiveConfiguration(conf conf.Accounting) {
func Close() {
snapshot.Stop()
Unload.Stop()
}
func GetAccounting(appId int32) Accounting {
return accountingStorage[appId]
}
func TakeSnapshot() []entity.Snapshot {
func takeSnapshot() []entity.Snapshot {
response := make([]entity.Snapshot, 0)
for appId, account := range accountingStorage {
response = append(response, entity.Snapshot{
+4
View File
@@ -26,6 +26,10 @@ var (
{Pattern: "mdm-master/group/method", MaxCount: 0, Timeout: "10s"},
}},
},
Unload: conf.UnloadSetting{
Count: 100,
Timeout: "1h",
},
}
reqExample = []struct {
+1 -1
View File
@@ -52,6 +52,6 @@ func (s *snapshotTask) Stop() {
}
func (s *snapshotTask) complete() error {
snapshotList := TakeSnapshot()
snapshotList := takeSnapshot()
return model.SnapshotRep.Update(snapshotList)
}
+110
View File
@@ -0,0 +1,110 @@
package accounting
import (
log "github.com/integration-system/isp-log"
"isp-gate-service/conf"
"isp-gate-service/entity"
"isp-gate-service/log_code"
"isp-gate-service/model"
"sync"
"time"
)
var Unload = &unloadingTask{
mx: sync.Mutex{},
counter: 0,
process: false,
chanTimeout: make(chan time.Time),
chanCounter: make(chan bool),
chanClose: make(chan bool),
}
type unloadingTask struct {
cache []entity.Unload
counter int
process bool
chanTimeout <-chan time.Time
chanCounter chan bool
chanClose chan bool
mx sync.Mutex
}
func (u *unloadingTask) Init(setting conf.UnloadSetting) error {
u.mx.Lock()
u.process = true
u.cache = make([]entity.Unload, setting.Count)
u.counter = 0
u.mx.Unlock()
timeout, err := time.ParseDuration(setting.Timeout)
if err != nil {
return err
}
go u.run(timeout)
return nil
}
func (u *unloadingTask) TakeRequest(appId int32, method string, date time.Time) {
if !u.process {
return
}
u.mx.Lock()
u.cache[u.counter] = entity.Unload{
AppId: appId,
Method: method,
CreatedAt: date,
}
u.counter++
if u.counter == len(u.cache) {
u.chanCounter <- true
}
u.mx.Unlock()
}
func (u *unloadingTask) Stop() {
u.mx.Lock()
if u.process {
defer u.unload()
u.chanClose <- true
u.process = false
}
u.mx.Unlock()
}
func (u *unloadingTask) run(timeout time.Duration) {
u.chanTimeout = time.After(timeout)
for {
select {
case <-u.chanClose:
return
case <-u.chanCounter:
u.unload()
u.chanTimeout = time.After(timeout)
case <-u.chanTimeout:
u.unload()
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 {
log.Error(log_code.ErrorUnloadAccounting, err)
}
u.counter = 0
u.cache = make([]entity.Unload, oldLen)
u.mx.Unlock()
}
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"google.golang.org/grpc/codes"
)
func createError(status codes.Code, details ...interface{}) ErrorDescription {
func createError(status codes.Code, details ...interface{}) error {
return ErrorDescription{grpcStatus: status, details: details}
}
+5 -1
View File
@@ -29,7 +29,11 @@
}
]
}
]
],
"unload": {
"count": 1,
"timeout": "30m"
}
},
"journalSetting": {
"journal": {
+6
View File
@@ -51,6 +51,7 @@ type (
Enable bool `schema:"Статус работы учета,включает/отключает учет запросов"`
SnapshotTimeout string `schema:"Время частоты выгрузки учтенных запросов" valid:"required~Required"`
Setting []AccountingSetting `schema:"Настройка учета для приложений"`
Unload UnloadSetting `schema:"Настройка выгрзуки всех запросов"`
}
AccountingSetting struct {
@@ -64,6 +65,11 @@ type (
Timeout string `schema:"Время жизни одного запроса"`
}
UnloadSetting struct {
Count int `schema:"Ограничение по количеству для выгрузки" valid:"required~Range(1|1000000)"`
Timeout string `schema:"Ограничение по времени для выгрузки" valid:"required~Required"`
}
HttpSetting struct {
MaxRequestBodySizeBytes int64 `schema:"Максимальный размер тела запроса,в байтайх, по умолчанию: 512 MB"`
}
+12 -1
View File
@@ -1,9 +1,20 @@
package entity
import "isp-gate-service/accounting/state"
import (
"isp-gate-service/accounting/state"
"time"
)
type Snapshot struct {
TableName string `sql:"gate_service.snapshot" json:"-"`
AppId int32 `sql:",pk"`
LimitState map[string]state.Snapshot
}
type Unload struct {
TableName string `sql:"gate_service.unload" json:"-"`
Id int `sql:",pk"`
AppId int32
Method string
CreatedAt time.Time
}
+1 -1
View File
@@ -82,7 +82,7 @@ func (handlerHelper) AuthenticateAccountingProxy(ctx *fasthttp.RequestCtx) domai
utils.WriteError(ctx, "forbidden", codes.ResourceExhausted, nil)
return domain.Create().SetError(err)
}
go accounting.Unload.TakeRequest(applicationId, path, time.Now())
return p.ProxyRequest(ctx)
}
+1
View File
@@ -19,4 +19,5 @@ const (
ErrorClientDatabase = 615
ErrorSnapshotAccounting = 616
ErrorUnloadAccounting = 617
)
@@ -0,0 +1,12 @@
-- +goose Up
CREATE TABLE unload
(
id SERIAL8 PRIMARY KEY,
app_id INTEGER NOT NULL,
method VARCHAR(255) NOT NULL,
created_at TIMESTAMP NOT NULL
);
-- +goose Down
DROP TABLE unload;
+1
View File
@@ -16,4 +16,5 @@ var (
}))
SnapshotRep SnapshotRepository = snapshotRepository{rxClient: DbClient}
UnloadRep UnloadRepository = unloadRepository{rxClient: DbClient}
)
+30
View File
@@ -0,0 +1,30 @@
package model
import (
"github.com/go-pg/pg/orm"
"github.com/integration-system/isp-lib/database"
"isp-gate-service/entity"
)
type (
UnloadRepository interface {
Insert([]entity.Unload) error
}
unloadRepository struct {
DB orm.DB
rxClient *database.RxDbClient
}
)
func (r unloadRepository) Insert(model []entity.Unload) error {
_, err := r.getDb().Model(&model).Insert()
return err
}
func (r unloadRepository) getDb() orm.DB {
if r.DB != nil {
return r.DB
}
return r.rxClient.Unsafe()
}