Files

83 lines
2.1 KiB
Go

package store
import (
"database/sql"
"errors"
)
const (
DefaultLogShardMaxBytes int64 = 256 << 20
MinLogShardMaxBytes int64 = 16 << 20
MaxLogShardMaxBytes int64 = 4 << 30
)
// LogSettings is configuration for append-oriented audit shard files.
type LogSettings struct {
MaxBytes int64 `json:"maxBytes"`
DefaultBytes int64 `json:"defaultBytes"`
MinBytes int64 `json:"minBytes"`
MaxAllowedBytes int64 `json:"maxAllowedBytes"`
}
func validateLogShardMaxBytes(value int64) error {
if value < MinLogShardMaxBytes || value > MaxLogShardMaxBytes {
return errors.New("maxBytes must be between 16777216 and 4294967296")
}
return nil
}
func (s *Store) initLogSettings() error {
if _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS log_settings(
id INTEGER PRIMARY KEY CHECK(id=1),
max_bytes INTEGER NOT NULL
);`); err != nil {
return err
}
var value int64
err := s.db.QueryRow("SELECT max_bytes FROM log_settings WHERE id=1").Scan(&value)
if err == sql.ErrNoRows {
value = DefaultLogShardMaxBytes
if _, err = s.db.Exec("INSERT INTO log_settings(id,max_bytes) VALUES(1,?)", value); err != nil {
return err
}
} else if err != nil {
return err
}
if err = validateLogShardMaxBytes(value); err != nil {
return err
}
s.auditMu.Lock()
s.auditMaxBytes = value
s.auditMu.Unlock()
return nil
}
func (s *Store) LogSettings() (LogSettings, error) {
var value int64
if err := s.db.QueryRow("SELECT max_bytes FROM log_settings WHERE id=1").Scan(&value); err != nil {
return LogSettings{}, err
}
if err := validateLogShardMaxBytes(value); err != nil {
return LogSettings{}, err
}
return LogSettings{
MaxBytes: value,
DefaultBytes: DefaultLogShardMaxBytes,
MinBytes: MinLogShardMaxBytes,
MaxAllowedBytes: MaxLogShardMaxBytes,
}, nil
}
func (s *Store) SaveLogSettings(value int64) error {
if err := validateLogShardMaxBytes(value); err != nil {
return err
}
if _, err := s.db.Exec("INSERT INTO log_settings(id,max_bytes) VALUES(1,?) ON CONFLICT(id) DO UPDATE SET max_bytes=excluded.max_bytes", value); err != nil {
return err
}
s.auditMu.Lock()
s.auditMaxBytes = value
s.auditMu.Unlock()
return nil
}