Merge branch 'MSP-325' into 'master'

Resolve MSP-325

Closes MSP-325

See merge request integration-system/isp-gate-service!4
This commit is contained in:
Грязнов Денис Владимирович committed 2021-10-22 11:58:30 +00:00
commit 97912e5d5a
24 files changed
+430 -122

No files matched your search

+1 -1
View File
@@ -1 +1 @@
2.7.6
2.8.0
+4
View File
@@ -1,3 +1,7 @@
### v2.8.0
* add new logger
* remove journal
* add identities to requests log
### v2.7.6
* updated dependencies
* migrated to common local config
+2 -2
View File
@@ -8,7 +8,7 @@ import (
"isp-gate-service/conf"
"isp-gate-service/entity"
"isp-gate-service/log_code"
"isp-gate-service/model"
"isp-gate-service/repository"
"isp-gate-service/service/matcher"
"sync"
"time"
@@ -110,7 +110,7 @@ func (w *accountingWorker) recoveryAccounting(appId int32, limitStates map[strin
importNotComplete = true
)
dbSnapshot, err := model.SnapshotRep.GetByApplication(appId)
dbSnapshot, err := repository.SnapshotRep.GetByApplication(appId)
if err != nil {
log.Warn(log_code.ErrorSnapshotAccounting, err)
}
+4 -4
View File
@@ -5,7 +5,7 @@ import (
"github.com/stretchr/testify/assert"
"isp-gate-service/conf"
"isp-gate-service/entity"
"isp-gate-service/model"
"isp-gate-service/repository"
"sync"
"testing"
"time"
@@ -65,7 +65,7 @@ var (
func TestAccounting(t *testing.T) {
a := assert.New(t)
snapshotRep := newSnapshotRepository(false)
model.SnapshotRep = snapshotRep
repository.SnapshotRep = snapshotRep
worker = &accountingWorker{
accountingStorage: make(map[int32]Accounting),
requestsStoring: make(map[int32]bool),
@@ -115,7 +115,7 @@ func TestAccounting(t *testing.T) {
func TestWorker_recoveryAccounting(t *testing.T) {
a := assert.New(t)
snapshotRep := newSnapshotRepository(true)
model.SnapshotRep = snapshotRep
repository.SnapshotRep = snapshotRep
worker = &accountingWorker{
accountingStorage: make(map[int32]Accounting),
@@ -138,7 +138,7 @@ func TestWorker_recoveryAccounting(t *testing.T) {
time.Sleep(time.Millisecond * 300)
a.True(snapshotRep.Wait())
snapshot, err := model.SnapshotRep.GetByApplication(appId)
snapshot, err := repository.SnapshotRep.GetByApplication(appId)
a.NoError(err)
a.NotNil(snapshot)
a.Equal(len(request), int(snapshot.Version))
+2 -2
View File
@@ -5,7 +5,7 @@ import (
"github.com/integration-system/isp-log/stdcodes"
"isp-gate-service/entity"
"isp-gate-service/log_code"
"isp-gate-service/model"
"isp-gate-service/repository"
"sync"
"time"
)
@@ -66,7 +66,7 @@ func (t *snapshotTask) run(timeout time.Duration) {
}
func (t *snapshotTask) unload(list []entity.Snapshot) {
if err := model.SnapshotRep.Update(list); err != nil {
if err := repository.SnapshotRep.Update(list); err != nil {
log.Error(log_code.ErrorSnapshotAccounting, err)
}
t.wg.Done()
+2 -2
View File
@@ -6,7 +6,7 @@ import (
"isp-gate-service/conf"
"isp-gate-service/entity"
"isp-gate-service/log_code"
"isp-gate-service/model"
"isp-gate-service/repository"
"sync"
"time"
)
@@ -100,7 +100,7 @@ func (t *storingTask) run(timeout time.Duration) {
}
func (t *storingTask) unload(cache []entity.Request) {
if err := model.RequestsRep.Insert(cache); err != nil {
if err := repository.RequestsRep.Insert(cache); err != nil {
log.Error(log_code.ErrorUnloadAccounting, err)
}
t.wg.Done()
+8 -7
View File
@@ -1,13 +1,14 @@
package accounting
import (
"github.com/stretchr/testify/assert"
"isp-gate-service/conf"
"isp-gate-service/entity"
"isp-gate-service/model"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"isp-gate-service/conf"
"isp-gate-service/entity"
"isp-gate-service/repository"
)
var (
@@ -28,10 +29,10 @@ var (
)
func initStoring(setting conf.StoringSetting) *requestsRepository {
repository := &requestsRepository{cache: make([]entity.Request, 0), wg: &sync.WaitGroup{}}
model.RequestsRep = repository
rep := &requestsRepository{cache: make([]entity.Request, 0), wg: &sync.WaitGroup{}}
repository.RequestsRep = rep
InitStoringTask(setting)
return repository
return rep
}
func wait(wg *sync.WaitGroup) bool {
+11 -7
View File
@@ -42,6 +42,7 @@ type (
verifiable struct {
appId int32
adminId int64
ctx *fasthttp.RequestCtx
path string
headers map[string]string
@@ -60,7 +61,7 @@ func ReceiveConfiguration(conf conf.Cache) {
}
}
func Do(ctx *fasthttp.RequestCtx, path string) (int32, error) {
func Do(ctx *fasthttp.RequestCtx, path string) (int32, int64, error) {
for _, notExpectedHeader := range notExpectedHeaders {
ctx.Request.Header.Del(notExpectedHeader)
}
@@ -68,27 +69,27 @@ func Do(ctx *fasthttp.RequestCtx, path string) (int32, error) {
verifiable := newVerifiable(ctx, path)
err := verifiable.verifyAppToken()
if err != nil {
return 0, err
return 0, 0, err
}
err = verifiable.verifyUserToken()
if err != nil {
return 0, err
return 0, 0, err
}
verifiable.setHeaders()
err = verifiable.checkInnerMethods()
if err != nil {
return 0, err
return 0, 0, err
}
err = verifiable.checkUserMethods()
if err != nil {
return 0, err
return 0, 0, err
}
return verifiable.appId, nil
return verifiable.appId, verifiable.adminId, nil
}
func newVerifiable(ctx *fasthttp.RequestCtx, path string) *verifiable {
@@ -96,6 +97,7 @@ func newVerifiable(ctx *fasthttp.RequestCtx, path string) *verifiable {
ctx: ctx,
path: path,
appId: -1,
adminId: -1,
headers: make(map[string]string),
}
}
@@ -179,9 +181,11 @@ func (v *verifiable) checkInnerMethods() error {
if adminToken == "" {
return createError("unauthorized", codes.Unauthenticated, "admin token required")
}
if verifyToken.Admin(adminToken) != nil {
adminId, err := verifyToken.Admin(adminToken)
if err != nil {
return createError("unauthorized", codes.Unauthenticated, "received invalid admin token")
}
v.adminId = adminId
}
return nil
}
+15 -3
View File
@@ -23,12 +23,24 @@ type userClaims struct {
UserId int64
}
type adminClaims struct {
*jwt.StandardClaims
Id int64
}
type token struct{}
func (t token) Admin(token string) error {
func (t token) Admin(token string) (int64, error) {
secret := config.GetRemote().(*conf.RemoteConfig).TokensSetting.AdminSecret
_, err := t.parse(token, secret, jwt.MapClaims{})
return err
parsed, err := t.parse(token, secret, &adminClaims{StandardClaims: &jwt.StandardClaims{}})
if err != nil {
return 0, err
}
claims, ok := parsed.Claims.(*adminClaims)
if !ok {
return 0, errInvalidToken
}
return claims.Id, nil
}
func (t token) Application(token string) (int32, error) {
+11 -4
View File
@@ -2,9 +2,9 @@
package conf
import (
"github.com/integration-system/isp-journal/rx"
"github.com/integration-system/isp-lib/v2/structure"
"time"
"github.com/integration-system/isp-lib/v2/structure"
)
const (
@@ -38,8 +38,15 @@ type (
}
Journal struct {
Journal rx.Config `schema:"Настройка конфигурации"`
MethodsPatterns []string `schema:"Список методов для логирования,список строк вида: 'module/group/method'(* - для частичного совпадения). При обработке запроса, если вызываемый метод совпадает со строкой из списка, тела запроса и ответа записываются в лог"`
Journal JorunalConfig `schema:"Настройка конфигурации"`
MethodsPatterns []string `schema:"Список методов для логирования,список строк вида: 'module/group/method'(* - для частичного совпадения). При обработке запроса, если вызываемый метод совпадает со строкой из списка, тела запроса и ответа записываются в лог"`
}
JorunalConfig struct {
Enable bool `schema:"Включение/отключение журналирования"`
Filename string `schema:"Имя файла,путь до файла в который будут записываться логи"`
MaxSizeMb int `schema:"Максимальный размер файла,ограничение по размеру файла после достижения которого логи будут записываться в новый файл"`
Compress bool `schema:"Сжатие логов,архивирует файлы в gzip"`
}
TokensSetting struct {
+2 -1
View File
@@ -9,7 +9,6 @@ require (
github.com/go-redis/redis/v8 v8.8.2
github.com/golang/protobuf v1.5.2
github.com/integration-system/go-cmp v0.0.0-20190131081942-ac5582987a2f
github.com/integration-system/isp-journal v1.5.0
github.com/integration-system/isp-lib/v2 v2.8.7
github.com/integration-system/isp-log v1.1.8
github.com/json-iterator/go v1.1.11
@@ -18,7 +17,9 @@ require (
github.com/spf13/cast v1.4.0
github.com/stretchr/testify v1.7.0
github.com/valyala/fasthttp v1.28.0
go.uber.org/zap v1.17.0
golang.org/x/net v0.0.0-20210510120150-4163338589ed
google.golang.org/grpc v1.38.0
google.golang.org/protobuf v1.26.0
gopkg.in/natefinch/lumberjack.v2 v2.0.0
)
+6 -6
View File
@@ -49,6 +49,7 @@ github.com/Azure/go-autorest/autorest/to v0.4.0/go.mod h1:fE8iZBn7LQR7zH/9XU2NcP
github.com/Azure/go-autorest/autorest/validation v0.3.1/go.mod h1:yhLgjC0Wda5DYXl6JAsWyUe4KVNffhoDhG0zVzUMo3E=
github.com/Azure/go-autorest/logger v0.2.1/go.mod h1:T9E3cAhj2VqvPOtCYAvby9aBXkZmbF5NWuPV8+WeEW8=
github.com/Azure/go-autorest/tracing v0.6.0/go.mod h1:+vhtPC754Xsa23ID7GlGsrdKBpUA79WCAKPPZVC2DeU=
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/DataDog/datadog-go v2.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ=
@@ -390,7 +391,6 @@ github.com/integration-system/go-cmp v0.0.0-20190131081942-ac5582987a2f h1:52UOJ
github.com/integration-system/go-cmp v0.0.0-20190131081942-ac5582987a2f/go.mod h1:w+dmaWojuIwNujSYg6qt1wKHhSdorLOivCEl/XuLzbM=
github.com/integration-system/gowsdl v1.0.0 h1:rDv5HrzNUs6aWTj9roSDS9ZdIf58FzF0YVP2nusvbto=
github.com/integration-system/gowsdl v1.0.0/go.mod h1:ZwTCE+Av5aQLnPj2/3PIop6mzCs1FY7jXrcWDvSjrBA=
github.com/integration-system/isp-etp-go/v2 v2.1.0/go.mod h1:Ndq5DMM3sDJjZn4cyKKvZrVED0FMeoXMRWHZTq+2Z1o=
github.com/integration-system/isp-etp-go/v2 v2.1.1/go.mod h1:Ndq5DMM3sDJjZn4cyKKvZrVED0FMeoXMRWHZTq+2Z1o=
github.com/integration-system/isp-etp-go/v2 v2.1.2/go.mod h1:fSkS09/engepaDDqaDAEeXUpzmtcMpSLjilZ35BfNcc=
github.com/integration-system/isp-etp-go/v2 v2.1.3 h1:vcHP/PE7p1G3rxqoVKrKtXzoSxFA4ryxigd+zPkAb3w=
@@ -399,15 +399,10 @@ github.com/integration-system/isp-event-lib v1.6.0/go.mod h1:lCzAci6oS+vc51W8EfH
github.com/integration-system/isp-event-lib v1.6.1/go.mod h1:5ZIXsMG3gC7sfQ+eICjkDpy2RSvSAxV3Cq1BVN8LFIk=
github.com/integration-system/isp-event-lib v1.6.5 h1:cHjQmp5Y48sbVgpF0sCE05INq9m1jh7vh+23Aersrns=
github.com/integration-system/isp-event-lib v1.6.5/go.mod h1:gQg0S8TMeISIkTLM9/DwgWwnpS3BUkNFjgByRg3+Ub0=
github.com/integration-system/isp-io v0.0.0-20190723122940-3daf588d878f h1:nJGOobuawo5d3QgoLl1i2SJVDIHkxMl0bhH1+iqZmnk=
github.com/integration-system/isp-io v0.0.0-20190723122940-3daf588d878f/go.mod h1:1cjy4g5F8WXrOB3l/bL3mw+TCWDppOL1pz08wOAMi9Y=
github.com/integration-system/isp-journal v1.5.0 h1:7Lpt7dHhpq1zRY4qRRYUMiEnaQZbxyPHRcy/ik/Vm8I=
github.com/integration-system/isp-journal v1.5.0/go.mod h1:B6cLJqjNL+XHWv4IzKt5aIZ7AjbHX2tQFXgRSaWNNIo=
github.com/integration-system/isp-lib-test v1.5.4/go.mod h1:rD+X0QMiOIeJDhqwB4avdYhnc1hoEkL4z+7C7lwTuOA=
github.com/integration-system/isp-lib-test v1.6.0/go.mod h1:If5QK5jsXE48DZuq6WzCw8yC22k7GogLrEnMngXiE2Y=
github.com/integration-system/isp-lib-test v1.6.4 h1:5n2Srk9pjAUqllYMxWid3yaJIiejLfZj2rN70AzZa5o=
github.com/integration-system/isp-lib-test v1.6.4/go.mod h1:k8DiXG/Bx3k8cft0QI/+BTRsL/43effW5575udzWv1M=
github.com/integration-system/isp-lib/v2 v2.3.1/go.mod h1:eRSmS3+S8WXTUKu7YtSimFJDrLF+/esM/989NBEsP2o=
github.com/integration-system/isp-lib/v2 v2.4.0/go.mod h1:hxyzKBD7eIf6Hm4x6zRsLW5p8m/aFeqeezKMFYBAtho=
github.com/integration-system/isp-lib/v2 v2.6.2/go.mod h1:ZGW7qQsCuELBHRBnSSDSEonPx+FxAfHiAfwsGQZzVO4=
github.com/integration-system/isp-lib/v2 v2.8.4/go.mod h1:bKFyatmLqEkaQWJjww0R1Dz+cRn8T7YSaf4VrROgeTw=
@@ -757,14 +752,17 @@ go.opentelemetry.io/otel/trace v0.19.0 h1:1ucYlenXIDA1OlHVLDZKX0ObXV5RLaq06DtUKz
go.opentelemetry.io/otel/trace v0.19.0/go.mod h1:4IXiNextNOpPnRlI4ryK69mn5iC84bjBWZQA5DXz/qg=
go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ=
go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw=
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A=
go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0=
go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4=
go.uber.org/multierr v1.6.0 h1:y6IPFStTAIT5Ytl7/XYmHvzXQ7S3g/IeZW9hyZ5thw4=
go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU=
go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA=
go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
go.uber.org/zap v1.14.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM=
go.uber.org/zap v1.17.0 h1:MTjgFu6ZLKvY6Pvaqk97GlxNBuMpV4Hy/3P6tRGlI2U=
go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20180910181607-0e37d006457b/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
@@ -1189,6 +1187,8 @@ gopkg.in/go-playground/validator.v8 v8.18.2/go.mod h1:RX2a/7Ha8BgOhfk7j780h4/u/R
gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/ini.v1 v1.62.0 h1:duBzk771uxoUuOlyRLkHsygud9+5lrlGjdFBb4mSKDU=
gopkg.in/ini.v1 v1.62.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/natefinch/lumberjack.v2 v2.0.0 h1:1Lc07Kr7qY4U2YPouBjpCLxpiyxIVoxqXgkXLknAOE8=
gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k=
gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
+47 -30
View File
@@ -1,21 +1,21 @@
package handler
import (
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/integration-system/isp-lib/v2/config"
log "github.com/integration-system/isp-log"
"github.com/pkg/errors"
"github.com/valyala/fasthttp"
"go.uber.org/zap"
"google.golang.org/grpc/codes"
"isp-gate-service/accounting"
"isp-gate-service/authenticate"
"isp-gate-service/conf"
"isp-gate-service/domain"
"isp-gate-service/invoker"
"isp-gate-service/log_code"
"isp-gate-service/log"
"isp-gate-service/proxy"
"isp-gate-service/routing"
"isp-gate-service/service"
@@ -27,63 +27,80 @@ const (
execution = 1e6
)
var (
errAccounting = errors.New("accounting error")
var errAccounting = errors.New("accounting error")
helper handlerHelper
)
type Handler struct {
logger log.Logger
}
type handlerHelper struct{}
func New(logger log.Logger) *Handler {
return &Handler{
logger: logger,
}
}
func CompleteRequest(ctx *fasthttp.RequestCtx) {
func (h Handler) CompleteRequest(ctx *fasthttp.RequestCtx) {
currentTime := time.Now()
method, resp := helper.AuthenticateAccountingProxy(ctx)
appId, adminId, path, resp := h.authenticateAccountingProxy(ctx)
executionTime := time.Since(currentTime) / execution
statusCode := ctx.Response.StatusCode()
service.Metrics.UpdateStatusCounter(helper.SetMetricStatus(statusCode))
service.Metrics.UpdateStatusCounter(h.setMetricStatus(statusCode))
if statusCode == http.StatusOK {
service.Metrics.UpdateMethodResponseTime(method, executionTime)
service.Metrics.UpdateMethodResponseTime(path, executionTime)
}
logEnable := config.GetRemote().(*conf.RemoteConfig).JournalSetting.Journal.Enable
//nolint
if logEnable && matcher.JournalMethods.Match(method) {
// nolintlint
if logEnable && matcher.JournalMethods.Match(path) {
requestBody, responseBody, err := resp.Get()
fields := []zap.Field{
zap.ByteString("http_method", ctx.Method()),
zap.String("remote_addr", ctx.RemoteAddr().String()),
zap.ByteString("x_forwarded_for", ctx.Request.Header.Peek("X-Forwarded-For")),
zap.Int("status_code", ctx.Response.StatusCode()),
zap.String("path", path),
zap.Int32("application_id", appId),
zap.Int64("admin_id", adminId),
zap.Any("request", json.RawMessage(requestBody)),
zap.Any("response", json.RawMessage(responseBody)),
zap.Error(err),
}
if err != nil {
if err := invoker.Journal.Error(method, requestBody, responseBody, err); err != nil {
log.Warnf(log_code.WarnJournalCouldNotWriteToFile, "could not write to file journal: %v", err)
}
h.logger.Error(ctx, "unsuccessful request", fields...)
} else {
if err := invoker.Journal.Info(method, requestBody, responseBody); err != nil {
log.Warnf(log_code.WarnJournalCouldNotWriteToFile, "could not write to file journal: %v", err)
}
h.logger.Info(ctx, "successful request", fields...)
}
}
}
func (handlerHelper) AuthenticateAccountingProxy(ctx *fasthttp.RequestCtx) (string, domain.ProxyResponse) {
initialPath := string(ctx.Path())
func (h Handler) authenticateAccountingProxy(ctx *fasthttp.RequestCtx) (int32, int64, string, domain.ProxyResponse) {
var (
appId int32 = -1
adminId int64 = -1
initialPath = string(ctx.Path())
)
p, path := proxy.Find(initialPath)
if p == nil {
msg := fmt.Sprintf("unknown proxy for '%s'", initialPath)
utils.WriteError(ctx, msg, codes.NotFound, nil)
return initialPath, domain.Create().SetError(errors.New(msg))
return appId, adminId, initialPath, domain.Create().SetError(errors.New(msg))
}
if !p.SkipExistCheck() {
if _, ok := routing.AllMethods[path]; !ok {
msg := "not implemented"
utils.WriteError(ctx, msg, codes.Unimplemented, nil)
return path, domain.Create().SetError(errors.New(msg))
return appId, adminId, path, domain.Create().SetError(errors.New(msg))
}
}
if !p.SkipAuth() {
applicationId, err := authenticate.Do(ctx, path)
var err error
appId, adminId, err = authenticate.Do(ctx, path)
if err != nil {
message := "unknown error"
status := codes.Unknown
@@ -94,20 +111,20 @@ func (handlerHelper) AuthenticateAccountingProxy(ctx *fasthttp.RequestCtx) (stri
details = e.Details()
}
utils.WriteError(ctx, message, status, details)
return path, domain.Create().SetError(err)
return appId, adminId, path, domain.Create().SetError(err)
}
if !accounting.AcceptRequest(applicationId, path) {
if !accounting.AcceptRequest(appId, path) {
err := errAccounting
utils.WriteError(ctx, "too many requests", codes.ResourceExhausted, nil)
return path, domain.Create().SetError(err)
return appId, adminId, path, domain.Create().SetError(err)
}
}
return path, p.ProxyRequest(ctx, path)
return appId, adminId, path, p.ProxyRequest(ctx, path)
}
func (handlerHelper) SetMetricStatus(statusCode int) string {
func (Handler) setMetricStatus(statusCode int) string {
metricStatus := "5xx"
switch {
case statusCode >= 100 && statusCode < 200:
-27
View File
@@ -1,27 +0,0 @@
package invoker
import (
"github.com/integration-system/isp-journal/rx"
"github.com/integration-system/isp-lib/v2/backend"
"github.com/integration-system/isp-lib/v2/structure"
"google.golang.org/grpc"
)
type journalService struct {
*rx.RxJournal
}
var (
journalClient = backend.NewRxGrpcClient(
backend.WithDialOptions(grpc.WithInsecure()),
)
Journal = &journalService{RxJournal: rx.NewDefaultRxJournal(journalClient)}
)
func (*journalService) ReceiveServiceAddressList(list []structure.AddressConfiguration) bool {
if ok := journalClient.ReceiveAddressList(list); !ok {
return false
}
go Journal.CollectAndTransferExistedLogs()
return true
}
+25
View File
@@ -0,0 +1,25 @@
package log
import (
"context"
"go.uber.org/zap"
)
type contextLogKey int
var (
contextKey = contextLogKey(-1)
)
func ContextLogValues(ctx context.Context) []zap.Field {
if value, ok := ctx.Value(contextKey).([]zap.Field); ok {
return value
}
return nil
}
func ToContext(ctx context.Context, kvs ...zap.Field) context.Context {
existedValues := append(ContextLogValues(ctx), kvs...)
return context.WithValue(ctx, contextKey, existedValues)
}
+14
View File
@@ -0,0 +1,14 @@
package log
import (
"context"
"go.uber.org/zap"
)
type Logger interface {
Info(ctx context.Context, message interface{}, fields ...zap.Field)
Error(ctx context.Context, message interface{}, fields ...zap.Field)
Debug(ctx context.Context, message interface{}, fields ...zap.Field)
Log(ctx context.Context, level Level, message interface{}, fields ...zap.Field)
}
+85
View File
@@ -0,0 +1,85 @@
package log
import (
"context"
"fmt"
"github.com/pkg/errors"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
type Level zapcore.Level
const (
ErrorLevel = Level(zap.ErrorLevel)
InfoLevel = Level(zap.InfoLevel)
DebugLevel = Level(zap.DebugLevel)
)
// nolint: maligned
type Adapter struct {
devMode bool
rotation *Rotation
initialLevel Level
logger *zap.Logger
level zap.AtomicLevel
}
func New(opts ...Option) (*Adapter, error) {
a := &Adapter{
devMode: false,
rotation: nil,
initialLevel: InfoLevel,
}
for _, opt := range opts {
opt(a)
}
cfg := zap.NewProductionConfig()
if a.devMode {
cfg = zap.NewDevelopmentConfig()
}
if a.rotation != nil {
outputUrl := rotationToUrl(*a.rotation)
cfg.OutputPaths = []string{outputUrl.String()}
}
level := zap.NewAtomicLevelAt(zapcore.Level(a.initialLevel))
cfg.Level = level
logger, err := cfg.Build(zap.WithCaller(false), zap.AddStacktrace(zap.FatalLevel))
if err != nil {
return nil, errors.Wrap(err, "build logger")
}
a.logger = logger
a.level = level
return a, nil
}
func (a *Adapter) Info(ctx context.Context, message interface{}, fields ...zap.Field) {
a.Log(ctx, InfoLevel, message, fields...)
}
func (a *Adapter) Error(ctx context.Context, message interface{}, fields ...zap.Field) {
a.Log(ctx, ErrorLevel, message, fields...)
}
func (a *Adapter) Debug(ctx context.Context, message interface{}, fields ...zap.Field) {
a.Log(ctx, DebugLevel, message, fields...)
}
func (a *Adapter) Log(ctx context.Context, level Level, message interface{}, fields ...zap.Field) {
entry := a.logger.Check(zapcore.Level(level), fmt.Sprintf("%v", message))
if entry != nil {
entry.Write(append(ContextLogValues(ctx), fields...)...)
}
}
func (a *Adapter) SetLevel(level Level) {
a.level.SetLevel(zapcore.Level(level))
}
func (a *Adapter) Close() error {
return a.logger.Sync()
}
+21
View File
@@ -0,0 +1,21 @@
package log
type Option func(a *Adapter)
func WithDevelopmentMode() Option {
return func(a *Adapter) {
a.devMode = true
}
}
func WithFileRotation(r Rotation) Option {
return func(a *Adapter) {
a.rotation = &r
}
}
func WithLevel(level Level) Option {
return func(a *Adapter) {
a.initialLevel = level
}
}
+106
View File
@@ -0,0 +1,106 @@
package log
import (
"io"
"net/url"
"strconv"
"github.com/pkg/errors"
"go.uber.org/zap"
"gopkg.in/natefinch/lumberjack.v2"
)
const (
lumberjackSchema = "lumberjack"
)
func init() {
err := zap.RegisterSink(lumberjackSchema, func(u *url.URL) (zap.Sink, error) {
r, err := rotationFromUrl(u)
if err != nil {
return nil, errors.Wrap(err, "unmarshal rotation config")
}
return newSink(NewFileRotationWriter(*r)), nil
})
if err != nil {
panic(err)
}
}
type Rotation struct {
File string
MaxSizeMb int
MaxDays int
MaxBackups int
Compress bool
}
func rotationToUrl(r Rotation) url.URL {
values := url.Values{
"file": {r.File},
"maxSizeMb": {strconv.Itoa(r.MaxSizeMb)},
"maxDays": {strconv.Itoa(r.MaxDays)},
"maxBackups": {strconv.Itoa(r.MaxBackups)},
"compress": {strconv.FormatBool(r.Compress)},
}
u := url.URL{
Scheme: lumberjackSchema,
RawQuery: values.Encode(),
}
return u
}
func rotationFromUrl(u *url.URL) (*Rotation, error) {
values, err := url.ParseQuery(u.RawQuery)
if err != nil {
return nil, errors.Wrap(err, "parse lumberjack params")
}
file := values.Get("file")
maxSizeMb, err := strconv.Atoi(values.Get("maxSizeMb"))
if err != nil {
return nil, errors.Wrap(err, "parse maxSizeMb")
}
maxDays, err := strconv.Atoi(values.Get("maxDays"))
if err != nil {
return nil, errors.Wrap(err, "parse maxDays")
}
maxBackups, err := strconv.Atoi(values.Get("maxBackups"))
if err != nil {
return nil, errors.Wrap(err, "parse maxBackups")
}
compress, err := strconv.ParseBool(values.Get("compress"))
if err != nil {
return nil, errors.Wrap(err, "parse compress")
}
return &Rotation{
File: file,
MaxSizeMb: maxSizeMb,
MaxDays: maxDays,
MaxBackups: maxBackups,
Compress: compress,
}, nil
}
func NewFileRotationWriter(r Rotation) io.WriteCloser {
return &lumberjack.Logger{
Filename: r.File,
MaxSize: r.MaxSizeMb,
MaxAge: r.MaxDays,
MaxBackups: r.MaxBackups,
Compress: r.Compress,
}
}
type sink struct {
io.WriteCloser
}
func (s sink) Sync() error {
return nil
}
func newSink(writer io.WriteCloser) sink {
return sink{
WriteCloser: writer,
}
}
+46 -11
View File
@@ -2,22 +2,25 @@ package main
import (
"context"
"log"
"os"
"github.com/integration-system/go-cmp/cmp"
"github.com/integration-system/isp-lib/v2/bootstrap"
"github.com/integration-system/isp-lib/v2/config"
"github.com/integration-system/isp-lib/v2/config/schema"
"github.com/integration-system/isp-lib/v2/metric"
"github.com/integration-system/isp-lib/v2/structure"
"github.com/integration-system/isp-lib/v2/utils"
logrus "github.com/integration-system/isp-log"
"github.com/integration-system/isp-log/stdcodes"
"github.com/pkg/errors"
"isp-gate-service/accounting"
"isp-gate-service/authenticate"
"isp-gate-service/conf"
"isp-gate-service/invoker"
"isp-gate-service/model"
"isp-gate-service/log"
"isp-gate-service/proxy"
"isp-gate-service/redis"
"isp-gate-service/repository"
"isp-gate-service/routing"
"isp-gate-service/server"
"isp-gate-service/service"
@@ -26,6 +29,8 @@ import (
var (
version = "0.1.0"
logger *log.Adapter
)
func main() {
@@ -38,12 +43,11 @@ func main() {
DeclareMe(makeDeclaration).
SocketConfiguration(socketConfiguration).
RequireRoutes(handleRouteUpdate).
RequireModule("journal", invoker.Journal.ReceiveServiceAddressList, false).
SubscribeBroadcastEvent(bootstrap.ListenRestartEvent())
requiredModules, err := proxy.InitProxies(cfg.Locations)
if err != nil {
log.Fatal(stdcodes.ModuleInvalidLocalConfig, err)
logrus.Fatal(stdcodes.ModuleInvalidLocalConfig, err)
}
for module, consumer := range requiredModules {
bs.RequireModule(module, consumer, false)
@@ -59,10 +63,7 @@ func onLocalConfigLoad(_ *conf.Configuration) {
}
func onRemoteConfigReceive(remoteConfig, oldRemoteConfig *conf.RemoteConfig) {
localCfg := config.Get().(*conf.Configuration)
model.DbClient.ReceiveConfiguration(remoteConfig.Database)
invoker.Journal.ReceiveConfiguration(remoteConfig.JournalSetting.Journal, localCfg.ModuleName)
repository.DbClient.ReceiveConfiguration(remoteConfig.Database)
matcher.JournalMethods = matcher.NewAtLeastOneMatcher(remoteConfig.JournalSetting.MethodsPatterns)
redis.Client.ReceiveConfiguration(remoteConfig.Redis)
@@ -73,7 +74,16 @@ func onRemoteConfigReceive(remoteConfig, oldRemoteConfig *conf.RemoteConfig) {
metric.InitHttpServer(remoteConfig.Metrics)
service.Metrics.Init()
server.Http.Init(remoteConfig.HttpSetting, oldRemoteConfig.HttpSetting)
oldLogger := setLogger(remoteConfig.JournalSetting.Journal, oldRemoteConfig.JournalSetting.Journal)
defer func() {
if oldLogger != nil {
_ = oldLogger.Close()
}
}()
isDifferentSettingForHttpServ :=
!cmp.Equal(remoteConfig.HttpSetting, oldRemoteConfig.HttpSetting) || oldLogger != nil
server.Http.Init(isDifferentSettingForHttpServ, remoteConfig.HttpSetting.GetMaxRequestBodySize(), logger)
}
func socketConfiguration(cfg interface{}) structure.SocketConfiguration {
@@ -93,7 +103,9 @@ func onShutdown(_ context.Context, _ os.Signal) {
accounting.Close()
proxy.Close()
_ = redis.Client.Close()
_ = invoker.Journal.Close()
if logger != nil {
_ = logger.Close()
}
}
func handleRouteUpdate(configs structure.RoutingConfig) bool {
@@ -110,3 +122,26 @@ func makeDeclaration(localConfig interface{}) bootstrap.ModuleInfo {
Endpoints: []structure.EndpointDescriptor{},
}
}
func setLogger(loggerCfg, oldLoggerCfg conf.JorunalConfig) *log.Adapter {
if cmp.Equal(loggerCfg, oldLoggerCfg) {
return nil
}
var err error
oldLogger := logger
if utils.DEV {
logger, err = log.New()
} else {
logger, err = log.New(log.WithFileRotation(log.Rotation{
File: loggerCfg.Filename,
MaxSizeMb: loggerCfg.MaxSizeMb,
Compress: loggerCfg.Compress,
}))
}
if err != nil {
logrus.Fatal(stdcodes.ModuleRunFatalError, errors.WithMessage(err, "set logger"))
}
return oldLogger
}
+1 -1
View File
@@ -1,4 +1,4 @@
package model
package repository
import (
"github.com/integration-system/isp-lib/v2/database"
+1 -1
View File
@@ -1,4 +1,4 @@
package model
package repository
import (
"github.com/go-pg/pg/v9/orm"
+1 -1
View File
@@ -1,4 +1,4 @@
package model
package repository
import (
"github.com/go-pg/pg/v9"
+15 -12
View File
@@ -1,15 +1,16 @@
package server
import (
"github.com/integration-system/go-cmp/cmp"
"sync"
"time"
"github.com/integration-system/isp-lib/v2/config"
log "github.com/integration-system/isp-log"
logrus "github.com/integration-system/isp-log"
"github.com/valyala/fasthttp"
"isp-gate-service/conf"
"isp-gate-service/handler"
"isp-gate-service/log"
"isp-gate-service/log_code"
"sync"
"time"
)
const defaultTimeout = 60 * time.Second
@@ -20,15 +21,17 @@ type httpSrv struct {
working bool
srv *fasthttp.Server
mx sync.Mutex
logger log.Logger
}
func (s *httpSrv) Init(new, old conf.HttpSetting) {
func (s *httpSrv) Init(isDifferentSetting bool, bodySize int64, logger log.Logger) {
s.logger = logger
if s.working {
if !cmp.Equal(new, old) {
s.run(new.GetMaxRequestBodySize())
if isDifferentSetting {
s.run(bodySize)
}
} else {
s.run(new.GetMaxRequestBodySize())
s.run(bodySize)
}
}
@@ -37,20 +40,20 @@ func (s *httpSrv) run(maxRequestBodySize int64) {
s.working = true
if s.srv != nil {
if err := s.srv.Shutdown(); err != nil {
log.Warn(log_code.WarnHttpServerShutdown, err)
logrus.Warn(log_code.WarnHttpServerShutdown, err)
}
}
localConfig := config.Get().(*conf.Configuration)
restAddress := localConfig.HttpInnerAddress.GetAddress()
s.srv = &fasthttp.Server{
Handler: handler.CompleteRequest,
Handler: handler.New(s.logger).CompleteRequest,
WriteTimeout: defaultTimeout,
ReadTimeout: defaultTimeout,
MaxRequestBodySize: int(maxRequestBodySize),
}
go func() {
if err := s.srv.ListenAndServe(restAddress); err != nil {
log.Error(log_code.ErrorHttpServerListen, err)
logrus.Error(log_code.ErrorHttpServerListen, err)
}
}()
s.mx.Unlock()
@@ -60,7 +63,7 @@ func (s *httpSrv) Close() {
if s.srv != nil {
s.working = false
if err := s.srv.Shutdown(); err != nil {
log.Warn(log_code.WarnHttpServerShutdown, err)
logrus.Warn(log_code.WarnHttpServerShutdown, err)
}
}
}