diff --git a/Gopkg.lock b/Gopkg.lock index 8ca5782..32efa0f 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -17,6 +17,14 @@ revision = "ade4e2031af3aed7fffd241084aad80a58faf421" version = "v0.1.1" +[[projects]] + digest = "1:ffe9824d294da03b391f44e1ae8281281b4afc1bdaa9588c9097785e3af10cec" + name = "github.com/davecgh/go-spew" + packages = ["spew"] + pruneopts = "UT" + revision = "8991bc29aa16c548c550c7ff78260e27b9ab7c73" + version = "v1.1.1" + [[projects]] digest = "1:76dc72490af7174349349838f2fe118996381b31ea83243812a97e5a0fd5ed55" name = "github.com/dgrijalva/jwt-go" @@ -155,7 +163,6 @@ version = "v1.3.0" [[projects]] - branch = "master" digest = "1:a1ebd1a46e87e9343cbabec1ca99c34a7a2e0572c0160fcf266175073b2adf5f" name = "github.com/integration-system/isp-lib" packages = [ @@ -174,6 +181,7 @@ ] pruneopts = "UT" revision = "5060d1348219abd8fad3628668b229779a5314c7" + version = "v1.9.0" [[projects]] branch = "master" @@ -206,7 +214,7 @@ version = "1.1.8" [[projects]] - digest = "1:caa1da085cc12cd39d3ddb267434902f621050e1b46f7e9477b2b933df680193" + digest = "1:acfc228fb5fbfb82645c121e3224bd546ed68aef6dfc87f63e2d8de099a3822b" name = "github.com/klauspost/compress" packages = [ "flate", @@ -214,16 +222,8 @@ "zlib", ] pruneopts = "UT" - revision = "da9470192e5d0ad619defde5ded583e5e907d3e8" - version = "v1.8.6" - -[[projects]] - digest = "1:923c4d7194b42e054b2eb8a6c62824ac55e23ececc1c7e48d4da69c971c55954" - name = "github.com/klauspost/cpuid" - packages = ["."] - pruneopts = "UT" - revision = "05a8198c0f5a27739aec358908d7e12c64ce6eb7" - version = "v1.2.1" + revision = "16a4d3d7137cdefd94d420f22b5c20260674b95c" + version = "v1.9.1" [[projects]] digest = "1:31e761d97c76151dde79e9d28964a812c46efc5baee4085b86f68f0c654450de" @@ -298,12 +298,12 @@ revision = "c48cc78d482608239f6c4c92a4abd87eb8761c90" [[projects]] - digest = "1:bbd3997f0121200f72b64d7a3826eb8a0b910d6a4c19894c9fe2852b9e5eaf3b" + digest = "1:6eea828983c70075ca297bb915ffbcfd3e34c5a50affd94428a65df955c0ff9c" name = "github.com/pelletier/go-toml" packages = ["."] pruneopts = "UT" - revision = "8fe62057ea2d46ce44254c98e84e810044dbe197" - version = "v1.5.0" + revision = "903d9455db9ff1d7ac1ab199062eca7266dd11a3" + version = "v1.6.0" [[projects]] digest = "1:cf31692c14422fa27c83a05292eb5cbe0fb2775972e8f1f8446a71549bd8980b" @@ -313,6 +313,14 @@ revision = "ba968bfe8b2f7e042a574c888954fccecfa385b4" version = "v0.8.1" +[[projects]] + digest = "1:0028cb19b2e4c3112225cd871870f2d9cf49b9b4276531f03438a88e94be86fe" + name = "github.com/pmezard/go-difflib" + packages = ["difflib"] + pruneopts = "UT" + revision = "792786c7400a136282c1664665ae0a8db921c6c2" + version = "v1.0.0" + [[projects]] branch = "master" digest = "1:5bbebe8ac19ecb6c87790a89faa20566e38ed0d6494a1d14c4f5b05d9ce2436c" @@ -365,13 +373,29 @@ version = "v1.0.5" [[projects]] - digest = "1:11118bd196646c6515fea3d6c43f66162833c6ae4939bfb229b9956d91c6cf17" + digest = "1:0b60fc944fb6a7b6c985832bd341bdb7ed8fe894fea330414e7774bb24652962" name = "github.com/spf13/viper" packages = ["."] pruneopts = "UT" - revision = "b5bf975e5823809fb22c7644d008757f78a4259e" + revision = "72b022eb357a56469725dcd03918449e2278d02e" + version = "v1.5.0" + +[[projects]] + digest = "1:8548c309c65a85933a625be5e7d52b6ac927ca30c56869fae58123b8a77a75e1" + name = "github.com/stretchr/testify" + packages = ["assert"] + pruneopts = "UT" + revision = "221dbe5ed46703ee255b1da0dec05086f5035f62" version = "v1.4.0" +[[projects]] + digest = "1:f4b32291cad5efac2bfdba89ccde6aa04618b62ce06c1a571da2dc4f3f2677fb" + name = "github.com/subosito/gotenv" + packages = ["."] + pruneopts = "UT" + revision = "2ef7124db659d49edac6aa459693a15ae36c671a" + version = "v1.2.0" + [[projects]] branch = "master" digest = "1:d32b64a7a82dd36b674fb73ff767e949eb7155b6b574ff276f49d4edc8af105f" @@ -390,7 +414,7 @@ [[projects]] branch = "master" - digest = "1:8df917c05bc5b359af4a95a39049919ec141d6224f48bb7b92a8f44c91c0f5ba" + digest = "1:35cbf67ac1c92eb7bd6fe70d17b75b60bd38fb2222fa71ac82d44d3813897d22" name = "github.com/valyala/fasthttp" packages = [ ".", @@ -398,7 +422,7 @@ "stackless", ] pruneopts = "UT" - revision = "707b1c1917f38038d0d81e856df73853513100b3" + revision = "87c4546c7b1268a1c29c46e8f54def6f0e7596eb" [[projects]] digest = "1:39a425f98fb19427061a693fe6bf0683c9bddec4b25b17067e34fdb465e39cb9" @@ -414,11 +438,11 @@ name = "golang.org/x/crypto" packages = ["ssh/terminal"] pruneopts = "UT" - revision = "87dc89f01550277dc22b74ffcf4cd89fa2f40f4c" + revision = "c7e5f84aec591254278750bee18f39e5dd19cdb5" [[projects]] branch = "master" - digest = "1:c124e945335a9c62ede3a565f3198c5ae9a5ecc39fddd85871138362d128fb74" + digest = "1:d639fcedf8f14de3eefa8f26740091ca737108a944314a4700d482bd11a18301" name = "golang.org/x/net" packages = [ "context", @@ -430,18 +454,18 @@ "trace", ] pruneopts = "UT" - revision = "ec77196f6094c3492a8b61f2c11cf937f78992ae" + revision = "a882066a44e04a21d46e51451c71e131344e830e" [[projects]] branch = "master" - digest = "1:f8c0a298987fa1c452d209f37d2ed9bcf874f2c6eec817607e8ebbba88e6331f" + digest = "1:1017834f19e0d987e8b1b928f016b0a1186a202ec1867fee7112efd4b4475bd1" name = "golang.org/x/sys" packages = [ "unix", "windows", ] pruneopts = "UT" - revision = "e66fe6eb8e0cbfacade8b490cf55cd2494f4db62" + revision = "c1f44814a5cd81a6d1cb589ef1e528bc5d305e07" [[projects]] digest = "1:8d8faad6b12a3a4c819a3f9618cb6ee1fa1cfc33253abeeea8b55336721e3405" @@ -477,13 +501,14 @@ "googleapis/rpc/status", ] pruneopts = "UT" - revision = "548a555dbc03994223efbaba0090152849259498" + revision = "919d9bdd9fe6f1a5dd95ce5d5e4cdb8fd3c516d0" [[projects]] - digest = "1:6cd77d0b616d2dcebd363dfecba593f27b0151fc82cdb5fbfb96c5a7cfbc95b5" + digest = "1:0c0ea0f0ccec8a112245dd3ca0c3b304224ede9afd4b7a2b482a7b48471ef894" name = "google.golang.org/grpc" packages = [ ".", + "backoff", "balancer", "balancer/base", "balancer/roundrobin", @@ -499,10 +524,13 @@ "internal/backoff", "internal/balancerload", "internal/binarylog", + "internal/buffer", "internal/channelz", "internal/envconfig", "internal/grpcrand", "internal/grpcsync", + "internal/resolver/dns", + "internal/resolver/passthrough", "internal/syscall", "internal/transport", "keepalive", @@ -510,24 +538,22 @@ "naming", "peer", "resolver", - "resolver/dns", - "resolver/passthrough", "serviceconfig", "stats", "status", "tap", ] pruneopts = "UT" - revision = "f6d0f9ee430895e87ef1ceb5ac8f39725bafceef" - version = "v1.24.0" + revision = "9d331e2b02dd47daeecae02790f61cc88dc75a64" + version = "v1.25.0" [[projects]] - digest = "1:59f10c1537d2199d9115d946927fe31165959a95190849c82ff11e05803528b0" + digest = "1:f26a5d382387e03a40d1471dddfba85dfff9bf05352d7e42d37612677c4d3c5c" name = "gopkg.in/yaml.v2" packages = ["."] pruneopts = "UT" - revision = "f221b8435cfb71e54062f6c6e99e9ade30b124d5" - version = "v2.2.4" + revision = "f90ceb4f409096b60e2e9076b38b304b8246e5fa" + version = "v2.2.5" [solve-meta] analyzer-name = "dep" @@ -553,6 +579,7 @@ "github.com/json-iterator/go", "github.com/pkg/errors", "github.com/rcrowley/go-metrics", + "github.com/stretchr/testify/assert", "github.com/valyala/fasthttp", "golang.org/x/net/context", "google.golang.org/grpc", diff --git a/Gopkg.toml b/Gopkg.toml index 655c622..a1b1f42 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -34,7 +34,7 @@ [[override]] name = "github.com/integration-system/isp-lib" - branch = "master" + version = "1.9.0" [prune] go-tests = true diff --git a/accounting/accounting.go b/accounting/accounting.go new file mode 100644 index 0000000..1f2a5a3 --- /dev/null +++ b/accounting/accounting.go @@ -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 +} diff --git a/accounting/accounting_test.go b/accounting/accounting_test.go new file mode 100644 index 0000000..819527d --- /dev/null +++ b/accounting/accounting_test.go @@ -0,0 +1,81 @@ +package accounting + +import ( + "github.com/stretchr/testify/assert" + "isp-gate-service/conf" + "testing" + "time" +) + +var ( + 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 { + appId int64 + path []string + }{ + 0: {appId: 1, path: []string{ + "mdm-master/group/method", "mdm-master/group/method", "mdm-master/group/method", + "mdm-master/group/method", "mdm-master/group/method", "mdm-master/group/method", + }}, + + 1: {appId: 2, path: []string{ + "mdm-master/group3/method", "mdm-master/group/method", "mdm-master/group3/method", + "mdm-master/group/method", "mdm-master/group3/method", "mdm-master/group/method", + }}, + + 2: {appId: 1, path: []string{ + "mdm-master/group3/method", "mdm-master/group3/method", "mdm-master/group3/method", + "mdm-master/group3/method", "mdm-master/group3/method", "mdm-master/group3/method", + }}, + 3: {appId: 1, path: []string{ + "mdm-master/group4/method", "mdm-master/group4/method", "mdm-master/group4/method", + "mdm-master/group4/method", "mdm-master/group4/method", "mdm-master/group4/method", + }}, + } +) + +func TestApprove(t *testing.T) { + a := assert.New(t) + ReceiveConfiguration(approveSetting) + + expected := true + req := reqExample[0] + for _, path := range req.path { + a.Equal(expected, GetAccounting(req.appId).TakeAccount(path)) + expected = !expected + time.Sleep(150 * time.Millisecond) + } + + //expected == true + req = reqExample[1] + for _, path := range req.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], GetAccounting(req.appId).TakeAccount(path)) + } + + //expected == true + req = reqExample[3] + for _, path := range req.path { + a.Equal(expected, GetAccounting(req.appId).TakeAccount(path)) + } +} diff --git a/accounting/state/limit_state.go b/accounting/state/limit_state.go new file mode 100644 index 0000000..694cbb9 --- /dev/null +++ b/accounting/state/limit_state.go @@ -0,0 +1,58 @@ +package state + +import ( + "isp-gate-service/conf" + "time" +) + +type ( + LimitState interface { + check() (bool, int, time.Time) + update(int, time.Time) + } + + updateRequest struct { + pointer int + requestTime time.Time + } +) + +func InitLimitState(limits []conf.LimitSetting) (map[string]LimitState, []string, error) { + limitStates := make(map[string]LimitState) + patternArray := make([]string, len(limits)) + + for i, limit := range limits { + timeout, err := time.ParseDuration(limit.Timeout) + if err != nil { + return nil, nil, err + } + if timeout == 0 && limit.MaxCount != 0 { + limit.MaxCount = 1 + } + + patternArray[i] = limit.Pattern + limitStates[limit.Pattern] = &limiter{ + timeout: timeout, + datetime: make([]time.Time, limit.MaxCount), + pattern: limit.Pattern, + pointer: -1, + } + } + return limitStates, patternArray, nil +} + +func Update(states []LimitState) bool { + update := make([]updateRequest, len(states)) + for i, st := range states { + 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.requestTime) + } + return true +} diff --git a/accounting/state/limiter.go b/accounting/state/limiter.go new file mode 100644 index 0000000..d81c9fb --- /dev/null +++ b/accounting/state/limiter.go @@ -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 +} diff --git a/authenticate/authenticate.go b/authenticate/authenticate.go index d3251f8..7c340e6 100644 --- a/authenticate/authenticate.go +++ b/authenticate/authenticate.go @@ -7,6 +7,7 @@ import ( "google.golang.org/grpc/codes" "isp-gate-service/log_code" "isp-gate-service/routing" + "strconv" "strings" ) @@ -19,23 +20,31 @@ var ( } ) -func Do(ctx *fasthttp.RequestCtx) error { +func Do(ctx *fasthttp.RequestCtx) (int64, error) { + path := ctx.Path() + uri := strings.Replace(strings.ToLower(string(path)), "/", "", -1) + path = getPathWithoutPrefix(path) + + if _, ok := routing.AddressMap[string(path)]; !ok { + return 0, createError(codes.Unimplemented) + } + for _, notExpectedHeader := range verifiableKeyHeaderKeyMap { ctx.Request.Header.Del(notExpectedHeader) } appToken := ctx.Request.Header.Peek(utils.ApplicationTokenHeader) if len(appToken) == 0 { - return createError(codes.Unauthenticated) + return 0, createError(codes.Unauthenticated) } keys, err := verification.appToken(string(appToken)) if err != nil { log.Error(log_code.ErrorAuthenticate, err) - return createError(codes.Internal) + return 0, createError(codes.Internal) } if len(keys) != 4 { - return createError(codes.Unauthenticated) + return 0, createError(codes.Unauthenticated) } verifiableKeys := make(map[string]string) @@ -43,36 +52,40 @@ func Do(ctx *fasthttp.RequestCtx) error { verifiableKeys[verifiableKeyHeaderKeyMap[i]] = value } - path := ctx.Path() - uri := strings.Replace(strings.ToLower(string(path)), "/", "", -1) verifiableKeys[utils.DeviceTokenHeader] = string(ctx.Request.Header.Peek(utils.DeviceTokenHeader)) verifiableKeys[utils.UserTokenHeader] = string(ctx.Request.Header.Peek(utils.UserTokenHeader)) verifiableKeys, err = verification.keys(verifiableKeys, uri) if err != nil { log.Error(log_code.ErrorAuthenticate, err) - return createError(codes.Internal) + return 0, createError(codes.Internal) } if verifiableKeys[permittedToCallInfo] == "0" { - return createError(codes.PermissionDenied) + return 0, createError(codes.PermissionDenied) } else { delete(verifiableKeys, permittedToCallInfo) } + applicationId, err := strconv.Atoi(verifiableKeys[utils.ApplicationIdHeader]) + if err != nil { + log.Error(log_code.ErrorAuthenticate, err) + return 0, createError(codes.Internal) + } + for key, value := range verifiableKeys { if value != "" { ctx.Request.Header.Set(key, value) } } - path = getPathWithoutPrefix(path) if _, ok := routing.InnerAddressMap[string(path)]; ok { adminToken := ctx.Request.Header.Peek("x-auth-admin") //todo const key if token.Check(string(adminToken)) != nil { - return createError(codes.PermissionDenied) + return 0, createError(codes.PermissionDenied) } } - return nil + + return int64(applicationId), nil } func getPathWithoutPrefix(path []byte) []byte { diff --git a/conf/remote_config.go b/conf/remote_config.go index 00c9c7e..c333601 100644 --- a/conf/remote_config.go +++ b/conf/remote_config.go @@ -20,13 +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"` + Redis structure.RedisConfiguration `schema:"Настройка Redis" valid:"required~Required"` + AccountingSetting Accounting `schema:"Настройка учета запросов"` + } + + Accounting struct { + Enable bool `schema:"Статус работы учета,включает/отключает учет запросов"` + Setting []AccountingSetting `schema:"Настройка учета для приложений"` + } + + AccountingSetting struct { + ApplicationId int64 `valid:"required~Required" schema:"Идентификатор приложения"` + Limits []LimitSetting `schema:"Настройка ограничений на запросы"` + } + + LimitSetting struct { + Pattern string `valid:"required~Required" schema:"Шаблон пути,указывается путь для которого будут применяется ограничения; поддерживается '/*' для неполного совпадения"` + MaxCount int `schema:"Количество запросов"` + Timeout string `schema:"Время жизни одного запроса"` } ServerSetting struct { @@ -62,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 -}*/ diff --git a/domain/response.go b/domain/response.go new file mode 100644 index 0000000..56f8a95 --- /dev/null +++ b/domain/response.go @@ -0,0 +1,30 @@ +package domain + +type ProxyResponse struct { + requestBody []byte + responseBody []byte + error error +} + +func Create() ProxyResponse { + return ProxyResponse{requestBody: nil, responseBody: nil, error: nil} +} + +func (p ProxyResponse) SetRequestBody(requestBody []byte) ProxyResponse { + p.requestBody = requestBody + return p +} + +func (p ProxyResponse) SetResponseBody(responseBody []byte) ProxyResponse { + p.responseBody = responseBody + return p +} + +func (p ProxyResponse) SetError(err error) ProxyResponse { + p.error = err + return p +} + +func (p ProxyResponse) Get() (requestBody, responseBody []byte, err error) { + return p.requestBody, p.responseBody, p.error +} diff --git a/handler/handler.go b/handler/handler.go index d7fb281..a533fd6 100644 --- a/handler/handler.go +++ b/handler/handler.go @@ -1,29 +1,102 @@ package handler import ( + "github.com/integration-system/isp-lib/config" + log "github.com/integration-system/isp-log" + "github.com/pkg/errors" "github.com/valyala/fasthttp" "google.golang.org/grpc/codes" + "isp-gate-service/accounting" "isp-gate-service/authenticate" + "isp-gate-service/conf" + "isp-gate-service/domain" + "isp-gate-service/journal" + "isp-gate-service/log_code" "isp-gate-service/proxy" + "isp-gate-service/service" + "isp-gate-service/service/matcher" "isp-gate-service/utils" + "net/http" + "time" ) -func Complete(ctx *fasthttp.RequestCtx) { - if err := authenticate.Do(ctx); err != nil { +var helper handlerHelper + +type handlerHelper struct{} + +func CompleteRequest(ctx *fasthttp.RequestCtx) { + currentTime := time.Now() + uri := string(ctx.RequestURI()) + + resp := helper.AuthenticateApproveProxy(ctx) + + executionTime := time.Since(currentTime) / 1e6 + + statusCode := ctx.Response.StatusCode() + service.Metrics.UpdateStatusCounter(helper.SetMetricStatus(statusCode)) + if statusCode == http.StatusOK { + service.Metrics.UpdateMethodResponseTime(uri, executionTime) + } + + requestBody, responseBody, err := resp.Get() + 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) + } + } + } + } +} + +func (handlerHelper) AuthenticateApproveProxy(ctx *fasthttp.RequestCtx) domain.ProxyResponse { + path := string(ctx.Path()) + + applicationId, err := authenticate.Do(ctx) + if err != nil { status := codes.Unknown switch e := err.(type) { case authenticate.ErrorDescription: status = e.ConvertToGrpcStatus() } - utils.SendError("authenticate error", status, nil, ctx) - return + utils.WriteError(ctx, "unauthorized", status, nil) + return domain.Create().SetError(err) + } + + 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) } - path := string(ctx.Path()) p := proxy.Find(path) if p != nil { - p.ProxyRequest(ctx) + return p.ProxyRequest(ctx) } else { - utils.SendError("unknown path", codes.NotFound, []interface{}{map[string]string{"path": path}}, ctx) + err := errors.Errorf("unknown path %s", path) + utils.WriteError(ctx, "not found", codes.NotFound, nil) + return domain.Create().SetError(err) } } + +func (handlerHelper) SetMetricStatus(statusCode int) string { + metricStatus := "5xx" + switch { + case statusCode >= 100 && statusCode < 200: + metricStatus = "1xx" + case statusCode >= 200 && statusCode < 300: + metricStatus = "2xx" + case statusCode >= 300 && statusCode < 400: + metricStatus = "3xx" + case statusCode >= 400 && statusCode < 500: + metricStatus = "4xx" + case statusCode >= 500 && statusCode < 600: + metricStatus = "5xx" + } + return metricStatus +} diff --git a/log_code/code.go b/log_code/code.go index f0ba89b..ac76df8 100644 --- a/log_code/code.go +++ b/log_code/code.go @@ -15,5 +15,6 @@ const ( ErrorClientJournal = 608 ErrorClientRedis = 609 - ErrorAuthenticate = 612 + ErrorAuthenticate = 612 + FatalConfigApproveSetting = 613 ) diff --git a/main.go b/main.go index bfe0094..347143a 100644 --- a/main.go +++ b/main.go @@ -8,6 +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/accounting" "isp-gate-service/conf" "isp-gate-service/journal" "isp-gate-service/log_code" @@ -16,6 +17,7 @@ import ( "isp-gate-service/routing" "isp-gate-service/server" "isp-gate-service/service" + "isp-gate-service/service/matcher" "os" ) @@ -39,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) } } @@ -59,8 +61,9 @@ func onRemoteConfigReceive(remoteConfig, oldRemoteConfig *conf.RemoteConfig) { journal.Client.ReceiveConfiguration(remoteConfig.Journal, localCfg.ModuleName) redis.Client.ReceiveConfiguration(remoteConfig.Redis) server.Http.Init(remoteConfig.ServerSetting.MaxRequestBodySizeBytes) + accounting.ReceiveConfiguration(remoteConfig.AccountingSetting) - service.JournalMethodsMatcher = service.NewCacheableMethodMatcher(remoteConfig.JournalingMethodsPatterns) + matcher.JournalMethods = matcher.NewAtLeastOneMatcher(remoteConfig.JournalingMethodsPatterns) metric.InitCollectors(remoteConfig.Metrics, oldRemoteConfig.Metrics) metric.InitHttpServer(remoteConfig.Metrics) diff --git a/proxy/description.go b/proxy/description.go index b7fd7e2..cb7fc16 100644 --- a/proxy/description.go +++ b/proxy/description.go @@ -5,7 +5,9 @@ import ( "github.com/pkg/errors" "github.com/valyala/fasthttp" "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" ) @@ -13,15 +15,18 @@ import ( var store = make(map[string]Proxy) const ( - httpProtocol = "http" - grpcProtocol = "grpc" + httpProtocol = "http" + grpcProtocol = "grpc" + healthCheckProtocol = "healthсheck" ) -type Proxy interface { - ProxyRequest(ctx *fasthttp.RequestCtx) - Consumer([]structure.AddressConfiguration) bool - Close() -} +type ( + Proxy interface { + ProxyRequest(ctx *fasthttp.RequestCtx) domain.ProxyResponse + Consumer([]structure.AddressConfiguration) bool + Close() + } +) func Init(location conf.Location) (Proxy, error) { if location.PathPrefix[0] != '/' { @@ -36,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) } } diff --git a/proxy/grpc/client.go b/proxy/grpc/client.go index d9dcd78..51231fa 100644 --- a/proxy/grpc/client.go +++ b/proxy/grpc/client.go @@ -4,16 +4,15 @@ import ( "github.com/integration-system/isp-lib/backend" "github.com/integration-system/isp-lib/structure" log "github.com/integration-system/isp-log" + "github.com/pkg/errors" "github.com/valyala/fasthttp" "google.golang.org/grpc" "google.golang.org/grpc/codes" "isp-gate-service/conf" + "isp-gate-service/domain" "isp-gate-service/log_code" "isp-gate-service/proxy/grpc/handlers" - "isp-gate-service/service" "isp-gate-service/utils" - "net/http" - "time" ) type grpcProxy struct { @@ -33,25 +32,19 @@ func NewProxy() *grpcProxy { )} } -func (p *grpcProxy) ProxyRequest(ctx *fasthttp.RequestCtx) { +func (p *grpcProxy) ProxyRequest(ctx *fasthttp.RequestCtx) domain.ProxyResponse { if p.client.InternalGrpcClient == nil { msg := "client undefined" log.Error(log_code.ErrorClientGrpc, msg) - utils.SendError(msg, codes.Internal, nil, ctx) - return + utils.WriteError(ctx, msg, codes.Internal, nil) + return domain.Create(). + SetRequestBody(ctx.Request.Body()). + SetResponseBody(ctx.Response.Body()). + SetError(errors.New(msg)) } - currentTime := time.Now() - uri := string(ctx.RequestURI()) - handlers.Handler.Get(ctx).Complete(ctx, uri, p.client) - executionTime := time.Since(currentTime) / 1e6 - - service.Metrics.UpdateStatusCounter(ctx.Response.StatusCode()) - if ctx.Response.StatusCode() == http.StatusOK { - service.Metrics.UpdateResponseTime(executionTime) - service.Metrics.UpdateMethodResponseTime(uri, executionTime) - } + return handlers.Handler.Get(ctx).Complete(ctx, uri, p.client) } func (p *grpcProxy) Consumer(addr []structure.AddressConfiguration) bool { diff --git a/proxy/grpc/handlers/common.go b/proxy/grpc/handlers/common.go index 3f4b803..fc5a132 100644 --- a/proxy/grpc/handlers/common.go +++ b/proxy/grpc/handlers/common.go @@ -18,8 +18,9 @@ import ( "google.golang.org/grpc/status" "io" "isp-gate-service/conf" + "isp-gate-service/domain" "isp-gate-service/log_code" - u "isp-gate-service/utils" + utils2 "isp-gate-service/utils" "net/http" "strings" "time" @@ -36,7 +37,8 @@ const ( ) var ( - json = jsoniter.ConfigFastest + json = jsoniter.ConfigFastest + emptyBody = make([]byte, 0) ) func convertError(err error) ([]byte, int) { @@ -137,14 +139,22 @@ func makeMetadata(r *fasthttp.RequestHeader, method string) (metadata.MD, string return md, method } -func checkError(err error, ctx *fasthttp.RequestCtx) (bool, bool) { +func checkError(err error, ctx *fasthttp.RequestCtx) (bool, bool, domain.ProxyResponse) { + var ( + ok = true + eof = false + resp = domain.ProxyResponse{} + ) + if err != nil { if err != io.EOF { logHandlerError(log_code.TypeData.GetFile, "", err) - u.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, ctx) - return false, false + utils2.WriteError(ctx, errorMsgInternal, codes.Internal, nil) + resp = domain.Create().SetError(err) + ok, eof = false, false + } else { + ok, eof = true, true } - return true, true } - return true, false + return ok, eof, resp } diff --git a/proxy/grpc/handlers/description.go b/proxy/grpc/handlers/description.go index 61e8e4a..f3ee7a1 100644 --- a/proxy/grpc/handlers/description.go +++ b/proxy/grpc/handlers/description.go @@ -4,6 +4,7 @@ import ( "github.com/integration-system/isp-lib/backend" u "github.com/integration-system/isp-lib/utils" "github.com/valyala/fasthttp" + "isp-gate-service/domain" "isp-gate-service/utils" "mime" ) @@ -14,7 +15,7 @@ type ( handlerHelper struct{} handler interface { - Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) + Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) domain.ProxyResponse } ) diff --git a/proxy/grpc/handlers/handle_get_file.go b/proxy/grpc/handlers/handle_get_file.go index 76bb385..fd38b7c 100644 --- a/proxy/grpc/handlers/handle_get_file.go +++ b/proxy/grpc/handlers/handle_get_file.go @@ -12,6 +12,7 @@ import ( "google.golang.org/grpc/codes" "io" "isp-gate-service/conf" + "isp-gate-service/domain" "isp-gate-service/log_code" "isp-gate-service/utils" "strconv" @@ -21,15 +22,15 @@ var getFile getFileDesc type getFileDesc struct{} -func (g getFileDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) { +func (g getFileDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) domain.ProxyResponse { cfg := config.GetRemote().(*conf.RemoteConfig).GrpcSetting timeout := cfg.GetStreamInvokeTimeout() req, err := g.readJsonBody(ctx) if err != nil { logHandlerError(log_code.TypeData.GetFile, method, err) - utils.SendError(err.Error(), codes.InvalidArgument, nil, ctx) - return + utils.WriteError(ctx, err.Error(), codes.InvalidArgument, nil) + return domain.Create().SetError(err) } stream, cancel, err := openStream(&ctx.Request.Header, method, timeout, client) @@ -40,8 +41,8 @@ func (g getFileDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *b }() if err != nil { logHandlerError(log_code.TypeData.GetFile, method, err) - utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, ctx) - return + utils.WriteError(ctx, errorMsgInternal, codes.Internal, nil) + return domain.Create().SetError(err) } if req != nil { @@ -49,8 +50,8 @@ func (g getFileDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *b err := stream.Send(backend.WrapBody(value)) if err != nil { logHandlerError(log_code.TypeData.GetFile, method, err) - utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, ctx) - return + utils.WriteError(ctx, errorMsgInternal, codes.Internal, nil) + return domain.Create().SetError(err) } } @@ -61,7 +62,7 @@ func (g getFileDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *b ctx.SetStatusCode(status) ctx.SetBody(bytes) } - return + return domain.Create().SetError(err) } bf := s.BeginFile{} err = bf.FromMessage(msg) @@ -71,7 +72,7 @@ func (g getFileDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *b ctx.SetStatusCode(status) ctx.SetBody(bytes) } - return + return domain.Create().SetError(err) } header := &ctx.Response.Header header.Set(headerKeyContentDisposition, fmt.Sprintf("attachment; filename=%s", bf.FileName)) @@ -105,6 +106,7 @@ func (g getFileDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *b break } } + return domain.Create().SetError(err) } func (getFileDesc) readJsonBody(ctx *fasthttp.RequestCtx) (interface{}, error) { diff --git a/proxy/grpc/handlers/handle_json.go b/proxy/grpc/handlers/handle_json.go index 1b2ea07..4484c2e 100644 --- a/proxy/grpc/handlers/handle_json.go +++ b/proxy/grpc/handlers/handle_json.go @@ -4,24 +4,21 @@ import ( "github.com/integration-system/isp-lib/backend" "github.com/integration-system/isp-lib/config" isp "github.com/integration-system/isp-lib/proto/stubs" - log "github.com/integration-system/isp-log" "github.com/valyala/fasthttp" "golang.org/x/net/context" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" "isp-gate-service/conf" - "isp-gate-service/journal" + "isp-gate-service/domain" "isp-gate-service/log_code" - "isp-gate-service/service" "isp-gate-service/utils" - "time" ) var handleJson handleJsonDesc type handleJsonDesc struct{} -func (p handleJsonDesc) Complete(c *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) { +func (p handleJsonDesc) Complete(c *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) domain.ProxyResponse { //body, err := utils.ReadJsonBody(c) body := c.Request.Body() /*if err != nil { @@ -32,43 +29,32 @@ func (p handleJsonDesc) Complete(c *fasthttp.RequestCtx, method string, client * md, methodName := makeMetadata(&c.Request.Header, method) ctx := metadata.NewOutgoingContext(context.Background(), md) - cfg := config.GetRemote().(*conf.RemoteConfig) - ctx, cancel := context.WithTimeout(ctx, cfg.GrpcSetting.GetSyncInvokeTimeout()) + grpcSetting := config.GetRemote().(*conf.RemoteConfig).GrpcSetting + ctx, cancel := context.WithTimeout(ctx, grpcSetting.GetSyncInvokeTimeout()) defer cancel() cli, err := client.Conn() if err != nil { logHandlerError(log_code.TypeData.JsonContent, methodName, err) - utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, c) - return + utils.WriteError(c, errorMsgInternal, codes.Internal, nil) + return domain.Create().SetError(err) } //structBody := u.ConvertInterfaceToGrpcStruct(body) - currentTime := time.Now() - response, invokerErr := cli.Request( + resp, invokerErr := cli.Request( ctx, &isp.Message{ Body: &isp.Message_BytesBody{BytesBody: body}, }, ) - service.Metrics.UpdateRouterResponseTime(time.Since(currentTime) / 1e6) - if data, status, err := getResponse(response, invokerErr); err == nil { + if data, status, err := getResponse(resp, invokerErr); err == nil { c.SetStatusCode(status) _, _ = c.Write(data) - if cfg.Journal.Enable && service.JournalMethodsMatcher.Match(methodName) { - if invokerErr != nil { - if err := journal.Client.Error(methodName, body, data, invokerErr); err != nil { - log.Warnf(log_code.WarnJournalCouldNotWriteToFile, "could not write to file journal: %v", err) - } - } else { - if err := journal.Client.Info(methodName, body, data); err != nil { - log.Warnf(log_code.WarnJournalCouldNotWriteToFile, "could not write to file journal: %v", err) - } - } - } + return domain.Create().SetError(invokerErr) } else { logHandlerError(log_code.TypeData.JsonContent, methodName, err) - utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, c) + utils.WriteError(c, errorMsgInternal, codes.Internal, nil) + return domain.Create().SetError(err) } } diff --git a/proxy/grpc/handlers/handle_send_multipart_data.go b/proxy/grpc/handlers/handle_send_multipart_data.go index 4b9822f..a6734a0 100644 --- a/proxy/grpc/handlers/handle_send_multipart_data.go +++ b/proxy/grpc/handlers/handle_send_multipart_data.go @@ -8,6 +8,7 @@ import ( "github.com/valyala/fasthttp" "google.golang.org/grpc/codes" "isp-gate-service/conf" + "isp-gate-service/domain" "isp-gate-service/log_code" "isp-gate-service/utils" "mime/multipart" @@ -18,7 +19,7 @@ var sendMultipartData sendMultipartDataDesc type sendMultipartDataDesc struct{} -func (h sendMultipartDataDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) { +func (h sendMultipartDataDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) domain.ProxyResponse { cfg := config.GetRemote().(*conf.RemoteConfig).GrpcSetting timeout := cfg.GetStreamInvokeTimeout() bufferSize := cfg.GetTransferFileBufferSize() @@ -31,8 +32,8 @@ func (h sendMultipartDataDesc) Complete(ctx *fasthttp.RequestCtx, method string, }() if err != nil { logHandlerError(log_code.TypeData.SendMultipart, method, err) - utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, ctx) - return + utils.WriteError(ctx, errorMsgInternal, codes.Internal, nil) + return domain.Create().SetError(err) } form, err := ctx.MultipartForm() @@ -44,8 +45,8 @@ func (h sendMultipartDataDesc) Complete(ctx *fasthttp.RequestCtx, method string, if err != nil { logHandlerError(log_code.TypeData.SendMultipart, method, err) - utils.SendError(errorMsgInvalidArg, codes.InvalidArgument, []interface{}{err.Error()}, ctx) - return + utils.WriteError(ctx, errorMsgInvalidArg, codes.InvalidArgument, nil) + return domain.Create().SetError(err) } formData := make(map[string]interface{}, len(form.Value)) @@ -56,10 +57,13 @@ func (h sendMultipartDataDesc) Complete(ctx *fasthttp.RequestCtx, method string, } } - response := make([]string, 0) - buffer := make([]byte, bufferSize) - ok := true - eof := false + var ( + proxyResp domain.ProxyResponse + resp = make([]string, 0) + buffer = make([]byte, bufferSize) + ok = true + eof = false + ) for formDataName, files := range form.File { if len(files) == 0 { @@ -77,19 +81,19 @@ func (h sendMultipartDataDesc) Complete(ctx *fasthttp.RequestCtx, method string, FormData: formData, } err = stream.Send(bf.ToMessage()) - if ok, eof = checkError(err, ctx); !ok || eof { + if ok, eof, proxyResp = checkError(err, ctx); !ok || eof { break } f, err := file.Open() - if ok, eof = checkError(err, ctx); !ok || eof { + if ok, eof, proxyResp = checkError(err, ctx); !ok || eof { break } - if ok, eof = h.transferFile(f, stream, buffer, ctx); ok { + if ok, eof, proxyResp = h.transferFile(f, stream, buffer, ctx); ok { msg, err := stream.Recv() v, _, err := getResponse(msg, err) if err == nil { - response = append(response, string(v)) + resp = append(resp, string(v)) } ok = err == nil } @@ -105,34 +109,38 @@ func (h sendMultipartDataDesc) Complete(ctx *fasthttp.RequestCtx, method string, } if ok { - arrayBody := strings.Join(response, ",") + arrayBody := strings.Join(resp, ",") _, err = ctx.WriteString("[" + arrayBody + "]") if err != nil { logHandlerError(log_code.TypeData.SendMultipart, method, err) } } + return proxyResp } func (sendMultipartDataDesc) transferFile(f multipart.File, stream isp.BackendService_RequestStreamClient, - buffer []byte, ctx *fasthttp.RequestCtx) (bool, bool) { + buffer []byte, ctx *fasthttp.RequestCtx) (bool, bool, domain.ProxyResponse) { - ok := true - eof := false + var ( + ok = true + eof = false + proxyResp domain.ProxyResponse + ) for { n, err := f.Read(buffer) if n > 0 { - err = stream.Send(&isp.Message{Body: &isp.Message_BytesBody{buffer[:n]}}) - if ok, eof = checkError(err, ctx); !ok || eof { + err = stream.Send(&isp.Message{Body: &isp.Message_BytesBody{BytesBody: buffer[:n]}}) + if ok, eof, proxyResp = checkError(err, ctx); !ok || eof { break } } if err != nil { - if ok, eof = checkError(err, ctx); ok && eof { + if ok, eof, proxyResp = checkError(err, ctx); ok && eof { err = stream.Send(s.FileEnd()) - ok, eof = checkError(err, ctx) + ok, eof, proxyResp = checkError(err, ctx) } break } } - return ok, eof + return ok, eof, proxyResp } diff --git a/proxy/health_check/health_check.go b/proxy/health_check/health_check.go new file mode 100644 index 0000000..da064c8 --- /dev/null +++ b/proxy/health_check/health_check.go @@ -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() { + +} diff --git a/proxy/http/client.go b/proxy/http/client.go index b385792..480feed 100644 --- a/proxy/http/client.go +++ b/proxy/http/client.go @@ -1,10 +1,12 @@ package http import ( + "errors" "github.com/integration-system/isp-lib/structure" log "github.com/integration-system/isp-log" "github.com/valyala/fasthttp" "google.golang.org/grpc/codes" + "isp-gate-service/domain" "isp-gate-service/log_code" "isp-gate-service/utils" "net" @@ -31,12 +33,15 @@ func (p *httpProxy) Consumer(addressList []structure.AddressConfiguration) bool return true } -func (p *httpProxy) ProxyRequest(ctx *fasthttp.RequestCtx) { +func (p *httpProxy) ProxyRequest(ctx *fasthttp.RequestCtx) domain.ProxyResponse { if p.client == nil { msg := "client undefined" log.Error(log_code.ErrorClientHttp, msg) - utils.SendError(msg, codes.Internal, nil, ctx) - return + utils.WriteError(ctx, msg, codes.Internal, nil) + return domain.Create(). + SetRequestBody(ctx.Request.Body()). + SetResponseBody(ctx.Response.Body()). + SetError(errors.New(msg)) } req := &ctx.Request @@ -46,10 +51,14 @@ func (p *httpProxy) ProxyRequest(ctx *fasthttp.RequestCtx) { req.Header.Add("X-Forwarded-For", addr) } - if err := p.client.Do(req, res); err != nil { + err := p.client.Do(req, res) + if err != nil { log.Error(log_code.ErrorClientHttp, err) - return } + return domain.Create(). + SetRequestBody(ctx.Request.Body()). + SetResponseBody(ctx.Response.Body()). + SetError(err) } func (p *httpProxy) Close() { diff --git a/routing/routing.go b/routing/routing.go index 24bc210..19a2c81 100644 --- a/routing/routing.go +++ b/routing/routing.go @@ -6,19 +6,23 @@ import ( var ( InnerAddressMap = make(map[string]bool) + AddressMap = make(map[string]bool) ) func InitRoutes(configs structure.RoutingConfig) { + newAddressMap := make(map[string]bool) newInnerAddressMap := make(map[string]bool) for _, backend := range configs { if backend.Address.IP == "" || backend.Address.Port == "" || len(backend.Endpoints) == 0 { continue } for _, v := range backend.Endpoints { + newAddressMap[v.Path] = true if v.Inner { newInnerAddressMap[v.Path] = true } } } + AddressMap = newAddressMap InnerAddressMap = newInnerAddressMap } diff --git a/server/http.go b/server/http.go index 9ff5a35..1d90510 100644 --- a/server/http.go +++ b/server/http.go @@ -29,7 +29,7 @@ func (s *httpSrv) Init(MaxRequestBodySize int64) { localConfig := config.Get().(*conf.Configuration) restAddress := localConfig.HttpInnerAddress.GetAddress() s.srv = &fasthttp.Server{ - Handler: handler.Complete, + Handler: handler.CompleteRequest, WriteTimeout: time.Second * 60, ReadTimeout: time.Second * 60, MaxRequestBodySize: int(maxRequestBodySize), diff --git a/service/matcher/at_least_one_mather.go b/service/matcher/at_least_one_mather.go new file mode 100644 index 0000000..e781b92 --- /dev/null +++ b/service/matcher/at_least_one_mather.go @@ -0,0 +1,33 @@ +package matcher + +import "sync" + +type atLeastOneMatcher struct { + cache map[string]bool + lock sync.RWMutex + rm runtimeMatcher +} + +func (mm *atLeastOneMatcher) Match(method string) bool { + if len(mm.rm.patterns) == 0 { + return false + } + + mm.lock.RLock() + matched, ok := mm.cache[method] + mm.lock.RUnlock() + if ok { + return matched + } + + mm.lock.Lock() + defer mm.lock.Unlock() + if matched, ok = mm.cache[method]; ok { + return matched + } else { + arrayPattern := mm.rm.Match(method) + matched = len(arrayPattern) > 0 + } + mm.cache[method] = matched + return matched +} diff --git a/service/matcher/cacheable_matcher.go b/service/matcher/cacheable_matcher.go new file mode 100644 index 0000000..7767938 --- /dev/null +++ b/service/matcher/cacheable_matcher.go @@ -0,0 +1,32 @@ +package matcher + +import "sync" + +type cacheableMatcher struct { + cache map[string][]string + lock sync.RWMutex + rm runtimeMatcher +} + +func (mm *cacheableMatcher) Match(method string) []string { + if len(mm.rm.patterns) == 0 { + return []string{} + } + + mm.lock.RLock() + arrayPattern, ok := mm.cache[method] + mm.lock.RUnlock() + if ok { + return arrayPattern + } + + mm.lock.Lock() + defer mm.lock.Unlock() + if arrayPattern, ok = mm.cache[method]; ok { + return arrayPattern + } else if arrayPattern = mm.rm.Match(method); len(arrayPattern) > 0 { + mm.cache[method] = arrayPattern + } + + return arrayPattern +} diff --git a/service/matcher/matcher.go b/service/matcher/matcher.go new file mode 100644 index 0000000..9f407f7 --- /dev/null +++ b/service/matcher/matcher.go @@ -0,0 +1,31 @@ +package matcher + +var JournalMethods AtLeastOneMatcher = &atLeastOneMatcher{} + +type Matcher interface { + Match(method string) []string +} + +type AtLeastOneMatcher interface { + Match(method string) bool +} + +func NewRuntimeMatcher(patterns []string) Matcher { + return &runtimeMatcher{ + patterns: patterns, + } +} + +func NewCacheableMatcher(patterns []string) Matcher { + return &cacheableMatcher{ + cache: make(map[string][]string, 0), + rm: runtimeMatcher{patterns: patterns}, + } +} + +func NewAtLeastOneMatcher(patterns []string) AtLeastOneMatcher { + return &atLeastOneMatcher{ + cache: make(map[string]bool, 0), + rm: runtimeMatcher{patterns: patterns}, + } +} diff --git a/service/matcher/matcher_test.go b/service/matcher/matcher_test.go new file mode 100644 index 0000000..b4651c3 --- /dev/null +++ b/service/matcher/matcher_test.go @@ -0,0 +1,65 @@ +package matcher + +import ( + "testing" +) + +var ( + patterns = []string{ + "mdm-master/group/method", + "mdm-master/group/*", + "mdm-master/group2/method", + "mdm-master/group3/*", + } + cases = []struct { + method string + coincidence int + atLeastOne bool + }{ + {method: "mdm-master/group/method", coincidence: 2, atLeastOne: true}, + {method: "mdm-master/group/method2", coincidence: 1, atLeastOne: true}, + {method: "mdm-master/group2/", coincidence: 0, atLeastOne: false}, + {method: "mdm-master/group2/method3", coincidence: 0, atLeastOne: false}, + {method: "mdm-master/group2/method", coincidence: 1, atLeastOne: true}, + {method: "mdm-master/group3/some", coincidence: 1, atLeastOne: true}, + {method: "mdm-master/group3/", coincidence: 1, atLeastOne: true}, + } +) + +func TestCacheableMatcher_Match(t *testing.T) { + matcher := NewCacheableMatcher(patterns) + for _, c := range cases { + res := matcher.Match(c.method) + if c.coincidence != len(res) { + t.Error(c) + } + } +} + +func TestAtLeastOneMatcher_Match(t *testing.T) { + matcher := NewAtLeastOneMatcher(patterns) + for _, c := range cases { + res := matcher.Match(c.method) + if c.atLeastOne != res { + t.Error(c) + } + } +} + +func BenchmarkCacheableMatcher_Match(b *testing.B) { + matcher := NewCacheableMatcher(patterns) + for i := 0; i < b.N; i++ { + for _, c := range cases { + _ = matcher.Match(c.method) + } + } +} + +func BenchmarkRuntimeMatcher_Match(b *testing.B) { + matcher := NewRuntimeMatcher(patterns) + for i := 0; i < b.N; i++ { + for _, c := range cases { + _ = matcher.Match(c.method) + } + } +} diff --git a/service/matcher/runtime_matcher.go b/service/matcher/runtime_matcher.go new file mode 100644 index 0000000..3189411 --- /dev/null +++ b/service/matcher/runtime_matcher.go @@ -0,0 +1,24 @@ +package matcher + +import ( + "strings" +) + +type runtimeMatcher struct { + patterns []string +} + +func (mm runtimeMatcher) Match(method string) []string { + resp := make([]string, 0) + for _, pattern := range mm.patterns { + patternLen := len(pattern) + if patternLen > 0 && pattern[patternLen-1] == '*' { + if strings.HasPrefix(method, pattern[:patternLen-1]) { + resp = append(resp, pattern) + } + } else if strings.EqualFold(method, pattern) { + resp = append(resp, pattern) + } + } + return resp +} diff --git a/service/method_matcher.go b/service/method_matcher.go deleted file mode 100644 index 45fae7b..0000000 --- a/service/method_matcher.go +++ /dev/null @@ -1,70 +0,0 @@ -package service - -import ( - "path" - "sync" -) - -var ( - JournalMethodsMatcher MethodMatcher = &cacheableMethodsMatcher{} -) - -type MethodMatcher interface { - Match(method string) bool -} - -type cacheableMethodsMatcher struct { - cache map[string]bool - lock sync.RWMutex - rm runtimeMatcher -} - -func (mm *cacheableMethodsMatcher) Match(method string) bool { - if len(mm.rm.patterns) == 0 { - return false - } - - mm.lock.RLock() - matched, ok := mm.cache[method] - mm.lock.RUnlock() - if ok { - return matched - } - - mm.lock.Lock() - defer mm.lock.Unlock() - if matched, ok := mm.cache[method]; ok { - return matched - } - matched = mm.rm.Match(method) - mm.cache[method] = matched - return matched -} - -func NewCacheableMethodMatcher(patterns []string) MethodMatcher { - return &cacheableMethodsMatcher{ - cache: make(map[string]bool, 0), - rm: runtimeMatcher{patterns: patterns}, - } -} - -type runtimeMatcher struct { - patterns []string -} - -func (mm runtimeMatcher) Match(method string) bool { - matched := false - for _, pattern := range mm.patterns { - matched, _ = path.Match(pattern, method) - if matched { - break - } - } - return matched -} - -func NewRuntimeMethodMatcher(patterns []string) MethodMatcher { - return &runtimeMatcher{ - patterns: patterns, - } -} diff --git a/service/method_matcher_test.go b/service/method_matcher_test.go deleted file mode 100644 index e3bf157..0000000 --- a/service/method_matcher_test.go +++ /dev/null @@ -1,50 +0,0 @@ -package service - -import "testing" - -var ( - patterns = []string{ - "mdm-master/group/method", - "mdm-master/group2/method", - "mdm-master/group3/*", - } - cases = []struct { - Method string - Result bool - }{ - {Method: "mdm-master/group/method", Result: true}, - {Method: "mdm-master/group/method2", Result: false}, - {Method: "mdm-master/group2/method3", Result: false}, - {Method: "mdm-master/group2/method", Result: true}, - {Method: "mdm-master/group3/some", Result: true}, - {Method: "mdm-master/group3/", Result: true}, - } -) - -func TestCacheableMethodsMatcher_Match(t *testing.T) { - matcher := NewCacheableMethodMatcher(patterns) - for _, c := range cases { - res := matcher.Match(c.Method) - if c.Result != res { - t.Error(c) - } - } -} - -func BenchmarkCacheableMethodsMatcher_Match(b *testing.B) { - matcher := NewCacheableMethodMatcher(patterns) - for i := 0; i < b.N; i++ { - for _, c := range cases { - _ = matcher.Match(c.Method) - } - } -} - -func BenchmarkRuntimeMatcher_Match(b *testing.B) { - matcher := NewRuntimeMethodMatcher(patterns) - for i := 0; i < b.N; i++ { - for _, c := range cases { - _ = matcher.Match(c.Method) - } - } -} diff --git a/service/metrics.go b/service/metrics.go index a087917..68ba94e 100644 --- a/service/metrics.go +++ b/service/metrics.go @@ -3,7 +3,6 @@ package service import ( "github.com/integration-system/isp-lib/metric" "github.com/rcrowley/go-metrics" - "strconv" "sync" "time" ) @@ -20,25 +19,17 @@ type ( } metricHolder struct { - methodHistograms map[string]metrics.Histogram - methodLock sync.RWMutex - statusCounters map[int]metrics.Counter - statusLock sync.RWMutex - routerResponseTime metrics.Histogram - responseTime metrics.Histogram + methodHistograms map[string]metrics.Histogram + methodLock sync.RWMutex + statusCounters map[string]metrics.Counter + statusLock sync.RWMutex } ) func (m *metricService) Init() { m.mh = &metricHolder{ methodHistograms: make(map[string]metrics.Histogram), - statusCounters: make(map[int]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), - ), + statusCounters: make(map[string]metrics.Counter), } } @@ -48,19 +39,7 @@ 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) UpdateRouterResponseTime(time time.Duration) { - if m.notEmptyHolder() { - m.mh.routerResponseTime.Update(int64(time)) - } -} - -func (m *metricService) UpdateStatusCounter(status int) { +func (m *metricService) UpdateStatusCounter(status string) { if m.notEmptyHolder() { m.getOrRegisterCounter(status).Inc(1) } @@ -88,7 +67,7 @@ func (m *metricService) getOrRegisterHistogram(uri string) metrics.Histogram { return histogram } -func (m *metricService) getOrRegisterCounter(status int) metrics.Counter { +func (m *metricService) getOrRegisterCounter(status string) metrics.Counter { m.mh.statusLock.RLock() d, ok := m.mh.statusCounters[status] m.mh.statusLock.RUnlock() @@ -101,7 +80,7 @@ func (m *metricService) getOrRegisterCounter(status int) metrics.Counter { if d, ok := m.mh.statusCounters[status]; ok { return d } - d = metrics.GetOrRegisterCounter("http.response.count."+strconv.Itoa(status), metric.GetRegistry()) + d = metrics.GetOrRegisterCounter("http.response.count."+status, metric.GetRegistry()) m.mh.statusCounters[status] = d return d } diff --git a/utils/utils.go b/utils/utils.go index f728bba..856745f 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -8,21 +8,19 @@ import ( "google.golang.org/grpc/codes" ) -const ( - JsonContentType = "application/json; charset=utf-8" -) +const JsonContentType = "application/json; charset=utf-8" -func SendError(errorMessage string, errorCode codes.Code, details []interface{}, ctx *fasthttp.RequestCtx) { - grpcCode := errorCode.String() +func WriteError(ctx *fasthttp.RequestCtx, message string, code codes.Code, details []interface{}) { + grpcCode := code.String() structureError := structure.GrpcError{ - ErrorMessage: errorMessage, + ErrorMessage: message, ErrorCode: grpcCode, Details: details, } ctx.SetContentType(JsonContentType) - ctx.SetStatusCode(http.CodeToHttpStatus(errorCode)) + ctx.SetStatusCode(http.CodeToHttpStatus(code)) msg, _ := json.Marshal(structureError) _, _ = ctx.Write(msg) }