From fe6f1f5e5af82280d21392dabfa4ad4daf5181fc Mon Sep 17 00:00:00 2001 From: DeniskaRediska Date: Mon, 21 Oct 2019 17:12:34 +0300 Subject: [PATCH] init --- .gitignore | 74 +++ .version | 1 + CHANGELOG.md | 0 Gopkg.lock | 565 ++++++++++++++++++ Gopkg.toml | 37 ++ conf/config.yml | 18 + conf/default_remote_config.json | 3 + conf/local_config.go | 20 + conf/remote_config.go | 59 ++ journal/client.go | 33 + log_code/code.go | 18 + log_code/metadata.go | 22 + main.go | 96 +++ proxy/description.go | 38 ++ proxy/grpc/client.go | 54 ++ proxy/grpc/handler.go | 48 ++ proxy/grpc/handlers/common.go | 79 +++ proxy/grpc/handlers/handle_get_file.go | 107 ++++ proxy/grpc/handlers/handle_json.go | 74 +++ .../handlers/handle_send_multipart_data.go | 112 ++++ proxy/grpc/utils/utils.go | 149 +++++ proxy/http/client.go | 90 +++ service/method_matcher.go | 70 +++ service/method_matcher_test.go | 50 ++ service/metrics.go | 101 ++++ 25 files changed, 1918 insertions(+) create mode 100644 .gitignore create mode 100644 .version create mode 100644 CHANGELOG.md create mode 100644 Gopkg.lock create mode 100644 Gopkg.toml create mode 100644 conf/config.yml create mode 100644 conf/default_remote_config.json create mode 100644 conf/local_config.go create mode 100644 conf/remote_config.go create mode 100644 journal/client.go create mode 100644 log_code/code.go create mode 100644 log_code/metadata.go create mode 100644 main.go create mode 100644 proxy/description.go create mode 100644 proxy/grpc/client.go create mode 100644 proxy/grpc/handler.go create mode 100644 proxy/grpc/handlers/common.go create mode 100644 proxy/grpc/handlers/handle_get_file.go create mode 100644 proxy/grpc/handlers/handle_json.go create mode 100644 proxy/grpc/handlers/handle_send_multipart_data.go create mode 100644 proxy/grpc/utils/utils.go create mode 100644 proxy/http/client.go create mode 100644 service/method_matcher.go create mode 100644 service/method_matcher_test.go create mode 100644 service/metrics.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3b079fc --- /dev/null +++ b/.gitignore @@ -0,0 +1,74 @@ +# Created by .ignore support plugin (hsz.mobi) +### JetBrains template +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff: +/.idea/ +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/dictionaries +*.iml +convert_service +convert-service + +# Sensitive or high-churn files: +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml + +# Gradle: +.idea/**/gradle.xml +.idea/**/libraries + +# CMake +cmake-build-debug/ +cmake-build-release/ + +# Mongo Explorer plugin: +.idea/**/mongoSettings.xml + +## File-based project format: +*.iws + +## Plugin-specific files: + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties +### Go template +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, build with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +/node_modules/ +/vendor/ +google/ +package.json +yarn.lock \ No newline at end of file diff --git a/.version b/.version new file mode 100644 index 0000000..8acdd82 --- /dev/null +++ b/.version @@ -0,0 +1 @@ +0.0.1 diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..e69de29 diff --git a/Gopkg.lock b/Gopkg.lock new file mode 100644 index 0000000..5e982f8 --- /dev/null +++ b/Gopkg.lock @@ -0,0 +1,565 @@ +# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. + + +[[projects]] + digest = "1:e92f5581902c345eb4ceffdcd4a854fb8f73cf436d47d837d1ec98ef1fe0a214" + name = "github.com/StackExchange/wmi" + packages = ["."] + pruneopts = "UT" + revision = "5d049714c4a64225c3c79a7cf7d02f7fb5b96338" + version = "1.0.0" + +[[projects]] + digest = "1:320e7ead93de9fd2b0e59b50fd92a4d50c1f8ab455d96bc2eb083267453a9709" + name = "github.com/asaskevich/govalidator" + packages = ["."] + pruneopts = "UT" + revision = "ccb8e960c48f04d6935e72476ae4a51028f9e22f" + version = "v9" + +[[projects]] + digest = "1:652880afc6b57ce0a67173f552cb35ccda816493a1da6ca20e5074a66bcd083f" + name = "github.com/buaazp/fasthttprouter" + packages = ["."] + pruneopts = "UT" + revision = "ade4e2031af3aed7fffd241084aad80a58faf421" + version = "v0.1.1" + +[[projects]] + digest = "1:abeb38ade3f32a92943e5be54f55ed6d6e3b6602761d74b4aab4c9dd45c18abd" + name = "github.com/fsnotify/fsnotify" + packages = ["."] + pruneopts = "UT" + revision = "c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9" + version = "v1.4.7" + +[[projects]] + digest = "1:440028f55cb322d8cb5b9d5ebec298a00b7d74690a658fe6b1c0c0b44341bfae" + name = "github.com/go-ole/go-ole" + packages = [ + ".", + "oleutil", + ] + pruneopts = "UT" + revision = "97b6244175ae18ea6eef668034fd6565847501c9" + version = "v1.2.4" + +[[projects]] + digest = "1:07f4fafe81587b642166199f41c3edcca12929fcfcc0261b00be5dea2f968f44" + name = "github.com/golang/protobuf" + packages = [ + "proto", + "ptypes", + "ptypes/any", + "ptypes/duration", + "ptypes/struct", + "ptypes/timestamp", + ] + pruneopts = "UT" + revision = "6c65a5562fc06764971b7c5d05c76c75e84bdbf7" + version = "v1.3.2" + +[[projects]] + digest = "1:e62657cca9badaa308d86e7716083e4c5933bb78e30a17743fc67f50be26f6f4" + name = "github.com/gorilla/websocket" + packages = ["."] + pruneopts = "UT" + revision = "c3e18be99d19e6b3e8f1559eea2c161a665c4b6b" + version = "v1.4.1" + +[[projects]] + digest = "1:c0d19ab64b32ce9fe5cf4ddceba78d5bc9807f0016db6b1183599da3dcc24d10" + name = "github.com/hashicorp/hcl" + packages = [ + ".", + "hcl/ast", + "hcl/parser", + "hcl/printer", + "hcl/scanner", + "hcl/strconv", + "hcl/token", + "json/parser", + "json/scanner", + "json/token", + ] + pruneopts = "UT" + revision = "8cb6e5b959231cc1119e43259c4a608f9c51a241" + version = "v1.0.0" + +[[projects]] + branch = "master" + digest = "1:2cf4ff28b309c93a52b3329c7a22d5375b137249d4ed63c9d40707a1b253f7df" + name = "github.com/integration-system/bellows" + packages = ["."] + pruneopts = "UT" + revision = "244325e8836c364c86f308e3aef7e979cb007114" + +[[projects]] + branch = "master" + digest = "1:c4f3970d1f30f5e9bc1751b62b7ea6127256e59fd63a3d36e166fe1121250c57" + name = "github.com/integration-system/go-cmp" + packages = [ + "cmp", + "cmp/internal/diff", + "cmp/internal/function", + "cmp/internal/value", + ] + pruneopts = "UT" + revision = "ac5582987a2f25e8743e0ebb7259312adda05c23" + +[[projects]] + digest = "1:12bcebed6dfc45cedc650f6dce60fe6ce6d27de88d9bfa8893a5b144c010d317" + name = "github.com/integration-system/golang-socketio" + packages = [ + ".", + "protocol", + "transport", + ] + pruneopts = "UT" + revision = "7513a9b590e428674e3c22ea82f46b28890cc17a" + version = "v1.0.0" + +[[projects]] + branch = "master" + digest = "1:abd0cd78d6d27a98080f2b2a7fd39bb2f3d3eef6aa20c720093129f04fb41d78" + name = "github.com/integration-system/gowsdl" + packages = ["soap"] + pruneopts = "UT" + revision = "368713356c71961354e09ab9b734740ebdd94784" + +[[projects]] + branch = "master" + digest = "1:9b7cbba3fe2efd27a291295e19a3731cd7bb1e0dcb6f41883e95b74f4ba0e09e" + name = "github.com/integration-system/isp-io" + packages = ["."] + pruneopts = "UT" + revision = "3daf588d878f287976f55a53917d535f787b7d64" + +[[projects]] + digest = "1:4b08bfb7e05c857ab9f985805f5c1e4c3049198f6909ddb5c632a3617322e4b7" + name = "github.com/integration-system/isp-journal" + packages = [ + ".", + "entry", + "log", + "rx", + "transfer", + ] + pruneopts = "UT" + revision = "13eb459c9964997befc886deba4d2dfb2c261b23" + version = "v1.3.0" + +[[projects]] + digest = "1:07a84c67d3c719dec447bf309303edda3b208234fee91fff5c38f466ee6665d1" + name = "github.com/integration-system/isp-lib" + packages = [ + "backend", + "bootstrap", + "config", + "config/schema", + "http", + "logger", + "metric", + "proto/stubs", + "streaming", + "structure", + "utils", + ] + pruneopts = "UT" + revision = "b110f4b47bc34145bda99c67560a780013d12f55" + version = "v1.6.3" + +[[projects]] + branch = "master" + digest = "1:ba98dc95f3f2eb551d124f9ed6a6a405ea95a6b2ab70450b988306e885caa4fe" + name = "github.com/integration-system/isp-log" + packages = ["."] + pruneopts = "UT" + revision = "a22bf2e0b56a9ef47db4a98756e39f700a99b688" + +[[projects]] + branch = "master" + digest = "1:48f3a739fabefebf152d0196277ee89136c1fa6d88fc67fa486fc765a05b1caa" + name = "github.com/integration-system/jsonschema" + packages = ["."] + pruneopts = "UT" + revision = "5475a8b08e62e41fa886641861ac225e7f91e4e5" + +[[projects]] + digest = "1:d78015a9da26d37166a2119592019e8bfe9b24bec60aff4a46db6110070fb1b2" + name = "github.com/json-iterator/go" + packages = [ + ".", + "extra", + ] + pruneopts = "UT" + revision = "03217c3e97663914aec3faafde50d081f197a0a2" + version = "1.1.8" + +[[projects]] + digest = "1:caa1da085cc12cd39d3ddb267434902f621050e1b46f7e9477b2b933df680193" + name = "github.com/klauspost/compress" + packages = [ + "flate", + "gzip", + "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" + +[[projects]] + digest = "1:31e761d97c76151dde79e9d28964a812c46efc5baee4085b86f68f0c654450de" + name = "github.com/konsorten/go-windows-terminal-sequences" + packages = ["."] + pruneopts = "UT" + revision = "f55edac94c9bbba5d6182a4be46d86a2c9b5b50e" + version = "v1.0.2" + +[[projects]] + digest = "1:5a0ef768465592efca0412f7e838cdc0826712f8447e70e6ccc52eb441e9ab13" + name = "github.com/magiconair/properties" + packages = ["."] + pruneopts = "UT" + revision = "de8848e004dd33dc07a2947b3d76f618a7fc7ef1" + version = "v1.8.1" + +[[projects]] + digest = "1:4a29eeb25603debe8f2098a9902c4d3851034cf70d33be428826e86e8c30a1b0" + name = "github.com/mattn/go-colorable" + packages = ["."] + pruneopts = "UT" + revision = "98ec13f34aabf44cc914c65a1cfb7b9bc815aef1" + version = "v0.1.4" + +[[projects]] + digest = "1:d62282425ffb75047679d7e2c3b980eea7f82c05ef5fb9142ee617ebac6e7432" + name = "github.com/mattn/go-isatty" + packages = ["."] + pruneopts = "UT" + revision = "88ba11cfdc67c7588b30042edf244b2875f892b6" + version = "v0.0.10" + +[[projects]] + branch = "master" + digest = "1:2b32af4d2a529083275afc192d1067d8126b578c7a9613b26600e4df9c735155" + name = "github.com/mgutz/ansi" + packages = ["."] + pruneopts = "UT" + revision = "9520e82c474b0a04dd04f8a40959027271bab992" + +[[projects]] + digest = "1:53bc4cd4914cd7cd52139990d5170d6dc99067ae31c56530621b18b35fc30318" + name = "github.com/mitchellh/mapstructure" + packages = ["."] + pruneopts = "UT" + revision = "3536a929edddb9a5b34bd6861dc4a9647cb459fe" + version = "v1.1.2" + +[[projects]] + digest = "1:33422d238f147d247752996a26574ac48dcf472976eda7f5134015f06bf16563" + name = "github.com/modern-go/concurrent" + packages = ["."] + pruneopts = "UT" + revision = "bacd9c7ef1dd9b15be4a9909b8ac7a4e313eec94" + version = "1.0.3" + +[[projects]] + digest = "1:e32bdbdb7c377a07a9a46378290059822efdce5c8d96fe71940d87cb4f918855" + name = "github.com/modern-go/reflect2" + packages = ["."] + pruneopts = "UT" + revision = "4b7aa43c6742a2c18fdef89dd197aaae7dac7ccd" + version = "1.0.1" + +[[projects]] + branch = "master" + digest = "1:84bd7f8a2e0bcd53ddc33c3b47c34c1fe340c8632cbe928f7f8ae10ec6ecdd62" + name = "github.com/mohae/deepcopy" + packages = ["."] + pruneopts = "UT" + revision = "c48cc78d482608239f6c4c92a4abd87eb8761c90" + +[[projects]] + digest = "1:bbd3997f0121200f72b64d7a3826eb8a0b910d6a4c19894c9fe2852b9e5eaf3b" + name = "github.com/pelletier/go-toml" + packages = ["."] + pruneopts = "UT" + revision = "8fe62057ea2d46ce44254c98e84e810044dbe197" + version = "v1.5.0" + +[[projects]] + digest = "1:cf31692c14422fa27c83a05292eb5cbe0fb2775972e8f1f8446a71549bd8980b" + name = "github.com/pkg/errors" + packages = ["."] + pruneopts = "UT" + revision = "ba968bfe8b2f7e042a574c888954fccecfa385b4" + version = "v0.8.1" + +[[projects]] + branch = "master" + digest = "1:5bbebe8ac19ecb6c87790a89faa20566e38ed0d6494a1d14c4f5b05d9ce2436c" + name = "github.com/rcrowley/go-metrics" + packages = ["."] + pruneopts = "UT" + revision = "cac0b30c2563378d434b5af411844adff8e32960" + +[[projects]] + digest = "1:ab1672baf07ee80c988e369e5633bcac459342e8e00d0c38a799056395fe9dba" + name = "github.com/shirou/gopsutil" + packages = [ + "cpu", + "internal/common", + ] + pruneopts = "UT" + revision = "1c09419d4b1c4c19e06d9f48b9406bda27d32acd" + version = "v2.19.9" + +[[projects]] + digest = "1:04457f9f6f3ffc5fea48e71d62f2ca256637dee0a04d710288e27e05c8b41976" + name = "github.com/sirupsen/logrus" + packages = ["."] + pruneopts = "UT" + revision = "839c75faf7f98a33d445d181f3018b5c3409a45e" + version = "v1.4.2" + +[[projects]] + digest = "1:bb495ec276ab82d3dd08504bbc0594a65de8c3b22c6f2aaa92d05b73fbf3a82e" + name = "github.com/spf13/afero" + packages = [ + ".", + "mem", + ] + pruneopts = "UT" + revision = "588a75ec4f32903aa5e39a2619ba6a4631e28424" + version = "v1.2.2" + +[[projects]] + digest = "1:08d65904057412fc0270fc4812a1c90c594186819243160dc779a402d4b6d0bc" + name = "github.com/spf13/cast" + packages = ["."] + pruneopts = "UT" + revision = "8c9545af88b134710ab1cd196795e7f2388358d7" + version = "v1.3.0" + +[[projects]] + digest = "1:1b753ec16506f5864d26a28b43703c58831255059644351bbcb019b843950900" + name = "github.com/spf13/jwalterweatherman" + packages = ["."] + pruneopts = "UT" + revision = "94f6ae3ed3bceceafa716478c5fbf8d29ca601a1" + version = "v1.1.0" + +[[projects]] + digest = "1:524b71991fc7d9246cc7dc2d9e0886ccb97648091c63e30eef619e6862c955dd" + name = "github.com/spf13/pflag" + packages = ["."] + pruneopts = "UT" + revision = "2e9d26c8c37aae03e3f9d4e90b7116f5accb7cab" + version = "v1.0.5" + +[[projects]] + digest = "1:11118bd196646c6515fea3d6c43f66162833c6ae4939bfb229b9956d91c6cf17" + name = "github.com/spf13/viper" + packages = ["."] + pruneopts = "UT" + revision = "b5bf975e5823809fb22c7644d008757f78a4259e" + version = "v1.4.0" + +[[projects]] + branch = "master" + digest = "1:d32b64a7a82dd36b674fb73ff767e949eb7155b6b574ff276f49d4edc8af105f" + name = "github.com/thecodeteam/goodbye" + packages = ["."] + pruneopts = "UT" + revision = "a83968bda2d37294a3541b7d2207fb6f5a3559a3" + +[[projects]] + digest = "1:c468422f334a6b46a19448ad59aaffdfc0a36b08fdcc1c749a0b29b6453d7e59" + name = "github.com/valyala/bytebufferpool" + packages = ["."] + pruneopts = "UT" + revision = "e746df99fe4a3986f4d4f79e13c1e0117ce9c2f7" + version = "v1.0.0" + +[[projects]] + branch = "master" + digest = "1:5788c649931a43dc8a21b07a4b51028238b1c2715baadef36c104572ba642be0" + name = "github.com/valyala/fasthttp" + packages = [ + ".", + "fasthttputil", + "stackless", + ] + pruneopts = "UT" + revision = "c3d82ca3a430260ff1795abfeac9e8396ed6f6fe" + +[[projects]] + digest = "1:39a425f98fb19427061a693fe6bf0683c9bddec4b25b17067e34fdb465e39cb9" + name = "github.com/x-cray/logrus-prefixed-formatter" + packages = ["."] + pruneopts = "UT" + revision = "bb2702d423886830dee131692131d35648c382e2" + version = "v0.5.2" + +[[projects]] + branch = "master" + digest = "1:bbe51412d9915d64ffaa96b51d409e070665efc5194fcf145c4a27d4133107a4" + name = "golang.org/x/crypto" + packages = ["ssh/terminal"] + pruneopts = "UT" + revision = "87dc89f01550277dc22b74ffcf4cd89fa2f40f4c" + +[[projects]] + branch = "master" + digest = "1:c124e945335a9c62ede3a565f3198c5ae9a5ecc39fddd85871138362d128fb74" + name = "golang.org/x/net" + packages = [ + "context", + "http/httpguts", + "http2", + "http2/hpack", + "idna", + "internal/timeseries", + "trace", + ] + pruneopts = "UT" + revision = "da9a3fd4c5820e74b24a6cb7fb438dc9b0dd377c" + +[[projects]] + branch = "master" + digest = "1:44480e76e73bb8d3104753f3618943ff331f2225c867c69af330e3e7f89b2e35" + name = "golang.org/x/sys" + packages = [ + "unix", + "windows", + ] + pruneopts = "UT" + revision = "727590c5006e77ca5247972f47e877f4929fc985" + +[[projects]] + digest = "1:8d8faad6b12a3a4c819a3f9618cb6ee1fa1cfc33253abeeea8b55336721e3405" + name = "golang.org/x/text" + packages = [ + "collate", + "collate/build", + "internal/colltab", + "internal/gen", + "internal/language", + "internal/language/compact", + "internal/tag", + "internal/triegen", + "internal/ucd", + "language", + "secure/bidirule", + "transform", + "unicode/bidi", + "unicode/cldr", + "unicode/norm", + "unicode/rangetable", + ] + pruneopts = "UT" + revision = "342b2e1fbaa52c93f31447ad2c6abc048c63e475" + version = "v0.3.2" + +[[projects]] + branch = "master" + digest = "1:a910255c3b706b4d8f2b185ed6b40c8f31b805111be240def2bdf2c62b87591b" + name = "google.golang.org/genproto" + packages = [ + "googleapis/rpc/errdetails", + "googleapis/rpc/status", + ] + pruneopts = "UT" + revision = "548a555dbc03994223efbaba0090152849259498" + +[[projects]] + digest = "1:6cd77d0b616d2dcebd363dfecba593f27b0151fc82cdb5fbfb96c5a7cfbc95b5" + name = "google.golang.org/grpc" + packages = [ + ".", + "balancer", + "balancer/base", + "balancer/roundrobin", + "binarylog/grpc_binarylog_v1", + "codes", + "connectivity", + "credentials", + "credentials/internal", + "encoding", + "encoding/proto", + "grpclog", + "internal", + "internal/backoff", + "internal/balancerload", + "internal/binarylog", + "internal/channelz", + "internal/envconfig", + "internal/grpcrand", + "internal/grpcsync", + "internal/syscall", + "internal/transport", + "keepalive", + "metadata", + "naming", + "peer", + "resolver", + "resolver/dns", + "resolver/passthrough", + "serviceconfig", + "stats", + "status", + "tap", + ] + pruneopts = "UT" + revision = "f6d0f9ee430895e87ef1ceb5ac8f39725bafceef" + version = "v1.24.0" + +[[projects]] + digest = "1:59f10c1537d2199d9115d946927fe31165959a95190849c82ff11e05803528b0" + name = "gopkg.in/yaml.v2" + packages = ["."] + pruneopts = "UT" + revision = "f221b8435cfb71e54062f6c6e99e9ade30b124d5" + version = "v2.2.4" + +[solve-meta] + analyzer-name = "dep" + analyzer-version = 1 + input-imports = [ + "github.com/buaazp/fasthttprouter", + "github.com/golang/protobuf/proto", + "github.com/golang/protobuf/ptypes/struct", + "github.com/integration-system/isp-journal/rx", + "github.com/integration-system/isp-lib/backend", + "github.com/integration-system/isp-lib/bootstrap", + "github.com/integration-system/isp-lib/config", + "github.com/integration-system/isp-lib/config/schema", + "github.com/integration-system/isp-lib/http", + "github.com/integration-system/isp-lib/metric", + "github.com/integration-system/isp-lib/proto/stubs", + "github.com/integration-system/isp-lib/streaming", + "github.com/integration-system/isp-lib/structure", + "github.com/integration-system/isp-lib/utils", + "github.com/integration-system/isp-log", + "github.com/json-iterator/go", + "github.com/pkg/errors", + "github.com/rcrowley/go-metrics", + "github.com/valyala/fasthttp", + "golang.org/x/net/context", + "google.golang.org/genproto/googleapis/rpc/errdetails", + "google.golang.org/grpc", + "google.golang.org/grpc/codes", + "google.golang.org/grpc/metadata", + "google.golang.org/grpc/status", + ] + solver-name = "gps-cdcl" + solver-version = 1 diff --git a/Gopkg.toml b/Gopkg.toml new file mode 100644 index 0000000..3734909 --- /dev/null +++ b/Gopkg.toml @@ -0,0 +1,37 @@ +# Gopkg.toml example +# +# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md +# for detailed Gopkg.toml documentation. +# +# required = ["github.com/user/thing/cmd/thing"] +# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] +# +# [[constraint]] +# name = "github.com/user/project" +# version = "1.0.0" +# +# [[constraint]] +# name = "github.com/user/project2" +# branch = "dev" +# source = "github.com/myfork/project2" +# +# [[override]] +# name = "github.com/x/y" +# version = "2.4.0" +# +# [prune] +# non-go = false +# go-tests = true +# unused-packages = true + +[[override]] + name = "mellium.im/sasl" + source = "https://github.com/mellium/sasl.git" + +[[override]] + name = "github.com/valyala/fasthttp" + branch = "master" + +[prune] + go-tests = true + unused-packages = true diff --git a/conf/config.yml b/conf/config.yml new file mode 100644 index 0000000..2fb628f --- /dev/null +++ b/conf/config.yml @@ -0,0 +1,18 @@ +configServiceAddress: + ip: 127.0.0.1 + port: 9001 +httpOuterAddress: + ip: http:// + port: 9003 +httpInnerAddress: + ip: 0.0.0.0 + port: 9003 +moduleName: isp-gate +instanceUuid: ec183598-746a-425f-b5e5-27b7fa8bc6af +locations: + - pathPrefix: /api + protocol: grpc + targetModule: router + - pathPrefix: /mdm + protocol: http + targetModule: mdm-api \ No newline at end of file diff --git a/conf/default_remote_config.json b/conf/default_remote_config.json new file mode 100644 index 0000000..0e0dcd2 --- /dev/null +++ b/conf/default_remote_config.json @@ -0,0 +1,3 @@ +{ + +} \ No newline at end of file diff --git a/conf/local_config.go b/conf/local_config.go new file mode 100644 index 0000000..5df2771 --- /dev/null +++ b/conf/local_config.go @@ -0,0 +1,20 @@ +package conf + +import "github.com/integration-system/isp-lib/structure" + +type ( + Configuration struct { + InstanceUuid string `valid:"required~Required"` + ModuleName string `valid:"required~Required"` + ConfigServiceAddress structure.AddressConfiguration `valid:"required~Required"` + HttpOuterAddress structure.AddressConfiguration `valid:"required~Required" json:"httpOuterAddress"` + HttpInnerAddress structure.AddressConfiguration `valid:"required~Required" json:"httpInnerAddress"` + Locations []Location + } + + Location struct { + PathPrefix string + Protocol string + TargetModule string + } +) diff --git a/conf/remote_config.go b/conf/remote_config.go new file mode 100644 index 0000000..7aba941 --- /dev/null +++ b/conf/remote_config.go @@ -0,0 +1,59 @@ +package conf + +import ( + "github.com/integration-system/isp-journal/rx" + "github.com/integration-system/isp-lib/structure" + "time" +) + +const ( + KB = int64(1024) + MB = int64(1 << 20) + + defaultSyncTimeout = 30 * time.Second + defaultStreamTimeout = 60 * time.Second + + defaultBufferSize = 4 * KB + defaultMaxRequestBodySize = 512 * MB + DefaultMaxResponseBodySize = 32 * MB +) + +type RemoteConfig struct { + EnableOriginalProtoErrors bool `schema:"Проксирование ошибок в протобаф,включение/отключение проксирования, по умолчанию отключено"` + ProxyGrpcErrorDetails bool `schema:"Проксирование первого элемента из details GRPC ошибки,включение/отключение проксирования, по умолчанию отключено"` + MultipartDataTransferBufferSizeBytes int64 `schema:"Размер буфера для передачи бинарных файлов,по умолчанию 4 KB"` + MaxRequestBodySizeBytes int64 `schema:"Максимальный размер тела запроса,в байтайх, по умолчанию: 512 MB"` + SyncInvokeMethodTimeoutMs int64 `schema:"Время ожидания вызова метода,значение в миллисекундах, по умолчанию: 30000"` + StreamInvokeMethodTimeoutMs int64 `schema:"Время ожидания передачи и обработки файла,значение в миллисекундах, по умолчанию: 60000"` + Metrics structure.MetricConfiguration `schema:"Настройка метрик"` + Journal rx.Config `schema:"Настройка логирования"` + JournalingMethodsPatterns []string `schema:"Список методов для логирования,список строк вида: 'module/group/method'(* - для частичного совпадения). При обработке запроса, если вызываемый метод совпадает со строкой из списка, тела запроса и ответа записываются в лог"` +} + +func (cfg RemoteConfig) GetSyncInvokeTimeout() time.Duration { + if cfg.SyncInvokeMethodTimeoutMs <= 0 { + return defaultSyncTimeout + } + return time.Duration(cfg.SyncInvokeMethodTimeoutMs) * time.Millisecond +} + +func (cfg RemoteConfig) GetStreamInvokeTimeout() time.Duration { + if cfg.StreamInvokeMethodTimeoutMs <= 0 { + return defaultStreamTimeout + } + return time.Duration(cfg.StreamInvokeMethodTimeoutMs) * time.Millisecond +} + +func (cfg RemoteConfig) GetTransferFileBufferSize() int64 { + if cfg.MultipartDataTransferBufferSizeBytes <= 0 { + return defaultBufferSize + } + return cfg.MultipartDataTransferBufferSizeBytes +} + +func (cfg RemoteConfig) GetMaxRequestBodySize() int64 { + if cfg.MaxRequestBodySizeBytes <= 0 { + return defaultMaxRequestBodySize + } + return cfg.MaxRequestBodySizeBytes +} diff --git a/journal/client.go b/journal/client.go new file mode 100644 index 0000000..1582f4a --- /dev/null +++ b/journal/client.go @@ -0,0 +1,33 @@ +package journal + +import ( + "github.com/integration-system/isp-journal/rx" + "github.com/integration-system/isp-lib/backend" + "github.com/integration-system/isp-lib/structure" + log "github.com/integration-system/isp-log" + "google.golang.org/grpc" + "isp-gate-service/log_code" +) + +var ( + journalServiceClient = backend.NewRxGrpcClient( + backend.WithDialOptions(grpc.WithInsecure(), grpc.WithBlock()), + backend.WithDialingErrorHandler(func(err error) { + log.Warnf(log_code.ErrorClientJournal, "journal client dialing err: %v", err) + }), + ) + Client = rx.NewDefaultRxJournal(journalServiceClient) +) + +func RequiredModule() (string, func([]structure.AddressConfiguration) bool, bool) { + return "journal", receiveJournalServiceAddressList, false +} + +func receiveJournalServiceAddressList(list []structure.AddressConfiguration) bool { + if ok := journalServiceClient.ReceiveAddressList(list); !ok { + return false + } else { + go Client.CollectAndTransferExistedLogs() + return true + } +} diff --git a/log_code/code.go b/log_code/code.go new file mode 100644 index 0000000..dca8361 --- /dev/null +++ b/log_code/code.go @@ -0,0 +1,18 @@ +package log_code + +const ( + InfoOnLocalConfigLoad = 601 + WarnCreateRestServerHttpSrvShutdown = 602 + ErrorCreateRestServerHttpSrvListenAndServe = 603 + WarnRequestHandler = 604 //metadata: {"typeData":"", "method":""} + WarnConvertErrorDataMarshalResponse = 605 + ErrorGrpcClientDialing = 606 + WarnJournalCouldNotWriteToFile = 607 + WarnJournalClientDialing = 608 + + ErrorClientJournal = 903 + + ErrorLocalConfig = 904 + ErrorClientGrpc = 905 + ErrorClientHttp = 906 +) diff --git a/log_code/metadata.go b/log_code/metadata.go new file mode 100644 index 0000000..f67952c --- /dev/null +++ b/log_code/metadata.go @@ -0,0 +1,22 @@ +package log_code + +const ( + MdTypeData = "typeData" + MdMethod = "method" +) + +var ( + TypeData = typeData{ + SendMultipart: "sendMultipart", + GetFile: "getFile", + JsonContent: "jsonContent", + } +) + +type ( + typeData struct { + SendMultipart string + GetFile string + JsonContent string + } +) diff --git a/main.go b/main.go new file mode 100644 index 0000000..ea2d0b4 --- /dev/null +++ b/main.go @@ -0,0 +1,96 @@ +package main + +import ( + "context" + + "github.com/integration-system/isp-lib/bootstrap" + "github.com/integration-system/isp-lib/config" + "github.com/integration-system/isp-lib/config/schema" + "github.com/integration-system/isp-lib/metric" + "github.com/integration-system/isp-lib/structure" + log "github.com/integration-system/isp-log" + + "isp-gate-service/conf" + "isp-gate-service/journal" + "isp-gate-service/log_code" + "isp-gate-service/proxy" + "isp-gate-service/service" + "os" +) + +var ( + version = "0.1.0" + date = "undefined" +) + +func main() { + + cfg := config.InitConfig(&conf.Configuration{}).(conf.Configuration) + + bs := bootstrap. + ServiceBootstrap(&conf.Configuration{}, &conf.RemoteConfig{}). + OnLocalConfigLoad(onLocalConfigLoad). + DefaultRemoteConfigPath(schema.ResolveDefaultConfigPath("default_remote_config.json")). + RequireModule(journal.RequiredModule()). //todo + SocketConfiguration(socketConfiguration). + DeclareMe(makeDeclaration). + OnRemoteConfigReceive(onRemoteConfigReceive). + OnShutdown(onShutdown) + + for _, location := range cfg.Locations { + if p, err := proxy.Init(location); err != nil { + log.Fatal(log_code.ErrorLocalConfig, err) // todo + } else { + bs.RequireModule(cfg.ModuleName, p.Consumer, false) + } + } + + bs.Run() +} + +func onLocalConfigLoad(cfg *conf.Configuration) { + log.Infof(log_code.InfoOnLocalConfigLoad, "Outer http address is %s", cfg.HttpOuterAddress.GetAddress()) +} + +func onRemoteConfigReceive(cfg, oldRemoteConfig *conf.RemoteConfig) { + localCfg := config.Get().(*conf.Configuration) + + journal.Client.ReceiveConfiguration(cfg.Journal, localCfg.ModuleName) + + service.JournalMethodsMatcher = service.NewCacheableMethodMatcher(cfg.JournalingMethodsPatterns) + + // + metric.InitCollectors(cfg.Metrics, oldRemoteConfig.Metrics) + metric.InitHttpServer(cfg.Metrics) + //metric.InitStatusChecker("router-grpc", helper.GetRoutersAndStatus) + service.Metrics.Init() +} + +func socketConfiguration(cfg interface{}) structure.SocketConfiguration { + appConfig := cfg.(*conf.Configuration) + return structure.SocketConfiguration{ + Host: appConfig.ConfigServiceAddress.IP, + Port: appConfig.ConfigServiceAddress.Port, + Secure: false, + UrlParams: map[string]string{ + "module_name": appConfig.ModuleName, + "instance_uuid": appConfig.InstanceUuid, + }, + } +} + +func onShutdown(_ context.Context, _ os.Signal) { + for _, p := range proxy.ProxyStore { + p.Close() + } +} + +func makeDeclaration(localConfig interface{}) bootstrap.ModuleInfo { + cfg := localConfig.(*conf.Configuration) + return bootstrap.ModuleInfo{ + ModuleName: cfg.ModuleName, + ModuleVersion: version, + GrpcOuterAddress: cfg.HttpOuterAddress, + Handlers: []interface{}{}, + } +} diff --git a/proxy/description.go b/proxy/description.go new file mode 100644 index 0000000..ad65db0 --- /dev/null +++ b/proxy/description.go @@ -0,0 +1,38 @@ +package proxy + +import ( + "errors" + "github.com/integration-system/isp-lib/structure" + "github.com/valyala/fasthttp" + "isp-gate-service/conf" + "isp-gate-service/proxy/grpc" + "isp-gate-service/proxy/http" +) + +var ProxyStore = make(map[string]Proxy) + +const ( + httpProtocol = "http" + grpcProtocol = "grpc" +) + +type Proxy interface { + ProxyRequest(ctx *fasthttp.RequestCtx) + Consumer([]structure.AddressConfiguration) bool + Close() +} + +func Init(location conf.Location) (Proxy, error) { + switch location.Protocol { + case httpProtocol: + proxy := http.NewProxy() + ProxyStore[location.PathPrefix] = proxy + return proxy, nil + case grpcProtocol: + proxy := grpc.NewProxy() + ProxyStore[location.PathPrefix] = proxy + return proxy, nil + default: + return nil, errors.New("unknown protocol") + } +} diff --git a/proxy/grpc/client.go b/proxy/grpc/client.go new file mode 100644 index 0000000..a304d45 --- /dev/null +++ b/proxy/grpc/client.go @@ -0,0 +1,54 @@ +package grpc + +import ( + "github.com/integration-system/isp-lib/backend" + "github.com/integration-system/isp-lib/structure" + log "github.com/integration-system/isp-log" + "github.com/valyala/fasthttp" + "google.golang.org/grpc" + "isp-gate-service/conf" + "isp-gate-service/log_code" + "isp-gate-service/service" + "net/http" + "time" +) + +type grpcProxy struct { + client *backend.RxGrpcClient +} + +func NewProxy() grpcProxy { + return grpcProxy{client: backend.NewRxGrpcClient( + backend.WithDialOptions( + grpc.WithInsecure(), grpc.WithBlock(), + grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(int(conf.DefaultMaxResponseBodySize))), + grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(int(conf.DefaultMaxResponseBodySize))), + ), + backend.WithDialingErrorHandler(func(err error) { + log.Errorf(log_code.ErrorClientGrpc, "dialing err: %v", err) + }), + )} +} + +func (p grpcProxy) ProxyRequest(ctx *fasthttp.RequestCtx) { + currentTime := time.Now() + + uri := string(ctx.RequestURI()) + SetHandler(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) + } +} + +func (p grpcProxy) Consumer(addr []structure.AddressConfiguration) bool { + return p.client.ReceiveAddressList(addr) +} + +func (p grpcProxy) Close() { + p.client.Close() +} diff --git a/proxy/grpc/handler.go b/proxy/grpc/handler.go new file mode 100644 index 0000000..607701c --- /dev/null +++ b/proxy/grpc/handler.go @@ -0,0 +1,48 @@ +package grpc + +import ( + "github.com/integration-system/isp-lib/backend" + u "github.com/integration-system/isp-lib/utils" + "github.com/valyala/fasthttp" + "isp-gate-service/proxy/grpc/handlers" + "isp-gate-service/proxy/grpc/utils" + "mime" +) + +type Handler interface { + Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) +} + +func SetHandler(ctx *fasthttp.RequestCtx) Handler { + isMultipart := isMultipart(ctx) + isExpectFile := string(ctx.Request.Header.Peek(u.ExpectFileHeader)) == "true" + + if isMultipart { + ctx.Response.Header.SetContentType(utils.JsonContentType) + return handlers.SendMultipartData + } else if isExpectFile { + return handlers.GetFile + } else { + ctx.Response.Header.SetContentType(utils.JsonContentType) + return handlers.Json + } +} + +func isMultipart(ctx *fasthttp.RequestCtx) bool { + if !ctx.IsPost() { + return false + } + v := string(ctx.Request.Header.ContentType()) + if v == "" { + return false + } + d, params, err := mime.ParseMediaType(v) + if err != nil || d != "multipart/form-data" { + return false + } + _, ok := params["boundary"] + if !ok { + return false + } + return true +} diff --git a/proxy/grpc/handlers/common.go b/proxy/grpc/handlers/common.go new file mode 100644 index 0000000..1dc03ce --- /dev/null +++ b/proxy/grpc/handlers/common.go @@ -0,0 +1,79 @@ +package handlers + +import ( + "github.com/integration-system/isp-lib/backend" + isp "github.com/integration-system/isp-lib/proto/stubs" + s "github.com/integration-system/isp-lib/streaming" + "github.com/valyala/fasthttp" + "golang.org/x/net/context" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/metadata" + "io" + "isp-gate-service/log_code" + "isp-gate-service/proxy/grpc/utils" + "mime/multipart" + "time" +) + +const ( + headerKeyContentDisposition = "Content-Disposition" + headerKeyContentType = "Content-Type" + headerKeyContentLength = "Content-Length" + headerKeyTransferEncoding = "Transfer-Encoding" + + errorMsgInternal = "Internal server error" + errorMsgInvalidArg = "Not able to read request body" +) + +func openStream(headers *fasthttp.RequestHeader, method string, timeout time.Duration, client *backend.RxGrpcClient) ( + isp.BackendService_RequestStreamClient, context.CancelFunc, error) { + + cli, err := client.Conn() + if err != nil { + return nil, nil, err + } + md, _ := utils.MakeMetadata(headers, method) + ctx := metadata.NewOutgoingContext(context.Background(), md) + ctx, cancel := context.WithTimeout(ctx, timeout) + stream, err := cli.RequestStream(ctx) + if err != nil { + return nil, nil, err + } + return stream, cancel, nil +} + +func transferFile(f multipart.File, stream isp.BackendService_RequestStreamClient, + buffer []byte, ctx *fasthttp.RequestCtx) (bool, bool) { + + ok := true + eof := false + 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 { + break + } + } + if err != nil { + if ok, eof = checkError(err, ctx); ok && eof { + err = stream.Send(s.FileEnd()) + ok, eof = checkError(err, ctx) + } + break + } + } + return ok, eof +} + +func checkError(err error, ctx *fasthttp.RequestCtx) (bool, bool) { + if err != nil { + if err != io.EOF { + utils.LogRequestHandlerError(log_code.TypeData.GetFile, "", err) + utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, ctx) + return false, false + } + return true, true + } + return true, false +} diff --git a/proxy/grpc/handlers/handle_get_file.go b/proxy/grpc/handlers/handle_get_file.go new file mode 100644 index 0000000..885b13f --- /dev/null +++ b/proxy/grpc/handlers/handle_get_file.go @@ -0,0 +1,107 @@ +package handlers + +import ( + "fmt" + "github.com/integration-system/isp-lib/backend" + "github.com/integration-system/isp-lib/config" + s "github.com/integration-system/isp-lib/streaming" + u "github.com/integration-system/isp-lib/utils" + log "github.com/integration-system/isp-log" + "github.com/valyala/fasthttp" + "google.golang.org/grpc/codes" + "io" + "isp-gate-service/conf" + "isp-gate-service/log_code" + "isp-gate-service/proxy/grpc/utils" + "strconv" +) + +var GetFile getFile + +type getFile struct{} + +func (getFile) Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) { + cfg := config.GetRemote().(*conf.RemoteConfig) + timeout := cfg.GetStreamInvokeTimeout() + + req, err := utils.ReadJsonBody(ctx) + if err != nil { + utils.LogRequestHandlerError(log_code.TypeData.GetFile, method, err) + utils.SendError(err.Error(), codes.InvalidArgument, nil, ctx) + return + } + + stream, cancel, err := openStream(&ctx.Request.Header, method, timeout, client) + defer func() { + if cancel != nil { + cancel() + } + }() + if err != nil { + utils.LogRequestHandlerError(log_code.TypeData.GetFile, method, err) + utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, ctx) + return + } + + if req != nil { + value := u.ConvertInterfaceToGrpcStruct(req) + err := stream.Send(backend.WrapBody(value)) + if err != nil { + utils.LogRequestHandlerError(log_code.TypeData.GetFile, method, err) + utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, ctx) + return + } + } + + msg, err := stream.Recv() + if err != nil { + bytes, status, err := utils.GetResponse(nil, err) + if err == nil { + ctx.SetStatusCode(status) + ctx.SetBody(bytes) + } + return + } + bf := s.BeginFile{} + err = bf.FromMessage(msg) + if err != nil { + bytes, status, err := utils.GetResponse(nil, err) + if err == nil { + ctx.SetStatusCode(status) + ctx.SetBody(bytes) + } + return + } + header := &ctx.Response.Header + header.Set(headerKeyContentDisposition, fmt.Sprintf("attachment; filename=%s", bf.FileName)) + header.Set(headerKeyContentType, bf.ContentType) + if bf.ContentLength > 0 { + header.Set(headerKeyContentLength, strconv.Itoa(int(bf.ContentLength))) + } else { + header.Set(headerKeyTransferEncoding, "chunked") + } + + for { + msg, err := stream.Recv() + if s.IsEndOfFile(msg) || err == io.EOF { + break + } + if err != nil { + utils.LogRequestHandlerError(log_code.TypeData.GetFile, method, err) + break + } + bytes := msg.GetBytesBody() + if bytes == nil { + log.WithMetadata(map[string]interface{}{ + log_code.MdTypeData: log_code.TypeData.GetFile, + log_code.MdMethod: method, + }).Errorf(log_code.WarnRequestHandler, "Method %s. Expected bytes array", method) + break + } + _, err = ctx.Write(bytes) + if err != nil { + utils.LogRequestHandlerError(log_code.TypeData.GetFile, method, err) + break + } + } +} diff --git a/proxy/grpc/handlers/handle_json.go b/proxy/grpc/handlers/handle_json.go new file mode 100644 index 0000000..2d1ed83 --- /dev/null +++ b/proxy/grpc/handlers/handle_json.go @@ -0,0 +1,74 @@ +package handlers + +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/log_code" + "isp-gate-service/proxy/grpc/utils" + "isp-gate-service/service" + "time" +) + +var Json handleJson + +type handleJson struct{} + +func (p handleJson) Complete(c *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) { + //body, err := utils.ReadJsonBody(c) + body := c.Request.Body() + /*if err != nil { + streaming.LogError(log_code.TypeData.JsonContent, method, err) + streaming.SendError(err.Error(), codes.InvalidArgument, []interface{}{err.Error()}, c) + return + }*/ + + md, methodName := utils.MakeMetadata(&c.Request.Header, method) + ctx := metadata.NewOutgoingContext(context.Background(), md) + cfg := config.GetRemote().(*conf.RemoteConfig) + ctx, cancel := context.WithTimeout(ctx, cfg.GetSyncInvokeTimeout()) + defer cancel() + + cli, err := client.Conn() + if err != nil { + utils.LogRequestHandlerError(log_code.TypeData.JsonContent, methodName, err) + utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, c) + return + } + + //structBody := u.ConvertInterfaceToGrpcStruct(body) + currentTime := time.Now() + response, invokerErr := cli.Request( + ctx, + &isp.Message{ + Body: &isp.Message_BytesBody{BytesBody: body}, + }, + ) + service.Metrics.UpdateRouterResponseTime(time.Since(currentTime) / 1e6) + + if data, status, err := utils.GetResponse(response, 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) + } + } + } + } else { + utils.LogRequestHandlerError(log_code.TypeData.JsonContent, methodName, err) + utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, c) + } +} diff --git a/proxy/grpc/handlers/handle_send_multipart_data.go b/proxy/grpc/handlers/handle_send_multipart_data.go new file mode 100644 index 0000000..5f23f49 --- /dev/null +++ b/proxy/grpc/handlers/handle_send_multipart_data.go @@ -0,0 +1,112 @@ +package handlers + +import ( + "github.com/integration-system/isp-lib/backend" + "github.com/integration-system/isp-lib/config" + s "github.com/integration-system/isp-lib/streaming" + "github.com/valyala/fasthttp" + "google.golang.org/grpc/codes" + "isp-gate-service/conf" + "isp-gate-service/log_code" + "isp-gate-service/proxy/grpc/utils" + "strings" +) + +var SendMultipartData sendMultipartData + +type sendMultipartData struct{} + +func (sendMultipartData) Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) { + cfg := config.GetRemote().(*conf.RemoteConfig) + timeout := cfg.GetStreamInvokeTimeout() + bufferSize := cfg.GetTransferFileBufferSize() + + stream, cancel, err := openStream(&ctx.Request.Header, method, timeout, client) + defer func() { + if cancel != nil { + cancel() + } + }() + if err != nil { + utils.LogRequestHandlerError(log_code.TypeData.SendMultipart, method, err) + utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, ctx) + return + } + + form, err := ctx.MultipartForm() + defer func() { + if form != nil { + _ = form.RemoveAll() + } + }() + + if err != nil { + utils.LogRequestHandlerError(log_code.TypeData.SendMultipart, method, err) + utils.SendError(errorMsgInvalidArg, codes.InvalidArgument, []interface{}{err.Error()}, ctx) + return + } + + formData := make(map[string]interface{}, len(form.Value)) + + for k, v := range form.Value { + if len(v) > 0 { + formData[k] = v[0] + } + } + + response := make([]string, 0) + buffer := make([]byte, bufferSize) + ok := true + eof := false + + for formDataName, files := range form.File { + if len(files) == 0 { + continue + } + file := files[0] + fileName := file.Filename + contentType := file.Header.Get(headerKeyContentType) + contentLength := file.Size + bf := s.BeginFile{ + FileName: fileName, + FormDataName: formDataName, + ContentType: contentType, + ContentLength: contentLength, + FormData: formData, + } + err = stream.Send(bf.ToMessage()) + if ok, eof = checkError(err, ctx); !ok || eof { + break + } + + f, err := file.Open() + if ok, eof = checkError(err, ctx); !ok || eof { + break + } + if ok, eof = transferFile(f, stream, buffer, ctx); ok { + msg, err := stream.Recv() + v, _, err := utils.GetResponse(msg, err) + if err == nil { + response = append(response, string(v)) + } + ok = err == nil + } + + if !ok || eof { + break + } + } + + err = stream.CloseSend() + if err != nil { + utils.LogRequestHandlerError(log_code.TypeData.SendMultipart, method, err) + } + + if ok { + arrayBody := strings.Join(response, ",") + _, err = ctx.WriteString("[" + arrayBody + "]") + if err != nil { + utils.LogRequestHandlerError(log_code.TypeData.SendMultipart, method, err) + } + } +} diff --git a/proxy/grpc/utils/utils.go b/proxy/grpc/utils/utils.go new file mode 100644 index 0000000..9c68e74 --- /dev/null +++ b/proxy/grpc/utils/utils.go @@ -0,0 +1,149 @@ +package utils + +import ( + "github.com/golang/protobuf/proto" + "github.com/integration-system/isp-lib/config" + "github.com/integration-system/isp-lib/structure" + log "github.com/integration-system/isp-log" + "google.golang.org/grpc/codes" + "isp-gate-service/conf" + "isp-gate-service/log_code" + "net/http" + "strings" + + "github.com/golang/protobuf/ptypes/struct" + "github.com/integration-system/isp-lib/backend" + http2 "github.com/integration-system/isp-lib/http" + "github.com/integration-system/isp-lib/proto/stubs" + "github.com/integration-system/isp-lib/utils" + "github.com/json-iterator/go" + "github.com/pkg/errors" + "github.com/valyala/fasthttp" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" +) + +const ( + JsonContentType = "application/json; charset=utf-8" +) + +var ( + json = jsoniter.ConfigFastest +) + +func ReadJsonBody(ctx *fasthttp.RequestCtx) (interface{}, error) { + requestBody := ctx.Request.Body() + var body interface{} + if len(requestBody) == 0 { + requestBody = []byte("{}") + } + if requestBody[0] == '{' { + body = make(map[string]interface{}) + } else if requestBody[0] == '[' { + body = make([]interface{}, 0) + } else { + return nil, errors.New("Invalid json format. Expected object or array") + } + + err := json.Unmarshal(requestBody, &body) + + if err != nil { + return nil, errors.New("Not able to read request body") + } + return body, err +} + +func GetResponse(msg *isp.Message, err error) ([]byte, int, error) { + if err != nil { + errorBody, errorStatus := convertError(err) + return errorBody, errorStatus, nil + } + + bytes := msg.GetBytesBody() + if bytes != nil { + return bytes, http.StatusOK, nil + } + result := backend.ResolveBody(msg) + data := utils.ConvertGrpcStructToInterface(result) + byteResponse, err := json.Marshal(data) + return byteResponse, http.StatusOK, err +} + +func MakeMetadata(r *fasthttp.RequestHeader, method string) (metadata.MD, string) { + method = strings.TrimPrefix(method, "/api/") + md := metadata.Pairs(utils.ProxyMethodNameHeader, method) + r.VisitAll(func(key, v []byte) { + lowerHeader := strings.ToLower(string(key)) + if len(v) > 0 && strings.HasPrefix(lowerHeader, "x-") { + md = metadata.Join(md, metadata.Pairs(lowerHeader, string(v))) + } + }) + return md, method +} + +func LogRequestHandlerError(typeData, method string, err error) { + log.WithMetadata(map[string]interface{}{ + log_code.MdTypeData: typeData, + log_code.MdMethod: method, + }).Warn(log_code.WarnRequestHandler, err) +} + +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.SetStatusCode(http2.CodeToHttpStatus(errorCode)) + msg, _ := json.Marshal(structureError) + _, _ = ctx.Write(msg) +} + +func convertError(err error) ([]byte, int) { + s, ok := status.FromError(err) + if ok { + cfg := config.GetRemote().(*conf.RemoteConfig) + if cfg.EnableOriginalProtoErrors { + if body, err := proto.Marshal(s.Proto()); err != nil { + return []byte(utils.ServiceError), http.StatusServiceUnavailable + } else { + return body, http2.CodeToHttpStatus(s.Code()) + } + } else { + details := s.Details() + newDetails := make([]interface{}, len(details)) + for i, detail := range details { + switch typeOfDetail := detail.(type) { + case *structpb.Struct: + newDetails[i] = utils.ConvertGrpcStructToInterface( + &structpb.Value{Kind: &structpb.Value_StructValue{StructValue: typeOfDetail}}, + ) + case *isp.Message: + newDetails[i] = utils.ConvertGrpcStructToInterface( + backend.ResolveBody(typeOfDetail), + ) + default: + newDetails[i] = typeOfDetail + } + } + + var respBody interface{} + if cfg.ProxyGrpcErrorDetails && len(newDetails) > 0 { + respBody = newDetails[0] + } else { + respBody = structure.GrpcError{ErrorMessage: s.Message(), ErrorCode: s.Code().String(), Details: newDetails} + } + if errorData, err := json.Marshal(respBody); err != nil { + log.Warn(log_code.WarnConvertErrorDataMarshalResponse, err) + return []byte(utils.ServiceError), http.StatusServiceUnavailable + } else { + return errorData, http2.CodeToHttpStatus(s.Code()) + } + } + } else { + return []byte(utils.ServiceError), http.StatusServiceUnavailable + } +} diff --git a/proxy/http/client.go b/proxy/http/client.go new file mode 100644 index 0000000..31c406c --- /dev/null +++ b/proxy/http/client.go @@ -0,0 +1,90 @@ +package http + +import ( + "github.com/integration-system/isp-lib/structure" + log "github.com/integration-system/isp-log" + "github.com/valyala/fasthttp" + "isp-gate-service/log_code" + "net" + "strings" +) + +type httpProxy struct { + client *fasthttp.HostClient +} + +func NewProxy() *httpProxy { + return &httpProxy{client: nil} +} + +func (p *httpProxy) Consumer(addressList []structure.AddressConfiguration) bool { + addresses := make([]string, len(addressList)) + for key, addr := range addressList { + addresses[key] = addr.GetAddress() + } + + p.client = &fasthttp.HostClient{ + Addr: strings.Join(addresses, `,`), + } + return true +} + +func (p *httpProxy) ProxyRequest(ctx *fasthttp.RequestCtx) { + req := &ctx.Request + res := &ctx.Response + + if clientIP, _, err := net.SplitHostPort(ctx.RemoteAddr().String()); err == nil { + req.Header.Add("X-Forwarded-For", clientIP) + } + + resHeaders := make(map[string]string) + res.Header.VisitAll(func(k, v []byte) { + key := string(k) + value := string(v) + if val, ok := resHeaders[key]; ok { + resHeaders[key] = val + "," + value + } + resHeaders[key] = value + }) + + for _, h := range hopHeaders { + // if h == "Te" && hv == "trailers" { + // continue + // } + req.Header.Del(h) + } + + if err := p.client.Do(req, res); err != nil { + log.Error(log_code.ErrorClientHttp, err) + return + } + + for _, h := range hopHeaders { + res.Header.Del(h) + } + for k, v := range resHeaders { + res.Header.Set(k, v) + } +} + +func (p *httpProxy) Close() { + p.client = nil + p = nil +} + +// Hop-by-hop headers. These are removed when sent to the backend. +// As of RFC 7230, hop-by-hop headers are required to appear in the +// Connection header field. These are the headers defined by the +// obsoleted RFC 2616 (section 13.5.1) and are used for backward +// compatibility. +var hopHeaders = []string{ + "Connection", + "Proxy-Connection", // non-standard but still sent by libcurl and rejected by e.g. google + "Keep-Alive", + "Proxy-Authenticate", + "Proxy-Authorization", + "Te", // canonicalized version of "TE" + "Trailer", // not Trailers per URL above; https://www.rfc-editor.org/errata_search.php?eid=4522 + "Transfer-Encoding", + "Upgrade", +} diff --git a/service/method_matcher.go b/service/method_matcher.go new file mode 100644 index 0000000..45fae7b --- /dev/null +++ b/service/method_matcher.go @@ -0,0 +1,70 @@ +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 new file mode 100644 index 0000000..8a1ceaa --- /dev/null +++ b/service/method_matcher_test.go @@ -0,0 +1,50 @@ +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 := 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 { + _ = Match(c.Method) + } + } +} + +func BenchmarkRuntimeMatcher_Match(b *testing.B) { + matcher := NewRuntimeMethodMatcher(patterns) + for i := 0; i < b.N; i++ { + for _, c := range cases { + _ = Match(c.Method) + } + } +} diff --git a/service/metrics.go b/service/metrics.go new file mode 100644 index 0000000..47e79fd --- /dev/null +++ b/service/metrics.go @@ -0,0 +1,101 @@ +package service + +import ( + "github.com/integration-system/isp-lib/metric" + "github.com/rcrowley/go-metrics" + "strconv" + "sync" + "time" +) + +const ( + defaultSampleSize = 2048 +) + +var Metrics = metricService{mh: nil} + +type ( + metricService struct { + mh *metricHolder + } + + metricHolder struct { + methodHistograms map[string]metrics.Histogram + methodLock sync.RWMutex + statusCounters map[int]metrics.Counter + statusLock sync.RWMutex + routerResponseTime metrics.Histogram + responseTime metrics.Histogram + } +) + +func (m metricService) Init() { + if m.mh == nil { + m.mh = &metricHolder{ + methodHistograms: make(map[string]metrics.Histogram), + statusCounters: make(map[int]metrics.Counter), + responseTime: metrics.GetOrRegisterHistogram( + "http.response.time", metric.GetRegistry(), metrics.NewUniformSample(defaultSampleSize), + ), + routerResponseTime: metrics.GetOrRegisterHistogram( + "grpc.router.response.time", metric.GetRegistry(), metrics.NewUniformSample(defaultSampleSize), + ), + } + } +} + +func (m metricService) UpdateMethodResponseTime(uri string, time time.Duration) { + m.getOrRegisterHistogram(uri).Update(int64(time)) +} + +func (m metricService) UpdateResponseTime(time time.Duration) { + m.mh.responseTime.Update(int64(time)) +} + +func (m metricService) UpdateRouterResponseTime(time time.Duration) { + m.mh.routerResponseTime.Update(int64(time)) +} + +func (m metricService) UpdateStatusCounter(status int) { + m.getOrRegisterCounter(status).Inc(1) +} + +func (m metricService) getOrRegisterHistogram(uri string) metrics.Histogram { + m.mh.methodLock.RLock() + histogram, ok := m.mh.methodHistograms[uri] + m.mh.methodLock.RUnlock() + if ok { + return histogram + } + + m.mh.methodLock.Lock() + defer m.mh.methodLock.Unlock() + if d, ok := m.mh.methodHistograms[uri]; ok { + return d + } + histogram = metrics.GetOrRegisterHistogram( + "http.response.time_"+uri, + metric.GetRegistry(), + metrics.NewUniformSample(defaultSampleSize), + ) + m.mh.methodHistograms[uri] = histogram + return histogram +} + +func (m metricService) getOrRegisterCounter(status int) metrics.Counter { + m.mh.statusLock.RLock() + d, ok := m.mh.statusCounters[status] + m.mh.statusLock.RUnlock() + if ok { + return d + } + + m.mh.statusLock.Lock() + defer m.mh.statusLock.Unlock() + if d, ok := m.mh.statusCounters[status]; ok { + return d + } + d = metrics.GetOrRegisterCounter("http.response.count."+strconv.Itoa(status), metric.GetRegistry()) + m.mh.statusCounters[status] = d + return d +}