From 1a8ed4e8ea033659eb908b4f005a8ddb15026142 Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Wed, 6 Nov 2019 16:38:50 +0300 Subject: [PATCH 1/7] add(approve request) --- Gopkg.lock | 93 ++++++++++++++++++---------- Gopkg.toml | 2 +- approve/approve.go | 44 +++++++++++++ approve/approve_test.go | 78 +++++++++++++++++++++++ approve/matcher/cacheable_matcher.go | 32 ++++++++++ approve/matcher/matcher.go | 18 ++++++ approve/matcher/matcher_test.go | 51 +++++++++++++++ approve/matcher/runtime_matcher.go | 17 +++++ approve/state/limit_state.go | 60 ++++++++++++++++++ approve/state/limiter.go | 44 +++++++++++++ authenticate/authenticate.go | 24 ++++--- conf/remote_config.go | 12 ++++ handler/handler.go | 10 ++- log_code/code.go | 3 +- main.go | 2 + 15 files changed, 446 insertions(+), 44 deletions(-) create mode 100644 approve/approve.go create mode 100644 approve/approve_test.go create mode 100644 approve/matcher/cacheable_matcher.go create mode 100644 approve/matcher/matcher.go create mode 100644 approve/matcher/matcher_test.go create mode 100644 approve/matcher/runtime_matcher.go create mode 100644 approve/state/limit_state.go create mode 100644 approve/state/limiter.go 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/approve/approve.go b/approve/approve.go new file mode 100644 index 0000000..3895b48 --- /dev/null +++ b/approve/approve.go @@ -0,0 +1,44 @@ +package approve + +import ( + log "github.com/integration-system/isp-log" + "isp-gate-service/approve/matcher" + "isp-gate-service/approve/state" + "isp-gate-service/conf" + "isp-gate-service/log_code" +) + +var approvingByAppId = make(map[int64]approve) + +type approve struct { + matcher matcher.Matcher + limitStates map[string]state.LimitState +} + +func ReceiveConfiguration(setting []conf.ApproveSetting) { + 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, + } + } +} + +func Complete(appId int64, method string) bool { + approve, ok := approvingByAppId[appId] + if !ok { + return true + } else { + stateStorage := make([]state.LimitState, 0) + patternArray := approve.matcher.Match(method) + for _, pattern := range patternArray { + stateStorage = append(stateStorage, approve.limitStates[pattern]) + } + return state.Update(stateStorage) + } +} diff --git a/approve/approve_test.go b/approve/approve_test.go new file mode 100644 index 0000000..61bbac5 --- /dev/null +++ b/approve/approve_test.go @@ -0,0 +1,78 @@ +package approve + +import ( + "github.com/stretchr/testify/assert" + "isp-gate-service/conf" + "testing" + "time" +) + +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"}, + }}, + } + + 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, Complete(req.appId, path)) + expected = !expected + time.Sleep(150 * time.Millisecond) + } + + //expected == true + req = reqExample[1] + for _, path := range req.path { + a.Equal(expected, Complete(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], Complete(req.appId, path)) + } + + //expected == true + req = reqExample[3] + for _, path := range req.path { + a.Equal(expected, Complete(req.appId, path)) + } +} diff --git a/approve/matcher/cacheable_matcher.go b/approve/matcher/cacheable_matcher.go new file mode 100644 index 0000000..7767938 --- /dev/null +++ b/approve/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/approve/matcher/matcher.go b/approve/matcher/matcher.go new file mode 100644 index 0000000..98cb6f3 --- /dev/null +++ b/approve/matcher/matcher.go @@ -0,0 +1,18 @@ +package matcher + +type Matcher interface { + Match(method string) []string +} + +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}, + } +} diff --git a/approve/matcher/matcher_test.go b/approve/matcher/matcher_test.go new file mode 100644 index 0000000..30c8754 --- /dev/null +++ b/approve/matcher/matcher_test.go @@ -0,0 +1,51 @@ +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 + length int + }{ + {method: "mdm-master/group/method", length: 2}, + {method: "mdm-master/group/method2", length: 1}, + {method: "mdm-master/group2/method3", length: 0}, + {method: "mdm-master/group2/method", length: 1}, + {method: "mdm-master/group3/some", length: 1}, + {method: "mdm-master/group3/", length: 1}, + } +) + +func TestCacheableMatcher_Match(t *testing.T) { + matcher := NewCacheableMatcher(patterns) + for _, c := range cases { + res := matcher.Match(c.method) + if c.length != len(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/approve/matcher/runtime_matcher.go b/approve/matcher/runtime_matcher.go new file mode 100644 index 0000000..4fb005b --- /dev/null +++ b/approve/matcher/runtime_matcher.go @@ -0,0 +1,17 @@ +package matcher + +import "path" + +type runtimeMatcher struct { + patterns []string +} + +func (mm runtimeMatcher) Match(method string) []string { + resp := make([]string, 0) + for _, pattern := range mm.patterns { + if matched, _ := path.Match(pattern, method); matched { + resp = append(resp, pattern) + } + } + return resp +} diff --git a/approve/state/limit_state.go b/approve/state/limit_state.go new file mode 100644 index 0000000..0fd75d9 --- /dev/null +++ b/approve/state/limit_state.go @@ -0,0 +1,60 @@ +package state + +import ( + "isp-gate-service/conf" + "sync" + "time" +) + +type ( + LimitState interface { + check() (bool, int, time.Time) + update(int, time.Time) + } + + updateRequest struct { + pointer int + datetime 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 { + lifetime, err := time.ParseDuration(limit.Lifetime) + if err != nil { + return nil, nil, err + } + if lifetime == 0 && limit.MaxCount != 0 { + limit.MaxCount = 1 + } + + patternArray[i] = limit.Pattern + limitStates[limit.Pattern] = &limiter{ + lifetime: lifetime, + datetime: make([]time.Time, limit.MaxCount), + pattern: limit.Pattern, + point: -1, + mx: sync.RWMutex{}, + } + } + return limitStates, patternArray, nil +} + +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} + } else { + return false + } + } + for i, st := range states { + u := update[i] + st.update(u.pointer, u.datetime) + } + return true +} diff --git a/approve/state/limiter.go b/approve/state/limiter.go new file mode 100644 index 0000000..bd31a25 --- /dev/null +++ b/approve/state/limiter.go @@ -0,0 +1,44 @@ +package state + +import ( + "sync" + "time" +) + +type limiter struct { + lifetime time.Duration + datetime []time.Time + pattern string + point int + mx sync.RWMutex +} + +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() + } + + lim.mx.RLock() + point := lim.point + 1 + if point >= len(lim.datetime) { + point = 0 + } + date := lim.datetime[point] + now := time.Now() + approve := now.Sub(date) > lim.lifetime + + lim.mx.RUnlock() + return approve, point, now +} + +func (lim *limiter) update(point int, time time.Time) { + lim.mx.Lock() + + lim.point = point + lim.datetime[point] = time + + lim.mx.Unlock() +} diff --git a/authenticate/authenticate.go b/authenticate/authenticate.go index d3251f8..5f29c4a 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,23 @@ var ( } ) -func Do(ctx *fasthttp.RequestCtx) error { +func Do(ctx *fasthttp.RequestCtx) (int64, error) { 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) @@ -51,14 +52,20 @@ func Do(ctx *fasthttp.RequestCtx) error { 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) @@ -69,10 +76,11 @@ func Do(ctx *fasthttp.RequestCtx) error { 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..b904c84 100644 --- a/conf/remote_config.go +++ b/conf/remote_config.go @@ -27,6 +27,18 @@ type ( Journal rx.Config `schema:"Настройка логирования"` JournalingMethodsPatterns []string `schema:"Список методов для логирования,список строк вида: 'module/group/method'(* - для частичного совпадения). При обработке запроса, если вызываемый метод совпадает со строкой из списка, тела запроса и ответа записываются в лог"` Redis structure.RedisConfiguration `schema:"Настрока Redis" valid:"required~Required"` + ApproveSetting []ApproveSetting + } + + ApproveSetting struct { + ApplicationId int64 + Limits []LimitSetting + } + + LimitSetting struct { + Pattern string + MaxCount int + Lifetime string } ServerSetting struct { diff --git a/handler/handler.go b/handler/handler.go index d7fb281..d1dfef7 100644 --- a/handler/handler.go +++ b/handler/handler.go @@ -3,13 +3,15 @@ package handler import ( "github.com/valyala/fasthttp" "google.golang.org/grpc/codes" + "isp-gate-service/approve" "isp-gate-service/authenticate" "isp-gate-service/proxy" "isp-gate-service/utils" ) func Complete(ctx *fasthttp.RequestCtx) { - if err := authenticate.Do(ctx); err != nil { + applicationId, err := authenticate.Do(ctx) + if err != nil { status := codes.Unknown switch e := err.(type) { case authenticate.ErrorDescription: @@ -20,6 +22,12 @@ func Complete(ctx *fasthttp.RequestCtx) { } path := string(ctx.Path()) + + if !approve.Complete(applicationId, path) { + utils.SendError("approve error", codes.PermissionDenied, nil, ctx) + return + } + p := proxy.Find(path) if p != nil { p.ProxyRequest(ctx) 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..d67582b 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/approve" "isp-gate-service/conf" "isp-gate-service/journal" "isp-gate-service/log_code" @@ -59,6 +60,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) service.JournalMethodsMatcher = service.NewCacheableMethodMatcher(remoteConfig.JournalingMethodsPatterns) From 2a81e83b2e271540bad7aa621575995d55c36287 Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Wed, 6 Nov 2019 19:14:40 +0300 Subject: [PATCH 2/7] fix(approve mutex) --- approve/approve.go | 34 +++++++++++++++++++++------------- approve/approve_test.go | 8 ++++---- approve/state/limit_state.go | 2 -- approve/state/limiter.go | 8 -------- handler/handler.go | 2 +- 5 files changed, 26 insertions(+), 28 deletions(-) diff --git a/approve/approve.go b/approve/approve.go index 3895b48..4708d65 100644 --- a/approve/approve.go +++ b/approve/approve.go @@ -6,39 +6,47 @@ import ( "isp-gate-service/approve/state" "isp-gate-service/conf" "isp-gate-service/log_code" + "sync" ) -var approvingByAppId = make(map[int64]approve) +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{ + approvingByAppId[s.ApplicationId] = &approve{ matcher: matcher.NewCacheableMatcher(patternArray), limitStates: limitState, + mx: sync.Mutex{}, } } } -func Complete(appId int64, method string) bool { - approve, ok := approvingByAppId[appId] - if !ok { - return true - } else { - stateStorage := make([]state.LimitState, 0) - patternArray := approve.matcher.Match(method) - for _, pattern := range patternArray { - stateStorage = append(stateStorage, approve.limitStates[pattern]) - } - return state.Update(stateStorage) +func GetApprove(appId int64) *approve { + return approvingByAppId[appId] +} + +func (app *approve) Complete(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 } diff --git a/approve/approve_test.go b/approve/approve_test.go index 61bbac5..b3dc8e0 100644 --- a/approve/approve_test.go +++ b/approve/approve_test.go @@ -52,7 +52,7 @@ func TestApprove(t *testing.T) { expected := true req := reqExample[0] for _, path := range req.path { - a.Equal(expected, Complete(req.appId, path)) + a.Equal(expected, GetApprove(req.appId).Complete(path)) expected = !expected time.Sleep(150 * time.Millisecond) } @@ -60,19 +60,19 @@ func TestApprove(t *testing.T) { //expected == true req = reqExample[1] for _, path := range req.path { - a.Equal(expected, Complete(req.appId, path)) + a.Equal(expected, GetApprove(req.appId).Complete(path)) expected = !expected } req = reqExample[2] expectedArray := []bool{true, true, true, true, true, false} for key, path := range req.path { - a.Equal(expectedArray[key], Complete(req.appId, path)) + a.Equal(expectedArray[key], GetApprove(req.appId).Complete(path)) } //expected == true req = reqExample[3] for _, path := range req.path { - a.Equal(expected, Complete(req.appId, path)) + a.Equal(expected, GetApprove(req.appId).Complete(path)) } } diff --git a/approve/state/limit_state.go b/approve/state/limit_state.go index 0fd75d9..8c8b0e7 100644 --- a/approve/state/limit_state.go +++ b/approve/state/limit_state.go @@ -2,7 +2,6 @@ package state import ( "isp-gate-service/conf" - "sync" "time" ) @@ -37,7 +36,6 @@ func InitLimitState(limits []conf.LimitSetting) (map[string]LimitState, []string datetime: make([]time.Time, limit.MaxCount), pattern: limit.Pattern, point: -1, - mx: sync.RWMutex{}, } } return limitStates, patternArray, nil diff --git a/approve/state/limiter.go b/approve/state/limiter.go index bd31a25..abb15c6 100644 --- a/approve/state/limiter.go +++ b/approve/state/limiter.go @@ -1,7 +1,6 @@ package state import ( - "sync" "time" ) @@ -10,7 +9,6 @@ type limiter struct { datetime []time.Time pattern string point int - mx sync.RWMutex } func (lim *limiter) check() (bool, int, time.Time) { @@ -21,7 +19,6 @@ func (lim *limiter) check() (bool, int, time.Time) { return true, 0, time.Now() } - lim.mx.RLock() point := lim.point + 1 if point >= len(lim.datetime) { point = 0 @@ -30,15 +27,10 @@ func (lim *limiter) check() (bool, int, time.Time) { now := time.Now() approve := now.Sub(date) > lim.lifetime - lim.mx.RUnlock() return approve, point, now } func (lim *limiter) update(point int, time time.Time) { - lim.mx.Lock() - lim.point = point lim.datetime[point] = time - - lim.mx.Unlock() } diff --git a/handler/handler.go b/handler/handler.go index d1dfef7..74827f1 100644 --- a/handler/handler.go +++ b/handler/handler.go @@ -23,7 +23,7 @@ func Complete(ctx *fasthttp.RequestCtx) { path := string(ctx.Path()) - if !approve.Complete(applicationId, path) { + if approver := approve.GetApprove(applicationId); approver != nil && !approver.Complete(path) { utils.SendError("approve error", codes.PermissionDenied, nil, ctx) return } From 3d97f3789a910435130f49e627c8c0694cb311a1 Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Thu, 7 Nov 2019 17:55:27 +0300 Subject: [PATCH 3/7] add(metrics and journaling) --- approve/approve.go | 2 +- approve/approve_test.go | 8 +- approve/matcher/matcher_test.go | 12 +- approve/matcher/runtime_matcher.go | 6 +- authenticate/authenticate.go | 11 +- domain/response.go | 7 ++ handler/handler.go | 103 ++++++++++++++++-- proxy/description.go | 13 ++- proxy/grpc/client.go | 23 +--- proxy/grpc/handlers/common.go | 23 ++-- proxy/grpc/handlers/description.go | 9 +- proxy/grpc/handlers/handle_get_file.go | 34 ++++-- proxy/grpc/handlers/handle_json.go | 46 ++++---- .../handlers/handle_send_multipart_data.go | 62 +++++++---- proxy/http/client.go | 11 +- proxy/response/response.go | 67 ++++++++++++ routing/routing.go | 4 + server/http.go | 2 +- service/metrics.go | 32 ++---- utils/utils.go | 28 ----- 20 files changed, 331 insertions(+), 172 deletions(-) create mode 100644 domain/response.go create mode 100644 proxy/response/response.go delete mode 100644 utils/utils.go diff --git a/approve/approve.go b/approve/approve.go index 4708d65..29e93cc 100644 --- a/approve/approve.go +++ b/approve/approve.go @@ -37,7 +37,7 @@ func GetApprove(appId int64) *approve { return approvingByAppId[appId] } -func (app *approve) Complete(method string) bool { +func (app *approve) ApproveMethod(method string) bool { app.mx.Lock() stateStorage := make([]state.LimitState, 0) diff --git a/approve/approve_test.go b/approve/approve_test.go index b3dc8e0..c50ce3f 100644 --- a/approve/approve_test.go +++ b/approve/approve_test.go @@ -52,7 +52,7 @@ func TestApprove(t *testing.T) { expected := true req := reqExample[0] for _, path := range req.path { - a.Equal(expected, GetApprove(req.appId).Complete(path)) + a.Equal(expected, GetApprove(req.appId).ApproveMethod(path)) expected = !expected time.Sleep(150 * time.Millisecond) } @@ -60,19 +60,19 @@ func TestApprove(t *testing.T) { //expected == true req = reqExample[1] for _, path := range req.path { - a.Equal(expected, GetApprove(req.appId).Complete(path)) + a.Equal(expected, GetApprove(req.appId).ApproveMethod(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).Complete(path)) + a.Equal(expectedArray[key], GetApprove(req.appId).ApproveMethod(path)) } //expected == true req = reqExample[3] for _, path := range req.path { - a.Equal(expected, GetApprove(req.appId).Complete(path)) + a.Equal(expected, GetApprove(req.appId).ApproveMethod(path)) } } diff --git a/approve/matcher/matcher_test.go b/approve/matcher/matcher_test.go index 30c8754..635066a 100644 --- a/approve/matcher/matcher_test.go +++ b/approve/matcher/matcher_test.go @@ -1,21 +1,23 @@ package matcher -import "testing" +import ( + "testing" +) var ( patterns = []string{ "mdm-master/group/method", - "mdm-master/group/*", + "mdm-master/group/", "mdm-master/group2/method", - "mdm-master/group3/*", + "mdm-master/group3/", } cases = []struct { method string length int }{ {method: "mdm-master/group/method", length: 2}, - {method: "mdm-master/group/method2", length: 1}, - {method: "mdm-master/group2/method3", length: 0}, + {method: "mdm-master/group/method2", length: 2}, + {method: "mdm-master/group2/method3", length: 1}, {method: "mdm-master/group2/method", length: 1}, {method: "mdm-master/group3/some", length: 1}, {method: "mdm-master/group3/", length: 1}, diff --git a/approve/matcher/runtime_matcher.go b/approve/matcher/runtime_matcher.go index 4fb005b..48eec21 100644 --- a/approve/matcher/runtime_matcher.go +++ b/approve/matcher/runtime_matcher.go @@ -1,6 +1,8 @@ package matcher -import "path" +import ( + "strings" +) type runtimeMatcher struct { patterns []string @@ -9,7 +11,7 @@ type runtimeMatcher struct { func (mm runtimeMatcher) Match(method string) []string { resp := make([]string, 0) for _, pattern := range mm.patterns { - if matched, _ := path.Match(pattern, method); matched { + if strings.HasPrefix(method, pattern) { resp = append(resp, pattern) } } diff --git a/authenticate/authenticate.go b/authenticate/authenticate.go index 5f29c4a..7c340e6 100644 --- a/authenticate/authenticate.go +++ b/authenticate/authenticate.go @@ -21,6 +21,14 @@ var ( ) 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) } @@ -44,8 +52,6 @@ func Do(ctx *fasthttp.RequestCtx) (int64, 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)) @@ -72,7 +78,6 @@ func Do(ctx *fasthttp.RequestCtx) (int64, error) { } } - 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 { diff --git a/domain/response.go b/domain/response.go new file mode 100644 index 0000000..b874c2a --- /dev/null +++ b/domain/response.go @@ -0,0 +1,7 @@ +package domain + +type ProxyResponse struct { + RequestBody []byte + ResponseBody []byte + Error error +} diff --git a/handler/handler.go b/handler/handler.go index 74827f1..c546a22 100644 --- a/handler/handler.go +++ b/handler/handler.go @@ -1,15 +1,59 @@ 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/approve" "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/utils" + "isp-gate-service/proxy/response" + "isp-gate-service/service" + "net/http" + "time" ) -func Complete(ctx *fasthttp.RequestCtx) { +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.UpdateResponseTime(executionTime) + service.Metrics.UpdateMethodResponseTime(uri, executionTime) + } + + if config.GetRemote().(*conf.RemoteConfig).Journal.Enable && service.JournalMethodsMatcher.Match(uri) { + if resp.Error != nil { + if err := journal.Client.Error(uri, resp.RequestBody, resp.ResponseBody, resp.Error); err != nil { + log.Warnf(log_code.WarnJournalCouldNotWriteToFile, "could not write to file journal: %v", err) + } + } else { + if err := journal.Client.Info(uri, resp.RequestBody, resp.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 @@ -17,21 +61,58 @@ func Complete(ctx *fasthttp.RequestCtx) { case authenticate.ErrorDescription: status = e.ConvertToGrpcStatus() } - utils.SendError("authenticate error", status, nil, ctx) - return + return response.Create(ctx, response.Option.SetAndSendError("unauthorized", status, err)) } - path := string(ctx.Path()) - - if approver := approve.GetApprove(applicationId); approver != nil && !approver.Complete(path) { - utils.SendError("approve error", codes.PermissionDenied, nil, ctx) - return + if approver := approve.GetApprove(applicationId); approver != nil && !approver.ApproveMethod(path) { + err := errors.New("approve error") + return response.Create(ctx, response.Option.SetAndSendError("forbidden", codes.PermissionDenied, err)) } 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) + return response.Create(ctx, response.Option.SetAndSendError("not found", codes.NotFound, 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 +} + +// +//func (h handlerHelper) CheckPath(path []byte) (bool, bool) { +// path = h.getPathWithoutPrefix(path) +// _, implemented := routing.AddressMap[string(path)] +// _, inner := routing.InnerAddressMap[string(path)] +// return implemented, inner +//} +// +//func (handlerHelper) getPathWithoutPrefix(path []byte) []byte { +// firstFound := false +// for i, value := range path { +// if value == '/' { +// if firstFound { +// return path[i+1:] +// } else { +// firstFound = true +// } +// } +// } +// return []byte{} +//} diff --git a/proxy/description.go b/proxy/description.go index b7fd7e2..049aea9 100644 --- a/proxy/description.go +++ b/proxy/description.go @@ -5,6 +5,7 @@ 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/http" "strings" @@ -17,11 +18,13 @@ const ( grpcProtocol = "grpc" ) -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] != '/' { diff --git a/proxy/grpc/client.go b/proxy/grpc/client.go index d9dcd78..488fa03 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" + "isp-gate-service/proxy/response" ) type grpcProxy struct { @@ -33,25 +32,15 @@ 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 + return response.Create(ctx, response.Option.SetAndSendError(msg, codes.Internal, 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..25e06bb 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" + "isp-gate-service/proxy/response" "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,21 @@ 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 + resp = response.Create(ctx, response.Option.SetAndSendError(errorMsgInternal, codes.Internal, 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..097eb3f 100644 --- a/proxy/grpc/handlers/description.go +++ b/proxy/grpc/handlers/description.go @@ -4,7 +4,8 @@ import ( "github.com/integration-system/isp-lib/backend" u "github.com/integration-system/isp-lib/utils" "github.com/valyala/fasthttp" - "isp-gate-service/utils" + "isp-gate-service/domain" + "isp-gate-service/proxy/response" "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 } ) @@ -23,12 +24,12 @@ func (h handlerHelper) Get(ctx *fasthttp.RequestCtx) handler { isExpectFile := string(ctx.Request.Header.Peek(u.ExpectFileHeader)) == "true" if isMultipart { - ctx.Response.Header.SetContentType(utils.JsonContentType) + ctx.Response.Header.SetContentType(response.JsonContentType) return sendMultipartData } else if isExpectFile { return getFile } else { - ctx.Response.Header.SetContentType(utils.JsonContentType) + ctx.Response.Header.SetContentType(response.JsonContentType) return handleJson } } diff --git a/proxy/grpc/handlers/handle_get_file.go b/proxy/grpc/handlers/handle_get_file.go index 76bb385..594d375 100644 --- a/proxy/grpc/handlers/handle_get_file.go +++ b/proxy/grpc/handlers/handle_get_file.go @@ -12,8 +12,9 @@ import ( "google.golang.org/grpc/codes" "io" "isp-gate-service/conf" + "isp-gate-service/domain" "isp-gate-service/log_code" - "isp-gate-service/utils" + "isp-gate-service/proxy/response" "strconv" ) @@ -21,15 +22,19 @@ 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 + return response.Create( + ctx, + response.Option.SetAndSendError(err.Error(), codes.InvalidArgument, err), + response.Option.EmptyRequest(), + response.Option.EmptyResponse(), + ) } stream, cancel, err := openStream(&ctx.Request.Header, method, timeout, client) @@ -40,8 +45,12 @@ 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 + return response.Create( + ctx, + response.Option.SetAndSendError(errorMsgInternal, codes.Internal, err), + response.Option.EmptyRequest(), + response.Option.EmptyResponse(), + ) } if req != nil { @@ -49,8 +58,12 @@ 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 + return response.Create( + ctx, + response.Option.SetAndSendError(errorMsgInternal, codes.Internal, err), + response.Option.EmptyRequest(), + response.Option.EmptyResponse(), + ) } } @@ -61,7 +74,7 @@ func (g getFileDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *b ctx.SetStatusCode(status) ctx.SetBody(bytes) } - return + return response.Create(ctx, response.Option.EmptyResponse(), response.Option.EmptyRequest()) } bf := s.BeginFile{} err = bf.FromMessage(msg) @@ -71,7 +84,7 @@ func (g getFileDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *b ctx.SetStatusCode(status) ctx.SetBody(bytes) } - return + return response.Create(ctx, response.Option.EmptyResponse(), response.Option.EmptyRequest()) } header := &ctx.Response.Header header.Set(headerKeyContentDisposition, fmt.Sprintf("attachment; filename=%s", bf.FileName)) @@ -105,6 +118,7 @@ func (g getFileDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *b break } } + return response.Create(ctx, response.Option.EmptyResponse(), response.Option.EmptyRequest()) } 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..5afe3fc 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" + "isp-gate-service/proxy/response" ) 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,40 @@ 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 + return response.Create( + c, + response.Option.SetAndSendError(errorMsgInternal, codes.Internal, err), + response.Option.EmptyRequest(), + response.Option.EmptyResponse(), + ) } //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 response.Create(c, response.Option.SetError(invokerErr)) } else { logHandlerError(log_code.TypeData.JsonContent, methodName, err) - utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, c) + return response.Create( + c, + response.Option.SetAndSendError(errorMsgInternal, codes.Internal, err), + response.Option.EmptyRequest(), + response.Option.EmptyResponse(), + ) } } diff --git a/proxy/grpc/handlers/handle_send_multipart_data.go b/proxy/grpc/handlers/handle_send_multipart_data.go index 4b9822f..e71c43b 100644 --- a/proxy/grpc/handlers/handle_send_multipart_data.go +++ b/proxy/grpc/handlers/handle_send_multipart_data.go @@ -8,8 +8,9 @@ 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" + "isp-gate-service/proxy/response" "mime/multipart" "strings" ) @@ -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,12 @@ 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 + return response.Create( + ctx, + response.Option.SetAndSendError(errorMsgInternal, codes.Internal, err), + response.Option.EmptyRequest(), + response.Option.EmptyResponse(), + ) } form, err := ctx.MultipartForm() @@ -44,8 +49,12 @@ 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 + return response.Create( + ctx, + response.Option.SetAndSendError(errorMsgInvalidArg, codes.InvalidArgument, err), + response.Option.EmptyRequest(), + response.Option.EmptyResponse(), + ) } formData := make(map[string]interface{}, len(form.Value)) @@ -56,10 +65,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 +89,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 +117,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/http/client.go b/proxy/http/client.go index b385792..023b66a 100644 --- a/proxy/http/client.go +++ b/proxy/http/client.go @@ -1,12 +1,14 @@ 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" + "isp-gate-service/proxy/response" "net" "strings" ) @@ -31,12 +33,11 @@ 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 + return response.Create(ctx, response.Option.SetAndSendError(msg, codes.Internal, errors.New(msg))) } req := &ctx.Request @@ -48,8 +49,8 @@ func (p *httpProxy) ProxyRequest(ctx *fasthttp.RequestCtx) { if err := p.client.Do(req, res); err != nil { log.Error(log_code.ErrorClientHttp, err) - return } + return response.Create(ctx) } func (p *httpProxy) Close() { diff --git a/proxy/response/response.go b/proxy/response/response.go new file mode 100644 index 0000000..126e6c6 --- /dev/null +++ b/proxy/response/response.go @@ -0,0 +1,67 @@ +package response + +import ( + "encoding/json" + "github.com/integration-system/isp-lib/http" + "github.com/integration-system/isp-lib/structure" + "github.com/valyala/fasthttp" + "google.golang.org/grpc/codes" + "isp-gate-service/domain" +) + +const JsonContentType = "application/json; charset=utf-8" + +var Option optionStruct + +type ( + optionStruct struct{} + option func(ctx *fasthttp.RequestCtx, response *domain.ProxyResponse) +) + +func Create(ctx *fasthttp.RequestCtx, options ...option) domain.ProxyResponse { + response := domain.ProxyResponse{ + RequestBody: ctx.Request.Body(), + ResponseBody: ctx.Response.Body(), + } + for _, option := range options { + option(ctx, &response) + } + return response +} + +func (optionStruct) EmptyRequest() option { + return func(ctx *fasthttp.RequestCtx, response *domain.ProxyResponse) { + response.RequestBody = make([]byte, 0) + } +} + +func (optionStruct) EmptyResponse() option { + return func(ctx *fasthttp.RequestCtx, response *domain.ProxyResponse) { + response.ResponseBody = make([]byte, 0) + } +} + +func (optionStruct) SetError(err error) option { + return func(ctx *fasthttp.RequestCtx, response *domain.ProxyResponse) { + response.Error = err + } +} + +func (optionStruct) SetAndSendError(msg string, code codes.Code, err error) option { + return func(ctx *fasthttp.RequestCtx, response *domain.ProxyResponse) { + response.Error = err + + grpcCode := code.String() + + structureError := structure.GrpcError{ + ErrorMessage: msg, + ErrorCode: grpcCode, + Details: []interface{}{err.Error()}, + } + + ctx.SetContentType(JsonContentType) + ctx.SetStatusCode(http.CodeToHttpStatus(code)) + msg, _ := json.Marshal(structureError) + _, _ = ctx.Write(msg) + } +} 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/metrics.go b/service/metrics.go index a087917..b24d91d 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,24 @@ 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 + responseTime metrics.Histogram } ) func (m *metricService) Init() { m.mh = &metricHolder{ methodHistograms: make(map[string]metrics.Histogram), - statusCounters: make(map[int]metrics.Counter), + 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), - ), + //routerResponseTime: metrics.GetOrRegisterHistogram( + // "grpc.router.response.time", metric.GetRegistry(), metrics.NewUniformSample(defaultSampleSize), + //), } } @@ -54,13 +52,7 @@ func (m *metricService) UpdateResponseTime(time time.Duration) { } } -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 +80,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 +93,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 deleted file mode 100644 index f728bba..0000000 --- a/utils/utils.go +++ /dev/null @@ -1,28 +0,0 @@ -package utils - -import ( - "encoding/json" - "github.com/integration-system/isp-lib/http" - "github.com/integration-system/isp-lib/structure" - "github.com/valyala/fasthttp" - "google.golang.org/grpc/codes" -) - -const ( - JsonContentType = "application/json; charset=utf-8" -) - -func SendError(errorMessage string, errorCode codes.Code, details []interface{}, ctx *fasthttp.RequestCtx) { - grpcCode := errorCode.String() - - structureError := structure.GrpcError{ - ErrorMessage: errorMessage, - ErrorCode: grpcCode, - Details: details, - } - - ctx.SetContentType(JsonContentType) - ctx.SetStatusCode(http.CodeToHttpStatus(errorCode)) - msg, _ := json.Marshal(structureError) - _, _ = ctx.Write(msg) -} From 1a46b678efb9d8472e6eda0274b8b4193a0fa1af Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Thu, 7 Nov 2019 18:08:17 +0300 Subject: [PATCH 4/7] up approve matcher --- approve/matcher/matcher_test.go | 8 ++++---- approve/matcher/runtime_matcher.go | 8 +++++++- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/approve/matcher/matcher_test.go b/approve/matcher/matcher_test.go index 635066a..a0ce9f9 100644 --- a/approve/matcher/matcher_test.go +++ b/approve/matcher/matcher_test.go @@ -7,17 +7,17 @@ import ( var ( patterns = []string{ "mdm-master/group/method", - "mdm-master/group/", + "mdm-master/group/*", "mdm-master/group2/method", - "mdm-master/group3/", + "mdm-master/group3/*", } cases = []struct { method string length int }{ {method: "mdm-master/group/method", length: 2}, - {method: "mdm-master/group/method2", length: 2}, - {method: "mdm-master/group2/method3", length: 1}, + {method: "mdm-master/group/method2", length: 1}, + {method: "mdm-master/group2/method3", length: 0}, {method: "mdm-master/group2/method", length: 1}, {method: "mdm-master/group3/some", length: 1}, {method: "mdm-master/group3/", length: 1}, diff --git a/approve/matcher/runtime_matcher.go b/approve/matcher/runtime_matcher.go index 48eec21..457d570 100644 --- a/approve/matcher/runtime_matcher.go +++ b/approve/matcher/runtime_matcher.go @@ -11,7 +11,13 @@ type runtimeMatcher struct { func (mm runtimeMatcher) Match(method string) []string { resp := make([]string, 0) for _, pattern := range mm.patterns { - if strings.HasPrefix(method, pattern) { + patternLen := len(pattern) + if patternLen > 0 && pattern[patternLen-1] == '*' { + pattern = pattern[:patternLen-1] + if strings.HasPrefix(method, pattern) { + resp = append(resp, pattern) + } + } else if strings.EqualFold(method, pattern) { resp = append(resp, pattern) } } From f802b2000dda08d5d5af4b5a63d14823cacbd95f Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Thu, 7 Nov 2019 19:16:40 +0300 Subject: [PATCH 5/7] up(proxy response) --- domain/response.go | 29 +++++++- handler/handler.go | 40 +++-------- proxy/grpc/client.go | 8 ++- proxy/grpc/handlers/common.go | 5 +- proxy/grpc/handlers/description.go | 6 +- proxy/grpc/handlers/handle_get_file.go | 32 +++------ proxy/grpc/handlers/handle_json.go | 20 ++---- .../handlers/handle_send_multipart_data.go | 18 ++--- proxy/http/client.go | 16 +++-- proxy/response/response.go | 67 ------------------- utils/utils.go | 26 +++++++ 11 files changed, 108 insertions(+), 159 deletions(-) delete mode 100644 proxy/response/response.go create mode 100644 utils/utils.go diff --git a/domain/response.go b/domain/response.go index b874c2a..56f8a95 100644 --- a/domain/response.go +++ b/domain/response.go @@ -1,7 +1,30 @@ package domain type ProxyResponse struct { - RequestBody []byte - ResponseBody []byte - Error error + 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 c546a22..4feb52c 100644 --- a/handler/handler.go +++ b/handler/handler.go @@ -13,8 +13,8 @@ import ( "isp-gate-service/journal" "isp-gate-service/log_code" "isp-gate-service/proxy" - "isp-gate-service/proxy/response" "isp-gate-service/service" + "isp-gate-service/utils" "net/http" "time" ) @@ -38,13 +38,14 @@ func CompleteRequest(ctx *fasthttp.RequestCtx) { service.Metrics.UpdateMethodResponseTime(uri, executionTime) } + requestBody, responseBody, err := resp.Get() if config.GetRemote().(*conf.RemoteConfig).Journal.Enable && service.JournalMethodsMatcher.Match(uri) { - if resp.Error != nil { - if err := journal.Client.Error(uri, resp.RequestBody, resp.ResponseBody, resp.Error); err != nil { + 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, resp.RequestBody, resp.ResponseBody); err != nil { + if err := journal.Client.Info(uri, requestBody, responseBody); err != nil { log.Warnf(log_code.WarnJournalCouldNotWriteToFile, "could not write to file journal: %v", err) } } @@ -61,12 +62,14 @@ func (handlerHelper) AuthenticateApproveProxy(ctx *fasthttp.RequestCtx) domain.P case authenticate.ErrorDescription: status = e.ConvertToGrpcStatus() } - return response.Create(ctx, response.Option.SetAndSendError("unauthorized", status, err)) + utils.WriteError(ctx, "unauthorized", status, nil) + return domain.Create().SetError(err) } if approver := approve.GetApprove(applicationId); approver != nil && !approver.ApproveMethod(path) { err := errors.New("approve error") - return response.Create(ctx, response.Option.SetAndSendError("forbidden", codes.PermissionDenied, err)) + utils.WriteError(ctx, "forbidden", codes.PermissionDenied, nil) + return domain.Create().SetError(err) } p := proxy.Find(path) @@ -74,7 +77,8 @@ func (handlerHelper) AuthenticateApproveProxy(ctx *fasthttp.RequestCtx) domain.P return p.ProxyRequest(ctx) } else { err := errors.Errorf("unknown path %s", path) - return response.Create(ctx, response.Option.SetAndSendError("not found", codes.NotFound, err)) + utils.WriteError(ctx, "not found", codes.NotFound, nil) + return domain.Create().SetError(err) } } @@ -94,25 +98,3 @@ func (handlerHelper) SetMetricStatus(statusCode int) string { } return metricStatus } - -// -//func (h handlerHelper) CheckPath(path []byte) (bool, bool) { -// path = h.getPathWithoutPrefix(path) -// _, implemented := routing.AddressMap[string(path)] -// _, inner := routing.InnerAddressMap[string(path)] -// return implemented, inner -//} -// -//func (handlerHelper) getPathWithoutPrefix(path []byte) []byte { -// firstFound := false -// for i, value := range path { -// if value == '/' { -// if firstFound { -// return path[i+1:] -// } else { -// firstFound = true -// } -// } -// } -// return []byte{} -//} diff --git a/proxy/grpc/client.go b/proxy/grpc/client.go index 488fa03..51231fa 100644 --- a/proxy/grpc/client.go +++ b/proxy/grpc/client.go @@ -12,7 +12,7 @@ import ( "isp-gate-service/domain" "isp-gate-service/log_code" "isp-gate-service/proxy/grpc/handlers" - "isp-gate-service/proxy/response" + "isp-gate-service/utils" ) type grpcProxy struct { @@ -36,7 +36,11 @@ func (p *grpcProxy) ProxyRequest(ctx *fasthttp.RequestCtx) domain.ProxyResponse if p.client.InternalGrpcClient == nil { msg := "client undefined" log.Error(log_code.ErrorClientGrpc, msg) - return response.Create(ctx, response.Option.SetAndSendError(msg, codes.Internal, errors.New(msg))) + utils.WriteError(ctx, msg, codes.Internal, nil) + return domain.Create(). + SetRequestBody(ctx.Request.Body()). + SetResponseBody(ctx.Response.Body()). + SetError(errors.New(msg)) } uri := string(ctx.RequestURI()) diff --git a/proxy/grpc/handlers/common.go b/proxy/grpc/handlers/common.go index 25e06bb..fc5a132 100644 --- a/proxy/grpc/handlers/common.go +++ b/proxy/grpc/handlers/common.go @@ -20,7 +20,7 @@ import ( "isp-gate-service/conf" "isp-gate-service/domain" "isp-gate-service/log_code" - "isp-gate-service/proxy/response" + utils2 "isp-gate-service/utils" "net/http" "strings" "time" @@ -149,7 +149,8 @@ func checkError(err error, ctx *fasthttp.RequestCtx) (bool, bool, domain.ProxyRe if err != nil { if err != io.EOF { logHandlerError(log_code.TypeData.GetFile, "", err) - resp = response.Create(ctx, response.Option.SetAndSendError(errorMsgInternal, codes.Internal, err)) + utils2.WriteError(ctx, errorMsgInternal, codes.Internal, nil) + resp = domain.Create().SetError(err) ok, eof = false, false } else { ok, eof = true, true diff --git a/proxy/grpc/handlers/description.go b/proxy/grpc/handlers/description.go index 097eb3f..f3ee7a1 100644 --- a/proxy/grpc/handlers/description.go +++ b/proxy/grpc/handlers/description.go @@ -5,7 +5,7 @@ import ( u "github.com/integration-system/isp-lib/utils" "github.com/valyala/fasthttp" "isp-gate-service/domain" - "isp-gate-service/proxy/response" + "isp-gate-service/utils" "mime" ) @@ -24,12 +24,12 @@ func (h handlerHelper) Get(ctx *fasthttp.RequestCtx) handler { isExpectFile := string(ctx.Request.Header.Peek(u.ExpectFileHeader)) == "true" if isMultipart { - ctx.Response.Header.SetContentType(response.JsonContentType) + ctx.Response.Header.SetContentType(utils.JsonContentType) return sendMultipartData } else if isExpectFile { return getFile } else { - ctx.Response.Header.SetContentType(response.JsonContentType) + ctx.Response.Header.SetContentType(utils.JsonContentType) return handleJson } } diff --git a/proxy/grpc/handlers/handle_get_file.go b/proxy/grpc/handlers/handle_get_file.go index 594d375..fd38b7c 100644 --- a/proxy/grpc/handlers/handle_get_file.go +++ b/proxy/grpc/handlers/handle_get_file.go @@ -14,7 +14,7 @@ import ( "isp-gate-service/conf" "isp-gate-service/domain" "isp-gate-service/log_code" - "isp-gate-service/proxy/response" + "isp-gate-service/utils" "strconv" ) @@ -29,12 +29,8 @@ func (g getFileDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *b req, err := g.readJsonBody(ctx) if err != nil { logHandlerError(log_code.TypeData.GetFile, method, err) - return response.Create( - ctx, - response.Option.SetAndSendError(err.Error(), codes.InvalidArgument, err), - response.Option.EmptyRequest(), - response.Option.EmptyResponse(), - ) + utils.WriteError(ctx, err.Error(), codes.InvalidArgument, nil) + return domain.Create().SetError(err) } stream, cancel, err := openStream(&ctx.Request.Header, method, timeout, client) @@ -45,12 +41,8 @@ func (g getFileDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *b }() if err != nil { logHandlerError(log_code.TypeData.GetFile, method, err) - return response.Create( - ctx, - response.Option.SetAndSendError(errorMsgInternal, codes.Internal, err), - response.Option.EmptyRequest(), - response.Option.EmptyResponse(), - ) + utils.WriteError(ctx, errorMsgInternal, codes.Internal, nil) + return domain.Create().SetError(err) } if req != nil { @@ -58,12 +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) - return response.Create( - ctx, - response.Option.SetAndSendError(errorMsgInternal, codes.Internal, err), - response.Option.EmptyRequest(), - response.Option.EmptyResponse(), - ) + utils.WriteError(ctx, errorMsgInternal, codes.Internal, nil) + return domain.Create().SetError(err) } } @@ -74,7 +62,7 @@ func (g getFileDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *b ctx.SetStatusCode(status) ctx.SetBody(bytes) } - return response.Create(ctx, response.Option.EmptyResponse(), response.Option.EmptyRequest()) + return domain.Create().SetError(err) } bf := s.BeginFile{} err = bf.FromMessage(msg) @@ -84,7 +72,7 @@ func (g getFileDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *b ctx.SetStatusCode(status) ctx.SetBody(bytes) } - return response.Create(ctx, response.Option.EmptyResponse(), response.Option.EmptyRequest()) + return domain.Create().SetError(err) } header := &ctx.Response.Header header.Set(headerKeyContentDisposition, fmt.Sprintf("attachment; filename=%s", bf.FileName)) @@ -118,7 +106,7 @@ func (g getFileDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *b break } } - return response.Create(ctx, response.Option.EmptyResponse(), response.Option.EmptyRequest()) + 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 5afe3fc..4484c2e 100644 --- a/proxy/grpc/handlers/handle_json.go +++ b/proxy/grpc/handlers/handle_json.go @@ -11,7 +11,7 @@ import ( "isp-gate-service/conf" "isp-gate-service/domain" "isp-gate-service/log_code" - "isp-gate-service/proxy/response" + "isp-gate-service/utils" ) var handleJson handleJsonDesc @@ -36,12 +36,8 @@ func (p handleJsonDesc) Complete(c *fasthttp.RequestCtx, method string, client * cli, err := client.Conn() if err != nil { logHandlerError(log_code.TypeData.JsonContent, methodName, err) - return response.Create( - c, - response.Option.SetAndSendError(errorMsgInternal, codes.Internal, err), - response.Option.EmptyRequest(), - response.Option.EmptyResponse(), - ) + utils.WriteError(c, errorMsgInternal, codes.Internal, nil) + return domain.Create().SetError(err) } //structBody := u.ConvertInterfaceToGrpcStruct(body) @@ -55,14 +51,10 @@ func (p handleJsonDesc) Complete(c *fasthttp.RequestCtx, method string, client * if data, status, err := getResponse(resp, invokerErr); err == nil { c.SetStatusCode(status) _, _ = c.Write(data) - return response.Create(c, response.Option.SetError(invokerErr)) + return domain.Create().SetError(invokerErr) } else { logHandlerError(log_code.TypeData.JsonContent, methodName, err) - return response.Create( - c, - response.Option.SetAndSendError(errorMsgInternal, codes.Internal, err), - response.Option.EmptyRequest(), - response.Option.EmptyResponse(), - ) + 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 e71c43b..a6734a0 100644 --- a/proxy/grpc/handlers/handle_send_multipart_data.go +++ b/proxy/grpc/handlers/handle_send_multipart_data.go @@ -10,7 +10,7 @@ import ( "isp-gate-service/conf" "isp-gate-service/domain" "isp-gate-service/log_code" - "isp-gate-service/proxy/response" + "isp-gate-service/utils" "mime/multipart" "strings" ) @@ -32,12 +32,8 @@ func (h sendMultipartDataDesc) Complete(ctx *fasthttp.RequestCtx, method string, }() if err != nil { logHandlerError(log_code.TypeData.SendMultipart, method, err) - return response.Create( - ctx, - response.Option.SetAndSendError(errorMsgInternal, codes.Internal, err), - response.Option.EmptyRequest(), - response.Option.EmptyResponse(), - ) + utils.WriteError(ctx, errorMsgInternal, codes.Internal, nil) + return domain.Create().SetError(err) } form, err := ctx.MultipartForm() @@ -49,12 +45,8 @@ func (h sendMultipartDataDesc) Complete(ctx *fasthttp.RequestCtx, method string, if err != nil { logHandlerError(log_code.TypeData.SendMultipart, method, err) - return response.Create( - ctx, - response.Option.SetAndSendError(errorMsgInvalidArg, codes.InvalidArgument, err), - response.Option.EmptyRequest(), - response.Option.EmptyResponse(), - ) + utils.WriteError(ctx, errorMsgInvalidArg, codes.InvalidArgument, nil) + return domain.Create().SetError(err) } formData := make(map[string]interface{}, len(form.Value)) diff --git a/proxy/http/client.go b/proxy/http/client.go index 023b66a..480feed 100644 --- a/proxy/http/client.go +++ b/proxy/http/client.go @@ -8,7 +8,7 @@ import ( "google.golang.org/grpc/codes" "isp-gate-service/domain" "isp-gate-service/log_code" - "isp-gate-service/proxy/response" + "isp-gate-service/utils" "net" "strings" ) @@ -37,7 +37,11 @@ func (p *httpProxy) ProxyRequest(ctx *fasthttp.RequestCtx) domain.ProxyResponse if p.client == nil { msg := "client undefined" log.Error(log_code.ErrorClientHttp, msg) - return response.Create(ctx, response.Option.SetAndSendError(msg, codes.Internal, errors.New(msg))) + 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 @@ -47,10 +51,14 @@ func (p *httpProxy) ProxyRequest(ctx *fasthttp.RequestCtx) domain.ProxyResponse 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 response.Create(ctx) + return domain.Create(). + SetRequestBody(ctx.Request.Body()). + SetResponseBody(ctx.Response.Body()). + SetError(err) } func (p *httpProxy) Close() { diff --git a/proxy/response/response.go b/proxy/response/response.go deleted file mode 100644 index 126e6c6..0000000 --- a/proxy/response/response.go +++ /dev/null @@ -1,67 +0,0 @@ -package response - -import ( - "encoding/json" - "github.com/integration-system/isp-lib/http" - "github.com/integration-system/isp-lib/structure" - "github.com/valyala/fasthttp" - "google.golang.org/grpc/codes" - "isp-gate-service/domain" -) - -const JsonContentType = "application/json; charset=utf-8" - -var Option optionStruct - -type ( - optionStruct struct{} - option func(ctx *fasthttp.RequestCtx, response *domain.ProxyResponse) -) - -func Create(ctx *fasthttp.RequestCtx, options ...option) domain.ProxyResponse { - response := domain.ProxyResponse{ - RequestBody: ctx.Request.Body(), - ResponseBody: ctx.Response.Body(), - } - for _, option := range options { - option(ctx, &response) - } - return response -} - -func (optionStruct) EmptyRequest() option { - return func(ctx *fasthttp.RequestCtx, response *domain.ProxyResponse) { - response.RequestBody = make([]byte, 0) - } -} - -func (optionStruct) EmptyResponse() option { - return func(ctx *fasthttp.RequestCtx, response *domain.ProxyResponse) { - response.ResponseBody = make([]byte, 0) - } -} - -func (optionStruct) SetError(err error) option { - return func(ctx *fasthttp.RequestCtx, response *domain.ProxyResponse) { - response.Error = err - } -} - -func (optionStruct) SetAndSendError(msg string, code codes.Code, err error) option { - return func(ctx *fasthttp.RequestCtx, response *domain.ProxyResponse) { - response.Error = err - - grpcCode := code.String() - - structureError := structure.GrpcError{ - ErrorMessage: msg, - ErrorCode: grpcCode, - Details: []interface{}{err.Error()}, - } - - ctx.SetContentType(JsonContentType) - ctx.SetStatusCode(http.CodeToHttpStatus(code)) - msg, _ := json.Marshal(structureError) - _, _ = ctx.Write(msg) - } -} diff --git a/utils/utils.go b/utils/utils.go new file mode 100644 index 0000000..856745f --- /dev/null +++ b/utils/utils.go @@ -0,0 +1,26 @@ +package utils + +import ( + "encoding/json" + "github.com/integration-system/isp-lib/http" + "github.com/integration-system/isp-lib/structure" + "github.com/valyala/fasthttp" + "google.golang.org/grpc/codes" +) + +const JsonContentType = "application/json; charset=utf-8" + +func WriteError(ctx *fasthttp.RequestCtx, message string, code codes.Code, details []interface{}) { + grpcCode := code.String() + + structureError := structure.GrpcError{ + ErrorMessage: message, + ErrorCode: grpcCode, + Details: details, + } + + ctx.SetContentType(JsonContentType) + ctx.SetStatusCode(http.CodeToHttpStatus(code)) + msg, _ := json.Marshal(structureError) + _, _ = ctx.Write(msg) +} From 8c68ffea8c96052dce84f3970cca229676ccc0cc Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Fri, 8 Nov 2019 11:49:37 +0300 Subject: [PATCH 6/7] up(matcher) --- approve/approve.go | 2 +- approve/matcher/matcher_test.go | 53 -------------- handler/handler.go | 3 +- main.go | 3 +- service/matcher/at_least_one_mather.go | 33 +++++++++ .../matcher/cacheable_matcher.go | 0 {approve => service}/matcher/matcher.go | 13 ++++ service/matcher/matcher_test.go | 65 +++++++++++++++++ .../matcher/runtime_matcher.go | 0 service/method_matcher.go | 70 ------------------- service/method_matcher_test.go | 50 ------------- 11 files changed, 116 insertions(+), 176 deletions(-) delete mode 100644 approve/matcher/matcher_test.go create mode 100644 service/matcher/at_least_one_mather.go rename {approve => service}/matcher/cacheable_matcher.go (100%) rename {approve => service}/matcher/matcher.go (53%) create mode 100644 service/matcher/matcher_test.go rename {approve => service}/matcher/runtime_matcher.go (100%) delete mode 100644 service/method_matcher.go delete mode 100644 service/method_matcher_test.go diff --git a/approve/approve.go b/approve/approve.go index 29e93cc..c94ad1f 100644 --- a/approve/approve.go +++ b/approve/approve.go @@ -2,10 +2,10 @@ package approve import ( log "github.com/integration-system/isp-log" - "isp-gate-service/approve/matcher" "isp-gate-service/approve/state" "isp-gate-service/conf" "isp-gate-service/log_code" + "isp-gate-service/service/matcher" "sync" ) diff --git a/approve/matcher/matcher_test.go b/approve/matcher/matcher_test.go deleted file mode 100644 index a0ce9f9..0000000 --- a/approve/matcher/matcher_test.go +++ /dev/null @@ -1,53 +0,0 @@ -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 - length int - }{ - {method: "mdm-master/group/method", length: 2}, - {method: "mdm-master/group/method2", length: 1}, - {method: "mdm-master/group2/method3", length: 0}, - {method: "mdm-master/group2/method", length: 1}, - {method: "mdm-master/group3/some", length: 1}, - {method: "mdm-master/group3/", length: 1}, - } -) - -func TestCacheableMatcher_Match(t *testing.T) { - matcher := NewCacheableMatcher(patterns) - for _, c := range cases { - res := matcher.Match(c.method) - if c.length != len(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/handler/handler.go b/handler/handler.go index 4feb52c..52818ca 100644 --- a/handler/handler.go +++ b/handler/handler.go @@ -14,6 +14,7 @@ import ( "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" @@ -39,7 +40,7 @@ func CompleteRequest(ctx *fasthttp.RequestCtx) { } requestBody, responseBody, err := resp.Get() - if config.GetRemote().(*conf.RemoteConfig).Journal.Enable && service.JournalMethodsMatcher.Match(uri) { + 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) diff --git a/main.go b/main.go index d67582b..96642df 100644 --- a/main.go +++ b/main.go @@ -17,6 +17,7 @@ import ( "isp-gate-service/routing" "isp-gate-service/server" "isp-gate-service/service" + "isp-gate-service/service/matcher" "os" ) @@ -62,7 +63,7 @@ func onRemoteConfigReceive(remoteConfig, oldRemoteConfig *conf.RemoteConfig) { server.Http.Init(remoteConfig.ServerSetting.MaxRequestBodySizeBytes) approve.ReceiveConfiguration(remoteConfig.ApproveSetting) - 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/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/approve/matcher/cacheable_matcher.go b/service/matcher/cacheable_matcher.go similarity index 100% rename from approve/matcher/cacheable_matcher.go rename to service/matcher/cacheable_matcher.go diff --git a/approve/matcher/matcher.go b/service/matcher/matcher.go similarity index 53% rename from approve/matcher/matcher.go rename to service/matcher/matcher.go index 98cb6f3..9f407f7 100644 --- a/approve/matcher/matcher.go +++ b/service/matcher/matcher.go @@ -1,9 +1,15 @@ 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, @@ -16,3 +22,10 @@ func NewCacheableMatcher(patterns []string) Matcher { 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/approve/matcher/runtime_matcher.go b/service/matcher/runtime_matcher.go similarity index 100% rename from approve/matcher/runtime_matcher.go rename to service/matcher/runtime_matcher.go 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) - } - } -} From 422bdb98318183ff658515587528cee49828cb82 Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Fri, 8 Nov 2019 16:36:43 +0300 Subject: [PATCH 7/7] ref --- accounting/accounting.go | 54 +++++++++++++++++++ .../accounting_test.go | 33 ++++++------ {approve => accounting}/state/limit_state.go | 18 +++---- accounting/state/limiter.go | 36 +++++++++++++ approve/approve.go | 52 ------------------ approve/state/limiter.go | 36 ------------- conf/remote_config.go | 34 ++++++------ handler/handler.go | 25 ++++----- main.go | 6 +-- proxy/description.go | 12 +++-- proxy/health_check/health_check.go | 26 +++++++++ service/matcher/runtime_matcher.go | 3 +- service/metrics.go | 13 ----- 13 files changed, 185 insertions(+), 163 deletions(-) create mode 100644 accounting/accounting.go rename approve/approve_test.go => accounting/accounting_test.go (65%) rename {approve => accounting}/state/limit_state.go (72%) create mode 100644 accounting/state/limiter.go delete mode 100644 approve/approve.go delete mode 100644 approve/state/limiter.go create mode 100644 proxy/health_check/health_check.go 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/approve/approve_test.go b/accounting/accounting_test.go similarity index 65% rename from approve/approve_test.go rename to accounting/accounting_test.go index c50ce3f..819527d 100644 --- a/approve/approve_test.go +++ b/accounting/accounting_test.go @@ -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)) } } diff --git a/approve/state/limit_state.go b/accounting/state/limit_state.go similarity index 72% rename from approve/state/limit_state.go rename to accounting/state/limit_state.go index 8c8b0e7..694cbb9 100644 --- a/approve/state/limit_state.go +++ b/accounting/state/limit_state.go @@ -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 } 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/approve/approve.go b/approve/approve.go deleted file mode 100644 index c94ad1f..0000000 --- a/approve/approve.go +++ /dev/null @@ -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 -} diff --git a/approve/state/limiter.go b/approve/state/limiter.go deleted file mode 100644 index abb15c6..0000000 --- a/approve/state/limiter.go +++ /dev/null @@ -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 -} diff --git a/conf/remote_config.go b/conf/remote_config.go index b904c84..c333601 100644 --- a/conf/remote_config.go +++ b/conf/remote_config.go @@ -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 -}*/ diff --git a/handler/handler.go b/handler/handler.go index 52818ca..a533fd6 100644 --- a/handler/handler.go +++ b/handler/handler.go @@ -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) } diff --git a/main.go b/main.go index 96642df..347143a 100644 --- a/main.go +++ b/main.go @@ -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) diff --git a/proxy/description.go b/proxy/description.go index 049aea9..cb7fc16 100644 --- a/proxy/description.go +++ b/proxy/description.go @@ -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) } } 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/service/matcher/runtime_matcher.go b/service/matcher/runtime_matcher.go index 457d570..3189411 100644 --- a/service/matcher/runtime_matcher.go +++ b/service/matcher/runtime_matcher.go @@ -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) { diff --git a/service/metrics.go b/service/metrics.go index b24d91d..68ba94e 100644 --- a/service/metrics.go +++ b/service/metrics.go @@ -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)