Merge branch 'fixes' into 'master'

fix search in locations, fix proxying URI in http

See merge request integration-system/isp-gate-service!9
This commit is contained in:
yan komissarov committed 2020-04-27 12:20:12 +03:00
commit 48cbb5c25d
9 files changed
+165 -115

No files matched your search

+1 -1
View File
@@ -1 +1 @@
2.6.2
2.6.3
+3
View File
@@ -1,3 +1,6 @@
## 2.6.3
* fix search from locations
* fix proxying URI in http and ws
## 2.6.2
* fix panic if journal enable and error logging
* add content-type, content-length header to response
+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() {
+9 -34
View File
@@ -2,13 +2,15 @@ package main
import (
"context"
"github.com/integration-system/isp-log/stdcodes"
"log"
"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"
log "github.com/integration-system/isp-log"
"github.com/integration-system/isp-log/stdcodes"
"isp-gate-service/accounting"
"isp-gate-service/authenticate"
"isp-gate-service/conf"
@@ -20,7 +22,6 @@ import (
"isp-gate-service/server"
"isp-gate-service/service"
"isp-gate-service/service/matcher"
"os"
)
var (
@@ -39,7 +40,10 @@ func main() {
RequireRoutes(handleRouteUpdate).
RequireModule("journal", invoker.Journal.ReceiveServiceAddressList, false)
requiredModules := getRequiredModulesByLocations(cfg.Locations)
requiredModules, err := proxy.InitProxies(cfg.Locations)
if err != nil {
log.Fatal(stdcodes.ModuleInvalidLocalConfig, err)
}
for module, consumer := range requiredModules {
bs.RequireModule(module, consumer, false)
}
@@ -50,7 +54,7 @@ func main() {
Run()
}
func onLocalConfigLoad(cfg *conf.Configuration) {
func onLocalConfigLoad(_ *conf.Configuration) {
}
@@ -107,32 +111,3 @@ func makeDeclaration(localConfig interface{}) bootstrap.ModuleInfo {
Endpoints: []structure.EndpointDescriptor{},
}
}
func getRequiredModulesByLocations(locations []conf.Location) map[string]func([]structure.AddressConfiguration) bool {
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 {
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
}
}
requiredModules[targetModule] = aggregateConsumers(consumerStorage...)
}
return requiredModules
}
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
}
}
+66 -32
View File
@@ -1,6 +1,10 @@
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"
@@ -9,10 +13,11 @@ 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 +34,88 @@ 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)
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)
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)
}
return proxy, nil
}
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 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
}
return ""
}
+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()
}