Merge remote-tracking branch 'origin/accounting_request'
# Conflicts: # .version # CHANGELOG.md
This commit is contained in:
commit
3e593f759d
27 files changed
+969
-147
No files matched your search
+4
-2
@@ -1,5 +1,7 @@
|
||||
## 1.1.1
|
||||
* add x-instance-identity header
|
||||
## 1.3.0
|
||||
* add unload requests
|
||||
## 1.2.0
|
||||
* add snapshot account
|
||||
## 1.1.0
|
||||
* add token verification via JWT
|
||||
* add accounting for applications
|
||||
|
||||
Generated
+119
-42
@@ -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"
|
||||
@@ -41,6 +49,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"
|
||||
@@ -72,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"
|
||||
@@ -120,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"
|
||||
@@ -140,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"
|
||||
@@ -163,13 +183,14 @@
|
||||
version = "v1.3.0"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:a1ebd1a46e87e9343cbabec1ca99c34a7a2e0572c0160fcf266175073b2adf5f"
|
||||
digest = "1:2f0bb39ac14ba6a8b8d3b065e10fbfce9f555bda35935fda71001dbba703b707"
|
||||
name = "github.com/integration-system/isp-lib"
|
||||
packages = [
|
||||
"backend",
|
||||
"bootstrap",
|
||||
"config",
|
||||
"config/schema",
|
||||
"database",
|
||||
"http",
|
||||
"logger",
|
||||
"metric",
|
||||
@@ -180,8 +201,8 @@
|
||||
"utils",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "5060d1348219abd8fad3628668b229779a5314c7"
|
||||
version = "v1.9.0"
|
||||
revision = "9ecfa413468d829dce66fe95562b4366b0dfb2a0"
|
||||
version = "v2.0.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
@@ -202,6 +223,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 +243,7 @@
|
||||
version = "1.1.8"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:acfc228fb5fbfb82645c121e3224bd546ed68aef6dfc87f63e2d8de099a3822b"
|
||||
digest = "1:fa4b4bfa0edfb83c4690d8746ea25bc2447ad0c20063ba72adcb5725f54acde0"
|
||||
name = "github.com/klauspost/compress"
|
||||
packages = [
|
||||
"flate",
|
||||
@@ -222,8 +251,8 @@
|
||||
"zlib",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "16a4d3d7137cdefd94d420f22b5c20260674b95c"
|
||||
version = "v1.9.1"
|
||||
revision = "4e96aec082898e4dad17d8aca1a7e2d01362ff6c"
|
||||
version = "v1.9.2"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:31e761d97c76151dde79e9d28964a812c46efc5baee4085b86f68f0c654450de"
|
||||
@@ -233,6 +262,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 +362,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 +463,7 @@
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:35cbf67ac1c92eb7bd6fe70d17b75b60bd38fb2222fa71ac82d44d3813897d22"
|
||||
digest = "1:dfb4a218519e3b4c8b5d92885496521d7f54d53350ea9ff5eacb5df2fea3d8b9"
|
||||
name = "github.com/valyala/fasthttp"
|
||||
packages = [
|
||||
".",
|
||||
@@ -422,7 +471,7 @@
|
||||
"stackless",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "87c4546c7b1268a1c29c46e8f54def6f0e7596eb"
|
||||
revision = "32de06dba4ebe30a9f88b43c3bc0f767994467be"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:39a425f98fb19427061a693fe6bf0683c9bddec4b25b17067e34fdb465e39cb9"
|
||||
@@ -434,15 +483,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 = "4f8c1d86b1ba699e7a66cd649947ed270a74e0bb"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:d639fcedf8f14de3eefa8f26740091ca737108a944314a4700d482bd11a18301"
|
||||
digest = "1:957579c244f371e4490a28c38685bfdb573639943d9add65aceb2dbd0ae76d50"
|
||||
name = "golang.org/x/net"
|
||||
packages = [
|
||||
"context",
|
||||
@@ -454,18 +506,18 @@
|
||||
"trace",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "a882066a44e04a21d46e51451c71e131344e830e"
|
||||
revision = "fc4aabc6c91483155dade6fbb627cc953a723260"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:1017834f19e0d987e8b1b928f016b0a1186a202ec1867fee7112efd4b4475bd1"
|
||||
digest = "1:adc8dbdd1348594585d83239cf52498fd87e103577dda9b50ccac2122d9ead72"
|
||||
name = "golang.org/x/sys"
|
||||
packages = [
|
||||
"unix",
|
||||
"windows",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "c1f44814a5cd81a6d1cb589ef1e528bc5d305e07"
|
||||
revision = "bd437916bb0eb726b873ee8e9b2dcf212d32e2fd"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:8d8faad6b12a3a4c819a3f9618cb6ee1fa1cfc33253abeeea8b55336721e3405"
|
||||
@@ -501,10 +553,10 @@
|
||||
"googleapis/rpc/status",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "919d9bdd9fe6f1a5dd95ce5d5e4cdb8fd3c516d0"
|
||||
revision = "83cc0476cb11ea0da33dacd4c6354ab192de6fe6"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:0c0ea0f0ccec8a112245dd3ca0c3b304224ede9afd4b7a2b482a7b48471ef894"
|
||||
digest = "1:b59ce3ddb11daeeccccc9cb3183b58ebf8e9a779f1c853308cd91612e817a301"
|
||||
name = "google.golang.org/grpc"
|
||||
packages = [
|
||||
".",
|
||||
@@ -544,22 +596,45 @@
|
||||
"tap",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "9d331e2b02dd47daeecae02790f61cc88dc75a64"
|
||||
version = "v1.25.0"
|
||||
revision = "1a3960e4bd028ac0cec0a2afd27d7d8e67c11514"
|
||||
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"
|
||||
name = "mellium.im/sasl"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "e58e780e1378aa4df5dc705364ff5ae9a4dd1e04"
|
||||
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
|
||||
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 +643,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",
|
||||
@@ -576,6 +652,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",
|
||||
|
||||
@@ -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
|
||||
@@ -0,0 +1,36 @@
|
||||
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) Accept(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) Snapshot() map[string]state.Snapshot {
|
||||
app.mx.Lock()
|
||||
snapshotLimitState := make(map[string]state.Snapshot, len(app.limitStates))
|
||||
for method, limitState := range app.limitStates {
|
||||
snapshotLimitState[method] = limitState.Export()
|
||||
}
|
||||
app.mx.Unlock()
|
||||
return snapshotLimitState
|
||||
}
|
||||
+93
-24
@@ -5,50 +5,119 @@ 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"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var accountingByApplicationId = make(map[int32]*accounting)
|
||||
var (
|
||||
accountingWorking = false
|
||||
accountingStorage = make(map[int32]Accounting)
|
||||
requestsStoring = make(map[int32]bool)
|
||||
)
|
||||
|
||||
type accounting struct {
|
||||
mx sync.Mutex
|
||||
matcher matcher.Matcher
|
||||
limitStates map[string]state.LimitState
|
||||
type Accounting interface {
|
||||
Accept(string) bool
|
||||
Snapshot() map[string]state.Snapshot
|
||||
}
|
||||
|
||||
func ReceiveConfiguration(conf conf.Accounting) {
|
||||
newAccountingByApplicationId := make(map[int32]*accounting)
|
||||
Close()
|
||||
newAccountingStorage := make(map[int32]Accounting)
|
||||
newRequestsStoring := make(map[int32]bool)
|
||||
|
||||
if conf.Enable {
|
||||
if err := InitStoringTask(conf.Storing); err != nil {
|
||||
log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err)
|
||||
}
|
||||
|
||||
for _, s := range conf.Setting {
|
||||
limitState, patternArray, err := state.InitLimitState(s.Limits)
|
||||
newRequestsStoring[s.ApplicationId] = s.EnableStoring
|
||||
|
||||
limitStates, patternArray, err := state.InitLimitState(s.Limits)
|
||||
if err != nil {
|
||||
log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err)
|
||||
}
|
||||
|
||||
newAccountingByApplicationId[s.ApplicationId] = &accounting{
|
||||
recoveryLimitState(s.ApplicationId, limitStates)
|
||||
|
||||
newAccountingStorage[s.ApplicationId] = &accountant{
|
||||
matcher: matcher.NewCacheableMatcher(patternArray),
|
||||
limitStates: limitState,
|
||||
limitStates: limitStates,
|
||||
mx: sync.Mutex{},
|
||||
}
|
||||
}
|
||||
}
|
||||
accountingByApplicationId = newAccountingByApplicationId
|
||||
}
|
||||
|
||||
func GetAccounting(appId int32) *accounting {
|
||||
return accountingByApplicationId[appId]
|
||||
}
|
||||
if snapshotTimeout, err := time.ParseDuration(conf.SnapshotTimeout); err != nil {
|
||||
log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err)
|
||||
} else {
|
||||
go snapshot.Start(snapshotTimeout)
|
||||
}
|
||||
|
||||
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]
|
||||
accountingWorking = true
|
||||
} else {
|
||||
accountingWorking = false
|
||||
}
|
||||
|
||||
app.mx.Lock()
|
||||
resp := state.Update(stateStorage)
|
||||
app.mx.Unlock()
|
||||
return resp
|
||||
requestsStoring = newRequestsStoring
|
||||
accountingStorage = newAccountingStorage
|
||||
}
|
||||
|
||||
func Accept(appId int32, path string) bool {
|
||||
if accouter, ok := accountingStorage[appId]; !ok {
|
||||
if requestsStoring[appId] {
|
||||
storage.TakeRequest(appId, path, time.Now())
|
||||
}
|
||||
return true
|
||||
} else {
|
||||
ok := accouter.Accept(path)
|
||||
if ok && requestsStoring[appId] {
|
||||
storage.TakeRequest(appId, path, time.Now())
|
||||
}
|
||||
return ok
|
||||
}
|
||||
}
|
||||
|
||||
func Close() {
|
||||
snapshot.Stop()
|
||||
if storage != nil {
|
||||
storage.Stop()
|
||||
}
|
||||
}
|
||||
|
||||
func takeSnapshot() []entity.Snapshot {
|
||||
response := make([]entity.Snapshot, 0, len(accountingStorage))
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,25 +2,34 @@ 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"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
approveSetting = conf.Accounting{
|
||||
Enable: true,
|
||||
accountingSetting = conf.Accounting{
|
||||
Enable: true,
|
||||
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"},
|
||||
{Pattern: "mdm-master/group5/method", MaxCount: 3, Timeout: "10s"},
|
||||
}},
|
||||
{ApplicationId: 2, Limits: []conf.LimitSetting{
|
||||
{Pattern: "mdm-master/group/method", MaxCount: 0, Timeout: "10s"},
|
||||
}},
|
||||
},
|
||||
Storing: conf.StoringSetting{
|
||||
Size: 100,
|
||||
Timeout: "1h",
|
||||
},
|
||||
}
|
||||
|
||||
reqExample = []struct {
|
||||
@@ -45,37 +54,76 @@ 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]state.Snapshot)}
|
||||
ReceiveConfiguration(accountingSetting)
|
||||
|
||||
req := reqExample[4]
|
||||
for _, path := range req.path {
|
||||
a.True(Accept(req.appId, path))
|
||||
}
|
||||
|
||||
expected := true
|
||||
req := reqExample[0]
|
||||
req = reqExample[0]
|
||||
for _, path := range req.path {
|
||||
a.Equal(expected, GetAccounting(req.appId).Check(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).Check(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).Check(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).Check(path))
|
||||
a.Equal(expected, Accept(req.appId, path))
|
||||
}
|
||||
|
||||
ReceiveConfiguration(accountingSetting)
|
||||
|
||||
req = reqExample[4]
|
||||
for _, path := range req.path {
|
||||
a.False(Accept(req.appId, path))
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
type snapshotRepository struct {
|
||||
cache map[int32]map[string]state.Snapshot
|
||||
}
|
||||
|
||||
func (r *snapshotRepository) GetByApplication(appId int32) (*entity.Snapshot, error) {
|
||||
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 {
|
||||
for _, s := range list {
|
||||
r.cache[s.AppId] = s.LimitState
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package accounting
|
||||
|
||||
import (
|
||||
log "github.com/integration-system/isp-log"
|
||||
"isp-gate-service/log_code"
|
||||
"isp-gate-service/model"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var snapshot = &snapshotTask{
|
||||
process: false,
|
||||
timeout: make(chan time.Time),
|
||||
close: make(chan bool),
|
||||
}
|
||||
|
||||
type snapshotTask struct {
|
||||
mx sync.Mutex
|
||||
process bool
|
||||
timeout <-chan time.Time
|
||||
close chan bool
|
||||
}
|
||||
|
||||
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:
|
||||
return
|
||||
case <-s.timeout:
|
||||
if err := s.saveSnapshot(); err != nil {
|
||||
log.Error(log_code.ErrorSnapshotAccounting, err)
|
||||
}
|
||||
s.timeout = time.After(timeout)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *snapshotTask) Stop() {
|
||||
s.mx.Lock()
|
||||
if s.process {
|
||||
s.process = false
|
||||
s.close <- true
|
||||
}
|
||||
s.mx.Unlock()
|
||||
}
|
||||
|
||||
func (s *snapshotTask) saveSnapshot() error {
|
||||
snapshotList := takeSnapshot()
|
||||
return model.SnapshotRep.Update(snapshotList)
|
||||
}
|
||||
@@ -7,10 +7,19 @@ import (
|
||||
|
||||
type (
|
||||
LimitState 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
|
||||
|
||||
@@ -11,6 +11,59 @@ type limiter struct {
|
||||
pointer int
|
||||
}
|
||||
|
||||
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(oldState Snapshot) {
|
||||
oldLim := limiter{
|
||||
timeout: oldState.Timeout,
|
||||
datetime: oldState.Datetime,
|
||||
pattern: oldState.Pattern,
|
||||
pointer: oldState.Pointer,
|
||||
}
|
||||
|
||||
lenOldDatetime := len(oldLim.datetime)
|
||||
lenNewDatetime := len(lim.datetime)
|
||||
|
||||
switch true {
|
||||
case lenOldDatetime == lenNewDatetime:
|
||||
lim.datetime = oldLim.datetime
|
||||
lim.pointer = oldLim.pointer
|
||||
|
||||
case lenOldDatetime < lenNewDatetime:
|
||||
oldPointer := oldLim.pointer
|
||||
for i := range lim.datetime {
|
||||
oldLim.pointer++
|
||||
if oldLim.pointer >= len(oldLim.datetime) {
|
||||
oldLim.pointer = 0
|
||||
}
|
||||
|
||||
lim.datetime[i] = oldLim.datetime[oldLim.pointer]
|
||||
|
||||
if oldPointer == oldLim.pointer {
|
||||
lim.pointer = i
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
case lenOldDatetime > lenNewDatetime:
|
||||
for i := range lim.datetime {
|
||||
oldLim.pointer++
|
||||
if oldLim.pointer >= len(oldLim.datetime) {
|
||||
oldLim.pointer = 0
|
||||
}
|
||||
lim.datetime[i] = oldLim.datetime[oldLim.pointer]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (lim *limiter) check() (bool, int, time.Time) {
|
||||
if len(lim.datetime) == 0 {
|
||||
return false, 0, time.Time{}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
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)
|
||||
|
||||
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])
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
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 storage *storingTask
|
||||
|
||||
type storingTask struct {
|
||||
buffer []entity.Request
|
||||
counter int
|
||||
|
||||
process bool
|
||||
chanTimeout <-chan time.Time
|
||||
chanCounter chan []entity.Request
|
||||
chanClose chan bool
|
||||
|
||||
mx sync.Mutex
|
||||
wg sync.WaitGroup
|
||||
}
|
||||
|
||||
func InitStoringTask(setting conf.StoringSetting) error {
|
||||
timeout, err := time.ParseDuration(setting.Timeout)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
storage = newStoringTask(timeout, setting.Size)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (u *storingTask) TakeRequest(appId int32, method string, date time.Time) {
|
||||
u.mx.Lock()
|
||||
if !u.process {
|
||||
u.mx.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
u.buffer[u.counter] = entity.Request{
|
||||
AppId: appId,
|
||||
Method: method,
|
||||
CreatedAt: date,
|
||||
}
|
||||
|
||||
u.counter++
|
||||
if u.counter == len(u.buffer) {
|
||||
u.chanCounter <- u.buffer
|
||||
u.clearBuffer()
|
||||
}
|
||||
|
||||
u.mx.Unlock()
|
||||
}
|
||||
|
||||
func (u *storingTask) Stop() {
|
||||
u.mx.Lock()
|
||||
if u.process {
|
||||
if u.counter != 0 {
|
||||
buffer := u.clearBuffer()
|
||||
defer func() {
|
||||
u.unload(buffer)
|
||||
u.wg.Wait()
|
||||
}()
|
||||
}
|
||||
u.chanClose <- true
|
||||
u.process = false
|
||||
}
|
||||
u.mx.Unlock()
|
||||
}
|
||||
|
||||
func (u *storingTask) run(timeout time.Duration) {
|
||||
defer u.wg.Done()
|
||||
u.chanTimeout = time.After(timeout)
|
||||
for {
|
||||
select {
|
||||
case <-u.chanClose:
|
||||
return
|
||||
case cache := <-u.chanCounter:
|
||||
go u.unload(cache)
|
||||
u.chanTimeout = time.After(timeout)
|
||||
case <-u.chanTimeout:
|
||||
u.mx.Lock()
|
||||
if u.counter != 0 {
|
||||
buffer := u.clearBuffer()
|
||||
go u.unload(buffer)
|
||||
}
|
||||
u.mx.Unlock()
|
||||
u.chanTimeout = time.After(timeout)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (u *storingTask) unload(cache []entity.Request) {
|
||||
if err := model.RequestsRep.Insert(cache); err != nil {
|
||||
log.Error(log_code.ErrorUnloadAccounting, err)
|
||||
}
|
||||
}
|
||||
|
||||
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{},
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package accounting
|
||||
|
||||
import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
"isp-gate-service/conf"
|
||||
"isp-gate-service/entity"
|
||||
"isp-gate-service/model"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
timeoutSetting = conf.StoringSetting{
|
||||
Size: 3,
|
||||
Timeout: "30ms",
|
||||
}
|
||||
|
||||
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 := InitStoringTask(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)
|
||||
|
||||
rep.wg.Add(2)
|
||||
for i, j := range []string{"Stop_1", "Stop_2", "Stop_3", "Stop_4", "Stop_5"} {
|
||||
storage.TakeRequest(int32(i), j, time.Now())
|
||||
}
|
||||
storage.Stop()
|
||||
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{"Buffer_1", "Buffer_2", "Buffer_3", "Buffer_4", "Buffer_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{"Timeout_1", "Timeout_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{"Unload_1", "Unload_2", "Unload_3", "Unload_4", "Unload_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.cache = append(r.cache, model...)
|
||||
r.wg.Done()
|
||||
return nil
|
||||
}
|
||||
@@ -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)
|
||||
} else if config.GetRemote().(*conf.RemoteConfig).Secrets.VerifyAppToken {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,11 +5,12 @@ import (
|
||||
"google.golang.org/grpc/codes"
|
||||
)
|
||||
|
||||
func createError(status codes.Code, details ...interface{}) ErrorDescription {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -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,51 @@
|
||||
{
|
||||
"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
|
||||
},
|
||||
"httpSetting": {
|
||||
"maxRequestBodySizeBytes": 0
|
||||
},
|
||||
"accountingSetting": {
|
||||
"enable": false,
|
||||
"setting": []
|
||||
"snapshotTimeout": "1h",
|
||||
"setting": [
|
||||
{
|
||||
"applicationId": 0,
|
||||
"enableStoring": false,
|
||||
"limits": [
|
||||
{
|
||||
"timeout": "1s",
|
||||
"maxCount": 500,
|
||||
"pattern": "/example/module/group/method"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"storing": {
|
||||
"size": 10000,
|
||||
"timeout": "30m"
|
||||
}
|
||||
},
|
||||
"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 +53,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"
|
||||
}
|
||||
}
|
||||
+16
-7
@@ -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,19 +41,22 @@ 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:"Настройка учета для приложений"`
|
||||
Storing StoringSetting `schema:"Настройка хранения запросов"`
|
||||
}
|
||||
|
||||
AccountingSetting struct {
|
||||
ApplicationId int32 `valid:"required~Required" schema:"Идентификатор приложения"`
|
||||
EnableStoring bool `schema:"Хранение запросов,если включено, каждый факт обработки запроса будет фиксироваться в БД"`
|
||||
Limits []LimitSetting `schema:"Настройка ограничений на запросы"`
|
||||
}
|
||||
|
||||
@@ -62,6 +66,11 @@ type (
|
||||
Timeout string `schema:"Время жизни одного запроса"`
|
||||
}
|
||||
|
||||
StoringSetting struct {
|
||||
Size int `schema:"Размер буфера,размер буфера,при достижении которого данные сбрасываются в БД" valid:"required,range(1|1000000)"`
|
||||
Timeout string `schema:"Частота сброса,периодичность сброса данных в БД" valid:"required~Required"`
|
||||
}
|
||||
|
||||
HttpSetting struct {
|
||||
MaxRequestBodySizeBytes int64 `schema:"Максимальный размер тела запроса,в байтайх, по умолчанию: 512 MB"`
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package entity
|
||||
|
||||
import (
|
||||
"isp-gate-service/accounting/state"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Snapshot struct {
|
||||
TableName string `sql:"?db_schema.snapshot" json:"-"`
|
||||
AppId int32 `sql:",pk"`
|
||||
LimitState map[string]state.Snapshot
|
||||
}
|
||||
|
||||
type Request struct {
|
||||
TableName string `sql:"?db_schema.requests" json:"-"`
|
||||
Id int `sql:",pk"`
|
||||
AppId int32
|
||||
Method string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
+7
-6
@@ -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)
|
||||
@@ -66,23 +66,24 @@ func (handlerHelper) AuthenticateApproveProxy(ctx *fasthttp.RequestCtx) domain.P
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
if approver := accounting.GetAccounting(applicationId); approver != nil && !approver.Check(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)
|
||||
}
|
||||
|
||||
return p.ProxyRequest(ctx)
|
||||
}
|
||||
|
||||
|
||||
+10
-5
@@ -1,18 +1,23 @@
|
||||
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
|
||||
ErrorUnloadAccounting = 617
|
||||
)
|
||||
@@ -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,9 @@
|
||||
-- +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,12 @@
|
||||
-- +goose Up
|
||||
|
||||
CREATE TABLE requests
|
||||
(
|
||||
id SERIAL8 PRIMARY KEY,
|
||||
app_id INT4 NOT NULL,
|
||||
method VARCHAR(255) NOT NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE requests;
|
||||
@@ -0,0 +1,20 @@
|
||||
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}
|
||||
RequestsRep RequestsRepository = requestsRepository{rxClient: DbClient}
|
||||
)
|
||||
@@ -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 (
|
||||
RequestsRepository interface {
|
||||
Insert([]entity.Request) error
|
||||
}
|
||||
|
||||
requestsRepository struct {
|
||||
DB orm.DB
|
||||
rxClient *database.RxDbClient
|
||||
}
|
||||
)
|
||||
|
||||
func (r requestsRepository) Insert(model []entity.Request) error {
|
||||
_, err := r.getDb().Model(&model).Insert()
|
||||
return err
|
||||
}
|
||||
|
||||
func (r requestsRepository) getDb() orm.DB {
|
||||
if r.DB != nil {
|
||||
return r.DB
|
||||
}
|
||||
return r.rxClient.Unsafe()
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
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)
|
||||
Update([]entity.Snapshot) error
|
||||
}
|
||||
|
||||
snapshotRepository struct {
|
||||
DB orm.DB
|
||||
rxClient *database.RxDbClient
|
||||
}
|
||||
)
|
||||
|
||||
func (r snapshotRepository) Update(list []entity.Snapshot) error {
|
||||
_, err := r.getDb().Model(&list).OnConflict("(app_id) DO UPDATE").Insert()
|
||||
return err
|
||||
}
|
||||
|
||||
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