ref
This commit is contained in:
1 parent
f3934e038e
commit
4fdf7c0ca2
19 files changed
+457
-379
No files matched your search
@@ -2,51 +2,56 @@ package authenticate
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/integration-system/isp-lib/utils"
|
"github.com/integration-system/isp-lib/utils"
|
||||||
"github.com/pkg/errors"
|
|
||||||
"github.com/valyala/fasthttp"
|
"github.com/valyala/fasthttp"
|
||||||
"isp-gate-service/redis"
|
"google.golang.org/grpc/codes"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
var redisKeyHeaderKeyMap = map[string]string{
|
var (
|
||||||
redis.SystemIdentity: utils.SystemIdHeader,
|
verifiableKeyHeaderKeyMap = map[string]string{
|
||||||
redis.DomainIdentity: utils.DomainIdHeader,
|
SystemIdentity: utils.SystemIdHeader,
|
||||||
redis.ServiceIdentity: utils.ServiceIdHeader,
|
DomainIdentity: utils.DomainIdHeader,
|
||||||
redis.ApplicationIdentity: utils.ApplicationIdHeader,
|
ServiceIdentity: utils.ServiceIdHeader,
|
||||||
redis.DeviceIdentity: utils.DeviceIdHeader,
|
ApplicationIdentity: utils.ApplicationIdHeader,
|
||||||
redis.UserIdentity: utils.UserIdHeader,
|
DeviceIdentity: utils.DeviceIdHeader,
|
||||||
redis.DeviceToken: utils.DeviceTokenHeader,
|
UserIdentity: utils.UserIdHeader,
|
||||||
redis.UserToken: utils.UserTokenHeader,
|
DeviceToken: utils.DeviceTokenHeader,
|
||||||
}
|
UserToken: utils.UserTokenHeader,
|
||||||
|
}
|
||||||
func Compete(ctx *fasthttp.RequestCtx) error {
|
notExpectedHeaders = []string{
|
||||||
for _, notExpectedHeader := range []string{
|
|
||||||
utils.SystemIdHeader, utils.DomainIdHeader, utils.ServiceIdHeader, utils.ApplicationIdHeader,
|
utils.SystemIdHeader, utils.DomainIdHeader, utils.ServiceIdHeader, utils.ApplicationIdHeader,
|
||||||
} {
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
func Do(ctx *fasthttp.RequestCtx) error {
|
||||||
|
for _, notExpectedHeader := range notExpectedHeaders {
|
||||||
ctx.Request.Header.Del(notExpectedHeader)
|
ctx.Request.Header.Del(notExpectedHeader)
|
||||||
}
|
}
|
||||||
|
|
||||||
appToken := ctx.Request.Header.Peek(utils.ApplicationTokenHeader)
|
appToken := ctx.Request.Header.Peek(utils.ApplicationTokenHeader)
|
||||||
if len(appToken) == 0 {
|
if len(appToken) == 0 {
|
||||||
return errors.Errorf("%s not found", utils.ApplicationTokenHeader)
|
return Error.Create(codes.Unauthenticated)
|
||||||
}
|
}
|
||||||
tokens, err := redis.Client.GetTokens(string(appToken))
|
verifiableKeys, err := verification.appToken(string(appToken))
|
||||||
if err != nil || len(tokens) != 4 {
|
|
||||||
return errors.Errorf("redis error %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
tokens[redis.Uri] = strings.Replace(strings.ToLower(string(ctx.Path())), "/", "", -1)
|
|
||||||
tokens[redis.DeviceToken] = string(ctx.Request.Header.Peek(utils.DeviceTokenHeader))
|
|
||||||
tokens[redis.UserToken] = string(ctx.Request.Header.Peek(utils.UserTokenHeader))
|
|
||||||
|
|
||||||
tokens, err = redis.Client.CheckTokens(tokens)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
delete(tokens, redis.Uri)
|
if len(verifiableKeys) != 4 {
|
||||||
for key, value := range tokens {
|
return Error.Create(codes.Unauthenticated)
|
||||||
|
}
|
||||||
|
|
||||||
|
uri := strings.Replace(strings.ToLower(string(ctx.Path())), "/", "", -1)
|
||||||
|
verifiableKeys[DeviceToken] = string(ctx.Request.Header.Peek(utils.DeviceTokenHeader))
|
||||||
|
verifiableKeys[UserToken] = string(ctx.Request.Header.Peek(utils.UserTokenHeader))
|
||||||
|
|
||||||
|
verifiableKeys, err = verification.keys(verifiableKeys, uri)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for key, value := range verifiableKeys {
|
||||||
if value != "" {
|
if value != "" {
|
||||||
ctx.Request.Header.Set(redisKeyHeaderKeyMap[key], value)
|
ctx.Request.Header.Set(verifiableKeyHeaderKeyMap[key], value)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package authenticate
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"google.golang.org/grpc/codes"
|
||||||
|
)
|
||||||
|
|
||||||
|
var Error errorHelper
|
||||||
|
|
||||||
|
func (errorHelper) Create(status codes.Code) ErrorDescription {
|
||||||
|
return ErrorDescription{grpcStatus: status}
|
||||||
|
}
|
||||||
|
|
||||||
|
type (
|
||||||
|
errorHelper struct{}
|
||||||
|
ErrorDescription struct {
|
||||||
|
grpcStatus codes.Code
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
func (e ErrorDescription) Error() string {
|
||||||
|
return fmt.Sprintf("%v", e)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e ErrorDescription) ConvertToGrpcStatus() codes.Code {
|
||||||
|
return e.grpcStatus
|
||||||
|
}
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
package authenticate
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
rd "github.com/go-redis/redis"
|
||||||
|
"github.com/integration-system/isp-lib/config"
|
||||||
|
"github.com/integration-system/isp-lib/redis"
|
||||||
|
"google.golang.org/grpc/codes"
|
||||||
|
"isp-gate-service/conf"
|
||||||
|
rdClient "isp-gate-service/redis"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
SystemIdentity = "1"
|
||||||
|
DomainIdentity = "2"
|
||||||
|
ServiceIdentity = "3"
|
||||||
|
ApplicationIdentity = "4"
|
||||||
|
|
||||||
|
DeviceIdentity = "5"
|
||||||
|
UserIdentity = "6"
|
||||||
|
|
||||||
|
DeviceToken = "7"
|
||||||
|
UserToken = "8"
|
||||||
|
)
|
||||||
|
|
||||||
|
var verification verificationHelper
|
||||||
|
|
||||||
|
type verificationHelper struct{}
|
||||||
|
|
||||||
|
func (v verificationHelper) appToken(token string) (map[string]string, error) {
|
||||||
|
instanceUuid := config.Get().(*conf.Configuration).InstanceUuid
|
||||||
|
key := fmt.Sprintf("%s|%s", token, instanceUuid)
|
||||||
|
|
||||||
|
if resp, err := rdClient.Client.Get().Pipelined(func(p rd.Pipeliner) error {
|
||||||
|
if cmd := p.Select(int(redis.ApplicationTokenDb)); v.notEmptyError(cmd.Err()) {
|
||||||
|
return cmd.Err()
|
||||||
|
}
|
||||||
|
if cmd := p.HGetAll(key); v.notEmptyError(cmd.Err()) {
|
||||||
|
return cmd.Err()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}); err != nil {
|
||||||
|
return nil, Error.Create(codes.Internal)
|
||||||
|
} else {
|
||||||
|
if len(resp) < 2 || resp[1].Err() == rd.Nil {
|
||||||
|
return nil, nil
|
||||||
|
} else if resp[1].Err() != nil {
|
||||||
|
return nil, Error.Create(codes.Unauthenticated)
|
||||||
|
} else if stringStringMapCmd, ok := resp[1].(*rd.StringStringMapCmd); !ok {
|
||||||
|
return nil, nil
|
||||||
|
} else {
|
||||||
|
return stringStringMapCmd.Val(), nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *verificationHelper) keys(t map[string]string, uri string) (map[string]string, error) {
|
||||||
|
secondDbKey := fmt.Sprintf("%s|%s", t[ApplicationIdentity], uri)
|
||||||
|
thirdDbKey := fmt.Sprintf("%s|%s", t[UserToken], t[DomainIdentity])
|
||||||
|
fifthDbKey := fmt.Sprintf("%s|%s", t[DeviceToken], t[DomainIdentity])
|
||||||
|
|
||||||
|
if resp, err := rdClient.Client.Get().Pipelined(func(p rd.Pipeliner) error {
|
||||||
|
if cmd := p.Select(int(redis.ApplicationPermissionDb)); v.notEmptyError(cmd.Err()) {
|
||||||
|
return cmd.Err()
|
||||||
|
}
|
||||||
|
if cmd := p.Get(secondDbKey); v.notEmptyError(cmd.Err()) {
|
||||||
|
return cmd.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
if cmd := p.Select(int(redis.UserTokenDb)); v.notEmptyError(cmd.Err()) {
|
||||||
|
return cmd.Err()
|
||||||
|
}
|
||||||
|
if cmd := p.Get(thirdDbKey); v.notEmptyError(cmd.Err()) {
|
||||||
|
return cmd.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
if cmd := p.Select(int(redis.DeviceTokenDb)); v.notEmptyError(cmd.Err()) {
|
||||||
|
return cmd.Err()
|
||||||
|
}
|
||||||
|
if cmd := p.Get(fifthDbKey); v.notEmptyError(cmd.Err()) {
|
||||||
|
return cmd.Err()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}); err != nil && err != rd.Nil {
|
||||||
|
return t, Error.Create(codes.Internal)
|
||||||
|
} else {
|
||||||
|
// It is not permitted to call this methodParts
|
||||||
|
if v.fineCmd(resp, 1) {
|
||||||
|
if intCmd, ok := resp[1].(*rd.IntCmd); ok && intCmd.Val() == 0 {
|
||||||
|
return t, Error.Create(codes.PermissionDenied)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// ===== CHECK USER TOKEN =====
|
||||||
|
if v.fineCmd(resp, 3) {
|
||||||
|
if stringCmd, ok := resp[3].(*rd.StringCmd); ok {
|
||||||
|
t[UserIdentity] = stringCmd.Val()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// ===== CHECK DEVICE TOKEN =====
|
||||||
|
if v.fineCmd(resp, 5) {
|
||||||
|
if stringCmd, ok := resp[5].(*rd.StringCmd); ok {
|
||||||
|
t[DeviceIdentity] = stringCmd.Val()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return t, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *verificationHelper) notEmptyError(err error) bool {
|
||||||
|
return err != nil && err != rd.Nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *verificationHelper) fineCmd(cmders []rd.Cmder, arrayKey int) bool {
|
||||||
|
if len(cmders) > arrayKey+1 {
|
||||||
|
cmder := cmders[arrayKey]
|
||||||
|
return cmder != nil && (cmder.Err() == nil || cmder.Err() == rd.Nil)
|
||||||
|
} else {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
+8
-21
@@ -1,28 +1,23 @@
|
|||||||
package handler
|
package handler
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
|
||||||
"github.com/integration-system/isp-lib/http"
|
|
||||||
"github.com/integration-system/isp-lib/structure"
|
|
||||||
"github.com/valyala/fasthttp"
|
"github.com/valyala/fasthttp"
|
||||||
"google.golang.org/grpc/codes"
|
"google.golang.org/grpc/codes"
|
||||||
"isp-gate-service/authenticate"
|
"isp-gate-service/authenticate"
|
||||||
"isp-gate-service/proxy"
|
"isp-gate-service/proxy"
|
||||||
|
"isp-gate-service/utils"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Complete(ctx *fasthttp.RequestCtx) {
|
func Complete(ctx *fasthttp.RequestCtx) {
|
||||||
path := string(ctx.Path())
|
path := string(ctx.Path())
|
||||||
|
|
||||||
if err := authenticate.Compete(ctx); err != nil {
|
if err := authenticate.Do(ctx); err != nil {
|
||||||
statusCode := codes.Unauthenticated
|
status := codes.Unknown
|
||||||
response := structure.GrpcError{
|
switch e := err.(type) {
|
||||||
ErrorMessage: "unauthenticated", ErrorCode: statusCode.String(),
|
case authenticate.ErrorDescription:
|
||||||
Details: []interface{}{err},
|
status = e.ConvertToGrpcStatus()
|
||||||
}
|
}
|
||||||
ctx.Response.Header.SetContentType("application/json; charset=utf-8")
|
utils.SendError("authenticate error", status, nil, ctx)
|
||||||
ctx.SetStatusCode(http.CodeToHttpStatus(statusCode))
|
|
||||||
message, _ := json.Marshal(response)
|
|
||||||
_, _ = ctx.Write(message)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,14 +25,6 @@ func Complete(ctx *fasthttp.RequestCtx) {
|
|||||||
if p != nil {
|
if p != nil {
|
||||||
p.ProxyRequest(ctx)
|
p.ProxyRequest(ctx)
|
||||||
} else {
|
} else {
|
||||||
statusCode := codes.NotFound
|
utils.SendError("unknown path", codes.NotFound, []interface{}{map[string]string{"path": path}}, ctx)
|
||||||
response := structure.GrpcError{
|
|
||||||
ErrorMessage: "unknown path", ErrorCode: statusCode.String(),
|
|
||||||
Details: []interface{}{map[string]string{"path": path}},
|
|
||||||
}
|
|
||||||
ctx.Response.Header.SetContentType("application/json; charset=utf-8")
|
|
||||||
ctx.SetStatusCode(http.CodeToHttpStatus(statusCode))
|
|
||||||
message, _ := json.Marshal(response)
|
|
||||||
_, _ = ctx.Write(message)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+4
-4
@@ -1,8 +1,6 @@
|
|||||||
package log_code
|
package log_code
|
||||||
|
|
||||||
const (
|
const (
|
||||||
InfoOnLocalConfigLoad = 601
|
|
||||||
|
|
||||||
WarnRequestHandler = 604 //metadata: {"typeData":"", "method":""}
|
WarnRequestHandler = 604 //metadata: {"typeData":"", "method":""}
|
||||||
WarnConvertErrorDataMarshalResponse = 605
|
WarnConvertErrorDataMarshalResponse = 605
|
||||||
ErrorGrpcClientDialing = 606
|
ErrorGrpcClientDialing = 606
|
||||||
@@ -11,10 +9,12 @@ const (
|
|||||||
|
|
||||||
ErrorClientJournal = 903
|
ErrorClientJournal = 903
|
||||||
|
|
||||||
WarnCreateRestServerHttpSrvShutdown = 602
|
WarnHttpServerShutdown = 602
|
||||||
ErrorCreateRestServerHttpSrvListenAndServe = 603
|
ErrorHttpServerListen = 603
|
||||||
|
|
||||||
ErrorLocalConfig = 904
|
ErrorLocalConfig = 904
|
||||||
ErrorClientGrpc = 905
|
ErrorClientGrpc = 905
|
||||||
ErrorClientHttp = 906
|
ErrorClientHttp = 906
|
||||||
|
|
||||||
|
ErrorClientRedis = 907
|
||||||
)
|
)
|
||||||
@@ -48,7 +48,7 @@ func main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func onLocalConfigLoad(cfg *conf.Configuration) {
|
func onLocalConfigLoad(cfg *conf.Configuration) {
|
||||||
log.Infof(log_code.InfoOnLocalConfigLoad, "Outer http address is %s", cfg.HttpOuterAddress.GetAddress())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func onRemoteConfigReceive(remoteConfig, oldRemoteConfig *conf.RemoteConfig) {
|
func onRemoteConfigReceive(remoteConfig, oldRemoteConfig *conf.RemoteConfig) {
|
||||||
@@ -81,6 +81,8 @@ func socketConfiguration(cfg interface{}) structure.SocketConfiguration {
|
|||||||
|
|
||||||
func onShutdown(_ context.Context, _ os.Signal) {
|
func onShutdown(_ context.Context, _ os.Signal) {
|
||||||
proxy.Close()
|
proxy.Close()
|
||||||
|
redis.Client.Close()
|
||||||
|
server.Http.Close()
|
||||||
}
|
}
|
||||||
|
|
||||||
func makeDeclaration(localConfig interface{}) bootstrap.ModuleInfo {
|
func makeDeclaration(localConfig interface{}) bootstrap.ModuleInfo {
|
||||||
|
|||||||
@@ -6,9 +6,12 @@ import (
|
|||||||
log "github.com/integration-system/isp-log"
|
log "github.com/integration-system/isp-log"
|
||||||
"github.com/valyala/fasthttp"
|
"github.com/valyala/fasthttp"
|
||||||
"google.golang.org/grpc"
|
"google.golang.org/grpc"
|
||||||
|
"google.golang.org/grpc/codes"
|
||||||
"isp-gate-service/conf"
|
"isp-gate-service/conf"
|
||||||
"isp-gate-service/log_code"
|
"isp-gate-service/log_code"
|
||||||
|
"isp-gate-service/proxy/grpc/handlers"
|
||||||
"isp-gate-service/service"
|
"isp-gate-service/service"
|
||||||
|
"isp-gate-service/utils"
|
||||||
"net/http"
|
"net/http"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
@@ -31,16 +34,17 @@ func NewProxy() *grpcProxy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (p *grpcProxy) ProxyRequest(ctx *fasthttp.RequestCtx) {
|
func (p *grpcProxy) ProxyRequest(ctx *fasthttp.RequestCtx) {
|
||||||
if p.client == nil {
|
if p.client.InternalGrpcClient == nil {
|
||||||
log.Error(log_code.ErrorClientGrpc, "client undefined")
|
msg := "client undefined"
|
||||||
|
log.Error(log_code.ErrorClientGrpc, msg)
|
||||||
|
utils.SendError(msg, codes.Internal, nil, ctx)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
currentTime := time.Now()
|
currentTime := time.Now()
|
||||||
|
|
||||||
uri := string(ctx.RequestURI())
|
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
|
executionTime := time.Since(currentTime) / 1e6
|
||||||
|
|
||||||
service.Metrics.UpdateStatusCounter(ctx.Response.StatusCode())
|
service.Metrics.UpdateStatusCounter(ctx.Response.StatusCode())
|
||||||
|
|||||||
@@ -1,17 +1,27 @@
|
|||||||
package handlers
|
package handlers
|
||||||
|
|
||||||
import (
|
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/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"
|
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"
|
"github.com/valyala/fasthttp"
|
||||||
"golang.org/x/net/context"
|
"golang.org/x/net/context"
|
||||||
"google.golang.org/grpc/codes"
|
"google.golang.org/grpc/codes"
|
||||||
"google.golang.org/grpc/metadata"
|
"google.golang.org/grpc/metadata"
|
||||||
|
"google.golang.org/grpc/status"
|
||||||
"io"
|
"io"
|
||||||
|
"isp-gate-service/conf"
|
||||||
"isp-gate-service/log_code"
|
"isp-gate-service/log_code"
|
||||||
"isp-gate-service/proxy/grpc/utils"
|
u "isp-gate-service/utils"
|
||||||
"mime/multipart"
|
"net/http"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -25,6 +35,79 @@ const (
|
|||||||
errorMsgInvalidArg = "Not able to read request body"
|
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) (
|
func openStream(headers *fasthttp.RequestHeader, method string, timeout time.Duration, client *backend.RxGrpcClient) (
|
||||||
isp.BackendService_RequestStreamClient, context.CancelFunc, error) {
|
isp.BackendService_RequestStreamClient, context.CancelFunc, error) {
|
||||||
|
|
||||||
@@ -32,7 +115,7 @@ func openStream(headers *fasthttp.RequestHeader, method string, timeout time.Dur
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, err
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
md, _ := utils.MakeMetadata(headers, method)
|
md, _ := makeMetadata(headers, method)
|
||||||
ctx := metadata.NewOutgoingContext(context.Background(), md)
|
ctx := metadata.NewOutgoingContext(context.Background(), md)
|
||||||
ctx, cancel := context.WithTimeout(ctx, timeout)
|
ctx, cancel := context.WithTimeout(ctx, timeout)
|
||||||
stream, err := cli.RequestStream(ctx)
|
stream, err := cli.RequestStream(ctx)
|
||||||
@@ -42,35 +125,23 @@ func openStream(headers *fasthttp.RequestHeader, method string, timeout time.Dur
|
|||||||
return stream, cancel, nil
|
return stream, cancel, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func transferFile(f multipart.File, stream isp.BackendService_RequestStreamClient,
|
func makeMetadata(r *fasthttp.RequestHeader, method string) (metadata.MD, string) {
|
||||||
buffer []byte, ctx *fasthttp.RequestCtx) (bool, bool) {
|
method = strings.TrimPrefix(method, "/api/")
|
||||||
|
md := metadata.Pairs(utils.ProxyMethodNameHeader, method)
|
||||||
ok := true
|
r.VisitAll(func(key, v []byte) {
|
||||||
eof := false
|
lowerHeader := strings.ToLower(string(key))
|
||||||
for {
|
if len(v) > 0 && strings.HasPrefix(lowerHeader, "x-") {
|
||||||
n, err := f.Read(buffer)
|
md = metadata.Join(md, metadata.Pairs(lowerHeader, string(v)))
|
||||||
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 {
|
return md, method
|
||||||
err = stream.Send(s.FileEnd())
|
|
||||||
ok, eof = checkError(err, ctx)
|
|
||||||
}
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return ok, eof
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func checkError(err error, ctx *fasthttp.RequestCtx) (bool, bool) {
|
func checkError(err error, ctx *fasthttp.RequestCtx) (bool, bool) {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err != io.EOF {
|
if err != io.EOF {
|
||||||
utils.LogRequestHandlerError(log_code.TypeData.GetFile, "", err)
|
logHandlerError(log_code.TypeData.GetFile, "", err)
|
||||||
utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, ctx)
|
u.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, ctx)
|
||||||
return false, false
|
return false, false
|
||||||
}
|
}
|
||||||
return true, true
|
return true, true
|
||||||
|
|||||||
@@ -1,34 +1,39 @@
|
|||||||
package grpc
|
package handlers
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/integration-system/isp-lib/backend"
|
"github.com/integration-system/isp-lib/backend"
|
||||||
u "github.com/integration-system/isp-lib/utils"
|
u "github.com/integration-system/isp-lib/utils"
|
||||||
"github.com/valyala/fasthttp"
|
"github.com/valyala/fasthttp"
|
||||||
"isp-gate-service/proxy/grpc/handlers"
|
"isp-gate-service/utils"
|
||||||
"isp-gate-service/proxy/grpc/utils"
|
|
||||||
"mime"
|
"mime"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Handler interface {
|
var Handler handlerHelper
|
||||||
Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient)
|
|
||||||
}
|
|
||||||
|
|
||||||
func SetHandler(ctx *fasthttp.RequestCtx) Handler {
|
type (
|
||||||
isMultipart := isMultipart(ctx)
|
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"
|
isExpectFile := string(ctx.Request.Header.Peek(u.ExpectFileHeader)) == "true"
|
||||||
|
|
||||||
if isMultipart {
|
if isMultipart {
|
||||||
ctx.Response.Header.SetContentType(utils.JsonContentType)
|
ctx.Response.Header.SetContentType(utils.JsonContentType)
|
||||||
return handlers.SendMultipartData
|
return sendMultipartData
|
||||||
} else if isExpectFile {
|
} else if isExpectFile {
|
||||||
return handlers.GetFile
|
return getFile
|
||||||
} else {
|
} else {
|
||||||
ctx.Response.Header.SetContentType(utils.JsonContentType)
|
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() {
|
if !ctx.IsPost() {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
@@ -7,26 +7,27 @@ import (
|
|||||||
s "github.com/integration-system/isp-lib/streaming"
|
s "github.com/integration-system/isp-lib/streaming"
|
||||||
u "github.com/integration-system/isp-lib/utils"
|
u "github.com/integration-system/isp-lib/utils"
|
||||||
log "github.com/integration-system/isp-log"
|
log "github.com/integration-system/isp-log"
|
||||||
|
"github.com/pkg/errors"
|
||||||
"github.com/valyala/fasthttp"
|
"github.com/valyala/fasthttp"
|
||||||
"google.golang.org/grpc/codes"
|
"google.golang.org/grpc/codes"
|
||||||
"io"
|
"io"
|
||||||
"isp-gate-service/conf"
|
"isp-gate-service/conf"
|
||||||
"isp-gate-service/log_code"
|
"isp-gate-service/log_code"
|
||||||
"isp-gate-service/proxy/grpc/utils"
|
"isp-gate-service/utils"
|
||||||
"strconv"
|
"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)
|
cfg := config.GetRemote().(*conf.RemoteConfig)
|
||||||
timeout := cfg.GetStreamInvokeTimeout()
|
timeout := cfg.GetStreamInvokeTimeout()
|
||||||
|
|
||||||
req, err := utils.ReadJsonBody(ctx)
|
req, err := g.readJsonBody(ctx)
|
||||||
if err != nil {
|
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)
|
utils.SendError(err.Error(), codes.InvalidArgument, nil, ctx)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -38,7 +39,7 @@ func (getFile) Complete(ctx *fasthttp.RequestCtx, method string, client *backend
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
if err != nil {
|
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)
|
utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, ctx)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -47,7 +48,7 @@ func (getFile) Complete(ctx *fasthttp.RequestCtx, method string, client *backend
|
|||||||
value := u.ConvertInterfaceToGrpcStruct(req)
|
value := u.ConvertInterfaceToGrpcStruct(req)
|
||||||
err := stream.Send(backend.WrapBody(value))
|
err := stream.Send(backend.WrapBody(value))
|
||||||
if err != nil {
|
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)
|
utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, ctx)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -55,7 +56,7 @@ func (getFile) Complete(ctx *fasthttp.RequestCtx, method string, client *backend
|
|||||||
|
|
||||||
msg, err := stream.Recv()
|
msg, err := stream.Recv()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
bytes, status, err := utils.GetResponse(nil, err)
|
bytes, status, err := getResponse(nil, err)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
ctx.SetStatusCode(status)
|
ctx.SetStatusCode(status)
|
||||||
ctx.SetBody(bytes)
|
ctx.SetBody(bytes)
|
||||||
@@ -65,7 +66,7 @@ func (getFile) Complete(ctx *fasthttp.RequestCtx, method string, client *backend
|
|||||||
bf := s.BeginFile{}
|
bf := s.BeginFile{}
|
||||||
err = bf.FromMessage(msg)
|
err = bf.FromMessage(msg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
bytes, status, err := utils.GetResponse(nil, err)
|
bytes, status, err := getResponse(nil, err)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
ctx.SetStatusCode(status)
|
ctx.SetStatusCode(status)
|
||||||
ctx.SetBody(bytes)
|
ctx.SetBody(bytes)
|
||||||
@@ -87,7 +88,7 @@ func (getFile) Complete(ctx *fasthttp.RequestCtx, method string, client *backend
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
utils.LogRequestHandlerError(log_code.TypeData.GetFile, method, err)
|
logHandlerError(log_code.TypeData.GetFile, method, err)
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
bytes := msg.GetBytesBody()
|
bytes := msg.GetBytesBody()
|
||||||
@@ -100,8 +101,30 @@ func (getFile) Complete(ctx *fasthttp.RequestCtx, method string, client *backend
|
|||||||
}
|
}
|
||||||
_, err = ctx.Write(bytes)
|
_, err = ctx.Write(bytes)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
utils.LogRequestHandlerError(log_code.TypeData.GetFile, method, err)
|
logHandlerError(log_code.TypeData.GetFile, method, err)
|
||||||
break
|
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
|
||||||
|
}
|
||||||
@@ -12,16 +12,16 @@ import (
|
|||||||
"isp-gate-service/conf"
|
"isp-gate-service/conf"
|
||||||
"isp-gate-service/journal"
|
"isp-gate-service/journal"
|
||||||
"isp-gate-service/log_code"
|
"isp-gate-service/log_code"
|
||||||
"isp-gate-service/proxy/grpc/utils"
|
|
||||||
"isp-gate-service/service"
|
"isp-gate-service/service"
|
||||||
|
"isp-gate-service/utils"
|
||||||
"time"
|
"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, err := utils.ReadJsonBody(c)
|
||||||
body := c.Request.Body()
|
body := c.Request.Body()
|
||||||
/*if err != nil {
|
/*if err != nil {
|
||||||
@@ -30,7 +30,7 @@ func (p handleJson) Complete(c *fasthttp.RequestCtx, method string, client *back
|
|||||||
return
|
return
|
||||||
}*/
|
}*/
|
||||||
|
|
||||||
md, methodName := utils.MakeMetadata(&c.Request.Header, method)
|
md, methodName := makeMetadata(&c.Request.Header, method)
|
||||||
ctx := metadata.NewOutgoingContext(context.Background(), md)
|
ctx := metadata.NewOutgoingContext(context.Background(), md)
|
||||||
cfg := config.GetRemote().(*conf.RemoteConfig)
|
cfg := config.GetRemote().(*conf.RemoteConfig)
|
||||||
ctx, cancel := context.WithTimeout(ctx, cfg.GetSyncInvokeTimeout())
|
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()
|
cli, err := client.Conn()
|
||||||
if err != nil {
|
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)
|
utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, c)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -53,7 +53,7 @@ func (p handleJson) Complete(c *fasthttp.RequestCtx, method string, client *back
|
|||||||
)
|
)
|
||||||
service.Metrics.UpdateRouterResponseTime(time.Since(currentTime) / 1e6)
|
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.SetStatusCode(status)
|
||||||
_, _ = c.Write(data)
|
_, _ = c.Write(data)
|
||||||
if cfg.Journal.Enable && service.JournalMethodsMatcher.Match(methodName) {
|
if cfg.Journal.Enable && service.JournalMethodsMatcher.Match(methodName) {
|
||||||
@@ -68,7 +68,7 @@ func (p handleJson) Complete(c *fasthttp.RequestCtx, method string, client *back
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} 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)
|
utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, c)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3,20 +3,22 @@ package handlers
|
|||||||
import (
|
import (
|
||||||
"github.com/integration-system/isp-lib/backend"
|
"github.com/integration-system/isp-lib/backend"
|
||||||
"github.com/integration-system/isp-lib/config"
|
"github.com/integration-system/isp-lib/config"
|
||||||
|
isp "github.com/integration-system/isp-lib/proto/stubs"
|
||||||
s "github.com/integration-system/isp-lib/streaming"
|
s "github.com/integration-system/isp-lib/streaming"
|
||||||
"github.com/valyala/fasthttp"
|
"github.com/valyala/fasthttp"
|
||||||
"google.golang.org/grpc/codes"
|
"google.golang.org/grpc/codes"
|
||||||
"isp-gate-service/conf"
|
"isp-gate-service/conf"
|
||||||
"isp-gate-service/log_code"
|
"isp-gate-service/log_code"
|
||||||
"isp-gate-service/proxy/grpc/utils"
|
"isp-gate-service/utils"
|
||||||
|
"mime/multipart"
|
||||||
"strings"
|
"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)
|
cfg := config.GetRemote().(*conf.RemoteConfig)
|
||||||
timeout := cfg.GetStreamInvokeTimeout()
|
timeout := cfg.GetStreamInvokeTimeout()
|
||||||
bufferSize := cfg.GetTransferFileBufferSize()
|
bufferSize := cfg.GetTransferFileBufferSize()
|
||||||
@@ -28,7 +30,7 @@ func (sendMultipartData) Complete(ctx *fasthttp.RequestCtx, method string, clien
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
if err != nil {
|
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)
|
utils.SendError(errorMsgInternal, codes.Internal, []interface{}{err.Error()}, ctx)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -41,7 +43,7 @@ func (sendMultipartData) Complete(ctx *fasthttp.RequestCtx, method string, clien
|
|||||||
}()
|
}()
|
||||||
|
|
||||||
if err != nil {
|
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)
|
utils.SendError(errorMsgInvalidArg, codes.InvalidArgument, []interface{}{err.Error()}, ctx)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -83,9 +85,9 @@ func (sendMultipartData) Complete(ctx *fasthttp.RequestCtx, method string, clien
|
|||||||
if ok, eof = checkError(err, ctx); !ok || eof {
|
if ok, eof = checkError(err, ctx); !ok || eof {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
if ok, eof = transferFile(f, stream, buffer, ctx); ok {
|
if ok, eof = h.transferFile(f, stream, buffer, ctx); ok {
|
||||||
msg, err := stream.Recv()
|
msg, err := stream.Recv()
|
||||||
v, _, err := utils.GetResponse(msg, err)
|
v, _, err := getResponse(msg, err)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
response = append(response, string(v))
|
response = append(response, string(v))
|
||||||
}
|
}
|
||||||
@@ -99,14 +101,38 @@ func (sendMultipartData) Complete(ctx *fasthttp.RequestCtx, method string, clien
|
|||||||
|
|
||||||
err = stream.CloseSend()
|
err = stream.CloseSend()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
utils.LogRequestHandlerError(log_code.TypeData.SendMultipart, method, err)
|
logHandlerError(log_code.TypeData.SendMultipart, method, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if ok {
|
if ok {
|
||||||
arrayBody := strings.Join(response, ",")
|
arrayBody := strings.Join(response, ",")
|
||||||
_, err = ctx.WriteString("[" + arrayBody + "]")
|
_, err = ctx.WriteString("[" + arrayBody + "]")
|
||||||
if err != nil {
|
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
|
||||||
|
}
|
||||||
@@ -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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -4,7 +4,9 @@ import (
|
|||||||
"github.com/integration-system/isp-lib/structure"
|
"github.com/integration-system/isp-lib/structure"
|
||||||
log "github.com/integration-system/isp-log"
|
log "github.com/integration-system/isp-log"
|
||||||
"github.com/valyala/fasthttp"
|
"github.com/valyala/fasthttp"
|
||||||
|
"google.golang.org/grpc/codes"
|
||||||
"isp-gate-service/log_code"
|
"isp-gate-service/log_code"
|
||||||
|
"isp-gate-service/utils"
|
||||||
"net"
|
"net"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
@@ -31,7 +33,9 @@ func (p *httpProxy) Consumer(addressList []structure.AddressConfiguration) bool
|
|||||||
|
|
||||||
func (p *httpProxy) ProxyRequest(ctx *fasthttp.RequestCtx) {
|
func (p *httpProxy) ProxyRequest(ctx *fasthttp.RequestCtx) {
|
||||||
if p.client == nil {
|
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
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+14
-82
@@ -1,16 +1,20 @@
|
|||||||
package redis
|
package redis
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"github.com/go-redis/redis"
|
|
||||||
"github.com/integration-system/isp-lib/config"
|
|
||||||
rd "github.com/integration-system/isp-lib/redis"
|
rd "github.com/integration-system/isp-lib/redis"
|
||||||
"github.com/integration-system/isp-lib/structure"
|
"github.com/integration-system/isp-lib/structure"
|
||||||
"github.com/pkg/errors"
|
log "github.com/integration-system/isp-log"
|
||||||
"isp-gate-service/conf"
|
"isp-gate-service/log_code"
|
||||||
)
|
)
|
||||||
|
|
||||||
var Client = &redisClient{cli: rd.NewRxClient()}
|
var Client = &redisClient{
|
||||||
|
cli: rd.NewRxClient(
|
||||||
|
rd.WithInitHandler(func(c *rd.Client, err error) {
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(log_code.ErrorClientRedis, err)
|
||||||
|
}
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
|
||||||
type redisClient struct {
|
type redisClient struct {
|
||||||
cli *rd.RxClient
|
cli *rd.RxClient
|
||||||
@@ -20,82 +24,10 @@ func (c *redisClient) ReceiveConfiguration(configuration structure.RedisConfigur
|
|||||||
c.cli.ReceiveConfiguration(configuration)
|
c.cli.ReceiveConfiguration(configuration)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *redisClient) GetTokens(appToken string) (map[string]string, error) {
|
func (c *redisClient) Get() *rd.RxClient {
|
||||||
if c.cli == nil {
|
return c.cli
|
||||||
return nil, errors.New("client undefined")
|
|
||||||
}
|
|
||||||
|
|
||||||
instanceUuid := config.Get().(*conf.Configuration).InstanceUuid
|
|
||||||
key := fmt.Sprintf("%s|%s", appToken, instanceUuid)
|
|
||||||
|
|
||||||
if resp, err := c.cli.Pipelined(func(p redis.Pipeliner) error {
|
|
||||||
if cmd := p.Select(int(rd.ApplicationTokenDb)); cmd.Err() != nil {
|
|
||||||
return cmd.Err()
|
|
||||||
}
|
|
||||||
p.HGetAll(key)
|
|
||||||
return nil
|
|
||||||
}); err != nil {
|
|
||||||
return nil, err
|
|
||||||
} else {
|
|
||||||
if len(resp) < 2 || resp[1].Err() == redis.Nil {
|
|
||||||
return nil, nil
|
|
||||||
} else if resp[1].Err() != nil {
|
|
||||||
return nil, err
|
|
||||||
} else if stringStringMapCmd, ok := resp[1].(*redis.StringStringMapCmd); !ok {
|
|
||||||
return nil, nil
|
|
||||||
} else {
|
|
||||||
return stringStringMapCmd.Val(), nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *redisClient) CheckTokens(t map[string]string) (map[string]string, error) {
|
func (c *redisClient) Close() {
|
||||||
secondDbKey := fmt.Sprintf("%s|%s", t[ApplicationIdentity], t[Uri])
|
_ = c.cli.Close()
|
||||||
thirdDbKey := fmt.Sprintf("%s|%s", t[UserToken], t[DomainIdentity])
|
|
||||||
fifthDbKey := fmt.Sprintf("%s|%s", t[DeviceToken], t[DomainIdentity])
|
|
||||||
|
|
||||||
if resp, err := c.cli.Pipelined(func(p redis.Pipeliner) error {
|
|
||||||
if cmd := p.Select(int(rd.ApplicationPermissionDb)); cmd.Err() != nil && cmd.Err() != redis.Nil {
|
|
||||||
return cmd.Err()
|
|
||||||
}
|
|
||||||
p.Get(secondDbKey)
|
|
||||||
|
|
||||||
if cmd := p.Select(int(rd.UserTokenDb)); cmd.Err() != nil && cmd.Err() != redis.Nil {
|
|
||||||
return cmd.Err()
|
|
||||||
}
|
|
||||||
p.Get(thirdDbKey)
|
|
||||||
|
|
||||||
if cmd := p.Select(int(rd.DeviceTokenDb)); cmd.Err() != nil && cmd.Err() != redis.Nil {
|
|
||||||
return cmd.Err()
|
|
||||||
}
|
|
||||||
p.Get(fifthDbKey)
|
|
||||||
return nil
|
|
||||||
}); err != nil && err != redis.Nil {
|
|
||||||
return t, err
|
|
||||||
} else {
|
|
||||||
// It is not permitted to call this methodParts
|
|
||||||
if fineCmd(resp, 1) {
|
|
||||||
if intCmd, ok := resp[1].(*redis.IntCmd); ok && intCmd.Val() == 0 {
|
|
||||||
return t, errors.New("invalid token")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// ===== CHECK USER TOKEN =====
|
|
||||||
if fineCmd(resp, 3) {
|
|
||||||
if stringCmd, ok := resp[3].(*redis.StringCmd); ok {
|
|
||||||
t[UserIdentity] = stringCmd.Val()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// ===== CHECK DEVICE TOKEN =====
|
|
||||||
if fineCmd(resp, 5) {
|
|
||||||
if stringCmd, ok := resp[5].(*redis.StringCmd); ok {
|
|
||||||
t[DeviceIdentity] = stringCmd.Val()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return t, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func fineCmd(cmders []redis.Cmder, arrayKey int) bool {
|
|
||||||
return len(cmders) > arrayKey+1 && cmders[arrayKey] != nil &&
|
|
||||||
(cmders[arrayKey].Err() == nil || cmders[arrayKey].Err() == redis.Nil)
|
|
||||||
}
|
}
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
package redis
|
|
||||||
|
|
||||||
const (
|
|
||||||
SystemIdentity = "1"
|
|
||||||
DomainIdentity = "2"
|
|
||||||
ServiceIdentity = "3"
|
|
||||||
ApplicationIdentity = "4"
|
|
||||||
|
|
||||||
DeviceIdentity = "5"
|
|
||||||
UserIdentity = "6"
|
|
||||||
|
|
||||||
DeviceToken = "7"
|
|
||||||
UserToken = "8"
|
|
||||||
Uri = "9"
|
|
||||||
)
|
|
||||||
+10
-2
@@ -22,7 +22,7 @@ func (s *httpSrv) Init(MaxRequestBodySize int64) {
|
|||||||
s.mx.Lock()
|
s.mx.Lock()
|
||||||
if s.srv != nil {
|
if s.srv != nil {
|
||||||
if err := s.srv.Shutdown(); err != nil {
|
if err := s.srv.Shutdown(); err != nil {
|
||||||
log.Warn(log_code.WarnCreateRestServerHttpSrvShutdown, err)
|
log.Warn(log_code.WarnHttpServerShutdown, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
maxRequestBodySize := MaxRequestBodySize
|
maxRequestBodySize := MaxRequestBodySize
|
||||||
@@ -36,8 +36,16 @@ func (s *httpSrv) Init(MaxRequestBodySize int64) {
|
|||||||
}
|
}
|
||||||
go func() {
|
go func() {
|
||||||
if err := s.srv.ListenAndServe(restAddress); err != nil {
|
if err := s.srv.ListenAndServe(restAddress); err != nil {
|
||||||
log.Error(log_code.ErrorCreateRestServerHttpSrvListenAndServe, err)
|
log.Error(log_code.ErrorHttpServerListen, err)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
s.mx.Unlock()
|
s.mx.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *httpSrv) Close() {
|
||||||
|
if s.srv != nil {
|
||||||
|
if err := s.srv.Shutdown(); err != nil {
|
||||||
|
log.Warn(log_code.WarnHttpServerShutdown, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
Reference in new issue
Block a user