add(metrics and journaling)

This commit is contained in:
DeniskaRediska committed 2019-11-07 17:55:27 +03:00
1 parent 2a81e83b2e
commit 3d97f3789a
20 files changed
+331 -172

No files matched your search

+1 -1
View File
@@ -37,7 +37,7 @@ func GetApprove(appId int64) *approve {
return approvingByAppId[appId]
}
func (app *approve) Complete(method string) bool {
func (app *approve) ApproveMethod(method string) bool {
app.mx.Lock()
stateStorage := make([]state.LimitState, 0)
+4 -4
View File
@@ -52,7 +52,7 @@ func TestApprove(t *testing.T) {
expected := true
req := reqExample[0]
for _, path := range req.path {
a.Equal(expected, GetApprove(req.appId).Complete(path))
a.Equal(expected, GetApprove(req.appId).ApproveMethod(path))
expected = !expected
time.Sleep(150 * time.Millisecond)
}
@@ -60,19 +60,19 @@ func TestApprove(t *testing.T) {
//expected == true
req = reqExample[1]
for _, path := range req.path {
a.Equal(expected, GetApprove(req.appId).Complete(path))
a.Equal(expected, GetApprove(req.appId).ApproveMethod(path))
expected = !expected
}
req = reqExample[2]
expectedArray := []bool{true, true, true, true, true, false}
for key, path := range req.path {
a.Equal(expectedArray[key], GetApprove(req.appId).Complete(path))
a.Equal(expectedArray[key], GetApprove(req.appId).ApproveMethod(path))
}
//expected == true
req = reqExample[3]
for _, path := range req.path {
a.Equal(expected, GetApprove(req.appId).Complete(path))
a.Equal(expected, GetApprove(req.appId).ApproveMethod(path))
}
}
+7 -5
View File
@@ -1,21 +1,23 @@
package matcher
import "testing"
import (
"testing"
)
var (
patterns = []string{
"mdm-master/group/method",
"mdm-master/group/*",
"mdm-master/group/",
"mdm-master/group2/method",
"mdm-master/group3/*",
"mdm-master/group3/",
}
cases = []struct {
method string
length int
}{
{method: "mdm-master/group/method", length: 2},
{method: "mdm-master/group/method2", length: 1},
{method: "mdm-master/group2/method3", length: 0},
{method: "mdm-master/group/method2", length: 2},
{method: "mdm-master/group2/method3", length: 1},
{method: "mdm-master/group2/method", length: 1},
{method: "mdm-master/group3/some", length: 1},
{method: "mdm-master/group3/", length: 1},
+4 -2
View File
@@ -1,6 +1,8 @@
package matcher
import "path"
import (
"strings"
)
type runtimeMatcher struct {
patterns []string
@@ -9,7 +11,7 @@ type runtimeMatcher struct {
func (mm runtimeMatcher) Match(method string) []string {
resp := make([]string, 0)
for _, pattern := range mm.patterns {
if matched, _ := path.Match(pattern, method); matched {
if strings.HasPrefix(method, pattern) {
resp = append(resp, pattern)
}
}
+8 -3
View File
@@ -21,6 +21,14 @@ var (
)
func Do(ctx *fasthttp.RequestCtx) (int64, error) {
path := ctx.Path()
uri := strings.Replace(strings.ToLower(string(path)), "/", "", -1)
path = getPathWithoutPrefix(path)
if _, ok := routing.AddressMap[string(path)]; !ok {
return 0, createError(codes.Unimplemented)
}
for _, notExpectedHeader := range verifiableKeyHeaderKeyMap {
ctx.Request.Header.Del(notExpectedHeader)
}
@@ -44,8 +52,6 @@ func Do(ctx *fasthttp.RequestCtx) (int64, error) {
verifiableKeys[verifiableKeyHeaderKeyMap[i]] = value
}
path := ctx.Path()
uri := strings.Replace(strings.ToLower(string(path)), "/", "", -1)
verifiableKeys[utils.DeviceTokenHeader] = string(ctx.Request.Header.Peek(utils.DeviceTokenHeader))
verifiableKeys[utils.UserTokenHeader] = string(ctx.Request.Header.Peek(utils.UserTokenHeader))
@@ -72,7 +78,6 @@ func Do(ctx *fasthttp.RequestCtx) (int64, error) {
}
}
path = getPathWithoutPrefix(path)
if _, ok := routing.InnerAddressMap[string(path)]; ok {
adminToken := ctx.Request.Header.Peek("x-auth-admin") //todo const key
if token.Check(string(adminToken)) != nil {
+7
View File
@@ -0,0 +1,7 @@
package domain
type ProxyResponse struct {
RequestBody []byte
ResponseBody []byte
Error error
}
+92 -11
View File
@@ -1,15 +1,59 @@
package handler
import (
"github.com/integration-system/isp-lib/config"
log "github.com/integration-system/isp-log"
"github.com/pkg/errors"
"github.com/valyala/fasthttp"
"google.golang.org/grpc/codes"
"isp-gate-service/approve"
"isp-gate-service/authenticate"
"isp-gate-service/conf"
"isp-gate-service/domain"
"isp-gate-service/journal"
"isp-gate-service/log_code"
"isp-gate-service/proxy"
"isp-gate-service/utils"
"isp-gate-service/proxy/response"
"isp-gate-service/service"
"net/http"
"time"
)
func Complete(ctx *fasthttp.RequestCtx) {
var helper handlerHelper
type handlerHelper struct{}
func CompleteRequest(ctx *fasthttp.RequestCtx) {
currentTime := time.Now()
uri := string(ctx.RequestURI())
resp := helper.AuthenticateApproveProxy(ctx)
executionTime := time.Since(currentTime) / 1e6
statusCode := ctx.Response.StatusCode()
service.Metrics.UpdateStatusCounter(helper.SetMetricStatus(statusCode))
if statusCode == http.StatusOK {
service.Metrics.UpdateResponseTime(executionTime)
service.Metrics.UpdateMethodResponseTime(uri, executionTime)
}
if config.GetRemote().(*conf.RemoteConfig).Journal.Enable && service.JournalMethodsMatcher.Match(uri) {
if resp.Error != nil {
if err := journal.Client.Error(uri, resp.RequestBody, resp.ResponseBody, resp.Error); err != nil {
log.Warnf(log_code.WarnJournalCouldNotWriteToFile, "could not write to file journal: %v", err)
}
} else {
if err := journal.Client.Info(uri, resp.RequestBody, resp.ResponseBody); err != nil {
log.Warnf(log_code.WarnJournalCouldNotWriteToFile, "could not write to file journal: %v", err)
}
}
}
}
func (handlerHelper) AuthenticateApproveProxy(ctx *fasthttp.RequestCtx) domain.ProxyResponse {
path := string(ctx.Path())
applicationId, err := authenticate.Do(ctx)
if err != nil {
status := codes.Unknown
@@ -17,21 +61,58 @@ func Complete(ctx *fasthttp.RequestCtx) {
case authenticate.ErrorDescription:
status = e.ConvertToGrpcStatus()
}
utils.SendError("authenticate error", status, nil, ctx)
return
return response.Create(ctx, response.Option.SetAndSendError("unauthorized", status, err))
}
path := string(ctx.Path())
if approver := approve.GetApprove(applicationId); approver != nil && !approver.Complete(path) {
utils.SendError("approve error", codes.PermissionDenied, nil, ctx)
return
if approver := approve.GetApprove(applicationId); approver != nil && !approver.ApproveMethod(path) {
err := errors.New("approve error")
return response.Create(ctx, response.Option.SetAndSendError("forbidden", codes.PermissionDenied, err))
}
p := proxy.Find(path)
if p != nil {
p.ProxyRequest(ctx)
return p.ProxyRequest(ctx)
} else {
utils.SendError("unknown path", codes.NotFound, []interface{}{map[string]string{"path": path}}, ctx)
err := errors.Errorf("unknown path %s", path)
return response.Create(ctx, response.Option.SetAndSendError("not found", codes.NotFound, err))
}
}
func (handlerHelper) 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
}
//
//func (h handlerHelper) CheckPath(path []byte) (bool, bool) {
// path = h.getPathWithoutPrefix(path)
// _, implemented := routing.AddressMap[string(path)]
// _, inner := routing.InnerAddressMap[string(path)]
// return implemented, inner
//}
//
//func (handlerHelper) getPathWithoutPrefix(path []byte) []byte {
// firstFound := false
// for i, value := range path {
// if value == '/' {
// if firstFound {
// return path[i+1:]
// } else {
// firstFound = true
// }
// }
// }
// return []byte{}
//}
+8 -5
View File
@@ -5,6 +5,7 @@ import (
"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/http"
"strings"
@@ -17,11 +18,13 @@ const (
grpcProtocol = "grpc"
)
type Proxy interface {
ProxyRequest(ctx *fasthttp.RequestCtx)
Consumer([]structure.AddressConfiguration) bool
Close()
}
type (
Proxy interface {
ProxyRequest(ctx *fasthttp.RequestCtx) domain.ProxyResponse
Consumer([]structure.AddressConfiguration) bool
Close()
}
)
func Init(location conf.Location) (Proxy, error) {
if location.PathPrefix[0] != '/' {
+6 -17
View File
@@ -4,16 +4,15 @@ import (
"github.com/integration-system/isp-lib/backend"
"github.com/integration-system/isp-lib/structure"
log "github.com/integration-system/isp-log"
"github.com/pkg/errors"
"github.com/valyala/fasthttp"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"isp-gate-service/conf"
"isp-gate-service/domain"
"isp-gate-service/log_code"
"isp-gate-service/proxy/grpc/handlers"
"isp-gate-service/service"
"isp-gate-service/utils"
"net/http"
"time"
"isp-gate-service/proxy/response"
)
type grpcProxy struct {
@@ -33,25 +32,15 @@ func NewProxy() *grpcProxy {
)}
}
func (p *grpcProxy) ProxyRequest(ctx *fasthttp.RequestCtx) {
func (p *grpcProxy) ProxyRequest(ctx *fasthttp.RequestCtx) domain.ProxyResponse {
if p.client.InternalGrpcClient == nil {
msg := "client undefined"
log.Error(log_code.ErrorClientGrpc, msg)
utils.SendError(msg, codes.Internal, nil, ctx)
return
return response.Create(ctx, response.Option.SetAndSendError(msg, codes.Internal, errors.New(msg)))
}
currentTime := time.Now()
uri := string(ctx.RequestURI())
handlers.Handler.Get(ctx).Complete(ctx, uri, p.client)
executionTime := time.Since(currentTime) / 1e6
service.Metrics.UpdateStatusCounter(ctx.Response.StatusCode())
if ctx.Response.StatusCode() == http.StatusOK {
service.Metrics.UpdateResponseTime(executionTime)
service.Metrics.UpdateMethodResponseTime(uri, executionTime)
}
return handlers.Handler.Get(ctx).Complete(ctx, uri, p.client)
}
func (p *grpcProxy) Consumer(addr []structure.AddressConfiguration) bool {
+16 -7
View File
@@ -18,8 +18,9 @@ import (
"google.golang.org/grpc/status"
"io"
"isp-gate-service/conf"
"isp-gate-service/domain"
"isp-gate-service/log_code"
u "isp-gate-service/utils"
"isp-gate-service/proxy/response"
"net/http"
"strings"
"time"
@@ -36,7 +37,8 @@ const (
)
var (
json = jsoniter.ConfigFastest
json = jsoniter.ConfigFastest
emptyBody = make([]byte, 0)
)
func convertError(err error) ([]byte, int) {
@@ -137,14 +139,21 @@ func makeMetadata(r *fasthttp.RequestHeader, method string) (metadata.MD, string
return md, method
}
func checkError(err error, ctx *fasthttp.RequestCtx) (bool, bool) {
func checkError(err error, ctx *fasthttp.RequestCtx) (bool, bool, domain.ProxyResponse) {
var (
ok = true
eof = false
resp = domain.ProxyResponse{}
)
if err != nil {
if err != io.EOF {
logHandlerError(log_code.TypeData.GetFile, "", err)
u.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, ctx)
return false, false
resp = response.Create(ctx, response.Option.SetAndSendError(errorMsgInternal, codes.Internal, err))
ok, eof = false, false
} else {
ok, eof = true, true
}
return true, true
}
return true, false
return ok, eof, resp
}
+5 -4
View File
@@ -4,7 +4,8 @@ import (
"github.com/integration-system/isp-lib/backend"
u "github.com/integration-system/isp-lib/utils"
"github.com/valyala/fasthttp"
"isp-gate-service/utils"
"isp-gate-service/domain"
"isp-gate-service/proxy/response"
"mime"
)
@@ -14,7 +15,7 @@ type (
handlerHelper struct{}
handler interface {
Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient)
Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) domain.ProxyResponse
}
)
@@ -23,12 +24,12 @@ func (h handlerHelper) Get(ctx *fasthttp.RequestCtx) handler {
isExpectFile := string(ctx.Request.Header.Peek(u.ExpectFileHeader)) == "true"
if isMultipart {
ctx.Response.Header.SetContentType(utils.JsonContentType)
ctx.Response.Header.SetContentType(response.JsonContentType)
return sendMultipartData
} else if isExpectFile {
return getFile
} else {
ctx.Response.Header.SetContentType(utils.JsonContentType)
ctx.Response.Header.SetContentType(response.JsonContentType)
return handleJson
}
}
+24 -10
View File
@@ -12,8 +12,9 @@ import (
"google.golang.org/grpc/codes"
"io"
"isp-gate-service/conf"
"isp-gate-service/domain"
"isp-gate-service/log_code"
"isp-gate-service/utils"
"isp-gate-service/proxy/response"
"strconv"
)
@@ -21,15 +22,19 @@ var getFile getFileDesc
type getFileDesc struct{}
func (g getFileDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) {
func (g getFileDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) domain.ProxyResponse {
cfg := config.GetRemote().(*conf.RemoteConfig).GrpcSetting
timeout := cfg.GetStreamInvokeTimeout()
req, err := g.readJsonBody(ctx)
if err != nil {
logHandlerError(log_code.TypeData.GetFile, method, err)
utils.SendError(err.Error(), codes.InvalidArgument, nil, ctx)
return
return response.Create(
ctx,
response.Option.SetAndSendError(err.Error(), codes.InvalidArgument, err),
response.Option.EmptyRequest(),
response.Option.EmptyResponse(),
)
}
stream, cancel, err := openStream(&ctx.Request.Header, method, timeout, client)
@@ -40,8 +45,12 @@ func (g getFileDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *b
}()
if err != nil {
logHandlerError(log_code.TypeData.GetFile, method, err)
utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, ctx)
return
return response.Create(
ctx,
response.Option.SetAndSendError(errorMsgInternal, codes.Internal, err),
response.Option.EmptyRequest(),
response.Option.EmptyResponse(),
)
}
if req != nil {
@@ -49,8 +58,12 @@ func (g getFileDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *b
err := stream.Send(backend.WrapBody(value))
if err != nil {
logHandlerError(log_code.TypeData.GetFile, method, err)
utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, ctx)
return
return response.Create(
ctx,
response.Option.SetAndSendError(errorMsgInternal, codes.Internal, err),
response.Option.EmptyRequest(),
response.Option.EmptyResponse(),
)
}
}
@@ -61,7 +74,7 @@ func (g getFileDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *b
ctx.SetStatusCode(status)
ctx.SetBody(bytes)
}
return
return response.Create(ctx, response.Option.EmptyResponse(), response.Option.EmptyRequest())
}
bf := s.BeginFile{}
err = bf.FromMessage(msg)
@@ -71,7 +84,7 @@ func (g getFileDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *b
ctx.SetStatusCode(status)
ctx.SetBody(bytes)
}
return
return response.Create(ctx, response.Option.EmptyResponse(), response.Option.EmptyRequest())
}
header := &ctx.Response.Header
header.Set(headerKeyContentDisposition, fmt.Sprintf("attachment; filename=%s", bf.FileName))
@@ -105,6 +118,7 @@ func (g getFileDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *b
break
}
}
return response.Create(ctx, response.Option.EmptyResponse(), response.Option.EmptyRequest())
}
func (getFileDesc) readJsonBody(ctx *fasthttp.RequestCtx) (interface{}, error) {
+20 -26
View File
@@ -4,24 +4,21 @@ import (
"github.com/integration-system/isp-lib/backend"
"github.com/integration-system/isp-lib/config"
isp "github.com/integration-system/isp-lib/proto/stubs"
log "github.com/integration-system/isp-log"
"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/journal"
"isp-gate-service/domain"
"isp-gate-service/log_code"
"isp-gate-service/service"
"isp-gate-service/utils"
"time"
"isp-gate-service/proxy/response"
)
var handleJson handleJsonDesc
type handleJsonDesc struct{}
func (p handleJsonDesc) Complete(c *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) {
func (p handleJsonDesc) Complete(c *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) domain.ProxyResponse {
//body, err := utils.ReadJsonBody(c)
body := c.Request.Body()
/*if err != nil {
@@ -32,43 +29,40 @@ func (p handleJsonDesc) Complete(c *fasthttp.RequestCtx, method string, client *
md, methodName := makeMetadata(&c.Request.Header, method)
ctx := metadata.NewOutgoingContext(context.Background(), md)
cfg := config.GetRemote().(*conf.RemoteConfig)
ctx, cancel := context.WithTimeout(ctx, cfg.GrpcSetting.GetSyncInvokeTimeout())
grpcSetting := config.GetRemote().(*conf.RemoteConfig).GrpcSetting
ctx, cancel := context.WithTimeout(ctx, grpcSetting.GetSyncInvokeTimeout())
defer cancel()
cli, err := client.Conn()
if err != nil {
logHandlerError(log_code.TypeData.JsonContent, methodName, err)
utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, c)
return
return response.Create(
c,
response.Option.SetAndSendError(errorMsgInternal, codes.Internal, err),
response.Option.EmptyRequest(),
response.Option.EmptyResponse(),
)
}
//structBody := u.ConvertInterfaceToGrpcStruct(body)
currentTime := time.Now()
response, invokerErr := cli.Request(
resp, invokerErr := cli.Request(
ctx,
&isp.Message{
Body: &isp.Message_BytesBody{BytesBody: body},
},
)
service.Metrics.UpdateRouterResponseTime(time.Since(currentTime) / 1e6)
if data, status, err := getResponse(response, invokerErr); err == nil {
if data, status, err := getResponse(resp, invokerErr); err == nil {
c.SetStatusCode(status)
_, _ = c.Write(data)
if cfg.Journal.Enable && service.JournalMethodsMatcher.Match(methodName) {
if invokerErr != nil {
if err := journal.Client.Error(methodName, body, data, invokerErr); err != nil {
log.Warnf(log_code.WarnJournalCouldNotWriteToFile, "could not write to file journal: %v", err)
}
} else {
if err := journal.Client.Info(methodName, body, data); err != nil {
log.Warnf(log_code.WarnJournalCouldNotWriteToFile, "could not write to file journal: %v", err)
}
}
}
return response.Create(c, response.Option.SetError(invokerErr))
} else {
logHandlerError(log_code.TypeData.JsonContent, methodName, err)
utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, c)
return response.Create(
c,
response.Option.SetAndSendError(errorMsgInternal, codes.Internal, err),
response.Option.EmptyRequest(),
response.Option.EmptyResponse(),
)
}
}
@@ -8,8 +8,9 @@ import (
"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"
"isp-gate-service/proxy/response"
"mime/multipart"
"strings"
)
@@ -18,7 +19,7 @@ var sendMultipartData sendMultipartDataDesc
type sendMultipartDataDesc struct{}
func (h sendMultipartDataDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) {
func (h sendMultipartDataDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) domain.ProxyResponse {
cfg := config.GetRemote().(*conf.RemoteConfig).GrpcSetting
timeout := cfg.GetStreamInvokeTimeout()
bufferSize := cfg.GetTransferFileBufferSize()
@@ -31,8 +32,12 @@ func (h sendMultipartDataDesc) Complete(ctx *fasthttp.RequestCtx, method string,
}()
if err != nil {
logHandlerError(log_code.TypeData.SendMultipart, method, err)
utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, ctx)
return
return response.Create(
ctx,
response.Option.SetAndSendError(errorMsgInternal, codes.Internal, err),
response.Option.EmptyRequest(),
response.Option.EmptyResponse(),
)
}
form, err := ctx.MultipartForm()
@@ -44,8 +49,12 @@ func (h sendMultipartDataDesc) Complete(ctx *fasthttp.RequestCtx, method string,
if err != nil {
logHandlerError(log_code.TypeData.SendMultipart, method, err)
utils.SendError(errorMsgInvalidArg, codes.InvalidArgument, []interface{}{err.Error()}, ctx)
return
return response.Create(
ctx,
response.Option.SetAndSendError(errorMsgInvalidArg, codes.InvalidArgument, err),
response.Option.EmptyRequest(),
response.Option.EmptyResponse(),
)
}
formData := make(map[string]interface{}, len(form.Value))
@@ -56,10 +65,13 @@ func (h sendMultipartDataDesc) Complete(ctx *fasthttp.RequestCtx, method string,
}
}
response := make([]string, 0)
buffer := make([]byte, bufferSize)
ok := true
eof := false
var (
proxyResp domain.ProxyResponse
resp = make([]string, 0)
buffer = make([]byte, bufferSize)
ok = true
eof = false
)
for formDataName, files := range form.File {
if len(files) == 0 {
@@ -77,19 +89,19 @@ func (h sendMultipartDataDesc) Complete(ctx *fasthttp.RequestCtx, method string,
FormData: formData,
}
err = stream.Send(bf.ToMessage())
if ok, eof = checkError(err, ctx); !ok || eof {
if ok, eof, proxyResp = checkError(err, ctx); !ok || eof {
break
}
f, err := file.Open()
if ok, eof = checkError(err, ctx); !ok || eof {
if ok, eof, proxyResp = checkError(err, ctx); !ok || eof {
break
}
if ok, eof = h.transferFile(f, stream, buffer, ctx); ok {
if ok, eof, proxyResp = h.transferFile(f, stream, buffer, ctx); ok {
msg, err := stream.Recv()
v, _, err := getResponse(msg, err)
if err == nil {
response = append(response, string(v))
resp = append(resp, string(v))
}
ok = err == nil
}
@@ -105,34 +117,38 @@ func (h sendMultipartDataDesc) Complete(ctx *fasthttp.RequestCtx, method string,
}
if ok {
arrayBody := strings.Join(response, ",")
arrayBody := strings.Join(resp, ",")
_, err = ctx.WriteString("[" + arrayBody + "]")
if err != nil {
logHandlerError(log_code.TypeData.SendMultipart, method, err)
}
}
return proxyResp
}
func (sendMultipartDataDesc) transferFile(f multipart.File, stream isp.BackendService_RequestStreamClient,
buffer []byte, ctx *fasthttp.RequestCtx) (bool, bool) {
buffer []byte, ctx *fasthttp.RequestCtx) (bool, bool, domain.ProxyResponse) {
ok := true
eof := false
var (
ok = true
eof = false
proxyResp domain.ProxyResponse
)
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 {
err = stream.Send(&isp.Message{Body: &isp.Message_BytesBody{BytesBody: buffer[:n]}})
if ok, eof, proxyResp = checkError(err, ctx); !ok || eof {
break
}
}
if err != nil {
if ok, eof = checkError(err, ctx); ok && eof {
if ok, eof, proxyResp = checkError(err, ctx); ok && eof {
err = stream.Send(s.FileEnd())
ok, eof = checkError(err, ctx)
ok, eof, proxyResp = checkError(err, ctx)
}
break
}
}
return ok, eof
return ok, eof, proxyResp
}
+6 -5
View File
@@ -1,12 +1,14 @@
package http
import (
"errors"
"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/domain"
"isp-gate-service/log_code"
"isp-gate-service/utils"
"isp-gate-service/proxy/response"
"net"
"strings"
)
@@ -31,12 +33,11 @@ func (p *httpProxy) Consumer(addressList []structure.AddressConfiguration) bool
return true
}
func (p *httpProxy) ProxyRequest(ctx *fasthttp.RequestCtx) {
func (p *httpProxy) ProxyRequest(ctx *fasthttp.RequestCtx) domain.ProxyResponse {
if p.client == nil {
msg := "client undefined"
log.Error(log_code.ErrorClientHttp, msg)
utils.SendError(msg, codes.Internal, nil, ctx)
return
return response.Create(ctx, response.Option.SetAndSendError(msg, codes.Internal, errors.New(msg)))
}
req := &ctx.Request
@@ -48,8 +49,8 @@ func (p *httpProxy) ProxyRequest(ctx *fasthttp.RequestCtx) {
if err := p.client.Do(req, res); err != nil {
log.Error(log_code.ErrorClientHttp, err)
return
}
return response.Create(ctx)
}
func (p *httpProxy) Close() {
+67
View File
@@ -0,0 +1,67 @@
package response
import (
"encoding/json"
"github.com/integration-system/isp-lib/http"
"github.com/integration-system/isp-lib/structure"
"github.com/valyala/fasthttp"
"google.golang.org/grpc/codes"
"isp-gate-service/domain"
)
const JsonContentType = "application/json; charset=utf-8"
var Option optionStruct
type (
optionStruct struct{}
option func(ctx *fasthttp.RequestCtx, response *domain.ProxyResponse)
)
func Create(ctx *fasthttp.RequestCtx, options ...option) domain.ProxyResponse {
response := domain.ProxyResponse{
RequestBody: ctx.Request.Body(),
ResponseBody: ctx.Response.Body(),
}
for _, option := range options {
option(ctx, &response)
}
return response
}
func (optionStruct) EmptyRequest() option {
return func(ctx *fasthttp.RequestCtx, response *domain.ProxyResponse) {
response.RequestBody = make([]byte, 0)
}
}
func (optionStruct) EmptyResponse() option {
return func(ctx *fasthttp.RequestCtx, response *domain.ProxyResponse) {
response.ResponseBody = make([]byte, 0)
}
}
func (optionStruct) SetError(err error) option {
return func(ctx *fasthttp.RequestCtx, response *domain.ProxyResponse) {
response.Error = err
}
}
func (optionStruct) SetAndSendError(msg string, code codes.Code, err error) option {
return func(ctx *fasthttp.RequestCtx, response *domain.ProxyResponse) {
response.Error = err
grpcCode := code.String()
structureError := structure.GrpcError{
ErrorMessage: msg,
ErrorCode: grpcCode,
Details: []interface{}{err.Error()},
}
ctx.SetContentType(JsonContentType)
ctx.SetStatusCode(http.CodeToHttpStatus(code))
msg, _ := json.Marshal(structureError)
_, _ = ctx.Write(msg)
}
}
+4
View File
@@ -6,19 +6,23 @@ import (
var (
InnerAddressMap = make(map[string]bool)
AddressMap = make(map[string]bool)
)
func InitRoutes(configs structure.RoutingConfig) {
newAddressMap := make(map[string]bool)
newInnerAddressMap := make(map[string]bool)
for _, backend := range configs {
if backend.Address.IP == "" || backend.Address.Port == "" || len(backend.Endpoints) == 0 {
continue
}
for _, v := range backend.Endpoints {
newAddressMap[v.Path] = true
if v.Inner {
newInnerAddressMap[v.Path] = true
}
}
}
AddressMap = newAddressMap
InnerAddressMap = newInnerAddressMap
}
+1 -1
View File
@@ -29,7 +29,7 @@ func (s *httpSrv) Init(MaxRequestBodySize int64) {
localConfig := config.Get().(*conf.Configuration)
restAddress := localConfig.HttpInnerAddress.GetAddress()
s.srv = &fasthttp.Server{
Handler: handler.Complete,
Handler: handler.CompleteRequest,
WriteTimeout: time.Second * 60,
ReadTimeout: time.Second * 60,
MaxRequestBodySize: int(maxRequestBodySize),
+12 -20
View File
@@ -3,7 +3,6 @@ package service
import (
"github.com/integration-system/isp-lib/metric"
"github.com/rcrowley/go-metrics"
"strconv"
"sync"
"time"
)
@@ -20,25 +19,24 @@ type (
}
metricHolder struct {
methodHistograms map[string]metrics.Histogram
methodLock sync.RWMutex
statusCounters map[int]metrics.Counter
statusLock sync.RWMutex
routerResponseTime metrics.Histogram
responseTime metrics.Histogram
methodHistograms map[string]metrics.Histogram
methodLock sync.RWMutex
statusCounters map[string]metrics.Counter
statusLock sync.RWMutex
responseTime metrics.Histogram
}
)
func (m *metricService) Init() {
m.mh = &metricHolder{
methodHistograms: make(map[string]metrics.Histogram),
statusCounters: make(map[int]metrics.Counter),
statusCounters: make(map[string]metrics.Counter),
responseTime: metrics.GetOrRegisterHistogram(
"http.response.time", metric.GetRegistry(), metrics.NewUniformSample(defaultSampleSize),
),
routerResponseTime: metrics.GetOrRegisterHistogram(
"grpc.router.response.time", metric.GetRegistry(), metrics.NewUniformSample(defaultSampleSize),
),
//routerResponseTime: metrics.GetOrRegisterHistogram(
// "grpc.router.response.time", metric.GetRegistry(), metrics.NewUniformSample(defaultSampleSize),
//),
}
}
@@ -54,13 +52,7 @@ func (m *metricService) UpdateResponseTime(time time.Duration) {
}
}
func (m *metricService) UpdateRouterResponseTime(time time.Duration) {
if m.notEmptyHolder() {
m.mh.routerResponseTime.Update(int64(time))
}
}
func (m *metricService) UpdateStatusCounter(status int) {
func (m *metricService) UpdateStatusCounter(status string) {
if m.notEmptyHolder() {
m.getOrRegisterCounter(status).Inc(1)
}
@@ -88,7 +80,7 @@ func (m *metricService) getOrRegisterHistogram(uri string) metrics.Histogram {
return histogram
}
func (m *metricService) getOrRegisterCounter(status int) metrics.Counter {
func (m *metricService) getOrRegisterCounter(status string) metrics.Counter {
m.mh.statusLock.RLock()
d, ok := m.mh.statusCounters[status]
m.mh.statusLock.RUnlock()
@@ -101,7 +93,7 @@ func (m *metricService) getOrRegisterCounter(status int) metrics.Counter {
if d, ok := m.mh.statusCounters[status]; ok {
return d
}
d = metrics.GetOrRegisterCounter("http.response.count."+strconv.Itoa(status), metric.GetRegistry())
d = metrics.GetOrRegisterCounter("http.response.count."+status, metric.GetRegistry())
m.mh.statusCounters[status] = d
return d
}
-28
View File
@@ -1,28 +0,0 @@
package utils
import (
"encoding/json"
"github.com/integration-system/isp-lib/http"
"github.com/integration-system/isp-lib/structure"
"github.com/valyala/fasthttp"
"google.golang.org/grpc/codes"
)
const (
JsonContentType = "application/json; charset=utf-8"
)
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.SetContentType(JsonContentType)
ctx.SetStatusCode(http.CodeToHttpStatus(errorCode))
msg, _ := json.Marshal(structureError)
_, _ = ctx.Write(msg)
}