fix search in locations, fix proxying URI in http

This commit is contained in:
Maxim Merzhanov committed 2020-04-24 19:12:31 +03:00
1 parent f0b8407479
commit 896dd36025
7 files changed
+126 -82

No files matched your search

+5 -4
View File
@@ -2,6 +2,9 @@ package handler
import (
"fmt"
"net/http"
"time"
"github.com/integration-system/isp-lib/v2/config"
log "github.com/integration-system/isp-log"
"github.com/pkg/errors"
@@ -18,8 +21,6 @@ import (
"isp-gate-service/service"
"isp-gate-service/service/matcher"
"isp-gate-service/utils"
"net/http"
"time"
)
const execution = 1e6
@@ -61,9 +62,9 @@ func (handlerHelper) AuthenticateAccountingProxy(ctx *fasthttp.RequestCtx) (stri
p, path := proxy.Find(initialPath)
if p == nil {
msg := fmt.Sprintf("unknown proxy for '%s'", path)
msg := fmt.Sprintf("unknown proxy for '%s'", initialPath)
utils.WriteError(ctx, msg, codes.NotFound, nil)
return path, domain.Create().SetError(errors.New(msg))
return initialPath, domain.Create().SetError(errors.New(msg))
}
if !p.SkipExistCheck() {
+5 -4
View File
@@ -2,6 +2,8 @@ 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"
@@ -20,7 +22,6 @@ import (
"isp-gate-service/server"
"isp-gate-service/service"
"isp-gate-service/service/matcher"
"os"
)
var (
@@ -50,7 +51,7 @@ func main() {
Run()
}
func onLocalConfigLoad(cfg *conf.Configuration) {
func onLocalConfigLoad(_ *conf.Configuration) {
}
@@ -118,12 +119,12 @@ func getRequiredModulesByLocations(locations []conf.Location) map[string]func([]
p, err := proxy.Init(location.Protocol, location.PathPrefix, location.SkipAuth, location.SkipExistCheck)
if err != nil {
log.Fatal(stdcodes.ModuleInvalidLocalConfig, err)
} else {
consumerStorage[i] = p.Consumer
}
consumerStorage[i] = p.Consumer
}
requiredModules[targetModule] = aggregateConsumers(consumerStorage...)
}
proxy.PostInit()
return requiredModules
}
+35 -30
View File
@@ -1,6 +1,9 @@
package proxy
import (
"sort"
"strings"
"github.com/integration-system/isp-lib/v2/structure"
"github.com/pkg/errors"
"github.com/valyala/fasthttp"
@@ -9,10 +12,9 @@ import (
"isp-gate-service/proxy/health_check"
"isp-gate-service/proxy/http"
"isp-gate-service/proxy/websocket"
"strings"
)
var store = make(map[string]Proxy)
var store = make([]storeItem, 0)
const (
httpProtocol = "http"
@@ -29,59 +31,62 @@ type (
SkipExistCheck() bool
Close()
}
storeItem struct {
pathPrefix string
proxy Proxy
}
)
func Init(protocol, pathPrefix string, skipAuth, skipExistCheck bool) (Proxy, error) {
if pathPrefix[0] != '/' {
return nil, errors.Errorf("path must begin with '/' in path '%s'", pathPrefix)
}
var proxy Proxy
switch protocol {
case httpProtocol:
proxy := http.NewProxy(skipAuth, skipExistCheck)
store[pathPrefix] = proxy
return proxy, nil
proxy = http.NewProxy(skipAuth, skipExistCheck)
case grpcProtocol:
proxy := grpc.NewProxy(skipAuth, skipExistCheck)
store[pathPrefix] = proxy
return proxy, nil
proxy = grpc.NewProxy(skipAuth, skipExistCheck)
case healthCheckProtocol:
proxy := health_check.NewProxy(skipAuth, skipExistCheck)
store[pathPrefix] = proxy
return proxy, nil
proxy = health_check.NewProxy(skipAuth, skipExistCheck)
case websocketProtocol:
proxy := websocket.NewProxy(skipAuth, skipExistCheck)
store[pathPrefix] = proxy
return proxy, nil
proxy = websocket.NewProxy(skipAuth, skipExistCheck)
default:
return nil, errors.Errorf("unknown protocol '%s'", protocol)
}
store = append(store, storeItem{
pathPrefix: pathPrefix,
proxy: proxy,
})
return proxy, nil
}
func PostInit() {
sort.Slice(store, func(i, j int) bool {
return store[i].pathPrefix > store[j].pathPrefix
})
}
func Find(path string) (Proxy, string) {
for pathPrefix, proxy := range store {
if strings.HasPrefix(path, pathPrefix) {
return proxy, getPathWithoutPrefix(path)
for _, item := range store {
if strings.HasPrefix(path, item.pathPrefix) {
return item.proxy, getPathWithoutPrefix(path, item.pathPrefix)
}
}
return nil, getPathWithoutPrefix(path)
return nil, ""
}
func Close() {
for _, p := range store {
p.Close()
p.proxy.Close()
}
}
func getPathWithoutPrefix(path string) string {
firstFound := false
for i, value := range path {
if value == '/' {
if firstFound {
return path[i+1:]
} else {
firstFound = true
}
}
func getPathWithoutPrefix(path, prefix string) string {
s := strings.TrimPrefix(path, prefix)
if len(s) > 0 && s[0] == '/' {
return s[1:]
}
return ""
return s
}
+33
View File
@@ -0,0 +1,33 @@
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 _, tt := range tests {
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)
}
})
}
}
+38 -38
View File
@@ -41,48 +41,48 @@ var json = jsoniter.ConfigFastest
func convertError(err error) ([]byte, int) {
s, ok := status.FromError(err)
if ok {
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 !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 {
log.Warn(log_code.WarnConvertErrorDataMarshalResponse, err)
return []byte(utils.ServiceError), http.StatusServiceUnavailable
}
return errorData, http2.CodeToHttpStatus(s.Code())
return body, http2.CodeToHttpStatus(s.Code())
}
return []byte(utils.ServiceError), http.StatusServiceUnavailable
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) {
+4 -3
View File
@@ -2,6 +2,9 @@ package http
import (
"errors"
"net"
"strings"
"github.com/integration-system/isp-lib/v2/structure"
log "github.com/integration-system/isp-log"
"github.com/valyala/fasthttp"
@@ -9,8 +12,6 @@ import (
"isp-gate-service/domain"
"isp-gate-service/log_code"
"isp-gate-service/utils"
"net"
"strings"
)
type httpProxy struct {
@@ -53,7 +54,7 @@ func (p *httpProxy) ProxyRequest(ctx *fasthttp.RequestCtx, path string) domain.P
req := &ctx.Request
res := &ctx.Response
req.SetRequestURI(path)
req.URI().SetPath("/" + path)
if addr, _, err := net.SplitHostPort(ctx.RemoteAddr().String()); err == nil {
req.Header.Add("X-Forwarded-For", addr)
+6 -3
View File
@@ -95,7 +95,10 @@ func (p *websocketProxy) ProxyRequest(ctx *fasthttp.RequestCtx, path string) dom
}
addr := addrs.Get()
urlAddr := "ws://" + addr.GetAddress() + "/" + path
uri := ctx.Request.URI()
uri.SetSchemeBytes([]byte("ws"))
uri.SetHost(addr.GetAddress())
uri.SetPath("/" + path)
header := http.Header{}
reqHeaders.VisitAll(func(key, value []byte) {
@@ -114,14 +117,14 @@ func (p *websocketProxy) ProxyRequest(ctx *fasthttp.RequestCtx, path string) dom
outgoingDialer.Jar = cookies
//nolint
outgoingConn, _, err := outgoingDialer.Dial(urlAddr, header)
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", urlAddr, err)
log.Errorf(log_code.ErrorWebsocketProxy, "unable to connect to service %s: %v", uri.String(), err)
_ = incomingConn.Close()
_ = outgoingConn.Close()
}