ref
This commit is contained in:
1 parent
8c68ffea8c
commit
422bdb9831
13 files changed
+185
-163
No files matched your search
@@ -0,0 +1,54 @@
|
||||
package accounting
|
||||
|
||||
import (
|
||||
log "github.com/integration-system/isp-log"
|
||||
"isp-gate-service/accounting/state"
|
||||
"isp-gate-service/conf"
|
||||
"isp-gate-service/log_code"
|
||||
"isp-gate-service/service/matcher"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var accountingByApplicationId = make(map[int64]*accounting)
|
||||
|
||||
type accounting struct {
|
||||
mx sync.Mutex
|
||||
matcher matcher.Matcher
|
||||
limitStates map[string]state.LimitState
|
||||
}
|
||||
|
||||
func ReceiveConfiguration(conf conf.Accounting) {
|
||||
newAccountingByApplicationId := make(map[int64]*accounting)
|
||||
if conf.Enable {
|
||||
for _, s := range conf.Setting {
|
||||
limitState, patternArray, err := state.InitLimitState(s.Limits)
|
||||
if err != nil {
|
||||
log.Fatal(log_code.FatalConfigApproveSetting, err)
|
||||
}
|
||||
|
||||
newAccountingByApplicationId[s.ApplicationId] = &accounting{
|
||||
matcher: matcher.NewCacheableMatcher(patternArray),
|
||||
limitStates: limitState,
|
||||
mx: sync.Mutex{},
|
||||
}
|
||||
}
|
||||
}
|
||||
accountingByApplicationId = newAccountingByApplicationId
|
||||
}
|
||||
|
||||
func GetAccounting(appId int64) *accounting {
|
||||
return accountingByApplicationId[appId]
|
||||
}
|
||||
|
||||
func (app *accounting) TakeAccount(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
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package approve
|
||||
package accounting
|
||||
|
||||
import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -8,16 +8,19 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
approveSetting = []conf.ApproveSetting{
|
||||
{ApplicationId: 1, Limits: []conf.LimitSetting{
|
||||
{Pattern: "mdm-master/group/method", MaxCount: 1, Lifetime: "290ms"},
|
||||
{Pattern: "mdm-master/group3/method", MaxCount: 10, Lifetime: "10s"},
|
||||
{Pattern: "mdm-master/group3/*", MaxCount: 5, Lifetime: "10s"},
|
||||
{Pattern: "mdm-master/group4/method", MaxCount: 2, Lifetime: "0s"},
|
||||
}},
|
||||
{ApplicationId: 2, Limits: []conf.LimitSetting{
|
||||
{Pattern: "mdm-master/group/method", MaxCount: 0, Lifetime: "10s"},
|
||||
}},
|
||||
approveSetting = conf.Accounting{
|
||||
Enable: true,
|
||||
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"},
|
||||
}},
|
||||
{ApplicationId: 2, Limits: []conf.LimitSetting{
|
||||
{Pattern: "mdm-master/group/method", MaxCount: 0, Timeout: "10s"},
|
||||
}},
|
||||
},
|
||||
}
|
||||
|
||||
reqExample = []struct {
|
||||
@@ -52,7 +55,7 @@ func TestApprove(t *testing.T) {
|
||||
expected := true
|
||||
req := reqExample[0]
|
||||
for _, path := range req.path {
|
||||
a.Equal(expected, GetApprove(req.appId).ApproveMethod(path))
|
||||
a.Equal(expected, GetAccounting(req.appId).TakeAccount(path))
|
||||
expected = !expected
|
||||
time.Sleep(150 * time.Millisecond)
|
||||
}
|
||||
@@ -60,19 +63,19 @@ func TestApprove(t *testing.T) {
|
||||
//expected == true
|
||||
req = reqExample[1]
|
||||
for _, path := range req.path {
|
||||
a.Equal(expected, GetApprove(req.appId).ApproveMethod(path))
|
||||
a.Equal(expected, GetAccounting(req.appId).TakeAccount(path))
|
||||
expected = !expected
|
||||
}
|
||||
|
||||
req = reqExample[2]
|
||||
expectedArray := []bool{true, true, true, true, true, false}
|
||||
for key, path := range req.path {
|
||||
a.Equal(expectedArray[key], GetApprove(req.appId).ApproveMethod(path))
|
||||
a.Equal(expectedArray[key], GetAccounting(req.appId).TakeAccount(path))
|
||||
}
|
||||
|
||||
//expected == true
|
||||
req = reqExample[3]
|
||||
for _, path := range req.path {
|
||||
a.Equal(expected, GetApprove(req.appId).ApproveMethod(path))
|
||||
a.Equal(expected, GetAccounting(req.appId).TakeAccount(path))
|
||||
}
|
||||
}
|
||||
@@ -12,8 +12,8 @@ type (
|
||||
}
|
||||
|
||||
updateRequest struct {
|
||||
pointer int
|
||||
datetime time.Time
|
||||
pointer int
|
||||
requestTime time.Time
|
||||
}
|
||||
)
|
||||
|
||||
@@ -22,20 +22,20 @@ func InitLimitState(limits []conf.LimitSetting) (map[string]LimitState, []string
|
||||
patternArray := make([]string, len(limits))
|
||||
|
||||
for i, limit := range limits {
|
||||
lifetime, err := time.ParseDuration(limit.Lifetime)
|
||||
timeout, err := time.ParseDuration(limit.Timeout)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if lifetime == 0 && limit.MaxCount != 0 {
|
||||
if timeout == 0 && limit.MaxCount != 0 {
|
||||
limit.MaxCount = 1
|
||||
}
|
||||
|
||||
patternArray[i] = limit.Pattern
|
||||
limitStates[limit.Pattern] = &limiter{
|
||||
lifetime: lifetime,
|
||||
timeout: timeout,
|
||||
datetime: make([]time.Time, limit.MaxCount),
|
||||
pattern: limit.Pattern,
|
||||
point: -1,
|
||||
pointer: -1,
|
||||
}
|
||||
}
|
||||
return limitStates, patternArray, nil
|
||||
@@ -44,15 +44,15 @@ func InitLimitState(limits []conf.LimitSetting) (map[string]LimitState, []string
|
||||
func Update(states []LimitState) bool {
|
||||
update := make([]updateRequest, len(states))
|
||||
for i, st := range states {
|
||||
if ok, point, datetime := st.check(); ok {
|
||||
update[i] = updateRequest{pointer: point, datetime: datetime}
|
||||
if ok, point, requestTime := st.check(); ok {
|
||||
update[i] = updateRequest{pointer: point, requestTime: requestTime}
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
for i, st := range states {
|
||||
u := update[i]
|
||||
st.update(u.pointer, u.datetime)
|
||||
st.update(u.pointer, u.requestTime)
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package state
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type limiter struct {
|
||||
timeout time.Duration
|
||||
datetime []time.Time
|
||||
pattern string
|
||||
pointer int
|
||||
}
|
||||
|
||||
func (lim *limiter) check() (bool, int, time.Time) {
|
||||
if len(lim.datetime) == 0 {
|
||||
return false, 0, time.Time{}
|
||||
}
|
||||
if lim.timeout == 0 {
|
||||
return true, 0, time.Now()
|
||||
}
|
||||
|
||||
pointer := lim.pointer + 1
|
||||
if pointer >= len(lim.datetime) {
|
||||
pointer = 0
|
||||
}
|
||||
date := lim.datetime[pointer]
|
||||
requestTime := time.Now()
|
||||
account := requestTime.Sub(date) > lim.timeout
|
||||
|
||||
return account, pointer, requestTime
|
||||
}
|
||||
|
||||
func (lim *limiter) update(point int, requestTime time.Time) {
|
||||
lim.pointer = point
|
||||
lim.datetime[point] = requestTime
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
package approve
|
||||
|
||||
import (
|
||||
log "github.com/integration-system/isp-log"
|
||||
"isp-gate-service/approve/state"
|
||||
"isp-gate-service/conf"
|
||||
"isp-gate-service/log_code"
|
||||
"isp-gate-service/service/matcher"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var approvingByAppId map[int64]*approve
|
||||
|
||||
type approve struct {
|
||||
mx sync.Mutex
|
||||
matcher matcher.Matcher
|
||||
limitStates map[string]state.LimitState
|
||||
}
|
||||
|
||||
func ReceiveConfiguration(setting []conf.ApproveSetting) {
|
||||
approvingByAppId = make(map[int64]*approve)
|
||||
for _, s := range setting {
|
||||
limitState, patternArray, err := state.InitLimitState(s.Limits)
|
||||
if err != nil {
|
||||
log.Fatal(log_code.FatalConfigApproveSetting, err)
|
||||
}
|
||||
|
||||
approvingByAppId[s.ApplicationId] = &approve{
|
||||
matcher: matcher.NewCacheableMatcher(patternArray),
|
||||
limitStates: limitState,
|
||||
mx: sync.Mutex{},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func GetApprove(appId int64) *approve {
|
||||
return approvingByAppId[appId]
|
||||
}
|
||||
|
||||
func (app *approve) ApproveMethod(method string) bool {
|
||||
app.mx.Lock()
|
||||
|
||||
stateStorage := make([]state.LimitState, 0)
|
||||
patternArray := app.matcher.Match(method)
|
||||
for _, pattern := range patternArray {
|
||||
stateStorage = append(stateStorage, app.limitStates[pattern])
|
||||
}
|
||||
|
||||
resp := state.Update(stateStorage)
|
||||
app.mx.Unlock()
|
||||
return resp
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
package state
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type limiter struct {
|
||||
lifetime time.Duration
|
||||
datetime []time.Time
|
||||
pattern string
|
||||
point int
|
||||
}
|
||||
|
||||
func (lim *limiter) check() (bool, int, time.Time) {
|
||||
if len(lim.datetime) == 0 {
|
||||
return false, 0, time.Time{}
|
||||
}
|
||||
if lim.lifetime == 0 {
|
||||
return true, 0, time.Now()
|
||||
}
|
||||
|
||||
point := lim.point + 1
|
||||
if point >= len(lim.datetime) {
|
||||
point = 0
|
||||
}
|
||||
date := lim.datetime[point]
|
||||
now := time.Now()
|
||||
approve := now.Sub(date) > lim.lifetime
|
||||
|
||||
return approve, point, now
|
||||
}
|
||||
|
||||
func (lim *limiter) update(point int, time time.Time) {
|
||||
lim.point = point
|
||||
lim.datetime[point] = time
|
||||
}
|
||||
+16
-18
@@ -20,25 +20,30 @@ const (
|
||||
|
||||
type (
|
||||
RemoteConfig struct {
|
||||
SecretKey string
|
||||
ServerSetting ServerSetting
|
||||
GrpcSetting GrpcSetting
|
||||
SecretKey string `schema:"Секрет"`
|
||||
ServerSetting ServerSetting `schema:"Настройка сервера"`
|
||||
GrpcSetting GrpcSetting `schema:"Настройка grpc соединения"`
|
||||
Metrics structure.MetricConfiguration `schema:"Настройка метрик"`
|
||||
Journal rx.Config `schema:"Настройка логирования"`
|
||||
JournalingMethodsPatterns []string `schema:"Список методов для логирования,список строк вида: 'module/group/method'(* - для частичного совпадения). При обработке запроса, если вызываемый метод совпадает со строкой из списка, тела запроса и ответа записываются в лог"`
|
||||
Redis structure.RedisConfiguration `schema:"Настрока Redis" valid:"required~Required"`
|
||||
ApproveSetting []ApproveSetting
|
||||
Redis structure.RedisConfiguration `schema:"Настройка Redis" valid:"required~Required"`
|
||||
AccountingSetting Accounting `schema:"Настройка учета запросов"`
|
||||
}
|
||||
|
||||
ApproveSetting struct {
|
||||
ApplicationId int64
|
||||
Limits []LimitSetting
|
||||
Accounting struct {
|
||||
Enable bool `schema:"Статус работы учета,включает/отключает учет запросов"`
|
||||
Setting []AccountingSetting `schema:"Настройка учета для приложений"`
|
||||
}
|
||||
|
||||
AccountingSetting struct {
|
||||
ApplicationId int64 `valid:"required~Required" schema:"Идентификатор приложения"`
|
||||
Limits []LimitSetting `schema:"Настройка ограничений на запросы"`
|
||||
}
|
||||
|
||||
LimitSetting struct {
|
||||
Pattern string
|
||||
MaxCount int
|
||||
Lifetime string
|
||||
Pattern string `valid:"required~Required" schema:"Шаблон пути,указывается путь для которого будут применяется ограничения; поддерживается '/*' для неполного совпадения"`
|
||||
MaxCount int `schema:"Количество запросов"`
|
||||
Timeout string `schema:"Время жизни одного запроса"`
|
||||
}
|
||||
|
||||
ServerSetting struct {
|
||||
@@ -74,10 +79,3 @@ func (cfg GrpcSetting) GetTransferFileBufferSize() int64 {
|
||||
}
|
||||
return cfg.MultipartDataTransferBufferSizeBytes
|
||||
}
|
||||
|
||||
/*func (cfg GrpcSetting) GetMaxRequestBodySize() int64 {
|
||||
if cfg.MaxRequestBodySizeBytes <= 0 {
|
||||
return defaultMaxRequestBodySize
|
||||
}
|
||||
return cfg.MaxRequestBodySizeBytes
|
||||
}*/
|
||||
+13
-12
@@ -6,7 +6,7 @@ import (
|
||||
"github.com/pkg/errors"
|
||||
"github.com/valyala/fasthttp"
|
||||
"google.golang.org/grpc/codes"
|
||||
"isp-gate-service/approve"
|
||||
"isp-gate-service/accounting"
|
||||
"isp-gate-service/authenticate"
|
||||
"isp-gate-service/conf"
|
||||
"isp-gate-service/domain"
|
||||
@@ -35,19 +35,20 @@ func CompleteRequest(ctx *fasthttp.RequestCtx) {
|
||||
statusCode := ctx.Response.StatusCode()
|
||||
service.Metrics.UpdateStatusCounter(helper.SetMetricStatus(statusCode))
|
||||
if statusCode == http.StatusOK {
|
||||
service.Metrics.UpdateResponseTime(executionTime)
|
||||
service.Metrics.UpdateMethodResponseTime(uri, executionTime)
|
||||
}
|
||||
|
||||
requestBody, responseBody, err := resp.Get()
|
||||
if config.GetRemote().(*conf.RemoteConfig).Journal.Enable && matcher.JournalMethods.Match(uri) {
|
||||
if err != nil {
|
||||
if err := journal.Client.Error(uri, requestBody, responseBody, err); err != nil {
|
||||
log.Warnf(log_code.WarnJournalCouldNotWriteToFile, "could not write to file journal: %v", err)
|
||||
}
|
||||
} else {
|
||||
if err := journal.Client.Info(uri, requestBody, responseBody); err != nil {
|
||||
log.Warnf(log_code.WarnJournalCouldNotWriteToFile, "could not write to file journal: %v", err)
|
||||
if config.GetRemote().(*conf.RemoteConfig).Journal.Enable {
|
||||
if matcher.JournalMethods.Match(uri) {
|
||||
if err != nil {
|
||||
if err := journal.Client.Error(uri, requestBody, responseBody, err); err != nil {
|
||||
log.Warnf(log_code.WarnJournalCouldNotWriteToFile, "could not write to file journal: %v", err)
|
||||
}
|
||||
} else {
|
||||
if err := journal.Client.Info(uri, requestBody, responseBody); err != nil {
|
||||
log.Warnf(log_code.WarnJournalCouldNotWriteToFile, "could not write to file journal: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -67,8 +68,8 @@ func (handlerHelper) AuthenticateApproveProxy(ctx *fasthttp.RequestCtx) domain.P
|
||||
return domain.Create().SetError(err)
|
||||
}
|
||||
|
||||
if approver := approve.GetApprove(applicationId); approver != nil && !approver.ApproveMethod(path) {
|
||||
err := errors.New("approve error")
|
||||
if approver := accounting.GetAccounting(applicationId); approver != nil && !approver.TakeAccount(path) {
|
||||
err := errors.New("accounting error")
|
||||
utils.WriteError(ctx, "forbidden", codes.PermissionDenied, nil)
|
||||
return domain.Create().SetError(err)
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"github.com/integration-system/isp-lib/metric"
|
||||
"github.com/integration-system/isp-lib/structure"
|
||||
log "github.com/integration-system/isp-log"
|
||||
"isp-gate-service/approve"
|
||||
"isp-gate-service/accounting"
|
||||
"isp-gate-service/conf"
|
||||
"isp-gate-service/journal"
|
||||
"isp-gate-service/log_code"
|
||||
@@ -41,7 +41,7 @@ func main() {
|
||||
for _, location := range cfg.Locations {
|
||||
if p, err := proxy.Init(location); err != nil {
|
||||
log.Fatal(log_code.FatalLocalConfig, err)
|
||||
} else {
|
||||
} else if location.TargetModule != "" {
|
||||
bs.RequireModule(location.TargetModule, p.Consumer, false)
|
||||
}
|
||||
}
|
||||
@@ -61,7 +61,7 @@ func onRemoteConfigReceive(remoteConfig, oldRemoteConfig *conf.RemoteConfig) {
|
||||
journal.Client.ReceiveConfiguration(remoteConfig.Journal, localCfg.ModuleName)
|
||||
redis.Client.ReceiveConfiguration(remoteConfig.Redis)
|
||||
server.Http.Init(remoteConfig.ServerSetting.MaxRequestBodySizeBytes)
|
||||
approve.ReceiveConfiguration(remoteConfig.ApproveSetting)
|
||||
accounting.ReceiveConfiguration(remoteConfig.AccountingSetting)
|
||||
|
||||
matcher.JournalMethods = matcher.NewAtLeastOneMatcher(remoteConfig.JournalingMethodsPatterns)
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"isp-gate-service/conf"
|
||||
"isp-gate-service/domain"
|
||||
"isp-gate-service/proxy/grpc"
|
||||
"isp-gate-service/proxy/health_check"
|
||||
"isp-gate-service/proxy/http"
|
||||
"strings"
|
||||
)
|
||||
@@ -14,8 +15,9 @@ import (
|
||||
var store = make(map[string]Proxy)
|
||||
|
||||
const (
|
||||
httpProtocol = "http"
|
||||
grpcProtocol = "grpc"
|
||||
httpProtocol = "http"
|
||||
grpcProtocol = "grpc"
|
||||
healthCheckProtocol = "healthсheck"
|
||||
)
|
||||
|
||||
type (
|
||||
@@ -39,8 +41,12 @@ func Init(location conf.Location) (Proxy, error) {
|
||||
proxy := grpc.NewProxy()
|
||||
store[location.PathPrefix] = proxy
|
||||
return proxy, nil
|
||||
case healthCheckProtocol:
|
||||
proxy := health_check.NewProxy()
|
||||
store[location.PathPrefix] = proxy
|
||||
return proxy, nil
|
||||
default:
|
||||
return nil, errors.New("unknown protocol")
|
||||
return nil, errors.Errorf("unknown protocol '%s'", location.Protocol)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package health_check
|
||||
|
||||
import (
|
||||
"github.com/integration-system/isp-lib/structure"
|
||||
"github.com/valyala/fasthttp"
|
||||
"isp-gate-service/domain"
|
||||
)
|
||||
|
||||
type healthCheckProxy struct {
|
||||
}
|
||||
|
||||
func NewProxy() *healthCheckProxy {
|
||||
return &healthCheckProxy{}
|
||||
}
|
||||
|
||||
func (p *healthCheckProxy) Consumer(addressList []structure.AddressConfiguration) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (p *healthCheckProxy) ProxyRequest(ctx *fasthttp.RequestCtx) domain.ProxyResponse {
|
||||
return domain.Create()
|
||||
}
|
||||
|
||||
func (p *healthCheckProxy) Close() {
|
||||
|
||||
}
|
||||
@@ -13,8 +13,7 @@ func (mm runtimeMatcher) Match(method string) []string {
|
||||
for _, pattern := range mm.patterns {
|
||||
patternLen := len(pattern)
|
||||
if patternLen > 0 && pattern[patternLen-1] == '*' {
|
||||
pattern = pattern[:patternLen-1]
|
||||
if strings.HasPrefix(method, pattern) {
|
||||
if strings.HasPrefix(method, pattern[:patternLen-1]) {
|
||||
resp = append(resp, pattern)
|
||||
}
|
||||
} else if strings.EqualFold(method, pattern) {
|
||||
|
||||
@@ -23,7 +23,6 @@ type (
|
||||
methodLock sync.RWMutex
|
||||
statusCounters map[string]metrics.Counter
|
||||
statusLock sync.RWMutex
|
||||
responseTime metrics.Histogram
|
||||
}
|
||||
)
|
||||
|
||||
@@ -31,12 +30,6 @@ func (m *metricService) Init() {
|
||||
m.mh = &metricHolder{
|
||||
methodHistograms: make(map[string]metrics.Histogram),
|
||||
statusCounters: make(map[string]metrics.Counter),
|
||||
responseTime: metrics.GetOrRegisterHistogram(
|
||||
"http.response.time", metric.GetRegistry(), metrics.NewUniformSample(defaultSampleSize),
|
||||
),
|
||||
//routerResponseTime: metrics.GetOrRegisterHistogram(
|
||||
// "grpc.router.response.time", metric.GetRegistry(), metrics.NewUniformSample(defaultSampleSize),
|
||||
//),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,12 +39,6 @@ func (m *metricService) UpdateMethodResponseTime(uri string, time time.Duration)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *metricService) UpdateResponseTime(time time.Duration) {
|
||||
if m.notEmptyHolder() {
|
||||
m.mh.responseTime.Update(int64(time))
|
||||
}
|
||||
}
|
||||
|
||||
func (m *metricService) UpdateStatusCounter(status string) {
|
||||
if m.notEmptyHolder() {
|
||||
m.getOrRegisterCounter(status).Inc(1)
|
||||
|
||||
Reference in new issue
Block a user