From 3d2cee1ae88ed692f203d9d4a228580731e6552c Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Fri, 15 Nov 2019 19:18:47 +0300 Subject: [PATCH 01/12] add snapshot --- Gopkg.lock | 96 +++++++++++++++++++++++----- accounting/accountant.go | 31 +++++++++ accounting/accounting.go | 58 ++++++++++------- accounting/accounting_test.go | 35 +++++++++- accounting/snapshot.go | 72 +++++++++++++++++++++ accounting/state/limit_state.go | 2 + accounting/state/limiter.go | 47 ++++++++++++++ accounting/state/limiter_test.go | 53 +++++++++++++++ authenticate/authenticate.go | 2 +- authenticate/token.go | 4 +- conf/default_remote_config.json | 82 +++++++++++++++--------- conf/remote_config.go | 16 +++-- entity/entity.go | 7 ++ log_code/code.go | 14 ++-- main.go | 3 + migrations/00002_2019-11-14_init.sql | 11 ++++ model/client.go | 19 ++++++ model/snapshot.go | 56 ++++++++++++++++ 18 files changed, 521 insertions(+), 87 deletions(-) create mode 100644 accounting/accountant.go create mode 100644 accounting/snapshot.go create mode 100644 accounting/state/limiter_test.go create mode 100644 entity/entity.go create mode 100644 migrations/00002_2019-11-14_init.sql create mode 100644 model/client.go create mode 100644 model/snapshot.go diff --git a/Gopkg.lock b/Gopkg.lock index 32efa0f..b6c7e69 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -41,6 +41,24 @@ revision = "c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9" version = "v1.4.7" +[[projects]] + digest = "1:f9448bfab8ebe44e3d91e4e4475cf92d60789a614652f361df4e41972c9d5caf" + name = "github.com/go-pg/pg" + packages = [ + ".", + "internal", + "internal/iszero", + "internal/parser", + "internal/pool", + "internal/struct_filter", + "internal/tag", + "orm", + "types", + ] + pruneopts = "UT" + revision = "1d957cb20f319c4a1e2db7d345824c12aefe5943" + version = "v8.0.6" + [[projects]] digest = "1:b46f50677ef33284ebde2b285a42b707ff9e1de1f37328d91869859c929ebbd2" name = "github.com/go-redis/redis" @@ -163,13 +181,14 @@ version = "v1.3.0" [[projects]] - digest = "1:a1ebd1a46e87e9343cbabec1ca99c34a7a2e0572c0160fcf266175073b2adf5f" + digest = "1:6b991c544a334db5cd4e7719bc446e8b41d1221031a87b55d36d2e81ec182257" name = "github.com/integration-system/isp-lib" packages = [ "backend", "bootstrap", "config", "config/schema", + "database", "http", "logger", "metric", @@ -202,6 +221,14 @@ pruneopts = "UT" revision = "5475a8b08e62e41fa886641861ac225e7f91e4e5" +[[projects]] + digest = "1:01ed62f8f4f574d8aff1d88caee113700a2b44c42351943fa73cc1808f736a50" + name = "github.com/jinzhu/inflection" + packages = ["."] + pruneopts = "UT" + revision = "f5c5f50e6090ae76a29240b61ae2a90dd810112e" + version = "v1.0.0" + [[projects]] digest = "1:d78015a9da26d37166a2119592019e8bfe9b24bec60aff4a46db6110070fb1b2" name = "github.com/json-iterator/go" @@ -214,7 +241,7 @@ version = "1.1.8" [[projects]] - digest = "1:acfc228fb5fbfb82645c121e3224bd546ed68aef6dfc87f63e2d8de099a3822b" + digest = "1:fa4b4bfa0edfb83c4690d8746ea25bc2447ad0c20063ba72adcb5725f54acde0" name = "github.com/klauspost/compress" packages = [ "flate", @@ -222,8 +249,8 @@ "zlib", ] pruneopts = "UT" - revision = "16a4d3d7137cdefd94d420f22b5c20260674b95c" - version = "v1.9.1" + revision = "4e96aec082898e4dad17d8aca1a7e2d01362ff6c" + version = "v1.9.2" [[projects]] digest = "1:31e761d97c76151dde79e9d28964a812c46efc5baee4085b86f68f0c654450de" @@ -233,6 +260,18 @@ revision = "f55edac94c9bbba5d6182a4be46d86a2c9b5b50e" version = "v1.0.2" +[[projects]] + digest = "1:12cb143f2148bf54bcd9fe622abac17325e85eeb1d84b8ec6caf1c80232108fd" + name = "github.com/lib/pq" + packages = [ + ".", + "oid", + "scram", + ] + pruneopts = "UT" + revision = "3427c32cb71afc948325f299f040e53c1dd78979" + version = "v1.2.0" + [[projects]] digest = "1:5a0ef768465592efca0412f7e838cdc0826712f8447e70e6ccc52eb441e9ab13" name = "github.com/magiconair/properties" @@ -321,6 +360,14 @@ revision = "792786c7400a136282c1664665ae0a8db921c6c2" version = "v1.0.0" +[[projects]] + digest = "1:7d99649602f68b73ade640ca6975ccc38735f329e159c6a507b63f00213678c0" + name = "github.com/pressly/goose" + packages = ["."] + pruneopts = "UT" + revision = "e4b98955473e91a12fc7d8816c28d06376d1d92c" + version = "v2.6.0" + [[projects]] branch = "master" digest = "1:5bbebe8ac19ecb6c87790a89faa20566e38ed0d6494a1d14c4f5b05d9ce2436c" @@ -414,7 +461,7 @@ [[projects]] branch = "master" - digest = "1:35cbf67ac1c92eb7bd6fe70d17b75b60bd38fb2222fa71ac82d44d3813897d22" + digest = "1:060c10c0942a53f52bc23c285f6c3d7ee12c2dafde0325e9f413e4d504963010" name = "github.com/valyala/fasthttp" packages = [ ".", @@ -422,7 +469,7 @@ "stackless", ] pruneopts = "UT" - revision = "87c4546c7b1268a1c29c46e8f54def6f0e7596eb" + revision = "5f666588000bc4a0e0852494958417036ccbb3b7" [[projects]] digest = "1:39a425f98fb19427061a693fe6bf0683c9bddec4b25b17067e34fdb465e39cb9" @@ -434,15 +481,18 @@ [[projects]] branch = "master" - digest = "1:bbe51412d9915d64ffaa96b51d409e070665efc5194fcf145c4a27d4133107a4" + digest = "1:35ce874cf16f78a2da908ab28b0277497e36603d289db00d39da5200bc8ace08" name = "golang.org/x/crypto" - packages = ["ssh/terminal"] + packages = [ + "pbkdf2", + "ssh/terminal", + ] pruneopts = "UT" - revision = "c7e5f84aec591254278750bee18f39e5dd19cdb5" + revision = "e1110fd1c708ef015366ea01799a23c459593c47" [[projects]] branch = "master" - digest = "1:d639fcedf8f14de3eefa8f26740091ca737108a944314a4700d482bd11a18301" + digest = "1:957579c244f371e4490a28c38685bfdb573639943d9add65aceb2dbd0ae76d50" name = "golang.org/x/net" packages = [ "context", @@ -454,18 +504,18 @@ "trace", ] pruneopts = "UT" - revision = "a882066a44e04a21d46e51451c71e131344e830e" + revision = "2180aed2234323691e9fd264fb1d32d20ff04b27" [[projects]] branch = "master" - digest = "1:1017834f19e0d987e8b1b928f016b0a1186a202ec1867fee7112efd4b4475bd1" + digest = "1:a8d09768b9b35851f498a4ba24ef08b7a72aa29bdb1673324394443e076bb440" name = "golang.org/x/sys" packages = [ "unix", "windows", ] pruneopts = "UT" - revision = "c1f44814a5cd81a6d1cb589ef1e528bc5d305e07" + revision = "4c7a9d0fe056d9d1de37e1409ca8a5c17accb46a" [[projects]] digest = "1:8d8faad6b12a3a4c819a3f9618cb6ee1fa1cfc33253abeeea8b55336721e3405" @@ -501,10 +551,10 @@ "googleapis/rpc/status", ] pruneopts = "UT" - revision = "919d9bdd9fe6f1a5dd95ce5d5e4cdb8fd3c516d0" + revision = "16a3f7862a1a494c52b23987ef8a993fd3f9a85e" [[projects]] - digest = "1:0c0ea0f0ccec8a112245dd3ca0c3b304224ede9afd4b7a2b482a7b48471ef894" + digest = "1:b59ce3ddb11daeeccccc9cb3183b58ebf8e9a779f1c853308cd91612e817a301" name = "google.golang.org/grpc" packages = [ ".", @@ -544,8 +594,8 @@ "tap", ] pruneopts = "UT" - revision = "9d331e2b02dd47daeecae02790f61cc88dc75a64" - version = "v1.25.0" + revision = "1a3960e4bd028ac0cec0a2afd27d7d8e67c11514" + version = "v1.25.1" [[projects]] digest = "1:f26a5d382387e03a40d1471dddfba85dfff9bf05352d7e42d37612677c4d3c5c" @@ -555,11 +605,22 @@ revision = "f90ceb4f409096b60e2e9076b38b304b8246e5fa" version = "v2.2.5" +[[projects]] + digest = "1:999d566ad1ae4303c456af5a155f7b42401cca4fd33552567ed9dd997b107a08" + name = "mellium.im/sasl" + packages = ["."] + pruneopts = "UT" + revision = "e58e780e1378aa4df5dc705364ff5ae9a4dd1e04" + source = "https://github.com/mellium/sasl.git" + version = "v0.2.1" + [solve-meta] analyzer-name = "dep" analyzer-version = 1 input-imports = [ "github.com/dgrijalva/jwt-go", + "github.com/go-pg/pg", + "github.com/go-pg/pg/orm", "github.com/go-redis/redis", "github.com/golang/protobuf/proto", "github.com/golang/protobuf/ptypes/struct", @@ -568,6 +629,7 @@ "github.com/integration-system/isp-lib/bootstrap", "github.com/integration-system/isp-lib/config", "github.com/integration-system/isp-lib/config/schema", + "github.com/integration-system/isp-lib/database", "github.com/integration-system/isp-lib/http", "github.com/integration-system/isp-lib/metric", "github.com/integration-system/isp-lib/proto/stubs", diff --git a/accounting/accountant.go b/accounting/accountant.go new file mode 100644 index 0000000..a26feb4 --- /dev/null +++ b/accounting/accountant.go @@ -0,0 +1,31 @@ +package accounting + +import ( + "isp-gate-service/accounting/state" + "isp-gate-service/service/matcher" + "sync" +) + +type accountant struct { + mx sync.Mutex + matcher matcher.Matcher + limitStates map[string]state.LimitState +} + +func (app *accountant) Check(method string) bool { + patternArray := app.matcher.Match(method) + stateStorage := make([]state.LimitState, len(patternArray)) + for i, pattern := range patternArray { + stateStorage[i] = app.limitStates[pattern] + } + + app.mx.Lock() + resp := state.Update(stateStorage) + app.mx.Unlock() + return resp +} + +func (app *accountant) getLimitState() map[string]state.LimitState { + limitStates := app.limitStates + return limitStates +} diff --git a/accounting/accounting.go b/accounting/accounting.go index b7a1727..a9c6d82 100644 --- a/accounting/accounting.go +++ b/accounting/accounting.go @@ -5,50 +5,62 @@ import ( "github.com/integration-system/isp-log/stdcodes" "isp-gate-service/accounting/state" "isp-gate-service/conf" + "isp-gate-service/log_code" + "isp-gate-service/model" "isp-gate-service/service/matcher" "sync" + "time" ) -var accountingByApplicationId = make(map[int32]*accounting) +var accountingByApplicationId = make(map[int32]Accounting) -type accounting struct { - mx sync.Mutex - matcher matcher.Matcher - limitStates map[string]state.LimitState +type Accounting interface { + Check(string) bool + getLimitState() map[string]state.LimitState } func ReceiveConfiguration(conf conf.Accounting) { - newAccountingByApplicationId := make(map[int32]*accounting) + snapshot.Stop() + + newAccountingByApplicationId := make(map[int32]Accounting) if conf.Enable { for _, s := range conf.Setting { - limitState, patternArray, err := state.InitLimitState(s.Limits) + limitStates, patternArray, err := state.InitLimitState(s.Limits) if err != nil { log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err) } - newAccountingByApplicationId[s.ApplicationId] = &accounting{ + if snapshot, err := model.SnapshotRep.GetByApplication(s.ApplicationId); err != nil { + 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) + } + } + } + } + + newAccountingByApplicationId[s.ApplicationId] = &accountant{ matcher: matcher.NewCacheableMatcher(patternArray), - limitStates: limitState, + limitStates: limitStates, mx: sync.Mutex{}, } } + if snapshotTimeout, err := time.ParseDuration(conf.SnapshotTimeout); err != nil { + log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err) + } else { + go snapshot.Start(snapshotTimeout) + } } accountingByApplicationId = newAccountingByApplicationId } -func GetAccounting(appId int32) *accounting { +func Close() { + snapshot.Stop() +} + +func GetAccounting(appId int32) Accounting { return accountingByApplicationId[appId] } - -func (app *accounting) Check(method string) bool { - patternArray := app.matcher.Match(method) - stateStorage := make([]state.LimitState, len(patternArray)) - for i, pattern := range patternArray { - stateStorage[i] = app.limitStates[pattern] - } - - app.mx.Lock() - resp := state.Update(stateStorage) - app.mx.Unlock() - return resp -} diff --git a/accounting/accounting_test.go b/accounting/accounting_test.go index 6ee1b6d..92aaed0 100644 --- a/accounting/accounting_test.go +++ b/accounting/accounting_test.go @@ -3,13 +3,16 @@ package accounting import ( "github.com/stretchr/testify/assert" "isp-gate-service/conf" + "isp-gate-service/entity" + "isp-gate-service/model" "testing" "time" ) var ( approveSetting = conf.Accounting{ - Enable: true, + Enable: true, + SnapshotTimeout: "2s", Setting: []conf.AccountingSetting{ {ApplicationId: 1, Limits: []conf.LimitSetting{ {Pattern: "mdm-master/group/method", MaxCount: 1, Timeout: "290ms"}, @@ -51,6 +54,7 @@ var ( func TestApprove(t *testing.T) { a := assert.New(t) ReceiveConfiguration(approveSetting) + model.SnapshotRep = &snapshotRepository{cache: make(map[int32]map[string]interface{})} expected := true req := reqExample[0] @@ -79,3 +83,32 @@ func TestApprove(t *testing.T) { a.Equal(expected, GetAccounting(req.appId).Check(path)) } } + +type snapshotRepository struct { + cache map[int32]map[string]interface{} +} + +func (r *snapshotRepository) GetByApplication(appId int32) (*entity.Snapshot, error) { + return &entity.Snapshot{ + AppId: appId, + LimitState: r.cache[appId], + }, nil +} + +func (r *snapshotRepository) Update(list []entity.Snapshot) error { + for _, s := range list { + r.cache[s.AppId] = s.LimitState + } + return nil +} + +func (r *snapshotRepository) GetAll() ([]entity.Snapshot, error) { + resp := make([]entity.Snapshot, 0) + for appId, limitState := range r.cache { + resp = append(resp, entity.Snapshot{ + AppId: appId, + LimitState: limitState, + }) + } + return resp, nil +} diff --git a/accounting/snapshot.go b/accounting/snapshot.go new file mode 100644 index 0000000..27b916c --- /dev/null +++ b/accounting/snapshot.go @@ -0,0 +1,72 @@ +package accounting + +import ( + log "github.com/integration-system/isp-log" + "isp-gate-service/entity" + "isp-gate-service/log_code" + "isp-gate-service/model" + "sync" + "time" +) + +var snapshot = &snapshotStruct{ + process: false, + timeout: make(chan time.Time), + close: make(chan bool), +} + +type snapshotStruct struct { + wg sync.WaitGroup + process bool + timeout <-chan time.Time + close chan bool +} + +func (s *snapshotStruct) Start(timeout time.Duration) { + if s.process { + s.close <- true + s.wg.Wait() + } + + s.process = true + s.wg.Add(1) + s.timeout = time.After(timeout) + + for { + select { + case <-s.close: + s.wg.Done() + return + case <-s.timeout: + applicationAccounting := accountingByApplicationId + if err := s.complete(applicationAccounting); err != nil { + log.Error(log_code.ErrorSnapshotAccounting, err) + } + s.timeout = time.After(timeout) + } + } +} + +func (s *snapshotStruct) Stop() { + if s.process { + s.process = false + s.close <- true + 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{}) + limitStates := account.getLimitState() + for method, limitState := range limitStates { + snapshotLimitState[method] = limitState.Export() + } + snapshot = append(snapshot, entity.Snapshot{ + AppId: application, + LimitState: snapshotLimitState, + }) + } + return model.SnapshotRep.Update(snapshot) +} diff --git a/accounting/state/limit_state.go b/accounting/state/limit_state.go index 694cbb9..46c7085 100644 --- a/accounting/state/limit_state.go +++ b/accounting/state/limit_state.go @@ -7,6 +7,8 @@ import ( type ( LimitState interface { + Import(interface{}) error + Export() interface{} check() (bool, int, time.Time) update(int, time.Time) } diff --git a/accounting/state/limiter.go b/accounting/state/limiter.go index d81c9fb..2ff318d 100644 --- a/accounting/state/limiter.go +++ b/accounting/state/limiter.go @@ -1,6 +1,7 @@ package state import ( + "github.com/pkg/errors" "time" ) @@ -11,6 +12,52 @@ type limiter struct { pointer int } +func (lim *limiter) Export() interface{} { + limitState := *lim + return limitState +} + +func (lim *limiter) Import(data interface{}) error { + importLim, ok := data.(limiter) + if !ok { + return errors.New("invalid limit state") + } + + lenImportDatetime := len(importLim.datetime) + lenDatetime := len(lim.datetime) + switch true { + case lenImportDatetime == lenDatetime: + lim.datetime = importLim.datetime + lim.pointer = importLim.pointer + + case lenImportDatetime < lenDatetime: + oldPointer := importLim.pointer + for i := range lim.datetime { + importLim.pointer++ + if importLim.pointer >= len(importLim.datetime) { + importLim.pointer = 0 + } + + lim.datetime[i] = importLim.datetime[importLim.pointer] + + if oldPointer == importLim.pointer { + lim.pointer = i + break + } + } + + case lenImportDatetime > lenDatetime: + for i := range lim.datetime { + importLim.pointer++ + if importLim.pointer >= len(importLim.datetime) { + importLim.pointer = 0 + } + lim.datetime[i] = importLim.datetime[importLim.pointer] + } + } + return nil +} + func (lim *limiter) check() (bool, int, time.Time) { if len(lim.datetime) == 0 { return false, 0, time.Time{} diff --git a/accounting/state/limiter_test.go b/accounting/state/limiter_test.go new file mode 100644 index 0000000..253c824 --- /dev/null +++ b/accounting/state/limiter_test.go @@ -0,0 +1,53 @@ +package state + +import ( + "github.com/stretchr/testify/assert" + "testing" + "time" +) + +func TestLimiter(t *testing.T) { + a := assert.New(t) + newLimiter := func(count int) *limiter { + return &limiter{timeout: 5 * time.Second, pattern: "example", pointer: -1, datetime: make([]time.Time, count)} + } + + store12 := newLimiter(12) + store10 := newLimiter(10) + store7 := newLimiter(7) + store5 := newLimiter(5) + + for i := 0; i < 7; i++ { + expectedTrue, pointer, reqTime := store10.check() + a.True(expectedTrue) + store10.update(pointer, reqTime) + + expectedTrue, pointer, reqTime = store7.check() + a.True(expectedTrue) + store7.update(pointer, reqTime) + } + + expectedFalse, _, _ := store7.check() + a.False(expectedFalse) + + err := store12.Import(store7.Export()) + a.NoError(err) + err = store5.Import(store10.Export()) + a.NoError(err) + + a.Equal(store5.datetime[0], store10.datetime[store10.pointer+1]) + a.Equal(store12.datetime[0], store7.datetime[0]) + a.Equal(store12.datetime[store7.pointer], store7.datetime[store7.pointer]) + a.Equal(store12.datetime[store7.pointer+1], time.Time{}) + + expectedTrue, _, _ := store12.check() + a.True(expectedTrue) + + for i := 0; i < 3; i++ { + expectedTrue, pointer, reqTime := store5.check() + a.True(expectedTrue) + store5.update(pointer, reqTime) + } + expectedFalse, _, _ = store5.check() + a.False(expectedFalse) +} diff --git a/authenticate/authenticate.go b/authenticate/authenticate.go index eb6aa2e..d068f8e 100644 --- a/authenticate/authenticate.go +++ b/authenticate/authenticate.go @@ -58,7 +58,7 @@ func Do(ctx *fasthttp.RequestCtx) (int32, error) { ) if len(appToken) == 0 { return 0, createError(codes.Unauthenticated) - } else if config.GetRemote().(*conf.RemoteConfig).Secrets.VerifyAppToken { + } else if config.GetRemote().(*conf.RemoteConfig).TokensSetting.ApplicationVerify { if appId, err = verifyToken.Application(string(appToken)); err != nil || appId == 0 { return 0, createError(codes.Unauthenticated, "invalid token") } diff --git a/authenticate/token.go b/authenticate/token.go index 2db7c0f..36b7168 100644 --- a/authenticate/token.go +++ b/authenticate/token.go @@ -17,13 +17,13 @@ type appClaims struct { type token struct{} func (t token) Admin(token string) error { - secret := config.GetRemote().(*conf.RemoteConfig).Secrets.Admin + secret := config.GetRemote().(*conf.RemoteConfig).TokensSetting.AdminSecret _, err := t.parse(token, secret, jwt.MapClaims{}) return err } func (t token) Application(token string) (int32, error) { - secret := config.GetRemote().(*conf.RemoteConfig).Secrets.Application + secret := config.GetRemote().(*conf.RemoteConfig).TokensSetting.ApplicationSecret if parsed, err := t.parse(token, secret, &appClaims{StandardClaims: &jwt.StandardClaims{}}); err != nil { return 0, err diff --git a/conf/default_remote_config.json b/conf/default_remote_config.json index 849c096..5b4d997 100644 --- a/conf/default_remote_config.json +++ b/conf/default_remote_config.json @@ -1,23 +1,46 @@ { - "metrics": { - "gc": true, - "memory": true, - "address": { - "path": "/metrics", - "port": "9553", - "ip": "0.0.0.0" - } + "database": { + "database": "database", + "password": "password", + "username": "name", + "port": "5432", + "schema": "gate_service", + "address": "127.0.0.1", + "createSchema": true }, "grpcSetting": { - "enableOriginalProtoErrors": false, - "proxyGrpcErrorDetails": false + "proxyGrpcErrorDetails": false, + "enableOriginalProtoErrors": false }, "serverSetting": { "maxRequestBodySizeBytes": 0 }, "accountingSetting": { "enable": false, - "setting": [] + "snapshotTimeout": "1h", + "setting": [ + { + "applicationId": 0, + "limits": [ + { + "timeout": "1s", + "maxCount": 500, + "pattern": "/example/module/group/method" + } + ] + } + ] + }, + "journalSetting": { + "journal": { + "compress": true, + "filename": "/var/log/isp-gate-service/runtime.log", + "maxSizeMb": 512, + "bufferSize": 4096, + "rotateTimeoutMs": 86400000, + "enableRemoteTransfer": true, + "enable": false + } }, "redis": { "address": { @@ -25,25 +48,22 @@ "port": "6379" } }, - "authCacheSetting": { - "evictTimeout": "1m", - "enableCash": false - }, - "secrets": { - "admin": "secret", - "application": "SECRET_ACCESS_KEY", - "verifyAppToken": false - }, - "journalSetting": { - "journal": { - "rotateTimeoutMs": 86400000, - "enableRemoteTransfer": true, - "enable": false, - "compress": true, - "filename": "/var/log/isp-gate-service/runtime.log", - "maxSizeMb": 512, - "bufferSize": 4096 + "metrics": { + "memory": true, + "address": { + "port": "9553", + "ip": "0.0.0.0", + "path": "/metrics" }, - "methodsPatterns": [] + "gc": true + }, + "tokensSetting": { + "adminSecret": "secret", + "applicationSecret": "secret", + "applicationVerify": false + }, + "authCacheSetting": { + "enableCash": false, + "evictTimeout": "1m" } -} +} \ No newline at end of file diff --git a/conf/remote_config.go b/conf/remote_config.go index c00f8f2..93906ba 100644 --- a/conf/remote_config.go +++ b/conf/remote_config.go @@ -20,7 +20,8 @@ const ( type ( RemoteConfig struct { - Secrets SecretSetting `schema:"Настройка секретов"` + Database structure.DBConfiguration `schema:"Настройка подключения к базе данных"` + TokensSetting TokensSetting `schema:"Настройка секретов"` ServerSetting HttpSetting `schema:"Настройка сервера"` GrpcSetting GrpcSetting `schema:"Настройка grpc соединения"` Metrics structure.MetricConfiguration `schema:"Настройка метрик"` @@ -40,15 +41,16 @@ type ( MethodsPatterns []string `schema:"Список методов для логирования,список строк вида: 'module/group/method'(* - для частичного совпадения). При обработке запроса, если вызываемый метод совпадает со строкой из списка, тела запроса и ответа записываются в лог"` } - SecretSetting struct { - Admin string `schema:"Секрет для проверки токена администратора"` - Application string `schema:"Секрет для проверки токена приложений"` - VerifyAppToken bool `schema:"Проверка подписи токена приложений"` + TokensSetting struct { + AdminSecret string `schema:"Секрет для проверки токена администратора"` + ApplicationSecret string `schema:"Секрет для проверки токена приложений"` + ApplicationVerify bool `schema:"Проверка подписи токена приложений"` } Accounting struct { - Enable bool `schema:"Статус работы учета,включает/отключает учет запросов"` - Setting []AccountingSetting `schema:"Настройка учета для приложений"` + Enable bool `schema:"Статус работы учета,включает/отключает учет запросов"` + SnapshotTimeout string `schema:"Время частоты выгрузки учтенных запросов" valid:"required~Required"` + Setting []AccountingSetting `schema:"Настройка учета для приложений"` } AccountingSetting struct { diff --git a/entity/entity.go b/entity/entity.go new file mode 100644 index 0000000..20c55b7 --- /dev/null +++ b/entity/entity.go @@ -0,0 +1,7 @@ +package entity + +type Snapshot struct { + TableName string `sql:"gate_service.snapshot" json:"-"` + AppId int32 `sql:",pk"` + LimitState map[string]interface{} +} diff --git a/log_code/code.go b/log_code/code.go index b2bfac8..bc3d90f 100644 --- a/log_code/code.go +++ b/log_code/code.go @@ -1,18 +1,22 @@ package log_code const ( - WarnProxyGrpcHandler = 604 //metadata: {"typeData":"", "method":""} - WarnConvertErrorDataMarshalResponse = 605 - WarnJournalCouldNotWriteToFile = 607 - WarnHttpServerShutdown = 602 ErrorHttpServerListen = 603 + WarnProxyGrpcHandler = 604 //metadata: {"typeData":"", "method":""} + WarnConvertErrorDataMarshalResponse = 605 + ErrorClientGrpc = 606 - ErrorClientHttp = 611 + + WarnJournalCouldNotWriteToFile = 607 ErrorClientJournal = 608 ErrorClientRedis = 609 + ErrorClientHttp = 611 ErrorAuthenticate = 612 + + ErrorClientDatabase = 615 + ErrorSnapshotAccounting = 616 ) diff --git a/main.go b/main.go index a984f4d..8b818e1 100644 --- a/main.go +++ b/main.go @@ -13,6 +13,7 @@ import ( "isp-gate-service/authenticate" "isp-gate-service/conf" "isp-gate-service/journal" + "isp-gate-service/model" "isp-gate-service/proxy" "isp-gate-service/redis" "isp-gate-service/routing" @@ -59,6 +60,7 @@ func onLocalConfigLoad(cfg *conf.Configuration) { func onRemoteConfigReceive(remoteConfig, oldRemoteConfig *conf.RemoteConfig) { localCfg := config.Get().(*conf.Configuration) + model.DbClient.ReceiveConfiguration(remoteConfig.Database) journal.Client.ReceiveConfiguration(remoteConfig.JournalSetting.Journal, localCfg.ModuleName) matcher.JournalMethods = matcher.NewAtLeastOneMatcher(remoteConfig.JournalSetting.MethodsPatterns) @@ -88,6 +90,7 @@ func socketConfiguration(cfg interface{}) structure.SocketConfiguration { func onShutdown(_ context.Context, _ os.Signal) { server.Http.Close() + accounting.Close() proxy.Close() redis.Client.Close() } diff --git a/migrations/00002_2019-11-14_init.sql b/migrations/00002_2019-11-14_init.sql new file mode 100644 index 0000000..886e04e --- /dev/null +++ b/migrations/00002_2019-11-14_init.sql @@ -0,0 +1,11 @@ +-- +goose Up + + +CREATE TABLE snapshot( + app_id INTEGER PRIMARY KEY, + limit_state jsonb +); + + +-- +goose Down +DROP SCHEMA IF EXISTS gate_service CASCADE; \ No newline at end of file diff --git a/model/client.go b/model/client.go new file mode 100644 index 0000000..2faaca6 --- /dev/null +++ b/model/client.go @@ -0,0 +1,19 @@ +package model + +import ( + "github.com/integration-system/isp-lib/database" + log "github.com/integration-system/isp-log" + "isp-gate-service/log_code" +) + +var ( + DbClient = database.NewRxDbClient( + database.WithSchemaEnsuring(), + database.WithSchemaAutoInjecting(), + database.WithMigrationsEnsuring(), + database.WithInitializingErrorHandler(func(err *database.ErrorEvent) { + log.Error(log_code.ErrorClientDatabase, err) + })) + + SnapshotRep SnapshotRepository = snapshotRepository{rxClient: DbClient} +) diff --git a/model/snapshot.go b/model/snapshot.go new file mode 100644 index 0000000..7d0ccc7 --- /dev/null +++ b/model/snapshot.go @@ -0,0 +1,56 @@ +package model + +import ( + "github.com/go-pg/pg" + "github.com/integration-system/isp-lib/database" + "isp-gate-service/entity" + + "github.com/go-pg/pg/orm" +) + +type ( + SnapshotRepository interface { + GetByApplication(int32) (*entity.Snapshot, error) + GetAll() ([]entity.Snapshot, error) + Update([]entity.Snapshot) error + } + + snapshotRepository struct { + DB orm.DB + rxClient *database.RxDbClient + } +) + +func (r snapshotRepository) Update(list []entity.Snapshot) error { + _, _ = r.getDb().Model(&list).WherePK().Delete() + _, err := r.getDb().Model(&list).Insert() + return err +} + +func (r snapshotRepository) GetAll() ([]entity.Snapshot, error) { + model := make([]entity.Snapshot, 0) + if err := r.getDb().Model(&model).Returning("*").Select(); err != nil { + return nil, err + } else { + return model, nil + } +} + +func (r snapshotRepository) GetByApplication(appId int32) (*entity.Snapshot, error) { + model := new(entity.Snapshot) + if err := r.getDb().Model(model).Where("app_id = ?", appId).Select(); err != nil { + if err == pg.ErrNoRows { + return nil, nil + } + return nil, err + } else { + return model, nil + } +} + +func (r snapshotRepository) getDb() orm.DB { + if r.DB != nil { + return r.DB + } + return r.rxClient.Unsafe() +} From 4d81fe7a265d241746a6f5cd21d70c59c755e402 Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Mon, 18 Nov 2019 15:48:50 +0300 Subject: [PATCH 02/12] 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 From 8af97e56d762eb1029a13843b7110feeab15dfd0 Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Tue, 19 Nov 2019 12:21:22 +0300 Subject: [PATCH 03/12] add recovery limit state from storage --- accounting/accountant.go | 13 ++++--- accounting/accounting.go | 66 +++++++++++++++++++++++++++-------- accounting/accounting_test.go | 36 +++++++------------ accounting/snapshot.go | 41 ++++++++-------------- accounting/state/limiter.go | 49 +++++++++++++------------- handler/handler.go | 2 +- model/snapshot.go | 13 +------ 7 files changed, 114 insertions(+), 106 deletions(-) diff --git a/accounting/accountant.go b/accounting/accountant.go index a26feb4..f4b6bb3 100644 --- a/accounting/accountant.go +++ b/accounting/accountant.go @@ -12,7 +12,7 @@ type accountant struct { limitStates map[string]state.LimitState } -func (app *accountant) Check(method string) bool { +func (app *accountant) Accept(method string) bool { patternArray := app.matcher.Match(method) stateStorage := make([]state.LimitState, len(patternArray)) for i, pattern := range patternArray { @@ -25,7 +25,12 @@ func (app *accountant) Check(method string) bool { return resp } -func (app *accountant) getLimitState() map[string]state.LimitState { - limitStates := app.limitStates - return limitStates +func (app *accountant) Snapshot() map[string]state.Snapshot { + app.mx.Lock() + snapshotLimitState := make(map[string]state.Snapshot) + for method, limitState := range app.limitStates { + snapshotLimitState[method] = limitState.Export() + } + app.mx.Unlock() + return snapshotLimitState } diff --git a/accounting/accounting.go b/accounting/accounting.go index 3c9bd5d..9e49d9b 100644 --- a/accounting/accounting.go +++ b/accounting/accounting.go @@ -5,6 +5,7 @@ import ( "github.com/integration-system/isp-log/stdcodes" "isp-gate-service/accounting/state" "isp-gate-service/conf" + "isp-gate-service/entity" "isp-gate-service/log_code" "isp-gate-service/model" "isp-gate-service/service/matcher" @@ -12,17 +13,20 @@ import ( "time" ) -var accountingByApplicationId = make(map[int32]Accounting) +var ( + accountingStorage = make(map[int32]Accounting) + accountingWorking = false +) type Accounting interface { - Check(string) bool - getLimitState() map[string]state.LimitState + Accept(string) bool + Snapshot() map[string]state.Snapshot } func ReceiveConfiguration(conf conf.Accounting) { snapshot.Stop() - newAccountingByApplicationId := make(map[int32]Accounting) + if conf.Enable { for _, s := range conf.Setting { limitStates, patternArray, err := state.InitLimitState(s.Limits) @@ -30,15 +34,7 @@ func ReceiveConfiguration(conf conf.Accounting) { log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err) } - if snapshot, err := model.SnapshotRep.GetByApplication(s.ApplicationId); err != nil { - log.Warn(log_code.ErrorSnapshotAccounting, err) - } else if snapshot != nil { - for method, limitState := range limitStates { - if value, ok := snapshot.LimitState[method]; ok { - limitState.Import(value) - } - } - } + recoveryLimitState(s.ApplicationId, limitStates) newAccountingByApplicationId[s.ApplicationId] = &accountant{ matcher: matcher.NewCacheableMatcher(patternArray), @@ -46,13 +42,19 @@ func ReceiveConfiguration(conf conf.Accounting) { mx: sync.Mutex{}, } } + if snapshotTimeout, err := time.ParseDuration(conf.SnapshotTimeout); err != nil { log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err) } else { go snapshot.Start(snapshotTimeout) } + + accountingWorking = true + } else { + accountingWorking = false } - accountingByApplicationId = newAccountingByApplicationId + + accountingStorage = newAccountingByApplicationId } func Close() { @@ -60,5 +62,39 @@ func Close() { } func GetAccounting(appId int32) Accounting { - return accountingByApplicationId[appId] + return accountingStorage[appId] +} + +func TakeSnapshot() []entity.Snapshot { + response := make([]entity.Snapshot, 0) + for appId, account := range accountingStorage { + response = append(response, entity.Snapshot{ + AppId: appId, + LimitState: account.Snapshot(), + }) + } + return response +} + +func recoveryLimitState(appId int32, limitStates map[string]state.LimitState) { + if accountingWorking { + if acc, ok := accountingStorage[appId]; ok { + snapshot := acc.Snapshot() + importLimitState(limitStates, snapshot) + } + } else { + if snapshot, err := model.SnapshotRep.GetByApplication(appId); err != nil { + log.Warn(log_code.ErrorSnapshotAccounting, err) + } else if snapshot != nil { + importLimitState(limitStates, snapshot.LimitState) + } + } +} + +func importLimitState(limitStates map[string]state.LimitState, snapshot map[string]state.Snapshot) { + for method, limitState := range limitStates { + if oldState, ok := snapshot[method]; ok { + limitState.Import(oldState) + } + } } diff --git a/accounting/accounting_test.go b/accounting/accounting_test.go index 6ecf500..016a0c8 100644 --- a/accounting/accounting_test.go +++ b/accounting/accounting_test.go @@ -61,10 +61,15 @@ func TestAccounting(t *testing.T) { model.SnapshotRep = &snapshotRepository{cache: make(map[int32]map[string]state.Snapshot)} ReceiveConfiguration(accountingSetting) - expected := true - req := reqExample[0] + req := reqExample[4] for _, path := range req.path { - a.Equal(expected, GetAccounting(req.appId).Check(path)) + a.True(GetAccounting(req.appId).Accept(path)) + } + + expected := true + req = reqExample[0] + for _, path := range req.path { + a.Equal(expected, GetAccounting(req.appId).Accept(path)) expected = !expected time.Sleep(150 * time.Millisecond) } @@ -72,31 +77,27 @@ func TestAccounting(t *testing.T) { //expected == true req = reqExample[1] for _, path := range req.path { - a.Equal(expected, GetAccounting(req.appId).Check(path)) + a.Equal(expected, GetAccounting(req.appId).Accept(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).Check(path)) + a.Equal(expectedArray[key], GetAccounting(req.appId).Accept(path)) } //expected == true req = reqExample[3] 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)) + a.Equal(expected, GetAccounting(req.appId).Accept(path)) } ReceiveConfiguration(accountingSetting) + req = reqExample[4] for _, path := range req.path { - a.False(GetAccounting(req.appId).Check(path)) + a.False(GetAccounting(req.appId).Accept(path)) } } @@ -122,14 +123,3 @@ func (r *snapshotRepository) Update(list []entity.Snapshot) error { } return nil } - -func (r *snapshotRepository) GetAll() ([]entity.Snapshot, error) { - resp := make([]entity.Snapshot, 0) - for appId, limitState := range r.cache { - resp = append(resp, entity.Snapshot{ - AppId: appId, - LimitState: limitState, - }) - } - return resp, nil -} diff --git a/accounting/snapshot.go b/accounting/snapshot.go index 33e80ae..99c1408 100644 --- a/accounting/snapshot.go +++ b/accounting/snapshot.go @@ -2,69 +2,56 @@ 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" "sync" "time" ) -var snapshot = &snapshotStruct{ +var snapshot = &snapshotTask{ process: false, timeout: make(chan time.Time), close: make(chan bool), } -type snapshotStruct struct { - wg sync.WaitGroup +type snapshotTask struct { + mx sync.Mutex process bool timeout <-chan time.Time close chan bool } -func (s *snapshotStruct) Start(timeout time.Duration) { +func (s *snapshotTask) Start(timeout time.Duration) { s.Stop() + + s.mx.Lock() s.process = true s.timeout = time.After(timeout) + s.mx.Unlock() for { select { case <-s.close: - s.wg.Wait() return case <-s.timeout: - s.wg.Add(1) - applicationAccounting := accountingByApplicationId - if err := s.complete(applicationAccounting); err != nil { + if err := s.complete(); err != nil { log.Error(log_code.ErrorSnapshotAccounting, err) } s.timeout = time.After(timeout) - s.wg.Done() } } } -func (s *snapshotStruct) Stop() { +func (s *snapshotTask) Stop() { + s.mx.Lock() if s.process { s.process = false s.close <- true } - s.wg.Wait() + s.mx.Unlock() } -func (s *snapshotStruct) complete(applicationAccounting map[int32]Accounting) error { - snapshot := make([]entity.Snapshot, 0) - for application, account := range applicationAccounting { - snapshotLimitState := make(map[string]state.Snapshot) - limitStates := account.getLimitState() - for method, limitState := range limitStates { - snapshotLimitState[method] = limitState.Export() - } - snapshot = append(snapshot, entity.Snapshot{ - AppId: application, - LimitState: snapshotLimitState, - }) - } - return model.SnapshotRep.Update(snapshot) +func (s *snapshotTask) complete() error { + snapshotList := TakeSnapshot() + return model.SnapshotRep.Update(snapshotList) } diff --git a/accounting/state/limiter.go b/accounting/state/limiter.go index ba10e72..1544c27 100644 --- a/accounting/state/limiter.go +++ b/accounting/state/limiter.go @@ -21,44 +21,45 @@ func (lim *limiter) Export() Snapshot { } } -func (lim *limiter) Import(data Snapshot) { - importLim := limiter{ - timeout: data.Timeout, - datetime: data.Datetime, - pattern: data.Pattern, - pointer: data.Pointer, +func (lim *limiter) Import(oldState Snapshot) { + oldLim := limiter{ + timeout: oldState.Timeout, + datetime: oldState.Datetime, + pattern: oldState.Pattern, + pointer: oldState.Pointer, } - lenImportDatetime := len(importLim.datetime) - lenDatetime := len(lim.datetime) - switch true { - case lenImportDatetime == lenDatetime: - lim.datetime = importLim.datetime - lim.pointer = importLim.pointer + lenOldDatetime := len(oldLim.datetime) + lenNewDatetime := len(lim.datetime) - case lenImportDatetime < lenDatetime: - oldPointer := importLim.pointer + switch true { + case lenOldDatetime == lenNewDatetime: + lim.datetime = oldLim.datetime + lim.pointer = oldLim.pointer + + case lenOldDatetime < lenNewDatetime: + oldPointer := oldLim.pointer for i := range lim.datetime { - importLim.pointer++ - if importLim.pointer >= len(importLim.datetime) { - importLim.pointer = 0 + oldLim.pointer++ + if oldLim.pointer >= len(oldLim.datetime) { + oldLim.pointer = 0 } - lim.datetime[i] = importLim.datetime[importLim.pointer] + lim.datetime[i] = oldLim.datetime[oldLim.pointer] - if oldPointer == importLim.pointer { + if oldPointer == oldLim.pointer { lim.pointer = i break } } - case lenImportDatetime > lenDatetime: + case lenOldDatetime > lenNewDatetime: for i := range lim.datetime { - importLim.pointer++ - if importLim.pointer >= len(importLim.datetime) { - importLim.pointer = 0 + oldLim.pointer++ + if oldLim.pointer >= len(oldLim.datetime) { + oldLim.pointer = 0 } - lim.datetime[i] = importLim.datetime[importLim.pointer] + lim.datetime[i] = oldLim.datetime[oldLim.pointer] } } } diff --git a/handler/handler.go b/handler/handler.go index 512df20..a46d4f0 100644 --- a/handler/handler.go +++ b/handler/handler.go @@ -77,7 +77,7 @@ func (handlerHelper) AuthenticateAccountingProxy(ctx *fasthttp.RequestCtx) domai return domain.Create().SetError(err) } - if account := accounting.GetAccounting(applicationId); account != nil && !account.Check(path) { + if account := accounting.GetAccounting(applicationId); account != nil && !account.Accept(path) { err := errors.New("accounting error") utils.WriteError(ctx, "forbidden", codes.ResourceExhausted, nil) return domain.Create().SetError(err) diff --git a/model/snapshot.go b/model/snapshot.go index 7d0ccc7..6950f2f 100644 --- a/model/snapshot.go +++ b/model/snapshot.go @@ -11,7 +11,6 @@ import ( type ( SnapshotRepository interface { GetByApplication(int32) (*entity.Snapshot, error) - GetAll() ([]entity.Snapshot, error) Update([]entity.Snapshot) error } @@ -22,20 +21,10 @@ type ( ) func (r snapshotRepository) Update(list []entity.Snapshot) error { - _, _ = r.getDb().Model(&list).WherePK().Delete() - _, err := r.getDb().Model(&list).Insert() + _, err := r.getDb().Model(&list).OnConflict("(app_id) DO UPDATE").Insert() return err } -func (r snapshotRepository) GetAll() ([]entity.Snapshot, error) { - model := make([]entity.Snapshot, 0) - if err := r.getDb().Model(&model).Returning("*").Select(); err != nil { - return nil, err - } else { - return model, nil - } -} - func (r snapshotRepository) GetByApplication(appId int32) (*entity.Snapshot, error) { model := new(entity.Snapshot) if err := r.getDb().Model(model).Where("app_id = ?", appId).Select(); err != nil { From 37c08f4500aee3304de6e324078012d6def3018b Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Tue, 19 Nov 2019 19:02:17 +0300 Subject: [PATCH 04/12] add unloading all requests --- accounting/accounting.go | 8 +- accounting/accounting_test.go | 4 + accounting/snapshot.go | 2 +- accounting/unload.go | 110 +++++++++++++++++++++ authenticate/error.go | 2 +- conf/default_remote_config.json | 6 +- conf/remote_config.go | 6 ++ entity/entity.go | 13 ++- handler/handler.go | 2 +- log_code/code.go | 1 + migrations/00002_2019-11-19_add_unload.sql | 12 +++ model/client.go | 1 + model/unload.go | 30 ++++++ 13 files changed, 191 insertions(+), 6 deletions(-) create mode 100644 accounting/unload.go create mode 100644 migrations/00002_2019-11-19_add_unload.sql create mode 100644 model/unload.go 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() +} From 8dcb8eef68b1f614bc398613d992c76e234e29e3 Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Wed, 20 Nov 2019 13:41:45 +0300 Subject: [PATCH 05/12] 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) } From 1665cc78cfae373bde768705a85c0696dd90a47c Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Wed, 20 Nov 2019 13:47:37 +0300 Subject: [PATCH 06/12] up version --- .version | 2 +- CHANGELOG.md | 2 ++ conf/default_remote_config.json | 1 + 3 files changed, 4 insertions(+), 1 deletion(-) diff --git a/.version b/.version index 9084fa2..f0bb29e 100644 --- a/.version +++ b/.version @@ -1 +1 @@ -1.1.0 +1.3.0 diff --git a/CHANGELOG.md b/CHANGELOG.md index e9977b3..73c82db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,5 @@ +## 1.3.0 +* add unload requests ## 1.2.0 * add snapshot account ## 1.1.0 diff --git a/conf/default_remote_config.json b/conf/default_remote_config.json index 2135df7..e6bc661 100644 --- a/conf/default_remote_config.json +++ b/conf/default_remote_config.json @@ -21,6 +21,7 @@ "setting": [ { "applicationId": 0, + "enableUnload": false, "limits": [ { "timeout": "1s", From 7acc4ebbd6bea0746ecfcacae0b66d979165a765 Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Wed, 20 Nov 2019 17:28:50 +0300 Subject: [PATCH 07/12] update error message --- authenticate/authenticate.go | 20 ++++++++++---------- authenticate/error.go | 9 +++++++-- handler/handler.go | 4 +++- 3 files changed, 20 insertions(+), 13 deletions(-) diff --git a/authenticate/authenticate.go b/authenticate/authenticate.go index d068f8e..fd62917 100644 --- a/authenticate/authenticate.go +++ b/authenticate/authenticate.go @@ -43,7 +43,7 @@ func Do(ctx *fasthttp.RequestCtx) (int32, error) { pathStr := getPathWithoutPrefix(path) if _, ok := routing.AllMethods[pathStr]; !ok { - return 0, createError(codes.Unimplemented) + return 0, createError("not implemented", codes.Unimplemented) } for _, notExpectedHeader := range notExpectedHeaders { @@ -57,29 +57,29 @@ func Do(ctx *fasthttp.RequestCtx) (int32, error) { appId int32 = -1 ) if len(appToken) == 0 { - return 0, createError(codes.Unauthenticated) + return 0, createError("unauthorized", codes.Unauthenticated) } else if config.GetRemote().(*conf.RemoteConfig).TokensSetting.ApplicationVerify { if appId, err = verifyToken.Application(string(appToken)); err != nil || appId == 0 { - return 0, createError(codes.Unauthenticated, "invalid token") + return 0, createError("unauthorized", codes.Unauthenticated, "invalid token") } } verifiableKeys, err := auth.verify.ApplicationToken(string(appToken)) if err != nil { log.Error(log_code.ErrorAuthenticate, err) - return 0, createError(codes.Internal) + return 0, createError("internal Server error", codes.Internal) } if len(verifiableKeys) != 4 { - return 0, createError(codes.Unauthenticated, "unknown token") + return 0, createError("unauthorized", codes.Unauthenticated, "unknown token") } applicationId, err := strconv.Atoi(verifiableKeys[utils.ApplicationIdHeader]) if err != nil { log.Error(log_code.ErrorAuthenticate, errors.WithMessagef(err, "parse appId from redis")) - return 0, createError(codes.Internal) + return 0, createError("internal Server error", codes.Internal) } if appId != -1 && int32(applicationId) != appId { - return 0, createError(codes.Unauthenticated, "unknown application identity") + return 0, createError("unauthorized", codes.Unauthenticated, "unknown application identity") } verifiableKeys[utils.DeviceTokenHeader] = string(ctx.Request.Header.Peek(utils.DeviceTokenHeader)) @@ -89,10 +89,10 @@ func Do(ctx *fasthttp.RequestCtx) (int32, error) { verifiableKeys, permittedToCall, err = auth.verify.Identity(verifiableKeys, pathStr) if err != nil { log.Error(log_code.ErrorAuthenticate, err) - return 0, createError(codes.Internal) + return 0, createError("internal Server error", codes.Internal) } if permittedToCall { - return 0, createError(codes.PermissionDenied) + return 0, createError("forbidden", codes.PermissionDenied) } for key, value := range verifiableKeys { @@ -104,7 +104,7 @@ func Do(ctx *fasthttp.RequestCtx) (int32, error) { if _, ok := routing.InnerMethods[pathStr]; ok { adminToken := ctx.Request.Header.Peek("x-auth-admin") //todo const key if verifyToken.Admin(string(adminToken)) != nil { - return 0, createError(codes.PermissionDenied) + return 0, createError("forbidden", codes.PermissionDenied) } } diff --git a/authenticate/error.go b/authenticate/error.go index d17399d..65a59ac 100644 --- a/authenticate/error.go +++ b/authenticate/error.go @@ -5,11 +5,12 @@ import ( "google.golang.org/grpc/codes" ) -func createError(status codes.Code, details ...interface{}) error { - return ErrorDescription{grpcStatus: status, details: details} +func createError(msg string, status codes.Code, details ...interface{}) error { + return ErrorDescription{message: msg, grpcStatus: status, details: details} } type ErrorDescription struct { + message string grpcStatus codes.Code details []interface{} } @@ -18,6 +19,10 @@ func (e ErrorDescription) Error() string { return fmt.Sprintf("%v", e) } +func (e ErrorDescription) Message() string { + return e.message +} + func (e ErrorDescription) ConvertToGrpcStatus() codes.Code { return e.grpcStatus } diff --git a/handler/handler.go b/handler/handler.go index 2bf4c99..840b9c9 100644 --- a/handler/handler.go +++ b/handler/handler.go @@ -66,14 +66,16 @@ func (handlerHelper) AuthenticateAccountingProxy(ctx *fasthttp.RequestCtx) domai applicationId, err := authenticate.Do(ctx) if err != nil { + message := "unknown error" status := codes.Unknown details := make([]interface{}, 0) switch e := err.(type) { case authenticate.ErrorDescription: + message = e.Message() status = e.ConvertToGrpcStatus() details = e.Details() } - utils.WriteError(ctx, "unauthorized", status, details) + utils.WriteError(ctx, message, status, details) return domain.Create().SetError(err) } From b4541f6c1bb8e36074ec9220e7e5d6ae385e5923 Mon Sep 17 00:00:00 2001 From: ykomissarov Date: Thu, 21 Nov 2019 11:39:20 +0300 Subject: [PATCH 08/12] refactoring --- Gopkg.lock | 1 + accounting/accountant.go | 2 +- accounting/accounting.go | 27 ++++++------ accounting/accounting_test.go | 4 +- accounting/snapshot.go | 4 +- accounting/{unload.go => storing.go} | 46 ++++++++++---------- accounting/storing_test.go | 50 ++++++++++++++++++++++ accounting/unload_test.go | 46 -------------------- conf/default_remote_config.json | 8 ++-- conf/remote_config.go | 14 +++--- entity/entity.go | 6 +-- migrations/00002_2019-11-19_add_unload.sql | 8 ++-- model/client.go | 2 +- model/{unload.go => requests.go} | 10 ++--- 14 files changed, 118 insertions(+), 110 deletions(-) rename accounting/{unload.go => storing.go} (59%) create mode 100644 accounting/storing_test.go delete mode 100644 accounting/unload_test.go rename model/{unload.go => requests.go} (60%) diff --git a/Gopkg.lock b/Gopkg.lock index b6c7e69..35e8408 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -638,6 +638,7 @@ "github.com/integration-system/isp-lib/structure", "github.com/integration-system/isp-lib/utils", "github.com/integration-system/isp-log", + "github.com/integration-system/isp-log/stdcodes", "github.com/json-iterator/go", "github.com/pkg/errors", "github.com/rcrowley/go-metrics", diff --git a/accounting/accountant.go b/accounting/accountant.go index f4b6bb3..cde93b0 100644 --- a/accounting/accountant.go +++ b/accounting/accountant.go @@ -27,7 +27,7 @@ func (app *accountant) Accept(method string) bool { func (app *accountant) Snapshot() map[string]state.Snapshot { app.mx.Lock() - snapshotLimitState := make(map[string]state.Snapshot) + snapshotLimitState := make(map[string]state.Snapshot, len(app.limitStates)) for method, limitState := range app.limitStates { snapshotLimitState[method] = limitState.Export() } diff --git a/accounting/accounting.go b/accounting/accounting.go index ac88932..8fc7cbd 100644 --- a/accounting/accounting.go +++ b/accounting/accounting.go @@ -16,7 +16,7 @@ import ( var ( accountingWorking = false accountingStorage = make(map[int32]Accounting) - unloadingStorage = make(map[int32]bool) + requestsStoring = make(map[int32]bool) ) type Accounting interface { @@ -27,15 +27,15 @@ type Accounting interface { func ReceiveConfiguration(conf conf.Accounting) { Close() newAccountingStorage := make(map[int32]Accounting) - newUnloadingStorage := make(map[int32]bool) + newRequestsStoring := make(map[int32]bool) if conf.Enable { - if err := unload.Init(conf.Unload); err != nil { + if err := storage.Init(conf.Storing); err != nil { log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err) } for _, s := range conf.Setting { - newUnloadingStorage[s.ApplicationId] = s.EnableUnload + newRequestsStoring[s.ApplicationId] = s.EnableStoring limitStates, patternArray, err := state.InitLimitState(s.Limits) if err != nil { @@ -62,29 +62,32 @@ func ReceiveConfiguration(conf conf.Accounting) { accountingWorking = false } - unloadingStorage = newUnloadingStorage + requestsStoring = newRequestsStoring accountingStorage = newAccountingStorage } func Accept(appId int32, path string) bool { - if unloadingStorage[appId] { - unload.TakeRequest(appId, path, time.Now()) - } - if accouter, ok := accountingStorage[appId]; !ok { + if requestsStoring[appId] { + storage.TakeRequest(appId, path, time.Now()) + } return true } else { - return accouter.Accept(path) + ok := accouter.Accept(path) + if ok && requestsStoring[appId] { + storage.TakeRequest(appId, path, time.Now()) + } + return ok } } func Close() { snapshot.Stop() - unload.Stop() + storage.Stop() } func takeSnapshot() []entity.Snapshot { - response := make([]entity.Snapshot, 0) + response := make([]entity.Snapshot, 0, len(accountingStorage)) for appId, account := range accountingStorage { response = append(response, entity.Snapshot{ AppId: appId, diff --git a/accounting/accounting_test.go b/accounting/accounting_test.go index 50fd95b..1389f83 100644 --- a/accounting/accounting_test.go +++ b/accounting/accounting_test.go @@ -26,8 +26,8 @@ var ( {Pattern: "mdm-master/group/method", MaxCount: 0, Timeout: "10s"}, }}, }, - Unload: conf.UnloadSetting{ - Count: 100, + Storing: conf.StoringSetting{ + Size: 100, Timeout: "1h", }, } diff --git a/accounting/snapshot.go b/accounting/snapshot.go index 6eea929..6e63173 100644 --- a/accounting/snapshot.go +++ b/accounting/snapshot.go @@ -34,7 +34,7 @@ func (s *snapshotTask) Start(timeout time.Duration) { case <-s.close: return case <-s.timeout: - if err := s.complete(); err != nil { + if err := s.saveSnapshot(); err != nil { log.Error(log_code.ErrorSnapshotAccounting, err) } s.timeout = time.After(timeout) @@ -51,7 +51,7 @@ func (s *snapshotTask) Stop() { s.mx.Unlock() } -func (s *snapshotTask) complete() error { +func (s *snapshotTask) saveSnapshot() error { snapshotList := takeSnapshot() return model.SnapshotRep.Update(snapshotList) } diff --git a/accounting/unload.go b/accounting/storing.go similarity index 59% rename from accounting/unload.go rename to accounting/storing.go index dc8b762..d10686a 100644 --- a/accounting/unload.go +++ b/accounting/storing.go @@ -10,31 +10,31 @@ import ( "time" ) -var unload = &unloadingTask{ +var storage = &storingTask{ mx: sync.Mutex{}, counter: 0, process: false, chanTimeout: make(chan time.Time), - chanCounter: make(chan []entity.Unload), + chanCounter: make(chan []entity.Request), chanClose: make(chan bool), } -type unloadingTask struct { - cache []entity.Unload +type storingTask struct { + buffer []entity.Request counter int process bool chanTimeout <-chan time.Time - chanCounter chan []entity.Unload + chanCounter chan []entity.Request chanClose chan bool mx sync.Mutex } -func (u *unloadingTask) Init(setting conf.UnloadSetting) error { +func (u *storingTask) Init(setting conf.StoringSetting) error { u.mx.Lock() u.process = true - u.cache = make([]entity.Unload, setting.Count) + u.buffer = make([]entity.Request, setting.Size) u.counter = 0 u.mx.Unlock() @@ -46,36 +46,36 @@ func (u *unloadingTask) Init(setting conf.UnloadSetting) error { return nil } -func (u *unloadingTask) TakeRequest(appId int32, method string, date time.Time) { +func (u *storingTask) TakeRequest(appId int32, method string, date time.Time) { u.mx.Lock() if !u.process { u.mx.Unlock() return } - u.cache[u.counter] = entity.Unload{ + u.buffer[u.counter] = entity.Request{ AppId: appId, Method: method, CreatedAt: date, } u.counter++ - if u.counter == len(u.cache) { - u.chanCounter <- u.cache + if u.counter == len(u.buffer) { + u.chanCounter <- u.buffer - oldLen := len(u.cache) + oldLen := len(u.buffer) u.counter = 0 - u.cache = make([]entity.Unload, oldLen) + u.buffer = make([]entity.Request, oldLen) } u.mx.Unlock() } -func (u *unloadingTask) Stop() { +func (u *storingTask) Stop() { u.mx.Lock() if u.process { if u.counter != 0 { - defer u.unload(u.cache[:u.counter]) + defer u.unload(u.buffer[:u.counter]) } u.chanClose <- true u.process = false @@ -83,25 +83,25 @@ func (u *unloadingTask) Stop() { u.mx.Unlock() } -func (u *unloadingTask) run(timeout time.Duration) { +func (u *storingTask) run(timeout time.Duration) { u.chanTimeout = time.After(timeout) for { select { case <-u.chanClose: return case cache := <-u.chanCounter: - u.unload(cache) + go u.unload(cache) u.chanTimeout = time.After(timeout) case <-u.chanTimeout: u.mx.Lock() if u.counter != 0 { - cache := u.cache[:u.counter] - oldLen := len(u.cache) + cache := u.buffer[:u.counter] + oldLen := len(u.buffer) u.counter = 0 - u.cache = make([]entity.Unload, oldLen) + u.buffer = make([]entity.Request, oldLen) u.mx.Unlock() - u.unload(cache) + go u.unload(cache) } else { u.mx.Unlock() } @@ -110,8 +110,8 @@ func (u *unloadingTask) run(timeout time.Duration) { } } -func (u *unloadingTask) unload(cache []entity.Unload) { - if err := model.UnloadRep.Insert(cache); err != nil { +func (u *storingTask) unload(cache []entity.Request) { + if err := model.RequestsRep.Insert(cache); err != nil { log.Error(log_code.ErrorUnloadAccounting, err) } } diff --git a/accounting/storing_test.go b/accounting/storing_test.go new file mode 100644 index 0000000..348ab8c --- /dev/null +++ b/accounting/storing_test.go @@ -0,0 +1,50 @@ +package accounting + +import ( + "github.com/stretchr/testify/assert" + "isp-gate-service/conf" + "isp-gate-service/entity" + "isp-gate-service/model" + "sync" + "testing" + "time" +) + +var unloadingSetting = conf.StoringSetting{ + Size: 3, + Timeout: "50ms", +} + +func TestStoringTask(t *testing.T) { + a := assert.New(t) + repository := &requestsRepository{cache: make([]entity.Request, 0)} + model.RequestsRep = repository + + err := storage.Init(unloadingSetting) + a.NoError(err) + + for i, j := range []string{"1", "2", "3", "4", "5"} { + storage.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"} { + storage.TakeRequest(int32(i), j, time.Now()) + } + storage.Stop() + a.Len(repository.cache, 10) +} + +type requestsRepository struct { + cache []entity.Request + mx sync.Mutex +} + +func (r *requestsRepository) Insert(model []entity.Request) error { + r.mx.Lock() + r.cache = append(r.cache, model...) + r.mx.Unlock() + return nil +} diff --git a/accounting/unload_test.go b/accounting/unload_test.go deleted file mode 100644 index 127265a..0000000 --- a/accounting/unload_test.go +++ /dev/null @@ -1,46 +0,0 @@ -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/default_remote_config.json b/conf/default_remote_config.json index e6bc661..6a3fc01 100644 --- a/conf/default_remote_config.json +++ b/conf/default_remote_config.json @@ -21,7 +21,7 @@ "setting": [ { "applicationId": 0, - "enableUnload": false, + "enableStoring": false, "limits": [ { "timeout": "1s", @@ -31,8 +31,8 @@ ] } ], - "unload": { - "count": 1, + "storing": { + "size": 10000, "timeout": "30m" } }, @@ -71,4 +71,4 @@ "enableCash": false, "evictTimeout": "1m" } -} \ No newline at end of file +} diff --git a/conf/remote_config.go b/conf/remote_config.go index 9747ac7..7a70ecf 100644 --- a/conf/remote_config.go +++ b/conf/remote_config.go @@ -48,15 +48,15 @@ type ( } Accounting struct { - Enable bool `schema:"Статус работы учета,включает/отключает учет запросов"` - SnapshotTimeout string `schema:"Время частоты выгрузки учтенных запросов" valid:"required~Required"` + Enable bool `schema:"Учет запросов,включает/отключает учет запросов"` + SnapshotTimeout string `schema:"Частота выгрузки данных учета в БД" valid:"required~Required"` Setting []AccountingSetting `schema:"Настройка учета для приложений"` - Unload UnloadSetting `schema:"Настройка общей выгрзуки запросов"` + Storing StoringSetting `schema:"Настройка хранения запросов"` } AccountingSetting struct { ApplicationId int32 `valid:"required~Required" schema:"Идентификатор приложения"` - EnableUnload bool `schema:"Включает в общую выгрузку запросы для этого приложения"` + EnableStoring bool `schema:"Хранение запросов,если включено, каждый факт обработки запроса будет фиксироваться в БД"` Limits []LimitSetting `schema:"Настройка ограничений на запросы"` } @@ -66,9 +66,9 @@ type ( Timeout string `schema:"Время жизни одного запроса"` } - UnloadSetting struct { - Count int `schema:"Ограничение по количеству для выгрузки" valid:"required~Range(1|1000000)"` - Timeout string `schema:"Ограничение по времени для выгрузки" valid:"required~Required"` + StoringSetting struct { + Size int `schema:"Размер буфера,размер буфера,при достижении которого данные сбрасываются в БД" valid:"required,range(1|1000000)"` + Timeout string `schema:"Частота сброса,периодичность сброса данных в БД" valid:"required~Required"` } HttpSetting struct { diff --git a/entity/entity.go b/entity/entity.go index d67041a..36b6f96 100644 --- a/entity/entity.go +++ b/entity/entity.go @@ -6,13 +6,13 @@ import ( ) type Snapshot struct { - TableName string `sql:"gate_service.snapshot" json:"-"` + TableName string `sql:"?db_schema.snapshot" json:"-"` AppId int32 `sql:",pk"` LimitState map[string]state.Snapshot } -type Unload struct { - TableName string `sql:"gate_service.unload" json:"-"` +type Request struct { + TableName string `sql:"?db_schema.requests" json:"-"` Id int `sql:",pk"` AppId int32 Method string diff --git a/migrations/00002_2019-11-19_add_unload.sql b/migrations/00002_2019-11-19_add_unload.sql index ab2c6e6..a7de482 100644 --- a/migrations/00002_2019-11-19_add_unload.sql +++ b/migrations/00002_2019-11-19_add_unload.sql @@ -1,12 +1,12 @@ -- +goose Up -CREATE TABLE unload +CREATE TABLE requests ( id SERIAL8 PRIMARY KEY, - app_id INTEGER NOT NULL, + app_id INT4 NOT NULL, method VARCHAR(255) NOT NULL, - created_at TIMESTAMP NOT NULL + created_at TIMESTAMP NOT NULL DEFAULT now() ); -- +goose Down -DROP TABLE unload; \ No newline at end of file +DROP TABLE requests; diff --git a/model/client.go b/model/client.go index 21712bd..2616156 100644 --- a/model/client.go +++ b/model/client.go @@ -16,5 +16,5 @@ var ( })) SnapshotRep SnapshotRepository = snapshotRepository{rxClient: DbClient} - UnloadRep UnloadRepository = unloadRepository{rxClient: DbClient} + RequestsRep RequestsRepository = requestsRepository{rxClient: DbClient} ) diff --git a/model/unload.go b/model/requests.go similarity index 60% rename from model/unload.go rename to model/requests.go index 0e1e78e..c102b26 100644 --- a/model/unload.go +++ b/model/requests.go @@ -7,22 +7,22 @@ import ( ) type ( - UnloadRepository interface { - Insert([]entity.Unload) error + RequestsRepository interface { + Insert([]entity.Request) error } - unloadRepository struct { + requestsRepository struct { DB orm.DB rxClient *database.RxDbClient } ) -func (r unloadRepository) Insert(model []entity.Unload) error { +func (r requestsRepository) Insert(model []entity.Request) error { _, err := r.getDb().Model(&model).Insert() return err } -func (r unloadRepository) getDb() orm.DB { +func (r requestsRepository) getDb() orm.DB { if r.DB != nil { return r.DB } From 3c801a4c099526fe9caf6773991539cee46c3254 Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Thu, 21 Nov 2019 13:06:18 +0300 Subject: [PATCH 09/12] fix storing test --- accounting/storing_test.go | 100 ++++++++++++++++++++++++++++++------- 1 file changed, 82 insertions(+), 18 deletions(-) diff --git a/accounting/storing_test.go b/accounting/storing_test.go index 348ab8c..9cb1934 100644 --- a/accounting/storing_test.go +++ b/accounting/storing_test.go @@ -10,41 +10,105 @@ import ( "time" ) -var unloadingSetting = conf.StoringSetting{ - Size: 3, - Timeout: "50ms", -} +var ( + timeoutSetting = conf.StoringSetting{ + Size: 3, + Timeout: "30ms", + } -func TestStoringTask(t *testing.T) { - a := assert.New(t) - repository := &requestsRepository{cache: make([]entity.Request, 0)} + bufferSetting = conf.StoringSetting{ + Size: 3, + Timeout: "2s", + } + + unloadSetting = conf.StoringSetting{ + Size: 3, + Timeout: "100ms", + } +) + +func initStoring(setting conf.StoringSetting) (*requestsRepository, error) { + repository := &requestsRepository{cache: make([]entity.Request, 0), wg: &sync.WaitGroup{}} model.RequestsRep = repository - err := storage.Init(unloadingSetting) + err := storage.Init(setting) + return repository, err +} + +func wait(wg *sync.WaitGroup) bool { + done := make(chan struct{}) + go func() { + wg.Wait() + close(done) + }() + select { + case <-done: + return true + case <-time.After(time.Second): + return false + } +} + +func TestStoringTask_Stop(t *testing.T) { + a := assert.New(t) + rep, err := initStoring(bufferSetting) a.NoError(err) - for i, j := range []string{"1", "2", "3", "4", "5"} { - storage.TakeRequest(int32(i), j, time.Now()) - } - a.Len(repository.cache, 3) - time.Sleep(time.Millisecond * 60) - a.Len(repository.cache, 5) - + rep.wg.Add(2) for i, j := range []string{"1", "2", "3", "4", "5"} { storage.TakeRequest(int32(i), j, time.Now()) } storage.Stop() - a.Len(repository.cache, 10) + a.Len(rep.cache, 5) +} + +func TestStoringTask_Buffer(t *testing.T) { + a := assert.New(t) + rep, err := initStoring(bufferSetting) + a.NoError(err) + + rep.wg.Add(1) + for i, j := range []string{"1", "2", "3", "4", "5"} { + storage.TakeRequest(int32(i), j, time.Now()) + } + a.True(wait(rep.wg)) + a.Len(rep.cache, 3) +} + +func TestStoringTask_Timeout(t *testing.T) { + a := assert.New(t) + rep, err := initStoring(timeoutSetting) + a.NoError(err) + + rep.wg.Add(1) + for i, j := range []string{"1", "2"} { + storage.TakeRequest(int32(i), j, time.Now()) + } + a.True(wait(rep.wg)) + a.Len(rep.cache, 2) +} + +func TestStoringTask_Unload(t *testing.T) { + a := assert.New(t) + rep, err := initStoring(unloadSetting) + a.NoError(err) + + rep.wg.Add(2) + for i, j := range []string{"1", "2", "3", "4", "5"} { + storage.TakeRequest(int32(i), j, time.Now()) + } + a.True(wait(rep.wg)) + a.Len(rep.cache, 5) } type requestsRepository struct { cache []entity.Request mx sync.Mutex + wg *sync.WaitGroup } func (r *requestsRepository) Insert(model []entity.Request) error { - r.mx.Lock() r.cache = append(r.cache, model...) - r.mx.Unlock() + r.wg.Done() return nil } From 7a22e3558e071bfc1cf1a49db06a294a848fbb85 Mon Sep 17 00:00:00 2001 From: ykomissarov Date: Thu, 21 Nov 2019 14:46:39 +0300 Subject: [PATCH 10/12] ref --- accounting/accounting.go | 6 ++++-- accounting/storing.go | 40 +++++++++++++++++++++++--------------- accounting/storing_test.go | 11 +++++------ 3 files changed, 33 insertions(+), 24 deletions(-) diff --git a/accounting/accounting.go b/accounting/accounting.go index 8fc7cbd..71699a6 100644 --- a/accounting/accounting.go +++ b/accounting/accounting.go @@ -30,7 +30,7 @@ func ReceiveConfiguration(conf conf.Accounting) { newRequestsStoring := make(map[int32]bool) if conf.Enable { - if err := storage.Init(conf.Storing); err != nil { + if err := InitStoringTask(conf.Storing); err != nil { log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err) } @@ -83,7 +83,9 @@ func Accept(appId int32, path string) bool { func Close() { snapshot.Stop() - storage.Stop() + if storage != nil { + storage.Stop() + } } func takeSnapshot() []entity.Snapshot { diff --git a/accounting/storing.go b/accounting/storing.go index d10686a..dbf95a5 100644 --- a/accounting/storing.go +++ b/accounting/storing.go @@ -10,14 +10,7 @@ import ( "time" ) -var storage = &storingTask{ - mx: sync.Mutex{}, - counter: 0, - process: false, - chanTimeout: make(chan time.Time), - chanCounter: make(chan []entity.Request), - chanClose: make(chan bool), -} +var storage *storingTask type storingTask struct { buffer []entity.Request @@ -29,20 +22,17 @@ type storingTask struct { chanClose chan bool mx sync.Mutex + wg sync.WaitGroup } -func (u *storingTask) Init(setting conf.StoringSetting) error { - u.mx.Lock() - u.process = true - u.buffer = make([]entity.Request, setting.Size) - u.counter = 0 - u.mx.Unlock() - +func InitStoringTask(setting conf.StoringSetting) error { timeout, err := time.ParseDuration(setting.Timeout) if err != nil { return err } - go u.run(timeout) + + storage = newStoringTask(timeout, setting.Size) + return nil } @@ -80,10 +70,12 @@ func (u *storingTask) Stop() { u.chanClose <- true u.process = false } + u.wg.Wait() u.mx.Unlock() } func (u *storingTask) run(timeout time.Duration) { + defer u.wg.Done() u.chanTimeout = time.After(timeout) for { select { @@ -115,3 +107,19 @@ func (u *storingTask) unload(cache []entity.Request) { log.Error(log_code.ErrorUnloadAccounting, err) } } + +func newStoringTask(timeout time.Duration, bufSize int) *storingTask { + task := &storingTask{ + mx: sync.Mutex{}, + counter: 0, + buffer: make([]entity.Request, bufSize), + process: true, + chanTimeout: make(chan time.Time), + chanCounter: make(chan []entity.Request), + chanClose: make(chan bool), + } + task.wg.Add(1) + go task.run(timeout) + + return task +} diff --git a/accounting/storing_test.go b/accounting/storing_test.go index 9cb1934..29e297b 100644 --- a/accounting/storing_test.go +++ b/accounting/storing_test.go @@ -30,8 +30,7 @@ var ( func initStoring(setting conf.StoringSetting) (*requestsRepository, error) { repository := &requestsRepository{cache: make([]entity.Request, 0), wg: &sync.WaitGroup{}} model.RequestsRep = repository - - err := storage.Init(setting) + err := InitStoringTask(setting) return repository, err } @@ -55,7 +54,7 @@ func TestStoringTask_Stop(t *testing.T) { a.NoError(err) rep.wg.Add(2) - for i, j := range []string{"1", "2", "3", "4", "5"} { + for i, j := range []string{"Stop_1", "Stop_2", "Stop_3", "Stop_4", "Stop_5"} { storage.TakeRequest(int32(i), j, time.Now()) } storage.Stop() @@ -68,7 +67,7 @@ func TestStoringTask_Buffer(t *testing.T) { a.NoError(err) rep.wg.Add(1) - for i, j := range []string{"1", "2", "3", "4", "5"} { + for i, j := range []string{"Buffer_1", "Buffer_2", "Buffer_3", "Buffer_4", "Buffer_5"} { storage.TakeRequest(int32(i), j, time.Now()) } a.True(wait(rep.wg)) @@ -81,7 +80,7 @@ func TestStoringTask_Timeout(t *testing.T) { a.NoError(err) rep.wg.Add(1) - for i, j := range []string{"1", "2"} { + for i, j := range []string{"Timeout_1", "Timeout_2"} { storage.TakeRequest(int32(i), j, time.Now()) } a.True(wait(rep.wg)) @@ -94,7 +93,7 @@ func TestStoringTask_Unload(t *testing.T) { a.NoError(err) rep.wg.Add(2) - for i, j := range []string{"1", "2", "3", "4", "5"} { + for i, j := range []string{"Unload_1", "Unload_2", "Unload_3", "Unload_4", "Unload_5"} { storage.TakeRequest(int32(i), j, time.Now()) } a.True(wait(rep.wg)) From bc53089fce58a0617ebaffe896211ab1282ee628 Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Thu, 21 Nov 2019 15:17:44 +0300 Subject: [PATCH 11/12] fix storing close --- accounting/storing.go | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/accounting/storing.go b/accounting/storing.go index dbf95a5..859c953 100644 --- a/accounting/storing.go +++ b/accounting/storing.go @@ -52,10 +52,7 @@ func (u *storingTask) TakeRequest(appId int32, method string, date time.Time) { u.counter++ if u.counter == len(u.buffer) { u.chanCounter <- u.buffer - - oldLen := len(u.buffer) - u.counter = 0 - u.buffer = make([]entity.Request, oldLen) + u.clearBuffer() } u.mx.Unlock() @@ -65,12 +62,15 @@ func (u *storingTask) Stop() { u.mx.Lock() if u.process { if u.counter != 0 { - defer u.unload(u.buffer[:u.counter]) + buffer := u.clearBuffer() + defer func() { + u.unload(buffer) + u.wg.Wait() + }() } u.chanClose <- true u.process = false } - u.wg.Wait() u.mx.Unlock() } @@ -87,16 +87,10 @@ func (u *storingTask) run(timeout time.Duration) { case <-u.chanTimeout: u.mx.Lock() if u.counter != 0 { - cache := u.buffer[:u.counter] - oldLen := len(u.buffer) - u.counter = 0 - u.buffer = make([]entity.Request, oldLen) - u.mx.Unlock() - - go u.unload(cache) - } else { - u.mx.Unlock() + buffer := u.clearBuffer() + go u.unload(buffer) } + u.mx.Unlock() u.chanTimeout = time.After(timeout) } } @@ -108,6 +102,14 @@ func (u *storingTask) unload(cache []entity.Request) { } } +func (u *storingTask) clearBuffer() []entity.Request { + oldBuffer := u.buffer[:u.counter] + oldLen := len(u.buffer) + u.counter = 0 + u.buffer = make([]entity.Request, oldLen) + return oldBuffer +} + func newStoringTask(timeout time.Duration, bufSize int) *storingTask { task := &storingTask{ mx: sync.Mutex{}, From 0672da8e9c7a7284c8004bb2d09b99086422b2d5 Mon Sep 17 00:00:00 2001 From: ykomissarov Date: Thu, 21 Nov 2019 15:24:19 +0300 Subject: [PATCH 12/12] upd lib --- Gopkg.lock | 80 ++++++++++++++++++++++++++++++++---------------------- Gopkg.toml | 4 --- 2 files changed, 47 insertions(+), 37 deletions(-) diff --git a/Gopkg.lock b/Gopkg.lock index 35e8408..52df29f 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -17,6 +17,14 @@ revision = "ade4e2031af3aed7fffd241084aad80a58faf421" version = "v0.1.1" +[[projects]] + digest = "1:c1100fc71e23b6a32b2c68a5202a848fd13811d5a10b12edb8019c3667d1cd9a" + name = "github.com/cenkalti/backoff" + packages = ["."] + pruneopts = "UT" + revision = "4b4cebaf850ec58f1bb1fec5bdebdf8501c2bc3f" + version = "v3.0.0" + [[projects]] digest = "1:ffe9824d294da03b391f44e1ae8281281b4afc1bdaa9588c9097785e3af10cec" name = "github.com/davecgh/go-spew" @@ -90,14 +98,6 @@ revision = "6c65a5562fc06764971b7c5d05c76c75e84bdbf7" version = "v1.3.2" -[[projects]] - digest = "1:e62657cca9badaa308d86e7716083e4c5933bb78e30a17743fc67f50be26f6f4" - name = "github.com/gorilla/websocket" - packages = ["."] - pruneopts = "UT" - revision = "c3e18be99d19e6b3e8f1559eea2c161a665c4b6b" - version = "v1.4.1" - [[projects]] digest = "1:c0d19ab64b32ce9fe5cf4ddceba78d5bc9807f0016db6b1183599da3dcc24d10" name = "github.com/hashicorp/hcl" @@ -138,18 +138,6 @@ pruneopts = "UT" revision = "ac5582987a2f25e8743e0ebb7259312adda05c23" -[[projects]] - digest = "1:12bcebed6dfc45cedc650f6dce60fe6ce6d27de88d9bfa8893a5b144c010d317" - name = "github.com/integration-system/golang-socketio" - packages = [ - ".", - "protocol", - "transport", - ] - pruneopts = "UT" - revision = "7513a9b590e428674e3c22ea82f46b28890cc17a" - version = "v1.0.0" - [[projects]] branch = "master" digest = "1:abd0cd78d6d27a98080f2b2a7fd39bb2f3d3eef6aa20c720093129f04fb41d78" @@ -158,6 +146,20 @@ pruneopts = "UT" revision = "368713356c71961354e09ab9b734740ebdd94784" +[[projects]] + digest = "1:143c6b11b882aae2896e07caad401ec0be62c330a85526b954a2cc5bdb3f75d7" + name = "github.com/integration-system/isp-etp-go" + packages = [ + "ack", + "bpool", + "client", + "gen", + "parser", + ] + pruneopts = "UT" + revision = "6e92a3dda2cf7c6ec82fc1a1ae922248754e49d9" + version = "v2.0.0" + [[projects]] branch = "master" digest = "1:9b7cbba3fe2efd27a291295e19a3731cd7bb1e0dcb6f41883e95b74f4ba0e09e" @@ -181,7 +183,7 @@ version = "v1.3.0" [[projects]] - digest = "1:6b991c544a334db5cd4e7719bc446e8b41d1221031a87b55d36d2e81ec182257" + digest = "1:2f0bb39ac14ba6a8b8d3b065e10fbfce9f555bda35935fda71001dbba703b707" name = "github.com/integration-system/isp-lib" packages = [ "backend", @@ -199,8 +201,8 @@ "utils", ] pruneopts = "UT" - revision = "5060d1348219abd8fad3628668b229779a5314c7" - version = "v1.9.0" + revision = "9ecfa413468d829dce66fe95562b4366b0dfb2a0" + version = "v2.0.0" [[projects]] branch = "master" @@ -461,7 +463,7 @@ [[projects]] branch = "master" - digest = "1:060c10c0942a53f52bc23c285f6c3d7ee12c2dafde0325e9f413e4d504963010" + digest = "1:dfb4a218519e3b4c8b5d92885496521d7f54d53350ea9ff5eacb5df2fea3d8b9" name = "github.com/valyala/fasthttp" packages = [ ".", @@ -469,7 +471,7 @@ "stackless", ] pruneopts = "UT" - revision = "5f666588000bc4a0e0852494958417036ccbb3b7" + revision = "32de06dba4ebe30a9f88b43c3bc0f767994467be" [[projects]] digest = "1:39a425f98fb19427061a693fe6bf0683c9bddec4b25b17067e34fdb465e39cb9" @@ -488,7 +490,7 @@ "ssh/terminal", ] pruneopts = "UT" - revision = "e1110fd1c708ef015366ea01799a23c459593c47" + revision = "4f8c1d86b1ba699e7a66cd649947ed270a74e0bb" [[projects]] branch = "master" @@ -504,18 +506,18 @@ "trace", ] pruneopts = "UT" - revision = "2180aed2234323691e9fd264fb1d32d20ff04b27" + revision = "fc4aabc6c91483155dade6fbb627cc953a723260" [[projects]] branch = "master" - digest = "1:a8d09768b9b35851f498a4ba24ef08b7a72aa29bdb1673324394443e076bb440" + digest = "1:adc8dbdd1348594585d83239cf52498fd87e103577dda9b50ccac2122d9ead72" name = "golang.org/x/sys" packages = [ "unix", "windows", ] pruneopts = "UT" - revision = "4c7a9d0fe056d9d1de37e1409ca8a5c17accb46a" + revision = "bd437916bb0eb726b873ee8e9b2dcf212d32e2fd" [[projects]] digest = "1:8d8faad6b12a3a4c819a3f9618cb6ee1fa1cfc33253abeeea8b55336721e3405" @@ -551,7 +553,7 @@ "googleapis/rpc/status", ] pruneopts = "UT" - revision = "16a3f7862a1a494c52b23987ef8a993fd3f9a85e" + revision = "83cc0476cb11ea0da33dacd4c6354ab192de6fe6" [[projects]] digest = "1:b59ce3ddb11daeeccccc9cb3183b58ebf8e9a779f1c853308cd91612e817a301" @@ -598,12 +600,12 @@ version = "v1.25.1" [[projects]] - digest = "1:f26a5d382387e03a40d1471dddfba85dfff9bf05352d7e42d37612677c4d3c5c" + digest = "1:b75b3deb2bce8bc079e16bb2aecfe01eb80098f5650f9e93e5643ca8b7b73737" name = "gopkg.in/yaml.v2" packages = ["."] pruneopts = "UT" - revision = "f90ceb4f409096b60e2e9076b38b304b8246e5fa" - version = "v2.2.5" + revision = "1f64d6156d11335c3f22d9330b0ad14fc1e789ce" + version = "v2.2.7" [[projects]] digest = "1:999d566ad1ae4303c456af5a155f7b42401cca4fd33552567ed9dd997b107a08" @@ -614,6 +616,18 @@ source = "https://github.com/mellium/sasl.git" version = "v0.2.1" +[[projects]] + digest = "1:25ea8c84118bb09a6ea1fe5d8a2e72d7ead40af714b74d1e849af821f3502414" + name = "nhooyr.io/websocket" + packages = [ + ".", + "internal/bpool", + "internal/wsjs", + ] + pruneopts = "UT" + revision = "edda9c633d5c78c7d38fcc952b4105dd4ccfb619" + version = "v1.7.4" + [solve-meta] analyzer-name = "dep" analyzer-version = 1 diff --git a/Gopkg.toml b/Gopkg.toml index a1b1f42..3734909 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -32,10 +32,6 @@ name = "github.com/valyala/fasthttp" branch = "master" -[[override]] - name = "github.com/integration-system/isp-lib" - version = "1.9.0" - [prune] go-tests = true unused-packages = true