diff --git a/accounting/accounting.go b/accounting/accounting.go index 9e49d9b..364c34a 100644 --- a/accounting/accounting.go +++ b/accounting/accounting.go @@ -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{ diff --git a/accounting/accounting_test.go b/accounting/accounting_test.go index 016a0c8..b9a675d 100644 --- a/accounting/accounting_test.go +++ b/accounting/accounting_test.go @@ -26,6 +26,10 @@ var ( {Pattern: "mdm-master/group/method", MaxCount: 0, Timeout: "10s"}, }}, }, + Unload: conf.UnloadSetting{ + Count: 100, + Timeout: "1h", + }, } reqExample = []struct { diff --git a/accounting/snapshot.go b/accounting/snapshot.go index 99c1408..6eea929 100644 --- a/accounting/snapshot.go +++ b/accounting/snapshot.go @@ -52,6 +52,6 @@ func (s *snapshotTask) Stop() { } func (s *snapshotTask) complete() error { - snapshotList := TakeSnapshot() + snapshotList := takeSnapshot() return model.SnapshotRep.Update(snapshotList) } diff --git a/accounting/unload.go b/accounting/unload.go new file mode 100644 index 0000000..f253a26 --- /dev/null +++ b/accounting/unload.go @@ -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() +} diff --git a/authenticate/error.go b/authenticate/error.go index 9df68a0..d17399d 100644 --- a/authenticate/error.go +++ b/authenticate/error.go @@ -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} } diff --git a/conf/default_remote_config.json b/conf/default_remote_config.json index 5b4d997..2135df7 100644 --- a/conf/default_remote_config.json +++ b/conf/default_remote_config.json @@ -29,7 +29,11 @@ } ] } - ] + ], + "unload": { + "count": 1, + "timeout": "30m" + } }, "journalSetting": { "journal": { diff --git a/conf/remote_config.go b/conf/remote_config.go index 93906ba..6f423c1 100644 --- a/conf/remote_config.go +++ b/conf/remote_config.go @@ -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"` } diff --git a/entity/entity.go b/entity/entity.go index 5d47761..d67041a 100644 --- a/entity/entity.go +++ b/entity/entity.go @@ -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 +} diff --git a/handler/handler.go b/handler/handler.go index a46d4f0..3f1a602 100644 --- a/handler/handler.go +++ b/handler/handler.go @@ -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) } diff --git a/log_code/code.go b/log_code/code.go index bc3d90f..b6e66cd 100644 --- a/log_code/code.go +++ b/log_code/code.go @@ -19,4 +19,5 @@ const ( ErrorClientDatabase = 615 ErrorSnapshotAccounting = 616 + ErrorUnloadAccounting = 617 ) diff --git a/migrations/00002_2019-11-19_add_unload.sql b/migrations/00002_2019-11-19_add_unload.sql new file mode 100644 index 0000000..ab2c6e6 --- /dev/null +++ b/migrations/00002_2019-11-19_add_unload.sql @@ -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; \ No newline at end of file diff --git a/model/client.go b/model/client.go index 2faaca6..21712bd 100644 --- a/model/client.go +++ b/model/client.go @@ -16,4 +16,5 @@ var ( })) SnapshotRep SnapshotRepository = snapshotRepository{rxClient: DbClient} + UnloadRep UnloadRepository = unloadRepository{rxClient: DbClient} ) diff --git a/model/unload.go b/model/unload.go new file mode 100644 index 0000000..0e1e78e --- /dev/null +++ b/model/unload.go @@ -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() +}