This commit is contained in:
DeniskaRediska committed 2019-10-24 14:37:22 +03:00
1 parent f3934e038e
commit 4fdf7c0ca2
19 files changed
+457 -379

No files matched your search

+8 -4
View File
@@ -6,9 +6,12 @@ import (
log "github.com/integration-system/isp-log"
"github.com/valyala/fasthttp"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"isp-gate-service/conf"
"isp-gate-service/log_code"
"isp-gate-service/proxy/grpc/handlers"
"isp-gate-service/service"
"isp-gate-service/utils"
"net/http"
"time"
)
@@ -31,16 +34,17 @@ func NewProxy() *grpcProxy {
}
func (p *grpcProxy) ProxyRequest(ctx *fasthttp.RequestCtx) {
if p.client == nil {
log.Error(log_code.ErrorClientGrpc, "client undefined")
if p.client.InternalGrpcClient == nil {
msg := "client undefined"
log.Error(log_code.ErrorClientGrpc, msg)
utils.SendError(msg, codes.Internal, nil, ctx)
return
}
currentTime := time.Now()
uri := string(ctx.RequestURI())
SetHandler(ctx).Complete(ctx, uri, p.client)
handlers.Handler.Get(ctx).Complete(ctx, uri, p.client)
executionTime := time.Since(currentTime) / 1e6
service.Metrics.UpdateStatusCounter(ctx.Response.StatusCode())
+98 -27
View File
@@ -1,17 +1,27 @@
package handlers
import (
"github.com/golang/protobuf/proto"
structpb "github.com/golang/protobuf/ptypes/struct"
"github.com/integration-system/isp-lib/backend"
"github.com/integration-system/isp-lib/config"
http2 "github.com/integration-system/isp-lib/http"
isp "github.com/integration-system/isp-lib/proto/stubs"
s "github.com/integration-system/isp-lib/streaming"
"github.com/integration-system/isp-lib/structure"
"github.com/integration-system/isp-lib/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"
"io"
"isp-gate-service/conf"
"isp-gate-service/log_code"
"isp-gate-service/proxy/grpc/utils"
"mime/multipart"
u "isp-gate-service/utils"
"net/http"
"strings"
"time"
)
@@ -25,6 +35,79 @@ const (
errorMsgInvalidArg = "Not able to read request body"
)
var (
json = jsoniter.ConfigFastest
)
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
}
}
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.WarnRequestHandler, err)
}
func openStream(headers *fasthttp.RequestHeader, method string, timeout time.Duration, client *backend.RxGrpcClient) (
isp.BackendService_RequestStreamClient, context.CancelFunc, error) {
@@ -32,7 +115,7 @@ func openStream(headers *fasthttp.RequestHeader, method string, timeout time.Dur
if err != nil {
return nil, nil, err
}
md, _ := utils.MakeMetadata(headers, method)
md, _ := makeMetadata(headers, method)
ctx := metadata.NewOutgoingContext(context.Background(), md)
ctx, cancel := context.WithTimeout(ctx, timeout)
stream, err := cli.RequestStream(ctx)
@@ -42,35 +125,23 @@ func openStream(headers *fasthttp.RequestHeader, method string, timeout time.Dur
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
}
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)))
}
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
})
return md, method
}
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)
logHandlerError(log_code.TypeData.GetFile, "", err)
u.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, ctx)
return false, false
}
return true, true
@@ -1,34 +1,39 @@
package grpc
package handlers
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"
"isp-gate-service/utils"
"mime"
)
type Handler interface {
Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient)
}
var Handler handlerHelper
func SetHandler(ctx *fasthttp.RequestCtx) Handler {
isMultipart := isMultipart(ctx)
type (
handlerHelper struct{}
handler interface {
Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient)
}
)
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.SetContentType(utils.JsonContentType)
return handlers.SendMultipartData
return sendMultipartData
} else if isExpectFile {
return handlers.GetFile
return getFile
} else {
ctx.Response.Header.SetContentType(utils.JsonContentType)
return handlers.Json
return handleJson
}
}
func isMultipart(ctx *fasthttp.RequestCtx) bool {
func (h handlerHelper) isMultipart(ctx *fasthttp.RequestCtx) bool {
if !ctx.IsPost() {
return false
}
+35 -12
View File
@@ -7,26 +7,27 @@ import (
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/pkg/errors"
"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"
"isp-gate-service/utils"
"strconv"
)
var GetFile getFile
var getFile getFileDesc
type getFile struct{}
type getFileDesc struct{}
func (getFile) Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) {
func (g getFileDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) {
cfg := config.GetRemote().(*conf.RemoteConfig)
timeout := cfg.GetStreamInvokeTimeout()
req, err := utils.ReadJsonBody(ctx)
req, err := g.readJsonBody(ctx)
if err != nil {
utils.LogRequestHandlerError(log_code.TypeData.GetFile, method, err)
logHandlerError(log_code.TypeData.GetFile, method, err)
utils.SendError(err.Error(), codes.InvalidArgument, nil, ctx)
return
}
@@ -38,7 +39,7 @@ func (getFile) Complete(ctx *fasthttp.RequestCtx, method string, client *backend
}
}()
if err != nil {
utils.LogRequestHandlerError(log_code.TypeData.GetFile, method, err)
logHandlerError(log_code.TypeData.GetFile, method, err)
utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, ctx)
return
}
@@ -47,7 +48,7 @@ func (getFile) Complete(ctx *fasthttp.RequestCtx, method string, client *backend
value := u.ConvertInterfaceToGrpcStruct(req)
err := stream.Send(backend.WrapBody(value))
if err != nil {
utils.LogRequestHandlerError(log_code.TypeData.GetFile, method, err)
logHandlerError(log_code.TypeData.GetFile, method, err)
utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, ctx)
return
}
@@ -55,7 +56,7 @@ func (getFile) Complete(ctx *fasthttp.RequestCtx, method string, client *backend
msg, err := stream.Recv()
if err != nil {
bytes, status, err := utils.GetResponse(nil, err)
bytes, status, err := getResponse(nil, err)
if err == nil {
ctx.SetStatusCode(status)
ctx.SetBody(bytes)
@@ -65,7 +66,7 @@ func (getFile) Complete(ctx *fasthttp.RequestCtx, method string, client *backend
bf := s.BeginFile{}
err = bf.FromMessage(msg)
if err != nil {
bytes, status, err := utils.GetResponse(nil, err)
bytes, status, err := getResponse(nil, err)
if err == nil {
ctx.SetStatusCode(status)
ctx.SetBody(bytes)
@@ -87,7 +88,7 @@ func (getFile) Complete(ctx *fasthttp.RequestCtx, method string, client *backend
break
}
if err != nil {
utils.LogRequestHandlerError(log_code.TypeData.GetFile, method, err)
logHandlerError(log_code.TypeData.GetFile, method, err)
break
}
bytes := msg.GetBytesBody()
@@ -100,8 +101,30 @@ func (getFile) Complete(ctx *fasthttp.RequestCtx, method string, client *backend
}
_, err = ctx.Write(bytes)
if err != nil {
utils.LogRequestHandlerError(log_code.TypeData.GetFile, method, err)
logHandlerError(log_code.TypeData.GetFile, method, err)
break
}
}
}
func (getFileDesc) 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
}
+8 -8
View File
@@ -12,16 +12,16 @@ import (
"isp-gate-service/conf"
"isp-gate-service/journal"
"isp-gate-service/log_code"
"isp-gate-service/proxy/grpc/utils"
"isp-gate-service/service"
"isp-gate-service/utils"
"time"
)
var Json handleJson
var handleJson handleJsonDesc
type handleJson struct{}
type handleJsonDesc struct{}
func (p handleJson) Complete(c *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) {
func (p handleJsonDesc) Complete(c *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) {
//body, err := utils.ReadJsonBody(c)
body := c.Request.Body()
/*if err != nil {
@@ -30,7 +30,7 @@ func (p handleJson) Complete(c *fasthttp.RequestCtx, method string, client *back
return
}*/
md, methodName := utils.MakeMetadata(&c.Request.Header, method)
md, methodName := makeMetadata(&c.Request.Header, method)
ctx := metadata.NewOutgoingContext(context.Background(), md)
cfg := config.GetRemote().(*conf.RemoteConfig)
ctx, cancel := context.WithTimeout(ctx, cfg.GetSyncInvokeTimeout())
@@ -38,7 +38,7 @@ func (p handleJson) Complete(c *fasthttp.RequestCtx, method string, client *back
cli, err := client.Conn()
if err != nil {
utils.LogRequestHandlerError(log_code.TypeData.JsonContent, methodName, err)
logHandlerError(log_code.TypeData.JsonContent, methodName, err)
utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, c)
return
}
@@ -53,7 +53,7 @@ func (p handleJson) Complete(c *fasthttp.RequestCtx, method string, client *back
)
service.Metrics.UpdateRouterResponseTime(time.Since(currentTime) / 1e6)
if data, status, err := utils.GetResponse(response, invokerErr); err == nil {
if data, status, err := getResponse(response, invokerErr); err == nil {
c.SetStatusCode(status)
_, _ = c.Write(data)
if cfg.Journal.Enable && service.JournalMethodsMatcher.Match(methodName) {
@@ -68,7 +68,7 @@ func (p handleJson) Complete(c *fasthttp.RequestCtx, method string, client *back
}
}
} else {
utils.LogRequestHandlerError(log_code.TypeData.JsonContent, methodName, err)
logHandlerError(log_code.TypeData.JsonContent, methodName, err)
utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, c)
}
}
@@ -3,20 +3,22 @@ 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"
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"
"isp-gate-service/utils"
"mime/multipart"
"strings"
)
var SendMultipartData sendMultipartData
var sendMultipartData sendMultipartDataDesc
type sendMultipartData struct{}
type sendMultipartDataDesc struct{}
func (sendMultipartData) Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) {
func (h sendMultipartDataDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) {
cfg := config.GetRemote().(*conf.RemoteConfig)
timeout := cfg.GetStreamInvokeTimeout()
bufferSize := cfg.GetTransferFileBufferSize()
@@ -28,7 +30,7 @@ func (sendMultipartData) Complete(ctx *fasthttp.RequestCtx, method string, clien
}
}()
if err != nil {
utils.LogRequestHandlerError(log_code.TypeData.SendMultipart, method, err)
logHandlerError(log_code.TypeData.SendMultipart, method, err)
utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, ctx)
return
}
@@ -41,7 +43,7 @@ func (sendMultipartData) Complete(ctx *fasthttp.RequestCtx, method string, clien
}()
if err != nil {
utils.LogRequestHandlerError(log_code.TypeData.SendMultipart, method, err)
logHandlerError(log_code.TypeData.SendMultipart, method, err)
utils.SendError(errorMsgInvalidArg, codes.InvalidArgument, []interface{}{err.Error()}, ctx)
return
}
@@ -83,9 +85,9 @@ func (sendMultipartData) Complete(ctx *fasthttp.RequestCtx, method string, clien
if ok, eof = checkError(err, ctx); !ok || eof {
break
}
if ok, eof = transferFile(f, stream, buffer, ctx); ok {
if ok, eof = h.transferFile(f, stream, buffer, ctx); ok {
msg, err := stream.Recv()
v, _, err := utils.GetResponse(msg, err)
v, _, err := getResponse(msg, err)
if err == nil {
response = append(response, string(v))
}
@@ -99,14 +101,38 @@ func (sendMultipartData) Complete(ctx *fasthttp.RequestCtx, method string, clien
err = stream.CloseSend()
if err != nil {
utils.LogRequestHandlerError(log_code.TypeData.SendMultipart, method, err)
logHandlerError(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)
logHandlerError(log_code.TypeData.SendMultipart, method, err)
}
}
}
func (sendMultipartDataDesc) 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
}
-149
View File
@@ -1,149 +0,0 @@
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
}
}
+5 -1
View File
@@ -4,7 +4,9 @@ import (
"github.com/integration-system/isp-lib/structure"
log "github.com/integration-system/isp-log"
"github.com/valyala/fasthttp"
"google.golang.org/grpc/codes"
"isp-gate-service/log_code"
"isp-gate-service/utils"
"net"
"strings"
)
@@ -31,7 +33,9 @@ func (p *httpProxy) Consumer(addressList []structure.AddressConfiguration) bool
func (p *httpProxy) ProxyRequest(ctx *fasthttp.RequestCtx) {
if p.client == nil {
log.Error(log_code.ErrorClientHttp, "client undefined")
msg := "client undefined"
log.Error(log_code.ErrorClientHttp, msg)
utils.SendError(msg, codes.Internal, nil, ctx)
return
}