fix recovery accounting

This commit is contained in:
DeniskaRediska committed 2019-11-27 13:46:46 +03:00
1 parent 909ff91b2b
commit 1ffe9e4a62
6 files changed
+148 -66

No files matched your search

+3 -6
View File
@@ -30,16 +30,13 @@ func (app *accountant) Accept(method string) bool {
return resp
}
func (app *accountant) Snapshot() map[string]state.Snapshot {
func (app *accountant) Snapshot() (map[string]state.Snapshot, int64) {
app.mx.Lock()
version := atomic.LoadInt64(&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
}
func (app *accountant) GetVersion() int64 {
return atomic.LoadInt64(&app.version)
return snapshotLimitState, version
}
+65 -38
View File
@@ -15,29 +15,38 @@ 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
GetVersion() int64
var Worker = &worker{
process: false,
accountingStorage: make(map[int32]Accounting),
requestsStoring: make(map[int32]bool),
}
func Consumer(list []structure.AddressConfiguration) bool {
type (
Accounting interface {
Accept(string) bool
Snapshot() (map[string]state.Snapshot, int64)
}
worker struct {
mx sync.RWMutex
process bool
accountingStorage map[int32]Accounting
requestsStoring map[int32]bool
}
)
func (w *worker) Consumer(list []structure.AddressConfiguration) bool {
accountingSetting := config.GetRemote().(*conf.RemoteConfig).AccountingSetting
ReceiveConfiguration(accountingSetting)
w.ReceiveConfiguration(accountingSetting)
return true
}
func ReceiveConfiguration(conf conf.Accounting) {
Close()
func (w *worker) ReceiveConfiguration(conf conf.Accounting) {
w.Close()
newAccountingStorage := make(map[int32]Accounting)
newRequestsStoring := make(map[int32]bool)
process := false
if conf.Enable {
if err := InitStoringTask(conf.Storing); err != nil {
@@ -52,7 +61,7 @@ func ReceiveConfiguration(conf conf.Accounting) {
log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err)
}
version := recoveryAccounting(s.ApplicationId, limitStates)
version := w.recoveryAccounting(s.ApplicationId, limitStates)
newAccountingStorage[s.ApplicationId] = &accountant{
version: version,
@@ -68,69 +77,87 @@ func ReceiveConfiguration(conf conf.Accounting) {
go snapshot.Start(snapshotTimeout)
}
accountingWorking = true
} else {
accountingWorking = false
process = true
}
requestsStoring = newRequestsStoring
accountingStorage = newAccountingStorage
w.mx.Lock()
w.requestsStoring = newRequestsStoring
w.accountingStorage = newAccountingStorage
w.process = process
w.mx.Unlock()
}
func Accept(appId int32, path string) bool {
if accouter, ok := accountingStorage[appId]; !ok {
if requestsStoring[appId] {
func (w *worker) AcceptRequest(appId int32, path string) bool {
w.mx.RLock()
defer w.mx.RUnlock()
if accouter, ok := w.accountingStorage[appId]; !ok {
if w.requestsStoring[appId] {
storage.TakeRequest(appId, path, time.Now())
}
return true
} else {
ok := accouter.Accept(path)
if ok && requestsStoring[appId] {
if ok && w.requestsStoring[appId] {
storage.TakeRequest(appId, path, time.Now())
}
return ok
}
}
func Close() {
func (w *worker) Close() {
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 *worker) takeSnapshot() []entity.Snapshot {
w.mx.RLock()
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(),
Version: account.GetVersion(),
LimitState: limitState,
Version: version,
})
}
w.mx.RUnlock()
return response
}
func recoveryAccounting(appId int32, limitStates map[string]state.LimitState) int64 {
func (w *worker) recoveryAccounting(appId int32, limitStates map[string]state.LimitState) int64 {
version := int64(0)
if accountingWorking {
if acc, ok := accountingStorage[appId]; ok {
version = acc.GetVersion()
snapshot := acc.Snapshot()
importLimitState(limitStates, snapshot)
w.mx.RLock()
if w.process {
if acc, ok := w.accountingStorage[appId]; ok {
cashLimitState, cashVersion := acc.Snapshot()
dbSnapshot, err := model.SnapshotRep.GetByApplication(appId)
if err != nil {
log.Warn(log_code.ErrorSnapshotAccounting, err)
}
if dbSnapshot != nil && dbSnapshot.Version > cashVersion {
w.importLimitState(limitStates, dbSnapshot.LimitState)
} else {
w.importLimitState(limitStates, cashLimitState)
}
}
} else {
if snapshot, err := model.SnapshotRep.GetByApplication(appId); err != nil {
log.Warn(log_code.ErrorSnapshotAccounting, err)
} else if snapshot != nil {
version = snapshot.Version
importLimitState(limitStates, snapshot.LimitState)
w.importLimitState(limitStates, snapshot.LimitState)
}
}
w.mx.RUnlock()
return version
}
func importLimitState(limitStates map[string]state.LimitState, snapshot map[string]state.Snapshot) {
func (w *worker) 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)
+75 -17
View File
@@ -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,18 @@ var (
func TestAccounting(t *testing.T) {
a := assert.New(t)
model.SnapshotRep = &snapshotRepository{cache: make(map[int32]map[string]state.Snapshot)}
ReceiveConfiguration(accountingSetting)
model.SnapshotRep = newSnapshotRepository(false)
Worker.ReceiveConfiguration(accountingSetting)
req := reqExample[4]
for _, path := range req.path {
a.True(Accept(req.appId, path))
a.True(Worker.AcceptRequest(req.appId, path))
}
expected := true
req = reqExample[0]
for _, path := range req.path {
a.Equal(expected, Accept(req.appId, path))
a.Equal(expected, Worker.AcceptRequest(req.appId, path))
expected = !expected
time.Sleep(50 * time.Millisecond)
}
@@ -81,49 +82,106 @@ 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, Worker.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], Worker.AcceptRequest(req.appId, path))
}
//expected == true
req = reqExample[3]
for _, path := range req.path {
a.Equal(expected, Accept(req.appId, path))
a.Equal(expected, Worker.AcceptRequest(req.appId, path))
}
ReceiveConfiguration(accountingSetting)
Worker.ReceiveConfiguration(accountingSetting)
req = reqExample[4]
for _, path := range req.path {
a.False(Accept(req.appId, path))
a.False(Worker.AcceptRequest(req.appId, path))
}
}
func TestWorker_recoveryAccounting(t *testing.T) {
a := assert.New(t)
snapshotRep := newSnapshotRepository(true)
model.SnapshotRep = snapshotRep
oldWorker := &worker{
process: false,
accountingStorage: make(map[int32]Accounting),
requestsStoring: make(map[int32]bool),
}
Worker.ReceiveConfiguration(accountingSetting)
oldWorker.ReceiveConfiguration(accountingSetting)
request := "1_3_5"
for range request {
a.True(Worker.AcceptRequest(1, "mdm-master/group6/method"))
}
a.False(Worker.AcceptRequest(1, "mdm-master/group6/method"))
time.Sleep(time.Millisecond * 300)
a.True(snapshotRep.Wait())
snapshot, err := model.SnapshotRep.GetByApplication(1)
a.NoError(err)
a.NotNil(snapshot)
a.Equal(len(request), int(snapshot.Version))
Worker = oldWorker
Worker.ReceiveConfiguration(accountingSetting)
a.False(Worker.AcceptRequest(1, "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(enableUpdate bool) *snapshotRepository {
return &snapshotRepository{
enableWaitGroup: enableUpdate,
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
}
+1 -1
View File
@@ -52,6 +52,6 @@ func (s *snapshotTask) Stop() {
}
func (s *snapshotTask) saveSnapshot() error {
snapshotList := takeSnapshot()
snapshotList := Worker.takeSnapshot()
return model.SnapshotRep.Update(snapshotList)
}
+1 -1
View File
@@ -88,7 +88,7 @@ func (handlerHelper) AuthenticateAccountingProxy(ctx *fasthttp.RequestCtx) domai
return domain.Create().SetError(err)
}
if !accounting.Accept(applicationId, path) {
if !accounting.Worker.AcceptRequest(applicationId, path) {
err := errors.New("accounting error")
utils.WriteError(ctx, "too many requests", codes.ResourceExhausted, nil)
return domain.Create().SetError(err)
+3 -3
View File
@@ -45,7 +45,7 @@ func main() {
bs.RequireModule(module, consumer, false)
}
bs.RequireModule(cfg.ModuleName, accounting.Consumer, false).
bs.RequireModule(cfg.ModuleName, accounting.Worker.Consumer, false).
OnShutdown(onShutdown).
OnRemoteConfigReceive(onRemoteConfigReceive).
Run()
@@ -64,7 +64,7 @@ func onRemoteConfigReceive(remoteConfig, oldRemoteConfig *conf.RemoteConfig) {
redis.Client.ReceiveConfiguration(remoteConfig.Redis)
authenticate.ReceiveConfiguration(remoteConfig.AuthCacheSetting)
accounting.ReceiveConfiguration(remoteConfig.AccountingSetting)
accounting.Worker.ReceiveConfiguration(remoteConfig.AccountingSetting)
metric.InitCollectors(remoteConfig.Metrics, oldRemoteConfig.Metrics)
metric.InitHttpServer(remoteConfig.Metrics)
@@ -88,7 +88,7 @@ func socketConfiguration(cfg interface{}) structure.SocketConfiguration {
func onShutdown(_ context.Context, _ os.Signal) {
server.Http.Close()
accounting.Close()
accounting.Worker.Close()
proxy.Close()
redis.Client.Close()
}