all: rewrite api
This commit is contained in:
parent
480b42c596
commit
e5871f45be
|
@ -65,9 +65,9 @@ func GenerateHostname(ip net.IP) (hostname string) {
|
|||
return generateIPv6Hostname(ip)
|
||||
}
|
||||
|
||||
// NewDomainNameSet returns nil and error, if list has duplicate or empty host
|
||||
// name. Otherwise returns a set, which contains lowercase host names without
|
||||
// dot at the end, and nil error.
|
||||
// NewDomainNameSet returns nil and error, if list has duplicate or empty
|
||||
// domain name. Otherwise returns a set, which contains non-FQDN domain names,
|
||||
// and nil error.
|
||||
func NewDomainNameSet(list []string) (set *stringutil.Set, err error) {
|
||||
set = stringutil.NewSet()
|
||||
|
||||
|
|
|
@ -240,9 +240,8 @@ type statsConfig struct {
|
|||
// Enabled defines if the statistics are enabled.
|
||||
Enabled bool `yaml:"enabled"`
|
||||
|
||||
// Interval is the time interval for flushing statistics to the disk in
|
||||
// days.
|
||||
Interval uint32 `yaml:"interval"`
|
||||
// Interval is the time interval for flushing statistics to the disk.
|
||||
Interval timeutil.Duration `yaml:"interval"`
|
||||
|
||||
// Ignored is the list of host names, which should not be counted.
|
||||
Ignored []string `yaml:"ignored"`
|
||||
|
@ -306,7 +305,7 @@ var config = &configuration{
|
|||
},
|
||||
Stats: statsConfig{
|
||||
Enabled: true,
|
||||
Interval: 1,
|
||||
Interval: timeutil.Duration{Duration: 1 * timeutil.Day},
|
||||
Ignored: []string{},
|
||||
},
|
||||
// NOTE: Keep these parameters in sync with the one put into
|
||||
|
@ -487,7 +486,7 @@ func (c *configuration) write() (err error) {
|
|||
if Context.stats != nil {
|
||||
statsConf := stats.Config{}
|
||||
Context.stats.WriteDiskConfig(&statsConf)
|
||||
config.Stats.Interval = statsConf.LimitDays
|
||||
config.Stats.Interval = timeutil.Duration{Duration: statsConf.LimitDays}
|
||||
config.Stats.Enabled = statsConf.Enabled
|
||||
config.Stats.Ignored = statsConf.Ignored.Values()
|
||||
sort.Strings(config.Stats.Ignored)
|
||||
|
|
|
@ -51,7 +51,7 @@ func initDNS() (err error) {
|
|||
|
||||
statsConf := stats.Config{
|
||||
Filename: filepath.Join(baseDir, "stats.db"),
|
||||
LimitDays: config.Stats.Interval,
|
||||
LimitDays: config.Stats.Interval.Duration,
|
||||
ConfigModified: onConfigModified,
|
||||
HTTPRegister: httpRegister,
|
||||
Enabled: config.Stats.Enabled,
|
||||
|
@ -87,7 +87,10 @@ func initDNS() (err error) {
|
|||
}
|
||||
|
||||
conf.Ignored = set
|
||||
Context.queryLog = querylog.New(conf)
|
||||
Context.queryLog, err = querylog.New(conf)
|
||||
if err != nil {
|
||||
return fmt.Errorf("init querylog: %w", err)
|
||||
}
|
||||
|
||||
Context.filters, err = filtering.New(config.DNS.DnsfilterConf, nil)
|
||||
if err != nil {
|
||||
|
|
|
@ -101,9 +101,16 @@ func (l *queryLog) handleQueryLogInfo(w http.ResponseWriter, r *http.Request) {
|
|||
l.lock.Lock()
|
||||
defer l.lock.Unlock()
|
||||
|
||||
ivl := l.conf.RotationIvl
|
||||
|
||||
ok := checkInterval(ivl)
|
||||
if !ok {
|
||||
ivl = timeutil.Day * 90
|
||||
}
|
||||
|
||||
_ = aghhttp.WriteJSONResponse(w, r, configJSON{
|
||||
Enabled: aghalg.BoolToNullBool(l.conf.Enabled),
|
||||
Interval: l.conf.RotationIvl.Hours() / 24,
|
||||
Interval: ivl.Hours() / 24,
|
||||
AnonymizeClientIP: aghalg.BoolToNullBool(l.conf.AnonymizeClientIP),
|
||||
})
|
||||
}
|
||||
|
@ -117,8 +124,7 @@ func (l *queryLog) handleQueryLogInfoV2(w http.ResponseWriter, r *http.Request)
|
|||
ignored := l.conf.Ignored.Values()
|
||||
_ = aghhttp.WriteJSONResponse(w, r, configJSONv2{
|
||||
Enabled: aghalg.BoolToNullBool(l.conf.Enabled),
|
||||
// 1 hour = 3,600,000 ms
|
||||
Interval: l.conf.RotationIvl.Hours() * 3_600_000,
|
||||
Interval: float64(l.conf.RotationIvl.Milliseconds()),
|
||||
AnonymizeClientIP: aghalg.BoolToNullBool(l.conf.AnonymizeClientIP),
|
||||
Ignored: ignored,
|
||||
})
|
||||
|
@ -192,8 +198,6 @@ func (l *queryLog) handleQueryLogConfig(w http.ResponseWriter, r *http.Request)
|
|||
// handleQueryLogConfigV2 handles the PUT /control/querylog/config/update
|
||||
// queries.
|
||||
func (l *queryLog) handleQueryLogConfigV2(w http.ResponseWriter, r *http.Request) {
|
||||
// Set NaN as initial value to be able to know if it changed later by
|
||||
// comparing it to NaN.
|
||||
newConf := &configJSONv2{}
|
||||
|
||||
err := json.NewDecoder(r.Body).Decode(newConf)
|
||||
|
@ -205,7 +209,7 @@ func (l *queryLog) handleQueryLogConfigV2(w http.ResponseWriter, r *http.Request
|
|||
|
||||
ivl := time.Duration(float64(time.Millisecond) * newConf.Interval)
|
||||
|
||||
if ivl < time.Hour || ivl > timeutil.Day*366 || !checkInterval(ivl) {
|
||||
if ivl < time.Hour || ivl > timeutil.Day*365 {
|
||||
aghhttp.Error(r, w, http.StatusBadRequest, "unsupported interval")
|
||||
|
||||
return
|
||||
|
@ -240,9 +244,9 @@ func (l *queryLog) handleQueryLogConfigV2(w http.ResponseWriter, r *http.Request
|
|||
aghhttp.Error(r, w, http.StatusBadRequest, "ignored: %s", serr)
|
||||
|
||||
return
|
||||
} else {
|
||||
conf.Ignored = set
|
||||
}
|
||||
|
||||
conf.Ignored = set
|
||||
}
|
||||
|
||||
l.conf = &conf
|
||||
|
|
|
@ -25,13 +25,14 @@ func TestMain(m *testing.M) {
|
|||
// TestQueryLog tests adding and loading (with filtering) entries from disk and
|
||||
// memory.
|
||||
func TestQueryLog(t *testing.T) {
|
||||
l := newQueryLog(Config{
|
||||
l, err := newQueryLog(Config{
|
||||
Enabled: true,
|
||||
FileEnabled: true,
|
||||
RotationIvl: timeutil.Day,
|
||||
MemSize: 100,
|
||||
BaseDir: t.TempDir(),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Add disk entries.
|
||||
addEntry(l, "example.org", net.IPv4(1, 1, 1, 1), net.IPv4(2, 2, 2, 1))
|
||||
|
@ -128,12 +129,13 @@ func TestQueryLog(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestQueryLogOffsetLimit(t *testing.T) {
|
||||
l := newQueryLog(Config{
|
||||
l, err := newQueryLog(Config{
|
||||
Enabled: true,
|
||||
RotationIvl: timeutil.Day,
|
||||
MemSize: 100,
|
||||
BaseDir: t.TempDir(),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
const (
|
||||
entNum = 10
|
||||
|
@ -202,13 +204,14 @@ func TestQueryLogOffsetLimit(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestQueryLogMaxFileScanEntries(t *testing.T) {
|
||||
l := newQueryLog(Config{
|
||||
l, err := newQueryLog(Config{
|
||||
Enabled: true,
|
||||
FileEnabled: true,
|
||||
RotationIvl: timeutil.Day,
|
||||
MemSize: 100,
|
||||
BaseDir: t.TempDir(),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
const entNum = 10
|
||||
// Add entries to the log.
|
||||
|
@ -230,13 +233,14 @@ func TestQueryLogMaxFileScanEntries(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestQueryLogFileDisabled(t *testing.T) {
|
||||
l := newQueryLog(Config{
|
||||
l, err := newQueryLog(Config{
|
||||
Enabled: true,
|
||||
FileEnabled: false,
|
||||
RotationIvl: timeutil.Day,
|
||||
MemSize: 2,
|
||||
BaseDir: t.TempDir(),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
addEntry(l, "example1.org", net.IPv4(1, 1, 1, 1), net.IPv4(2, 2, 2, 1))
|
||||
addEntry(l, "example2.org", net.IPv4(1, 1, 1, 1), net.IPv4(2, 2, 2, 1))
|
||||
|
@ -257,13 +261,14 @@ func TestQueryLogShouldLog(t *testing.T) {
|
|||
)
|
||||
set := stringutil.NewSet(ignored1, ignored2)
|
||||
|
||||
l := newQueryLog(Config{
|
||||
l, err := newQueryLog(Config{
|
||||
Enabled: true,
|
||||
RotationIvl: timeutil.Day,
|
||||
MemSize: 100,
|
||||
BaseDir: t.TempDir(),
|
||||
Ignored: set,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
|
|
|
@ -9,7 +9,6 @@ import (
|
|||
"github.com/AdguardTeam/AdGuardHome/internal/aghnet"
|
||||
"github.com/AdguardTeam/AdGuardHome/internal/filtering"
|
||||
"github.com/AdguardTeam/golibs/errors"
|
||||
"github.com/AdguardTeam/golibs/log"
|
||||
"github.com/AdguardTeam/golibs/stringutil"
|
||||
"github.com/AdguardTeam/golibs/timeutil"
|
||||
"github.com/miekg/dns"
|
||||
|
@ -135,12 +134,12 @@ func (p *AddParams) validate() (err error) {
|
|||
}
|
||||
|
||||
// New creates a new instance of the query log.
|
||||
func New(conf Config) (ql QueryLog) {
|
||||
func New(conf Config) (ql QueryLog, err error) {
|
||||
return newQueryLog(conf)
|
||||
}
|
||||
|
||||
// newQueryLog crates a new queryLog.
|
||||
func newQueryLog(conf Config) (l *queryLog) {
|
||||
func newQueryLog(conf Config) (l *queryLog, err error) {
|
||||
findClient := conf.FindClient
|
||||
if findClient == nil {
|
||||
findClient = func(_ []string) (_ *Client, _ error) {
|
||||
|
@ -158,13 +157,12 @@ func newQueryLog(conf Config) (l *queryLog) {
|
|||
l.conf = &Config{}
|
||||
*l.conf = conf
|
||||
|
||||
if !checkInterval(conf.RotationIvl) {
|
||||
log.Info(
|
||||
"querylog: warning: unsupported rotation interval %s, setting to 1 day",
|
||||
conf.RotationIvl,
|
||||
)
|
||||
l.conf.RotationIvl = timeutil.Day
|
||||
if conf.RotationIvl < time.Hour {
|
||||
return nil, errors.Error("interval: less than an hour")
|
||||
}
|
||||
if conf.RotationIvl > timeutil.Day*365 {
|
||||
return nil, errors.Error("interval: more than a year")
|
||||
}
|
||||
|
||||
return l
|
||||
return l, nil
|
||||
}
|
||||
|
|
|
@ -35,7 +35,7 @@ func TestQueryLog_Search_findClient(t *testing.T) {
|
|||
return nil, nil
|
||||
}
|
||||
|
||||
l := newQueryLog(Config{
|
||||
l, err := newQueryLog(Config{
|
||||
FindClient: findClient,
|
||||
BaseDir: t.TempDir(),
|
||||
RotationIvl: timeutil.Day,
|
||||
|
@ -44,6 +44,7 @@ func TestQueryLog_Search_findClient(t *testing.T) {
|
|||
FileEnabled: true,
|
||||
AnonymizeClientIP: false,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(l.Close)
|
||||
|
||||
q := &dns.Msg{
|
||||
|
|
|
@ -47,7 +47,7 @@ func (s *StatsCtx) handleStats(w http.ResponseWriter, r *http.Request) {
|
|||
defer s.lock.Unlock()
|
||||
|
||||
start := time.Now()
|
||||
resp, ok := s.getData(s.limitHours)
|
||||
resp, ok := s.getData(uint32(s.limitHours.Hours()))
|
||||
log.Debug("stats: prepared data in %v", time.Since(start))
|
||||
|
||||
if !ok {
|
||||
|
@ -84,7 +84,15 @@ func (s *StatsCtx) handleStatsInfo(w http.ResponseWriter, r *http.Request) {
|
|||
s.lock.Lock()
|
||||
defer s.lock.Unlock()
|
||||
|
||||
resp := configResp{IntervalDays: s.limitHours / 24}
|
||||
days := uint32(s.limitHours.Hours() / 24)
|
||||
|
||||
ok := checkInterval(days)
|
||||
if !ok || (s.enabled && days == 0) {
|
||||
t := timeutil.Day * 90
|
||||
days = uint32(t.Hours() / 24)
|
||||
}
|
||||
|
||||
resp := configResp{IntervalDays: days}
|
||||
if !s.enabled {
|
||||
resp.IntervalDays = 0
|
||||
}
|
||||
|
@ -98,28 +106,28 @@ func (s *StatsCtx) handleStatsInfoV2(w http.ResponseWriter, r *http.Request) {
|
|||
|
||||
resp := configRespV2{
|
||||
Enabled: aghalg.BoolToNullBool(s.enabled),
|
||||
// 1 hour = 3,600,600 ms
|
||||
Interval: float64(s.limitHours) * 3_600_000,
|
||||
Interval: float64(s.limitHours.Milliseconds()),
|
||||
Ignored: s.ignored.Values(),
|
||||
}
|
||||
_ = aghhttp.WriteJSONResponse(w, r, resp)
|
||||
err := aghhttp.WriteJSONResponse(w, r, resp)
|
||||
if err != nil {
|
||||
log.Debug("stats: write response: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
// handleStatsConfig handles requests to the POST /v2/control/stats_config
|
||||
// handleStatsConfig handles requests to the POST /control/stats_config
|
||||
// endpoint.
|
||||
func (s *StatsCtx) handleStatsConfig(w http.ResponseWriter, r *http.Request) {
|
||||
reqData := configResp{}
|
||||
err := json.NewDecoder(r.Body).Decode(&reqData)
|
||||
if err != nil {
|
||||
aghhttp.Error(r, w, http.StatusBadRequest, "json decode: %s", err)
|
||||
s.lock.Unlock()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if !checkInterval(reqData.IntervalDays) {
|
||||
aghhttp.Error(r, w, http.StatusBadRequest, "Unsupported interval")
|
||||
s.lock.Unlock()
|
||||
|
||||
return
|
||||
}
|
||||
|
@ -130,11 +138,9 @@ func (s *StatsCtx) handleStatsConfig(w http.ResponseWriter, r *http.Request) {
|
|||
defer s.lock.Unlock()
|
||||
|
||||
s.setLimit(int(reqData.IntervalDays))
|
||||
|
||||
s.configModified()
|
||||
}
|
||||
|
||||
// handleStatsConfigV2 handles requests to the POST /v2/control/stats_config
|
||||
// handleStatsConfigV2 handles requests to the POST /control/stats_config
|
||||
// endpoint.
|
||||
func (s *StatsCtx) handleStatsConfigV2(w http.ResponseWriter, r *http.Request) {
|
||||
reqData := configRespV2{}
|
||||
|
@ -146,9 +152,8 @@ func (s *StatsCtx) handleStatsConfigV2(w http.ResponseWriter, r *http.Request) {
|
|||
}
|
||||
|
||||
ivl := time.Duration(float64(time.Millisecond) * reqData.Interval)
|
||||
days := ivl.Hours() / 24
|
||||
|
||||
if ivl < time.Hour || ivl > timeutil.Day*366 || !checkInterval(uint32(days)) {
|
||||
if ivl < time.Hour || ivl > timeutil.Day*365 {
|
||||
aghhttp.Error(r, w, http.StatusBadRequest, "unsupported interval")
|
||||
|
||||
return
|
||||
|
@ -159,7 +164,9 @@ func (s *StatsCtx) handleStatsConfigV2(w http.ResponseWriter, r *http.Request) {
|
|||
s.lock.Lock()
|
||||
defer s.lock.Unlock()
|
||||
|
||||
s.setLimit(int(days))
|
||||
s.enabled = reqData.Enabled == aghalg.NBTrue
|
||||
|
||||
s.limitHours = ivl
|
||||
|
||||
if len(reqData.Ignored) > 0 {
|
||||
set, serr := aghnet.NewDomainNameSet(reqData.Ignored)
|
||||
|
@ -167,9 +174,9 @@ func (s *StatsCtx) handleStatsConfigV2(w http.ResponseWriter, r *http.Request) {
|
|||
aghhttp.Error(r, w, http.StatusBadRequest, "ignored: %s", serr)
|
||||
|
||||
return
|
||||
} else {
|
||||
s.ignored = set
|
||||
}
|
||||
|
||||
s.ignored = set
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -16,6 +16,7 @@ import (
|
|||
"github.com/AdguardTeam/golibs/errors"
|
||||
"github.com/AdguardTeam/golibs/log"
|
||||
"github.com/AdguardTeam/golibs/stringutil"
|
||||
"github.com/AdguardTeam/golibs/timeutil"
|
||||
"go.etcd.io/bbolt"
|
||||
)
|
||||
|
||||
|
@ -44,7 +45,7 @@ type Config struct {
|
|||
|
||||
// LimitDays is the maximum number of days to collect statistics into the
|
||||
// current unit.
|
||||
LimitDays uint32
|
||||
LimitDays time.Duration
|
||||
|
||||
// Enabled tells if the statistics are enabled.
|
||||
Enabled bool
|
||||
|
@ -107,9 +108,7 @@ type StatsCtx struct {
|
|||
|
||||
// limitHours is the maximum number of hours to collect statistics into the
|
||||
// current unit.
|
||||
//
|
||||
// TODO(s.chzhen): Rewrite to use time.Duration.
|
||||
limitHours uint32
|
||||
limitHours time.Duration
|
||||
|
||||
// ignored is the list of host names, which should not be counted.
|
||||
ignored *stringutil.Set
|
||||
|
@ -128,9 +127,15 @@ func New(conf Config) (s *StatsCtx, err error) {
|
|||
httpRegister: conf.HTTPRegister,
|
||||
ignored: conf.Ignored,
|
||||
}
|
||||
if s.limitHours = conf.LimitDays * 24; !checkInterval(conf.LimitDays) {
|
||||
s.limitHours = 24
|
||||
|
||||
if conf.LimitDays < time.Hour {
|
||||
return nil, errors.Error("interval: less than an hour")
|
||||
}
|
||||
if conf.LimitDays > timeutil.Day*365 {
|
||||
return nil, errors.Error("interval: more than a year")
|
||||
}
|
||||
s.limitHours = conf.LimitDays
|
||||
|
||||
if s.unitIDGen = newUnitID; conf.UnitID != nil {
|
||||
s.unitIDGen = conf.UnitID
|
||||
}
|
||||
|
@ -150,7 +155,7 @@ func New(conf Config) (s *StatsCtx, err error) {
|
|||
return nil, fmt.Errorf("stats: opening a transaction: %w", err)
|
||||
}
|
||||
|
||||
deleted := deleteOldUnits(tx, id-s.limitHours-1)
|
||||
deleted := deleteOldUnits(tx, id-uint32(s.limitHours.Hours())-1)
|
||||
udb = loadUnitFromDB(tx, id)
|
||||
|
||||
err = finishTxn(tx, deleted > 0)
|
||||
|
@ -273,7 +278,7 @@ func (s *StatsCtx) TopClientsIP(maxCount uint) (ips []netip.Addr) {
|
|||
s.lock.Lock()
|
||||
defer s.lock.Unlock()
|
||||
|
||||
limit := s.limitHours
|
||||
limit := uint32(s.limitHours.Hours())
|
||||
if !s.enabled || limit == 0 {
|
||||
return nil
|
||||
}
|
||||
|
@ -377,7 +382,7 @@ func (s *StatsCtx) flush() (cont bool, sleepFor time.Duration) {
|
|||
return false, 0
|
||||
}
|
||||
|
||||
limit := s.limitHours
|
||||
limit := uint32(s.limitHours.Hours())
|
||||
if limit == 0 || ptr.id == id {
|
||||
return true, time.Second
|
||||
}
|
||||
|
@ -440,7 +445,7 @@ func (s *StatsCtx) periodicFlush() {
|
|||
func (s *StatsCtx) setLimit(limitDays int) {
|
||||
if limitDays != 0 {
|
||||
s.enabled = true
|
||||
s.limitHours = uint32(24 * limitDays)
|
||||
s.limitHours = time.Duration(int(timeutil.Day) * limitDays)
|
||||
log.Debug("stats: set limit: %d days", limitDays)
|
||||
|
||||
return
|
||||
|
|
|
@ -37,7 +37,7 @@ func TestStats_races(t *testing.T) {
|
|||
conf := Config{
|
||||
UnitID: idGen,
|
||||
Filename: filepath.Join(t.TempDir(), "./stats.db"),
|
||||
LimitDays: 1,
|
||||
LimitDays: time.Hour * 24,
|
||||
}
|
||||
|
||||
s, err := New(conf)
|
||||
|
|
|
@ -9,6 +9,7 @@ import (
|
|||
"path/filepath"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/AdguardTeam/AdGuardHome/internal/stats"
|
||||
"github.com/AdguardTeam/golibs/netutil"
|
||||
|
@ -52,7 +53,7 @@ func TestStats(t *testing.T) {
|
|||
handlers := map[string]http.Handler{}
|
||||
conf := stats.Config{
|
||||
Filename: filepath.Join(t.TempDir(), "stats.db"),
|
||||
LimitDays: 1,
|
||||
LimitDays: time.Hour * 24,
|
||||
Enabled: true,
|
||||
UnitID: constUnitID,
|
||||
HTTPRegister: func(_, url string, handler http.HandlerFunc) {
|
||||
|
@ -158,7 +159,7 @@ func TestLargeNumbers(t *testing.T) {
|
|||
|
||||
conf := stats.Config{
|
||||
Filename: filepath.Join(t.TempDir(), "stats.db"),
|
||||
LimitDays: 1,
|
||||
LimitDays: time.Hour * 24,
|
||||
Enabled: true,
|
||||
UnitID: func() (id uint32) { return atomic.LoadUint32(&curHour) },
|
||||
HTTPRegister: func(_, url string, handler http.HandlerFunc) { handlers[url] = handler },
|
||||
|
|
Loading…
Reference in New Issue