MSP-625 reimplement proxy

This commit is contained in:
DeniskaRediska authored and d1slike committed 2022-07-27 10:44:07 +03:00
1 parent ba2aeaf556
commit f2928ddcf7
8 files changed
+140 -389

No files matched your search

+140
View File
@@ -0,0 +1,140 @@
package assembly
import (
"fmt"
"net/http"
"github.com/integration-system/isp-kit/grpc/client"
"github.com/integration-system/isp-kit/http/endpoint"
"github.com/integration-system/isp-kit/json"
"github.com/integration-system/isp-kit/lb"
"github.com/integration-system/isp-kit/log"
"github.com/integration-system/isp-kit/requestid"
"github.com/pkg/errors"
"isp-gate-service/conf"
"isp-gate-service/domain"
"isp-gate-service/middleware"
"isp-gate-service/proxy"
"isp-gate-service/routes"
"isp-gate-service/service"
)
type Locator struct {
logger endpoint.Logger
grpcClientByModuleName map[string]*client.Client
httpHostManagerByModuleName map[string]*lb.RoundRobin
routes *routes.Routes
}
func NewLocator(
logger endpoint.Logger,
grpcClientByModuleName map[string]*client.Client,
httpHostManagerByModuleName map[string]*lb.RoundRobin,
routes *routes.Routes,
) Locator {
return Locator{
logger: logger,
grpcClientByModuleName: grpcClientByModuleName,
httpHostManagerByModuleName: httpHostManagerByModuleName,
routes: routes,
}
}
func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Handler, error) {
adminService := service.NewAdmin(config.TokensSetting.AdminSecret, l.routes)
mux := http.NewServeMux()
for _, location := range locations {
var proxyFunc middleware.Handler
switch location.Protocol {
case conf.GrpcProtocol:
cli := l.grpcClientByModuleName[location.TargetModule]
proxyFunc = proxy.NewGrpc(cli)
case conf.HttpProtocol:
hostManager := l.httpHostManagerByModuleName[location.TargetModule]
proxyFunc = proxy.NewHttp(hostManager)
case conf.WebsocketProtocol:
default:
return nil, errors.New("")
}
middlewares := []middleware.Middleware{
middleware.Path(location.PathPrefix),
middleware.Authenticate(adminService),
middleware.Authorize(adminService),
}
for i := len(middlewares) - 1; i >= 0; i-- {
proxyFunc = middlewares[i](proxyFunc)
}
var adapter = http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
ctx := &middleware.Context{
Id: requestid.Next(),
Request: request,
ResponseWriter: writer,
}
err := proxyFunc.Handle(ctx)
if err != nil {
l.handleError(ctx, err)
} else {
l.logger.Info(request.Context(), "successful request",
log.String("id", ctx.Id),
log.String("path", ctx.Path),
log.Int("application_id", ctx.AppId),
log.Int("admin_id", ctx.AdminId),
)
}
})
mux.HandleFunc(fmt.Sprintf("%s/", location.PathPrefix), adapter)
}
return mux, nil
}
func (l Locator) handleError(ctx *middleware.Context, err error) {
l.logger.Error(ctx.Request.Context(), "unsuccessful request",
log.String("id", ctx.Id),
log.Any("error", err),
)
status := 0
details := make(map[string]string)
switch {
case errors.Is(err, domain.ErrAuthorize):
status = http.StatusUnauthorized
details["message"] = domain.ErrAuthorize.Error()
case errors.Is(err, domain.ErrAuthenticate):
status = http.StatusUnauthorized
details["message"] = domain.ErrAuthenticate.Error()
default:
status = http.StatusInternalServerError
}
details["id"] = ctx.Id
result := domain.Error{
ErrorMessage: http.StatusText(status),
ErrorCode: http.StatusText(status),
Details: []interface{}{details},
}
body, err := json.Marshal(result)
if err != nil {
l.logger.Error(ctx.Request.Context(), "json error marshal",
log.String("id", ctx.Id),
log.Any("error", err),
)
return
}
ctx.ResponseWriter.Header().Set("Content-Type", "application/json; charset=utf-8")
ctx.ResponseWriter.WriteHeader(status)
_, err = ctx.ResponseWriter.Write(body)
if err != nil {
l.logger.Error(ctx.Request.Context(), "write error response",
log.String("id", ctx.Id),
log.Any("error", err),
)
return
}
}
-130
View File
@@ -1,130 +0,0 @@
package handler
import (
"fmt"
"net/http"
"time"
"github.com/integration-system/isp-kit/log"
"github.com/integration-system/isp-lib/v2/config"
"github.com/pkg/errors"
"github.com/valyala/fasthttp"
"google.golang.org/grpc/codes"
"isp-gate-service/authenticate"
"isp-gate-service/conf"
"isp-gate-service/domain"
"isp-gate-service/proxy"
"isp-gate-service/routing"
"isp-gate-service/service"
"isp-gate-service/service/matcher"
"isp-gate-service/utils"
)
const (
execution = 1e6
)
type Handler struct {
logger log.Logger
}
func New(logger log.Logger) *Handler {
return &Handler{
logger: logger,
}
}
func (h Handler) CompleteRequest(ctx *fasthttp.RequestCtx) {
currentTime := time.Now()
appId, adminId, path, resp := h.authenticateAccountingProxy(ctx)
executionTime := time.Since(currentTime) / execution
statusCode := ctx.Response.StatusCode()
service.Metrics.UpdateStatusCounter(h.setMetricStatus(statusCode))
if statusCode == http.StatusOK {
service.Metrics.UpdateMethodResponseTime(path, executionTime)
}
logEnable := config.GetRemote().(*conf.RemoteConfig).JournalSetting.Journal.Enable
// nolintlint
if logEnable && matcher.JournalMethods.Match(path) {
requestBody, responseBody, err := resp.Get()
fields := []log.Field{
log.ByteString("http_method", ctx.Method()),
log.String("remote_addr", ctx.RemoteAddr().String()),
log.ByteString("x_forwarded_for", ctx.Request.Header.Peek("X-Forwarded-For")),
log.Int("status_code", ctx.Response.StatusCode()),
log.String("path", path),
log.Int32("application_id", appId),
log.Int64("admin_id", adminId),
log.ByteString("request", requestBody),
log.ByteString("response", responseBody),
}
if err != nil {
fields = append(fields, log.Any("error", err))
h.logger.Error(ctx, "unsuccessful request", fields...)
} else {
h.logger.Info(ctx, "successful request", fields...)
}
}
}
func (h Handler) authenticateAccountingProxy(ctx *fasthttp.RequestCtx) (int32, int64, string, domain.ProxyResponse) {
var (
appId int32 = -1
adminId int64 = -1
initialPath = string(ctx.Path())
)
p, path := proxy.Find(initialPath)
if p == nil {
msg := fmt.Sprintf("unknown proxy for '%s'", initialPath)
utils.WriteError(ctx, msg, codes.NotFound, nil)
return appId, adminId, initialPath, domain.Create().SetError(errors.New(msg))
}
if !p.SkipExistCheck() {
if _, ok := routing.AllMethods[path]; !ok {
msg := "not implemented"
utils.WriteError(ctx, msg, codes.Unimplemented, nil)
return appId, adminId, path, domain.Create().SetError(errors.New(msg))
}
}
if !p.SkipAuth() {
var err error
appId, adminId, err = authenticate.Do(ctx, path)
if err != nil {
message := "unknown error"
status := codes.Unknown
details := make([]interface{}, 0)
if e, ok := err.(authenticate.ErrorDescription); ok {
message = e.Message()
status = e.ConvertToGrpcStatus()
details = e.Details()
}
utils.WriteError(ctx, message, status, details)
return appId, adminId, path, domain.Create().SetError(err)
}
}
return appId, adminId, path, p.ProxyRequest(ctx, path)
}
func (Handler) 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
}
-25
View File
@@ -1,25 +0,0 @@
package log_code
const (
WarnHttpServerShutdown = 602
ErrorHttpServerListen = 603
WarnProxyGrpcHandler = 604 //metadata: {"typeData":"", "method":""}
WarnConvertErrorDataMarshalResponse = 605
ErrorClientGrpc = 606
WarnJournalCouldNotWriteToFile = 607
ErrorClientJournal = 608
ErrorClientRedis = 609
ErrorClientHttp = 611
ErrorAuthenticate = 612
ErrorClientDatabase = 615
ErrorSnapshotAccounting = 616
ErrorUnloadAccounting = 617
ErrorWebsocketProxy = 618
)
-22
View File
@@ -1,22 +0,0 @@
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
}
)
-121
View File
@@ -1,121 +0,0 @@
package proxy
import (
"isp-gate-service/conf"
"sort"
"strings"
"github.com/integration-system/isp-lib/v2/structure"
"github.com/pkg/errors"
"github.com/valyala/fasthttp"
"isp-gate-service/domain"
"isp-gate-service/proxy/grpc"
"isp-gate-service/proxy/health_check"
"isp-gate-service/proxy/http"
"isp-gate-service/proxy/websocket"
)
var (
store = make([]storeItem, 0)
)
const (
httpProtocol = "http"
websocketProtocol = "websocket"
grpcProtocol = "grpc"
healthCheckProtocol = "healthсheck"
)
type (
Proxy interface {
ProxyRequest(ctx *fasthttp.RequestCtx, path string) domain.ProxyResponse
Consumer([]structure.AddressConfiguration) bool
SkipAuth() bool
SkipExistCheck() bool
Close()
}
storeItem struct {
pathPrefix string
proxy Proxy
}
)
func InitProxies(locations []conf.Location) (map[string]func([]structure.AddressConfiguration) bool, error) {
locationsByTargetModule := conf.GetLocationsByTargetModule(locations)
requiredModules := make(map[string]func([]structure.AddressConfiguration) bool)
for targetModule, locations := range locationsByTargetModule {
consumerStorage := make([]func([]structure.AddressConfiguration) bool, len(locations))
for i, location := range locations {
if location.PathPrefix[0] != '/' {
return nil, errors.Errorf("path must begin with '/' in path '%s'", location.PathPrefix)
}
p, err := makeProxy(location.Protocol, location.SkipAuth, location.SkipExistCheck)
if err != nil {
return nil, err
}
store = append(store, storeItem{
pathPrefix: location.PathPrefix,
proxy: p,
})
consumerStorage[i] = p.Consumer
}
requiredModules[targetModule] = aggregateConsumers(consumerStorage...)
}
sort.Slice(store, func(i, j int) bool {
return store[i].pathPrefix > store[j].pathPrefix
})
return requiredModules, nil
}
func makeProxy(protocol string, skipAuth, skipExistCheck bool) (Proxy, error) {
var proxy Proxy
switch protocol {
case httpProtocol:
proxy = http.NewProxy(skipAuth, skipExistCheck)
case grpcProtocol:
proxy = grpc.NewProxy(skipAuth, skipExistCheck)
case healthCheckProtocol:
proxy = health_check.NewProxy(skipAuth, skipExistCheck)
case websocketProtocol:
proxy = websocket.NewProxy(skipAuth, skipExistCheck)
default:
return nil, errors.Errorf("unknown protocol '%s'", protocol)
}
return proxy, nil
}
func Find(path string) (Proxy, string) {
for _, item := range store {
if strings.HasPrefix(path, item.pathPrefix) {
return item.proxy, getPathWithoutPrefix(path, item.pathPrefix)
}
}
return nil, ""
}
func Close() {
for _, p := range store {
p.proxy.Close()
}
}
func getPathWithoutPrefix(path, prefix string) string {
s := strings.TrimPrefix(path, prefix)
if len(s) > 0 && s[0] == '/' {
return s[1:]
}
return s
}
func aggregateConsumers(consumers ...func([]structure.AddressConfiguration) bool) func([]structure.AddressConfiguration) bool {
return func(list []structure.AddressConfiguration) bool {
for _, consumer := range consumers {
consumer(list)
}
return true
}
}
-34
View File
@@ -1,34 +0,0 @@
package proxy
import (
"testing"
)
func Test_getPathWithoutPrefix(t *testing.T) {
type args struct {
path string
prefix string
}
tests := []struct {
name string
args args
want string
}{
{name: "#1", args: args{
path: "/api/some/11/22",
prefix: "/api/some",
}, want: "11/22"},
{name: "#2", args: args{
path: "/api/service/group/method",
prefix: "/api",
}, want: "service/group/method"},
}
for _, test := range tests {
tt := test
t.Run(tt.name, func(t *testing.T) {
if got := getPathWithoutPrefix(tt.args.path, tt.args.prefix); got != tt.want {
t.Errorf("getPathWithoutPrefix() = %v, want %v", got, tt.want)
}
})
}
}
-28
View File
@@ -1,28 +0,0 @@
package websocket
import (
"github.com/integration-system/isp-lib/v2/structure"
"sync"
)
type RoundRobinAddrs struct {
mu *sync.Mutex
addrs []structure.AddressConfiguration
index int
}
func (u *RoundRobinAddrs) Get() structure.AddressConfiguration {
u.mu.Lock()
u.index = (u.index + 1) % len(u.addrs)
addr := u.addrs[u.index]
u.mu.Unlock()
return addr
}
func NewRoundRobinAddrs(addrs []structure.AddressConfiguration) *RoundRobinAddrs {
return &RoundRobinAddrs{
addrs: addrs,
index: -1,
mu: new(sync.Mutex),
}
}
-29
View File
@@ -1,29 +0,0 @@
package utils
import (
"encoding/json"
"github.com/integration-system/isp-lib/v2/http"
"github.com/integration-system/isp-lib/v2/structure"
"github.com/valyala/fasthttp"
"google.golang.org/grpc/codes"
)
var (
JsonContentType = []byte("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.SetContentTypeBytes(JsonContentType)
ctx.SetStatusCode(http.CodeToHttpStatus(code))
msg, _ := json.Marshal(structureError)
ctx.Response.Header.SetContentLength(len(msg))
_, _ = ctx.Write(msg)
}