delete proxy functional from gate, locations replaced with router config

This commit is contained in:
dmitrijgulacenkov committed 2020-10-12 14:43:05 +03:00
1 parent c1410dfef1
commit d4c76d33ef
16 files changed
+38 -1026

No files matched your search

+5 -7
View File
@@ -9,10 +9,8 @@ httpInnerAddress:
port: 9003
moduleName: isp-gate
instanceUuid: 9d89354b-c728-4b48-b002-a7d3b229f151
locations:
- pathPrefix: /api
protocol: http
targetModule: router
- pathPrefix: /mdm
protocol: http
targetModule: mdm-api
routerConfig:
routerModuleName: router
pathPrefix: /api
skipAuth: false
skipExistCheck: false
+6 -24
View File
@@ -11,31 +11,13 @@ type (
ConfigServiceAddress structure.AddressConfiguration `valid:"required~Required"`
HttpOuterAddress structure.AddressConfiguration `valid:"required~Required" json:"httpOuterAddress"`
HttpInnerAddress structure.AddressConfiguration `valid:"required~Required" json:"httpInnerAddress"`
Locations []Location
RouterConfig RouterConfig `valid:"required~Required" json:"routerConfig"`
}
Location struct {
SkipAuth bool
SkipExistCheck bool
PathPrefix string `valid:"required~Required"`
Protocol string `valid:"required~Required"`
TargetModule string `valid:"required~Required"`
RouterConfig struct {
RouterModuleName string `valid:"required~Required"`
PathPrefix string `valid:"required~Required"`
SkipAuth bool
SkipExistCheck bool
}
)
func GetLocationsByTargetModule(locations []Location) map[string][]Location {
requiredModules := make(map[string][]Location)
for _, location := range locations {
if location.TargetModule == "" {
continue
}
if loc, ok := requiredModules[location.TargetModule]; ok {
requiredModules[location.TargetModule] = append(loc, location)
} else {
requiredModules[location.TargetModule] = []Location{location}
}
}
return requiredModules
}
+2 -2
View File
@@ -67,7 +67,8 @@ func CompleteRequest(ctx *fasthttp.RequestCtx) {
func (handlerHelper) AuthenticateAccountingProxy(ctx *fasthttp.RequestCtx) (string, domain.ProxyResponse) {
initialPath := string(ctx.Path())
p, path := proxy.Find(initialPath)
p := proxy.RoutingProxy
path := proxy.GetPathWithoutApiPrefix(initialPath)
if p == nil {
msg := fmt.Sprintf("unknown proxy for '%s'", initialPath)
utils.WriteError(ctx, msg, codes.NotFound, nil)
@@ -96,7 +97,6 @@ func (handlerHelper) AuthenticateAccountingProxy(ctx *fasthttp.RequestCtx) (stri
utils.WriteError(ctx, message, status, details)
return path, domain.Create().SetError(err)
}
if !accounting.AcceptRequest(applicationId, path) {
err := errAccounting
utils.WriteError(ctx, "too many requests", codes.ResourceExhausted, nil)
+6 -13
View File
@@ -2,12 +2,13 @@ package main
import (
"context"
"os"
"github.com/integration-system/isp-lib/v2/bootstrap"
"github.com/integration-system/isp-lib/v2/config"
"github.com/integration-system/isp-lib/v2/config/schema"
"github.com/integration-system/isp-lib/v2/metric"
"github.com/integration-system/isp-lib/v2/structure"
"github.com/integration-system/isp-log/stdcodes"
"isp-gate-service/accounting"
"isp-gate-service/authenticate"
"isp-gate-service/conf"
@@ -19,8 +20,6 @@ import (
"isp-gate-service/server"
"isp-gate-service/service"
"isp-gate-service/service/matcher"
"log"
"os"
)
var (
@@ -38,17 +37,11 @@ func main() {
SocketConfiguration(socketConfiguration).
RequireRoutes(handleRouteUpdate).
RequireModule("journal", invoker.Journal.ReceiveServiceAddressList, false).
SubscribeBroadcastEvent(bootstrap.ListenRestartEvent())
SubscribeBroadcastEvent(bootstrap.ListenRestartEvent()).OnShutdown(onShutdown)
requiredModules, err := proxy.InitProxies(cfg.Locations)
if err != nil {
log.Fatal(stdcodes.ModuleInvalidLocalConfig, err)
}
for module, consumer := range requiredModules {
bs.RequireModule(module, consumer, false)
}
bs.RequireModule(cfg.ModuleName, accounting.NewConnectionConsumer, false).
OnShutdown(onShutdown).
proxy.ApiPathPrefix = cfg.RouterConfig.PathPrefix
proxyConsumer := proxy.InitRoutingProxy(cfg.RouterConfig.SkipAuth, cfg.RouterConfig.SkipExistCheck)
bs.RequireModule(cfg.RouterConfig.RouterModuleName, proxyConsumer, true).
OnRemoteConfigReceive(onRemoteConfigReceive).
Run()
}
-50
View File
@@ -1,50 +0,0 @@
package grpc
import (
"github.com/integration-system/isp-lib/v2/backend"
"github.com/integration-system/isp-lib/v2/structure"
"github.com/valyala/fasthttp"
"google.golang.org/grpc"
"isp-gate-service/conf"
"isp-gate-service/domain"
"isp-gate-service/proxy/grpc/handlers"
)
type grpcProxy struct {
client *backend.RxGrpcClient
skipAuth bool
skipExistCheck bool
}
func NewProxy(skipAuth, skipExistCheck bool) *grpcProxy {
return &grpcProxy{
client: backend.NewRxGrpcClient(
backend.WithDialOptions(
grpc.WithInsecure(),
grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(int(conf.DefaultMaxResponseBodySize))),
grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(int(conf.DefaultMaxResponseBodySize))),
)),
skipAuth: skipAuth,
skipExistCheck: skipExistCheck,
}
}
func (p *grpcProxy) ProxyRequest(ctx *fasthttp.RequestCtx, path string) domain.ProxyResponse {
return handlers.Handler.Get(ctx).Complete(ctx, path, p.client)
}
func (p *grpcProxy) Consumer(addr []structure.AddressConfiguration) bool {
return p.client.ReceiveAddressList(addr)
}
func (p *grpcProxy) SkipAuth() bool {
return p.skipAuth
}
func (p *grpcProxy) SkipExistCheck() bool {
return p.skipExistCheck
}
func (p *grpcProxy) Close() {
_ = p.client.Close()
}
-163
View File
@@ -1,163 +0,0 @@
package handlers
import (
"bytes"
"io"
"net/http"
"time"
"github.com/golang/protobuf/proto"
structpb "github.com/golang/protobuf/ptypes/struct"
"github.com/integration-system/isp-lib/v2/backend"
"github.com/integration-system/isp-lib/v2/config"
http2 "github.com/integration-system/isp-lib/v2/http"
"github.com/integration-system/isp-lib/v2/isp"
"github.com/integration-system/isp-lib/v2/structure"
"github.com/integration-system/isp-lib/v2/utils"
log "github.com/integration-system/isp-log"
jsoniter "github.com/json-iterator/go"
"github.com/valyala/fasthttp"
"golang.org/x/net/context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"isp-gate-service/conf"
"isp-gate-service/domain"
"isp-gate-service/log_code"
utils2 "isp-gate-service/utils"
)
const (
headerKeyContentDisposition = "Content-Disposition"
headerKeyContentType = "Content-Type"
headerKeyContentLength = "Content-Length"
headerKeyTransferEncoding = "Transfer-Encoding"
errorMsgInternal = "Internal server error"
errorMsgInvalidArg = "Not able to read request body"
)
var json = jsoniter.ConfigFastest
func convertError(err error) ([]byte, int) {
s, ok := status.FromError(err)
if !ok {
return []byte(utils.ServiceError), http.StatusServiceUnavailable
}
cfg := config.GetRemote().(*conf.RemoteConfig).GrpcSetting
if cfg.EnableOriginalProtoErrors {
body, err := proto.Marshal(s.Proto())
if err != nil {
return []byte(utils.ServiceError), http.StatusServiceUnavailable
}
return body, http2.CodeToHttpStatus(s.Code())
}
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}
}
errorData, err := json.Marshal(respBody)
if err != nil {
log.Warn(log_code.WarnConvertErrorDataMarshalResponse, err)
return []byte(utils.ServiceError), http.StatusServiceUnavailable
}
return errorData, http2.CodeToHttpStatus(s.Code())
}
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 logHandlerError(typeData, method string, err error) {
log.WithMetadata(map[string]interface{}{
log_code.MdTypeData: typeData,
log_code.MdMethod: method,
}).Warn(log_code.WarnProxyGrpcHandler, err)
}
func openStream(headers *fasthttp.RequestHeader, method string, timeout time.Duration, client *backend.RxGrpcClient) (
isp.BackendService_RequestStreamClient, context.CancelFunc, error) {
cli := client.Conn()
md, _ := 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 makeMetadata(r *fasthttp.RequestHeader, method string) (metadata.MD, string) {
md := make(metadata.MD, 5)
md[utils.ProxyMethodNameHeader] = []string{method}
r.VisitAll(func(key, v []byte) {
lowerHeader := bytes.ToLower(key)
if len(v) > 0 && bytes.HasPrefix(lowerHeader, []byte("x-")) {
md[string(lowerHeader)] = []string{string(v)}
}
})
return md, method
}
func checkError(err error, ctx *fasthttp.RequestCtx, method string) (bool, bool, domain.ProxyResponse) {
var (
ok = true
eof = false
resp = domain.ProxyResponse{}
msg = errorMsgInternal
code = codes.Internal
details []interface{} = nil
)
if err != nil {
if err != io.EOF {
s, itStatus := status.FromError(err)
if itStatus {
msg = s.Message()
code = s.Code()
details = s.Details()
}
logHandlerError(log_code.TypeData.GetFile, method, err)
utils2.WriteError(ctx, msg, code, details)
resp = domain.Create().SetError(err)
ok, eof = false, false
} else {
ok, eof = true, true
}
}
return ok, eof, resp
}
-51
View File
@@ -1,51 +0,0 @@
package handlers
import (
"github.com/integration-system/isp-lib/v2/backend"
u "github.com/integration-system/isp-lib/v2/utils"
"github.com/valyala/fasthttp"
"isp-gate-service/domain"
"isp-gate-service/utils"
"mime"
)
var Handler handlerHelper
type (
handlerHelper struct{}
handler interface {
Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) domain.ProxyResponse
}
)
func (h handlerHelper) Get(ctx *fasthttp.RequestCtx) handler {
isMultipart := h.isMultipart(ctx)
isExpectFile := string(ctx.Request.Header.Peek(u.ExpectFileHeader)) == "true"
if isMultipart {
ctx.Response.Header.SetContentTypeBytes(utils.JsonContentType)
return sendMultipartData
}
if isExpectFile {
return getFile
}
ctx.Response.Header.SetContentTypeBytes(utils.JsonContentType)
return handleJson
}
func (h handlerHelper) 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"]
return ok
}
-139
View File
@@ -1,139 +0,0 @@
package handlers
import (
"fmt"
"github.com/integration-system/isp-lib/v2/backend"
"github.com/integration-system/isp-lib/v2/config"
"github.com/integration-system/isp-lib/v2/isp"
s "github.com/integration-system/isp-lib/v2/streaming"
u "github.com/integration-system/isp-lib/v2/utils"
log "github.com/integration-system/isp-log"
"github.com/pkg/errors"
"github.com/valyala/fasthttp"
"google.golang.org/grpc/codes"
"io"
"isp-gate-service/conf"
"isp-gate-service/domain"
"isp-gate-service/log_code"
"isp-gate-service/utils"
"strconv"
)
var (
errInvalidJson = errors.New("invalid json format. Expected object or array")
getFile getFileDesc
)
type getFileDesc struct{}
func (g getFileDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) domain.ProxyResponse {
req, err := g.readJsonBody(ctx)
if err != nil {
return g.formError(ctx, err, method, err.Error(), codes.InvalidArgument)
}
timeout := config.GetRemote().(*conf.RemoteConfig).GrpcSetting.GetStreamInvokeTimeout()
stream, cancel, err := openStream(&ctx.Request.Header, method, timeout, client)
defer func() {
if cancel != nil {
cancel()
}
}()
if err != nil {
return g.formError(ctx, err, method, errorMsgInternal, codes.Internal)
}
if req != nil {
value := u.ConvertInterfaceToGrpcStruct(req)
err := stream.Send(backend.WrapBody(value))
if err != nil {
return g.formError(ctx, err, method, errorMsgInternal, codes.Internal)
}
}
msg, err := stream.Recv()
if err != nil {
response, status, err := getResponse(nil, err)
if err == nil {
ctx.SetStatusCode(status)
ctx.SetBody(response)
}
return domain.Create().SetError(err)
}
bf := s.BeginFile{}
err = bf.FromMessage(msg)
if err != nil {
response, status, err := getResponse(nil, err)
if err == nil {
ctx.SetStatusCode(status)
ctx.SetBody(response)
}
return domain.Create().SetError(err)
}
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")
}
err = g.write(ctx, stream, method)
return domain.Create().SetError(err)
}
//nolint
func (getFileDesc) write(ctx *fasthttp.RequestCtx, stream isp.BackendService_RequestStreamClient, method string) error {
for {
msg, err := stream.Recv()
if s.IsEndOfFile(msg) || err == io.EOF {
return nil
}
if err != nil {
logHandlerError(log_code.TypeData.GetFile, method, err)
return err
}
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.WarnProxyGrpcHandler, "Method %s. Expected bytes array", method)
return nil
}
_, err = ctx.Write(bytes)
if err != nil {
logHandlerError(log_code.TypeData.GetFile, method, err)
return err
}
}
}
func (getFileDesc) readJsonBody(ctx *fasthttp.RequestCtx) (interface{}, error) {
requestBody := ctx.Request.Body()
var body interface{}
if len(requestBody) == 0 {
requestBody = []byte("{}")
}
switch requestBody[0] {
case '{':
body = make(map[string]interface{})
case '[':
body = make([]interface{}, 0)
default:
return nil, errInvalidJson
}
err := json.Unmarshal(requestBody, &body)
if err != nil {
return nil, err
}
return body, err
}
func (getFileDesc) formError(ctx *fasthttp.RequestCtx, err error, method, msg string, code codes.Code) domain.ProxyResponse {
logHandlerError(log_code.TypeData.GetFile, method, err)
utils.WriteError(ctx, msg, code, nil)
return domain.Create().SetError(err)
}
-50
View File
@@ -1,50 +0,0 @@
package handlers
import (
"github.com/integration-system/isp-lib/v2/backend"
"github.com/integration-system/isp-lib/v2/config"
"github.com/integration-system/isp-lib/v2/isp"
"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/domain"
"isp-gate-service/log_code"
"isp-gate-service/utils"
)
var handleJson handleJsonDesc
type handleJsonDesc struct{}
func (p handleJsonDesc) Complete(c *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) domain.ProxyResponse {
body := c.Request.Body()
md, methodName := makeMetadata(&c.Request.Header, method)
ctx := metadata.NewOutgoingContext(context.Background(), md)
grpcSetting := config.GetRemote().(*conf.RemoteConfig).GrpcSetting
ctx, cancel := context.WithTimeout(ctx, grpcSetting.GetSyncInvokeTimeout())
defer cancel()
cli := client.Conn()
msg, invokerErr := cli.Request(
ctx,
&isp.Message{
Body: &isp.Message_BytesBody{BytesBody: body},
},
)
if response, status, err := getResponse(msg, invokerErr); err == nil {
c.SetStatusCode(status)
c.SetContentTypeBytes(utils.JsonContentType)
c.Response.Header.SetContentLength(len(response))
_, _ = c.Write(response)
return domain.Create().SetRequestBody(body).SetResponseBody(c.Response.Body()).SetError(invokerErr)
} else {
logHandlerError(log_code.TypeData.JsonContent, methodName, err)
utils.WriteError(c, errorMsgInternal, codes.Internal, nil)
return domain.Create().SetRequestBody(body).SetResponseBody(c.Response.Body()).SetError(err)
}
}
@@ -1,158 +0,0 @@
package handlers
import (
"github.com/integration-system/isp-lib/v2/backend"
"github.com/integration-system/isp-lib/v2/config"
"github.com/integration-system/isp-lib/v2/isp"
s "github.com/integration-system/isp-lib/v2/streaming"
"github.com/valyala/fasthttp"
"google.golang.org/grpc/codes"
"isp-gate-service/conf"
"isp-gate-service/domain"
"isp-gate-service/log_code"
"isp-gate-service/utils"
"mime/multipart"
"strings"
)
var sendMultipartData sendMultipartDataDesc
type sendMultipartDataDesc struct{}
func (h sendMultipartDataDesc) Complete(c *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) domain.ProxyResponse {
cfg := config.GetRemote().(*conf.RemoteConfig).GrpcSetting
timeout := cfg.GetStreamInvokeTimeout()
stream, cancel, err := openStream(&c.Request.Header, method, timeout, client)
defer func() {
if cancel != nil {
cancel()
}
}()
if err != nil {
logHandlerError(log_code.TypeData.SendMultipart, method, err)
utils.WriteError(c, errorMsgInternal, codes.Internal, nil)
return domain.Create().SetError(err)
}
form, err := c.MultipartForm()
defer func() {
if form != nil {
_ = form.RemoveAll()
}
}()
if err != nil {
logHandlerError(log_code.TypeData.SendMultipart, method, err)
utils.WriteError(c, errorMsgInvalidArg, codes.InvalidArgument, nil)
return domain.Create().SetError(err)
}
resp, proxyResp, ok := h.formResponse(c, stream, form, method)
err = stream.CloseSend()
if err != nil {
logHandlerError(log_code.TypeData.SendMultipart, method, err)
}
if ok {
arrayBody := strings.Join(resp, ",")
_, err = c.WriteString("[" + arrayBody + "]")
if err != nil {
logHandlerError(log_code.TypeData.SendMultipart, method, err)
}
}
return proxyResp
}
func (h sendMultipartDataDesc) formResponse(c *fasthttp.RequestCtx, stream isp.BackendService_RequestStreamClient,
form *multipart.Form, method string) ([]string, domain.ProxyResponse, bool) {
formData := make(map[string]interface{}, len(form.Value))
for k, v := range form.Value {
if len(v) > 0 {
formData[k] = v[0]
}
}
var (
resp = make([]string, 0)
buffer = make([]byte, config.GetRemote().(*conf.RemoteConfig).GrpcSetting.GetTransferFileBufferSize())
proxyResp domain.ProxyResponse
ok = true
eof bool
err error
)
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())
ok, eof, proxyResp = checkError(err, c, method)
if !ok || eof {
break
}
f, err := file.Open()
ok, eof, proxyResp = checkError(err, c, method)
if !ok || eof {
break
}
ok, eof, proxyResp = h.transferFile(f, stream, buffer, c, method)
if !ok || eof {
break
}
msg, invokeErr := stream.Recv()
ok, eof, proxyResp = checkError(invokeErr, c, method)
if !ok || eof {
break
}
response, _, err := getResponse(msg, invokeErr)
if err != nil {
ok = false
break
}
resp = append(resp, string(response))
}
return resp, proxyResp, ok
}
func (sendMultipartDataDesc) transferFile(f multipart.File, stream isp.BackendService_RequestStreamClient,
buffer []byte, ctx *fasthttp.RequestCtx, method string) (bool, bool, domain.ProxyResponse) {
var (
ok = true
eof bool
proxyResp domain.ProxyResponse
)
for {
n, err := f.Read(buffer)
if n > 0 {
err = stream.Send(&isp.Message{Body: &isp.Message_BytesBody{BytesBody: buffer[:n]}})
ok, eof, proxyResp = checkError(err, ctx, method)
if !ok || eof {
break
}
}
if err != nil {
ok, eof, proxyResp = checkError(err, ctx, method)
if ok && eof {
err = stream.Send(s.FileEnd())
ok, eof, proxyResp = checkError(err, ctx, method)
}
break
}
}
return ok, eof, proxyResp
}
-38
View File
@@ -1,38 +0,0 @@
package health_check
import (
"github.com/integration-system/isp-lib/v2/structure"
"github.com/valyala/fasthttp"
"isp-gate-service/domain"
)
type healthCheckProxy struct {
skipAuth bool
skipExistCheck bool
}
func NewProxy(skipAuth, skipExistCheck bool) *healthCheckProxy {
return &healthCheckProxy{skipAuth: skipAuth, skipExistCheck: skipExistCheck}
}
func (p *healthCheckProxy) Consumer(addressList []structure.AddressConfiguration) bool {
return true
}
func (p *healthCheckProxy) ProxyRequest(ctx *fasthttp.RequestCtx, path string) domain.ProxyResponse {
ctx.Response.SetBody(ctx.Request.Body())
ctx.Request.SetRequestURI(path)
return domain.Create()
}
func (p *healthCheckProxy) SkipAuth() bool {
return p.skipAuth
}
func (p *healthCheckProxy) SkipExistCheck() bool {
return p.skipExistCheck
}
func (p *healthCheckProxy) Close() {
}
+8 -8
View File
@@ -18,17 +18,17 @@ var (
errNotInitialized = errors.New("http proxy not initialized")
)
type httpProxy struct {
type HttpProxy struct {
client *fasthttp.HostClient
skipAuth bool
skipExistCheck bool
}
func NewProxy(skipAuth, skipExistCheck bool) *httpProxy {
return &httpProxy{client: nil, skipAuth: skipAuth, skipExistCheck: skipExistCheck}
func NewProxy(skipAuth, skipExistCheck bool) *HttpProxy {
return &HttpProxy{client: nil, skipAuth: skipAuth, skipExistCheck: skipExistCheck}
}
func (p *httpProxy) Consumer(addressList []structure.AddressConfiguration) bool {
func (p *HttpProxy) Consumer(addressList []structure.AddressConfiguration) bool {
if len(addressList) == 0 {
p.client = nil
return true
@@ -44,7 +44,7 @@ func (p *httpProxy) Consumer(addressList []structure.AddressConfiguration) bool
return true
}
func (p *httpProxy) ProxyRequest(ctx *fasthttp.RequestCtx, path string) domain.ProxyResponse {
func (p *HttpProxy) ProxyRequest(ctx *fasthttp.RequestCtx, path string) domain.ProxyResponse {
client := p.client
if client == nil {
log.Error(log_code.ErrorClientHttp, errNotInitialized)
@@ -73,14 +73,14 @@ func (p *httpProxy) ProxyRequest(ctx *fasthttp.RequestCtx, path string) domain.P
SetError(err)
}
func (p *httpProxy) SkipAuth() bool {
func (p *HttpProxy) SkipAuth() bool {
return p.skipAuth
}
func (p *httpProxy) SkipExistCheck() bool {
func (p *HttpProxy) SkipExistCheck() bool {
return p.skipExistCheck
}
func (p *httpProxy) Close() {
func (p *HttpProxy) Close() {
p.client = nil
}
+11 -87
View File
@@ -1,29 +1,17 @@
package proxy
import (
"sort"
"strings"
"github.com/integration-system/isp-lib/v2/structure"
"github.com/pkg/errors"
"github.com/valyala/fasthttp"
"isp-gate-service/conf"
"isp-gate-service/domain"
"isp-gate-service/proxy/grpc"
"isp-gate-service/proxy/health_check"
"isp-gate-service/proxy/http"
"isp-gate-service/proxy/websocket"
)
var (
store = make([]storeItem, 0)
)
const (
httpProtocol = "http"
websocketProtocol = "websocket"
grpcProtocol = "grpc"
healthCheckProtocol = "healthсheck"
RoutingProxy *http.HttpProxy
ApiPathPrefix string
)
type (
@@ -34,88 +22,24 @@ type (
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 InitRoutingProxy(skipAuth bool, skipExistCheck bool) func(list []structure.AddressConfiguration) bool {
RoutingProxy = http.NewProxy(skipAuth, skipExistCheck)
return func(list []structure.AddressConfiguration) bool {
RoutingProxy.Consumer(list)
return true
}
}
func getPathWithoutPrefix(path, prefix string) string {
s := strings.TrimPrefix(path, prefix)
func GetPathWithoutApiPrefix(initialPath string) string {
s := strings.TrimPrefix(initialPath, ApiPathPrefix)
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
}
func Close() {
RoutingProxy.Close()
}
-34
View File
@@ -1,34 +0,0 @@
package proxy //nolint
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),
}
}
-174
View File
@@ -1,174 +0,0 @@
package websocket
import (
"errors"
"io"
"net"
"net/http"
"net/http/cookiejar"
"net/url"
"sync"
"github.com/fasthttp/websocket"
"github.com/integration-system/isp-lib/v2/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"
)
const (
writeBufSize = 4 << 10
readBufSize = 4 << 10
)
var (
errNoAddresses = errors.New("no available address")
pool = &sync.Pool{New: func() interface{} {
buf := make([]byte, readBufSize)
return &buf
}}
)
// used to filter client request headers
//
var forbiddenDuplicateHeaders = map[string]struct{}{
"Upgrade": {},
"Connection": {},
"Sec-Websocket-Key": {},
"Sec-Websocket-Version": {},
"Sec-Websocket-Extensions": {},
"Sec-Websocket-Protocol": {},
}
var upgrader = websocket.FastHTTPUpgrader{
ReadBufferSize: readBufSize,
WriteBufferSize: writeBufSize,
CheckOrigin: func(ctx *fasthttp.RequestCtx) bool {
return true
},
}
type websocketProxy struct {
addrs *RoundRobinAddrs
skipAuth bool
skipExistCheck bool
}
func NewProxy(skipAuth, skipExistCheck bool) *websocketProxy {
return &websocketProxy{addrs: nil, skipAuth: skipAuth, skipExistCheck: skipExistCheck}
}
func (p *websocketProxy) Consumer(addressList []structure.AddressConfiguration) bool {
if len(addressList) == 0 {
p.addrs = nil
} else {
p.addrs = NewRoundRobinAddrs(addressList)
}
return true
}
func (p *websocketProxy) ProxyRequest(ctx *fasthttp.RequestCtx, path string) domain.ProxyResponse {
addrs := p.addrs
if addrs == nil {
msg := errNoAddresses
log.Error(log_code.ErrorWebsocketProxy, msg)
utils.WriteError(ctx, msg.Error(), codes.Internal, nil)
return domain.Create().
SetRequestBody(ctx.Request.Body()).
SetResponseBody(ctx.Response.Body()).
SetError(errNoAddresses)
}
reqHeaders := fasthttp.RequestHeader{}
ctx.Request.Header.CopyTo(&reqHeaders)
reqHost := string(ctx.Request.URI().Host())
reqScheme := string(ctx.Request.URI().Scheme())
if addr, _, err := net.SplitHostPort(ctx.RemoteAddr().String()); err == nil {
reqHeaders.Add("X-Forwarded-For", addr)
}
err := upgrader.Upgrade(ctx, func(incomingConn *websocket.Conn) {
outgoingDialer := websocket.Dialer{
ReadBufferSize: readBufSize,
WriteBufferSize: writeBufSize,
NetDial: net.Dial,
}
addr := addrs.Get()
uri := ctx.Request.URI()
uri.SetSchemeBytes([]byte("ws"))
uri.SetHost(addr.GetAddress())
uri.SetPath("/" + path)
header := http.Header{}
reqHeaders.VisitAll(func(key, value []byte) {
keyStr := string(key)
if _, forbidden := forbiddenDuplicateHeaders[keyStr]; !forbidden {
header.Add(keyStr, string(value))
}
})
cookie := make([]*http.Cookie, 0)
reqHeaders.VisitAllCookie(func(key, value []byte) {
cookie = append(cookie, &http.Cookie{Domain: reqHost, Name: string(key), Value: string(value)})
})
cookies := &cookiejar.Jar{}
cookies.SetCookies(&url.URL{Host: reqHost, Scheme: reqScheme}, cookie)
outgoingDialer.Jar = cookies
//nolint
outgoingConn, _, err := outgoingDialer.Dial(uri.String(), header)
if err == nil {
go func() {
_ = p.proxyConn(outgoingConn, incomingConn)
}()
_ = p.proxyConn(incomingConn, outgoingConn)
} else {
log.Errorf(log_code.ErrorWebsocketProxy, "unable to connect to service %s: %v", uri.String(), err)
_ = incomingConn.Close()
_ = outgoingConn.Close()
}
})
return domain.Create().SetError(err)
}
func (p *websocketProxy) SkipAuth() bool {
return p.skipAuth
}
func (p *websocketProxy) SkipExistCheck() bool {
return p.skipExistCheck
}
func (p *websocketProxy) Close() {
}
func (p *websocketProxy) proxyConn(from, to *websocket.Conn) error {
buf := pool.Get().(*[]byte)
defer func() {
_ = from.Close()
_ = to.Close()
pool.Put(buf)
}()
for {
msgType, reader, err := from.NextReader()
if err != nil {
return err
}
writer, err := to.NextWriter(msgType)
if err != nil {
return err
}
if _, err := io.CopyBuffer(writer, reader, *buf); err != nil {
return err
}
if err := writer.Close(); err != nil {
return err
}
}
}