Files

134 lines
3.4 KiB
Go

package exploits
import (
"fmt"
"strings"
"sync"
"github.com/samber/lo"
"github.com/sirupsen/logrus"
bolt "go.etcd.io/bbolt"
"google.golang.org/protobuf/proto"
epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
)
const (
stateBucketKey = "states"
)
func NewBoltStorage(path string) (*CachedStorage, error) {
db, err := bolt.Open(path, 0755, nil)
if err != nil {
return nil, fmt.Errorf("открытие базы Bolt %s: %w", path, err)
}
return NewStorage(db)
}
func NewStorage(db *bolt.DB) (*CachedStorage, error) {
cs := &CachedStorage{
stateCache: nil,
bdb: db,
}
if err := cs.initDB(); err != nil {
return nil, err
}
cs.initCache()
return cs, nil
}
type CachedStorage struct {
stateCache map[string]*epb.ExploitState
m sync.RWMutex
bdb *bolt.DB
}
func (cs *CachedStorage) States() []*epb.ExploitState {
cs.m.RLock()
defer cs.m.RUnlock()
return lo.Values(cs.stateCache)
}
func (cs *CachedStorage) GetState(exploitID string) (*epb.ExploitState, bool) {
cs.m.RLock()
defer cs.m.RUnlock()
val, ok := cs.stateCache[exploitID]
return val, ok
}
func (cs *CachedStorage) UpdateExploitVersion(newState *epb.ExploitState) (*epb.ExploitState, error) {
cs.m.Lock()
defer cs.m.Unlock()
if state, ok := cs.stateCache[newState.ExploitId]; ok {
newState.Version = state.Version + 1
} else {
newState.Version = 1
}
key := []byte(fmt.Sprintf("%s:%d", newState.ExploitId, newState.Version))
stateBytes, err := proto.Marshal(newState)
if err != nil {
return nil, fmt.Errorf("сериализация состояния: %w", err)
}
if err := cs.bdb.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(stateBucketKey))
if err := b.Put(key, stateBytes); err != nil {
return fmt.Errorf("сохранение состояния в базе: %w", err)
}
return nil
}); err != nil {
return nil, fmt.Errorf("обновление состояния в базе: %w", err)
}
cs.stateCache[newState.ExploitId] = newState
return newState, nil
}
func (cs *CachedStorage) initCache() {
cs.m.Lock()
defer cs.m.Unlock()
if cs.stateCache == nil {
cs.stateCache = make(map[string]*epb.ExploitState)
if err := cs.readDB(); err != nil {
logrus.Errorf("Не удалось прочитать данные эксплойта из базы: %v", err)
}
}
}
func (cs *CachedStorage) readDB() error {
if err := cs.bdb.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(stateBucketKey))
if err := b.ForEach(func(k, v []byte) error {
key := string(k)
eID := strings.Split(key, ":")[0]
es := new(epb.ExploitState)
if err := proto.Unmarshal(v, es); err != nil {
return fmt.Errorf("разбор состояния эксплойта: %w", err)
}
if v, ok := cs.stateCache[eID]; !ok || es.Version > v.Version {
cs.stateCache[eID] = es
}
return nil
}); err != nil {
return fmt.Errorf("чтение состояний эксплойтов: %w", err)
}
return nil
}); err != nil {
return fmt.Errorf("чтение состояния из базы: %w", err)
}
return nil
}
func (cs *CachedStorage) initDB() error {
if err := cs.bdb.Update(func(tx *bolt.Tx) error {
if _, err := tx.CreateBucketIfNotExists([]byte(stateBucketKey)); err != nil {
return fmt.Errorf("создание раздела состояний: %w", err)
}
return nil
}); err != nil {
return fmt.Errorf("инициализация базы: %w", err)
}
return nil
}