Merge pull request #7 from integration-system/update_proxy
Update proxy
This commit is contained in:
25 files changed
+494
-289
No files matched your search
@@ -1,3 +1,7 @@
|
||||
## 2.1.0
|
||||
* fix proxy path
|
||||
* add skip authenticate
|
||||
* add snapshot version
|
||||
## 2.0.0
|
||||
* add integration with isp-config-service 2.0
|
||||
## 1.3.0
|
||||
|
||||
Generated
+5
-5
@@ -18,12 +18,12 @@
|
||||
version = "v0.1.1"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:c1100fc71e23b6a32b2c68a5202a848fd13811d5a10b12edb8019c3667d1cd9a"
|
||||
digest = "1:44f56f927970ceccb0a28eccbea0cde48e56f04619ddbb70198036407f14cd0e"
|
||||
name = "github.com/cenkalti/backoff"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "4b4cebaf850ec58f1bb1fec5bdebdf8501c2bc3f"
|
||||
version = "v3.0.0"
|
||||
revision = "1ff1c09ea627d2be64cea605afa999c582c7cd01"
|
||||
version = "v3.1.1"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:ffe9824d294da03b391f44e1ae8281281b4afc1bdaa9588c9097785e3af10cec"
|
||||
@@ -490,7 +490,7 @@
|
||||
"ssh/terminal",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "4f8c1d86b1ba699e7a66cd649947ed270a74e0bb"
|
||||
revision = "ac88ee75c92c889b97e05591e9a39b6480c538b3"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
@@ -506,7 +506,7 @@
|
||||
"trace",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "fc4aabc6c91483155dade6fbb627cc953a723260"
|
||||
revision = "ffdde105785063a81acd95bdf89ea53f6e0aac2d"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
|
||||
@@ -10,6 +10,7 @@ type accountant struct {
|
||||
mx sync.Mutex
|
||||
matcher matcher.Matcher
|
||||
limitStates map[string]state.LimitState
|
||||
version int64
|
||||
}
|
||||
|
||||
func (app *accountant) Accept(method string) bool {
|
||||
@@ -21,16 +22,20 @@ func (app *accountant) Accept(method string) bool {
|
||||
|
||||
app.mx.Lock()
|
||||
resp := state.Update(stateStorage)
|
||||
if resp {
|
||||
app.version++
|
||||
}
|
||||
app.mx.Unlock()
|
||||
return resp
|
||||
}
|
||||
|
||||
func (app *accountant) Snapshot() map[string]state.Snapshot {
|
||||
func (app *accountant) Snapshot() (map[string]state.Snapshot, int64) {
|
||||
app.mx.Lock()
|
||||
version := app.version
|
||||
snapshotLimitState := make(map[string]state.Snapshot, len(app.limitStates))
|
||||
for method, limitState := range app.limitStates {
|
||||
snapshotLimitState[method] = limitState.Export()
|
||||
}
|
||||
app.mx.Unlock()
|
||||
return snapshotLimitState
|
||||
return snapshotLimitState, version
|
||||
}
|
||||
+97
-73
@@ -1,8 +1,9 @@
|
||||
package accounting
|
||||
|
||||
import (
|
||||
"github.com/integration-system/isp-lib/config"
|
||||
"github.com/integration-system/isp-lib/structure"
|
||||
log "github.com/integration-system/isp-log"
|
||||
"github.com/integration-system/isp-log/stdcodes"
|
||||
"isp-gate-service/accounting/state"
|
||||
"isp-gate-service/conf"
|
||||
"isp-gate-service/entity"
|
||||
@@ -13,108 +14,131 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
accountingWorking = false
|
||||
accountingStorage = make(map[int32]Accounting)
|
||||
requestsStoring = make(map[int32]bool)
|
||||
)
|
||||
|
||||
type Accounting interface {
|
||||
Accept(string) bool
|
||||
Snapshot() map[string]state.Snapshot
|
||||
var worker = &accountingWorker{
|
||||
accountingStorage: make(map[int32]Accounting),
|
||||
requestsStoring: make(map[int32]bool),
|
||||
}
|
||||
|
||||
func ReceiveConfiguration(conf conf.Accounting) {
|
||||
Close()
|
||||
newAccountingStorage := make(map[int32]Accounting)
|
||||
newRequestsStoring := make(map[int32]bool)
|
||||
|
||||
if conf.Enable {
|
||||
if err := InitStoringTask(conf.Storing); err != nil {
|
||||
log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err)
|
||||
}
|
||||
|
||||
for _, s := range conf.Setting {
|
||||
newRequestsStoring[s.ApplicationId] = s.EnableStoring
|
||||
|
||||
limitStates, patternArray, err := state.InitLimitState(s.Limits)
|
||||
if err != nil {
|
||||
log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err)
|
||||
}
|
||||
|
||||
recoveryLimitState(s.ApplicationId, limitStates)
|
||||
|
||||
newAccountingStorage[s.ApplicationId] = &accountant{
|
||||
matcher: matcher.NewCacheableMatcher(patternArray),
|
||||
limitStates: limitStates,
|
||||
mx: sync.Mutex{},
|
||||
}
|
||||
}
|
||||
|
||||
if snapshotTimeout, err := time.ParseDuration(conf.SnapshotTimeout); err != nil {
|
||||
log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err)
|
||||
} else {
|
||||
go snapshot.Start(snapshotTimeout)
|
||||
}
|
||||
|
||||
accountingWorking = true
|
||||
} else {
|
||||
accountingWorking = false
|
||||
type (
|
||||
Accounting interface {
|
||||
Accept(string) bool
|
||||
Snapshot() (map[string]state.Snapshot, int64)
|
||||
}
|
||||
|
||||
requestsStoring = newRequestsStoring
|
||||
accountingStorage = newAccountingStorage
|
||||
accountingWorker struct {
|
||||
accountingStorage map[int32]Accounting
|
||||
requestsStoring map[int32]bool
|
||||
}
|
||||
)
|
||||
|
||||
func NewConnectionConsumer(list []structure.AddressConfiguration) bool {
|
||||
accountingSetting := config.GetRemote().(*conf.RemoteConfig).AccountingSetting
|
||||
worker.init(accountingSetting)
|
||||
return true
|
||||
}
|
||||
|
||||
func Accept(appId int32, path string) bool {
|
||||
if accouter, ok := accountingStorage[appId]; !ok {
|
||||
if requestsStoring[appId] {
|
||||
storage.TakeRequest(appId, path, time.Now())
|
||||
}
|
||||
return true
|
||||
} else {
|
||||
func ReceiveConfiguration(accountingSetting conf.Accounting) {
|
||||
worker.init(accountingSetting)
|
||||
}
|
||||
|
||||
func AcceptRequest(appId int32, path string) bool {
|
||||
if accouter, ok := worker.accountingStorage[appId]; ok {
|
||||
ok := accouter.Accept(path)
|
||||
if ok && requestsStoring[appId] {
|
||||
if ok && worker.requestsStoring[appId] {
|
||||
storage.TakeRequest(appId, path, time.Now())
|
||||
}
|
||||
return ok
|
||||
} else {
|
||||
if worker.requestsStoring[appId] {
|
||||
storage.TakeRequest(appId, path, time.Now())
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
func Close() {
|
||||
snapshot.Stop()
|
||||
if snapshot != nil {
|
||||
snapshot.Stop()
|
||||
}
|
||||
if storage != nil {
|
||||
storage.Stop()
|
||||
}
|
||||
}
|
||||
|
||||
func takeSnapshot() []entity.Snapshot {
|
||||
response := make([]entity.Snapshot, 0, len(accountingStorage))
|
||||
for appId, account := range accountingStorage {
|
||||
func (w *accountingWorker) init(accountingSetting conf.Accounting) {
|
||||
Close()
|
||||
|
||||
newAccountingStorage := make(map[int32]Accounting)
|
||||
newRequestsStoringStorage := make(map[int32]bool)
|
||||
|
||||
if accountingSetting.Enable {
|
||||
InitStoringTask(accountingSetting.Storing)
|
||||
|
||||
for _, s := range accountingSetting.Setting {
|
||||
limitStates, patternArray := state.InitLimitState(s.Limits)
|
||||
accounting := w.recoveryAccounting(s.ApplicationId, limitStates, patternArray)
|
||||
|
||||
newAccountingStorage[s.ApplicationId] = accounting
|
||||
newRequestsStoringStorage[s.ApplicationId] = s.EnableStoring
|
||||
}
|
||||
|
||||
InitSnapshotTask(accountingSetting.SnapshotTimeout)
|
||||
}
|
||||
|
||||
w.requestsStoring = newRequestsStoringStorage
|
||||
w.accountingStorage = newAccountingStorage
|
||||
}
|
||||
|
||||
func (w *accountingWorker) takeSnapshot() []entity.Snapshot {
|
||||
response := make([]entity.Snapshot, 0, len(w.accountingStorage))
|
||||
for appId, account := range w.accountingStorage {
|
||||
|
||||
limitState, version := account.Snapshot()
|
||||
|
||||
response = append(response, entity.Snapshot{
|
||||
AppId: appId,
|
||||
LimitState: account.Snapshot(),
|
||||
LimitState: limitState,
|
||||
Version: version,
|
||||
})
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
func recoveryLimitState(appId int32, limitStates map[string]state.LimitState) {
|
||||
if accountingWorking {
|
||||
if acc, ok := accountingStorage[appId]; ok {
|
||||
snapshot := acc.Snapshot()
|
||||
importLimitState(limitStates, snapshot)
|
||||
}
|
||||
} else {
|
||||
if snapshot, err := model.SnapshotRep.GetByApplication(appId); err != nil {
|
||||
log.Warn(log_code.ErrorSnapshotAccounting, err)
|
||||
} else if snapshot != nil {
|
||||
importLimitState(limitStates, snapshot.LimitState)
|
||||
func (w *accountingWorker) recoveryAccounting(appId int32, limitStates map[string]state.LimitState, patternArray []string) *accountant {
|
||||
var (
|
||||
version = int64(0)
|
||||
importNotComplete = true
|
||||
)
|
||||
|
||||
dbSnapshot, err := model.SnapshotRep.GetByApplication(appId)
|
||||
if err != nil {
|
||||
log.Warn(log_code.ErrorSnapshotAccounting, err)
|
||||
}
|
||||
|
||||
if cash, ok := w.accountingStorage[appId]; ok {
|
||||
cashLimitState, cashVersion := cash.Snapshot()
|
||||
|
||||
if dbSnapshot == nil || dbSnapshot.Version < cashVersion {
|
||||
version = cashVersion
|
||||
w.importLimitState(limitStates, cashLimitState)
|
||||
importNotComplete = false
|
||||
}
|
||||
}
|
||||
|
||||
if dbSnapshot != nil && importNotComplete {
|
||||
version = dbSnapshot.Version
|
||||
w.importLimitState(limitStates, dbSnapshot.LimitState)
|
||||
}
|
||||
|
||||
return &accountant{
|
||||
mx: sync.Mutex{},
|
||||
matcher: matcher.NewCacheableMatcher(patternArray),
|
||||
limitStates: limitStates,
|
||||
version: version,
|
||||
}
|
||||
}
|
||||
|
||||
func importLimitState(limitStates map[string]state.LimitState, snapshot map[string]state.Snapshot) {
|
||||
func (w *accountingWorker) importLimitState(limitStates map[string]state.LimitState, snapshot map[string]state.Snapshot) {
|
||||
for method, limitState := range limitStates {
|
||||
if oldState, ok := snapshot[method]; ok {
|
||||
limitState.Import(oldState)
|
||||
|
||||
@@ -2,10 +2,10 @@ package accounting
|
||||
|
||||
import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
"isp-gate-service/accounting/state"
|
||||
"isp-gate-service/conf"
|
||||
"isp-gate-service/entity"
|
||||
"isp-gate-service/model"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
@@ -21,6 +21,7 @@ var (
|
||||
{Pattern: "mdm-master/group3/*", MaxCount: 5, Timeout: "10s"},
|
||||
{Pattern: "mdm-master/group4/method", MaxCount: 2, Timeout: "0s"},
|
||||
{Pattern: "mdm-master/group5/method", MaxCount: 3, Timeout: "10s"},
|
||||
{Pattern: "mdm-master/group6/method", MaxCount: 5, Timeout: "10s"},
|
||||
}},
|
||||
{ApplicationId: 2, Limits: []conf.LimitSetting{
|
||||
{Pattern: "mdm-master/group/method", MaxCount: 0, Timeout: "10s"},
|
||||
@@ -62,18 +63,23 @@ var (
|
||||
|
||||
func TestAccounting(t *testing.T) {
|
||||
a := assert.New(t)
|
||||
model.SnapshotRep = &snapshotRepository{cache: make(map[int32]map[string]state.Snapshot)}
|
||||
ReceiveConfiguration(accountingSetting)
|
||||
snapshotRep := newSnapshotRepository(false)
|
||||
model.SnapshotRep = snapshotRep
|
||||
worker = &accountingWorker{
|
||||
accountingStorage: make(map[int32]Accounting),
|
||||
requestsStoring: make(map[int32]bool),
|
||||
}
|
||||
worker.init(accountingSetting)
|
||||
|
||||
req := reqExample[4]
|
||||
for _, path := range req.path {
|
||||
a.True(Accept(req.appId, path))
|
||||
a.True(AcceptRequest(req.appId, path))
|
||||
}
|
||||
|
||||
expected := true
|
||||
req = reqExample[0]
|
||||
for _, path := range req.path {
|
||||
a.Equal(expected, Accept(req.appId, path))
|
||||
a.Equal(expected, AcceptRequest(req.appId, path))
|
||||
expected = !expected
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
@@ -81,49 +87,111 @@ func TestAccounting(t *testing.T) {
|
||||
//expected == true
|
||||
req = reqExample[1]
|
||||
for _, path := range req.path {
|
||||
a.Equal(expected, Accept(req.appId, path))
|
||||
a.Equal(expected, AcceptRequest(req.appId, path))
|
||||
expected = !expected
|
||||
}
|
||||
|
||||
req = reqExample[2]
|
||||
expectedArray := []bool{true, true, true, true, true, false}
|
||||
for key, path := range req.path {
|
||||
a.Equal(expectedArray[key], Accept(req.appId, path))
|
||||
a.Equal(expectedArray[key], AcceptRequest(req.appId, path))
|
||||
}
|
||||
|
||||
//expected == true
|
||||
req = reqExample[3]
|
||||
for _, path := range req.path {
|
||||
a.Equal(expected, Accept(req.appId, path))
|
||||
a.Equal(expected, AcceptRequest(req.appId, path))
|
||||
}
|
||||
|
||||
ReceiveConfiguration(accountingSetting)
|
||||
worker.init(accountingSetting)
|
||||
|
||||
req = reqExample[4]
|
||||
for _, path := range req.path {
|
||||
a.False(Accept(req.appId, path))
|
||||
a.False(AcceptRequest(req.appId, path))
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorker_recoveryAccounting(t *testing.T) {
|
||||
a := assert.New(t)
|
||||
snapshotRep := newSnapshotRepository(true)
|
||||
model.SnapshotRep = snapshotRep
|
||||
|
||||
worker = &accountingWorker{
|
||||
accountingStorage: make(map[int32]Accounting),
|
||||
requestsStoring: make(map[int32]bool),
|
||||
}
|
||||
secondWorker := &accountingWorker{
|
||||
accountingStorage: make(map[int32]Accounting),
|
||||
requestsStoring: make(map[int32]bool),
|
||||
}
|
||||
|
||||
worker.init(accountingSetting)
|
||||
secondWorker.init(accountingSetting)
|
||||
|
||||
appId := int32(1)
|
||||
request := "1_3_5"
|
||||
for range request {
|
||||
a.True(AcceptRequest(appId, "mdm-master/group6/method"))
|
||||
}
|
||||
a.False(AcceptRequest(appId, "mdm-master/group6/method"))
|
||||
|
||||
time.Sleep(time.Millisecond * 300)
|
||||
a.True(snapshotRep.Wait())
|
||||
snapshot, err := model.SnapshotRep.GetByApplication(appId)
|
||||
a.NoError(err)
|
||||
a.NotNil(snapshot)
|
||||
a.Equal(len(request), int(snapshot.Version))
|
||||
|
||||
Close()
|
||||
worker = secondWorker
|
||||
worker.init(accountingSetting)
|
||||
a.False(AcceptRequest(appId, "mdm-master/group6/method"))
|
||||
}
|
||||
|
||||
type snapshotRepository struct {
|
||||
cache map[int32]map[string]state.Snapshot
|
||||
enableWaitGroup bool
|
||||
wg sync.WaitGroup
|
||||
cache map[int32]entity.Snapshot
|
||||
}
|
||||
|
||||
func newSnapshotRepository(enableWaitGroup bool) *snapshotRepository {
|
||||
return &snapshotRepository{
|
||||
enableWaitGroup: enableWaitGroup,
|
||||
wg: sync.WaitGroup{},
|
||||
cache: make(map[int32]entity.Snapshot),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *snapshotRepository) Wait() bool {
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
r.wg.Wait()
|
||||
close(done)
|
||||
}()
|
||||
select {
|
||||
case <-done:
|
||||
return true
|
||||
case <-time.After(time.Second):
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (r *snapshotRepository) GetByApplication(appId int32) (*entity.Snapshot, error) {
|
||||
if limitState, ok := r.cache[appId]; ok {
|
||||
return &entity.Snapshot{
|
||||
AppId: appId,
|
||||
LimitState: limitState,
|
||||
}, nil
|
||||
if snapshot, ok := r.cache[appId]; ok {
|
||||
return &snapshot, nil
|
||||
} else {
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (r *snapshotRepository) Update(list []entity.Snapshot) error {
|
||||
if r.enableWaitGroup {
|
||||
r.wg.Add(1)
|
||||
defer r.wg.Done()
|
||||
}
|
||||
|
||||
for _, s := range list {
|
||||
r.cache[s.AppId] = s.LimitState
|
||||
r.cache[s.AppId] = s
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+54
-26
@@ -2,56 +2,84 @@ package accounting
|
||||
|
||||
import (
|
||||
log "github.com/integration-system/isp-log"
|
||||
"github.com/integration-system/isp-log/stdcodes"
|
||||
"isp-gate-service/entity"
|
||||
"isp-gate-service/log_code"
|
||||
"isp-gate-service/model"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var snapshot = &snapshotTask{
|
||||
process: false,
|
||||
timeout: make(chan time.Time),
|
||||
close: make(chan bool),
|
||||
}
|
||||
var snapshot *snapshotTask
|
||||
|
||||
type snapshotTask struct {
|
||||
mx sync.Mutex
|
||||
mx sync.Mutex
|
||||
wg sync.WaitGroup
|
||||
|
||||
process bool
|
||||
timeout <-chan time.Time
|
||||
close chan bool
|
||||
}
|
||||
|
||||
func (s *snapshotTask) Start(timeout time.Duration) {
|
||||
s.Stop()
|
||||
func InitSnapshotTask(snapshotTimeout string) {
|
||||
timeout, err := time.ParseDuration(snapshotTimeout)
|
||||
if err != nil {
|
||||
log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err)
|
||||
}
|
||||
|
||||
s.mx.Lock()
|
||||
s.process = true
|
||||
s.timeout = time.After(timeout)
|
||||
s.mx.Unlock()
|
||||
snapshot = newSnapshotTask(timeout)
|
||||
}
|
||||
|
||||
func (t *snapshotTask) Stop() {
|
||||
t.mx.Lock()
|
||||
if t.process {
|
||||
snapshotList := worker.takeSnapshot()
|
||||
if len(snapshotList) != 0 {
|
||||
defer func() {
|
||||
t.wg.Add(1)
|
||||
t.unload(snapshotList)
|
||||
t.wg.Wait()
|
||||
}()
|
||||
}
|
||||
t.process = false
|
||||
t.close <- true
|
||||
}
|
||||
t.mx.Unlock()
|
||||
}
|
||||
|
||||
func (t *snapshotTask) run(timeout time.Duration) {
|
||||
defer t.wg.Done()
|
||||
t.timeout = time.After(timeout)
|
||||
for {
|
||||
select {
|
||||
case <-s.close:
|
||||
case <-t.close:
|
||||
return
|
||||
case <-s.timeout:
|
||||
if err := s.saveSnapshot(); err != nil {
|
||||
log.Error(log_code.ErrorSnapshotAccounting, err)
|
||||
case <-t.timeout:
|
||||
list := worker.takeSnapshot()
|
||||
if len(list) > 0 {
|
||||
t.wg.Add(1)
|
||||
go t.unload(list)
|
||||
}
|
||||
s.timeout = time.After(timeout)
|
||||
t.timeout = time.After(timeout)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *snapshotTask) Stop() {
|
||||
s.mx.Lock()
|
||||
if s.process {
|
||||
s.process = false
|
||||
s.close <- true
|
||||
func (t *snapshotTask) unload(list []entity.Snapshot) {
|
||||
if err := model.SnapshotRep.Update(list); err != nil {
|
||||
log.Error(log_code.ErrorSnapshotAccounting, err)
|
||||
}
|
||||
s.mx.Unlock()
|
||||
t.wg.Done()
|
||||
}
|
||||
|
||||
func (s *snapshotTask) saveSnapshot() error {
|
||||
snapshotList := takeSnapshot()
|
||||
return model.SnapshotRep.Update(snapshotList)
|
||||
func newSnapshotTask(timeout time.Duration) *snapshotTask {
|
||||
task := &snapshotTask{
|
||||
process: true,
|
||||
timeout: make(chan time.Time),
|
||||
close: make(chan bool),
|
||||
}
|
||||
|
||||
task.wg.Add(1)
|
||||
go task.run(timeout)
|
||||
return task
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
package state
|
||||
|
||||
import (
|
||||
log "github.com/integration-system/isp-log"
|
||||
"github.com/integration-system/isp-log/stdcodes"
|
||||
"isp-gate-service/conf"
|
||||
"time"
|
||||
)
|
||||
@@ -26,19 +28,19 @@ type (
|
||||
}
|
||||
)
|
||||
|
||||
func InitLimitState(limits []conf.LimitSetting) (map[string]LimitState, []string, error) {
|
||||
func InitLimitState(limits []conf.LimitSetting) (map[string]LimitState, []string) {
|
||||
limitStates := make(map[string]LimitState)
|
||||
patternArray := make([]string, len(limits))
|
||||
|
||||
for i, limit := range limits {
|
||||
timeout, err := time.ParseDuration(limit.Timeout)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err)
|
||||
}
|
||||
|
||||
if timeout == 0 && limit.MaxCount != 0 {
|
||||
limit.MaxCount = 1
|
||||
}
|
||||
|
||||
patternArray[i] = limit.Pattern
|
||||
limitStates[limit.Pattern] = &limiter{
|
||||
timeout: timeout,
|
||||
@@ -47,7 +49,7 @@ func InitLimitState(limits []conf.LimitSetting) (map[string]LimitState, []string
|
||||
pointer: -1,
|
||||
}
|
||||
}
|
||||
return limitStates, patternArray, nil
|
||||
return limitStates, patternArray
|
||||
}
|
||||
|
||||
func Update(states []LimitState) bool {
|
||||
|
||||
+47
-44
@@ -2,6 +2,7 @@ package accounting
|
||||
|
||||
import (
|
||||
log "github.com/integration-system/isp-log"
|
||||
"github.com/integration-system/isp-log/stdcodes"
|
||||
"isp-gate-service/conf"
|
||||
"isp-gate-service/entity"
|
||||
"isp-gate-service/log_code"
|
||||
@@ -25,88 +26,90 @@ type storingTask struct {
|
||||
wg sync.WaitGroup
|
||||
}
|
||||
|
||||
func InitStoringTask(setting conf.StoringSetting) error {
|
||||
func InitStoringTask(setting conf.StoringSetting) {
|
||||
timeout, err := time.ParseDuration(setting.Timeout)
|
||||
if err != nil {
|
||||
return err
|
||||
log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err)
|
||||
}
|
||||
|
||||
storage = newStoringTask(timeout, setting.Size)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (u *storingTask) TakeRequest(appId int32, method string, date time.Time) {
|
||||
u.mx.Lock()
|
||||
if !u.process {
|
||||
u.mx.Unlock()
|
||||
func (t *storingTask) TakeRequest(appId int32, method string, date time.Time) {
|
||||
t.mx.Lock()
|
||||
if !t.process {
|
||||
t.mx.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
u.buffer[u.counter] = entity.Request{
|
||||
t.buffer[t.counter] = entity.Request{
|
||||
AppId: appId,
|
||||
Method: method,
|
||||
CreatedAt: date,
|
||||
}
|
||||
|
||||
u.counter++
|
||||
if u.counter == len(u.buffer) {
|
||||
u.chanCounter <- u.buffer
|
||||
u.clearBuffer()
|
||||
t.counter++
|
||||
if t.counter == len(t.buffer) {
|
||||
t.chanCounter <- t.buffer
|
||||
t.clearBuffer()
|
||||
}
|
||||
|
||||
u.mx.Unlock()
|
||||
t.mx.Unlock()
|
||||
}
|
||||
|
||||
func (u *storingTask) Stop() {
|
||||
u.mx.Lock()
|
||||
if u.process {
|
||||
if u.counter != 0 {
|
||||
buffer := u.clearBuffer()
|
||||
func (t *storingTask) Stop() {
|
||||
t.mx.Lock()
|
||||
if t.process {
|
||||
if t.counter != 0 {
|
||||
buffer := t.clearBuffer()
|
||||
defer func() {
|
||||
u.unload(buffer)
|
||||
u.wg.Wait()
|
||||
t.wg.Add(1)
|
||||
t.unload(buffer)
|
||||
t.wg.Wait()
|
||||
}()
|
||||
}
|
||||
u.chanClose <- true
|
||||
u.process = false
|
||||
t.chanClose <- true
|
||||
t.process = false
|
||||
}
|
||||
u.mx.Unlock()
|
||||
t.mx.Unlock()
|
||||
}
|
||||
|
||||
func (u *storingTask) run(timeout time.Duration) {
|
||||
defer u.wg.Done()
|
||||
u.chanTimeout = time.After(timeout)
|
||||
func (t *storingTask) run(timeout time.Duration) {
|
||||
defer t.wg.Done()
|
||||
t.chanTimeout = time.After(timeout)
|
||||
for {
|
||||
select {
|
||||
case <-u.chanClose:
|
||||
case <-t.chanClose:
|
||||
return
|
||||
case cache := <-u.chanCounter:
|
||||
go u.unload(cache)
|
||||
u.chanTimeout = time.After(timeout)
|
||||
case <-u.chanTimeout:
|
||||
u.mx.Lock()
|
||||
if u.counter != 0 {
|
||||
buffer := u.clearBuffer()
|
||||
go u.unload(buffer)
|
||||
case cache := <-t.chanCounter:
|
||||
t.wg.Add(1)
|
||||
go t.unload(cache)
|
||||
t.chanTimeout = time.After(timeout)
|
||||
case <-t.chanTimeout:
|
||||
t.mx.Lock()
|
||||
if t.counter != 0 {
|
||||
buffer := t.clearBuffer()
|
||||
t.wg.Add(1)
|
||||
go t.unload(buffer)
|
||||
}
|
||||
u.mx.Unlock()
|
||||
u.chanTimeout = time.After(timeout)
|
||||
t.mx.Unlock()
|
||||
t.chanTimeout = time.After(timeout)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (u *storingTask) unload(cache []entity.Request) {
|
||||
func (t *storingTask) unload(cache []entity.Request) {
|
||||
if err := model.RequestsRep.Insert(cache); err != nil {
|
||||
log.Error(log_code.ErrorUnloadAccounting, err)
|
||||
}
|
||||
t.wg.Done()
|
||||
}
|
||||
|
||||
func (u *storingTask) clearBuffer() []entity.Request {
|
||||
oldBuffer := u.buffer[:u.counter]
|
||||
oldLen := len(u.buffer)
|
||||
u.counter = 0
|
||||
u.buffer = make([]entity.Request, oldLen)
|
||||
func (t *storingTask) clearBuffer() []entity.Request {
|
||||
oldBuffer := t.buffer[:t.counter]
|
||||
oldLen := len(t.buffer)
|
||||
t.counter = 0
|
||||
t.buffer = make([]entity.Request, oldLen)
|
||||
return oldBuffer
|
||||
}
|
||||
|
||||
|
||||
@@ -27,11 +27,11 @@ var (
|
||||
}
|
||||
)
|
||||
|
||||
func initStoring(setting conf.StoringSetting) (*requestsRepository, error) {
|
||||
func initStoring(setting conf.StoringSetting) *requestsRepository {
|
||||
repository := &requestsRepository{cache: make([]entity.Request, 0), wg: &sync.WaitGroup{}}
|
||||
model.RequestsRep = repository
|
||||
err := InitStoringTask(setting)
|
||||
return repository, err
|
||||
InitStoringTask(setting)
|
||||
return repository
|
||||
}
|
||||
|
||||
func wait(wg *sync.WaitGroup) bool {
|
||||
@@ -50,8 +50,7 @@ func wait(wg *sync.WaitGroup) bool {
|
||||
|
||||
func TestStoringTask_Stop(t *testing.T) {
|
||||
a := assert.New(t)
|
||||
rep, err := initStoring(bufferSetting)
|
||||
a.NoError(err)
|
||||
rep := initStoring(bufferSetting)
|
||||
|
||||
rep.wg.Add(2)
|
||||
for i, j := range []string{"Stop_1", "Stop_2", "Stop_3", "Stop_4", "Stop_5"} {
|
||||
@@ -63,8 +62,7 @@ func TestStoringTask_Stop(t *testing.T) {
|
||||
|
||||
func TestStoringTask_Buffer(t *testing.T) {
|
||||
a := assert.New(t)
|
||||
rep, err := initStoring(bufferSetting)
|
||||
a.NoError(err)
|
||||
rep := initStoring(bufferSetting)
|
||||
|
||||
rep.wg.Add(1)
|
||||
for i, j := range []string{"Buffer_1", "Buffer_2", "Buffer_3", "Buffer_4", "Buffer_5"} {
|
||||
@@ -76,8 +74,7 @@ func TestStoringTask_Buffer(t *testing.T) {
|
||||
|
||||
func TestStoringTask_Timeout(t *testing.T) {
|
||||
a := assert.New(t)
|
||||
rep, err := initStoring(timeoutSetting)
|
||||
a.NoError(err)
|
||||
rep := initStoring(timeoutSetting)
|
||||
|
||||
rep.wg.Add(1)
|
||||
for i, j := range []string{"Timeout_1", "Timeout_2"} {
|
||||
@@ -89,8 +86,7 @@ func TestStoringTask_Timeout(t *testing.T) {
|
||||
|
||||
func TestStoringTask_Unload(t *testing.T) {
|
||||
a := assert.New(t)
|
||||
rep, err := initStoring(unloadSetting)
|
||||
a.NoError(err)
|
||||
rep := initStoring(unloadSetting)
|
||||
|
||||
rep.wg.Add(2)
|
||||
for i, j := range []string{"Unload_1", "Unload_2", "Unload_3", "Unload_4", "Unload_5"} {
|
||||
|
||||
@@ -38,14 +38,7 @@ func ReceiveConfiguration(conf conf.Cache) {
|
||||
}
|
||||
}
|
||||
|
||||
func Do(ctx *fasthttp.RequestCtx) (int32, error) {
|
||||
path := ctx.Path()
|
||||
pathStr := getPathWithoutPrefix(path)
|
||||
|
||||
if _, ok := routing.AllMethods[pathStr]; !ok {
|
||||
return 0, createError("not implemented", codes.Unimplemented)
|
||||
}
|
||||
|
||||
func Do(ctx *fasthttp.RequestCtx, path string) (int32, error) {
|
||||
for _, notExpectedHeader := range notExpectedHeaders {
|
||||
ctx.Request.Header.Del(notExpectedHeader)
|
||||
}
|
||||
@@ -56,6 +49,7 @@ func Do(ctx *fasthttp.RequestCtx) (int32, error) {
|
||||
err error
|
||||
appId int32 = -1
|
||||
)
|
||||
|
||||
if len(appToken) == 0 {
|
||||
return 0, createError("unauthorized", codes.Unauthenticated)
|
||||
} else if config.GetRemote().(*conf.RemoteConfig).TokensSetting.ApplicationVerify {
|
||||
@@ -86,7 +80,7 @@ func Do(ctx *fasthttp.RequestCtx) (int32, error) {
|
||||
verifiableKeys[utils.UserTokenHeader] = string(ctx.Request.Header.Peek(utils.UserTokenHeader))
|
||||
|
||||
permittedToCall := false
|
||||
verifiableKeys, permittedToCall, err = auth.verify.Identity(verifiableKeys, pathStr)
|
||||
verifiableKeys, permittedToCall, err = auth.verify.Identity(verifiableKeys, path)
|
||||
if err != nil {
|
||||
log.Error(log_code.ErrorAuthenticate, err)
|
||||
return 0, createError("internal Server error", codes.Internal)
|
||||
@@ -101,7 +95,7 @@ func Do(ctx *fasthttp.RequestCtx) (int32, error) {
|
||||
}
|
||||
}
|
||||
|
||||
if _, ok := routing.InnerMethods[pathStr]; ok {
|
||||
if _, ok := routing.InnerMethods[path]; ok {
|
||||
adminToken := ctx.Request.Header.Peek("x-auth-admin") //todo const key
|
||||
if verifyToken.Admin(string(adminToken)) != nil {
|
||||
return 0, createError("forbidden", codes.PermissionDenied)
|
||||
@@ -114,17 +108,3 @@ func Do(ctx *fasthttp.RequestCtx) (int32, error) {
|
||||
|
||||
return appId, nil
|
||||
}
|
||||
|
||||
func getPathWithoutPrefix(path []byte) string {
|
||||
firstFound := false
|
||||
for i, value := range path {
|
||||
if value == '/' {
|
||||
if firstFound {
|
||||
return string(path[i+1:])
|
||||
} else {
|
||||
firstFound = true
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
+21
-1
@@ -1,6 +1,8 @@
|
||||
package conf
|
||||
|
||||
import "github.com/integration-system/isp-lib/structure"
|
||||
import (
|
||||
"github.com/integration-system/isp-lib/structure"
|
||||
)
|
||||
|
||||
type (
|
||||
Configuration struct {
|
||||
@@ -13,8 +15,26 @@ type (
|
||||
}
|
||||
|
||||
Location struct {
|
||||
SkipAuth bool
|
||||
PathPrefix string `valid:"required~Required"`
|
||||
Protocol string `valid:"required~Required"`
|
||||
TargetModule string `valid:"required~Required"`
|
||||
}
|
||||
)
|
||||
|
||||
func GetLocationsByTargetModule(locations []Location) map[string][]Location {
|
||||
requiredModules := make(map[string][]Location)
|
||||
|
||||
for _, location := range locations {
|
||||
if location.TargetModule == "" {
|
||||
continue
|
||||
}
|
||||
if loc, ok := requiredModules[location.TargetModule]; ok {
|
||||
requiredModules[location.TargetModule] = append(loc, location)
|
||||
} else {
|
||||
requiredModules[location.TargetModule] = []Location{location}
|
||||
}
|
||||
}
|
||||
|
||||
return requiredModules
|
||||
}
|
||||
@@ -49,9 +49,9 @@ type (
|
||||
|
||||
Accounting struct {
|
||||
Enable bool `schema:"Учет запросов,включает/отключает учет запросов"`
|
||||
SnapshotTimeout string `schema:"Частота выгрузки данных учета в БД" valid:"required~Required"`
|
||||
SnapshotTimeout string `schema:"Частота выгрузки ограничений для приложений" valid:"required~Required"`
|
||||
Setting []AccountingSetting `schema:"Настройка учета для приложений"`
|
||||
Storing StoringSetting `schema:"Настройка хранения запросов"`
|
||||
Storing StoringSetting `schema:"Настройка хранения всех запросов"`
|
||||
}
|
||||
|
||||
AccountingSetting struct {
|
||||
@@ -68,7 +68,7 @@ type (
|
||||
|
||||
StoringSetting struct {
|
||||
Size int `schema:"Размер буфера,размер буфера,при достижении которого данные сбрасываются в БД" valid:"required,range(1|1000000)"`
|
||||
Timeout string `schema:"Частота сброса,периодичность сброса данных в БД" valid:"required~Required"`
|
||||
Timeout string `schema:"Частота выгрузки всех учтенных запросов,периодичность сброса данных в БД" valid:"required~Required"`
|
||||
}
|
||||
|
||||
HttpSetting struct {
|
||||
|
||||
@@ -9,6 +9,7 @@ type Snapshot struct {
|
||||
TableName string `sql:"?db_schema.snapshot" json:"-"`
|
||||
AppId int32 `sql:",pk"`
|
||||
LimitState map[string]state.Snapshot
|
||||
Version int64
|
||||
}
|
||||
|
||||
type Request struct {
|
||||
|
||||
+34
-23
@@ -1,6 +1,7 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/integration-system/isp-lib/config"
|
||||
log "github.com/integration-system/isp-log"
|
||||
"github.com/pkg/errors"
|
||||
@@ -13,6 +14,7 @@ import (
|
||||
"isp-gate-service/journal"
|
||||
"isp-gate-service/log_code"
|
||||
"isp-gate-service/proxy"
|
||||
"isp-gate-service/routing"
|
||||
"isp-gate-service/service"
|
||||
"isp-gate-service/service/matcher"
|
||||
"isp-gate-service/utils"
|
||||
@@ -55,36 +57,45 @@ func CompleteRequest(ctx *fasthttp.RequestCtx) {
|
||||
}
|
||||
|
||||
func (handlerHelper) AuthenticateAccountingProxy(ctx *fasthttp.RequestCtx) domain.ProxyResponse {
|
||||
path := string(ctx.Path())
|
||||
initialPath := string(ctx.Path())
|
||||
|
||||
p := proxy.Find(path)
|
||||
p, path := proxy.Find(initialPath)
|
||||
if p == nil {
|
||||
err := errors.Errorf("unknown path %s", path)
|
||||
utils.WriteError(ctx, "not found", codes.NotFound, nil)
|
||||
return domain.Create().SetError(err)
|
||||
msg := fmt.Sprintf("unknown proxy for '%s'", path)
|
||||
utils.WriteError(ctx, msg, codes.NotFound, nil)
|
||||
return domain.Create().SetError(errors.New(msg))
|
||||
}
|
||||
|
||||
applicationId, err := authenticate.Do(ctx)
|
||||
if err != nil {
|
||||
message := "unknown error"
|
||||
status := codes.Unknown
|
||||
details := make([]interface{}, 0)
|
||||
switch e := err.(type) {
|
||||
case authenticate.ErrorDescription:
|
||||
message = e.Message()
|
||||
status = e.ConvertToGrpcStatus()
|
||||
details = e.Details()
|
||||
if _, ok := routing.AllMethods[path]; !ok {
|
||||
msg := "not implemented"
|
||||
utils.WriteError(ctx, msg, codes.Unimplemented, nil)
|
||||
return domain.Create().SetError(errors.New(msg))
|
||||
}
|
||||
|
||||
if !p.SkipAuth() {
|
||||
applicationId, err := authenticate.Do(ctx, path)
|
||||
if err != nil {
|
||||
message := "unknown error"
|
||||
status := codes.Unknown
|
||||
details := make([]interface{}, 0)
|
||||
switch e := err.(type) {
|
||||
case authenticate.ErrorDescription:
|
||||
message = e.Message()
|
||||
status = e.ConvertToGrpcStatus()
|
||||
details = e.Details()
|
||||
}
|
||||
utils.WriteError(ctx, message, status, details)
|
||||
return domain.Create().SetError(err)
|
||||
}
|
||||
|
||||
if !accounting.AcceptRequest(applicationId, path) {
|
||||
err := errors.New("accounting error")
|
||||
utils.WriteError(ctx, "too many requests", codes.ResourceExhausted, nil)
|
||||
return domain.Create().SetError(err)
|
||||
}
|
||||
utils.WriteError(ctx, message, status, details)
|
||||
return domain.Create().SetError(err)
|
||||
}
|
||||
|
||||
if !accounting.Accept(applicationId, path) {
|
||||
err := errors.New("accounting error")
|
||||
utils.WriteError(ctx, "too many requests", codes.ResourceExhausted, nil)
|
||||
return domain.Create().SetError(err)
|
||||
}
|
||||
return p.ProxyRequest(ctx)
|
||||
return p.ProxyRequest(ctx, path)
|
||||
}
|
||||
|
||||
func (handlerHelper) SetMetricStatus(statusCode int) string {
|
||||
|
||||
@@ -40,15 +40,13 @@ func main() {
|
||||
RequireRoutes(handleRouteUpdate).
|
||||
RequireModule(journal.RequiredModule())
|
||||
|
||||
for _, location := range cfg.Locations {
|
||||
if p, err := proxy.Init(location); err != nil {
|
||||
log.Fatal(stdcodes.ModuleInvalidLocalConfig, err)
|
||||
} else if location.TargetModule != "" {
|
||||
bs.RequireModule(location.TargetModule, p.Consumer, false)
|
||||
}
|
||||
requiredModules := getRequiredModulesByLocations(cfg.Locations)
|
||||
for module, consumer := range requiredModules {
|
||||
bs.RequireModule(module, consumer, false)
|
||||
}
|
||||
|
||||
bs.OnShutdown(onShutdown).
|
||||
bs.RequireModule(cfg.ModuleName, accounting.NewConnectionConsumer, false).
|
||||
OnShutdown(onShutdown).
|
||||
OnRemoteConfigReceive(onRemoteConfigReceive).
|
||||
Run()
|
||||
}
|
||||
@@ -65,8 +63,8 @@ func onRemoteConfigReceive(remoteConfig, oldRemoteConfig *conf.RemoteConfig) {
|
||||
matcher.JournalMethods = matcher.NewAtLeastOneMatcher(remoteConfig.JournalSetting.MethodsPatterns)
|
||||
|
||||
redis.Client.ReceiveConfiguration(remoteConfig.Redis)
|
||||
accounting.ReceiveConfiguration(remoteConfig.AccountingSetting)
|
||||
authenticate.ReceiveConfiguration(remoteConfig.AuthCacheSetting)
|
||||
accounting.ReceiveConfiguration(remoteConfig.AccountingSetting)
|
||||
|
||||
metric.InitCollectors(remoteConfig.Metrics, oldRemoteConfig.Metrics)
|
||||
metric.InitHttpServer(remoteConfig.Metrics)
|
||||
@@ -109,3 +107,31 @@ func makeDeclaration(localConfig interface{}) bootstrap.ModuleInfo {
|
||||
Handlers: []interface{}{},
|
||||
}
|
||||
}
|
||||
|
||||
func getRequiredModulesByLocations(locations []conf.Location) map[string]func([]structure.AddressConfiguration) bool {
|
||||
locationsByTargetModule := conf.GetLocationsByTargetModule(locations)
|
||||
requiredModules := make(map[string]func([]structure.AddressConfiguration) bool)
|
||||
|
||||
for targetModule, locations := range locationsByTargetModule {
|
||||
consumerStorage := make([]func([]structure.AddressConfiguration) bool, len(locations))
|
||||
for i, location := range locations {
|
||||
if p, err := proxy.Init(location.Protocol, location.PathPrefix, location.SkipAuth); err != nil {
|
||||
log.Fatal(stdcodes.ModuleInvalidLocalConfig, err)
|
||||
} else {
|
||||
consumerStorage[i] = p.Consumer
|
||||
}
|
||||
}
|
||||
requiredModules[targetModule] = aggregateConsumers(consumerStorage...)
|
||||
}
|
||||
|
||||
return requiredModules
|
||||
}
|
||||
|
||||
func aggregateConsumers(consumers ...func([]structure.AddressConfiguration) bool) func([]structure.AddressConfiguration) bool {
|
||||
return func(list []structure.AddressConfiguration) bool {
|
||||
for _, consumer := range consumers {
|
||||
consumer(list)
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
File renamed without changes.
@@ -0,0 +1,6 @@
|
||||
-- +goose Up
|
||||
|
||||
ALTER TABLE snapshot
|
||||
ADD version BIGINT NOT NULL DEFAULT 0;
|
||||
|
||||
-- +goose Down
|
||||
+6
-1
@@ -21,7 +21,12 @@ type (
|
||||
)
|
||||
|
||||
func (r snapshotRepository) Update(list []entity.Snapshot) error {
|
||||
_, err := r.getDb().Model(&list).OnConflict("(app_id) DO UPDATE").Insert()
|
||||
_, err := r.getDb().Model(&list).OnConflict("(app_id) DO UPDATE").
|
||||
Set("version = EXCLUDED.version").
|
||||
Set("app_id = EXCLUDED.app_id").
|
||||
Set("limit_state = EXCLUDED.limit_state").
|
||||
Where("snapshot.version < EXCLUDED.version").
|
||||
Insert()
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
+30
-16
@@ -4,7 +4,6 @@ import (
|
||||
"github.com/integration-system/isp-lib/structure"
|
||||
"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/health_check"
|
||||
@@ -22,41 +21,42 @@ const (
|
||||
|
||||
type (
|
||||
Proxy interface {
|
||||
ProxyRequest(ctx *fasthttp.RequestCtx) domain.ProxyResponse
|
||||
ProxyRequest(ctx *fasthttp.RequestCtx, path string) domain.ProxyResponse
|
||||
Consumer([]structure.AddressConfiguration) bool
|
||||
SkipAuth() bool
|
||||
Close()
|
||||
}
|
||||
)
|
||||
|
||||
func Init(location conf.Location) (Proxy, error) {
|
||||
if location.PathPrefix[0] != '/' {
|
||||
return nil, errors.Errorf("path must begin with '/' in path '%s'", location.PathPrefix)
|
||||
func Init(protocol, pathPrefix string, skipAuth bool) (Proxy, error) {
|
||||
if pathPrefix[0] != '/' {
|
||||
return nil, errors.Errorf("path must begin with '/' in path '%s'", pathPrefix)
|
||||
}
|
||||
switch location.Protocol {
|
||||
switch protocol {
|
||||
case httpProtocol:
|
||||
proxy := http.NewProxy()
|
||||
store[location.PathPrefix] = proxy
|
||||
proxy := http.NewProxy(skipAuth)
|
||||
store[pathPrefix] = proxy
|
||||
return proxy, nil
|
||||
case grpcProtocol:
|
||||
proxy := grpc.NewProxy()
|
||||
store[location.PathPrefix] = proxy
|
||||
proxy := grpc.NewProxy(skipAuth)
|
||||
store[pathPrefix] = proxy
|
||||
return proxy, nil
|
||||
case healthCheckProtocol:
|
||||
proxy := health_check.NewProxy()
|
||||
store[location.PathPrefix] = proxy
|
||||
proxy := health_check.NewProxy(skipAuth)
|
||||
store[pathPrefix] = proxy
|
||||
return proxy, nil
|
||||
default:
|
||||
return nil, errors.Errorf("unknown protocol '%s'", location.Protocol)
|
||||
return nil, errors.Errorf("unknown protocol '%s'", protocol)
|
||||
}
|
||||
}
|
||||
|
||||
func Find(path string) Proxy {
|
||||
func Find(path string) (Proxy, string) {
|
||||
for pathPrefix, proxy := range store {
|
||||
if strings.HasPrefix(path, pathPrefix) {
|
||||
return proxy
|
||||
return proxy, getPathWithoutPrefix(path)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return nil, getPathWithoutPrefix(path)
|
||||
}
|
||||
|
||||
func Close() {
|
||||
@@ -64,3 +64,17 @@ func Close() {
|
||||
p.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func getPathWithoutPrefix(path string) string {
|
||||
firstFound := false
|
||||
for i, value := range path {
|
||||
if value == '/' {
|
||||
if firstFound {
|
||||
return path[i+1:]
|
||||
} else {
|
||||
firstFound = true
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
+21
-15
@@ -16,23 +16,26 @@ import (
|
||||
)
|
||||
|
||||
type grpcProxy struct {
|
||||
client *backend.RxGrpcClient
|
||||
client *backend.RxGrpcClient
|
||||
skipAuth bool
|
||||
}
|
||||
|
||||
func NewProxy() *grpcProxy {
|
||||
return &grpcProxy{client: backend.NewRxGrpcClient(
|
||||
backend.WithDialOptions(
|
||||
grpc.WithInsecure(), grpc.WithBlock(),
|
||||
grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(int(conf.DefaultMaxResponseBodySize))),
|
||||
grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(int(conf.DefaultMaxResponseBodySize))),
|
||||
),
|
||||
backend.WithDialingErrorHandler(func(err error) {
|
||||
log.Errorf(log_code.ErrorClientGrpc, "dialing err: %v", err)
|
||||
}),
|
||||
)}
|
||||
func NewProxy(skiAuth bool) *grpcProxy {
|
||||
return &grpcProxy{
|
||||
client: backend.NewRxGrpcClient(
|
||||
backend.WithDialOptions(
|
||||
grpc.WithInsecure(), grpc.WithBlock(),
|
||||
grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(int(conf.DefaultMaxResponseBodySize))),
|
||||
grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(int(conf.DefaultMaxResponseBodySize))),
|
||||
),
|
||||
backend.WithDialingErrorHandler(func(err error) {
|
||||
log.Errorf(log_code.ErrorClientGrpc, "dialing err: %v", err)
|
||||
})),
|
||||
skipAuth: skiAuth,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *grpcProxy) ProxyRequest(ctx *fasthttp.RequestCtx) domain.ProxyResponse {
|
||||
func (p *grpcProxy) ProxyRequest(ctx *fasthttp.RequestCtx, path string) domain.ProxyResponse {
|
||||
if p.client.InternalGrpcClient == nil {
|
||||
msg := "client undefined"
|
||||
log.Error(log_code.ErrorClientGrpc, msg)
|
||||
@@ -43,14 +46,17 @@ func (p *grpcProxy) ProxyRequest(ctx *fasthttp.RequestCtx) domain.ProxyResponse
|
||||
SetError(errors.New(msg))
|
||||
}
|
||||
|
||||
uri := string(ctx.RequestURI())
|
||||
return handlers.Handler.Get(ctx).Complete(ctx, uri, p.client)
|
||||
return handlers.Handler.Get(ctx).Complete(ctx, path, p.client)
|
||||
}
|
||||
|
||||
func (p *grpcProxy) Consumer(addr []structure.AddressConfiguration) bool {
|
||||
return p.client.ReceiveAddressList(addr)
|
||||
}
|
||||
|
||||
func (p *grpcProxy) SkipAuth() bool {
|
||||
return p.skipAuth
|
||||
}
|
||||
|
||||
func (p *grpcProxy) Close() {
|
||||
p.client.Close()
|
||||
}
|
||||
@@ -128,7 +128,7 @@ func openStream(headers *fasthttp.RequestHeader, method string, timeout time.Dur
|
||||
}
|
||||
|
||||
func makeMetadata(r *fasthttp.RequestHeader, method string) (metadata.MD, string) {
|
||||
method = strings.TrimPrefix(method, "/api/")
|
||||
//method = strings.TrimPrefix(method, "/api/")
|
||||
md := metadata.Pairs(utils.ProxyMethodNameHeader, method)
|
||||
r.VisitAll(func(key, v []byte) {
|
||||
lowerHeader := strings.ToLower(string(key))
|
||||
|
||||
@@ -19,13 +19,7 @@ var handleJson handleJsonDesc
|
||||
type handleJsonDesc struct{}
|
||||
|
||||
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 {
|
||||
streaming.LogError(log_code.TypeData.JsonContent, method, err)
|
||||
streaming.SendError(err.Error(), codes.InvalidArgument, []interface{}{err.Error()}, c)
|
||||
return
|
||||
}*/
|
||||
|
||||
md, methodName := makeMetadata(&c.Request.Header, method)
|
||||
ctx := metadata.NewOutgoingContext(context.Background(), md)
|
||||
@@ -40,7 +34,6 @@ func (p handleJsonDesc) Complete(c *fasthttp.RequestCtx, method string, client *
|
||||
return domain.Create().SetError(err)
|
||||
}
|
||||
|
||||
//structBody := u.ConvertInterfaceToGrpcStruct(body)
|
||||
resp, invokerErr := cli.Request(
|
||||
ctx,
|
||||
&isp.Message{
|
||||
|
||||
@@ -7,20 +7,27 @@ import (
|
||||
)
|
||||
|
||||
type healthCheckProxy struct {
|
||||
skipAuth bool
|
||||
}
|
||||
|
||||
func NewProxy() *healthCheckProxy {
|
||||
return &healthCheckProxy{}
|
||||
func NewProxy(skipAuth bool) *healthCheckProxy {
|
||||
return &healthCheckProxy{skipAuth: skipAuth}
|
||||
}
|
||||
|
||||
func (p *healthCheckProxy) Consumer(addressList []structure.AddressConfiguration) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (p *healthCheckProxy) ProxyRequest(ctx *fasthttp.RequestCtx) domain.ProxyResponse {
|
||||
func (p *healthCheckProxy) ProxyRequest(ctx *fasthttp.RequestCtx, path string) domain.ProxyResponse {
|
||||
ctx.Response.SetBody(ctx.Request.Body())
|
||||
ctx.Request.SetRequestURI(path)
|
||||
return domain.Create()
|
||||
}
|
||||
|
||||
func (p *healthCheckProxy) SkipAuth() bool {
|
||||
return p.skipAuth
|
||||
}
|
||||
|
||||
func (p *healthCheckProxy) Close() {
|
||||
|
||||
}
|
||||
+10
-4
@@ -14,11 +14,12 @@ import (
|
||||
)
|
||||
|
||||
type httpProxy struct {
|
||||
client *fasthttp.HostClient
|
||||
client *fasthttp.HostClient
|
||||
skipAuth bool
|
||||
}
|
||||
|
||||
func NewProxy() *httpProxy {
|
||||
return &httpProxy{client: nil}
|
||||
func NewProxy(skipAuth bool) *httpProxy {
|
||||
return &httpProxy{client: nil, skipAuth: skipAuth}
|
||||
}
|
||||
|
||||
func (p *httpProxy) Consumer(addressList []structure.AddressConfiguration) bool {
|
||||
@@ -33,7 +34,7 @@ func (p *httpProxy) Consumer(addressList []structure.AddressConfiguration) bool
|
||||
return true
|
||||
}
|
||||
|
||||
func (p *httpProxy) ProxyRequest(ctx *fasthttp.RequestCtx) domain.ProxyResponse {
|
||||
func (p *httpProxy) ProxyRequest(ctx *fasthttp.RequestCtx, path string) domain.ProxyResponse {
|
||||
if p.client == nil {
|
||||
msg := "client undefined"
|
||||
log.Error(log_code.ErrorClientHttp, msg)
|
||||
@@ -46,6 +47,7 @@ func (p *httpProxy) ProxyRequest(ctx *fasthttp.RequestCtx) domain.ProxyResponse
|
||||
|
||||
req := &ctx.Request
|
||||
res := &ctx.Response
|
||||
req.SetRequestURI(path)
|
||||
|
||||
if addr, _, err := net.SplitHostPort(ctx.RemoteAddr().String()); err == nil {
|
||||
req.Header.Add("X-Forwarded-For", addr)
|
||||
@@ -61,6 +63,10 @@ func (p *httpProxy) ProxyRequest(ctx *fasthttp.RequestCtx) domain.ProxyResponse
|
||||
SetError(err)
|
||||
}
|
||||
|
||||
func (p *httpProxy) SkipAuth() bool {
|
||||
return p.skipAuth
|
||||
}
|
||||
|
||||
func (p *httpProxy) Close() {
|
||||
p.client = nil
|
||||
}
|
||||
Reference in new issue
Block a user