add snapshot
This commit is contained in:
1 parent
0e3c14d099
commit
3d2cee1ae8
18 files changed
+521
-87
No files matched your search
Generated
+79
-17
@@ -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",
|
||||
|
||||
@@ -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
|
||||
}
|
||||
+35
-23
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -7,6 +7,8 @@ import (
|
||||
|
||||
type (
|
||||
LimitState interface {
|
||||
Import(interface{}) error
|
||||
Export() interface{}
|
||||
check() (bool, int, time.Time)
|
||||
update(int, time.Time)
|
||||
}
|
||||
|
||||
@@ -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{}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package entity
|
||||
|
||||
type Snapshot struct {
|
||||
TableName string `sql:"gate_service.snapshot" json:"-"`
|
||||
AppId int32 `sql:",pk"`
|
||||
LimitState map[string]interface{}
|
||||
}
|
||||
+9
-5
@@ -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
|
||||
)
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
@@ -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}
|
||||
)
|
||||
@@ -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()
|
||||
}
|
||||
Reference in new issue
Block a user