docstring_tokens
stringlengths 0
76.5k
| code_tokens
stringlengths 75
1.81M
| label_window
sequencelengths 4
2.12k
| html_url
stringlengths 74
116
| file_name
stringlengths 3
311
|
---|---|---|---|---|
// StatsResp is a response to the GET /control/stats.
type StatsResp struct { | <mask> // topAddrs is an alias for the types of the TopFoo fields of statsResponse.
<mask> // The key is either a client's address or a requested address.
<mask> type topAddrs = map[string]uint64
<mask>
<mask> // statsResponse is a response for getting statistics.
<mask> type statsResponse struct {
<mask> TimeUnits string `json:"time_units"`
<mask>
<mask> NumDNSQueries uint64 `json:"num_dns_queries"`
<mask> NumBlockedFiltering uint64 `json:"num_blocked_filtering"`
<mask> NumReplacedSafebrowsing uint64 `json:"num_replaced_safebrowsing"`
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove NumDNSQueries uint64 `json:"num_dns_queries"`
NumBlockedFiltering uint64 `json:"num_blocked_filtering"`
NumReplacedSafebrowsing uint64 `json:"num_replaced_safebrowsing"`
NumReplacedSafesearch uint64 `json:"num_replaced_safesearch"`
NumReplacedParental uint64 `json:"num_replaced_parental"`
AvgProcessingTime float64 `json:"avg_processing_time"`
</s> add </s> remove // unitDB is the structure for deserializing statistics data into the database.
</s> add // unitDB is the structure for serializing statistics data into the database. </s> remove // TODO(e.burkov): Use atomic.Pointer for accessing curr and db in go1.19.
type StatsCtx struct {
// currMu protects the current unit.
currMu *sync.Mutex
// curr is the actual statistics collection result.
curr *unit
// dbMu protects db.
dbMu *sync.Mutex
// db is the opened statistics database, if any.
db *bbolt.DB
// unitIDGen is the function that generates an identifier for the current
// unit. It's here for only testing purposes.
unitIDGen UnitIDGenFunc
// httpRegister is used to set HTTP handlers.
httpRegister aghhttp.RegisterFunc
// configModified is called whenever the configuration is modified via web
// interface.
configModified func()
// filename is the name of database file.
filename string
// limitHours is the maximum number of hours to collect statistics into the
// current unit.
limitHours uint32
</s> add // TODO(e.burkov): Think about better naming.
const (
RNotFiltered Result = iota + 1
RFiltered
RSafeBrowsing
RSafeSearch
RParental
resultLast = RParental + 1
)
// Entry is a statistics data entry.
type Entry struct {
// Clients is the client's primary ID.
//
// TODO(a.garipov): Make this a {net.IP, string} enum?
Client string
// Domain is the domain name requested.
Domain string
// Result is the result of processing the request.
Result Result
// Time is the duration of the request processing in milliseconds.
Time uint32 </s> remove start := time.Now()
var resp statsResponse
var ok bool
resp, ok = s.getData()
</s> add limit := atomic.LoadUint32(&s.limitHours) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/http.go |
<mask> // statsResponse is a response for getting statistics.
<mask> type statsResponse struct {
<mask> TimeUnits string `json:"time_units"`
<mask>
<mask> NumDNSQueries uint64 `json:"num_dns_queries"`
<mask> NumBlockedFiltering uint64 `json:"num_blocked_filtering"`
<mask> NumReplacedSafebrowsing uint64 `json:"num_replaced_safebrowsing"`
<mask> NumReplacedSafesearch uint64 `json:"num_replaced_safesearch"`
<mask> NumReplacedParental uint64 `json:"num_replaced_parental"`
<mask>
<mask> AvgProcessingTime float64 `json:"avg_processing_time"`
<mask>
<mask> TopQueried []topAddrs `json:"top_queried_domains"`
<mask> TopClients []topAddrs `json:"top_clients"`
<mask> TopBlocked []topAddrs `json:"top_blocked_domains"`
<mask>
<mask> DNSQueries []uint64 `json:"dns_queries"`
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove // statsResponse is a response for getting statistics.
type statsResponse struct {
</s> add // StatsResp is a response to the GET /control/stats.
type StatsResp struct { </s> remove // unitDB is the structure for deserializing statistics data into the database.
</s> add // unitDB is the structure for serializing statistics data into the database. </s> remove // handleStats is a handler for getting statistics.
</s> add // handleStats handles requests to the GET /control/stats endpoint. | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/http.go |
|
NumDNSQueries uint64 `json:"num_dns_queries"`
NumBlockedFiltering uint64 `json:"num_blocked_filtering"`
NumReplacedSafebrowsing uint64 `json:"num_replaced_safebrowsing"`
NumReplacedSafesearch uint64 `json:"num_replaced_safesearch"`
NumReplacedParental uint64 `json:"num_replaced_parental"`
AvgProcessingTime float64 `json:"avg_processing_time"` | <mask>
<mask> BlockedFiltering []uint64 `json:"blocked_filtering"`
<mask> ReplacedSafebrowsing []uint64 `json:"replaced_safebrowsing"`
<mask> ReplacedParental []uint64 `json:"replaced_parental"`
<mask> }
<mask>
<mask> // handleStats handles requests to the GET /control/stats endpoint.
<mask> func (s *StatsCtx) handleStats(w http.ResponseWriter, r *http.Request) {
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove // handleStats is a handler for getting statistics.
</s> add // handleStats handles requests to the GET /control/stats endpoint. </s> remove // Get configuration
</s> add // handleStatsInfo handles requests to the GET /control/stats_info endpoint. </s> remove // Reset data
</s> add // handleStatsReset handles requests to the POST /control/stats_reset endpoint. </s> remove // Set configuration
</s> add // handleStatsConfig handles requests to the POST /control/stats_config
// endpoint. | [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/http.go |
// handleStats handles requests to the GET /control/stats endpoint. | <mask> ReplacedSafebrowsing []uint64 `json:"replaced_safebrowsing"`
<mask> ReplacedParental []uint64 `json:"replaced_parental"`
<mask> }
<mask>
<mask> // handleStats is a handler for getting statistics.
<mask> func (s *StatsCtx) handleStats(w http.ResponseWriter, r *http.Request) {
<mask> start := time.Now()
<mask>
<mask> var resp statsResponse
<mask> var ok bool
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove start := time.Now()
var resp statsResponse
var ok bool
resp, ok = s.getData()
</s> add limit := atomic.LoadUint32(&s.limitHours) </s> remove NumDNSQueries uint64 `json:"num_dns_queries"`
NumBlockedFiltering uint64 `json:"num_blocked_filtering"`
NumReplacedSafebrowsing uint64 `json:"num_replaced_safebrowsing"`
NumReplacedSafesearch uint64 `json:"num_replaced_safesearch"`
NumReplacedParental uint64 `json:"num_replaced_parental"`
AvgProcessingTime float64 `json:"avg_processing_time"`
</s> add </s> remove resp := config{}
resp.IntervalDays = s.limitHours / 24
data, err := json.Marshal(resp)
if err != nil {
aghhttp.Error(r, w, http.StatusInternalServerError, "json encode: %s", err)
</s> add resp := configResp{IntervalDays: atomic.LoadUint32(&s.limitHours) / 24} | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/http.go |
limit := atomic.LoadUint32(&s.limitHours) | <mask> }
<mask>
<mask> // handleStats is a handler for getting statistics.
<mask> func (s *StatsCtx) handleStats(w http.ResponseWriter, r *http.Request) {
<mask> start := time.Now()
<mask>
<mask> var resp statsResponse
<mask> var ok bool
<mask> resp, ok = s.getData()
<mask>
<mask> log.Debug("stats: prepared data in %v", time.Since(start))
<mask>
<mask> if !ok {
<mask> // Don't bring the message to the lower case since it's a part of UI
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove // handleStats is a handler for getting statistics.
</s> add // handleStats handles requests to the GET /control/stats endpoint. </s> remove // statsResponse is a response for getting statistics.
type statsResponse struct {
</s> add // StatsResp is a response to the GET /control/stats.
type StatsResp struct { </s> remove // withRecovered turns the value recovered from panic if any into an error and
// combines it with the one pointed by orig. orig must be non-nil.
func withRecovered(orig *error) {
p := recover()
if p == nil {
return
}
var err error
switch p := p.(type) {
case error:
err = fmt.Errorf("panic: %w", p)
default:
err = fmt.Errorf("panic: recovered value of type %[1]T: %[1]v", p)
}
*orig = errors.WithDeferred(*orig, err)
}
// isEnabled is a helper that check if the statistics collecting is enabled.
func (s *StatsCtx) isEnabled() (ok bool) {
return atomic.LoadUint32(&s.limitHours) != 0
}
// New creates s from conf and properly initializes it. Don't use s before
// calling it's Start method.
func New(conf Config) (s *StatsCtx, err error) {
defer withRecovered(&err)
s = &StatsCtx{
currMu: &sync.Mutex{},
dbMu: &sync.Mutex{},
filename: conf.Filename,
configModified: conf.ConfigModified,
httpRegister: conf.HTTPRegister,
}
if s.limitHours = conf.LimitDays * 24; !checkInterval(conf.LimitDays) {
s.limitHours = 24
}
if s.unitIDGen = newUnitID; conf.UnitID != nil {
s.unitIDGen = conf.UnitID
}
if err = s.dbOpen(); err != nil {
return nil, fmt.Errorf("opening database: %w", err)
}
id := s.unitIDGen()
tx := beginTxn(s.db, true)
var udb *unitDB
if tx != nil {
log.Tracef("Deleting old units...")
firstID := id - s.limitHours - 1
unitDel := 0
err = tx.ForEach(newBucketWalker(tx, &unitDel, firstID))
if err != nil && !errors.Is(err, errStop) {
log.Debug("stats: deleting units: %s", err)
}
udb = s.loadUnitFromDB(tx, id)
if unitDel != 0 {
s.commitTxn(tx)
} else {
err = tx.Rollback()
if err != nil {
log.Debug("rolling back: %s", err)
}
}
}
u := newUnit(id)
// This use of deserialize is safe since the accessed unit has just been
// created.
u.deserialize(udb)
s.curr = u
log.Debug("stats: initialized")
return s, nil
}
// TODO(a.garipov): See if this is actually necessary. Looks like a rather
// bizarre solution.
const errStop errors.Error = "stop iteration"
// newBucketWalker returns a new bucket walker that deletes old units. The
// integer that unitDelPtr points to is incremented for every successful
// deletion. If the bucket isn't deleted, f returns errStop.
func newBucketWalker(
tx *bbolt.Tx,
unitDelPtr *int,
firstID uint32,
) (f func(name []byte, b *bbolt.Bucket) (err error)) {
return func(name []byte, _ *bbolt.Bucket) (err error) {
nameID, ok := unitNameToID(name)
if !ok || nameID < firstID {
err = tx.DeleteBucket(name)
if err != nil {
log.Debug("stats: tx.DeleteBucket: %s", err)
return nil
}
log.Debug("stats: deleted unit %d (name %x)", nameID, name)
*unitDelPtr++
return nil
}
return errStop
}
}
// Start makes s process the incoming data.
func (s *StatsCtx) Start() {
s.initWeb()
go s.periodicFlush()
}
// checkInterval returns true if days is valid to be used as statistics
// retention interval. The valid values are 0, 1, 7, 30 and 90.
func checkInterval(days uint32) (ok bool) {
return days == 0 || days == 1 || days == 7 || days == 30 || days == 90
}
// dbOpen returns an error if the database can't be opened from the specified
// file. It's safe for concurrent use.
func (s *StatsCtx) dbOpen() (err error) {
log.Tracef("db.Open...")
s.dbMu.Lock()
defer s.dbMu.Unlock()
s.db, err = bbolt.Open(s.filename, 0o644, nil)
if err != nil {
log.Error("stats: open DB: %s: %s", s.filename, err)
if err.Error() == "invalid argument" {
log.Error("AdGuard Home cannot be initialized due to an incompatible file system.\nPlease read the explanation here: https://github.com/AdguardTeam/AdGuardHome/wiki/Getting-Started#limitations")
}
return err
}
log.Tracef("db.Open")
return nil
}
</s> add </s> remove // Entry is a statistics data entry.
type Entry struct {
// Clients is the client's primary ID.
//
// TODO(a.garipov): Make this a {net.IP, string} enum?
Client string
</s> add // httpRegister is used to set HTTP handlers.
httpRegister aghhttp.RegisterFunc
// configModified is called whenever the configuration is modified via web
// interface.
configModified func()
// filename is the name of database file.
filename string
}
var _ Interface = &StatsCtx{}
// New creates s from conf and properly initializes it. Don't use s before
// calling it's Start method.
func New(conf Config) (s *StatsCtx, err error) {
defer withRecovered(&err)
s = &StatsCtx{
currMu: &sync.RWMutex{},
dbMu: &sync.Mutex{},
filename: conf.Filename,
configModified: conf.ConfigModified,
httpRegister: conf.HTTPRegister,
}
if s.limitHours = conf.LimitDays * 24; !checkInterval(conf.LimitDays) {
s.limitHours = 24
}
if s.unitIDGen = newUnitID; conf.UnitID != nil {
s.unitIDGen = conf.UnitID
}
// TODO(e.burkov): Move the code below to the Start method.
err = s.openDB()
if err != nil {
return nil, fmt.Errorf("opening database: %w", err)
}
var udb *unitDB
id := s.unitIDGen()
tx, err := s.db.Begin(true)
if err != nil {
return nil, fmt.Errorf("stats: opening a transaction: %w", err)
}
deleted := deleteOldUnits(tx, id-s.limitHours-1)
udb = loadUnitFromDB(tx, id)
err = finishTxn(tx, deleted > 0)
if err != nil {
log.Error("stats: %s", err)
}
s.curr = newUnit(id)
s.curr.deserialize(udb)
log.Debug("stats: initialized")
return s, nil
}
// withRecovered turns the value recovered from panic if any into an error and
// combines it with the one pointed by orig. orig must be non-nil.
func withRecovered(orig *error) {
p := recover()
if p == nil {
return
}
var err error
switch p := p.(type) {
case error:
err = fmt.Errorf("panic: %w", p)
default:
err = fmt.Errorf("panic: recovered value of type %[1]T: %[1]v", p)
}
*orig = errors.WithDeferred(*orig, err)
}
// Start implements the Interface interface for *StatsCtx.
func (s *StatsCtx) Start() {
s.initWeb()
go s.periodicFlush()
}
// Close implements the io.Closer interface for *StatsCtx.
func (s *StatsCtx) Close() (err error) {
defer func() { err = errors.Annotate(err, "stats: closing: %w") }()
db := s.swapDatabase(nil)
if db == nil {
return nil
}
defer func() {
cerr := db.Close()
if cerr == nil {
log.Debug("stats: database closed")
}
err = errors.WithDeferred(err, cerr)
}()
tx, err := db.Begin(true)
if err != nil {
return fmt.Errorf("opening transaction: %w", err)
}
defer func() { err = errors.WithDeferred(err, finishTxn(tx, err == nil)) }()
s.currMu.RLock()
defer s.currMu.RUnlock()
udb := s.curr.serialize()
return udb.flushUnitToDB(tx, s.curr.id)
}
// Update implements the Interface interface for *StatsCtx.
func (s *StatsCtx) Update(e Entry) {
if atomic.LoadUint32(&s.limitHours) == 0 {
return
}
if e.Result == 0 || e.Result >= resultLast || e.Domain == "" || e.Client == "" {
log.Debug("stats: malformed entry")
return
}
s.currMu.Lock()
defer s.currMu.Unlock()
if s.curr == nil {
log.Error("stats: current unit is nil")
return
}
clientID := e.Client
if ip := net.ParseIP(clientID); ip != nil {
clientID = ip.String()
}
s.curr.add(e.Result, e.Domain, clientID, uint64(e.Time))
}
// WriteDiskConfig implements the Interface interface for *StatsCtx.
func (s *StatsCtx) WriteDiskConfig(dc *DiskConfig) {
dc.Interval = atomic.LoadUint32(&s.limitHours) / 24
}
// TopClientsIP implements the Interface interface for *StatsCtx.
func (s *StatsCtx) TopClientsIP(maxCount uint) (ips []net.IP) {
limit := atomic.LoadUint32(&s.limitHours)
if limit == 0 {
return nil
}
units, _ := s.loadUnits(limit)
if units == nil {
return nil
}
// Collect data for all the clients to sort and crop it afterwards.
m := map[string]uint64{}
for _, u := range units {
for _, it := range u.Clients {
m[it.Name] += it.Count
}
}
a := convertMapToSlice(m, int(maxCount))
ips = []net.IP{}
for _, it := range a {
ip := net.ParseIP(it.Name)
if ip != nil {
ips = append(ips, ip)
}
}
return ips
}
// database returns the database if it's opened. It's safe for concurrent use.
func (s *StatsCtx) database() (db *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
return s.db
}
// swapDatabase swaps the database with another one and returns it. It's safe
// for concurrent use.
func (s *StatsCtx) swapDatabase(with *bbolt.DB) (old *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
old, s.db = s.db, with
return old
}
// deleteOldUnits walks the buckets available to tx and deletes old units. It
// returns the number of deletions performed.
func deleteOldUnits(tx *bbolt.Tx, firstID uint32) (deleted int) {
log.Debug("stats: deleting old units until id %d", firstID)
// TODO(a.garipov): See if this is actually necessary. Looks like a rather
// bizarre solution.
const errStop errors.Error = "stop iteration"
walk := func(name []byte, _ *bbolt.Bucket) (err error) {
nameID, ok := unitNameToID(name)
if ok && nameID >= firstID {
return errStop
}
err = tx.DeleteBucket(name)
if err != nil {
log.Debug("stats: deleting bucket: %s", err)
return nil
}
log.Debug("stats: deleted unit %d (name %x)", nameID, name)
deleted++
return nil
}
err := tx.ForEach(walk)
if err != nil && !errors.Is(err, errStop) {
log.Debug("stats: deleting units: %s", err)
}
return deleted
}
// openDB returns an error if the database can't be opened from the specified
// file. It's safe for concurrent use.
func (s *StatsCtx) openDB() (err error) {
log.Debug("stats: opening database")
var db *bbolt.DB
db, err = bbolt.Open(s.filename, 0o644, nil)
if err != nil {
if err.Error() == "invalid argument" {
log.Error("AdGuard Home cannot be initialized due to an incompatible file system.\nPlease read the explanation here: https://github.com/AdguardTeam/AdGuardHome/wiki/Getting-Started#limitations")
}
return err
}
// Use defer to unlock the mutex as soon as possible.
defer log.Debug("stats: database opened")
s.dbMu.Lock()
defer s.dbMu.Unlock()
s.db = db
return nil
}
func (s *StatsCtx) flush() (cont bool, sleepFor time.Duration) {
id := s.unitIDGen()
s.currMu.Lock()
defer s.currMu.Unlock()
ptr := s.curr
if ptr == nil {
return false, 0
}
limit := atomic.LoadUint32(&s.limitHours)
if limit == 0 || ptr.id == id {
return true, time.Second
}
db := s.database()
if db == nil {
return true, 0
}
tx, err := db.Begin(true)
if err != nil {
log.Error("stats: opening transaction: %s", err)
return true, 0
}
s.curr = newUnit(id)
isCommitable := true
ferr := ptr.serialize().flushUnitToDB(tx, ptr.id)
if ferr != nil {
log.Error("stats: flushing unit: %s", ferr)
isCommitable = false
}
derr := tx.DeleteBucket(idToUnitName(id - limit))
if derr != nil {
log.Error("stats: deleting unit: %s", derr)
if !errors.Is(derr, bbolt.ErrBucketNotFound) {
isCommitable = false
}
}
err = finishTxn(tx, isCommitable)
if err != nil {
log.Error("stats: %s", err)
}
return true, 0
}
// periodicFlush checks and flushes the unit to the database if the freshly
// generated unit ID differs from the current's ID. Flushing process includes:
// - swapping the current unit with the new empty one;
// - writing the current unit to the database;
// - removing the stale unit from the database.
func (s *StatsCtx) periodicFlush() {
for cont, sleepFor := true, time.Duration(0); cont; time.Sleep(sleepFor) {
cont, sleepFor = s.flush()
}
log.Debug("periodic flushing finished")
}
func (s *StatsCtx) setLimit(limitDays int) {
atomic.StoreUint32(&s.limitHours, uint32(24*limitDays))
if limitDays == 0 {
if err := s.clear(); err != nil {
log.Error("stats: %s", err)
}
}
log.Debug("stats: set limit: %d days", limitDays)
}
// Reset counters and clear database
func (s *StatsCtx) clear() (err error) {
defer func() { err = errors.Annotate(err, "clearing: %w") }()
db := s.swapDatabase(nil)
if db != nil {
var tx *bbolt.Tx
tx, err = db.Begin(true)
if err != nil {
log.Error("stats: opening a transaction: %s", err)
} else if err = finishTxn(tx, false); err != nil {
// Don't wrap the error since it's informative enough as is.
return err
}
// Active transactions will continue using database, but new ones won't
// be created.
err = db.Close()
if err != nil {
return fmt.Errorf("closing database: %w", err)
}
// All active transactions are now closed.
log.Debug("stats: database closed")
}
err = os.Remove(s.filename)
if err != nil {
log.Error("stats: %s", err)
}
err = s.openDB()
if err != nil {
log.Error("stats: opening database: %s", err)
}
// Use defer to unlock the mutex as soon as possible.
defer log.Debug("stats: cleared")
s.currMu.Lock()
defer s.currMu.Unlock()
s.curr = newUnit(s.unitIDGen())
return nil
}
func (s *StatsCtx) loadUnits(limit uint32) (units []*unitDB, firstID uint32) {
db := s.database()
if db == nil {
return nil, 0
}
// Use writable transaction to ensure any ongoing writable transaction is
// taken into account.
tx, err := db.Begin(true)
if err != nil {
log.Error("stats: opening transaction: %s", err)
return nil, 0
}
s.currMu.RLock()
defer s.currMu.RUnlock()
cur := s.curr
var curID uint32
if cur != nil {
curID = cur.id
} else {
curID = s.unitIDGen()
}
// Per-hour units.
units = make([]*unitDB, 0, limit)
firstID = curID - limit + 1
for i := firstID; i != curID; i++ {
u := loadUnitFromDB(tx, i)
if u == nil {
u = &unitDB{NResult: make([]uint64, resultLast)}
}
units = append(units, u)
}
err = finishTxn(tx, false)
if err != nil {
log.Error("stats: %s", err)
} | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/http.go |
start := time.Now()
resp, ok := s.getData(limit) | <mask> // handleStats handles requests to the GET /control/stats endpoint.
<mask> func (s *StatsCtx) handleStats(w http.ResponseWriter, r *http.Request) {
<mask> limit := atomic.LoadUint32(&s.limitHours)
<mask>
<mask> log.Debug("stats: prepared data in %v", time.Since(start))
<mask>
<mask> if !ok {
<mask> // Don't bring the message to the lower case since it's a part of UI
<mask> // text for the moment.
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove start := time.Now()
var resp statsResponse
var ok bool
resp, ok = s.getData()
</s> add limit := atomic.LoadUint32(&s.limitHours) </s> remove // handleStats is a handler for getting statistics.
</s> add // handleStats handles requests to the GET /control/stats endpoint. </s> remove // Get configuration
</s> add // handleStatsInfo handles requests to the GET /control/stats_info endpoint. </s> remove // Reset data
</s> add // handleStatsReset handles requests to the POST /control/stats_reset endpoint. | [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/http.go |
<mask>
<mask> err := json.NewEncoder(w).Encode(resp)
<mask> if err != nil {
<mask> aghhttp.Error(r, w, http.StatusInternalServerError, "json encode: %s", err)
<mask>
<mask> return
<mask> }
<mask> }
<mask>
<mask> type config struct {
<mask> IntervalDays uint32 `json:"interval"`
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove return
}
</s> add </s> remove aghhttp.Error(r, w, http.StatusInternalServerError, "http write: %s", err)
</s> add aghhttp.Error(r, w, http.StatusInternalServerError, "json encode: %s", err) </s> remove _, err = w.Write(data)
</s> add err := json.NewEncoder(w).Encode(resp) </s> remove resp := config{}
resp.IntervalDays = s.limitHours / 24
data, err := json.Marshal(resp)
if err != nil {
aghhttp.Error(r, w, http.StatusInternalServerError, "json encode: %s", err)
</s> add resp := configResp{IntervalDays: atomic.LoadUint32(&s.limitHours) / 24} </s> remove // Set configuration
</s> add // handleStatsConfig handles requests to the POST /control/stats_config
// endpoint. | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/http.go |
|
// configResp is the response to the GET /control/stats_info.
type configResp struct { | <mask> return
<mask> }
<mask> }
<mask>
<mask> type config struct {
<mask> IntervalDays uint32 `json:"interval"`
<mask> }
<mask>
<mask> // Get configuration
<mask> func (s *StatsCtx) handleStatsInfo(w http.ResponseWriter, r *http.Request) {
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove // Get configuration
</s> add // handleStatsInfo handles requests to the GET /control/stats_info endpoint. </s> remove
return
</s> add </s> remove resp := config{}
resp.IntervalDays = s.limitHours / 24
data, err := json.Marshal(resp)
if err != nil {
aghhttp.Error(r, w, http.StatusInternalServerError, "json encode: %s", err)
</s> add resp := configResp{IntervalDays: atomic.LoadUint32(&s.limitHours) / 24} </s> remove aghhttp.Error(r, w, http.StatusInternalServerError, "http write: %s", err)
</s> add aghhttp.Error(r, w, http.StatusInternalServerError, "json encode: %s", err) </s> remove // Register web handlers
</s> add // initWeb registers the handlers for web endpoints of statistics module. | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/http.go |
// handleStatsInfo handles requests to the GET /control/stats_info endpoint. | <mask> type config struct {
<mask> IntervalDays uint32 `json:"interval"`
<mask> }
<mask>
<mask> // Get configuration
<mask> func (s *StatsCtx) handleStatsInfo(w http.ResponseWriter, r *http.Request) {
<mask> resp := config{}
<mask> resp.IntervalDays = s.limitHours / 24
<mask>
<mask> data, err := json.Marshal(resp)
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove resp := config{}
resp.IntervalDays = s.limitHours / 24
data, err := json.Marshal(resp)
if err != nil {
aghhttp.Error(r, w, http.StatusInternalServerError, "json encode: %s", err)
</s> add resp := configResp{IntervalDays: atomic.LoadUint32(&s.limitHours) / 24} </s> remove type config struct {
</s> add // configResp is the response to the GET /control/stats_info.
type configResp struct { </s> remove
return
</s> add </s> remove reqData := config{}
</s> add reqData := configResp{} </s> remove // Set configuration
</s> add // handleStatsConfig handles requests to the POST /control/stats_config
// endpoint. | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/http.go |
resp := configResp{IntervalDays: atomic.LoadUint32(&s.limitHours) / 24} | <mask> }
<mask>
<mask> // Get configuration
<mask> func (s *StatsCtx) handleStatsInfo(w http.ResponseWriter, r *http.Request) {
<mask> resp := config{}
<mask> resp.IntervalDays = s.limitHours / 24
<mask>
<mask> data, err := json.Marshal(resp)
<mask> if err != nil {
<mask> aghhttp.Error(r, w, http.StatusInternalServerError, "json encode: %s", err)
<mask>
<mask> return
<mask> }
<mask> w.Header().Set("Content-Type", "application/json")
<mask> _, err = w.Write(data)
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove // Get configuration
</s> add // handleStatsInfo handles requests to the GET /control/stats_info endpoint. </s> remove aghhttp.Error(r, w, http.StatusInternalServerError, "http write: %s", err)
</s> add aghhttp.Error(r, w, http.StatusInternalServerError, "json encode: %s", err) </s> remove return
}
</s> add </s> remove // Set configuration
</s> add // handleStatsConfig handles requests to the POST /control/stats_config
// endpoint. </s> remove _, err = w.Write(data)
</s> add err := json.NewEncoder(w).Encode(resp) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/http.go |
<mask> data, err := json.Marshal(resp)
<mask> if err != nil {
<mask> aghhttp.Error(r, w, http.StatusInternalServerError, "json encode: %s", err)
<mask>
<mask> return
<mask> }
<mask> w.Header().Set("Content-Type", "application/json")
<mask> _, err = w.Write(data)
<mask> if err != nil {
<mask> aghhttp.Error(r, w, http.StatusInternalServerError, "http write: %s", err)
<mask> }
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove aghhttp.Error(r, w, http.StatusInternalServerError, "http write: %s", err)
</s> add aghhttp.Error(r, w, http.StatusInternalServerError, "json encode: %s", err) </s> remove _, err = w.Write(data)
</s> add err := json.NewEncoder(w).Encode(resp) </s> remove resp := config{}
resp.IntervalDays = s.limitHours / 24
data, err := json.Marshal(resp)
if err != nil {
aghhttp.Error(r, w, http.StatusInternalServerError, "json encode: %s", err)
</s> add resp := configResp{IntervalDays: atomic.LoadUint32(&s.limitHours) / 24} </s> remove // Set configuration
</s> add // handleStatsConfig handles requests to the POST /control/stats_config
// endpoint. </s> remove
return
</s> add | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/http.go |
|
err := json.NewEncoder(w).Encode(resp) | <mask>
<mask> return
<mask> }
<mask> w.Header().Set("Content-Type", "application/json")
<mask> _, err = w.Write(data)
<mask> if err != nil {
<mask> aghhttp.Error(r, w, http.StatusInternalServerError, "http write: %s", err)
<mask> }
<mask> }
<mask>
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove return
}
</s> add </s> remove aghhttp.Error(r, w, http.StatusInternalServerError, "http write: %s", err)
</s> add aghhttp.Error(r, w, http.StatusInternalServerError, "json encode: %s", err) </s> remove resp := config{}
resp.IntervalDays = s.limitHours / 24
data, err := json.Marshal(resp)
if err != nil {
aghhttp.Error(r, w, http.StatusInternalServerError, "json encode: %s", err)
</s> add resp := configResp{IntervalDays: atomic.LoadUint32(&s.limitHours) / 24} </s> remove // Set configuration
</s> add // handleStatsConfig handles requests to the POST /control/stats_config
// endpoint. </s> remove
return
</s> add | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/http.go |
aghhttp.Error(r, w, http.StatusInternalServerError, "json encode: %s", err) | <mask> }
<mask> w.Header().Set("Content-Type", "application/json")
<mask> _, err = w.Write(data)
<mask> if err != nil {
<mask> aghhttp.Error(r, w, http.StatusInternalServerError, "http write: %s", err)
<mask> }
<mask> }
<mask>
<mask> // Set configuration
<mask> func (s *StatsCtx) handleStatsConfig(w http.ResponseWriter, r *http.Request) {
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove // Set configuration
</s> add // handleStatsConfig handles requests to the POST /control/stats_config
// endpoint. </s> remove return
}
</s> add </s> remove _, err = w.Write(data)
</s> add err := json.NewEncoder(w).Encode(resp) </s> remove resp := config{}
resp.IntervalDays = s.limitHours / 24
data, err := json.Marshal(resp)
if err != nil {
aghhttp.Error(r, w, http.StatusInternalServerError, "json encode: %s", err)
</s> add resp := configResp{IntervalDays: atomic.LoadUint32(&s.limitHours) / 24} </s> remove reqData := config{}
</s> add reqData := configResp{} | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/http.go |
// handleStatsConfig handles requests to the POST /control/stats_config
// endpoint. | <mask> aghhttp.Error(r, w, http.StatusInternalServerError, "http write: %s", err)
<mask> }
<mask> }
<mask>
<mask> // Set configuration
<mask> func (s *StatsCtx) handleStatsConfig(w http.ResponseWriter, r *http.Request) {
<mask> reqData := config{}
<mask> err := json.NewDecoder(r.Body).Decode(&reqData)
<mask> if err != nil {
<mask> aghhttp.Error(r, w, http.StatusBadRequest, "json decode: %s", err)
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove reqData := config{}
</s> add reqData := configResp{} </s> remove aghhttp.Error(r, w, http.StatusInternalServerError, "http write: %s", err)
</s> add aghhttp.Error(r, w, http.StatusInternalServerError, "json encode: %s", err) </s> remove return
}
</s> add </s> remove resp := config{}
resp.IntervalDays = s.limitHours / 24
data, err := json.Marshal(resp)
if err != nil {
aghhttp.Error(r, w, http.StatusInternalServerError, "json encode: %s", err)
</s> add resp := configResp{IntervalDays: atomic.LoadUint32(&s.limitHours) / 24} </s> remove s.clear()
</s> add err := s.clear()
if err != nil {
aghhttp.Error(r, w, http.StatusInternalServerError, "stats: %s", err)
} | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/http.go |
reqData := configResp{} | <mask> }
<mask>
<mask> // Set configuration
<mask> func (s *StatsCtx) handleStatsConfig(w http.ResponseWriter, r *http.Request) {
<mask> reqData := config{}
<mask> err := json.NewDecoder(r.Body).Decode(&reqData)
<mask> if err != nil {
<mask> aghhttp.Error(r, w, http.StatusBadRequest, "json decode: %s", err)
<mask>
<mask> return
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove // Set configuration
</s> add // handleStatsConfig handles requests to the POST /control/stats_config
// endpoint. </s> remove aghhttp.Error(r, w, http.StatusInternalServerError, "http write: %s", err)
</s> add aghhttp.Error(r, w, http.StatusInternalServerError, "json encode: %s", err) </s> remove resp := config{}
resp.IntervalDays = s.limitHours / 24
data, err := json.Marshal(resp)
if err != nil {
aghhttp.Error(r, w, http.StatusInternalServerError, "json encode: %s", err)
</s> add resp := configResp{IntervalDays: atomic.LoadUint32(&s.limitHours) / 24} </s> remove s.clear()
</s> add err := s.clear()
if err != nil {
aghhttp.Error(r, w, http.StatusInternalServerError, "stats: %s", err)
} </s> remove return
}
</s> add | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/http.go |
// handleStatsReset handles requests to the POST /control/stats_reset endpoint. | <mask> s.setLimit(int(reqData.IntervalDays))
<mask> s.configModified()
<mask> }
<mask>
<mask> // Reset data
<mask> func (s *StatsCtx) handleStatsReset(w http.ResponseWriter, r *http.Request) {
<mask> s.clear()
<mask> }
<mask>
<mask> // Register web handlers
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove s.clear()
</s> add err := s.clear()
if err != nil {
aghhttp.Error(r, w, http.StatusInternalServerError, "stats: %s", err)
} </s> remove // Register web handlers
</s> add // initWeb registers the handlers for web endpoints of statistics module. </s> remove type config struct {
</s> add // configResp is the response to the GET /control/stats_info.
type configResp struct { </s> remove aghhttp.Error(r, w, http.StatusInternalServerError, "http write: %s", err)
</s> add aghhttp.Error(r, w, http.StatusInternalServerError, "json encode: %s", err) </s> remove // Set configuration
</s> add // handleStatsConfig handles requests to the POST /control/stats_config
// endpoint. | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/http.go |
err := s.clear()
if err != nil {
aghhttp.Error(r, w, http.StatusInternalServerError, "stats: %s", err)
} | <mask> }
<mask>
<mask> // Reset data
<mask> func (s *StatsCtx) handleStatsReset(w http.ResponseWriter, r *http.Request) {
<mask> s.clear()
<mask> }
<mask>
<mask> // Register web handlers
<mask> func (s *StatsCtx) initWeb() {
<mask> if s.httpRegister == nil {
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove // Register web handlers
</s> add // initWeb registers the handlers for web endpoints of statistics module. </s> remove // Reset data
</s> add // handleStatsReset handles requests to the POST /control/stats_reset endpoint. </s> remove type config struct {
</s> add // configResp is the response to the GET /control/stats_info.
type configResp struct { </s> remove aghhttp.Error(r, w, http.StatusInternalServerError, "http write: %s", err)
</s> add aghhttp.Error(r, w, http.StatusInternalServerError, "json encode: %s", err) </s> remove reqData := config{}
</s> add reqData := configResp{} | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/http.go |
// initWeb registers the handlers for web endpoints of statistics module. | <mask> func (s *StatsCtx) handleStatsReset(w http.ResponseWriter, r *http.Request) {
<mask> s.clear()
<mask> }
<mask>
<mask> // Register web handlers
<mask> func (s *StatsCtx) initWeb() {
<mask> if s.httpRegister == nil {
<mask> return
<mask> }
<mask>
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove s.clear()
</s> add err := s.clear()
if err != nil {
aghhttp.Error(r, w, http.StatusInternalServerError, "stats: %s", err)
} </s> remove // Reset data
</s> add // handleStatsReset handles requests to the POST /control/stats_reset endpoint. </s> remove type config struct {
</s> add // configResp is the response to the GET /control/stats_info.
type configResp struct { </s> remove aghhttp.Error(r, w, http.StatusInternalServerError, "http write: %s", err)
</s> add aghhttp.Error(r, w, http.StatusInternalServerError, "json encode: %s", err) </s> remove reqData := config{}
</s> add reqData := configResp{} | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/http.go |
"fmt"
"io" | <mask> package stats
<mask>
<mask> import (
<mask> "net"
<mask> "os"
<mask> "sync"
<mask> "sync/atomic"
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove package stats
</s> add package stats_test </s> remove "os"
</s> add "net/http"
"net/http/httptest"
"path/filepath" </s> remove "sync"
"sync/atomic"
</s> add | [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats.go |
"os"
"sync"
"sync/atomic"
"time" | <mask> "fmt"
<mask> "io"
<mask> "net"
<mask>
<mask> "github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
<mask> "github.com/AdguardTeam/golibs/errors"
<mask> "github.com/AdguardTeam/golibs/log"
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove "sync"
"sync/atomic"
</s> add </s> remove "github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
</s> add | [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats.go |
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/log"
"go.etcd.io/bbolt" | <mask>
<mask> "github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
<mask> )
<mask>
<mask> // DiskConfig is the configuration structure that is stored in file.
<mask> type DiskConfig struct {
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove // UnitIDGenFunc is the signature of a function that generates a unique ID for
// the statistics unit.
type UnitIDGenFunc func() (id uint32)
</s> add </s> remove // TODO(e.burkov): Use atomic.Pointer for accessing curr and db in go1.19.
type StatsCtx struct {
// currMu protects the current unit.
currMu *sync.Mutex
// curr is the actual statistics collection result.
curr *unit
// dbMu protects db.
dbMu *sync.Mutex
// db is the opened statistics database, if any.
db *bbolt.DB
// unitIDGen is the function that generates an identifier for the current
// unit. It's here for only testing purposes.
unitIDGen UnitIDGenFunc
// httpRegister is used to set HTTP handlers.
httpRegister aghhttp.RegisterFunc
// configModified is called whenever the configuration is modified via web
// interface.
configModified func()
// filename is the name of database file.
filename string
// limitHours is the maximum number of hours to collect statistics into the
// current unit.
limitHours uint32
</s> add // TODO(e.burkov): Think about better naming.
const (
RNotFiltered Result = iota + 1
RFiltered
RSafeBrowsing
RSafeSearch
RParental
resultLast = RParental + 1
)
// Entry is a statistics data entry.
type Entry struct {
// Clients is the client's primary ID.
//
// TODO(a.garipov): Make this a {net.IP, string} enum?
Client string
// Domain is the domain name requested.
Domain string
// Result is the result of processing the request.
Result Result
// Time is the duration of the request processing in milliseconds.
Time uint32 </s> remove // StatsCtx collects the statistics and flushes it to the database. Its default
// flushing interval is one hour.
</s> add // UnitIDGenFunc is the signature of a function that generates a unique ID for
// the statistics unit.
type UnitIDGenFunc func() (id uint32)
// TimeUnit is the unit of measuring time while aggregating the statistics.
type TimeUnit int
// Supported TimeUnit values.
const (
Hours TimeUnit = iota
Days
)
// Result is the resulting code of processing the DNS request.
type Result int
// Supported Result values. </s> remove // TimeUnit is the unit of measuring time while aggregating the statistics.
type TimeUnit int
</s> add // StatsCtx collects the statistics and flushes it to the database. Its default
// flushing interval is one hour.
//
// TODO(e.burkov): Use atomic.Pointer for accessing db in go1.19.
type StatsCtx struct {
// limitHours is the maximum number of hours to collect statistics into the
// current unit.
//
// It is of type uint32 to be accessed by atomic. It's arranged at the
// beginning of the structure to keep 64-bit alignment.
limitHours uint32 </s> remove // unitDB is the structure for deserializing statistics data into the database.
</s> add // unitDB is the structure for serializing statistics data into the database. | [
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats.go |
<mask>
<mask> "github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
<mask> )
<mask>
<mask> // UnitIDGenFunc is the signature of a function that generates a unique ID for
<mask> // the statistics unit.
<mask> type UnitIDGenFunc func() (id uint32)
<mask>
<mask> // DiskConfig is the configuration structure that is stored in file.
<mask> type DiskConfig struct {
<mask> // Interval is the number of days for which the statistics are collected
<mask> // before flushing to the database.
<mask> Interval uint32 `yaml:"statistics_interval"`
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove // StatsCtx collects the statistics and flushes it to the database. Its default
// flushing interval is one hour.
</s> add // UnitIDGenFunc is the signature of a function that generates a unique ID for
// the statistics unit.
type UnitIDGenFunc func() (id uint32)
// TimeUnit is the unit of measuring time while aggregating the statistics.
type TimeUnit int
// Supported TimeUnit values.
const (
Hours TimeUnit = iota
Days
)
// Result is the resulting code of processing the DNS request.
type Result int
// Supported Result values. </s> remove // TODO(e.burkov): Use atomic.Pointer for accessing curr and db in go1.19.
type StatsCtx struct {
// currMu protects the current unit.
currMu *sync.Mutex
// curr is the actual statistics collection result.
curr *unit
// dbMu protects db.
dbMu *sync.Mutex
// db is the opened statistics database, if any.
db *bbolt.DB
// unitIDGen is the function that generates an identifier for the current
// unit. It's here for only testing purposes.
unitIDGen UnitIDGenFunc
// httpRegister is used to set HTTP handlers.
httpRegister aghhttp.RegisterFunc
// configModified is called whenever the configuration is modified via web
// interface.
configModified func()
// filename is the name of database file.
filename string
// limitHours is the maximum number of hours to collect statistics into the
// current unit.
limitHours uint32
</s> add // TODO(e.burkov): Think about better naming.
const (
RNotFiltered Result = iota + 1
RFiltered
RSafeBrowsing
RSafeSearch
RParental
resultLast = RParental + 1
)
// Entry is a statistics data entry.
type Entry struct {
// Clients is the client's primary ID.
//
// TODO(a.garipov): Make this a {net.IP, string} enum?
Client string
// Domain is the domain name requested.
Domain string
// Result is the result of processing the request.
Result Result
// Time is the duration of the request processing in milliseconds.
Time uint32 </s> remove // Supported Result values.
//
// TODO(e.burkov): Think about better naming.
const (
RNotFiltered Result = iota + 1
RFiltered
RSafeBrowsing
RSafeSearch
RParental
resultLast = RParental + 1
)
</s> add // unitIDGen is the function that generates an identifier for the current
// unit. It's here for only testing purposes.
unitIDGen UnitIDGenFunc | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats.go |
|
// checkInterval returns true if days is valid to be used as statistics
// retention interval. The valid values are 0, 1, 7, 30 and 90.
func checkInterval(days uint32) (ok bool) {
return days == 0 || days == 1 || days == 7 || days == 30 || days == 90
}
| <mask> }
<mask>
<mask> // Config is the configuration structure for the statistics collecting.
<mask> type Config struct {
<mask> // UnitID is the function to generate the identifier for current unit. If
<mask> // nil, the default function is used, see newUnitID.
<mask> UnitID UnitIDGenFunc
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove // UnitIDGenFunc is the signature of a function that generates a unique ID for
// the statistics unit.
type UnitIDGenFunc func() (id uint32)
</s> add </s> remove // Supported Result values.
//
// TODO(e.burkov): Think about better naming.
const (
RNotFiltered Result = iota + 1
RFiltered
RSafeBrowsing
RSafeSearch
RParental
resultLast = RParental + 1
)
</s> add // unitIDGen is the function that generates an identifier for the current
// unit. It's here for only testing purposes.
unitIDGen UnitIDGenFunc </s> remove // TODO(e.burkov): Use atomic.Pointer for accessing curr and db in go1.19.
type StatsCtx struct {
// currMu protects the current unit.
currMu *sync.Mutex
// curr is the actual statistics collection result.
curr *unit
// dbMu protects db.
dbMu *sync.Mutex
// db is the opened statistics database, if any.
db *bbolt.DB
// unitIDGen is the function that generates an identifier for the current
// unit. It's here for only testing purposes.
unitIDGen UnitIDGenFunc
// httpRegister is used to set HTTP handlers.
httpRegister aghhttp.RegisterFunc
// configModified is called whenever the configuration is modified via web
// interface.
configModified func()
// filename is the name of database file.
filename string
// limitHours is the maximum number of hours to collect statistics into the
// current unit.
limitHours uint32
</s> add // TODO(e.burkov): Think about better naming.
const (
RNotFiltered Result = iota + 1
RFiltered
RSafeBrowsing
RSafeSearch
RParental
resultLast = RParental + 1
)
// Entry is a statistics data entry.
type Entry struct {
// Clients is the client's primary ID.
//
// TODO(a.garipov): Make this a {net.IP, string} enum?
Client string
// Domain is the domain name requested.
Domain string
// Result is the result of processing the request.
Result Result
// Time is the duration of the request processing in milliseconds.
Time uint32 </s> remove // StatsCtx collects the statistics and flushes it to the database. Its default
// flushing interval is one hour.
</s> add // UnitIDGenFunc is the signature of a function that generates a unique ID for
// the statistics unit.
type UnitIDGenFunc func() (id uint32)
// TimeUnit is the unit of measuring time while aggregating the statistics.
type TimeUnit int
// Supported TimeUnit values.
const (
Hours TimeUnit = iota
Days
)
// Result is the resulting code of processing the DNS request.
type Result int
// Supported Result values. </s> remove // TimeUnit is the unit of measuring time while aggregating the statistics.
type TimeUnit int
</s> add // StatsCtx collects the statistics and flushes it to the database. Its default
// flushing interval is one hour.
//
// TODO(e.burkov): Use atomic.Pointer for accessing db in go1.19.
type StatsCtx struct {
// limitHours is the maximum number of hours to collect statistics into the
// current unit.
//
// It is of type uint32 to be accessed by atomic. It's arranged at the
// beginning of the structure to keep 64-bit alignment.
limitHours uint32 | [
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats.go |
io.Closer | <mask> type Interface interface {
<mask> // Start begins the statistics collecting.
<mask> Start()
<mask>
<mask> // Close stops the statistics collecting.
<mask> Close()
<mask>
<mask> // Update collects the incoming statistics data.
<mask> Update(e Entry)
<mask>
<mask> // GetTopClientIP returns at most limit IP addresses corresponding to the
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove GetTopClientsIP(limit uint) []net.IP
</s> add TopClientsIP(limit uint) []net.IP </s> remove // TimeUnit is the unit of measuring time while aggregating the statistics.
type TimeUnit int
</s> add // StatsCtx collects the statistics and flushes it to the database. Its default
// flushing interval is one hour.
//
// TODO(e.burkov): Use atomic.Pointer for accessing db in go1.19.
type StatsCtx struct {
// limitHours is the maximum number of hours to collect statistics into the
// current unit.
//
// It is of type uint32 to be accessed by atomic. It's arranged at the
// beginning of the structure to keep 64-bit alignment.
limitHours uint32 </s> remove // TODO(e.burkov): Use atomic.Pointer for accessing curr and db in go1.19.
type StatsCtx struct {
// currMu protects the current unit.
currMu *sync.Mutex
// curr is the actual statistics collection result.
curr *unit
// dbMu protects db.
dbMu *sync.Mutex
// db is the opened statistics database, if any.
db *bbolt.DB
// unitIDGen is the function that generates an identifier for the current
// unit. It's here for only testing purposes.
unitIDGen UnitIDGenFunc
// httpRegister is used to set HTTP handlers.
httpRegister aghhttp.RegisterFunc
// configModified is called whenever the configuration is modified via web
// interface.
configModified func()
// filename is the name of database file.
filename string
// limitHours is the maximum number of hours to collect statistics into the
// current unit.
limitHours uint32
</s> add // TODO(e.burkov): Think about better naming.
const (
RNotFiltered Result = iota + 1
RFiltered
RSafeBrowsing
RSafeSearch
RParental
resultLast = RParental + 1
)
// Entry is a statistics data entry.
type Entry struct {
// Clients is the client's primary ID.
//
// TODO(a.garipov): Make this a {net.IP, string} enum?
Client string
// Domain is the domain name requested.
Domain string
// Result is the result of processing the request.
Result Result
// Time is the duration of the request processing in milliseconds.
Time uint32 </s> remove // UnitIDGenFunc is the signature of a function that generates a unique ID for
// the statistics unit.
type UnitIDGenFunc func() (id uint32)
</s> add | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats.go |
TopClientsIP(limit uint) []net.IP | <mask> Update(e Entry)
<mask>
<mask> // GetTopClientIP returns at most limit IP addresses corresponding to the
<mask> // clients with the most number of requests.
<mask> GetTopClientsIP(limit uint) []net.IP
<mask>
<mask> // WriteDiskConfig puts the Interface's configuration to the dc.
<mask> WriteDiskConfig(dc *DiskConfig)
<mask> }
<mask>
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove // Close stops the statistics collecting.
Close()
</s> add io.Closer </s> remove // TimeUnit is the unit of measuring time while aggregating the statistics.
type TimeUnit int
</s> add // StatsCtx collects the statistics and flushes it to the database. Its default
// flushing interval is one hour.
//
// TODO(e.burkov): Use atomic.Pointer for accessing db in go1.19.
type StatsCtx struct {
// limitHours is the maximum number of hours to collect statistics into the
// current unit.
//
// It is of type uint32 to be accessed by atomic. It's arranged at the
// beginning of the structure to keep 64-bit alignment.
limitHours uint32 </s> remove // ongoing returns the current unit. It's safe for concurrent use.
//
// Note that the unit itself should be locked before accessing.
func (s *StatsCtx) ongoing() (u *unit) {
s.currMu.Lock()
defer s.currMu.Unlock()
return s.curr
}
// swapCurrent swaps the current unit with another and returns it. It's safe
// for concurrent use.
func (s *StatsCtx) swapCurrent(with *unit) (old *unit) {
s.currMu.Lock()
defer s.currMu.Unlock()
old, s.curr = s.curr, with
return old
}
// database returns the database if it's opened. It's safe for concurrent use.
func (s *StatsCtx) database() (db *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
return s.db
}
// swapDatabase swaps the database with another one and returns it. It's safe
// for concurrent use.
func (s *StatsCtx) swapDatabase(with *bbolt.DB) (old *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
old, s.db = s.db, with
return old
</s> add // newUnit allocates the new *unit.
func newUnit(id uint32) (u *unit) {
return &unit{
id: id,
nResult: make([]uint64, resultLast),
domains: make(map[string]uint64),
blockedDomains: make(map[string]uint64),
clients: make(map[string]uint64),
} </s> remove // mu protects all the fields of a unit.
mu *sync.RWMutex
</s> add </s> remove maxDomains = 100 // max number of top domains to store in file or return via Get()
maxClients = 100 // max number of top clients to store in file or return via Get()
</s> add // maxDomains is the max number of top domains to return.
maxDomains = 100
// maxClients is the max number of top clients to return.
maxClients = 100 | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats.go |
// StatsCtx collects the statistics and flushes it to the database. Its default
// flushing interval is one hour.
//
// TODO(e.burkov): Use atomic.Pointer for accessing db in go1.19.
type StatsCtx struct {
// limitHours is the maximum number of hours to collect statistics into the
// current unit.
//
// It is of type uint32 to be accessed by atomic. It's arranged at the
// beginning of the structure to keep 64-bit alignment.
limitHours uint32 | <mask> // WriteDiskConfig puts the Interface's configuration to the dc.
<mask> WriteDiskConfig(dc *DiskConfig)
<mask> }
<mask>
<mask> // TimeUnit is the unit of measuring time while aggregating the statistics.
<mask> type TimeUnit int
<mask>
<mask> // Supported TimeUnit values.
<mask> const (
<mask> Hours TimeUnit = iota
<mask> Days
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove // Supported TimeUnit values.
const (
Hours TimeUnit = iota
Days
)
</s> add // currMu protects curr.
currMu *sync.RWMutex
// curr is the actual statistics collection result.
curr *unit </s> remove // StatsCtx collects the statistics and flushes it to the database. Its default
// flushing interval is one hour.
</s> add // UnitIDGenFunc is the signature of a function that generates a unique ID for
// the statistics unit.
type UnitIDGenFunc func() (id uint32)
// TimeUnit is the unit of measuring time while aggregating the statistics.
type TimeUnit int
// Supported TimeUnit values.
const (
Hours TimeUnit = iota
Days
)
// Result is the resulting code of processing the DNS request.
type Result int
// Supported Result values. </s> remove // Result is the resulting code of processing the DNS request.
type Result int
</s> add // dbMu protects db.
dbMu *sync.Mutex
// db is the opened statistics database, if any.
db *bbolt.DB </s> remove GetTopClientsIP(limit uint) []net.IP
</s> add TopClientsIP(limit uint) []net.IP </s> remove // Supported Result values.
//
// TODO(e.burkov): Think about better naming.
const (
RNotFiltered Result = iota + 1
RFiltered
RSafeBrowsing
RSafeSearch
RParental
resultLast = RParental + 1
)
</s> add // unitIDGen is the function that generates an identifier for the current
// unit. It's here for only testing purposes.
unitIDGen UnitIDGenFunc | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats.go |
// currMu protects curr.
currMu *sync.RWMutex
// curr is the actual statistics collection result.
curr *unit | <mask>
<mask> // TimeUnit is the unit of measuring time while aggregating the statistics.
<mask> type TimeUnit int
<mask>
<mask> // Supported TimeUnit values.
<mask> const (
<mask> Hours TimeUnit = iota
<mask> Days
<mask> )
<mask>
<mask> // Result is the resulting code of processing the DNS request.
<mask> type Result int
<mask>
<mask> // Supported Result values.
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove // StatsCtx collects the statistics and flushes it to the database. Its default
// flushing interval is one hour.
</s> add // UnitIDGenFunc is the signature of a function that generates a unique ID for
// the statistics unit.
type UnitIDGenFunc func() (id uint32)
// TimeUnit is the unit of measuring time while aggregating the statistics.
type TimeUnit int
// Supported TimeUnit values.
const (
Hours TimeUnit = iota
Days
)
// Result is the resulting code of processing the DNS request.
type Result int
// Supported Result values. </s> remove // Result is the resulting code of processing the DNS request.
type Result int
</s> add // dbMu protects db.
dbMu *sync.Mutex
// db is the opened statistics database, if any.
db *bbolt.DB </s> remove // TimeUnit is the unit of measuring time while aggregating the statistics.
type TimeUnit int
</s> add // StatsCtx collects the statistics and flushes it to the database. Its default
// flushing interval is one hour.
//
// TODO(e.burkov): Use atomic.Pointer for accessing db in go1.19.
type StatsCtx struct {
// limitHours is the maximum number of hours to collect statistics into the
// current unit.
//
// It is of type uint32 to be accessed by atomic. It's arranged at the
// beginning of the structure to keep 64-bit alignment.
limitHours uint32 </s> remove // Supported Result values.
//
// TODO(e.burkov): Think about better naming.
const (
RNotFiltered Result = iota + 1
RFiltered
RSafeBrowsing
RSafeSearch
RParental
resultLast = RParental + 1
)
</s> add // unitIDGen is the function that generates an identifier for the current
// unit. It's here for only testing purposes.
unitIDGen UnitIDGenFunc </s> remove // TODO(e.burkov): Use atomic.Pointer for accessing curr and db in go1.19.
type StatsCtx struct {
// currMu protects the current unit.
currMu *sync.Mutex
// curr is the actual statistics collection result.
curr *unit
// dbMu protects db.
dbMu *sync.Mutex
// db is the opened statistics database, if any.
db *bbolt.DB
// unitIDGen is the function that generates an identifier for the current
// unit. It's here for only testing purposes.
unitIDGen UnitIDGenFunc
// httpRegister is used to set HTTP handlers.
httpRegister aghhttp.RegisterFunc
// configModified is called whenever the configuration is modified via web
// interface.
configModified func()
// filename is the name of database file.
filename string
// limitHours is the maximum number of hours to collect statistics into the
// current unit.
limitHours uint32
</s> add // TODO(e.burkov): Think about better naming.
const (
RNotFiltered Result = iota + 1
RFiltered
RSafeBrowsing
RSafeSearch
RParental
resultLast = RParental + 1
)
// Entry is a statistics data entry.
type Entry struct {
// Clients is the client's primary ID.
//
// TODO(a.garipov): Make this a {net.IP, string} enum?
Client string
// Domain is the domain name requested.
Domain string
// Result is the result of processing the request.
Result Result
// Time is the duration of the request processing in milliseconds.
Time uint32 | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats.go |
// dbMu protects db.
dbMu *sync.Mutex
// db is the opened statistics database, if any.
db *bbolt.DB | <mask> Hours TimeUnit = iota
<mask> Days
<mask> )
<mask>
<mask> // Result is the resulting code of processing the DNS request.
<mask> type Result int
<mask>
<mask> // Supported Result values.
<mask> //
<mask> // TODO(e.burkov): Think about better naming.
<mask> const (
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove // Supported TimeUnit values.
const (
Hours TimeUnit = iota
Days
)
</s> add // currMu protects curr.
currMu *sync.RWMutex
// curr is the actual statistics collection result.
curr *unit </s> remove // Supported Result values.
//
// TODO(e.burkov): Think about better naming.
const (
RNotFiltered Result = iota + 1
RFiltered
RSafeBrowsing
RSafeSearch
RParental
resultLast = RParental + 1
)
</s> add // unitIDGen is the function that generates an identifier for the current
// unit. It's here for only testing purposes.
unitIDGen UnitIDGenFunc </s> remove // StatsCtx collects the statistics and flushes it to the database. Its default
// flushing interval is one hour.
</s> add // UnitIDGenFunc is the signature of a function that generates a unique ID for
// the statistics unit.
type UnitIDGenFunc func() (id uint32)
// TimeUnit is the unit of measuring time while aggregating the statistics.
type TimeUnit int
// Supported TimeUnit values.
const (
Hours TimeUnit = iota
Days
)
// Result is the resulting code of processing the DNS request.
type Result int
// Supported Result values. </s> remove // TimeUnit is the unit of measuring time while aggregating the statistics.
type TimeUnit int
</s> add // StatsCtx collects the statistics and flushes it to the database. Its default
// flushing interval is one hour.
//
// TODO(e.burkov): Use atomic.Pointer for accessing db in go1.19.
type StatsCtx struct {
// limitHours is the maximum number of hours to collect statistics into the
// current unit.
//
// It is of type uint32 to be accessed by atomic. It's arranged at the
// beginning of the structure to keep 64-bit alignment.
limitHours uint32 </s> remove // TODO(e.burkov): Use atomic.Pointer for accessing curr and db in go1.19.
type StatsCtx struct {
// currMu protects the current unit.
currMu *sync.Mutex
// curr is the actual statistics collection result.
curr *unit
// dbMu protects db.
dbMu *sync.Mutex
// db is the opened statistics database, if any.
db *bbolt.DB
// unitIDGen is the function that generates an identifier for the current
// unit. It's here for only testing purposes.
unitIDGen UnitIDGenFunc
// httpRegister is used to set HTTP handlers.
httpRegister aghhttp.RegisterFunc
// configModified is called whenever the configuration is modified via web
// interface.
configModified func()
// filename is the name of database file.
filename string
// limitHours is the maximum number of hours to collect statistics into the
// current unit.
limitHours uint32
</s> add // TODO(e.burkov): Think about better naming.
const (
RNotFiltered Result = iota + 1
RFiltered
RSafeBrowsing
RSafeSearch
RParental
resultLast = RParental + 1
)
// Entry is a statistics data entry.
type Entry struct {
// Clients is the client's primary ID.
//
// TODO(a.garipov): Make this a {net.IP, string} enum?
Client string
// Domain is the domain name requested.
Domain string
// Result is the result of processing the request.
Result Result
// Time is the duration of the request processing in milliseconds.
Time uint32 | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats.go |
// unitIDGen is the function that generates an identifier for the current
// unit. It's here for only testing purposes.
unitIDGen UnitIDGenFunc | <mask>
<mask> // Result is the resulting code of processing the DNS request.
<mask> type Result int
<mask>
<mask> // Supported Result values.
<mask> //
<mask> // TODO(e.burkov): Think about better naming.
<mask> const (
<mask> RNotFiltered Result = iota + 1
<mask> RFiltered
<mask> RSafeBrowsing
<mask> RSafeSearch
<mask> RParental
<mask>
<mask> resultLast = RParental + 1
<mask> )
<mask>
<mask> // Entry is a statistics data entry.
<mask> type Entry struct {
<mask> // Clients is the client's primary ID.
<mask> //
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove // Result is the resulting code of processing the DNS request.
type Result int
</s> add // dbMu protects db.
dbMu *sync.Mutex
// db is the opened statistics database, if any.
db *bbolt.DB </s> remove // TODO(e.burkov): Use atomic.Pointer for accessing curr and db in go1.19.
type StatsCtx struct {
// currMu protects the current unit.
currMu *sync.Mutex
// curr is the actual statistics collection result.
curr *unit
// dbMu protects db.
dbMu *sync.Mutex
// db is the opened statistics database, if any.
db *bbolt.DB
// unitIDGen is the function that generates an identifier for the current
// unit. It's here for only testing purposes.
unitIDGen UnitIDGenFunc
// httpRegister is used to set HTTP handlers.
httpRegister aghhttp.RegisterFunc
// configModified is called whenever the configuration is modified via web
// interface.
configModified func()
// filename is the name of database file.
filename string
// limitHours is the maximum number of hours to collect statistics into the
// current unit.
limitHours uint32
</s> add // TODO(e.burkov): Think about better naming.
const (
RNotFiltered Result = iota + 1
RFiltered
RSafeBrowsing
RSafeSearch
RParental
resultLast = RParental + 1
)
// Entry is a statistics data entry.
type Entry struct {
// Clients is the client's primary ID.
//
// TODO(a.garipov): Make this a {net.IP, string} enum?
Client string
// Domain is the domain name requested.
Domain string
// Result is the result of processing the request.
Result Result
// Time is the duration of the request processing in milliseconds.
Time uint32 </s> remove // Supported TimeUnit values.
const (
Hours TimeUnit = iota
Days
)
</s> add // currMu protects curr.
currMu *sync.RWMutex
// curr is the actual statistics collection result.
curr *unit </s> remove // StatsCtx collects the statistics and flushes it to the database. Its default
// flushing interval is one hour.
</s> add // UnitIDGenFunc is the signature of a function that generates a unique ID for
// the statistics unit.
type UnitIDGenFunc func() (id uint32)
// TimeUnit is the unit of measuring time while aggregating the statistics.
type TimeUnit int
// Supported TimeUnit values.
const (
Hours TimeUnit = iota
Days
)
// Result is the resulting code of processing the DNS request.
type Result int
// Supported Result values. </s> remove // Domain is the domain name requested.
Domain string
</s> add if cur != nil {
units = append(units, cur.serialize())
} | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats.go |
// httpRegister is used to set HTTP handlers.
httpRegister aghhttp.RegisterFunc
// configModified is called whenever the configuration is modified via web
// interface.
configModified func()
// filename is the name of database file.
filename string
}
var _ Interface = &StatsCtx{}
// New creates s from conf and properly initializes it. Don't use s before
// calling it's Start method.
func New(conf Config) (s *StatsCtx, err error) {
defer withRecovered(&err)
s = &StatsCtx{
currMu: &sync.RWMutex{},
dbMu: &sync.Mutex{},
filename: conf.Filename,
configModified: conf.ConfigModified,
httpRegister: conf.HTTPRegister,
}
if s.limitHours = conf.LimitDays * 24; !checkInterval(conf.LimitDays) {
s.limitHours = 24
}
if s.unitIDGen = newUnitID; conf.UnitID != nil {
s.unitIDGen = conf.UnitID
}
// TODO(e.burkov): Move the code below to the Start method.
err = s.openDB()
if err != nil {
return nil, fmt.Errorf("opening database: %w", err)
}
var udb *unitDB
id := s.unitIDGen()
tx, err := s.db.Begin(true)
if err != nil {
return nil, fmt.Errorf("stats: opening a transaction: %w", err)
}
deleted := deleteOldUnits(tx, id-s.limitHours-1)
udb = loadUnitFromDB(tx, id)
err = finishTxn(tx, deleted > 0)
if err != nil {
log.Error("stats: %s", err)
}
s.curr = newUnit(id)
s.curr.deserialize(udb)
log.Debug("stats: initialized")
return s, nil
}
// withRecovered turns the value recovered from panic if any into an error and
// combines it with the one pointed by orig. orig must be non-nil.
func withRecovered(orig *error) {
p := recover()
if p == nil {
return
}
var err error
switch p := p.(type) {
case error:
err = fmt.Errorf("panic: %w", p)
default:
err = fmt.Errorf("panic: recovered value of type %[1]T: %[1]v", p)
}
*orig = errors.WithDeferred(*orig, err)
}
// Start implements the Interface interface for *StatsCtx.
func (s *StatsCtx) Start() {
s.initWeb()
go s.periodicFlush()
}
// Close implements the io.Closer interface for *StatsCtx.
func (s *StatsCtx) Close() (err error) {
defer func() { err = errors.Annotate(err, "stats: closing: %w") }()
db := s.swapDatabase(nil)
if db == nil {
return nil
}
defer func() {
cerr := db.Close()
if cerr == nil {
log.Debug("stats: database closed")
}
err = errors.WithDeferred(err, cerr)
}()
tx, err := db.Begin(true)
if err != nil {
return fmt.Errorf("opening transaction: %w", err)
}
defer func() { err = errors.WithDeferred(err, finishTxn(tx, err == nil)) }()
s.currMu.RLock()
defer s.currMu.RUnlock()
udb := s.curr.serialize()
return udb.flushUnitToDB(tx, s.curr.id)
}
// Update implements the Interface interface for *StatsCtx.
func (s *StatsCtx) Update(e Entry) {
if atomic.LoadUint32(&s.limitHours) == 0 {
return
}
if e.Result == 0 || e.Result >= resultLast || e.Domain == "" || e.Client == "" {
log.Debug("stats: malformed entry")
return
}
s.currMu.Lock()
defer s.currMu.Unlock()
if s.curr == nil {
log.Error("stats: current unit is nil")
return
}
clientID := e.Client
if ip := net.ParseIP(clientID); ip != nil {
clientID = ip.String()
}
s.curr.add(e.Result, e.Domain, clientID, uint64(e.Time))
}
// WriteDiskConfig implements the Interface interface for *StatsCtx.
func (s *StatsCtx) WriteDiskConfig(dc *DiskConfig) {
dc.Interval = atomic.LoadUint32(&s.limitHours) / 24
}
// TopClientsIP implements the Interface interface for *StatsCtx.
func (s *StatsCtx) TopClientsIP(maxCount uint) (ips []net.IP) {
limit := atomic.LoadUint32(&s.limitHours)
if limit == 0 {
return nil
}
units, _ := s.loadUnits(limit)
if units == nil {
return nil
}
// Collect data for all the clients to sort and crop it afterwards.
m := map[string]uint64{}
for _, u := range units {
for _, it := range u.Clients {
m[it.Name] += it.Count
}
}
a := convertMapToSlice(m, int(maxCount))
ips = []net.IP{}
for _, it := range a {
ip := net.ParseIP(it.Name)
if ip != nil {
ips = append(ips, ip)
}
}
return ips
}
// database returns the database if it's opened. It's safe for concurrent use.
func (s *StatsCtx) database() (db *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
return s.db
}
// swapDatabase swaps the database with another one and returns it. It's safe
// for concurrent use.
func (s *StatsCtx) swapDatabase(with *bbolt.DB) (old *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
old, s.db = s.db, with
return old
}
// deleteOldUnits walks the buckets available to tx and deletes old units. It
// returns the number of deletions performed.
func deleteOldUnits(tx *bbolt.Tx, firstID uint32) (deleted int) {
log.Debug("stats: deleting old units until id %d", firstID)
// TODO(a.garipov): See if this is actually necessary. Looks like a rather
// bizarre solution.
const errStop errors.Error = "stop iteration"
walk := func(name []byte, _ *bbolt.Bucket) (err error) {
nameID, ok := unitNameToID(name)
if ok && nameID >= firstID {
return errStop
}
err = tx.DeleteBucket(name)
if err != nil {
log.Debug("stats: deleting bucket: %s", err)
return nil
}
log.Debug("stats: deleted unit %d (name %x)", nameID, name)
deleted++
return nil
}
err := tx.ForEach(walk)
if err != nil && !errors.Is(err, errStop) {
log.Debug("stats: deleting units: %s", err)
}
return deleted
}
// openDB returns an error if the database can't be opened from the specified
// file. It's safe for concurrent use.
func (s *StatsCtx) openDB() (err error) {
log.Debug("stats: opening database")
var db *bbolt.DB
db, err = bbolt.Open(s.filename, 0o644, nil)
if err != nil {
if err.Error() == "invalid argument" {
log.Error("AdGuard Home cannot be initialized due to an incompatible file system.\nPlease read the explanation here: https://github.com/AdguardTeam/AdGuardHome/wiki/Getting-Started#limitations")
}
return err
}
// Use defer to unlock the mutex as soon as possible.
defer log.Debug("stats: database opened")
s.dbMu.Lock()
defer s.dbMu.Unlock()
s.db = db
return nil
}
func (s *StatsCtx) flush() (cont bool, sleepFor time.Duration) {
id := s.unitIDGen()
s.currMu.Lock()
defer s.currMu.Unlock()
ptr := s.curr
if ptr == nil {
return false, 0
}
limit := atomic.LoadUint32(&s.limitHours)
if limit == 0 || ptr.id == id {
return true, time.Second
}
db := s.database()
if db == nil {
return true, 0
}
tx, err := db.Begin(true)
if err != nil {
log.Error("stats: opening transaction: %s", err)
return true, 0
}
s.curr = newUnit(id)
isCommitable := true
ferr := ptr.serialize().flushUnitToDB(tx, ptr.id)
if ferr != nil {
log.Error("stats: flushing unit: %s", ferr)
isCommitable = false
}
derr := tx.DeleteBucket(idToUnitName(id - limit))
if derr != nil {
log.Error("stats: deleting unit: %s", derr)
if !errors.Is(derr, bbolt.ErrBucketNotFound) {
isCommitable = false
}
}
err = finishTxn(tx, isCommitable)
if err != nil {
log.Error("stats: %s", err)
}
return true, 0
}
// periodicFlush checks and flushes the unit to the database if the freshly
// generated unit ID differs from the current's ID. Flushing process includes:
// - swapping the current unit with the new empty one;
// - writing the current unit to the database;
// - removing the stale unit from the database.
func (s *StatsCtx) periodicFlush() {
for cont, sleepFor := true, time.Duration(0); cont; time.Sleep(sleepFor) {
cont, sleepFor = s.flush()
}
log.Debug("periodic flushing finished")
}
func (s *StatsCtx) setLimit(limitDays int) {
atomic.StoreUint32(&s.limitHours, uint32(24*limitDays))
if limitDays == 0 {
if err := s.clear(); err != nil {
log.Error("stats: %s", err)
}
}
log.Debug("stats: set limit: %d days", limitDays)
}
// Reset counters and clear database
func (s *StatsCtx) clear() (err error) {
defer func() { err = errors.Annotate(err, "clearing: %w") }()
db := s.swapDatabase(nil)
if db != nil {
var tx *bbolt.Tx
tx, err = db.Begin(true)
if err != nil {
log.Error("stats: opening a transaction: %s", err)
} else if err = finishTxn(tx, false); err != nil {
// Don't wrap the error since it's informative enough as is.
return err
}
// Active transactions will continue using database, but new ones won't
// be created.
err = db.Close()
if err != nil {
return fmt.Errorf("closing database: %w", err)
}
// All active transactions are now closed.
log.Debug("stats: database closed")
}
err = os.Remove(s.filename)
if err != nil {
log.Error("stats: %s", err)
}
err = s.openDB()
if err != nil {
log.Error("stats: opening database: %s", err)
}
// Use defer to unlock the mutex as soon as possible.
defer log.Debug("stats: cleared")
s.currMu.Lock()
defer s.currMu.Unlock()
s.curr = newUnit(s.unitIDGen())
return nil
}
func (s *StatsCtx) loadUnits(limit uint32) (units []*unitDB, firstID uint32) {
db := s.database()
if db == nil {
return nil, 0
}
// Use writable transaction to ensure any ongoing writable transaction is
// taken into account.
tx, err := db.Begin(true)
if err != nil {
log.Error("stats: opening transaction: %s", err)
return nil, 0
}
s.currMu.RLock()
defer s.currMu.RUnlock()
cur := s.curr
var curID uint32
if cur != nil {
curID = cur.id
} else {
curID = s.unitIDGen()
}
// Per-hour units.
units = make([]*unitDB, 0, limit)
firstID = curID - limit + 1
for i := firstID; i != curID; i++ {
u := loadUnitFromDB(tx, i)
if u == nil {
u = &unitDB{NResult: make([]uint64, resultLast)}
}
units = append(units, u)
}
err = finishTxn(tx, false)
if err != nil {
log.Error("stats: %s", err)
} | <mask>
<mask> resultLast = RParental + 1
<mask> )
<mask>
<mask> // Entry is a statistics data entry.
<mask> type Entry struct {
<mask> // Clients is the client's primary ID.
<mask> //
<mask> // TODO(a.garipov): Make this a {net.IP, string} enum?
<mask> Client string
<mask>
<mask> // Domain is the domain name requested.
<mask> Domain string
<mask>
<mask> // Result is the result of processing the request.
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats.go |
if cur != nil {
units = append(units, cur.serialize())
} | <mask> //
<mask> // TODO(a.garipov): Make this a {net.IP, string} enum?
<mask> Client string
<mask>
<mask> // Domain is the domain name requested.
<mask> Domain string
<mask>
<mask> // Result is the result of processing the request.
<mask> Result Result
<mask>
<mask> // Time is the duration of the request processing in milliseconds.
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove // Result is the result of processing the request.
Result Result
</s> add if unitsLen := len(units); unitsLen != int(limit) {
log.Fatalf("loaded %d units whilst the desired number is %d", unitsLen, limit)
} </s> remove // TODO(e.burkov): Use atomic.Pointer for accessing curr and db in go1.19.
type StatsCtx struct {
// currMu protects the current unit.
currMu *sync.Mutex
// curr is the actual statistics collection result.
curr *unit
// dbMu protects db.
dbMu *sync.Mutex
// db is the opened statistics database, if any.
db *bbolt.DB
// unitIDGen is the function that generates an identifier for the current
// unit. It's here for only testing purposes.
unitIDGen UnitIDGenFunc
// httpRegister is used to set HTTP handlers.
httpRegister aghhttp.RegisterFunc
// configModified is called whenever the configuration is modified via web
// interface.
configModified func()
// filename is the name of database file.
filename string
// limitHours is the maximum number of hours to collect statistics into the
// current unit.
limitHours uint32
</s> add // TODO(e.burkov): Think about better naming.
const (
RNotFiltered Result = iota + 1
RFiltered
RSafeBrowsing
RSafeSearch
RParental
resultLast = RParental + 1
)
// Entry is a statistics data entry.
type Entry struct {
// Clients is the client's primary ID.
//
// TODO(a.garipov): Make this a {net.IP, string} enum?
Client string
// Domain is the domain name requested.
Domain string
// Result is the result of processing the request.
Result Result
// Time is the duration of the request processing in milliseconds.
Time uint32 </s> remove // Time is the duration of the request processing in milliseconds.
Time uint32
</s> add return units, firstID </s> remove // Result is the resulting code of processing the DNS request.
type Result int
</s> add // dbMu protects db.
dbMu *sync.Mutex
// db is the opened statistics database, if any.
db *bbolt.DB </s> remove // Supported TimeUnit values.
const (
Hours TimeUnit = iota
Days
)
</s> add // currMu protects curr.
currMu *sync.RWMutex
// curr is the actual statistics collection result.
curr *unit | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats.go |
if unitsLen := len(units); unitsLen != int(limit) {
log.Fatalf("loaded %d units whilst the desired number is %d", unitsLen, limit)
} | <mask>
<mask> // Domain is the domain name requested.
<mask> Domain string
<mask>
<mask> // Result is the result of processing the request.
<mask> Result Result
<mask>
<mask> // Time is the duration of the request processing in milliseconds.
<mask> Time uint32
<mask> }
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove // Domain is the domain name requested.
Domain string
</s> add if cur != nil {
units = append(units, cur.serialize())
} </s> remove // Time is the duration of the request processing in milliseconds.
Time uint32
</s> add return units, firstID </s> remove // TODO(e.burkov): Use atomic.Pointer for accessing curr and db in go1.19.
type StatsCtx struct {
// currMu protects the current unit.
currMu *sync.Mutex
// curr is the actual statistics collection result.
curr *unit
// dbMu protects db.
dbMu *sync.Mutex
// db is the opened statistics database, if any.
db *bbolt.DB
// unitIDGen is the function that generates an identifier for the current
// unit. It's here for only testing purposes.
unitIDGen UnitIDGenFunc
// httpRegister is used to set HTTP handlers.
httpRegister aghhttp.RegisterFunc
// configModified is called whenever the configuration is modified via web
// interface.
configModified func()
// filename is the name of database file.
filename string
// limitHours is the maximum number of hours to collect statistics into the
// current unit.
limitHours uint32
</s> add // TODO(e.burkov): Think about better naming.
const (
RNotFiltered Result = iota + 1
RFiltered
RSafeBrowsing
RSafeSearch
RParental
resultLast = RParental + 1
)
// Entry is a statistics data entry.
type Entry struct {
// Clients is the client's primary ID.
//
// TODO(a.garipov): Make this a {net.IP, string} enum?
Client string
// Domain is the domain name requested.
Domain string
// Result is the result of processing the request.
Result Result
// Time is the duration of the request processing in milliseconds.
Time uint32 </s> remove // Supported TimeUnit values.
const (
Hours TimeUnit = iota
Days
)
</s> add // currMu protects curr.
currMu *sync.RWMutex
// curr is the actual statistics collection result.
curr *unit </s> remove // Result is the resulting code of processing the DNS request.
type Result int
</s> add // dbMu protects db.
dbMu *sync.Mutex
// db is the opened statistics database, if any.
db *bbolt.DB | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats.go |
return units, firstID | <mask>
<mask> // Result is the result of processing the request.
<mask> Result Result
<mask>
<mask> // Time is the duration of the request processing in milliseconds.
<mask> Time uint32
<mask> }
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove // Result is the result of processing the request.
Result Result
</s> add if unitsLen := len(units); unitsLen != int(limit) {
log.Fatalf("loaded %d units whilst the desired number is %d", unitsLen, limit)
} </s> remove // Domain is the domain name requested.
Domain string
</s> add if cur != nil {
units = append(units, cur.serialize())
} </s> remove // TODO(e.burkov): Use atomic.Pointer for accessing curr and db in go1.19.
type StatsCtx struct {
// currMu protects the current unit.
currMu *sync.Mutex
// curr is the actual statistics collection result.
curr *unit
// dbMu protects db.
dbMu *sync.Mutex
// db is the opened statistics database, if any.
db *bbolt.DB
// unitIDGen is the function that generates an identifier for the current
// unit. It's here for only testing purposes.
unitIDGen UnitIDGenFunc
// httpRegister is used to set HTTP handlers.
httpRegister aghhttp.RegisterFunc
// configModified is called whenever the configuration is modified via web
// interface.
configModified func()
// filename is the name of database file.
filename string
// limitHours is the maximum number of hours to collect statistics into the
// current unit.
limitHours uint32
</s> add // TODO(e.burkov): Think about better naming.
const (
RNotFiltered Result = iota + 1
RFiltered
RSafeBrowsing
RSafeSearch
RParental
resultLast = RParental + 1
)
// Entry is a statistics data entry.
type Entry struct {
// Clients is the client's primary ID.
//
// TODO(a.garipov): Make this a {net.IP, string} enum?
Client string
// Domain is the domain name requested.
Domain string
// Result is the result of processing the request.
Result Result
// Time is the duration of the request processing in milliseconds.
Time uint32 </s> remove // Result is the resulting code of processing the DNS request.
type Result int
</s> add // dbMu protects db.
dbMu *sync.Mutex
// db is the opened statistics database, if any.
db *bbolt.DB </s> remove // Supported TimeUnit values.
const (
Hours TimeUnit = iota
Days
)
</s> add // currMu protects curr.
currMu *sync.RWMutex
// curr is the actual statistics collection result.
curr *unit | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats.go |
package stats_test | <mask> package stats
<mask>
<mask> import (
<mask> "fmt"
<mask> "net"
<mask> "os"
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove "os"
</s> add "net/http"
"net/http/httptest"
"path/filepath" </s> remove "net"
"os"
</s> add </s> remove "sync"
"sync/atomic"
</s> add | [
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats_test.go |
"encoding/json" | <mask> package stats_test
<mask>
<mask> import (
<mask> "fmt"
<mask> "net"
<mask> "net/http"
<mask> "net/http/httptest"
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove package stats
</s> add package stats_test </s> remove "os"
</s> add "net/http"
"net/http/httptest"
"path/filepath" </s> remove "net"
"os"
</s> add | [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats_test.go |
"net/http"
"net/http/httptest"
"path/filepath" | <mask>
<mask> import (
<mask> "fmt"
<mask> "net"
<mask> "os"
<mask> "sync/atomic"
<mask> "testing"
<mask>
<mask> "github.com/AdguardTeam/AdGuardHome/internal/aghtest"
<mask> "github.com/AdguardTeam/golibs/testutil"
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove package stats
</s> add package stats_test </s> remove "net"
"os"
</s> add </s> remove "sync"
"sync/atomic"
</s> add | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats_test.go |
"github.com/AdguardTeam/AdGuardHome/internal/stats" | <mask>
<mask> "github.com/AdguardTeam/AdGuardHome/internal/aghtest"
<mask> "github.com/AdguardTeam/golibs/testutil"
<mask> "github.com/stretchr/testify/assert"
<mask> "github.com/stretchr/testify/require"
<mask> )
<mask>
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove "os"
</s> add "net/http"
"net/http/httptest"
"path/filepath" </s> remove "github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
</s> add </s> remove // Result is the resulting code of processing the DNS request.
type Result int
</s> add // dbMu protects db.
dbMu *sync.Mutex
// db is the opened statistics database, if any.
db *bbolt.DB | [
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats_test.go |
// constUnitID is the UnitIDGenFunc which always return 0.
func constUnitID() (id uint32) { return 0 } | <mask> func TestMain(m *testing.M) {
<mask> aghtest.DiscardLogOutput(m)
<mask> }
<mask>
<mask> func UIntArrayEquals(a, b []uint64) bool {
<mask> if len(a) != len(b) {
<mask> return false
<mask> }
<mask>
<mask> for i := range a {
<mask> if a[i] != b[i] {
<mask> return false
<mask> }
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove for i := range a {
if a[i] != b[i] {
return false
}
</s> add func assertSuccessAndUnmarshal(t *testing.T, to any, handler http.Handler, req *http.Request) {
t.Helper()
require.NotNil(t, handler)
rw := httptest.NewRecorder()
handler.ServeHTTP(rw, req)
require.Equal(t, http.StatusOK, rw.Code)
data := rw.Body.Bytes()
if to == nil {
assert.Empty(t, data)
return </s> remove log.Debug("stats: deleted unit %d", id)
return true
}
func convertMapToSlice(m map[string]uint64, max int) []countPair {
a := []countPair{}
for k, v := range m {
a = append(a, countPair{Name: k, Count: v})
}
less := func(i, j int) bool {
return a[j].Count < a[i].Count
}
sort.Slice(a, less)
if max > len(a) {
max = len(a)
}
return a[:max]
</s> add return s[:max] </s> remove log.Tracef("periodicFlush() exited")
}
// deleteUnit removes the unit by it's id from the database the tx belongs to.
func (s *StatsCtx) deleteUnit(tx *bbolt.Tx, id uint32) bool {
err := tx.DeleteBucket(idToUnitName(id))
if err != nil {
log.Tracef("stats: bolt DeleteBucket: %s", err)
return false
</s> add sort.Slice(s, func(i, j int) bool {
return s[j].Count < s[i].Count
})
if max > len(s) {
max = len(s) </s> remove
func (s *StatsCtx) GetTopClientsIP(maxCount uint) []net.IP {
if !s.isEnabled() {
return nil
}
units, _ := s.loadUnits(atomic.LoadUint32(&s.limitHours))
if units == nil {
return nil
}
// top clients
m := map[string]uint64{}
for _, u := range units {
for _, it := range u.Clients {
m[it.Name] += it.Count
}
}
a := convertMapToSlice(m, int(maxCount))
d := []net.IP{}
for _, it := range a {
ip := net.ParseIP(it.Name)
if ip != nil {
d = append(d, ip)
}
}
return d
}
</s> add | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats_test.go |
func assertSuccessAndUnmarshal(t *testing.T, to any, handler http.Handler, req *http.Request) {
t.Helper()
require.NotNil(t, handler)
rw := httptest.NewRecorder()
handler.ServeHTTP(rw, req)
require.Equal(t, http.StatusOK, rw.Code)
data := rw.Body.Bytes()
if to == nil {
assert.Empty(t, data)
return | <mask> if len(a) != len(b) {
<mask> return false
<mask> }
<mask>
<mask> for i := range a {
<mask> if a[i] != b[i] {
<mask> return false
<mask> }
<mask> }
<mask>
<mask> return true
<mask> }
<mask>
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove func UIntArrayEquals(a, b []uint64) bool {
if len(a) != len(b) {
return false
}
</s> add // constUnitID is the UnitIDGenFunc which always return 0.
func constUnitID() (id uint32) { return 0 } </s> remove log.Debug("stats: deleted unit %d", id)
return true
}
func convertMapToSlice(m map[string]uint64, max int) []countPair {
a := []countPair{}
for k, v := range m {
a = append(a, countPair{Name: k, Count: v})
}
less := func(i, j int) bool {
return a[j].Count < a[i].Count
}
sort.Slice(a, less)
if max > len(a) {
max = len(a)
}
return a[:max]
</s> add return s[:max] </s> remove
func (s *StatsCtx) GetTopClientsIP(maxCount uint) []net.IP {
if !s.isEnabled() {
return nil
}
units, _ := s.loadUnits(atomic.LoadUint32(&s.limitHours))
if units == nil {
return nil
}
// top clients
m := map[string]uint64{}
for _, u := range units {
for _, it := range u.Clients {
m[it.Name] += it.Count
}
}
a := convertMapToSlice(m, int(maxCount))
d := []net.IP{}
for _, it := range a {
ip := net.ParseIP(it.Name)
if ip != nil {
d = append(d, ip)
}
}
return d
}
</s> add </s> remove return statsResponse{}, false
</s> add return StatsResp{}, false </s> remove log.Error("bkt.Put: %s", err)
return false
}
return true
}
func (s *StatsCtx) loadUnitFromDB(tx *bbolt.Tx, id uint32) *unitDB {
bkt := tx.Bucket(idToUnitName(id))
if bkt == nil {
return nil
</s> add return fmt.Errorf("putting unit to database: %w", err) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats_test.go |
err := json.Unmarshal(data, to)
require.NoError(t, err) | <mask> return false
<mask> }
<mask> }
<mask>
<mask> return true
<mask> }
<mask>
<mask> func TestStats(t *testing.T) {
<mask> conf := Config{
<mask> Filename: "./stats.db",
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove conf := Config{
Filename: "./stats.db",
</s> add cliIP := net.IP{127, 0, 0, 1}
cliIPStr := cliIP.String()
handlers := map[string]http.Handler{}
conf := stats.Config{
Filename: filepath.Join(t.TempDir(), "stats.db"), </s> remove var hour int32 = 0
newID := func() uint32 {
// Use "atomic" to make go race detector happy.
return uint32(atomic.LoadInt32(&hour))
</s> add var curHour uint32 = 1
handlers := map[string]http.Handler{}
conf := stats.Config{
Filename: filepath.Join(t.TempDir(), "stats.db"),
LimitDays: 1,
UnitID: func() (id uint32) { return atomic.LoadUint32(&curHour) },
HTTPRegister: func(_, url string, handler http.HandlerFunc) { handlers[url] = handler }, </s> remove conf := Config{
Filename: "./stats.db",
LimitDays: 1,
UnitID: newID,
}
s, err := New(conf)
</s> add s, err := stats.New(conf) </s> remove s, err := New(conf)
</s> add s, err := stats.New(conf) </s> remove for i := range a {
if a[i] != b[i] {
return false
}
</s> add func assertSuccessAndUnmarshal(t *testing.T, to any, handler http.Handler, req *http.Request) {
t.Helper()
require.NotNil(t, handler)
rw := httptest.NewRecorder()
handler.ServeHTTP(rw, req)
require.Equal(t, http.StatusOK, rw.Code)
data := rw.Body.Bytes()
if to == nil {
assert.Empty(t, data)
return | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats_test.go |
cliIP := net.IP{127, 0, 0, 1}
cliIPStr := cliIP.String()
handlers := map[string]http.Handler{}
conf := stats.Config{
Filename: filepath.Join(t.TempDir(), "stats.db"), | <mask> return true
<mask> }
<mask>
<mask> func TestStats(t *testing.T) {
<mask> conf := Config{
<mask> Filename: "./stats.db",
<mask> LimitDays: 1,
<mask> }
<mask>
<mask> s, err := New(conf)
<mask> require.NoError(t, err)
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove return true
</s> add err := json.Unmarshal(data, to)
require.NoError(t, err) </s> remove conf := Config{
Filename: "./stats.db",
LimitDays: 1,
UnitID: newID,
}
s, err := New(conf)
</s> add s, err := stats.New(conf) </s> remove s, err := New(conf)
</s> add s, err := stats.New(conf) </s> remove var hour int32 = 0
newID := func() uint32 {
// Use "atomic" to make go race detector happy.
return uint32(atomic.LoadInt32(&hour))
</s> add var curHour uint32 = 1
handlers := map[string]http.Handler{}
conf := stats.Config{
Filename: filepath.Join(t.TempDir(), "stats.db"),
LimitDays: 1,
UnitID: func() (id uint32) { return atomic.LoadUint32(&curHour) },
HTTPRegister: func(_, url string, handler http.HandlerFunc) { handlers[url] = handler }, | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats_test.go |
UnitID: constUnitID,
HTTPRegister: func(_, url string, handler http.HandlerFunc) {
handlers[url] = handler
}, | <mask> Filename: filepath.Join(t.TempDir(), "stats.db"),
<mask> LimitDays: 1,
<mask> }
<mask>
<mask> s, err := stats.New(conf)
<mask> require.NoError(t, err)
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove conf := Config{
Filename: "./stats.db",
</s> add cliIP := net.IP{127, 0, 0, 1}
cliIPStr := cliIP.String()
handlers := map[string]http.Handler{}
conf := stats.Config{
Filename: filepath.Join(t.TempDir(), "stats.db"), </s> remove s, err := New(conf)
</s> add s, err := stats.New(conf) </s> remove conf := Config{
Filename: "./stats.db",
LimitDays: 1,
UnitID: newID,
}
s, err := New(conf)
</s> add s, err := stats.New(conf) </s> remove var hour int32 = 0
newID := func() uint32 {
// Use "atomic" to make go race detector happy.
return uint32(atomic.LoadInt32(&hour))
</s> add var curHour uint32 = 1
handlers := map[string]http.Handler{}
conf := stats.Config{
Filename: filepath.Join(t.TempDir(), "stats.db"),
LimitDays: 1,
UnitID: func() (id uint32) { return atomic.LoadUint32(&curHour) },
HTTPRegister: func(_, url string, handler http.HandlerFunc) { handlers[url] = handler }, </s> remove return true
</s> add err := json.Unmarshal(data, to)
require.NoError(t, err) | [
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats_test.go |
s, err := stats.New(conf) | <mask> Filename: "./stats.db",
<mask> LimitDays: 1,
<mask> }
<mask>
<mask> s, err := New(conf)
<mask> require.NoError(t, err)
<mask> testutil.CleanupAndRequireSuccess(t, func() (err error) {
<mask> s.clear()
<mask> s.Close()
<mask>
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove conf := Config{
Filename: "./stats.db",
LimitDays: 1,
UnitID: newID,
}
s, err := New(conf)
</s> add s, err := stats.New(conf) </s> remove testutil.CleanupAndRequireSuccess(t, func() (err error) {
s.clear()
s.Close()
</s> add </s> remove testutil.CleanupAndRequireSuccess(t, func() (err error) {
s.Close()
</s> add </s> remove conf := Config{
Filename: "./stats.db",
</s> add cliIP := net.IP{127, 0, 0, 1}
cliIPStr := cliIP.String()
handlers := map[string]http.Handler{}
conf := stats.Config{
Filename: filepath.Join(t.TempDir(), "stats.db"), | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats_test.go |
<mask> }
<mask>
<mask> s, err := New(conf)
<mask> require.NoError(t, err)
<mask> testutil.CleanupAndRequireSuccess(t, func() (err error) {
<mask> s.clear()
<mask> s.Close()
<mask>
<mask> return os.Remove(conf.Filename)
<mask> })
<mask>
<mask> s.Update(Entry{
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove s, err := New(conf)
</s> add s, err := stats.New(conf) </s> remove testutil.CleanupAndRequireSuccess(t, func() (err error) {
s.Close()
</s> add </s> remove conf := Config{
Filename: "./stats.db",
LimitDays: 1,
UnitID: newID,
}
s, err := New(conf)
</s> add s, err := stats.New(conf) </s> remove return os.Remove(conf.Filename)
})
</s> add s.Start()
testutil.CleanupAndRequireSuccess(t, s.Close) </s> remove conf := Config{
Filename: "./stats.db",
</s> add cliIP := net.IP{127, 0, 0, 1}
cliIPStr := cliIP.String()
handlers := map[string]http.Handler{}
conf := stats.Config{
Filename: filepath.Join(t.TempDir(), "stats.db"), | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats_test.go |
|
s.Start()
testutil.CleanupAndRequireSuccess(t, s.Close)
t.Run("data", func(t *testing.T) {
const reqDomain = "domain"
entries := []stats.Entry{{
Domain: reqDomain,
Client: cliIPStr,
Result: stats.RFiltered,
Time: 123456,
}, {
Domain: reqDomain,
Client: cliIPStr,
Result: stats.RNotFiltered,
Time: 123456,
}}
wantData := &stats.StatsResp{
TimeUnits: "hours",
TopQueried: []map[string]uint64{0: {reqDomain: 1}},
TopClients: []map[string]uint64{0: {cliIPStr: 2}},
TopBlocked: []map[string]uint64{0: {reqDomain: 1}},
DNSQueries: []uint64{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
},
BlockedFiltering: []uint64{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
},
ReplacedSafebrowsing: []uint64{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
},
ReplacedParental: []uint64{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
},
NumDNSQueries: 2,
NumBlockedFiltering: 1,
NumReplacedSafebrowsing: 0,
NumReplacedSafesearch: 0,
NumReplacedParental: 0,
AvgProcessingTime: 0.123456,
} | <mask> testutil.CleanupAndRequireSuccess(t, func() (err error) {
<mask> s.clear()
<mask> s.Close()
<mask>
<mask> return os.Remove(conf.Filename)
<mask> })
<mask>
<mask> s.Update(Entry{
<mask> Domain: "domain",
<mask> Client: "127.0.0.1",
<mask> Result: RFiltered,
<mask> Time: 123456,
<mask> })
<mask> s.Update(Entry{
<mask> Domain: "domain",
<mask> Client: "127.0.0.1",
<mask> Result: RNotFiltered,
<mask> Time: 123456,
<mask> })
<mask>
<mask> d, ok := s.getData()
<mask> require.True(t, ok)
<mask>
<mask> a := []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2}
<mask> assert.True(t, UIntArrayEquals(d.DNSQueries, a))
<mask>
<mask> a = []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}
<mask> assert.True(t, UIntArrayEquals(d.BlockedFiltering, a))
<mask>
<mask> a = []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove a = []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}
assert.True(t, UIntArrayEquals(d.BlockedFiltering, a))
</s> add for _, e := range entries {
s.Update(e)
} </s> remove a = []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
assert.True(t, UIntArrayEquals(d.ReplacedSafebrowsing, a))
</s> add data := &stats.StatsResp{}
req := httptest.NewRequest(http.MethodGet, "/control/stats", nil)
assertSuccessAndUnmarshal(t, data, handlers["/control/stats"], req) </s> remove a = []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
assert.True(t, UIntArrayEquals(d.ReplacedParental, a))
</s> add assert.Equal(t, wantData, data)
}) </s> remove m := d.TopQueried
require.NotEmpty(t, m)
assert.EqualValues(t, 1, m[0]["domain"])
</s> add t.Run("tops", func(t *testing.T) {
topClients := s.TopClientsIP(2)
require.NotEmpty(t, topClients) </s> remove topClients := s.GetTopClientsIP(2)
require.NotEmpty(t, topClients)
assert.True(t, net.IP{127, 0, 0, 1}.Equal(topClients[0]))
</s> add assertSuccessAndUnmarshal(t, data, handlers["/control/stats"], req)
assert.Equal(t, emptyData, data)
}) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats_test.go |
for _, e := range entries {
s.Update(e)
} | <mask>
<mask> a := []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2}
<mask> assert.True(t, UIntArrayEquals(d.DNSQueries, a))
<mask>
<mask> a = []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}
<mask> assert.True(t, UIntArrayEquals(d.BlockedFiltering, a))
<mask>
<mask> a = []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
<mask> assert.True(t, UIntArrayEquals(d.ReplacedSafebrowsing, a))
<mask>
<mask> a = []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove a = []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
assert.True(t, UIntArrayEquals(d.ReplacedSafebrowsing, a))
</s> add data := &stats.StatsResp{}
req := httptest.NewRequest(http.MethodGet, "/control/stats", nil)
assertSuccessAndUnmarshal(t, data, handlers["/control/stats"], req) </s> remove a = []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
assert.True(t, UIntArrayEquals(d.ReplacedParental, a))
</s> add assert.Equal(t, wantData, data)
}) </s> remove m := d.TopQueried
require.NotEmpty(t, m)
assert.EqualValues(t, 1, m[0]["domain"])
</s> add t.Run("tops", func(t *testing.T) {
topClients := s.TopClientsIP(2)
require.NotEmpty(t, topClients) </s> remove return os.Remove(conf.Filename)
})
s.Update(Entry{
Domain: "domain",
Client: "127.0.0.1",
Result: RFiltered,
Time: 123456,
})
s.Update(Entry{
Domain: "domain",
Client: "127.0.0.1",
Result: RNotFiltered,
Time: 123456,
})
d, ok := s.getData()
require.True(t, ok)
a := []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2}
assert.True(t, UIntArrayEquals(d.DNSQueries, a))
</s> add s.Start()
testutil.CleanupAndRequireSuccess(t, s.Close)
t.Run("data", func(t *testing.T) {
const reqDomain = "domain"
entries := []stats.Entry{{
Domain: reqDomain,
Client: cliIPStr,
Result: stats.RFiltered,
Time: 123456,
}, {
Domain: reqDomain,
Client: cliIPStr,
Result: stats.RNotFiltered,
Time: 123456,
}}
wantData := &stats.StatsResp{
TimeUnits: "hours",
TopQueried: []map[string]uint64{0: {reqDomain: 1}},
TopClients: []map[string]uint64{0: {cliIPStr: 2}},
TopBlocked: []map[string]uint64{0: {reqDomain: 1}},
DNSQueries: []uint64{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
},
BlockedFiltering: []uint64{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
},
ReplacedSafebrowsing: []uint64{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
},
ReplacedParental: []uint64{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
},
NumDNSQueries: 2,
NumBlockedFiltering: 1,
NumReplacedSafebrowsing: 0,
NumReplacedSafesearch: 0,
NumReplacedParental: 0,
AvgProcessingTime: 0.123456,
} </s> remove assert.EqualValues(t, 2, d.NumDNSQueries)
assert.EqualValues(t, 1, d.NumBlockedFiltering)
assert.EqualValues(t, 0, d.NumReplacedSafebrowsing)
assert.EqualValues(t, 0, d.NumReplacedSafesearch)
assert.EqualValues(t, 0, d.NumReplacedParental)
assert.EqualValues(t, 0.123456, d.AvgProcessingTime)
</s> add req = httptest.NewRequest(http.MethodGet, "/control/stats", nil)
data := &stats.StatsResp{} | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats_test.go |
data := &stats.StatsResp{}
req := httptest.NewRequest(http.MethodGet, "/control/stats", nil)
assertSuccessAndUnmarshal(t, data, handlers["/control/stats"], req) | <mask>
<mask> a = []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}
<mask> assert.True(t, UIntArrayEquals(d.BlockedFiltering, a))
<mask>
<mask> a = []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
<mask> assert.True(t, UIntArrayEquals(d.ReplacedSafebrowsing, a))
<mask>
<mask> a = []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
<mask> assert.True(t, UIntArrayEquals(d.ReplacedParental, a))
<mask>
<mask> m := d.TopQueried
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove a = []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
assert.True(t, UIntArrayEquals(d.ReplacedParental, a))
</s> add assert.Equal(t, wantData, data)
}) </s> remove a = []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}
assert.True(t, UIntArrayEquals(d.BlockedFiltering, a))
</s> add for _, e := range entries {
s.Update(e)
} </s> remove m := d.TopQueried
require.NotEmpty(t, m)
assert.EqualValues(t, 1, m[0]["domain"])
</s> add t.Run("tops", func(t *testing.T) {
topClients := s.TopClientsIP(2)
require.NotEmpty(t, topClients) </s> remove return os.Remove(conf.Filename)
})
s.Update(Entry{
Domain: "domain",
Client: "127.0.0.1",
Result: RFiltered,
Time: 123456,
})
s.Update(Entry{
Domain: "domain",
Client: "127.0.0.1",
Result: RNotFiltered,
Time: 123456,
})
d, ok := s.getData()
require.True(t, ok)
a := []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2}
assert.True(t, UIntArrayEquals(d.DNSQueries, a))
</s> add s.Start()
testutil.CleanupAndRequireSuccess(t, s.Close)
t.Run("data", func(t *testing.T) {
const reqDomain = "domain"
entries := []stats.Entry{{
Domain: reqDomain,
Client: cliIPStr,
Result: stats.RFiltered,
Time: 123456,
}, {
Domain: reqDomain,
Client: cliIPStr,
Result: stats.RNotFiltered,
Time: 123456,
}}
wantData := &stats.StatsResp{
TimeUnits: "hours",
TopQueried: []map[string]uint64{0: {reqDomain: 1}},
TopClients: []map[string]uint64{0: {cliIPStr: 2}},
TopBlocked: []map[string]uint64{0: {reqDomain: 1}},
DNSQueries: []uint64{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
},
BlockedFiltering: []uint64{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
},
ReplacedSafebrowsing: []uint64{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
},
ReplacedParental: []uint64{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
},
NumDNSQueries: 2,
NumBlockedFiltering: 1,
NumReplacedSafebrowsing: 0,
NumReplacedSafesearch: 0,
NumReplacedParental: 0,
AvgProcessingTime: 0.123456,
} </s> remove assert.EqualValues(t, 2, d.NumDNSQueries)
assert.EqualValues(t, 1, d.NumBlockedFiltering)
assert.EqualValues(t, 0, d.NumReplacedSafebrowsing)
assert.EqualValues(t, 0, d.NumReplacedSafesearch)
assert.EqualValues(t, 0, d.NumReplacedParental)
assert.EqualValues(t, 0.123456, d.AvgProcessingTime)
</s> add req = httptest.NewRequest(http.MethodGet, "/control/stats", nil)
data := &stats.StatsResp{} | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats_test.go |
assert.Equal(t, wantData, data)
}) | <mask>
<mask> a = []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
<mask> assert.True(t, UIntArrayEquals(d.ReplacedSafebrowsing, a))
<mask>
<mask> a = []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
<mask> assert.True(t, UIntArrayEquals(d.ReplacedParental, a))
<mask>
<mask> m := d.TopQueried
<mask> require.NotEmpty(t, m)
<mask> assert.EqualValues(t, 1, m[0]["domain"])
<mask>
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove m := d.TopQueried
require.NotEmpty(t, m)
assert.EqualValues(t, 1, m[0]["domain"])
</s> add t.Run("tops", func(t *testing.T) {
topClients := s.TopClientsIP(2)
require.NotEmpty(t, topClients) </s> remove a = []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
assert.True(t, UIntArrayEquals(d.ReplacedSafebrowsing, a))
</s> add data := &stats.StatsResp{}
req := httptest.NewRequest(http.MethodGet, "/control/stats", nil)
assertSuccessAndUnmarshal(t, data, handlers["/control/stats"], req) </s> remove a = []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}
assert.True(t, UIntArrayEquals(d.BlockedFiltering, a))
</s> add for _, e := range entries {
s.Update(e)
} </s> remove return os.Remove(conf.Filename)
})
s.Update(Entry{
Domain: "domain",
Client: "127.0.0.1",
Result: RFiltered,
Time: 123456,
})
s.Update(Entry{
Domain: "domain",
Client: "127.0.0.1",
Result: RNotFiltered,
Time: 123456,
})
d, ok := s.getData()
require.True(t, ok)
a := []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2}
assert.True(t, UIntArrayEquals(d.DNSQueries, a))
</s> add s.Start()
testutil.CleanupAndRequireSuccess(t, s.Close)
t.Run("data", func(t *testing.T) {
const reqDomain = "domain"
entries := []stats.Entry{{
Domain: reqDomain,
Client: cliIPStr,
Result: stats.RFiltered,
Time: 123456,
}, {
Domain: reqDomain,
Client: cliIPStr,
Result: stats.RNotFiltered,
Time: 123456,
}}
wantData := &stats.StatsResp{
TimeUnits: "hours",
TopQueried: []map[string]uint64{0: {reqDomain: 1}},
TopClients: []map[string]uint64{0: {cliIPStr: 2}},
TopBlocked: []map[string]uint64{0: {reqDomain: 1}},
DNSQueries: []uint64{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
},
BlockedFiltering: []uint64{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
},
ReplacedSafebrowsing: []uint64{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
},
ReplacedParental: []uint64{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
},
NumDNSQueries: 2,
NumBlockedFiltering: 1,
NumReplacedSafebrowsing: 0,
NumReplacedSafesearch: 0,
NumReplacedParental: 0,
AvgProcessingTime: 0.123456,
} </s> remove assert.EqualValues(t, 2, d.NumDNSQueries)
assert.EqualValues(t, 1, d.NumBlockedFiltering)
assert.EqualValues(t, 0, d.NumReplacedSafebrowsing)
assert.EqualValues(t, 0, d.NumReplacedSafesearch)
assert.EqualValues(t, 0, d.NumReplacedParental)
assert.EqualValues(t, 0.123456, d.AvgProcessingTime)
</s> add req = httptest.NewRequest(http.MethodGet, "/control/stats", nil)
data := &stats.StatsResp{} | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats_test.go |
t.Run("tops", func(t *testing.T) {
topClients := s.TopClientsIP(2)
require.NotEmpty(t, topClients) | <mask>
<mask> a = []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
<mask> assert.True(t, UIntArrayEquals(d.ReplacedParental, a))
<mask>
<mask> m := d.TopQueried
<mask> require.NotEmpty(t, m)
<mask> assert.EqualValues(t, 1, m[0]["domain"])
<mask>
<mask> m = d.TopBlocked
<mask> require.NotEmpty(t, m)
<mask> assert.EqualValues(t, 1, m[0]["domain"])
<mask>
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove a = []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
assert.True(t, UIntArrayEquals(d.ReplacedParental, a))
</s> add assert.Equal(t, wantData, data)
}) </s> remove assert.EqualValues(t, 2, d.NumDNSQueries)
assert.EqualValues(t, 1, d.NumBlockedFiltering)
assert.EqualValues(t, 0, d.NumReplacedSafebrowsing)
assert.EqualValues(t, 0, d.NumReplacedSafesearch)
assert.EqualValues(t, 0, d.NumReplacedParental)
assert.EqualValues(t, 0.123456, d.AvgProcessingTime)
</s> add req = httptest.NewRequest(http.MethodGet, "/control/stats", nil)
data := &stats.StatsResp{} </s> remove a = []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
assert.True(t, UIntArrayEquals(d.ReplacedSafebrowsing, a))
</s> add data := &stats.StatsResp{}
req := httptest.NewRequest(http.MethodGet, "/control/stats", nil)
assertSuccessAndUnmarshal(t, data, handlers["/control/stats"], req) </s> remove m = d.TopClients
require.NotEmpty(t, m)
assert.EqualValues(t, 2, m[0]["127.0.0.1"])
</s> add t.Run("reset", func(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/control/stats_reset", nil)
assertSuccessAndUnmarshal(t, nil, handlers["/control/stats_reset"], req)
_24zeroes := [24]uint64{}
emptyData := &stats.StatsResp{
TimeUnits: "hours",
TopQueried: []map[string]uint64{},
TopClients: []map[string]uint64{},
TopBlocked: []map[string]uint64{},
DNSQueries: _24zeroes[:],
BlockedFiltering: _24zeroes[:],
ReplacedSafebrowsing: _24zeroes[:],
ReplacedParental: _24zeroes[:],
} </s> remove a = []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}
assert.True(t, UIntArrayEquals(d.BlockedFiltering, a))
</s> add for _, e := range entries {
s.Update(e)
} | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats_test.go |
assert.True(t, cliIP.Equal(topClients[0]))
}) | <mask> m := d.TopQueried
<mask> require.NotEmpty(t, m)
<mask> assert.EqualValues(t, 1, m[0]["domain"])
<mask>
<mask> m = d.TopBlocked
<mask> require.NotEmpty(t, m)
<mask> assert.EqualValues(t, 1, m[0]["domain"])
<mask>
<mask> m = d.TopClients
<mask> require.NotEmpty(t, m)
<mask> assert.EqualValues(t, 2, m[0]["127.0.0.1"])
<mask>
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove m = d.TopClients
require.NotEmpty(t, m)
assert.EqualValues(t, 2, m[0]["127.0.0.1"])
</s> add t.Run("reset", func(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/control/stats_reset", nil)
assertSuccessAndUnmarshal(t, nil, handlers["/control/stats_reset"], req)
_24zeroes := [24]uint64{}
emptyData := &stats.StatsResp{
TimeUnits: "hours",
TopQueried: []map[string]uint64{},
TopClients: []map[string]uint64{},
TopBlocked: []map[string]uint64{},
DNSQueries: _24zeroes[:],
BlockedFiltering: _24zeroes[:],
ReplacedSafebrowsing: _24zeroes[:],
ReplacedParental: _24zeroes[:],
} </s> remove m := d.TopQueried
require.NotEmpty(t, m)
assert.EqualValues(t, 1, m[0]["domain"])
</s> add t.Run("tops", func(t *testing.T) {
topClients := s.TopClientsIP(2)
require.NotEmpty(t, topClients) </s> remove assert.EqualValues(t, 2, d.NumDNSQueries)
assert.EqualValues(t, 1, d.NumBlockedFiltering)
assert.EqualValues(t, 0, d.NumReplacedSafebrowsing)
assert.EqualValues(t, 0, d.NumReplacedSafesearch)
assert.EqualValues(t, 0, d.NumReplacedParental)
assert.EqualValues(t, 0.123456, d.AvgProcessingTime)
</s> add req = httptest.NewRequest(http.MethodGet, "/control/stats", nil)
data := &stats.StatsResp{} </s> remove a = []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
assert.True(t, UIntArrayEquals(d.ReplacedParental, a))
</s> add assert.Equal(t, wantData, data)
}) </s> remove topClients := s.GetTopClientsIP(2)
require.NotEmpty(t, topClients)
assert.True(t, net.IP{127, 0, 0, 1}.Equal(topClients[0]))
</s> add assertSuccessAndUnmarshal(t, data, handlers["/control/stats"], req)
assert.Equal(t, emptyData, data)
}) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats_test.go |
t.Run("reset", func(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/control/stats_reset", nil)
assertSuccessAndUnmarshal(t, nil, handlers["/control/stats_reset"], req)
_24zeroes := [24]uint64{}
emptyData := &stats.StatsResp{
TimeUnits: "hours",
TopQueried: []map[string]uint64{},
TopClients: []map[string]uint64{},
TopBlocked: []map[string]uint64{},
DNSQueries: _24zeroes[:],
BlockedFiltering: _24zeroes[:],
ReplacedSafebrowsing: _24zeroes[:],
ReplacedParental: _24zeroes[:],
} | <mask> m = d.TopBlocked
<mask> require.NotEmpty(t, m)
<mask> assert.EqualValues(t, 1, m[0]["domain"])
<mask>
<mask> m = d.TopClients
<mask> require.NotEmpty(t, m)
<mask> assert.EqualValues(t, 2, m[0]["127.0.0.1"])
<mask>
<mask> assert.EqualValues(t, 2, d.NumDNSQueries)
<mask> assert.EqualValues(t, 1, d.NumBlockedFiltering)
<mask> assert.EqualValues(t, 0, d.NumReplacedSafebrowsing)
<mask> assert.EqualValues(t, 0, d.NumReplacedSafesearch)
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove assert.EqualValues(t, 2, d.NumDNSQueries)
assert.EqualValues(t, 1, d.NumBlockedFiltering)
assert.EqualValues(t, 0, d.NumReplacedSafebrowsing)
assert.EqualValues(t, 0, d.NumReplacedSafesearch)
assert.EqualValues(t, 0, d.NumReplacedParental)
assert.EqualValues(t, 0.123456, d.AvgProcessingTime)
</s> add req = httptest.NewRequest(http.MethodGet, "/control/stats", nil)
data := &stats.StatsResp{} </s> remove m = d.TopBlocked
require.NotEmpty(t, m)
assert.EqualValues(t, 1, m[0]["domain"])
</s> add assert.True(t, cliIP.Equal(topClients[0]))
}) </s> remove m := d.TopQueried
require.NotEmpty(t, m)
assert.EqualValues(t, 1, m[0]["domain"])
</s> add t.Run("tops", func(t *testing.T) {
topClients := s.TopClientsIP(2)
require.NotEmpty(t, topClients) </s> remove a = []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
assert.True(t, UIntArrayEquals(d.ReplacedParental, a))
</s> add assert.Equal(t, wantData, data)
}) </s> remove topClients := s.GetTopClientsIP(2)
require.NotEmpty(t, topClients)
assert.True(t, net.IP{127, 0, 0, 1}.Equal(topClients[0]))
</s> add assertSuccessAndUnmarshal(t, data, handlers["/control/stats"], req)
assert.Equal(t, emptyData, data)
}) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats_test.go |
req = httptest.NewRequest(http.MethodGet, "/control/stats", nil)
data := &stats.StatsResp{} | <mask> m = d.TopClients
<mask> require.NotEmpty(t, m)
<mask> assert.EqualValues(t, 2, m[0]["127.0.0.1"])
<mask>
<mask> assert.EqualValues(t, 2, d.NumDNSQueries)
<mask> assert.EqualValues(t, 1, d.NumBlockedFiltering)
<mask> assert.EqualValues(t, 0, d.NumReplacedSafebrowsing)
<mask> assert.EqualValues(t, 0, d.NumReplacedSafesearch)
<mask> assert.EqualValues(t, 0, d.NumReplacedParental)
<mask> assert.EqualValues(t, 0.123456, d.AvgProcessingTime)
<mask>
<mask> topClients := s.GetTopClientsIP(2)
<mask> require.NotEmpty(t, topClients)
<mask> assert.True(t, net.IP{127, 0, 0, 1}.Equal(topClients[0]))
<mask> }
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove m = d.TopClients
require.NotEmpty(t, m)
assert.EqualValues(t, 2, m[0]["127.0.0.1"])
</s> add t.Run("reset", func(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/control/stats_reset", nil)
assertSuccessAndUnmarshal(t, nil, handlers["/control/stats_reset"], req)
_24zeroes := [24]uint64{}
emptyData := &stats.StatsResp{
TimeUnits: "hours",
TopQueried: []map[string]uint64{},
TopClients: []map[string]uint64{},
TopBlocked: []map[string]uint64{},
DNSQueries: _24zeroes[:],
BlockedFiltering: _24zeroes[:],
ReplacedSafebrowsing: _24zeroes[:],
ReplacedParental: _24zeroes[:],
} </s> remove topClients := s.GetTopClientsIP(2)
require.NotEmpty(t, topClients)
assert.True(t, net.IP{127, 0, 0, 1}.Equal(topClients[0]))
</s> add assertSuccessAndUnmarshal(t, data, handlers["/control/stats"], req)
assert.Equal(t, emptyData, data)
}) </s> remove m = d.TopBlocked
require.NotEmpty(t, m)
assert.EqualValues(t, 1, m[0]["domain"])
</s> add assert.True(t, cliIP.Equal(topClients[0]))
}) </s> remove m := d.TopQueried
require.NotEmpty(t, m)
assert.EqualValues(t, 1, m[0]["domain"])
</s> add t.Run("tops", func(t *testing.T) {
topClients := s.TopClientsIP(2)
require.NotEmpty(t, topClients) </s> remove a = []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
assert.True(t, UIntArrayEquals(d.ReplacedParental, a))
</s> add assert.Equal(t, wantData, data)
}) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats_test.go |
assertSuccessAndUnmarshal(t, data, handlers["/control/stats"], req)
assert.Equal(t, emptyData, data)
}) | <mask> assert.EqualValues(t, 0, d.NumReplacedSafesearch)
<mask> assert.EqualValues(t, 0, d.NumReplacedParental)
<mask> assert.EqualValues(t, 0.123456, d.AvgProcessingTime)
<mask>
<mask> topClients := s.GetTopClientsIP(2)
<mask> require.NotEmpty(t, topClients)
<mask> assert.True(t, net.IP{127, 0, 0, 1}.Equal(topClients[0]))
<mask> }
<mask>
<mask> func TestLargeNumbers(t *testing.T) {
<mask> var hour int32 = 0
<mask> newID := func() uint32 {
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove assert.EqualValues(t, 2, d.NumDNSQueries)
assert.EqualValues(t, 1, d.NumBlockedFiltering)
assert.EqualValues(t, 0, d.NumReplacedSafebrowsing)
assert.EqualValues(t, 0, d.NumReplacedSafesearch)
assert.EqualValues(t, 0, d.NumReplacedParental)
assert.EqualValues(t, 0.123456, d.AvgProcessingTime)
</s> add req = httptest.NewRequest(http.MethodGet, "/control/stats", nil)
data := &stats.StatsResp{} </s> remove var hour int32 = 0
newID := func() uint32 {
// Use "atomic" to make go race detector happy.
return uint32(atomic.LoadInt32(&hour))
</s> add var curHour uint32 = 1
handlers := map[string]http.Handler{}
conf := stats.Config{
Filename: filepath.Join(t.TempDir(), "stats.db"),
LimitDays: 1,
UnitID: func() (id uint32) { return atomic.LoadUint32(&curHour) },
HTTPRegister: func(_, url string, handler http.HandlerFunc) { handlers[url] = handler }, </s> remove m := d.TopQueried
require.NotEmpty(t, m)
assert.EqualValues(t, 1, m[0]["domain"])
</s> add t.Run("tops", func(t *testing.T) {
topClients := s.TopClientsIP(2)
require.NotEmpty(t, topClients) </s> remove m = d.TopClients
require.NotEmpty(t, m)
assert.EqualValues(t, 2, m[0]["127.0.0.1"])
</s> add t.Run("reset", func(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/control/stats_reset", nil)
assertSuccessAndUnmarshal(t, nil, handlers["/control/stats_reset"], req)
_24zeroes := [24]uint64{}
emptyData := &stats.StatsResp{
TimeUnits: "hours",
TopQueried: []map[string]uint64{},
TopClients: []map[string]uint64{},
TopBlocked: []map[string]uint64{},
DNSQueries: _24zeroes[:],
BlockedFiltering: _24zeroes[:],
ReplacedSafebrowsing: _24zeroes[:],
ReplacedParental: _24zeroes[:],
} </s> remove d, ok := s.getData()
require.True(t, ok)
assert.EqualValues(t, hour*n, d.NumDNSQueries)
}
func TestStatsCollector(t *testing.T) {
ng := func(_ *unitDB) uint64 {
return 0
}
units := make([]*unitDB, 720)
</s> add req := httptest.NewRequest(http.MethodGet, "/control/stats", nil) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats_test.go |
var curHour uint32 = 1
handlers := map[string]http.Handler{}
conf := stats.Config{
Filename: filepath.Join(t.TempDir(), "stats.db"),
LimitDays: 1,
UnitID: func() (id uint32) { return atomic.LoadUint32(&curHour) },
HTTPRegister: func(_, url string, handler http.HandlerFunc) { handlers[url] = handler }, | <mask> assert.True(t, net.IP{127, 0, 0, 1}.Equal(topClients[0]))
<mask> }
<mask>
<mask> func TestLargeNumbers(t *testing.T) {
<mask> var hour int32 = 0
<mask> newID := func() uint32 {
<mask> // Use "atomic" to make go race detector happy.
<mask> return uint32(atomic.LoadInt32(&hour))
<mask> }
<mask>
<mask> conf := Config{
<mask> Filename: "./stats.db",
<mask> LimitDays: 1,
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove conf := Config{
Filename: "./stats.db",
LimitDays: 1,
UnitID: newID,
}
s, err := New(conf)
</s> add s, err := stats.New(conf) </s> remove topClients := s.GetTopClientsIP(2)
require.NotEmpty(t, topClients)
assert.True(t, net.IP{127, 0, 0, 1}.Equal(topClients[0]))
</s> add assertSuccessAndUnmarshal(t, data, handlers["/control/stats"], req)
assert.Equal(t, emptyData, data)
}) </s> remove conf := Config{
Filename: "./stats.db",
</s> add cliIP := net.IP{127, 0, 0, 1}
cliIPStr := cliIP.String()
handlers := map[string]http.Handler{}
conf := stats.Config{
Filename: filepath.Join(t.TempDir(), "stats.db"), </s> remove return true
</s> add err := json.Unmarshal(data, to)
require.NoError(t, err) </s> remove s, err := New(conf)
</s> add s, err := stats.New(conf) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats_test.go |
s, err := stats.New(conf) | <mask> // Use "atomic" to make go race detector happy.
<mask> return uint32(atomic.LoadInt32(&hour))
<mask> }
<mask>
<mask> conf := Config{
<mask> Filename: "./stats.db",
<mask> LimitDays: 1,
<mask> UnitID: newID,
<mask> }
<mask> s, err := New(conf)
<mask> require.NoError(t, err)
<mask> testutil.CleanupAndRequireSuccess(t, func() (err error) {
<mask> s.Close()
<mask>
<mask> return os.Remove(conf.Filename)
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove var hour int32 = 0
newID := func() uint32 {
// Use "atomic" to make go race detector happy.
return uint32(atomic.LoadInt32(&hour))
</s> add var curHour uint32 = 1
handlers := map[string]http.Handler{}
conf := stats.Config{
Filename: filepath.Join(t.TempDir(), "stats.db"),
LimitDays: 1,
UnitID: func() (id uint32) { return atomic.LoadUint32(&curHour) },
HTTPRegister: func(_, url string, handler http.HandlerFunc) { handlers[url] = handler }, </s> remove s, err := New(conf)
</s> add s, err := stats.New(conf) </s> remove testutil.CleanupAndRequireSuccess(t, func() (err error) {
s.Close()
</s> add </s> remove conf := Config{
Filename: "./stats.db",
</s> add cliIP := net.IP{127, 0, 0, 1}
cliIPStr := cliIP.String()
handlers := map[string]http.Handler{}
conf := stats.Config{
Filename: filepath.Join(t.TempDir(), "stats.db"), </s> remove testutil.CleanupAndRequireSuccess(t, func() (err error) {
s.clear()
s.Close()
</s> add | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats_test.go |
<mask> UnitID: newID,
<mask> }
<mask> s, err := New(conf)
<mask> require.NoError(t, err)
<mask> testutil.CleanupAndRequireSuccess(t, func() (err error) {
<mask> s.Close()
<mask>
<mask> return os.Remove(conf.Filename)
<mask> })
<mask>
<mask> // Number of distinct clients and domains every hour.
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove return os.Remove(conf.Filename)
})
</s> add s.Start()
testutil.CleanupAndRequireSuccess(t, s.Close) </s> remove conf := Config{
Filename: "./stats.db",
LimitDays: 1,
UnitID: newID,
}
s, err := New(conf)
</s> add s, err := stats.New(conf) </s> remove testutil.CleanupAndRequireSuccess(t, func() (err error) {
s.clear()
s.Close()
</s> add </s> remove s, err := New(conf)
</s> add s, err := stats.New(conf) </s> remove // Number of distinct clients and domains every hour.
const n = 1000
for h := 0; h < 12; h++ {
atomic.AddInt32(&hour, 1)
for i := 0; i < n; i++ {
s.Update(Entry{
Domain: fmt.Sprintf("domain%d", i),
Client: net.IP{
127,
0,
byte((i & 0xff00) >> 8),
byte(i & 0xff),
}.String(),
Result: RNotFiltered,
Time: 123456,
})
}
}
</s> add const (
hoursNum = 12
cliNumPerHour = 1000
) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats_test.go |
|
s.Start()
testutil.CleanupAndRequireSuccess(t, s.Close) | <mask> require.NoError(t, err)
<mask> testutil.CleanupAndRequireSuccess(t, func() (err error) {
<mask> s.Close()
<mask>
<mask> return os.Remove(conf.Filename)
<mask> })
<mask>
<mask> // Number of distinct clients and domains every hour.
<mask> const n = 1000
<mask>
<mask> for h := 0; h < 12; h++ {
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove // Number of distinct clients and domains every hour.
const n = 1000
for h := 0; h < 12; h++ {
atomic.AddInt32(&hour, 1)
for i := 0; i < n; i++ {
s.Update(Entry{
Domain: fmt.Sprintf("domain%d", i),
Client: net.IP{
127,
0,
byte((i & 0xff00) >> 8),
byte(i & 0xff),
}.String(),
Result: RNotFiltered,
Time: 123456,
})
}
}
</s> add const (
hoursNum = 12
cliNumPerHour = 1000
) </s> remove testutil.CleanupAndRequireSuccess(t, func() (err error) {
s.Close()
</s> add </s> remove testutil.CleanupAndRequireSuccess(t, func() (err error) {
s.clear()
s.Close()
</s> add </s> remove t.Run("hours", func(t *testing.T) {
statsData := statsCollector(units, 0, Hours, ng)
assert.Len(t, statsData, 720)
})
</s> add for h := 0; h < hoursNum; h++ {
atomic.AddUint32(&curHour, 1) </s> remove conf := Config{
Filename: "./stats.db",
LimitDays: 1,
UnitID: newID,
}
s, err := New(conf)
</s> add s, err := stats.New(conf) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats_test.go |
const (
hoursNum = 12
cliNumPerHour = 1000
) | <mask>
<mask> return os.Remove(conf.Filename)
<mask> })
<mask>
<mask> // Number of distinct clients and domains every hour.
<mask> const n = 1000
<mask>
<mask> for h := 0; h < 12; h++ {
<mask> atomic.AddInt32(&hour, 1)
<mask> for i := 0; i < n; i++ {
<mask> s.Update(Entry{
<mask> Domain: fmt.Sprintf("domain%d", i),
<mask> Client: net.IP{
<mask> 127,
<mask> 0,
<mask> byte((i & 0xff00) >> 8),
<mask> byte(i & 0xff),
<mask> }.String(),
<mask> Result: RNotFiltered,
<mask> Time: 123456,
<mask> })
<mask> }
<mask> }
<mask>
<mask> d, ok := s.getData()
<mask> require.True(t, ok)
<mask> assert.EqualValues(t, hour*n, d.NumDNSQueries)
<mask> }
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove t.Run("days", func(t *testing.T) {
for i := 0; i != 25; i++ {
statsData := statsCollector(units, uint32(i), Days, ng)
require.Lenf(t, statsData, 30, "i=%d", i)
</s> add for i := 0; i < cliNumPerHour; i++ {
ip := net.IP{127, 0, byte((i & 0xff00) >> 8), byte(i & 0xff)}
e := stats.Entry{
Domain: fmt.Sprintf("domain%d.hour%d", i, h),
Client: ip.String(),
Result: stats.RNotFiltered,
Time: 123456,
}
s.Update(e) </s> remove return os.Remove(conf.Filename)
})
</s> add s.Start()
testutil.CleanupAndRequireSuccess(t, s.Close) </s> remove t.Run("hours", func(t *testing.T) {
statsData := statsCollector(units, 0, Hours, ng)
assert.Len(t, statsData, 720)
})
</s> add for h := 0; h < hoursNum; h++ {
atomic.AddUint32(&curHour, 1) </s> remove d, ok := s.getData()
require.True(t, ok)
assert.EqualValues(t, hour*n, d.NumDNSQueries)
}
func TestStatsCollector(t *testing.T) {
ng := func(_ *unitDB) uint64 {
return 0
}
units := make([]*unitDB, 720)
</s> add req := httptest.NewRequest(http.MethodGet, "/control/stats", nil) </s> remove testutil.CleanupAndRequireSuccess(t, func() (err error) {
s.Close()
</s> add | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats_test.go |
req := httptest.NewRequest(http.MethodGet, "/control/stats", nil) | <mask> })
<mask> }
<mask> }
<mask>
<mask> d, ok := s.getData()
<mask> require.True(t, ok)
<mask> assert.EqualValues(t, hour*n, d.NumDNSQueries)
<mask> }
<mask>
<mask> func TestStatsCollector(t *testing.T) {
<mask> ng := func(_ *unitDB) uint64 {
<mask> return 0
<mask> }
<mask> units := make([]*unitDB, 720)
<mask>
<mask> t.Run("hours", func(t *testing.T) {
<mask> statsData := statsCollector(units, 0, Hours, ng)
<mask> assert.Len(t, statsData, 720)
<mask> })
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove t.Run("hours", func(t *testing.T) {
statsData := statsCollector(units, 0, Hours, ng)
assert.Len(t, statsData, 720)
})
</s> add for h := 0; h < hoursNum; h++ {
atomic.AddUint32(&curHour, 1) </s> remove t.Run("days", func(t *testing.T) {
for i := 0; i != 25; i++ {
statsData := statsCollector(units, uint32(i), Days, ng)
require.Lenf(t, statsData, 30, "i=%d", i)
</s> add for i := 0; i < cliNumPerHour; i++ {
ip := net.IP{127, 0, byte((i & 0xff00) >> 8), byte(i & 0xff)}
e := stats.Entry{
Domain: fmt.Sprintf("domain%d.hour%d", i, h),
Client: ip.String(),
Result: stats.RNotFiltered,
Time: 123456,
}
s.Update(e) </s> remove // Number of distinct clients and domains every hour.
const n = 1000
for h := 0; h < 12; h++ {
atomic.AddInt32(&hour, 1)
for i := 0; i < n; i++ {
s.Update(Entry{
Domain: fmt.Sprintf("domain%d", i),
Client: net.IP{
127,
0,
byte((i & 0xff00) >> 8),
byte(i & 0xff),
}.String(),
Result: RNotFiltered,
Time: 123456,
})
}
}
</s> add const (
hoursNum = 12
cliNumPerHour = 1000
) </s> remove })
</s> add }
data := &stats.StatsResp{}
assertSuccessAndUnmarshal(t, data, handlers["/control/stats"], req)
assert.Equal(t, hoursNum*cliNumPerHour, int(data.NumDNSQueries)) </s> remove topClients := s.GetTopClientsIP(2)
require.NotEmpty(t, topClients)
assert.True(t, net.IP{127, 0, 0, 1}.Equal(topClients[0]))
</s> add assertSuccessAndUnmarshal(t, data, handlers["/control/stats"], req)
assert.Equal(t, emptyData, data)
}) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats_test.go |
for h := 0; h < hoursNum; h++ {
atomic.AddUint32(&curHour, 1) | <mask> return 0
<mask> }
<mask> units := make([]*unitDB, 720)
<mask>
<mask> t.Run("hours", func(t *testing.T) {
<mask> statsData := statsCollector(units, 0, Hours, ng)
<mask> assert.Len(t, statsData, 720)
<mask> })
<mask>
<mask> t.Run("days", func(t *testing.T) {
<mask> for i := 0; i != 25; i++ {
<mask> statsData := statsCollector(units, uint32(i), Days, ng)
<mask> require.Lenf(t, statsData, 30, "i=%d", i)
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove t.Run("days", func(t *testing.T) {
for i := 0; i != 25; i++ {
statsData := statsCollector(units, uint32(i), Days, ng)
require.Lenf(t, statsData, 30, "i=%d", i)
</s> add for i := 0; i < cliNumPerHour; i++ {
ip := net.IP{127, 0, byte((i & 0xff00) >> 8), byte(i & 0xff)}
e := stats.Entry{
Domain: fmt.Sprintf("domain%d.hour%d", i, h),
Client: ip.String(),
Result: stats.RNotFiltered,
Time: 123456,
}
s.Update(e) </s> remove })
</s> add }
data := &stats.StatsResp{}
assertSuccessAndUnmarshal(t, data, handlers["/control/stats"], req)
assert.Equal(t, hoursNum*cliNumPerHour, int(data.NumDNSQueries)) </s> remove d, ok := s.getData()
require.True(t, ok)
assert.EqualValues(t, hour*n, d.NumDNSQueries)
}
func TestStatsCollector(t *testing.T) {
ng := func(_ *unitDB) uint64 {
return 0
}
units := make([]*unitDB, 720)
</s> add req := httptest.NewRequest(http.MethodGet, "/control/stats", nil) </s> remove // Number of distinct clients and domains every hour.
const n = 1000
for h := 0; h < 12; h++ {
atomic.AddInt32(&hour, 1)
for i := 0; i < n; i++ {
s.Update(Entry{
Domain: fmt.Sprintf("domain%d", i),
Client: net.IP{
127,
0,
byte((i & 0xff00) >> 8),
byte(i & 0xff),
}.String(),
Result: RNotFiltered,
Time: 123456,
})
}
}
</s> add const (
hoursNum = 12
cliNumPerHour = 1000
) </s> remove return statsResponse{}, false
</s> add return StatsResp{}, false | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats_test.go |
for i := 0; i < cliNumPerHour; i++ {
ip := net.IP{127, 0, byte((i & 0xff00) >> 8), byte(i & 0xff)}
e := stats.Entry{
Domain: fmt.Sprintf("domain%d.hour%d", i, h),
Client: ip.String(),
Result: stats.RNotFiltered,
Time: 123456,
}
s.Update(e) | <mask> statsData := statsCollector(units, 0, Hours, ng)
<mask> assert.Len(t, statsData, 720)
<mask> })
<mask>
<mask> t.Run("days", func(t *testing.T) {
<mask> for i := 0; i != 25; i++ {
<mask> statsData := statsCollector(units, uint32(i), Days, ng)
<mask> require.Lenf(t, statsData, 30, "i=%d", i)
<mask> }
<mask> })
<mask> }
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove t.Run("hours", func(t *testing.T) {
statsData := statsCollector(units, 0, Hours, ng)
assert.Len(t, statsData, 720)
})
</s> add for h := 0; h < hoursNum; h++ {
atomic.AddUint32(&curHour, 1) </s> remove })
</s> add }
data := &stats.StatsResp{}
assertSuccessAndUnmarshal(t, data, handlers["/control/stats"], req)
assert.Equal(t, hoursNum*cliNumPerHour, int(data.NumDNSQueries)) </s> remove d, ok := s.getData()
require.True(t, ok)
assert.EqualValues(t, hour*n, d.NumDNSQueries)
}
func TestStatsCollector(t *testing.T) {
ng := func(_ *unitDB) uint64 {
return 0
}
units := make([]*unitDB, 720)
</s> add req := httptest.NewRequest(http.MethodGet, "/control/stats", nil) </s> remove // Number of distinct clients and domains every hour.
const n = 1000
for h := 0; h < 12; h++ {
atomic.AddInt32(&hour, 1)
for i := 0; i < n; i++ {
s.Update(Entry{
Domain: fmt.Sprintf("domain%d", i),
Client: net.IP{
127,
0,
byte((i & 0xff00) >> 8),
byte(i & 0xff),
}.String(),
Result: RNotFiltered,
Time: 123456,
})
}
}
</s> add const (
hoursNum = 12
cliNumPerHour = 1000
) </s> remove return statsResponse{}, false
</s> add return StatsResp{}, false | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats_test.go |
}
data := &stats.StatsResp{}
assertSuccessAndUnmarshal(t, data, handlers["/control/stats"], req)
assert.Equal(t, hoursNum*cliNumPerHour, int(data.NumDNSQueries)) | <mask> for i := 0; i != 25; i++ {
<mask> statsData := statsCollector(units, uint32(i), Days, ng)
<mask> require.Lenf(t, statsData, 30, "i=%d", i)
<mask> }
<mask> })
<mask> }
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove t.Run("hours", func(t *testing.T) {
statsData := statsCollector(units, 0, Hours, ng)
assert.Len(t, statsData, 720)
})
</s> add for h := 0; h < hoursNum; h++ {
atomic.AddUint32(&curHour, 1) </s> remove t.Run("days", func(t *testing.T) {
for i := 0; i != 25; i++ {
statsData := statsCollector(units, uint32(i), Days, ng)
require.Lenf(t, statsData, 30, "i=%d", i)
</s> add for i := 0; i < cliNumPerHour; i++ {
ip := net.IP{127, 0, byte((i & 0xff00) >> 8), byte(i & 0xff)}
e := stats.Entry{
Domain: fmt.Sprintf("domain%d.hour%d", i, h),
Client: ip.String(),
Result: stats.RNotFiltered,
Time: 123456,
}
s.Update(e) </s> remove d, ok := s.getData()
require.True(t, ok)
assert.EqualValues(t, hour*n, d.NumDNSQueries)
}
func TestStatsCollector(t *testing.T) {
ng := func(_ *unitDB) uint64 {
return 0
}
units := make([]*unitDB, 720)
</s> add req := httptest.NewRequest(http.MethodGet, "/control/stats", nil) </s> remove // Number of distinct clients and domains every hour.
const n = 1000
for h := 0; h < 12; h++ {
atomic.AddInt32(&hour, 1)
for i := 0; i < n; i++ {
s.Update(Entry{
Domain: fmt.Sprintf("domain%d", i),
Client: net.IP{
127,
0,
byte((i & 0xff00) >> 8),
byte(i & 0xff),
}.String(),
Result: RNotFiltered,
Time: 123456,
})
}
}
</s> add const (
hoursNum = 12
cliNumPerHour = 1000
) </s> remove for i := range a {
if a[i] != b[i] {
return false
}
</s> add func assertSuccessAndUnmarshal(t *testing.T, to any, handler http.Handler, req *http.Request) {
t.Helper()
require.NotNil(t, handler)
rw := httptest.NewRecorder()
handler.ServeHTTP(rw, req)
require.Equal(t, http.StatusOK, rw.Code)
data := rw.Body.Bytes()
if to == nil {
assert.Empty(t, data)
return | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/stats_test.go |
<mask> "bytes"
<mask> "encoding/binary"
<mask> "encoding/gob"
<mask> "fmt"
<mask> "net"
<mask> "os"
<mask> "sort"
<mask> "sync"
<mask> "sync/atomic"
<mask> "time"
<mask>
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove "sync"
"sync/atomic"
</s> add </s> remove "os"
</s> add "net/http"
"net/http/httptest"
"path/filepath" </s> remove "github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
</s> add | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
|
<mask> "fmt"
<mask> "net"
<mask> "os"
<mask> "sort"
<mask> "sync"
<mask> "sync/atomic"
<mask> "time"
<mask>
<mask> "github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
<mask> "github.com/AdguardTeam/golibs/errors"
<mask> "github.com/AdguardTeam/golibs/log"
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove "net"
"os"
</s> add </s> remove "github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
</s> add | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
|
<mask> "sync"
<mask> "sync/atomic"
<mask> "time"
<mask>
<mask> "github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
<mask> "github.com/AdguardTeam/golibs/errors"
<mask> "github.com/AdguardTeam/golibs/log"
<mask> "go.etcd.io/bbolt"
<mask> )
<mask>
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove "sync"
"sync/atomic"
</s> add </s> remove "net"
"os"
</s> add | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
|
// maxDomains is the max number of top domains to return.
maxDomains = 100
// maxClients is the max number of top clients to return.
maxClients = 100 | <mask> // TODO(a.garipov): Rewrite all of this. Add proper error handling and
<mask> // inspection. Improve logging. Decrease complexity.
<mask>
<mask> const (
<mask> maxDomains = 100 // max number of top domains to store in file or return via Get()
<mask> maxClients = 100 // max number of top clients to store in file or return via Get()
<mask> )
<mask>
<mask> // StatsCtx collects the statistics and flushes it to the database. Its default
<mask> // flushing interval is one hour.
<mask> //
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove // StatsCtx collects the statistics and flushes it to the database. Its default
// flushing interval is one hour.
</s> add // UnitIDGenFunc is the signature of a function that generates a unique ID for
// the statistics unit.
type UnitIDGenFunc func() (id uint32)
// TimeUnit is the unit of measuring time while aggregating the statistics.
type TimeUnit int
// Supported TimeUnit values.
const (
Hours TimeUnit = iota
Days
)
// Result is the resulting code of processing the DNS request.
type Result int
// Supported Result values. </s> remove // TimeUnit is the unit of measuring time while aggregating the statistics.
type TimeUnit int
</s> add // StatsCtx collects the statistics and flushes it to the database. Its default
// flushing interval is one hour.
//
// TODO(e.burkov): Use atomic.Pointer for accessing db in go1.19.
type StatsCtx struct {
// limitHours is the maximum number of hours to collect statistics into the
// current unit.
//
// It is of type uint32 to be accessed by atomic. It's arranged at the
// beginning of the structure to keep 64-bit alignment.
limitHours uint32 </s> remove // TODO(e.burkov): Use atomic.Pointer for accessing curr and db in go1.19.
type StatsCtx struct {
// currMu protects the current unit.
currMu *sync.Mutex
// curr is the actual statistics collection result.
curr *unit
// dbMu protects db.
dbMu *sync.Mutex
// db is the opened statistics database, if any.
db *bbolt.DB
// unitIDGen is the function that generates an identifier for the current
// unit. It's here for only testing purposes.
unitIDGen UnitIDGenFunc
// httpRegister is used to set HTTP handlers.
httpRegister aghhttp.RegisterFunc
// configModified is called whenever the configuration is modified via web
// interface.
configModified func()
// filename is the name of database file.
filename string
// limitHours is the maximum number of hours to collect statistics into the
// current unit.
limitHours uint32
</s> add // TODO(e.burkov): Think about better naming.
const (
RNotFiltered Result = iota + 1
RFiltered
RSafeBrowsing
RSafeSearch
RParental
resultLast = RParental + 1
)
// Entry is a statistics data entry.
type Entry struct {
// Clients is the client's primary ID.
//
// TODO(a.garipov): Make this a {net.IP, string} enum?
Client string
// Domain is the domain name requested.
Domain string
// Result is the result of processing the request.
Result Result
// Time is the duration of the request processing in milliseconds.
Time uint32 </s> remove // UnitIDGenFunc is the signature of a function that generates a unique ID for
// the statistics unit.
type UnitIDGenFunc func() (id uint32)
</s> add </s> remove // mu protects all the fields of a unit.
mu *sync.RWMutex
</s> add | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
// UnitIDGenFunc is the signature of a function that generates a unique ID for
// the statistics unit.
type UnitIDGenFunc func() (id uint32)
// TimeUnit is the unit of measuring time while aggregating the statistics.
type TimeUnit int
// Supported TimeUnit values.
const (
Hours TimeUnit = iota
Days
)
// Result is the resulting code of processing the DNS request.
type Result int
// Supported Result values. | <mask> maxDomains = 100 // max number of top domains to store in file or return via Get()
<mask> maxClients = 100 // max number of top clients to store in file or return via Get()
<mask> )
<mask>
<mask> // StatsCtx collects the statistics and flushes it to the database. Its default
<mask> // flushing interval is one hour.
<mask> //
<mask> // TODO(e.burkov): Use atomic.Pointer for accessing curr and db in go1.19.
<mask> type StatsCtx struct {
<mask> // currMu protects the current unit.
<mask> currMu *sync.Mutex
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove maxDomains = 100 // max number of top domains to store in file or return via Get()
maxClients = 100 // max number of top clients to store in file or return via Get()
</s> add // maxDomains is the max number of top domains to return.
maxDomains = 100
// maxClients is the max number of top clients to return.
maxClients = 100 </s> remove // TODO(e.burkov): Use atomic.Pointer for accessing curr and db in go1.19.
type StatsCtx struct {
// currMu protects the current unit.
currMu *sync.Mutex
// curr is the actual statistics collection result.
curr *unit
// dbMu protects db.
dbMu *sync.Mutex
// db is the opened statistics database, if any.
db *bbolt.DB
// unitIDGen is the function that generates an identifier for the current
// unit. It's here for only testing purposes.
unitIDGen UnitIDGenFunc
// httpRegister is used to set HTTP handlers.
httpRegister aghhttp.RegisterFunc
// configModified is called whenever the configuration is modified via web
// interface.
configModified func()
// filename is the name of database file.
filename string
// limitHours is the maximum number of hours to collect statistics into the
// current unit.
limitHours uint32
</s> add // TODO(e.burkov): Think about better naming.
const (
RNotFiltered Result = iota + 1
RFiltered
RSafeBrowsing
RSafeSearch
RParental
resultLast = RParental + 1
)
// Entry is a statistics data entry.
type Entry struct {
// Clients is the client's primary ID.
//
// TODO(a.garipov): Make this a {net.IP, string} enum?
Client string
// Domain is the domain name requested.
Domain string
// Result is the result of processing the request.
Result Result
// Time is the duration of the request processing in milliseconds.
Time uint32 </s> remove // TimeUnit is the unit of measuring time while aggregating the statistics.
type TimeUnit int
</s> add // StatsCtx collects the statistics and flushes it to the database. Its default
// flushing interval is one hour.
//
// TODO(e.burkov): Use atomic.Pointer for accessing db in go1.19.
type StatsCtx struct {
// limitHours is the maximum number of hours to collect statistics into the
// current unit.
//
// It is of type uint32 to be accessed by atomic. It's arranged at the
// beginning of the structure to keep 64-bit alignment.
limitHours uint32 </s> remove // UnitIDGenFunc is the signature of a function that generates a unique ID for
// the statistics unit.
type UnitIDGenFunc func() (id uint32)
</s> add </s> remove // Supported TimeUnit values.
const (
Hours TimeUnit = iota
Days
)
</s> add // currMu protects curr.
currMu *sync.RWMutex
// curr is the actual statistics collection result.
curr *unit | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
// TODO(e.burkov): Think about better naming.
const (
RNotFiltered Result = iota + 1
RFiltered
RSafeBrowsing
RSafeSearch
RParental
resultLast = RParental + 1
)
// Entry is a statistics data entry.
type Entry struct {
// Clients is the client's primary ID.
//
// TODO(a.garipov): Make this a {net.IP, string} enum?
Client string
// Domain is the domain name requested.
Domain string
// Result is the result of processing the request.
Result Result
// Time is the duration of the request processing in milliseconds.
Time uint32 | <mask>
<mask> // StatsCtx collects the statistics and flushes it to the database. Its default
<mask> // flushing interval is one hour.
<mask> //
<mask> // TODO(e.burkov): Use atomic.Pointer for accessing curr and db in go1.19.
<mask> type StatsCtx struct {
<mask> // currMu protects the current unit.
<mask> currMu *sync.Mutex
<mask> // curr is the actual statistics collection result.
<mask> curr *unit
<mask>
<mask> // dbMu protects db.
<mask> dbMu *sync.Mutex
<mask> // db is the opened statistics database, if any.
<mask> db *bbolt.DB
<mask>
<mask> // unitIDGen is the function that generates an identifier for the current
<mask> // unit. It's here for only testing purposes.
<mask> unitIDGen UnitIDGenFunc
<mask>
<mask> // httpRegister is used to set HTTP handlers.
<mask> httpRegister aghhttp.RegisterFunc
<mask>
<mask> // configModified is called whenever the configuration is modified via web
<mask> // interface.
<mask> configModified func()
<mask>
<mask> // filename is the name of database file.
<mask> filename string
<mask>
<mask> // limitHours is the maximum number of hours to collect statistics into the
<mask> // current unit.
<mask> limitHours uint32
<mask> }
<mask>
<mask> // unit collects the statistics data for a specific period of time.
<mask> type unit struct {
<mask> // mu protects all the fields of a unit.
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove // StatsCtx collects the statistics and flushes it to the database. Its default
// flushing interval is one hour.
</s> add // UnitIDGenFunc is the signature of a function that generates a unique ID for
// the statistics unit.
type UnitIDGenFunc func() (id uint32)
// TimeUnit is the unit of measuring time while aggregating the statistics.
type TimeUnit int
// Supported TimeUnit values.
const (
Hours TimeUnit = iota
Days
)
// Result is the resulting code of processing the DNS request.
type Result int
// Supported Result values. </s> remove // TimeUnit is the unit of measuring time while aggregating the statistics.
type TimeUnit int
</s> add // StatsCtx collects the statistics and flushes it to the database. Its default
// flushing interval is one hour.
//
// TODO(e.burkov): Use atomic.Pointer for accessing db in go1.19.
type StatsCtx struct {
// limitHours is the maximum number of hours to collect statistics into the
// current unit.
//
// It is of type uint32 to be accessed by atomic. It's arranged at the
// beginning of the structure to keep 64-bit alignment.
limitHours uint32 </s> remove // mu protects all the fields of a unit.
mu *sync.RWMutex
</s> add </s> remove // Supported Result values.
//
// TODO(e.burkov): Think about better naming.
const (
RNotFiltered Result = iota + 1
RFiltered
RSafeBrowsing
RSafeSearch
RParental
resultLast = RParental + 1
)
</s> add // unitIDGen is the function that generates an identifier for the current
// unit. It's here for only testing purposes.
unitIDGen UnitIDGenFunc </s> remove // Result is the resulting code of processing the DNS request.
type Result int
</s> add // dbMu protects db.
dbMu *sync.Mutex
// db is the opened statistics database, if any.
db *bbolt.DB | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
<mask> }
<mask>
<mask> // unit collects the statistics data for a specific period of time.
<mask> type unit struct {
<mask> // mu protects all the fields of a unit.
<mask> mu *sync.RWMutex
<mask>
<mask> // id is the unique unit's identifier. It's set to an absolute hour number
<mask> // since the beginning of UNIX time by the default ID generating function.
<mask> id uint32
<mask>
<mask> // nTotal stores the total number of requests.
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove // TODO(e.burkov): Use atomic.Pointer for accessing curr and db in go1.19.
type StatsCtx struct {
// currMu protects the current unit.
currMu *sync.Mutex
// curr is the actual statistics collection result.
curr *unit
// dbMu protects db.
dbMu *sync.Mutex
// db is the opened statistics database, if any.
db *bbolt.DB
// unitIDGen is the function that generates an identifier for the current
// unit. It's here for only testing purposes.
unitIDGen UnitIDGenFunc
// httpRegister is used to set HTTP handlers.
httpRegister aghhttp.RegisterFunc
// configModified is called whenever the configuration is modified via web
// interface.
configModified func()
// filename is the name of database file.
filename string
// limitHours is the maximum number of hours to collect statistics into the
// current unit.
limitHours uint32
</s> add // TODO(e.burkov): Think about better naming.
const (
RNotFiltered Result = iota + 1
RFiltered
RSafeBrowsing
RSafeSearch
RParental
resultLast = RParental + 1
)
// Entry is a statistics data entry.
type Entry struct {
// Clients is the client's primary ID.
//
// TODO(a.garipov): Make this a {net.IP, string} enum?
Client string
// Domain is the domain name requested.
Domain string
// Result is the result of processing the request.
Result Result
// Time is the duration of the request processing in milliseconds.
Time uint32 </s> remove // TimeUnit is the unit of measuring time while aggregating the statistics.
type TimeUnit int
</s> add // StatsCtx collects the statistics and flushes it to the database. Its default
// flushing interval is one hour.
//
// TODO(e.burkov): Use atomic.Pointer for accessing db in go1.19.
type StatsCtx struct {
// limitHours is the maximum number of hours to collect statistics into the
// current unit.
//
// It is of type uint32 to be accessed by atomic. It's arranged at the
// beginning of the structure to keep 64-bit alignment.
limitHours uint32 </s> remove // StatsCtx collects the statistics and flushes it to the database. Its default
// flushing interval is one hour.
</s> add // UnitIDGenFunc is the signature of a function that generates a unique ID for
// the statistics unit.
type UnitIDGenFunc func() (id uint32)
// TimeUnit is the unit of measuring time while aggregating the statistics.
type TimeUnit int
// Supported TimeUnit values.
const (
Hours TimeUnit = iota
Days
)
// Result is the resulting code of processing the DNS request.
type Result int
// Supported Result values. </s> remove // unitDB is the structure for deserializing statistics data into the database.
</s> add // unitDB is the structure for serializing statistics data into the database. | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
|
//
// Must not be rewritten after creating to be accessed concurrently without
// using mu. | <mask> type unit struct {
<mask> // id is the unique unit's identifier. It's set to an absolute hour number
<mask> // since the beginning of UNIX time by the default ID generating function.
<mask> id uint32
<mask>
<mask> // nTotal stores the total number of requests.
<mask> nTotal uint64
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove // mu protects all the fields of a unit.
mu *sync.RWMutex
</s> add </s> remove // unitDB is the structure for deserializing statistics data into the database.
</s> add // unitDB is the structure for serializing statistics data into the database. </s> remove // TimeUnit is the unit of measuring time while aggregating the statistics.
type TimeUnit int
</s> add // StatsCtx collects the statistics and flushes it to the database. Its default
// flushing interval is one hour.
//
// TODO(e.burkov): Use atomic.Pointer for accessing db in go1.19.
type StatsCtx struct {
// limitHours is the maximum number of hours to collect statistics into the
// current unit.
//
// It is of type uint32 to be accessed by atomic. It's arranged at the
// beginning of the structure to keep 64-bit alignment.
limitHours uint32 </s> remove // StatsCtx collects the statistics and flushes it to the database. Its default
// flushing interval is one hour.
</s> add // UnitIDGenFunc is the signature of a function that generates a unique ID for
// the statistics unit.
type UnitIDGenFunc func() (id uint32)
// TimeUnit is the unit of measuring time while aggregating the statistics.
type TimeUnit int
// Supported TimeUnit values.
const (
Hours TimeUnit = iota
Days
)
// Result is the resulting code of processing the DNS request.
type Result int
// Supported Result values. </s> remove // UnitIDGenFunc is the signature of a function that generates a unique ID for
// the statistics unit.
type UnitIDGenFunc func() (id uint32)
</s> add | [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
// newUnit allocates the new *unit.
func newUnit(id uint32) (u *unit) {
return &unit{
id: id,
nResult: make([]uint64, resultLast),
domains: make(map[string]uint64),
blockedDomains: make(map[string]uint64),
clients: make(map[string]uint64),
} | <mask> // clients stores the number of requests from each client.
<mask> clients map[string]uint64
<mask> }
<mask>
<mask> // ongoing returns the current unit. It's safe for concurrent use.
<mask> //
<mask> // Note that the unit itself should be locked before accessing.
<mask> func (s *StatsCtx) ongoing() (u *unit) {
<mask> s.currMu.Lock()
<mask> defer s.currMu.Unlock()
<mask>
<mask> return s.curr
<mask> }
<mask>
<mask> // swapCurrent swaps the current unit with another and returns it. It's safe
<mask> // for concurrent use.
<mask> func (s *StatsCtx) swapCurrent(with *unit) (old *unit) {
<mask> s.currMu.Lock()
<mask> defer s.currMu.Unlock()
<mask>
<mask> old, s.curr = s.curr, with
<mask>
<mask> return old
<mask> }
<mask>
<mask> // database returns the database if it's opened. It's safe for concurrent use.
<mask> func (s *StatsCtx) database() (db *bbolt.DB) {
<mask> s.dbMu.Lock()
<mask> defer s.dbMu.Unlock()
<mask>
<mask> return s.db
<mask> }
<mask>
<mask> // swapDatabase swaps the database with another one and returns it. It's safe
<mask> // for concurrent use.
<mask> func (s *StatsCtx) swapDatabase(with *bbolt.DB) (old *bbolt.DB) {
<mask> s.dbMu.Lock()
<mask> defer s.dbMu.Unlock()
<mask>
<mask> old, s.db = s.db, with
<mask>
<mask> return old
<mask> }
<mask>
<mask> // countPair is a single name-number pair for deserializing statistics data into
<mask> // the database.
<mask> type countPair struct {
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove // serialize converts u to the *unitDB. It's safe for concurrent use.
</s> add // serialize converts u to the *unitDB. It's safe for concurrent use. u must
// not be nil. </s> remove // Entry is a statistics data entry.
type Entry struct {
// Clients is the client's primary ID.
//
// TODO(a.garipov): Make this a {net.IP, string} enum?
Client string
</s> add // httpRegister is used to set HTTP handlers.
httpRegister aghhttp.RegisterFunc
// configModified is called whenever the configuration is modified via web
// interface.
configModified func()
// filename is the name of database file.
filename string
}
var _ Interface = &StatsCtx{}
// New creates s from conf and properly initializes it. Don't use s before
// calling it's Start method.
func New(conf Config) (s *StatsCtx, err error) {
defer withRecovered(&err)
s = &StatsCtx{
currMu: &sync.RWMutex{},
dbMu: &sync.Mutex{},
filename: conf.Filename,
configModified: conf.ConfigModified,
httpRegister: conf.HTTPRegister,
}
if s.limitHours = conf.LimitDays * 24; !checkInterval(conf.LimitDays) {
s.limitHours = 24
}
if s.unitIDGen = newUnitID; conf.UnitID != nil {
s.unitIDGen = conf.UnitID
}
// TODO(e.burkov): Move the code below to the Start method.
err = s.openDB()
if err != nil {
return nil, fmt.Errorf("opening database: %w", err)
}
var udb *unitDB
id := s.unitIDGen()
tx, err := s.db.Begin(true)
if err != nil {
return nil, fmt.Errorf("stats: opening a transaction: %w", err)
}
deleted := deleteOldUnits(tx, id-s.limitHours-1)
udb = loadUnitFromDB(tx, id)
err = finishTxn(tx, deleted > 0)
if err != nil {
log.Error("stats: %s", err)
}
s.curr = newUnit(id)
s.curr.deserialize(udb)
log.Debug("stats: initialized")
return s, nil
}
// withRecovered turns the value recovered from panic if any into an error and
// combines it with the one pointed by orig. orig must be non-nil.
func withRecovered(orig *error) {
p := recover()
if p == nil {
return
}
var err error
switch p := p.(type) {
case error:
err = fmt.Errorf("panic: %w", p)
default:
err = fmt.Errorf("panic: recovered value of type %[1]T: %[1]v", p)
}
*orig = errors.WithDeferred(*orig, err)
}
// Start implements the Interface interface for *StatsCtx.
func (s *StatsCtx) Start() {
s.initWeb()
go s.periodicFlush()
}
// Close implements the io.Closer interface for *StatsCtx.
func (s *StatsCtx) Close() (err error) {
defer func() { err = errors.Annotate(err, "stats: closing: %w") }()
db := s.swapDatabase(nil)
if db == nil {
return nil
}
defer func() {
cerr := db.Close()
if cerr == nil {
log.Debug("stats: database closed")
}
err = errors.WithDeferred(err, cerr)
}()
tx, err := db.Begin(true)
if err != nil {
return fmt.Errorf("opening transaction: %w", err)
}
defer func() { err = errors.WithDeferred(err, finishTxn(tx, err == nil)) }()
s.currMu.RLock()
defer s.currMu.RUnlock()
udb := s.curr.serialize()
return udb.flushUnitToDB(tx, s.curr.id)
}
// Update implements the Interface interface for *StatsCtx.
func (s *StatsCtx) Update(e Entry) {
if atomic.LoadUint32(&s.limitHours) == 0 {
return
}
if e.Result == 0 || e.Result >= resultLast || e.Domain == "" || e.Client == "" {
log.Debug("stats: malformed entry")
return
}
s.currMu.Lock()
defer s.currMu.Unlock()
if s.curr == nil {
log.Error("stats: current unit is nil")
return
}
clientID := e.Client
if ip := net.ParseIP(clientID); ip != nil {
clientID = ip.String()
}
s.curr.add(e.Result, e.Domain, clientID, uint64(e.Time))
}
// WriteDiskConfig implements the Interface interface for *StatsCtx.
func (s *StatsCtx) WriteDiskConfig(dc *DiskConfig) {
dc.Interval = atomic.LoadUint32(&s.limitHours) / 24
}
// TopClientsIP implements the Interface interface for *StatsCtx.
func (s *StatsCtx) TopClientsIP(maxCount uint) (ips []net.IP) {
limit := atomic.LoadUint32(&s.limitHours)
if limit == 0 {
return nil
}
units, _ := s.loadUnits(limit)
if units == nil {
return nil
}
// Collect data for all the clients to sort and crop it afterwards.
m := map[string]uint64{}
for _, u := range units {
for _, it := range u.Clients {
m[it.Name] += it.Count
}
}
a := convertMapToSlice(m, int(maxCount))
ips = []net.IP{}
for _, it := range a {
ip := net.ParseIP(it.Name)
if ip != nil {
ips = append(ips, ip)
}
}
return ips
}
// database returns the database if it's opened. It's safe for concurrent use.
func (s *StatsCtx) database() (db *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
return s.db
}
// swapDatabase swaps the database with another one and returns it. It's safe
// for concurrent use.
func (s *StatsCtx) swapDatabase(with *bbolt.DB) (old *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
old, s.db = s.db, with
return old
}
// deleteOldUnits walks the buckets available to tx and deletes old units. It
// returns the number of deletions performed.
func deleteOldUnits(tx *bbolt.Tx, firstID uint32) (deleted int) {
log.Debug("stats: deleting old units until id %d", firstID)
// TODO(a.garipov): See if this is actually necessary. Looks like a rather
// bizarre solution.
const errStop errors.Error = "stop iteration"
walk := func(name []byte, _ *bbolt.Bucket) (err error) {
nameID, ok := unitNameToID(name)
if ok && nameID >= firstID {
return errStop
}
err = tx.DeleteBucket(name)
if err != nil {
log.Debug("stats: deleting bucket: %s", err)
return nil
}
log.Debug("stats: deleted unit %d (name %x)", nameID, name)
deleted++
return nil
}
err := tx.ForEach(walk)
if err != nil && !errors.Is(err, errStop) {
log.Debug("stats: deleting units: %s", err)
}
return deleted
}
// openDB returns an error if the database can't be opened from the specified
// file. It's safe for concurrent use.
func (s *StatsCtx) openDB() (err error) {
log.Debug("stats: opening database")
var db *bbolt.DB
db, err = bbolt.Open(s.filename, 0o644, nil)
if err != nil {
if err.Error() == "invalid argument" {
log.Error("AdGuard Home cannot be initialized due to an incompatible file system.\nPlease read the explanation here: https://github.com/AdguardTeam/AdGuardHome/wiki/Getting-Started#limitations")
}
return err
}
// Use defer to unlock the mutex as soon as possible.
defer log.Debug("stats: database opened")
s.dbMu.Lock()
defer s.dbMu.Unlock()
s.db = db
return nil
}
func (s *StatsCtx) flush() (cont bool, sleepFor time.Duration) {
id := s.unitIDGen()
s.currMu.Lock()
defer s.currMu.Unlock()
ptr := s.curr
if ptr == nil {
return false, 0
}
limit := atomic.LoadUint32(&s.limitHours)
if limit == 0 || ptr.id == id {
return true, time.Second
}
db := s.database()
if db == nil {
return true, 0
}
tx, err := db.Begin(true)
if err != nil {
log.Error("stats: opening transaction: %s", err)
return true, 0
}
s.curr = newUnit(id)
isCommitable := true
ferr := ptr.serialize().flushUnitToDB(tx, ptr.id)
if ferr != nil {
log.Error("stats: flushing unit: %s", ferr)
isCommitable = false
}
derr := tx.DeleteBucket(idToUnitName(id - limit))
if derr != nil {
log.Error("stats: deleting unit: %s", derr)
if !errors.Is(derr, bbolt.ErrBucketNotFound) {
isCommitable = false
}
}
err = finishTxn(tx, isCommitable)
if err != nil {
log.Error("stats: %s", err)
}
return true, 0
}
// periodicFlush checks and flushes the unit to the database if the freshly
// generated unit ID differs from the current's ID. Flushing process includes:
// - swapping the current unit with the new empty one;
// - writing the current unit to the database;
// - removing the stale unit from the database.
func (s *StatsCtx) periodicFlush() {
for cont, sleepFor := true, time.Duration(0); cont; time.Sleep(sleepFor) {
cont, sleepFor = s.flush()
}
log.Debug("periodic flushing finished")
}
func (s *StatsCtx) setLimit(limitDays int) {
atomic.StoreUint32(&s.limitHours, uint32(24*limitDays))
if limitDays == 0 {
if err := s.clear(); err != nil {
log.Error("stats: %s", err)
}
}
log.Debug("stats: set limit: %d days", limitDays)
}
// Reset counters and clear database
func (s *StatsCtx) clear() (err error) {
defer func() { err = errors.Annotate(err, "clearing: %w") }()
db := s.swapDatabase(nil)
if db != nil {
var tx *bbolt.Tx
tx, err = db.Begin(true)
if err != nil {
log.Error("stats: opening a transaction: %s", err)
} else if err = finishTxn(tx, false); err != nil {
// Don't wrap the error since it's informative enough as is.
return err
}
// Active transactions will continue using database, but new ones won't
// be created.
err = db.Close()
if err != nil {
return fmt.Errorf("closing database: %w", err)
}
// All active transactions are now closed.
log.Debug("stats: database closed")
}
err = os.Remove(s.filename)
if err != nil {
log.Error("stats: %s", err)
}
err = s.openDB()
if err != nil {
log.Error("stats: opening database: %s", err)
}
// Use defer to unlock the mutex as soon as possible.
defer log.Debug("stats: cleared")
s.currMu.Lock()
defer s.currMu.Unlock()
s.curr = newUnit(s.unitIDGen())
return nil
}
func (s *StatsCtx) loadUnits(limit uint32) (units []*unitDB, firstID uint32) {
db := s.database()
if db == nil {
return nil, 0
}
// Use writable transaction to ensure any ongoing writable transaction is
// taken into account.
tx, err := db.Begin(true)
if err != nil {
log.Error("stats: opening transaction: %s", err)
return nil, 0
}
s.currMu.RLock()
defer s.currMu.RUnlock()
cur := s.curr
var curID uint32
if cur != nil {
curID = cur.id
} else {
curID = s.unitIDGen()
}
// Per-hour units.
units = make([]*unitDB, 0, limit)
firstID = curID - limit + 1
for i := firstID; i != curID; i++ {
u := loadUnitFromDB(tx, i)
if u == nil {
u = &unitDB{NResult: make([]uint64, resultLast)}
}
units = append(units, u)
}
err = finishTxn(tx, false)
if err != nil {
log.Error("stats: %s", err)
} </s> remove u.mu.RLock()
defer u.mu.RUnlock()
</s> add </s> remove func flushUnitToDB(tx *bbolt.Tx, id uint32, udb *unitDB) bool {
log.Tracef("Flushing unit %d", id)
</s> add // add adds new data to u. It's safe for concurrent use.
func (u *unit) add(res Result, domain, cli string, dur uint64) {
u.nResult[res]++
if res == RNotFiltered {
u.domains[domain]++
} else {
u.blockedDomains[domain]++
}
u.clients[cli]++
u.timeSum += dur
u.nTotal++
}
// flushUnitToDB puts udb to the database at id.
func (udb *unitDB) flushUnitToDB(tx *bbolt.Tx, id uint32) (err error) {
log.Debug("stats: flushing unit with id %d and total of %d", id, udb.NTotal) </s> remove // withRecovered turns the value recovered from panic if any into an error and
// combines it with the one pointed by orig. orig must be non-nil.
func withRecovered(orig *error) {
p := recover()
if p == nil {
return
}
var err error
switch p := p.(type) {
case error:
err = fmt.Errorf("panic: %w", p)
default:
err = fmt.Errorf("panic: recovered value of type %[1]T: %[1]v", p)
}
*orig = errors.WithDeferred(*orig, err)
}
// isEnabled is a helper that check if the statistics collecting is enabled.
func (s *StatsCtx) isEnabled() (ok bool) {
return atomic.LoadUint32(&s.limitHours) != 0
}
// New creates s from conf and properly initializes it. Don't use s before
// calling it's Start method.
func New(conf Config) (s *StatsCtx, err error) {
defer withRecovered(&err)
s = &StatsCtx{
currMu: &sync.Mutex{},
dbMu: &sync.Mutex{},
filename: conf.Filename,
configModified: conf.ConfigModified,
httpRegister: conf.HTTPRegister,
}
if s.limitHours = conf.LimitDays * 24; !checkInterval(conf.LimitDays) {
s.limitHours = 24
}
if s.unitIDGen = newUnitID; conf.UnitID != nil {
s.unitIDGen = conf.UnitID
}
if err = s.dbOpen(); err != nil {
return nil, fmt.Errorf("opening database: %w", err)
}
id := s.unitIDGen()
tx := beginTxn(s.db, true)
var udb *unitDB
if tx != nil {
log.Tracef("Deleting old units...")
firstID := id - s.limitHours - 1
unitDel := 0
err = tx.ForEach(newBucketWalker(tx, &unitDel, firstID))
if err != nil && !errors.Is(err, errStop) {
log.Debug("stats: deleting units: %s", err)
}
udb = s.loadUnitFromDB(tx, id)
if unitDel != 0 {
s.commitTxn(tx)
} else {
err = tx.Rollback()
if err != nil {
log.Debug("rolling back: %s", err)
}
}
}
u := newUnit(id)
// This use of deserialize is safe since the accessed unit has just been
// created.
u.deserialize(udb)
s.curr = u
log.Debug("stats: initialized")
return s, nil
}
// TODO(a.garipov): See if this is actually necessary. Looks like a rather
// bizarre solution.
const errStop errors.Error = "stop iteration"
// newBucketWalker returns a new bucket walker that deletes old units. The
// integer that unitDelPtr points to is incremented for every successful
// deletion. If the bucket isn't deleted, f returns errStop.
func newBucketWalker(
tx *bbolt.Tx,
unitDelPtr *int,
firstID uint32,
) (f func(name []byte, b *bbolt.Bucket) (err error)) {
return func(name []byte, _ *bbolt.Bucket) (err error) {
nameID, ok := unitNameToID(name)
if !ok || nameID < firstID {
err = tx.DeleteBucket(name)
if err != nil {
log.Debug("stats: tx.DeleteBucket: %s", err)
return nil
}
log.Debug("stats: deleted unit %d (name %x)", nameID, name)
*unitDelPtr++
return nil
}
return errStop
}
}
// Start makes s process the incoming data.
func (s *StatsCtx) Start() {
s.initWeb()
go s.periodicFlush()
}
// checkInterval returns true if days is valid to be used as statistics
// retention interval. The valid values are 0, 1, 7, 30 and 90.
func checkInterval(days uint32) (ok bool) {
return days == 0 || days == 1 || days == 7 || days == 30 || days == 90
}
// dbOpen returns an error if the database can't be opened from the specified
// file. It's safe for concurrent use.
func (s *StatsCtx) dbOpen() (err error) {
log.Tracef("db.Open...")
s.dbMu.Lock()
defer s.dbMu.Unlock()
s.db, err = bbolt.Open(s.filename, 0o644, nil)
if err != nil {
log.Error("stats: open DB: %s: %s", s.filename, err)
if err.Error() == "invalid argument" {
log.Error("AdGuard Home cannot be initialized due to an incompatible file system.\nPlease read the explanation here: https://github.com/AdguardTeam/AdGuardHome/wiki/Getting-Started#limitations")
}
return err
}
log.Tracef("db.Open")
return nil
}
</s> add | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
// unitDB is the structure for serializing statistics data into the database. | <mask> Name string
<mask> Count uint64
<mask> }
<mask>
<mask> // unitDB is the structure for deserializing statistics data into the database.
<mask> type unitDB struct {
<mask> // NTotal is the total number of requests.
<mask> NTotal uint64
<mask> // NResult is the number of requests by the result's kind.
<mask> NResult []uint64
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove // mu protects all the fields of a unit.
mu *sync.RWMutex
</s> add </s> remove // TimeUnit is the unit of measuring time while aggregating the statistics.
type TimeUnit int
</s> add // StatsCtx collects the statistics and flushes it to the database. Its default
// flushing interval is one hour.
//
// TODO(e.burkov): Use atomic.Pointer for accessing db in go1.19.
type StatsCtx struct {
// limitHours is the maximum number of hours to collect statistics into the
// current unit.
//
// It is of type uint32 to be accessed by atomic. It's arranged at the
// beginning of the structure to keep 64-bit alignment.
limitHours uint32 </s> remove // UnitIDGenFunc is the signature of a function that generates a unique ID for
// the statistics unit.
type UnitIDGenFunc func() (id uint32)
</s> add </s> remove // statsResponse is a response for getting statistics.
type statsResponse struct {
</s> add // StatsResp is a response to the GET /control/stats.
type StatsResp struct { | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
<mask> // requests in the unit.
<mask> TimeAvg uint32
<mask> }
<mask>
<mask> // withRecovered turns the value recovered from panic if any into an error and
<mask> // combines it with the one pointed by orig. orig must be non-nil.
<mask> func withRecovered(orig *error) {
<mask> p := recover()
<mask> if p == nil {
<mask> return
<mask> }
<mask>
<mask> var err error
<mask> switch p := p.(type) {
<mask> case error:
<mask> err = fmt.Errorf("panic: %w", p)
<mask> default:
<mask> err = fmt.Errorf("panic: recovered value of type %[1]T: %[1]v", p)
<mask> }
<mask>
<mask> *orig = errors.WithDeferred(*orig, err)
<mask> }
<mask>
<mask> // isEnabled is a helper that check if the statistics collecting is enabled.
<mask> func (s *StatsCtx) isEnabled() (ok bool) {
<mask> return atomic.LoadUint32(&s.limitHours) != 0
<mask> }
<mask>
<mask> // New creates s from conf and properly initializes it. Don't use s before
<mask> // calling it's Start method.
<mask> func New(conf Config) (s *StatsCtx, err error) {
<mask> defer withRecovered(&err)
<mask>
<mask> s = &StatsCtx{
<mask> currMu: &sync.Mutex{},
<mask> dbMu: &sync.Mutex{},
<mask> filename: conf.Filename,
<mask> configModified: conf.ConfigModified,
<mask> httpRegister: conf.HTTPRegister,
<mask> }
<mask> if s.limitHours = conf.LimitDays * 24; !checkInterval(conf.LimitDays) {
<mask> s.limitHours = 24
<mask> }
<mask> if s.unitIDGen = newUnitID; conf.UnitID != nil {
<mask> s.unitIDGen = conf.UnitID
<mask> }
<mask>
<mask> if err = s.dbOpen(); err != nil {
<mask> return nil, fmt.Errorf("opening database: %w", err)
<mask> }
<mask>
<mask> id := s.unitIDGen()
<mask> tx := beginTxn(s.db, true)
<mask> var udb *unitDB
<mask> if tx != nil {
<mask> log.Tracef("Deleting old units...")
<mask> firstID := id - s.limitHours - 1
<mask> unitDel := 0
<mask>
<mask> err = tx.ForEach(newBucketWalker(tx, &unitDel, firstID))
<mask> if err != nil && !errors.Is(err, errStop) {
<mask> log.Debug("stats: deleting units: %s", err)
<mask> }
<mask>
<mask> udb = s.loadUnitFromDB(tx, id)
<mask>
<mask> if unitDel != 0 {
<mask> s.commitTxn(tx)
<mask> } else {
<mask> err = tx.Rollback()
<mask> if err != nil {
<mask> log.Debug("rolling back: %s", err)
<mask> }
<mask> }
<mask> }
<mask>
<mask> u := newUnit(id)
<mask> // This use of deserialize is safe since the accessed unit has just been
<mask> // created.
<mask> u.deserialize(udb)
<mask> s.curr = u
<mask>
<mask> log.Debug("stats: initialized")
<mask>
<mask> return s, nil
<mask> }
<mask>
<mask> // TODO(a.garipov): See if this is actually necessary. Looks like a rather
<mask> // bizarre solution.
<mask> const errStop errors.Error = "stop iteration"
<mask>
<mask> // newBucketWalker returns a new bucket walker that deletes old units. The
<mask> // integer that unitDelPtr points to is incremented for every successful
<mask> // deletion. If the bucket isn't deleted, f returns errStop.
<mask> func newBucketWalker(
<mask> tx *bbolt.Tx,
<mask> unitDelPtr *int,
<mask> firstID uint32,
<mask> ) (f func(name []byte, b *bbolt.Bucket) (err error)) {
<mask> return func(name []byte, _ *bbolt.Bucket) (err error) {
<mask> nameID, ok := unitNameToID(name)
<mask> if !ok || nameID < firstID {
<mask> err = tx.DeleteBucket(name)
<mask> if err != nil {
<mask> log.Debug("stats: tx.DeleteBucket: %s", err)
<mask>
<mask> return nil
<mask> }
<mask>
<mask> log.Debug("stats: deleted unit %d (name %x)", nameID, name)
<mask>
<mask> *unitDelPtr++
<mask>
<mask> return nil
<mask> }
<mask>
<mask> return errStop
<mask> }
<mask> }
<mask>
<mask> // Start makes s process the incoming data.
<mask> func (s *StatsCtx) Start() {
<mask> s.initWeb()
<mask> go s.periodicFlush()
<mask> }
<mask>
<mask> // checkInterval returns true if days is valid to be used as statistics
<mask> // retention interval. The valid values are 0, 1, 7, 30 and 90.
<mask> func checkInterval(days uint32) (ok bool) {
<mask> return days == 0 || days == 1 || days == 7 || days == 30 || days == 90
<mask> }
<mask>
<mask> // dbOpen returns an error if the database can't be opened from the specified
<mask> // file. It's safe for concurrent use.
<mask> func (s *StatsCtx) dbOpen() (err error) {
<mask> log.Tracef("db.Open...")
<mask>
<mask> s.dbMu.Lock()
<mask> defer s.dbMu.Unlock()
<mask>
<mask> s.db, err = bbolt.Open(s.filename, 0o644, nil)
<mask> if err != nil {
<mask> log.Error("stats: open DB: %s: %s", s.filename, err)
<mask> if err.Error() == "invalid argument" {
<mask> log.Error("AdGuard Home cannot be initialized due to an incompatible file system.\nPlease read the explanation here: https://github.com/AdguardTeam/AdGuardHome/wiki/Getting-Started#limitations")
<mask> }
<mask>
<mask> return err
<mask> }
<mask>
<mask> log.Tracef("db.Open")
<mask>
<mask> return nil
<mask> }
<mask>
<mask> // newUnitID is the default UnitIDGenFunc that generates the unique id hourly.
<mask> func newUnitID() (id uint32) {
<mask> const secsInHour = int64(time.Hour / time.Second)
<mask>
<mask> return uint32(time.Now().Unix() / secsInHour)
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove // Entry is a statistics data entry.
type Entry struct {
// Clients is the client's primary ID.
//
// TODO(a.garipov): Make this a {net.IP, string} enum?
Client string
</s> add // httpRegister is used to set HTTP handlers.
httpRegister aghhttp.RegisterFunc
// configModified is called whenever the configuration is modified via web
// interface.
configModified func()
// filename is the name of database file.
filename string
}
var _ Interface = &StatsCtx{}
// New creates s from conf and properly initializes it. Don't use s before
// calling it's Start method.
func New(conf Config) (s *StatsCtx, err error) {
defer withRecovered(&err)
s = &StatsCtx{
currMu: &sync.RWMutex{},
dbMu: &sync.Mutex{},
filename: conf.Filename,
configModified: conf.ConfigModified,
httpRegister: conf.HTTPRegister,
}
if s.limitHours = conf.LimitDays * 24; !checkInterval(conf.LimitDays) {
s.limitHours = 24
}
if s.unitIDGen = newUnitID; conf.UnitID != nil {
s.unitIDGen = conf.UnitID
}
// TODO(e.burkov): Move the code below to the Start method.
err = s.openDB()
if err != nil {
return nil, fmt.Errorf("opening database: %w", err)
}
var udb *unitDB
id := s.unitIDGen()
tx, err := s.db.Begin(true)
if err != nil {
return nil, fmt.Errorf("stats: opening a transaction: %w", err)
}
deleted := deleteOldUnits(tx, id-s.limitHours-1)
udb = loadUnitFromDB(tx, id)
err = finishTxn(tx, deleted > 0)
if err != nil {
log.Error("stats: %s", err)
}
s.curr = newUnit(id)
s.curr.deserialize(udb)
log.Debug("stats: initialized")
return s, nil
}
// withRecovered turns the value recovered from panic if any into an error and
// combines it with the one pointed by orig. orig must be non-nil.
func withRecovered(orig *error) {
p := recover()
if p == nil {
return
}
var err error
switch p := p.(type) {
case error:
err = fmt.Errorf("panic: %w", p)
default:
err = fmt.Errorf("panic: recovered value of type %[1]T: %[1]v", p)
}
*orig = errors.WithDeferred(*orig, err)
}
// Start implements the Interface interface for *StatsCtx.
func (s *StatsCtx) Start() {
s.initWeb()
go s.periodicFlush()
}
// Close implements the io.Closer interface for *StatsCtx.
func (s *StatsCtx) Close() (err error) {
defer func() { err = errors.Annotate(err, "stats: closing: %w") }()
db := s.swapDatabase(nil)
if db == nil {
return nil
}
defer func() {
cerr := db.Close()
if cerr == nil {
log.Debug("stats: database closed")
}
err = errors.WithDeferred(err, cerr)
}()
tx, err := db.Begin(true)
if err != nil {
return fmt.Errorf("opening transaction: %w", err)
}
defer func() { err = errors.WithDeferred(err, finishTxn(tx, err == nil)) }()
s.currMu.RLock()
defer s.currMu.RUnlock()
udb := s.curr.serialize()
return udb.flushUnitToDB(tx, s.curr.id)
}
// Update implements the Interface interface for *StatsCtx.
func (s *StatsCtx) Update(e Entry) {
if atomic.LoadUint32(&s.limitHours) == 0 {
return
}
if e.Result == 0 || e.Result >= resultLast || e.Domain == "" || e.Client == "" {
log.Debug("stats: malformed entry")
return
}
s.currMu.Lock()
defer s.currMu.Unlock()
if s.curr == nil {
log.Error("stats: current unit is nil")
return
}
clientID := e.Client
if ip := net.ParseIP(clientID); ip != nil {
clientID = ip.String()
}
s.curr.add(e.Result, e.Domain, clientID, uint64(e.Time))
}
// WriteDiskConfig implements the Interface interface for *StatsCtx.
func (s *StatsCtx) WriteDiskConfig(dc *DiskConfig) {
dc.Interval = atomic.LoadUint32(&s.limitHours) / 24
}
// TopClientsIP implements the Interface interface for *StatsCtx.
func (s *StatsCtx) TopClientsIP(maxCount uint) (ips []net.IP) {
limit := atomic.LoadUint32(&s.limitHours)
if limit == 0 {
return nil
}
units, _ := s.loadUnits(limit)
if units == nil {
return nil
}
// Collect data for all the clients to sort and crop it afterwards.
m := map[string]uint64{}
for _, u := range units {
for _, it := range u.Clients {
m[it.Name] += it.Count
}
}
a := convertMapToSlice(m, int(maxCount))
ips = []net.IP{}
for _, it := range a {
ip := net.ParseIP(it.Name)
if ip != nil {
ips = append(ips, ip)
}
}
return ips
}
// database returns the database if it's opened. It's safe for concurrent use.
func (s *StatsCtx) database() (db *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
return s.db
}
// swapDatabase swaps the database with another one and returns it. It's safe
// for concurrent use.
func (s *StatsCtx) swapDatabase(with *bbolt.DB) (old *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
old, s.db = s.db, with
return old
}
// deleteOldUnits walks the buckets available to tx and deletes old units. It
// returns the number of deletions performed.
func deleteOldUnits(tx *bbolt.Tx, firstID uint32) (deleted int) {
log.Debug("stats: deleting old units until id %d", firstID)
// TODO(a.garipov): See if this is actually necessary. Looks like a rather
// bizarre solution.
const errStop errors.Error = "stop iteration"
walk := func(name []byte, _ *bbolt.Bucket) (err error) {
nameID, ok := unitNameToID(name)
if ok && nameID >= firstID {
return errStop
}
err = tx.DeleteBucket(name)
if err != nil {
log.Debug("stats: deleting bucket: %s", err)
return nil
}
log.Debug("stats: deleted unit %d (name %x)", nameID, name)
deleted++
return nil
}
err := tx.ForEach(walk)
if err != nil && !errors.Is(err, errStop) {
log.Debug("stats: deleting units: %s", err)
}
return deleted
}
// openDB returns an error if the database can't be opened from the specified
// file. It's safe for concurrent use.
func (s *StatsCtx) openDB() (err error) {
log.Debug("stats: opening database")
var db *bbolt.DB
db, err = bbolt.Open(s.filename, 0o644, nil)
if err != nil {
if err.Error() == "invalid argument" {
log.Error("AdGuard Home cannot be initialized due to an incompatible file system.\nPlease read the explanation here: https://github.com/AdguardTeam/AdGuardHome/wiki/Getting-Started#limitations")
}
return err
}
// Use defer to unlock the mutex as soon as possible.
defer log.Debug("stats: database opened")
s.dbMu.Lock()
defer s.dbMu.Unlock()
s.db = db
return nil
}
func (s *StatsCtx) flush() (cont bool, sleepFor time.Duration) {
id := s.unitIDGen()
s.currMu.Lock()
defer s.currMu.Unlock()
ptr := s.curr
if ptr == nil {
return false, 0
}
limit := atomic.LoadUint32(&s.limitHours)
if limit == 0 || ptr.id == id {
return true, time.Second
}
db := s.database()
if db == nil {
return true, 0
}
tx, err := db.Begin(true)
if err != nil {
log.Error("stats: opening transaction: %s", err)
return true, 0
}
s.curr = newUnit(id)
isCommitable := true
ferr := ptr.serialize().flushUnitToDB(tx, ptr.id)
if ferr != nil {
log.Error("stats: flushing unit: %s", ferr)
isCommitable = false
}
derr := tx.DeleteBucket(idToUnitName(id - limit))
if derr != nil {
log.Error("stats: deleting unit: %s", derr)
if !errors.Is(derr, bbolt.ErrBucketNotFound) {
isCommitable = false
}
}
err = finishTxn(tx, isCommitable)
if err != nil {
log.Error("stats: %s", err)
}
return true, 0
}
// periodicFlush checks and flushes the unit to the database if the freshly
// generated unit ID differs from the current's ID. Flushing process includes:
// - swapping the current unit with the new empty one;
// - writing the current unit to the database;
// - removing the stale unit from the database.
func (s *StatsCtx) periodicFlush() {
for cont, sleepFor := true, time.Duration(0); cont; time.Sleep(sleepFor) {
cont, sleepFor = s.flush()
}
log.Debug("periodic flushing finished")
}
func (s *StatsCtx) setLimit(limitDays int) {
atomic.StoreUint32(&s.limitHours, uint32(24*limitDays))
if limitDays == 0 {
if err := s.clear(); err != nil {
log.Error("stats: %s", err)
}
}
log.Debug("stats: set limit: %d days", limitDays)
}
// Reset counters and clear database
func (s *StatsCtx) clear() (err error) {
defer func() { err = errors.Annotate(err, "clearing: %w") }()
db := s.swapDatabase(nil)
if db != nil {
var tx *bbolt.Tx
tx, err = db.Begin(true)
if err != nil {
log.Error("stats: opening a transaction: %s", err)
} else if err = finishTxn(tx, false); err != nil {
// Don't wrap the error since it's informative enough as is.
return err
}
// Active transactions will continue using database, but new ones won't
// be created.
err = db.Close()
if err != nil {
return fmt.Errorf("closing database: %w", err)
}
// All active transactions are now closed.
log.Debug("stats: database closed")
}
err = os.Remove(s.filename)
if err != nil {
log.Error("stats: %s", err)
}
err = s.openDB()
if err != nil {
log.Error("stats: opening database: %s", err)
}
// Use defer to unlock the mutex as soon as possible.
defer log.Debug("stats: cleared")
s.currMu.Lock()
defer s.currMu.Unlock()
s.curr = newUnit(s.unitIDGen())
return nil
}
func (s *StatsCtx) loadUnits(limit uint32) (units []*unitDB, firstID uint32) {
db := s.database()
if db == nil {
return nil, 0
}
// Use writable transaction to ensure any ongoing writable transaction is
// taken into account.
tx, err := db.Begin(true)
if err != nil {
log.Error("stats: opening transaction: %s", err)
return nil, 0
}
s.currMu.RLock()
defer s.currMu.RUnlock()
cur := s.curr
var curID uint32
if cur != nil {
curID = cur.id
} else {
curID = s.unitIDGen()
}
// Per-hour units.
units = make([]*unitDB, 0, limit)
firstID = curID - limit + 1
for i := firstID; i != curID; i++ {
u := loadUnitFromDB(tx, i)
if u == nil {
u = &unitDB{NResult: make([]uint64, resultLast)}
}
units = append(units, u)
}
err = finishTxn(tx, false)
if err != nil {
log.Error("stats: %s", err)
} </s> remove func (s *StatsCtx) setLimit(limitDays int) {
atomic.StoreUint32(&s.limitHours, uint32(24*limitDays))
if limitDays == 0 {
s.clear()
}
log.Debug("stats: set limit: %d days", limitDays)
}
func (s *StatsCtx) WriteDiskConfig(dc *DiskConfig) {
dc.Interval = atomic.LoadUint32(&s.limitHours) / 24
}
func (s *StatsCtx) Close() {
u := s.swapCurrent(nil)
db := s.database()
if tx := beginTxn(db, true); tx != nil {
udb := u.serialize()
if flushUnitToDB(tx, u.id, udb) {
s.commitTxn(tx)
} else {
_ = tx.Rollback()
}
}
if db != nil {
log.Tracef("db.Close...")
_ = db.Close()
log.Tracef("db.Close")
}
log.Debug("stats: closed")
}
// Reset counters and clear database
func (s *StatsCtx) clear() {
db := s.database()
tx := beginTxn(db, true)
if tx != nil {
_ = s.swapDatabase(nil)
_ = tx.Rollback()
// the active transactions can continue using database,
// but no new transactions will be opened
_ = db.Close()
log.Tracef("db.Close")
// all active transactions are now closed
}
u := newUnit(s.unitIDGen())
_ = s.swapCurrent(u)
err := os.Remove(s.filename)
if err != nil {
log.Error("os.Remove: %s", err)
}
_ = s.dbOpen()
log.Debug("stats: cleared")
}
func (s *StatsCtx) Update(e Entry) {
if !s.isEnabled() {
return
}
if e.Result == 0 ||
e.Result >= resultLast ||
e.Domain == "" ||
e.Client == "" {
return
}
clientID := e.Client
if ip := net.ParseIP(clientID); ip != nil {
clientID = ip.String()
}
u := s.ongoing()
if u == nil {
return
}
u.mu.Lock()
defer u.mu.Unlock()
u.nResult[e.Result]++
if e.Result == RNotFiltered {
u.domains[e.Domain]++
} else {
u.blockedDomains[e.Domain]++
}
u.clients[clientID]++
u.timeSum += uint64(e.Time)
u.nTotal++
}
func (s *StatsCtx) loadUnits(limit uint32) ([]*unitDB, uint32) {
tx := beginTxn(s.database(), false)
if tx == nil {
return nil, 0
}
cur := s.ongoing()
var curID uint32
if cur != nil {
curID = atomic.LoadUint32(&cur.id)
} else {
curID = s.unitIDGen()
}
// Per-hour units.
units := []*unitDB{}
firstID := curID - limit + 1
for i := firstID; i != curID; i++ {
u := s.loadUnitFromDB(tx, i)
if u == nil {
u = &unitDB{}
u.NResult = make([]uint64, resultLast)
}
units = append(units, u)
}
_ = tx.Rollback()
if cur != nil {
units = append(units, cur.serialize())
}
if len(units) != int(limit) {
log.Fatalf("len(units) != limit: %d %d", len(units), limit)
}
return units, firstID
}
</s> add </s> remove // newUnit allocates the new *unit.
func newUnit(id uint32) (u *unit) {
return &unit{
mu: &sync.RWMutex{},
id: id,
nResult: make([]uint64, resultLast),
domains: make(map[string]uint64),
blockedDomains: make(map[string]uint64),
clients: make(map[string]uint64),
}
}
// beginTxn opens a new database transaction. If writable is true, the
// transaction will be opened for writing, and for reading otherwise. It
// returns nil if the transaction can't be created.
func beginTxn(db *bbolt.DB, writable bool) (tx *bbolt.Tx) {
if db == nil {
return nil
}
log.Tracef("opening a database transaction")
tx, err := db.Begin(writable)
if err != nil {
log.Error("stats: opening a transaction: %s", err)
return nil
}
log.Tracef("transaction has been opened")
return tx
}
// commitTxn applies the changes made in tx to the database.
func (s *StatsCtx) commitTxn(tx *bbolt.Tx) {
err := tx.Commit()
if err != nil {
log.Error("stats: committing a transaction: %s", err)
return
</s> add func finishTxn(tx *bbolt.Tx, commit bool) (err error) {
if commit {
err = errors.Annotate(tx.Commit(), "committing: %w")
} else {
err = errors.Annotate(tx.Rollback(), "rolling back: %w") </s> remove // Flush the current unit to DB and delete an old unit when a new hour is started
// If a unit must be flushed:
// . lock DB
// . atomically set a new empty unit as the current one and get the old unit
// This is important to do it inside DB lock, so the reader won't get inconsistent results.
// . write the unit to DB
// . remove the stale unit from DB
// . unlock DB
func (s *StatsCtx) periodicFlush() {
for ptr := s.ongoing(); ptr != nil; ptr = s.ongoing() {
id := s.unitIDGen()
// Access the unit's ID with atomic to avoid locking the whole unit.
if !s.isEnabled() || atomic.LoadUint32(&ptr.id) == id {
time.Sleep(time.Second)
continue
}
tx := beginTxn(s.database(), true)
nu := newUnit(id)
u := s.swapCurrent(nu)
udb := u.serialize()
if tx == nil {
continue
}
flushOK := flushUnitToDB(tx, u.id, udb)
delOK := s.deleteUnit(tx, id-atomic.LoadUint32(&s.limitHours))
if flushOK || delOK {
s.commitTxn(tx)
} else {
_ = tx.Rollback()
}
</s> add func convertMapToSlice(m map[string]uint64, max int) (s []countPair) {
s = make([]countPair, 0, len(m))
for k, v := range m {
s = append(s, countPair{Name: k, Count: v}) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
|
func finishTxn(tx *bbolt.Tx, commit bool) (err error) {
if commit {
err = errors.Annotate(tx.Commit(), "committing: %w")
} else {
err = errors.Annotate(tx.Rollback(), "rolling back: %w") | <mask>
<mask> return uint32(time.Now().Unix() / secsInHour)
<mask> }
<mask>
<mask> // newUnit allocates the new *unit.
<mask> func newUnit(id uint32) (u *unit) {
<mask> return &unit{
<mask> mu: &sync.RWMutex{},
<mask> id: id,
<mask> nResult: make([]uint64, resultLast),
<mask> domains: make(map[string]uint64),
<mask> blockedDomains: make(map[string]uint64),
<mask> clients: make(map[string]uint64),
<mask> }
<mask> }
<mask>
<mask> // beginTxn opens a new database transaction. If writable is true, the
<mask> // transaction will be opened for writing, and for reading otherwise. It
<mask> // returns nil if the transaction can't be created.
<mask> func beginTxn(db *bbolt.DB, writable bool) (tx *bbolt.Tx) {
<mask> if db == nil {
<mask> return nil
<mask> }
<mask>
<mask> log.Tracef("opening a database transaction")
<mask>
<mask> tx, err := db.Begin(writable)
<mask> if err != nil {
<mask> log.Error("stats: opening a transaction: %s", err)
<mask>
<mask> return nil
<mask> }
<mask>
<mask> log.Tracef("transaction has been opened")
<mask>
<mask> return tx
<mask> }
<mask>
<mask> // commitTxn applies the changes made in tx to the database.
<mask> func (s *StatsCtx) commitTxn(tx *bbolt.Tx) {
<mask> err := tx.Commit()
<mask> if err != nil {
<mask> log.Error("stats: committing a transaction: %s", err)
<mask>
<mask> return
<mask> }
<mask>
<mask> log.Tracef("transaction has been committed")
<mask> }
<mask>
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove // ongoing returns the current unit. It's safe for concurrent use.
//
// Note that the unit itself should be locked before accessing.
func (s *StatsCtx) ongoing() (u *unit) {
s.currMu.Lock()
defer s.currMu.Unlock()
return s.curr
}
// swapCurrent swaps the current unit with another and returns it. It's safe
// for concurrent use.
func (s *StatsCtx) swapCurrent(with *unit) (old *unit) {
s.currMu.Lock()
defer s.currMu.Unlock()
old, s.curr = s.curr, with
return old
}
// database returns the database if it's opened. It's safe for concurrent use.
func (s *StatsCtx) database() (db *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
return s.db
}
// swapDatabase swaps the database with another one and returns it. It's safe
// for concurrent use.
func (s *StatsCtx) swapDatabase(with *bbolt.DB) (old *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
old, s.db = s.db, with
return old
</s> add // newUnit allocates the new *unit.
func newUnit(id uint32) (u *unit) {
return &unit{
id: id,
nResult: make([]uint64, resultLast),
domains: make(map[string]uint64),
blockedDomains: make(map[string]uint64),
clients: make(map[string]uint64),
} </s> remove // Entry is a statistics data entry.
type Entry struct {
// Clients is the client's primary ID.
//
// TODO(a.garipov): Make this a {net.IP, string} enum?
Client string
</s> add // httpRegister is used to set HTTP handlers.
httpRegister aghhttp.RegisterFunc
// configModified is called whenever the configuration is modified via web
// interface.
configModified func()
// filename is the name of database file.
filename string
}
var _ Interface = &StatsCtx{}
// New creates s from conf and properly initializes it. Don't use s before
// calling it's Start method.
func New(conf Config) (s *StatsCtx, err error) {
defer withRecovered(&err)
s = &StatsCtx{
currMu: &sync.RWMutex{},
dbMu: &sync.Mutex{},
filename: conf.Filename,
configModified: conf.ConfigModified,
httpRegister: conf.HTTPRegister,
}
if s.limitHours = conf.LimitDays * 24; !checkInterval(conf.LimitDays) {
s.limitHours = 24
}
if s.unitIDGen = newUnitID; conf.UnitID != nil {
s.unitIDGen = conf.UnitID
}
// TODO(e.burkov): Move the code below to the Start method.
err = s.openDB()
if err != nil {
return nil, fmt.Errorf("opening database: %w", err)
}
var udb *unitDB
id := s.unitIDGen()
tx, err := s.db.Begin(true)
if err != nil {
return nil, fmt.Errorf("stats: opening a transaction: %w", err)
}
deleted := deleteOldUnits(tx, id-s.limitHours-1)
udb = loadUnitFromDB(tx, id)
err = finishTxn(tx, deleted > 0)
if err != nil {
log.Error("stats: %s", err)
}
s.curr = newUnit(id)
s.curr.deserialize(udb)
log.Debug("stats: initialized")
return s, nil
}
// withRecovered turns the value recovered from panic if any into an error and
// combines it with the one pointed by orig. orig must be non-nil.
func withRecovered(orig *error) {
p := recover()
if p == nil {
return
}
var err error
switch p := p.(type) {
case error:
err = fmt.Errorf("panic: %w", p)
default:
err = fmt.Errorf("panic: recovered value of type %[1]T: %[1]v", p)
}
*orig = errors.WithDeferred(*orig, err)
}
// Start implements the Interface interface for *StatsCtx.
func (s *StatsCtx) Start() {
s.initWeb()
go s.periodicFlush()
}
// Close implements the io.Closer interface for *StatsCtx.
func (s *StatsCtx) Close() (err error) {
defer func() { err = errors.Annotate(err, "stats: closing: %w") }()
db := s.swapDatabase(nil)
if db == nil {
return nil
}
defer func() {
cerr := db.Close()
if cerr == nil {
log.Debug("stats: database closed")
}
err = errors.WithDeferred(err, cerr)
}()
tx, err := db.Begin(true)
if err != nil {
return fmt.Errorf("opening transaction: %w", err)
}
defer func() { err = errors.WithDeferred(err, finishTxn(tx, err == nil)) }()
s.currMu.RLock()
defer s.currMu.RUnlock()
udb := s.curr.serialize()
return udb.flushUnitToDB(tx, s.curr.id)
}
// Update implements the Interface interface for *StatsCtx.
func (s *StatsCtx) Update(e Entry) {
if atomic.LoadUint32(&s.limitHours) == 0 {
return
}
if e.Result == 0 || e.Result >= resultLast || e.Domain == "" || e.Client == "" {
log.Debug("stats: malformed entry")
return
}
s.currMu.Lock()
defer s.currMu.Unlock()
if s.curr == nil {
log.Error("stats: current unit is nil")
return
}
clientID := e.Client
if ip := net.ParseIP(clientID); ip != nil {
clientID = ip.String()
}
s.curr.add(e.Result, e.Domain, clientID, uint64(e.Time))
}
// WriteDiskConfig implements the Interface interface for *StatsCtx.
func (s *StatsCtx) WriteDiskConfig(dc *DiskConfig) {
dc.Interval = atomic.LoadUint32(&s.limitHours) / 24
}
// TopClientsIP implements the Interface interface for *StatsCtx.
func (s *StatsCtx) TopClientsIP(maxCount uint) (ips []net.IP) {
limit := atomic.LoadUint32(&s.limitHours)
if limit == 0 {
return nil
}
units, _ := s.loadUnits(limit)
if units == nil {
return nil
}
// Collect data for all the clients to sort and crop it afterwards.
m := map[string]uint64{}
for _, u := range units {
for _, it := range u.Clients {
m[it.Name] += it.Count
}
}
a := convertMapToSlice(m, int(maxCount))
ips = []net.IP{}
for _, it := range a {
ip := net.ParseIP(it.Name)
if ip != nil {
ips = append(ips, ip)
}
}
return ips
}
// database returns the database if it's opened. It's safe for concurrent use.
func (s *StatsCtx) database() (db *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
return s.db
}
// swapDatabase swaps the database with another one and returns it. It's safe
// for concurrent use.
func (s *StatsCtx) swapDatabase(with *bbolt.DB) (old *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
old, s.db = s.db, with
return old
}
// deleteOldUnits walks the buckets available to tx and deletes old units. It
// returns the number of deletions performed.
func deleteOldUnits(tx *bbolt.Tx, firstID uint32) (deleted int) {
log.Debug("stats: deleting old units until id %d", firstID)
// TODO(a.garipov): See if this is actually necessary. Looks like a rather
// bizarre solution.
const errStop errors.Error = "stop iteration"
walk := func(name []byte, _ *bbolt.Bucket) (err error) {
nameID, ok := unitNameToID(name)
if ok && nameID >= firstID {
return errStop
}
err = tx.DeleteBucket(name)
if err != nil {
log.Debug("stats: deleting bucket: %s", err)
return nil
}
log.Debug("stats: deleted unit %d (name %x)", nameID, name)
deleted++
return nil
}
err := tx.ForEach(walk)
if err != nil && !errors.Is(err, errStop) {
log.Debug("stats: deleting units: %s", err)
}
return deleted
}
// openDB returns an error if the database can't be opened from the specified
// file. It's safe for concurrent use.
func (s *StatsCtx) openDB() (err error) {
log.Debug("stats: opening database")
var db *bbolt.DB
db, err = bbolt.Open(s.filename, 0o644, nil)
if err != nil {
if err.Error() == "invalid argument" {
log.Error("AdGuard Home cannot be initialized due to an incompatible file system.\nPlease read the explanation here: https://github.com/AdguardTeam/AdGuardHome/wiki/Getting-Started#limitations")
}
return err
}
// Use defer to unlock the mutex as soon as possible.
defer log.Debug("stats: database opened")
s.dbMu.Lock()
defer s.dbMu.Unlock()
s.db = db
return nil
}
func (s *StatsCtx) flush() (cont bool, sleepFor time.Duration) {
id := s.unitIDGen()
s.currMu.Lock()
defer s.currMu.Unlock()
ptr := s.curr
if ptr == nil {
return false, 0
}
limit := atomic.LoadUint32(&s.limitHours)
if limit == 0 || ptr.id == id {
return true, time.Second
}
db := s.database()
if db == nil {
return true, 0
}
tx, err := db.Begin(true)
if err != nil {
log.Error("stats: opening transaction: %s", err)
return true, 0
}
s.curr = newUnit(id)
isCommitable := true
ferr := ptr.serialize().flushUnitToDB(tx, ptr.id)
if ferr != nil {
log.Error("stats: flushing unit: %s", ferr)
isCommitable = false
}
derr := tx.DeleteBucket(idToUnitName(id - limit))
if derr != nil {
log.Error("stats: deleting unit: %s", derr)
if !errors.Is(derr, bbolt.ErrBucketNotFound) {
isCommitable = false
}
}
err = finishTxn(tx, isCommitable)
if err != nil {
log.Error("stats: %s", err)
}
return true, 0
}
// periodicFlush checks and flushes the unit to the database if the freshly
// generated unit ID differs from the current's ID. Flushing process includes:
// - swapping the current unit with the new empty one;
// - writing the current unit to the database;
// - removing the stale unit from the database.
func (s *StatsCtx) periodicFlush() {
for cont, sleepFor := true, time.Duration(0); cont; time.Sleep(sleepFor) {
cont, sleepFor = s.flush()
}
log.Debug("periodic flushing finished")
}
func (s *StatsCtx) setLimit(limitDays int) {
atomic.StoreUint32(&s.limitHours, uint32(24*limitDays))
if limitDays == 0 {
if err := s.clear(); err != nil {
log.Error("stats: %s", err)
}
}
log.Debug("stats: set limit: %d days", limitDays)
}
// Reset counters and clear database
func (s *StatsCtx) clear() (err error) {
defer func() { err = errors.Annotate(err, "clearing: %w") }()
db := s.swapDatabase(nil)
if db != nil {
var tx *bbolt.Tx
tx, err = db.Begin(true)
if err != nil {
log.Error("stats: opening a transaction: %s", err)
} else if err = finishTxn(tx, false); err != nil {
// Don't wrap the error since it's informative enough as is.
return err
}
// Active transactions will continue using database, but new ones won't
// be created.
err = db.Close()
if err != nil {
return fmt.Errorf("closing database: %w", err)
}
// All active transactions are now closed.
log.Debug("stats: database closed")
}
err = os.Remove(s.filename)
if err != nil {
log.Error("stats: %s", err)
}
err = s.openDB()
if err != nil {
log.Error("stats: opening database: %s", err)
}
// Use defer to unlock the mutex as soon as possible.
defer log.Debug("stats: cleared")
s.currMu.Lock()
defer s.currMu.Unlock()
s.curr = newUnit(s.unitIDGen())
return nil
}
func (s *StatsCtx) loadUnits(limit uint32) (units []*unitDB, firstID uint32) {
db := s.database()
if db == nil {
return nil, 0
}
// Use writable transaction to ensure any ongoing writable transaction is
// taken into account.
tx, err := db.Begin(true)
if err != nil {
log.Error("stats: opening transaction: %s", err)
return nil, 0
}
s.currMu.RLock()
defer s.currMu.RUnlock()
cur := s.curr
var curID uint32
if cur != nil {
curID = cur.id
} else {
curID = s.unitIDGen()
}
// Per-hour units.
units = make([]*unitDB, 0, limit)
firstID = curID - limit + 1
for i := firstID; i != curID; i++ {
u := loadUnitFromDB(tx, i)
if u == nil {
u = &unitDB{NResult: make([]uint64, resultLast)}
}
units = append(units, u)
}
err = finishTxn(tx, false)
if err != nil {
log.Error("stats: %s", err)
} </s> remove // withRecovered turns the value recovered from panic if any into an error and
// combines it with the one pointed by orig. orig must be non-nil.
func withRecovered(orig *error) {
p := recover()
if p == nil {
return
}
var err error
switch p := p.(type) {
case error:
err = fmt.Errorf("panic: %w", p)
default:
err = fmt.Errorf("panic: recovered value of type %[1]T: %[1]v", p)
}
*orig = errors.WithDeferred(*orig, err)
}
// isEnabled is a helper that check if the statistics collecting is enabled.
func (s *StatsCtx) isEnabled() (ok bool) {
return atomic.LoadUint32(&s.limitHours) != 0
}
// New creates s from conf and properly initializes it. Don't use s before
// calling it's Start method.
func New(conf Config) (s *StatsCtx, err error) {
defer withRecovered(&err)
s = &StatsCtx{
currMu: &sync.Mutex{},
dbMu: &sync.Mutex{},
filename: conf.Filename,
configModified: conf.ConfigModified,
httpRegister: conf.HTTPRegister,
}
if s.limitHours = conf.LimitDays * 24; !checkInterval(conf.LimitDays) {
s.limitHours = 24
}
if s.unitIDGen = newUnitID; conf.UnitID != nil {
s.unitIDGen = conf.UnitID
}
if err = s.dbOpen(); err != nil {
return nil, fmt.Errorf("opening database: %w", err)
}
id := s.unitIDGen()
tx := beginTxn(s.db, true)
var udb *unitDB
if tx != nil {
log.Tracef("Deleting old units...")
firstID := id - s.limitHours - 1
unitDel := 0
err = tx.ForEach(newBucketWalker(tx, &unitDel, firstID))
if err != nil && !errors.Is(err, errStop) {
log.Debug("stats: deleting units: %s", err)
}
udb = s.loadUnitFromDB(tx, id)
if unitDel != 0 {
s.commitTxn(tx)
} else {
err = tx.Rollback()
if err != nil {
log.Debug("rolling back: %s", err)
}
}
}
u := newUnit(id)
// This use of deserialize is safe since the accessed unit has just been
// created.
u.deserialize(udb)
s.curr = u
log.Debug("stats: initialized")
return s, nil
}
// TODO(a.garipov): See if this is actually necessary. Looks like a rather
// bizarre solution.
const errStop errors.Error = "stop iteration"
// newBucketWalker returns a new bucket walker that deletes old units. The
// integer that unitDelPtr points to is incremented for every successful
// deletion. If the bucket isn't deleted, f returns errStop.
func newBucketWalker(
tx *bbolt.Tx,
unitDelPtr *int,
firstID uint32,
) (f func(name []byte, b *bbolt.Bucket) (err error)) {
return func(name []byte, _ *bbolt.Bucket) (err error) {
nameID, ok := unitNameToID(name)
if !ok || nameID < firstID {
err = tx.DeleteBucket(name)
if err != nil {
log.Debug("stats: tx.DeleteBucket: %s", err)
return nil
}
log.Debug("stats: deleted unit %d (name %x)", nameID, name)
*unitDelPtr++
return nil
}
return errStop
}
}
// Start makes s process the incoming data.
func (s *StatsCtx) Start() {
s.initWeb()
go s.periodicFlush()
}
// checkInterval returns true if days is valid to be used as statistics
// retention interval. The valid values are 0, 1, 7, 30 and 90.
func checkInterval(days uint32) (ok bool) {
return days == 0 || days == 1 || days == 7 || days == 30 || days == 90
}
// dbOpen returns an error if the database can't be opened from the specified
// file. It's safe for concurrent use.
func (s *StatsCtx) dbOpen() (err error) {
log.Tracef("db.Open...")
s.dbMu.Lock()
defer s.dbMu.Unlock()
s.db, err = bbolt.Open(s.filename, 0o644, nil)
if err != nil {
log.Error("stats: open DB: %s: %s", s.filename, err)
if err.Error() == "invalid argument" {
log.Error("AdGuard Home cannot be initialized due to an incompatible file system.\nPlease read the explanation here: https://github.com/AdguardTeam/AdGuardHome/wiki/Getting-Started#limitations")
}
return err
}
log.Tracef("db.Open")
return nil
}
</s> add </s> remove func (s *StatsCtx) setLimit(limitDays int) {
atomic.StoreUint32(&s.limitHours, uint32(24*limitDays))
if limitDays == 0 {
s.clear()
}
log.Debug("stats: set limit: %d days", limitDays)
}
func (s *StatsCtx) WriteDiskConfig(dc *DiskConfig) {
dc.Interval = atomic.LoadUint32(&s.limitHours) / 24
}
func (s *StatsCtx) Close() {
u := s.swapCurrent(nil)
db := s.database()
if tx := beginTxn(db, true); tx != nil {
udb := u.serialize()
if flushUnitToDB(tx, u.id, udb) {
s.commitTxn(tx)
} else {
_ = tx.Rollback()
}
}
if db != nil {
log.Tracef("db.Close...")
_ = db.Close()
log.Tracef("db.Close")
}
log.Debug("stats: closed")
}
// Reset counters and clear database
func (s *StatsCtx) clear() {
db := s.database()
tx := beginTxn(db, true)
if tx != nil {
_ = s.swapDatabase(nil)
_ = tx.Rollback()
// the active transactions can continue using database,
// but no new transactions will be opened
_ = db.Close()
log.Tracef("db.Close")
// all active transactions are now closed
}
u := newUnit(s.unitIDGen())
_ = s.swapCurrent(u)
err := os.Remove(s.filename)
if err != nil {
log.Error("os.Remove: %s", err)
}
_ = s.dbOpen()
log.Debug("stats: cleared")
}
func (s *StatsCtx) Update(e Entry) {
if !s.isEnabled() {
return
}
if e.Result == 0 ||
e.Result >= resultLast ||
e.Domain == "" ||
e.Client == "" {
return
}
clientID := e.Client
if ip := net.ParseIP(clientID); ip != nil {
clientID = ip.String()
}
u := s.ongoing()
if u == nil {
return
}
u.mu.Lock()
defer u.mu.Unlock()
u.nResult[e.Result]++
if e.Result == RNotFiltered {
u.domains[e.Domain]++
} else {
u.blockedDomains[e.Domain]++
}
u.clients[clientID]++
u.timeSum += uint64(e.Time)
u.nTotal++
}
func (s *StatsCtx) loadUnits(limit uint32) ([]*unitDB, uint32) {
tx := beginTxn(s.database(), false)
if tx == nil {
return nil, 0
}
cur := s.ongoing()
var curID uint32
if cur != nil {
curID = atomic.LoadUint32(&cur.id)
} else {
curID = s.unitIDGen()
}
// Per-hour units.
units := []*unitDB{}
firstID := curID - limit + 1
for i := firstID; i != curID; i++ {
u := s.loadUnitFromDB(tx, i)
if u == nil {
u = &unitDB{}
u.NResult = make([]uint64, resultLast)
}
units = append(units, u)
}
_ = tx.Rollback()
if cur != nil {
units = append(units, cur.serialize())
}
if len(units) != int(limit) {
log.Fatalf("len(units) != limit: %d %d", len(units), limit)
}
return units, firstID
}
</s> add </s> remove func flushUnitToDB(tx *bbolt.Tx, id uint32, udb *unitDB) bool {
log.Tracef("Flushing unit %d", id)
</s> add // add adds new data to u. It's safe for concurrent use.
func (u *unit) add(res Result, domain, cli string, dur uint64) {
u.nResult[res]++
if res == RNotFiltered {
u.domains[domain]++
} else {
u.blockedDomains[domain]++
}
u.clients[cli]++
u.timeSum += dur
u.nTotal++
}
// flushUnitToDB puts udb to the database at id.
func (udb *unitDB) flushUnitToDB(tx *bbolt.Tx, id uint32) (err error) {
log.Debug("stats: flushing unit with id %d and total of %d", id, udb.NTotal) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
return err | <mask>
<mask> return
<mask> }
<mask>
<mask> log.Tracef("transaction has been committed")
<mask> }
<mask>
<mask> // bucketNameLen is the length of a bucket, a 64-bit unsigned integer.
<mask> //
<mask> // TODO(a.garipov): Find out why a 64-bit integer is used when IDs seem to
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove // newUnit allocates the new *unit.
func newUnit(id uint32) (u *unit) {
return &unit{
mu: &sync.RWMutex{},
id: id,
nResult: make([]uint64, resultLast),
domains: make(map[string]uint64),
blockedDomains: make(map[string]uint64),
clients: make(map[string]uint64),
}
}
// beginTxn opens a new database transaction. If writable is true, the
// transaction will be opened for writing, and for reading otherwise. It
// returns nil if the transaction can't be created.
func beginTxn(db *bbolt.DB, writable bool) (tx *bbolt.Tx) {
if db == nil {
return nil
}
log.Tracef("opening a database transaction")
tx, err := db.Begin(writable)
if err != nil {
log.Error("stats: opening a transaction: %s", err)
return nil
}
log.Tracef("transaction has been opened")
return tx
}
// commitTxn applies the changes made in tx to the database.
func (s *StatsCtx) commitTxn(tx *bbolt.Tx) {
err := tx.Commit()
if err != nil {
log.Error("stats: committing a transaction: %s", err)
return
</s> add func finishTxn(tx *bbolt.Tx, commit bool) (err error) {
if commit {
err = errors.Annotate(tx.Commit(), "committing: %w")
} else {
err = errors.Annotate(tx.Rollback(), "rolling back: %w") </s> remove // TimeUnit is the unit of measuring time while aggregating the statistics.
type TimeUnit int
</s> add // StatsCtx collects the statistics and flushes it to the database. Its default
// flushing interval is one hour.
//
// TODO(e.burkov): Use atomic.Pointer for accessing db in go1.19.
type StatsCtx struct {
// limitHours is the maximum number of hours to collect statistics into the
// current unit.
//
// It is of type uint32 to be accessed by atomic. It's arranged at the
// beginning of the structure to keep 64-bit alignment.
limitHours uint32 </s> remove // Domain is the domain name requested.
Domain string
</s> add if cur != nil {
units = append(units, cur.serialize())
} </s> remove // TODO(e.burkov): Use atomic.Pointer for accessing curr and db in go1.19.
type StatsCtx struct {
// currMu protects the current unit.
currMu *sync.Mutex
// curr is the actual statistics collection result.
curr *unit
// dbMu protects db.
dbMu *sync.Mutex
// db is the opened statistics database, if any.
db *bbolt.DB
// unitIDGen is the function that generates an identifier for the current
// unit. It's here for only testing purposes.
unitIDGen UnitIDGenFunc
// httpRegister is used to set HTTP handlers.
httpRegister aghhttp.RegisterFunc
// configModified is called whenever the configuration is modified via web
// interface.
configModified func()
// filename is the name of database file.
filename string
// limitHours is the maximum number of hours to collect statistics into the
// current unit.
limitHours uint32
</s> add // TODO(e.burkov): Think about better naming.
const (
RNotFiltered Result = iota + 1
RFiltered
RSafeBrowsing
RSafeSearch
RParental
resultLast = RParental + 1
)
// Entry is a statistics data entry.
type Entry struct {
// Clients is the client's primary ID.
//
// TODO(a.garipov): Make this a {net.IP, string} enum?
Client string
// Domain is the domain name requested.
Domain string
// Result is the result of processing the request.
Result Result
// Time is the duration of the request processing in milliseconds.
Time uint32 </s> remove // withRecovered turns the value recovered from panic if any into an error and
// combines it with the one pointed by orig. orig must be non-nil.
func withRecovered(orig *error) {
p := recover()
if p == nil {
return
}
var err error
switch p := p.(type) {
case error:
err = fmt.Errorf("panic: %w", p)
default:
err = fmt.Errorf("panic: recovered value of type %[1]T: %[1]v", p)
}
*orig = errors.WithDeferred(*orig, err)
}
// isEnabled is a helper that check if the statistics collecting is enabled.
func (s *StatsCtx) isEnabled() (ok bool) {
return atomic.LoadUint32(&s.limitHours) != 0
}
// New creates s from conf and properly initializes it. Don't use s before
// calling it's Start method.
func New(conf Config) (s *StatsCtx, err error) {
defer withRecovered(&err)
s = &StatsCtx{
currMu: &sync.Mutex{},
dbMu: &sync.Mutex{},
filename: conf.Filename,
configModified: conf.ConfigModified,
httpRegister: conf.HTTPRegister,
}
if s.limitHours = conf.LimitDays * 24; !checkInterval(conf.LimitDays) {
s.limitHours = 24
}
if s.unitIDGen = newUnitID; conf.UnitID != nil {
s.unitIDGen = conf.UnitID
}
if err = s.dbOpen(); err != nil {
return nil, fmt.Errorf("opening database: %w", err)
}
id := s.unitIDGen()
tx := beginTxn(s.db, true)
var udb *unitDB
if tx != nil {
log.Tracef("Deleting old units...")
firstID := id - s.limitHours - 1
unitDel := 0
err = tx.ForEach(newBucketWalker(tx, &unitDel, firstID))
if err != nil && !errors.Is(err, errStop) {
log.Debug("stats: deleting units: %s", err)
}
udb = s.loadUnitFromDB(tx, id)
if unitDel != 0 {
s.commitTxn(tx)
} else {
err = tx.Rollback()
if err != nil {
log.Debug("rolling back: %s", err)
}
}
}
u := newUnit(id)
// This use of deserialize is safe since the accessed unit has just been
// created.
u.deserialize(udb)
s.curr = u
log.Debug("stats: initialized")
return s, nil
}
// TODO(a.garipov): See if this is actually necessary. Looks like a rather
// bizarre solution.
const errStop errors.Error = "stop iteration"
// newBucketWalker returns a new bucket walker that deletes old units. The
// integer that unitDelPtr points to is incremented for every successful
// deletion. If the bucket isn't deleted, f returns errStop.
func newBucketWalker(
tx *bbolt.Tx,
unitDelPtr *int,
firstID uint32,
) (f func(name []byte, b *bbolt.Bucket) (err error)) {
return func(name []byte, _ *bbolt.Bucket) (err error) {
nameID, ok := unitNameToID(name)
if !ok || nameID < firstID {
err = tx.DeleteBucket(name)
if err != nil {
log.Debug("stats: tx.DeleteBucket: %s", err)
return nil
}
log.Debug("stats: deleted unit %d (name %x)", nameID, name)
*unitDelPtr++
return nil
}
return errStop
}
}
// Start makes s process the incoming data.
func (s *StatsCtx) Start() {
s.initWeb()
go s.periodicFlush()
}
// checkInterval returns true if days is valid to be used as statistics
// retention interval. The valid values are 0, 1, 7, 30 and 90.
func checkInterval(days uint32) (ok bool) {
return days == 0 || days == 1 || days == 7 || days == 30 || days == 90
}
// dbOpen returns an error if the database can't be opened from the specified
// file. It's safe for concurrent use.
func (s *StatsCtx) dbOpen() (err error) {
log.Tracef("db.Open...")
s.dbMu.Lock()
defer s.dbMu.Unlock()
s.db, err = bbolt.Open(s.filename, 0o644, nil)
if err != nil {
log.Error("stats: open DB: %s: %s", s.filename, err)
if err.Error() == "invalid argument" {
log.Error("AdGuard Home cannot be initialized due to an incompatible file system.\nPlease read the explanation here: https://github.com/AdguardTeam/AdGuardHome/wiki/Getting-Started#limitations")
}
return err
}
log.Tracef("db.Open")
return nil
}
</s> add | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
func convertMapToSlice(m map[string]uint64, max int) (s []countPair) {
s = make([]countPair, 0, len(m))
for k, v := range m {
s = append(s, countPair{Name: k, Count: v}) | <mask>
<mask> return uint32(binary.BigEndian.Uint64(name)), true
<mask> }
<mask>
<mask> // Flush the current unit to DB and delete an old unit when a new hour is started
<mask> // If a unit must be flushed:
<mask> // . lock DB
<mask> // . atomically set a new empty unit as the current one and get the old unit
<mask> // This is important to do it inside DB lock, so the reader won't get inconsistent results.
<mask> // . write the unit to DB
<mask> // . remove the stale unit from DB
<mask> // . unlock DB
<mask> func (s *StatsCtx) periodicFlush() {
<mask> for ptr := s.ongoing(); ptr != nil; ptr = s.ongoing() {
<mask> id := s.unitIDGen()
<mask> // Access the unit's ID with atomic to avoid locking the whole unit.
<mask> if !s.isEnabled() || atomic.LoadUint32(&ptr.id) == id {
<mask> time.Sleep(time.Second)
<mask>
<mask> continue
<mask> }
<mask>
<mask> tx := beginTxn(s.database(), true)
<mask>
<mask> nu := newUnit(id)
<mask> u := s.swapCurrent(nu)
<mask> udb := u.serialize()
<mask>
<mask> if tx == nil {
<mask> continue
<mask> }
<mask>
<mask> flushOK := flushUnitToDB(tx, u.id, udb)
<mask> delOK := s.deleteUnit(tx, id-atomic.LoadUint32(&s.limitHours))
<mask> if flushOK || delOK {
<mask> s.commitTxn(tx)
<mask> } else {
<mask> _ = tx.Rollback()
<mask> }
<mask> }
<mask>
<mask> log.Tracef("periodicFlush() exited")
<mask> }
<mask>
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove func (s *StatsCtx) setLimit(limitDays int) {
atomic.StoreUint32(&s.limitHours, uint32(24*limitDays))
if limitDays == 0 {
s.clear()
}
log.Debug("stats: set limit: %d days", limitDays)
}
func (s *StatsCtx) WriteDiskConfig(dc *DiskConfig) {
dc.Interval = atomic.LoadUint32(&s.limitHours) / 24
}
func (s *StatsCtx) Close() {
u := s.swapCurrent(nil)
db := s.database()
if tx := beginTxn(db, true); tx != nil {
udb := u.serialize()
if flushUnitToDB(tx, u.id, udb) {
s.commitTxn(tx)
} else {
_ = tx.Rollback()
}
}
if db != nil {
log.Tracef("db.Close...")
_ = db.Close()
log.Tracef("db.Close")
}
log.Debug("stats: closed")
}
// Reset counters and clear database
func (s *StatsCtx) clear() {
db := s.database()
tx := beginTxn(db, true)
if tx != nil {
_ = s.swapDatabase(nil)
_ = tx.Rollback()
// the active transactions can continue using database,
// but no new transactions will be opened
_ = db.Close()
log.Tracef("db.Close")
// all active transactions are now closed
}
u := newUnit(s.unitIDGen())
_ = s.swapCurrent(u)
err := os.Remove(s.filename)
if err != nil {
log.Error("os.Remove: %s", err)
}
_ = s.dbOpen()
log.Debug("stats: cleared")
}
func (s *StatsCtx) Update(e Entry) {
if !s.isEnabled() {
return
}
if e.Result == 0 ||
e.Result >= resultLast ||
e.Domain == "" ||
e.Client == "" {
return
}
clientID := e.Client
if ip := net.ParseIP(clientID); ip != nil {
clientID = ip.String()
}
u := s.ongoing()
if u == nil {
return
}
u.mu.Lock()
defer u.mu.Unlock()
u.nResult[e.Result]++
if e.Result == RNotFiltered {
u.domains[e.Domain]++
} else {
u.blockedDomains[e.Domain]++
}
u.clients[clientID]++
u.timeSum += uint64(e.Time)
u.nTotal++
}
func (s *StatsCtx) loadUnits(limit uint32) ([]*unitDB, uint32) {
tx := beginTxn(s.database(), false)
if tx == nil {
return nil, 0
}
cur := s.ongoing()
var curID uint32
if cur != nil {
curID = atomic.LoadUint32(&cur.id)
} else {
curID = s.unitIDGen()
}
// Per-hour units.
units := []*unitDB{}
firstID := curID - limit + 1
for i := firstID; i != curID; i++ {
u := s.loadUnitFromDB(tx, i)
if u == nil {
u = &unitDB{}
u.NResult = make([]uint64, resultLast)
}
units = append(units, u)
}
_ = tx.Rollback()
if cur != nil {
units = append(units, cur.serialize())
}
if len(units) != int(limit) {
log.Fatalf("len(units) != limit: %d %d", len(units), limit)
}
return units, firstID
}
</s> add </s> remove // Entry is a statistics data entry.
type Entry struct {
// Clients is the client's primary ID.
//
// TODO(a.garipov): Make this a {net.IP, string} enum?
Client string
</s> add // httpRegister is used to set HTTP handlers.
httpRegister aghhttp.RegisterFunc
// configModified is called whenever the configuration is modified via web
// interface.
configModified func()
// filename is the name of database file.
filename string
}
var _ Interface = &StatsCtx{}
// New creates s from conf and properly initializes it. Don't use s before
// calling it's Start method.
func New(conf Config) (s *StatsCtx, err error) {
defer withRecovered(&err)
s = &StatsCtx{
currMu: &sync.RWMutex{},
dbMu: &sync.Mutex{},
filename: conf.Filename,
configModified: conf.ConfigModified,
httpRegister: conf.HTTPRegister,
}
if s.limitHours = conf.LimitDays * 24; !checkInterval(conf.LimitDays) {
s.limitHours = 24
}
if s.unitIDGen = newUnitID; conf.UnitID != nil {
s.unitIDGen = conf.UnitID
}
// TODO(e.burkov): Move the code below to the Start method.
err = s.openDB()
if err != nil {
return nil, fmt.Errorf("opening database: %w", err)
}
var udb *unitDB
id := s.unitIDGen()
tx, err := s.db.Begin(true)
if err != nil {
return nil, fmt.Errorf("stats: opening a transaction: %w", err)
}
deleted := deleteOldUnits(tx, id-s.limitHours-1)
udb = loadUnitFromDB(tx, id)
err = finishTxn(tx, deleted > 0)
if err != nil {
log.Error("stats: %s", err)
}
s.curr = newUnit(id)
s.curr.deserialize(udb)
log.Debug("stats: initialized")
return s, nil
}
// withRecovered turns the value recovered from panic if any into an error and
// combines it with the one pointed by orig. orig must be non-nil.
func withRecovered(orig *error) {
p := recover()
if p == nil {
return
}
var err error
switch p := p.(type) {
case error:
err = fmt.Errorf("panic: %w", p)
default:
err = fmt.Errorf("panic: recovered value of type %[1]T: %[1]v", p)
}
*orig = errors.WithDeferred(*orig, err)
}
// Start implements the Interface interface for *StatsCtx.
func (s *StatsCtx) Start() {
s.initWeb()
go s.periodicFlush()
}
// Close implements the io.Closer interface for *StatsCtx.
func (s *StatsCtx) Close() (err error) {
defer func() { err = errors.Annotate(err, "stats: closing: %w") }()
db := s.swapDatabase(nil)
if db == nil {
return nil
}
defer func() {
cerr := db.Close()
if cerr == nil {
log.Debug("stats: database closed")
}
err = errors.WithDeferred(err, cerr)
}()
tx, err := db.Begin(true)
if err != nil {
return fmt.Errorf("opening transaction: %w", err)
}
defer func() { err = errors.WithDeferred(err, finishTxn(tx, err == nil)) }()
s.currMu.RLock()
defer s.currMu.RUnlock()
udb := s.curr.serialize()
return udb.flushUnitToDB(tx, s.curr.id)
}
// Update implements the Interface interface for *StatsCtx.
func (s *StatsCtx) Update(e Entry) {
if atomic.LoadUint32(&s.limitHours) == 0 {
return
}
if e.Result == 0 || e.Result >= resultLast || e.Domain == "" || e.Client == "" {
log.Debug("stats: malformed entry")
return
}
s.currMu.Lock()
defer s.currMu.Unlock()
if s.curr == nil {
log.Error("stats: current unit is nil")
return
}
clientID := e.Client
if ip := net.ParseIP(clientID); ip != nil {
clientID = ip.String()
}
s.curr.add(e.Result, e.Domain, clientID, uint64(e.Time))
}
// WriteDiskConfig implements the Interface interface for *StatsCtx.
func (s *StatsCtx) WriteDiskConfig(dc *DiskConfig) {
dc.Interval = atomic.LoadUint32(&s.limitHours) / 24
}
// TopClientsIP implements the Interface interface for *StatsCtx.
func (s *StatsCtx) TopClientsIP(maxCount uint) (ips []net.IP) {
limit := atomic.LoadUint32(&s.limitHours)
if limit == 0 {
return nil
}
units, _ := s.loadUnits(limit)
if units == nil {
return nil
}
// Collect data for all the clients to sort and crop it afterwards.
m := map[string]uint64{}
for _, u := range units {
for _, it := range u.Clients {
m[it.Name] += it.Count
}
}
a := convertMapToSlice(m, int(maxCount))
ips = []net.IP{}
for _, it := range a {
ip := net.ParseIP(it.Name)
if ip != nil {
ips = append(ips, ip)
}
}
return ips
}
// database returns the database if it's opened. It's safe for concurrent use.
func (s *StatsCtx) database() (db *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
return s.db
}
// swapDatabase swaps the database with another one and returns it. It's safe
// for concurrent use.
func (s *StatsCtx) swapDatabase(with *bbolt.DB) (old *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
old, s.db = s.db, with
return old
}
// deleteOldUnits walks the buckets available to tx and deletes old units. It
// returns the number of deletions performed.
func deleteOldUnits(tx *bbolt.Tx, firstID uint32) (deleted int) {
log.Debug("stats: deleting old units until id %d", firstID)
// TODO(a.garipov): See if this is actually necessary. Looks like a rather
// bizarre solution.
const errStop errors.Error = "stop iteration"
walk := func(name []byte, _ *bbolt.Bucket) (err error) {
nameID, ok := unitNameToID(name)
if ok && nameID >= firstID {
return errStop
}
err = tx.DeleteBucket(name)
if err != nil {
log.Debug("stats: deleting bucket: %s", err)
return nil
}
log.Debug("stats: deleted unit %d (name %x)", nameID, name)
deleted++
return nil
}
err := tx.ForEach(walk)
if err != nil && !errors.Is(err, errStop) {
log.Debug("stats: deleting units: %s", err)
}
return deleted
}
// openDB returns an error if the database can't be opened from the specified
// file. It's safe for concurrent use.
func (s *StatsCtx) openDB() (err error) {
log.Debug("stats: opening database")
var db *bbolt.DB
db, err = bbolt.Open(s.filename, 0o644, nil)
if err != nil {
if err.Error() == "invalid argument" {
log.Error("AdGuard Home cannot be initialized due to an incompatible file system.\nPlease read the explanation here: https://github.com/AdguardTeam/AdGuardHome/wiki/Getting-Started#limitations")
}
return err
}
// Use defer to unlock the mutex as soon as possible.
defer log.Debug("stats: database opened")
s.dbMu.Lock()
defer s.dbMu.Unlock()
s.db = db
return nil
}
func (s *StatsCtx) flush() (cont bool, sleepFor time.Duration) {
id := s.unitIDGen()
s.currMu.Lock()
defer s.currMu.Unlock()
ptr := s.curr
if ptr == nil {
return false, 0
}
limit := atomic.LoadUint32(&s.limitHours)
if limit == 0 || ptr.id == id {
return true, time.Second
}
db := s.database()
if db == nil {
return true, 0
}
tx, err := db.Begin(true)
if err != nil {
log.Error("stats: opening transaction: %s", err)
return true, 0
}
s.curr = newUnit(id)
isCommitable := true
ferr := ptr.serialize().flushUnitToDB(tx, ptr.id)
if ferr != nil {
log.Error("stats: flushing unit: %s", ferr)
isCommitable = false
}
derr := tx.DeleteBucket(idToUnitName(id - limit))
if derr != nil {
log.Error("stats: deleting unit: %s", derr)
if !errors.Is(derr, bbolt.ErrBucketNotFound) {
isCommitable = false
}
}
err = finishTxn(tx, isCommitable)
if err != nil {
log.Error("stats: %s", err)
}
return true, 0
}
// periodicFlush checks and flushes the unit to the database if the freshly
// generated unit ID differs from the current's ID. Flushing process includes:
// - swapping the current unit with the new empty one;
// - writing the current unit to the database;
// - removing the stale unit from the database.
func (s *StatsCtx) periodicFlush() {
for cont, sleepFor := true, time.Duration(0); cont; time.Sleep(sleepFor) {
cont, sleepFor = s.flush()
}
log.Debug("periodic flushing finished")
}
func (s *StatsCtx) setLimit(limitDays int) {
atomic.StoreUint32(&s.limitHours, uint32(24*limitDays))
if limitDays == 0 {
if err := s.clear(); err != nil {
log.Error("stats: %s", err)
}
}
log.Debug("stats: set limit: %d days", limitDays)
}
// Reset counters and clear database
func (s *StatsCtx) clear() (err error) {
defer func() { err = errors.Annotate(err, "clearing: %w") }()
db := s.swapDatabase(nil)
if db != nil {
var tx *bbolt.Tx
tx, err = db.Begin(true)
if err != nil {
log.Error("stats: opening a transaction: %s", err)
} else if err = finishTxn(tx, false); err != nil {
// Don't wrap the error since it's informative enough as is.
return err
}
// Active transactions will continue using database, but new ones won't
// be created.
err = db.Close()
if err != nil {
return fmt.Errorf("closing database: %w", err)
}
// All active transactions are now closed.
log.Debug("stats: database closed")
}
err = os.Remove(s.filename)
if err != nil {
log.Error("stats: %s", err)
}
err = s.openDB()
if err != nil {
log.Error("stats: opening database: %s", err)
}
// Use defer to unlock the mutex as soon as possible.
defer log.Debug("stats: cleared")
s.currMu.Lock()
defer s.currMu.Unlock()
s.curr = newUnit(s.unitIDGen())
return nil
}
func (s *StatsCtx) loadUnits(limit uint32) (units []*unitDB, firstID uint32) {
db := s.database()
if db == nil {
return nil, 0
}
// Use writable transaction to ensure any ongoing writable transaction is
// taken into account.
tx, err := db.Begin(true)
if err != nil {
log.Error("stats: opening transaction: %s", err)
return nil, 0
}
s.currMu.RLock()
defer s.currMu.RUnlock()
cur := s.curr
var curID uint32
if cur != nil {
curID = cur.id
} else {
curID = s.unitIDGen()
}
// Per-hour units.
units = make([]*unitDB, 0, limit)
firstID = curID - limit + 1
for i := firstID; i != curID; i++ {
u := loadUnitFromDB(tx, i)
if u == nil {
u = &unitDB{NResult: make([]uint64, resultLast)}
}
units = append(units, u)
}
err = finishTxn(tx, false)
if err != nil {
log.Error("stats: %s", err)
} </s> remove // withRecovered turns the value recovered from panic if any into an error and
// combines it with the one pointed by orig. orig must be non-nil.
func withRecovered(orig *error) {
p := recover()
if p == nil {
return
}
var err error
switch p := p.(type) {
case error:
err = fmt.Errorf("panic: %w", p)
default:
err = fmt.Errorf("panic: recovered value of type %[1]T: %[1]v", p)
}
*orig = errors.WithDeferred(*orig, err)
}
// isEnabled is a helper that check if the statistics collecting is enabled.
func (s *StatsCtx) isEnabled() (ok bool) {
return atomic.LoadUint32(&s.limitHours) != 0
}
// New creates s from conf and properly initializes it. Don't use s before
// calling it's Start method.
func New(conf Config) (s *StatsCtx, err error) {
defer withRecovered(&err)
s = &StatsCtx{
currMu: &sync.Mutex{},
dbMu: &sync.Mutex{},
filename: conf.Filename,
configModified: conf.ConfigModified,
httpRegister: conf.HTTPRegister,
}
if s.limitHours = conf.LimitDays * 24; !checkInterval(conf.LimitDays) {
s.limitHours = 24
}
if s.unitIDGen = newUnitID; conf.UnitID != nil {
s.unitIDGen = conf.UnitID
}
if err = s.dbOpen(); err != nil {
return nil, fmt.Errorf("opening database: %w", err)
}
id := s.unitIDGen()
tx := beginTxn(s.db, true)
var udb *unitDB
if tx != nil {
log.Tracef("Deleting old units...")
firstID := id - s.limitHours - 1
unitDel := 0
err = tx.ForEach(newBucketWalker(tx, &unitDel, firstID))
if err != nil && !errors.Is(err, errStop) {
log.Debug("stats: deleting units: %s", err)
}
udb = s.loadUnitFromDB(tx, id)
if unitDel != 0 {
s.commitTxn(tx)
} else {
err = tx.Rollback()
if err != nil {
log.Debug("rolling back: %s", err)
}
}
}
u := newUnit(id)
// This use of deserialize is safe since the accessed unit has just been
// created.
u.deserialize(udb)
s.curr = u
log.Debug("stats: initialized")
return s, nil
}
// TODO(a.garipov): See if this is actually necessary. Looks like a rather
// bizarre solution.
const errStop errors.Error = "stop iteration"
// newBucketWalker returns a new bucket walker that deletes old units. The
// integer that unitDelPtr points to is incremented for every successful
// deletion. If the bucket isn't deleted, f returns errStop.
func newBucketWalker(
tx *bbolt.Tx,
unitDelPtr *int,
firstID uint32,
) (f func(name []byte, b *bbolt.Bucket) (err error)) {
return func(name []byte, _ *bbolt.Bucket) (err error) {
nameID, ok := unitNameToID(name)
if !ok || nameID < firstID {
err = tx.DeleteBucket(name)
if err != nil {
log.Debug("stats: tx.DeleteBucket: %s", err)
return nil
}
log.Debug("stats: deleted unit %d (name %x)", nameID, name)
*unitDelPtr++
return nil
}
return errStop
}
}
// Start makes s process the incoming data.
func (s *StatsCtx) Start() {
s.initWeb()
go s.periodicFlush()
}
// checkInterval returns true if days is valid to be used as statistics
// retention interval. The valid values are 0, 1, 7, 30 and 90.
func checkInterval(days uint32) (ok bool) {
return days == 0 || days == 1 || days == 7 || days == 30 || days == 90
}
// dbOpen returns an error if the database can't be opened from the specified
// file. It's safe for concurrent use.
func (s *StatsCtx) dbOpen() (err error) {
log.Tracef("db.Open...")
s.dbMu.Lock()
defer s.dbMu.Unlock()
s.db, err = bbolt.Open(s.filename, 0o644, nil)
if err != nil {
log.Error("stats: open DB: %s: %s", s.filename, err)
if err.Error() == "invalid argument" {
log.Error("AdGuard Home cannot be initialized due to an incompatible file system.\nPlease read the explanation here: https://github.com/AdguardTeam/AdGuardHome/wiki/Getting-Started#limitations")
}
return err
}
log.Tracef("db.Open")
return nil
}
</s> add </s> remove log.Tracef("periodicFlush() exited")
}
// deleteUnit removes the unit by it's id from the database the tx belongs to.
func (s *StatsCtx) deleteUnit(tx *bbolt.Tx, id uint32) bool {
err := tx.DeleteBucket(idToUnitName(id))
if err != nil {
log.Tracef("stats: bolt DeleteBucket: %s", err)
return false
</s> add sort.Slice(s, func(i, j int) bool {
return s[j].Count < s[i].Count
})
if max > len(s) {
max = len(s) </s> remove func flushUnitToDB(tx *bbolt.Tx, id uint32, udb *unitDB) bool {
log.Tracef("Flushing unit %d", id)
</s> add // add adds new data to u. It's safe for concurrent use.
func (u *unit) add(res Result, domain, cli string, dur uint64) {
u.nResult[res]++
if res == RNotFiltered {
u.domains[domain]++
} else {
u.blockedDomains[domain]++
}
u.clients[cli]++
u.timeSum += dur
u.nTotal++
}
// flushUnitToDB puts udb to the database at id.
func (udb *unitDB) flushUnitToDB(tx *bbolt.Tx, id uint32) (err error) {
log.Debug("stats: flushing unit with id %d and total of %d", id, udb.NTotal) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
sort.Slice(s, func(i, j int) bool {
return s[j].Count < s[i].Count
})
if max > len(s) {
max = len(s) | <mask> _ = tx.Rollback()
<mask> }
<mask> }
<mask>
<mask> log.Tracef("periodicFlush() exited")
<mask> }
<mask>
<mask> // deleteUnit removes the unit by it's id from the database the tx belongs to.
<mask> func (s *StatsCtx) deleteUnit(tx *bbolt.Tx, id uint32) bool {
<mask> err := tx.DeleteBucket(idToUnitName(id))
<mask> if err != nil {
<mask> log.Tracef("stats: bolt DeleteBucket: %s", err)
<mask>
<mask> return false
<mask> }
<mask>
<mask> log.Debug("stats: deleted unit %d", id)
<mask>
<mask> return true
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove log.Error("bkt.Put: %s", err)
return false
}
return true
}
func (s *StatsCtx) loadUnitFromDB(tx *bbolt.Tx, id uint32) *unitDB {
bkt := tx.Bucket(idToUnitName(id))
if bkt == nil {
return nil
</s> add return fmt.Errorf("putting unit to database: %w", err) </s> remove func flushUnitToDB(tx *bbolt.Tx, id uint32, udb *unitDB) bool {
log.Tracef("Flushing unit %d", id)
</s> add // add adds new data to u. It's safe for concurrent use.
func (u *unit) add(res Result, domain, cli string, dur uint64) {
u.nResult[res]++
if res == RNotFiltered {
u.domains[domain]++
} else {
u.blockedDomains[domain]++
}
u.clients[cli]++
u.timeSum += dur
u.nTotal++
}
// flushUnitToDB puts udb to the database at id.
func (udb *unitDB) flushUnitToDB(tx *bbolt.Tx, id uint32) (err error) {
log.Debug("stats: flushing unit with id %d and total of %d", id, udb.NTotal) </s> remove // Entry is a statistics data entry.
type Entry struct {
// Clients is the client's primary ID.
//
// TODO(a.garipov): Make this a {net.IP, string} enum?
Client string
</s> add // httpRegister is used to set HTTP handlers.
httpRegister aghhttp.RegisterFunc
// configModified is called whenever the configuration is modified via web
// interface.
configModified func()
// filename is the name of database file.
filename string
}
var _ Interface = &StatsCtx{}
// New creates s from conf and properly initializes it. Don't use s before
// calling it's Start method.
func New(conf Config) (s *StatsCtx, err error) {
defer withRecovered(&err)
s = &StatsCtx{
currMu: &sync.RWMutex{},
dbMu: &sync.Mutex{},
filename: conf.Filename,
configModified: conf.ConfigModified,
httpRegister: conf.HTTPRegister,
}
if s.limitHours = conf.LimitDays * 24; !checkInterval(conf.LimitDays) {
s.limitHours = 24
}
if s.unitIDGen = newUnitID; conf.UnitID != nil {
s.unitIDGen = conf.UnitID
}
// TODO(e.burkov): Move the code below to the Start method.
err = s.openDB()
if err != nil {
return nil, fmt.Errorf("opening database: %w", err)
}
var udb *unitDB
id := s.unitIDGen()
tx, err := s.db.Begin(true)
if err != nil {
return nil, fmt.Errorf("stats: opening a transaction: %w", err)
}
deleted := deleteOldUnits(tx, id-s.limitHours-1)
udb = loadUnitFromDB(tx, id)
err = finishTxn(tx, deleted > 0)
if err != nil {
log.Error("stats: %s", err)
}
s.curr = newUnit(id)
s.curr.deserialize(udb)
log.Debug("stats: initialized")
return s, nil
}
// withRecovered turns the value recovered from panic if any into an error and
// combines it with the one pointed by orig. orig must be non-nil.
func withRecovered(orig *error) {
p := recover()
if p == nil {
return
}
var err error
switch p := p.(type) {
case error:
err = fmt.Errorf("panic: %w", p)
default:
err = fmt.Errorf("panic: recovered value of type %[1]T: %[1]v", p)
}
*orig = errors.WithDeferred(*orig, err)
}
// Start implements the Interface interface for *StatsCtx.
func (s *StatsCtx) Start() {
s.initWeb()
go s.periodicFlush()
}
// Close implements the io.Closer interface for *StatsCtx.
func (s *StatsCtx) Close() (err error) {
defer func() { err = errors.Annotate(err, "stats: closing: %w") }()
db := s.swapDatabase(nil)
if db == nil {
return nil
}
defer func() {
cerr := db.Close()
if cerr == nil {
log.Debug("stats: database closed")
}
err = errors.WithDeferred(err, cerr)
}()
tx, err := db.Begin(true)
if err != nil {
return fmt.Errorf("opening transaction: %w", err)
}
defer func() { err = errors.WithDeferred(err, finishTxn(tx, err == nil)) }()
s.currMu.RLock()
defer s.currMu.RUnlock()
udb := s.curr.serialize()
return udb.flushUnitToDB(tx, s.curr.id)
}
// Update implements the Interface interface for *StatsCtx.
func (s *StatsCtx) Update(e Entry) {
if atomic.LoadUint32(&s.limitHours) == 0 {
return
}
if e.Result == 0 || e.Result >= resultLast || e.Domain == "" || e.Client == "" {
log.Debug("stats: malformed entry")
return
}
s.currMu.Lock()
defer s.currMu.Unlock()
if s.curr == nil {
log.Error("stats: current unit is nil")
return
}
clientID := e.Client
if ip := net.ParseIP(clientID); ip != nil {
clientID = ip.String()
}
s.curr.add(e.Result, e.Domain, clientID, uint64(e.Time))
}
// WriteDiskConfig implements the Interface interface for *StatsCtx.
func (s *StatsCtx) WriteDiskConfig(dc *DiskConfig) {
dc.Interval = atomic.LoadUint32(&s.limitHours) / 24
}
// TopClientsIP implements the Interface interface for *StatsCtx.
func (s *StatsCtx) TopClientsIP(maxCount uint) (ips []net.IP) {
limit := atomic.LoadUint32(&s.limitHours)
if limit == 0 {
return nil
}
units, _ := s.loadUnits(limit)
if units == nil {
return nil
}
// Collect data for all the clients to sort and crop it afterwards.
m := map[string]uint64{}
for _, u := range units {
for _, it := range u.Clients {
m[it.Name] += it.Count
}
}
a := convertMapToSlice(m, int(maxCount))
ips = []net.IP{}
for _, it := range a {
ip := net.ParseIP(it.Name)
if ip != nil {
ips = append(ips, ip)
}
}
return ips
}
// database returns the database if it's opened. It's safe for concurrent use.
func (s *StatsCtx) database() (db *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
return s.db
}
// swapDatabase swaps the database with another one and returns it. It's safe
// for concurrent use.
func (s *StatsCtx) swapDatabase(with *bbolt.DB) (old *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
old, s.db = s.db, with
return old
}
// deleteOldUnits walks the buckets available to tx and deletes old units. It
// returns the number of deletions performed.
func deleteOldUnits(tx *bbolt.Tx, firstID uint32) (deleted int) {
log.Debug("stats: deleting old units until id %d", firstID)
// TODO(a.garipov): See if this is actually necessary. Looks like a rather
// bizarre solution.
const errStop errors.Error = "stop iteration"
walk := func(name []byte, _ *bbolt.Bucket) (err error) {
nameID, ok := unitNameToID(name)
if ok && nameID >= firstID {
return errStop
}
err = tx.DeleteBucket(name)
if err != nil {
log.Debug("stats: deleting bucket: %s", err)
return nil
}
log.Debug("stats: deleted unit %d (name %x)", nameID, name)
deleted++
return nil
}
err := tx.ForEach(walk)
if err != nil && !errors.Is(err, errStop) {
log.Debug("stats: deleting units: %s", err)
}
return deleted
}
// openDB returns an error if the database can't be opened from the specified
// file. It's safe for concurrent use.
func (s *StatsCtx) openDB() (err error) {
log.Debug("stats: opening database")
var db *bbolt.DB
db, err = bbolt.Open(s.filename, 0o644, nil)
if err != nil {
if err.Error() == "invalid argument" {
log.Error("AdGuard Home cannot be initialized due to an incompatible file system.\nPlease read the explanation here: https://github.com/AdguardTeam/AdGuardHome/wiki/Getting-Started#limitations")
}
return err
}
// Use defer to unlock the mutex as soon as possible.
defer log.Debug("stats: database opened")
s.dbMu.Lock()
defer s.dbMu.Unlock()
s.db = db
return nil
}
func (s *StatsCtx) flush() (cont bool, sleepFor time.Duration) {
id := s.unitIDGen()
s.currMu.Lock()
defer s.currMu.Unlock()
ptr := s.curr
if ptr == nil {
return false, 0
}
limit := atomic.LoadUint32(&s.limitHours)
if limit == 0 || ptr.id == id {
return true, time.Second
}
db := s.database()
if db == nil {
return true, 0
}
tx, err := db.Begin(true)
if err != nil {
log.Error("stats: opening transaction: %s", err)
return true, 0
}
s.curr = newUnit(id)
isCommitable := true
ferr := ptr.serialize().flushUnitToDB(tx, ptr.id)
if ferr != nil {
log.Error("stats: flushing unit: %s", ferr)
isCommitable = false
}
derr := tx.DeleteBucket(idToUnitName(id - limit))
if derr != nil {
log.Error("stats: deleting unit: %s", derr)
if !errors.Is(derr, bbolt.ErrBucketNotFound) {
isCommitable = false
}
}
err = finishTxn(tx, isCommitable)
if err != nil {
log.Error("stats: %s", err)
}
return true, 0
}
// periodicFlush checks and flushes the unit to the database if the freshly
// generated unit ID differs from the current's ID. Flushing process includes:
// - swapping the current unit with the new empty one;
// - writing the current unit to the database;
// - removing the stale unit from the database.
func (s *StatsCtx) periodicFlush() {
for cont, sleepFor := true, time.Duration(0); cont; time.Sleep(sleepFor) {
cont, sleepFor = s.flush()
}
log.Debug("periodic flushing finished")
}
func (s *StatsCtx) setLimit(limitDays int) {
atomic.StoreUint32(&s.limitHours, uint32(24*limitDays))
if limitDays == 0 {
if err := s.clear(); err != nil {
log.Error("stats: %s", err)
}
}
log.Debug("stats: set limit: %d days", limitDays)
}
// Reset counters and clear database
func (s *StatsCtx) clear() (err error) {
defer func() { err = errors.Annotate(err, "clearing: %w") }()
db := s.swapDatabase(nil)
if db != nil {
var tx *bbolt.Tx
tx, err = db.Begin(true)
if err != nil {
log.Error("stats: opening a transaction: %s", err)
} else if err = finishTxn(tx, false); err != nil {
// Don't wrap the error since it's informative enough as is.
return err
}
// Active transactions will continue using database, but new ones won't
// be created.
err = db.Close()
if err != nil {
return fmt.Errorf("closing database: %w", err)
}
// All active transactions are now closed.
log.Debug("stats: database closed")
}
err = os.Remove(s.filename)
if err != nil {
log.Error("stats: %s", err)
}
err = s.openDB()
if err != nil {
log.Error("stats: opening database: %s", err)
}
// Use defer to unlock the mutex as soon as possible.
defer log.Debug("stats: cleared")
s.currMu.Lock()
defer s.currMu.Unlock()
s.curr = newUnit(s.unitIDGen())
return nil
}
func (s *StatsCtx) loadUnits(limit uint32) (units []*unitDB, firstID uint32) {
db := s.database()
if db == nil {
return nil, 0
}
// Use writable transaction to ensure any ongoing writable transaction is
// taken into account.
tx, err := db.Begin(true)
if err != nil {
log.Error("stats: opening transaction: %s", err)
return nil, 0
}
s.currMu.RLock()
defer s.currMu.RUnlock()
cur := s.curr
var curID uint32
if cur != nil {
curID = cur.id
} else {
curID = s.unitIDGen()
}
// Per-hour units.
units = make([]*unitDB, 0, limit)
firstID = curID - limit + 1
for i := firstID; i != curID; i++ {
u := loadUnitFromDB(tx, i)
if u == nil {
u = &unitDB{NResult: make([]uint64, resultLast)}
}
units = append(units, u)
}
err = finishTxn(tx, false)
if err != nil {
log.Error("stats: %s", err)
} </s> remove // Flush the current unit to DB and delete an old unit when a new hour is started
// If a unit must be flushed:
// . lock DB
// . atomically set a new empty unit as the current one and get the old unit
// This is important to do it inside DB lock, so the reader won't get inconsistent results.
// . write the unit to DB
// . remove the stale unit from DB
// . unlock DB
func (s *StatsCtx) periodicFlush() {
for ptr := s.ongoing(); ptr != nil; ptr = s.ongoing() {
id := s.unitIDGen()
// Access the unit's ID with atomic to avoid locking the whole unit.
if !s.isEnabled() || atomic.LoadUint32(&ptr.id) == id {
time.Sleep(time.Second)
continue
}
tx := beginTxn(s.database(), true)
nu := newUnit(id)
u := s.swapCurrent(nu)
udb := u.serialize()
if tx == nil {
continue
}
flushOK := flushUnitToDB(tx, u.id, udb)
delOK := s.deleteUnit(tx, id-atomic.LoadUint32(&s.limitHours))
if flushOK || delOK {
s.commitTxn(tx)
} else {
_ = tx.Rollback()
}
</s> add func convertMapToSlice(m map[string]uint64, max int) (s []countPair) {
s = make([]countPair, 0, len(m))
for k, v := range m {
s = append(s, countPair{Name: k, Count: v}) </s> remove // withRecovered turns the value recovered from panic if any into an error and
// combines it with the one pointed by orig. orig must be non-nil.
func withRecovered(orig *error) {
p := recover()
if p == nil {
return
}
var err error
switch p := p.(type) {
case error:
err = fmt.Errorf("panic: %w", p)
default:
err = fmt.Errorf("panic: recovered value of type %[1]T: %[1]v", p)
}
*orig = errors.WithDeferred(*orig, err)
}
// isEnabled is a helper that check if the statistics collecting is enabled.
func (s *StatsCtx) isEnabled() (ok bool) {
return atomic.LoadUint32(&s.limitHours) != 0
}
// New creates s from conf and properly initializes it. Don't use s before
// calling it's Start method.
func New(conf Config) (s *StatsCtx, err error) {
defer withRecovered(&err)
s = &StatsCtx{
currMu: &sync.Mutex{},
dbMu: &sync.Mutex{},
filename: conf.Filename,
configModified: conf.ConfigModified,
httpRegister: conf.HTTPRegister,
}
if s.limitHours = conf.LimitDays * 24; !checkInterval(conf.LimitDays) {
s.limitHours = 24
}
if s.unitIDGen = newUnitID; conf.UnitID != nil {
s.unitIDGen = conf.UnitID
}
if err = s.dbOpen(); err != nil {
return nil, fmt.Errorf("opening database: %w", err)
}
id := s.unitIDGen()
tx := beginTxn(s.db, true)
var udb *unitDB
if tx != nil {
log.Tracef("Deleting old units...")
firstID := id - s.limitHours - 1
unitDel := 0
err = tx.ForEach(newBucketWalker(tx, &unitDel, firstID))
if err != nil && !errors.Is(err, errStop) {
log.Debug("stats: deleting units: %s", err)
}
udb = s.loadUnitFromDB(tx, id)
if unitDel != 0 {
s.commitTxn(tx)
} else {
err = tx.Rollback()
if err != nil {
log.Debug("rolling back: %s", err)
}
}
}
u := newUnit(id)
// This use of deserialize is safe since the accessed unit has just been
// created.
u.deserialize(udb)
s.curr = u
log.Debug("stats: initialized")
return s, nil
}
// TODO(a.garipov): See if this is actually necessary. Looks like a rather
// bizarre solution.
const errStop errors.Error = "stop iteration"
// newBucketWalker returns a new bucket walker that deletes old units. The
// integer that unitDelPtr points to is incremented for every successful
// deletion. If the bucket isn't deleted, f returns errStop.
func newBucketWalker(
tx *bbolt.Tx,
unitDelPtr *int,
firstID uint32,
) (f func(name []byte, b *bbolt.Bucket) (err error)) {
return func(name []byte, _ *bbolt.Bucket) (err error) {
nameID, ok := unitNameToID(name)
if !ok || nameID < firstID {
err = tx.DeleteBucket(name)
if err != nil {
log.Debug("stats: tx.DeleteBucket: %s", err)
return nil
}
log.Debug("stats: deleted unit %d (name %x)", nameID, name)
*unitDelPtr++
return nil
}
return errStop
}
}
// Start makes s process the incoming data.
func (s *StatsCtx) Start() {
s.initWeb()
go s.periodicFlush()
}
// checkInterval returns true if days is valid to be used as statistics
// retention interval. The valid values are 0, 1, 7, 30 and 90.
func checkInterval(days uint32) (ok bool) {
return days == 0 || days == 1 || days == 7 || days == 30 || days == 90
}
// dbOpen returns an error if the database can't be opened from the specified
// file. It's safe for concurrent use.
func (s *StatsCtx) dbOpen() (err error) {
log.Tracef("db.Open...")
s.dbMu.Lock()
defer s.dbMu.Unlock()
s.db, err = bbolt.Open(s.filename, 0o644, nil)
if err != nil {
log.Error("stats: open DB: %s: %s", s.filename, err)
if err.Error() == "invalid argument" {
log.Error("AdGuard Home cannot be initialized due to an incompatible file system.\nPlease read the explanation here: https://github.com/AdguardTeam/AdGuardHome/wiki/Getting-Started#limitations")
}
return err
}
log.Tracef("db.Open")
return nil
}
</s> add | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
return s[:max] | <mask>
<mask> return false
<mask> }
<mask>
<mask> log.Debug("stats: deleted unit %d", id)
<mask>
<mask> return true
<mask> }
<mask>
<mask> func convertMapToSlice(m map[string]uint64, max int) []countPair {
<mask> a := []countPair{}
<mask> for k, v := range m {
<mask> a = append(a, countPair{Name: k, Count: v})
<mask> }
<mask> less := func(i, j int) bool {
<mask> return a[j].Count < a[i].Count
<mask> }
<mask> sort.Slice(a, less)
<mask> if max > len(a) {
<mask> max = len(a)
<mask> }
<mask> return a[:max]
<mask> }
<mask>
<mask> func convertSliceToMap(a []countPair) map[string]uint64 {
<mask> m := map[string]uint64{}
<mask> for _, it := range a {
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove func convertSliceToMap(a []countPair) map[string]uint64 {
m := map[string]uint64{}
</s> add func convertSliceToMap(a []countPair) (m map[string]uint64) {
m = map[string]uint64{} </s> remove log.Tracef("periodicFlush() exited")
}
// deleteUnit removes the unit by it's id from the database the tx belongs to.
func (s *StatsCtx) deleteUnit(tx *bbolt.Tx, id uint32) bool {
err := tx.DeleteBucket(idToUnitName(id))
if err != nil {
log.Tracef("stats: bolt DeleteBucket: %s", err)
return false
</s> add sort.Slice(s, func(i, j int) bool {
return s[j].Count < s[i].Count
})
if max > len(s) {
max = len(s) </s> remove // Flush the current unit to DB and delete an old unit when a new hour is started
// If a unit must be flushed:
// . lock DB
// . atomically set a new empty unit as the current one and get the old unit
// This is important to do it inside DB lock, so the reader won't get inconsistent results.
// . write the unit to DB
// . remove the stale unit from DB
// . unlock DB
func (s *StatsCtx) periodicFlush() {
for ptr := s.ongoing(); ptr != nil; ptr = s.ongoing() {
id := s.unitIDGen()
// Access the unit's ID with atomic to avoid locking the whole unit.
if !s.isEnabled() || atomic.LoadUint32(&ptr.id) == id {
time.Sleep(time.Second)
continue
}
tx := beginTxn(s.database(), true)
nu := newUnit(id)
u := s.swapCurrent(nu)
udb := u.serialize()
if tx == nil {
continue
}
flushOK := flushUnitToDB(tx, u.id, udb)
delOK := s.deleteUnit(tx, id-atomic.LoadUint32(&s.limitHours))
if flushOK || delOK {
s.commitTxn(tx)
} else {
_ = tx.Rollback()
}
</s> add func convertMapToSlice(m map[string]uint64, max int) (s []countPair) {
s = make([]countPair, 0, len(m))
for k, v := range m {
s = append(s, countPair{Name: k, Count: v}) </s> remove
func (s *StatsCtx) GetTopClientsIP(maxCount uint) []net.IP {
if !s.isEnabled() {
return nil
}
units, _ := s.loadUnits(atomic.LoadUint32(&s.limitHours))
if units == nil {
return nil
}
// top clients
m := map[string]uint64{}
for _, u := range units {
for _, it := range u.Clients {
m[it.Name] += it.Count
}
}
a := convertMapToSlice(m, int(maxCount))
d := []net.IP{}
for _, it := range a {
ip := net.ParseIP(it.Name)
if ip != nil {
d = append(d, ip)
}
}
return d
}
</s> add </s> remove // log.Tracef("Loading unit %d", id)
var buf bytes.Buffer
buf.Write(bkt.Get([]byte{0}))
dec := gob.NewDecoder(&buf)
udb := unitDB{}
err := dec.Decode(&udb)
if err != nil {
log.Error("gob Decode: %s", err)
return nil
}
return &udb
</s> add return nil | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
func convertSliceToMap(a []countPair) (m map[string]uint64) {
m = map[string]uint64{} | <mask> }
<mask> return a[:max]
<mask> }
<mask>
<mask> func convertSliceToMap(a []countPair) map[string]uint64 {
<mask> m := map[string]uint64{}
<mask> for _, it := range a {
<mask> m[it.Name] = it.Count
<mask> }
<mask> return m
<mask> }
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove log.Debug("stats: deleted unit %d", id)
return true
}
func convertMapToSlice(m map[string]uint64, max int) []countPair {
a := []countPair{}
for k, v := range m {
a = append(a, countPair{Name: k, Count: v})
}
less := func(i, j int) bool {
return a[j].Count < a[i].Count
}
sort.Slice(a, less)
if max > len(a) {
max = len(a)
}
return a[:max]
</s> add return s[:max] </s> remove
func (s *StatsCtx) GetTopClientsIP(maxCount uint) []net.IP {
if !s.isEnabled() {
return nil
}
units, _ := s.loadUnits(atomic.LoadUint32(&s.limitHours))
if units == nil {
return nil
}
// top clients
m := map[string]uint64{}
for _, u := range units {
for _, it := range u.Clients {
m[it.Name] += it.Count
}
}
a := convertMapToSlice(m, int(maxCount))
d := []net.IP{}
for _, it := range a {
ip := net.ParseIP(it.Name)
if ip != nil {
d = append(d, ip)
}
}
return d
}
</s> add </s> remove // log.Tracef("Loading unit %d", id)
var buf bytes.Buffer
buf.Write(bkt.Get([]byte{0}))
dec := gob.NewDecoder(&buf)
udb := unitDB{}
err := dec.Decode(&udb)
if err != nil {
log.Error("gob Decode: %s", err)
return nil
}
return &udb
</s> add return nil </s> remove // Flush the current unit to DB and delete an old unit when a new hour is started
// If a unit must be flushed:
// . lock DB
// . atomically set a new empty unit as the current one and get the old unit
// This is important to do it inside DB lock, so the reader won't get inconsistent results.
// . write the unit to DB
// . remove the stale unit from DB
// . unlock DB
func (s *StatsCtx) periodicFlush() {
for ptr := s.ongoing(); ptr != nil; ptr = s.ongoing() {
id := s.unitIDGen()
// Access the unit's ID with atomic to avoid locking the whole unit.
if !s.isEnabled() || atomic.LoadUint32(&ptr.id) == id {
time.Sleep(time.Second)
continue
}
tx := beginTxn(s.database(), true)
nu := newUnit(id)
u := s.swapCurrent(nu)
udb := u.serialize()
if tx == nil {
continue
}
flushOK := flushUnitToDB(tx, u.id, udb)
delOK := s.deleteUnit(tx, id-atomic.LoadUint32(&s.limitHours))
if flushOK || delOK {
s.commitTxn(tx)
} else {
_ = tx.Rollback()
}
</s> add func convertMapToSlice(m map[string]uint64, max int) (s []countPair) {
s = make([]countPair, 0, len(m))
for k, v := range m {
s = append(s, countPair{Name: k, Count: v}) </s> remove for _, ip := range Context.stats.GetTopClientsIP(topClientsNumber) {
</s> add for _, ip := range Context.stats.TopClientsIP(topClientsNumber) { | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
// serialize converts u to the *unitDB. It's safe for concurrent use. u must
// not be nil. | <mask> }
<mask> return m
<mask> }
<mask>
<mask> // serialize converts u to the *unitDB. It's safe for concurrent use.
<mask> func (u *unit) serialize() (udb *unitDB) {
<mask> u.mu.RLock()
<mask> defer u.mu.RUnlock()
<mask>
<mask> var timeAvg uint32 = 0
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove u.mu.RLock()
defer u.mu.RUnlock()
</s> add </s> remove // ongoing returns the current unit. It's safe for concurrent use.
//
// Note that the unit itself should be locked before accessing.
func (s *StatsCtx) ongoing() (u *unit) {
s.currMu.Lock()
defer s.currMu.Unlock()
return s.curr
}
// swapCurrent swaps the current unit with another and returns it. It's safe
// for concurrent use.
func (s *StatsCtx) swapCurrent(with *unit) (old *unit) {
s.currMu.Lock()
defer s.currMu.Unlock()
old, s.curr = s.curr, with
return old
}
// database returns the database if it's opened. It's safe for concurrent use.
func (s *StatsCtx) database() (db *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
return s.db
}
// swapDatabase swaps the database with another one and returns it. It's safe
// for concurrent use.
func (s *StatsCtx) swapDatabase(with *bbolt.DB) (old *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
old, s.db = s.db, with
return old
</s> add // newUnit allocates the new *unit.
func newUnit(id uint32) (u *unit) {
return &unit{
id: id,
nResult: make([]uint64, resultLast),
domains: make(map[string]uint64),
blockedDomains: make(map[string]uint64),
clients: make(map[string]uint64),
} </s> remove func flushUnitToDB(tx *bbolt.Tx, id uint32, udb *unitDB) bool {
log.Tracef("Flushing unit %d", id)
</s> add // add adds new data to u. It's safe for concurrent use.
func (u *unit) add(res Result, domain, cli string, dur uint64) {
u.nResult[res]++
if res == RNotFiltered {
u.domains[domain]++
} else {
u.blockedDomains[domain]++
}
u.clients[cli]++
u.timeSum += dur
u.nTotal++
}
// flushUnitToDB puts udb to the database at id.
func (udb *unitDB) flushUnitToDB(tx *bbolt.Tx, id uint32) (err error) {
log.Debug("stats: flushing unit with id %d and total of %d", id, udb.NTotal) </s> remove // Entry is a statistics data entry.
type Entry struct {
// Clients is the client's primary ID.
//
// TODO(a.garipov): Make this a {net.IP, string} enum?
Client string
</s> add // httpRegister is used to set HTTP handlers.
httpRegister aghhttp.RegisterFunc
// configModified is called whenever the configuration is modified via web
// interface.
configModified func()
// filename is the name of database file.
filename string
}
var _ Interface = &StatsCtx{}
// New creates s from conf and properly initializes it. Don't use s before
// calling it's Start method.
func New(conf Config) (s *StatsCtx, err error) {
defer withRecovered(&err)
s = &StatsCtx{
currMu: &sync.RWMutex{},
dbMu: &sync.Mutex{},
filename: conf.Filename,
configModified: conf.ConfigModified,
httpRegister: conf.HTTPRegister,
}
if s.limitHours = conf.LimitDays * 24; !checkInterval(conf.LimitDays) {
s.limitHours = 24
}
if s.unitIDGen = newUnitID; conf.UnitID != nil {
s.unitIDGen = conf.UnitID
}
// TODO(e.burkov): Move the code below to the Start method.
err = s.openDB()
if err != nil {
return nil, fmt.Errorf("opening database: %w", err)
}
var udb *unitDB
id := s.unitIDGen()
tx, err := s.db.Begin(true)
if err != nil {
return nil, fmt.Errorf("stats: opening a transaction: %w", err)
}
deleted := deleteOldUnits(tx, id-s.limitHours-1)
udb = loadUnitFromDB(tx, id)
err = finishTxn(tx, deleted > 0)
if err != nil {
log.Error("stats: %s", err)
}
s.curr = newUnit(id)
s.curr.deserialize(udb)
log.Debug("stats: initialized")
return s, nil
}
// withRecovered turns the value recovered from panic if any into an error and
// combines it with the one pointed by orig. orig must be non-nil.
func withRecovered(orig *error) {
p := recover()
if p == nil {
return
}
var err error
switch p := p.(type) {
case error:
err = fmt.Errorf("panic: %w", p)
default:
err = fmt.Errorf("panic: recovered value of type %[1]T: %[1]v", p)
}
*orig = errors.WithDeferred(*orig, err)
}
// Start implements the Interface interface for *StatsCtx.
func (s *StatsCtx) Start() {
s.initWeb()
go s.periodicFlush()
}
// Close implements the io.Closer interface for *StatsCtx.
func (s *StatsCtx) Close() (err error) {
defer func() { err = errors.Annotate(err, "stats: closing: %w") }()
db := s.swapDatabase(nil)
if db == nil {
return nil
}
defer func() {
cerr := db.Close()
if cerr == nil {
log.Debug("stats: database closed")
}
err = errors.WithDeferred(err, cerr)
}()
tx, err := db.Begin(true)
if err != nil {
return fmt.Errorf("opening transaction: %w", err)
}
defer func() { err = errors.WithDeferred(err, finishTxn(tx, err == nil)) }()
s.currMu.RLock()
defer s.currMu.RUnlock()
udb := s.curr.serialize()
return udb.flushUnitToDB(tx, s.curr.id)
}
// Update implements the Interface interface for *StatsCtx.
func (s *StatsCtx) Update(e Entry) {
if atomic.LoadUint32(&s.limitHours) == 0 {
return
}
if e.Result == 0 || e.Result >= resultLast || e.Domain == "" || e.Client == "" {
log.Debug("stats: malformed entry")
return
}
s.currMu.Lock()
defer s.currMu.Unlock()
if s.curr == nil {
log.Error("stats: current unit is nil")
return
}
clientID := e.Client
if ip := net.ParseIP(clientID); ip != nil {
clientID = ip.String()
}
s.curr.add(e.Result, e.Domain, clientID, uint64(e.Time))
}
// WriteDiskConfig implements the Interface interface for *StatsCtx.
func (s *StatsCtx) WriteDiskConfig(dc *DiskConfig) {
dc.Interval = atomic.LoadUint32(&s.limitHours) / 24
}
// TopClientsIP implements the Interface interface for *StatsCtx.
func (s *StatsCtx) TopClientsIP(maxCount uint) (ips []net.IP) {
limit := atomic.LoadUint32(&s.limitHours)
if limit == 0 {
return nil
}
units, _ := s.loadUnits(limit)
if units == nil {
return nil
}
// Collect data for all the clients to sort and crop it afterwards.
m := map[string]uint64{}
for _, u := range units {
for _, it := range u.Clients {
m[it.Name] += it.Count
}
}
a := convertMapToSlice(m, int(maxCount))
ips = []net.IP{}
for _, it := range a {
ip := net.ParseIP(it.Name)
if ip != nil {
ips = append(ips, ip)
}
}
return ips
}
// database returns the database if it's opened. It's safe for concurrent use.
func (s *StatsCtx) database() (db *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
return s.db
}
// swapDatabase swaps the database with another one and returns it. It's safe
// for concurrent use.
func (s *StatsCtx) swapDatabase(with *bbolt.DB) (old *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
old, s.db = s.db, with
return old
}
// deleteOldUnits walks the buckets available to tx and deletes old units. It
// returns the number of deletions performed.
func deleteOldUnits(tx *bbolt.Tx, firstID uint32) (deleted int) {
log.Debug("stats: deleting old units until id %d", firstID)
// TODO(a.garipov): See if this is actually necessary. Looks like a rather
// bizarre solution.
const errStop errors.Error = "stop iteration"
walk := func(name []byte, _ *bbolt.Bucket) (err error) {
nameID, ok := unitNameToID(name)
if ok && nameID >= firstID {
return errStop
}
err = tx.DeleteBucket(name)
if err != nil {
log.Debug("stats: deleting bucket: %s", err)
return nil
}
log.Debug("stats: deleted unit %d (name %x)", nameID, name)
deleted++
return nil
}
err := tx.ForEach(walk)
if err != nil && !errors.Is(err, errStop) {
log.Debug("stats: deleting units: %s", err)
}
return deleted
}
// openDB returns an error if the database can't be opened from the specified
// file. It's safe for concurrent use.
func (s *StatsCtx) openDB() (err error) {
log.Debug("stats: opening database")
var db *bbolt.DB
db, err = bbolt.Open(s.filename, 0o644, nil)
if err != nil {
if err.Error() == "invalid argument" {
log.Error("AdGuard Home cannot be initialized due to an incompatible file system.\nPlease read the explanation here: https://github.com/AdguardTeam/AdGuardHome/wiki/Getting-Started#limitations")
}
return err
}
// Use defer to unlock the mutex as soon as possible.
defer log.Debug("stats: database opened")
s.dbMu.Lock()
defer s.dbMu.Unlock()
s.db = db
return nil
}
func (s *StatsCtx) flush() (cont bool, sleepFor time.Duration) {
id := s.unitIDGen()
s.currMu.Lock()
defer s.currMu.Unlock()
ptr := s.curr
if ptr == nil {
return false, 0
}
limit := atomic.LoadUint32(&s.limitHours)
if limit == 0 || ptr.id == id {
return true, time.Second
}
db := s.database()
if db == nil {
return true, 0
}
tx, err := db.Begin(true)
if err != nil {
log.Error("stats: opening transaction: %s", err)
return true, 0
}
s.curr = newUnit(id)
isCommitable := true
ferr := ptr.serialize().flushUnitToDB(tx, ptr.id)
if ferr != nil {
log.Error("stats: flushing unit: %s", ferr)
isCommitable = false
}
derr := tx.DeleteBucket(idToUnitName(id - limit))
if derr != nil {
log.Error("stats: deleting unit: %s", derr)
if !errors.Is(derr, bbolt.ErrBucketNotFound) {
isCommitable = false
}
}
err = finishTxn(tx, isCommitable)
if err != nil {
log.Error("stats: %s", err)
}
return true, 0
}
// periodicFlush checks and flushes the unit to the database if the freshly
// generated unit ID differs from the current's ID. Flushing process includes:
// - swapping the current unit with the new empty one;
// - writing the current unit to the database;
// - removing the stale unit from the database.
func (s *StatsCtx) periodicFlush() {
for cont, sleepFor := true, time.Duration(0); cont; time.Sleep(sleepFor) {
cont, sleepFor = s.flush()
}
log.Debug("periodic flushing finished")
}
func (s *StatsCtx) setLimit(limitDays int) {
atomic.StoreUint32(&s.limitHours, uint32(24*limitDays))
if limitDays == 0 {
if err := s.clear(); err != nil {
log.Error("stats: %s", err)
}
}
log.Debug("stats: set limit: %d days", limitDays)
}
// Reset counters and clear database
func (s *StatsCtx) clear() (err error) {
defer func() { err = errors.Annotate(err, "clearing: %w") }()
db := s.swapDatabase(nil)
if db != nil {
var tx *bbolt.Tx
tx, err = db.Begin(true)
if err != nil {
log.Error("stats: opening a transaction: %s", err)
} else if err = finishTxn(tx, false); err != nil {
// Don't wrap the error since it's informative enough as is.
return err
}
// Active transactions will continue using database, but new ones won't
// be created.
err = db.Close()
if err != nil {
return fmt.Errorf("closing database: %w", err)
}
// All active transactions are now closed.
log.Debug("stats: database closed")
}
err = os.Remove(s.filename)
if err != nil {
log.Error("stats: %s", err)
}
err = s.openDB()
if err != nil {
log.Error("stats: opening database: %s", err)
}
// Use defer to unlock the mutex as soon as possible.
defer log.Debug("stats: cleared")
s.currMu.Lock()
defer s.currMu.Unlock()
s.curr = newUnit(s.unitIDGen())
return nil
}
func (s *StatsCtx) loadUnits(limit uint32) (units []*unitDB, firstID uint32) {
db := s.database()
if db == nil {
return nil, 0
}
// Use writable transaction to ensure any ongoing writable transaction is
// taken into account.
tx, err := db.Begin(true)
if err != nil {
log.Error("stats: opening transaction: %s", err)
return nil, 0
}
s.currMu.RLock()
defer s.currMu.RUnlock()
cur := s.curr
var curID uint32
if cur != nil {
curID = cur.id
} else {
curID = s.unitIDGen()
}
// Per-hour units.
units = make([]*unitDB, 0, limit)
firstID = curID - limit + 1
for i := firstID; i != curID; i++ {
u := loadUnitFromDB(tx, i)
if u == nil {
u = &unitDB{NResult: make([]uint64, resultLast)}
}
units = append(units, u)
}
err = finishTxn(tx, false)
if err != nil {
log.Error("stats: %s", err)
} </s> remove func (s *StatsCtx) setLimit(limitDays int) {
atomic.StoreUint32(&s.limitHours, uint32(24*limitDays))
if limitDays == 0 {
s.clear()
}
log.Debug("stats: set limit: %d days", limitDays)
}
func (s *StatsCtx) WriteDiskConfig(dc *DiskConfig) {
dc.Interval = atomic.LoadUint32(&s.limitHours) / 24
}
func (s *StatsCtx) Close() {
u := s.swapCurrent(nil)
db := s.database()
if tx := beginTxn(db, true); tx != nil {
udb := u.serialize()
if flushUnitToDB(tx, u.id, udb) {
s.commitTxn(tx)
} else {
_ = tx.Rollback()
}
}
if db != nil {
log.Tracef("db.Close...")
_ = db.Close()
log.Tracef("db.Close")
}
log.Debug("stats: closed")
}
// Reset counters and clear database
func (s *StatsCtx) clear() {
db := s.database()
tx := beginTxn(db, true)
if tx != nil {
_ = s.swapDatabase(nil)
_ = tx.Rollback()
// the active transactions can continue using database,
// but no new transactions will be opened
_ = db.Close()
log.Tracef("db.Close")
// all active transactions are now closed
}
u := newUnit(s.unitIDGen())
_ = s.swapCurrent(u)
err := os.Remove(s.filename)
if err != nil {
log.Error("os.Remove: %s", err)
}
_ = s.dbOpen()
log.Debug("stats: cleared")
}
func (s *StatsCtx) Update(e Entry) {
if !s.isEnabled() {
return
}
if e.Result == 0 ||
e.Result >= resultLast ||
e.Domain == "" ||
e.Client == "" {
return
}
clientID := e.Client
if ip := net.ParseIP(clientID); ip != nil {
clientID = ip.String()
}
u := s.ongoing()
if u == nil {
return
}
u.mu.Lock()
defer u.mu.Unlock()
u.nResult[e.Result]++
if e.Result == RNotFiltered {
u.domains[e.Domain]++
} else {
u.blockedDomains[e.Domain]++
}
u.clients[clientID]++
u.timeSum += uint64(e.Time)
u.nTotal++
}
func (s *StatsCtx) loadUnits(limit uint32) ([]*unitDB, uint32) {
tx := beginTxn(s.database(), false)
if tx == nil {
return nil, 0
}
cur := s.ongoing()
var curID uint32
if cur != nil {
curID = atomic.LoadUint32(&cur.id)
} else {
curID = s.unitIDGen()
}
// Per-hour units.
units := []*unitDB{}
firstID := curID - limit + 1
for i := firstID; i != curID; i++ {
u := s.loadUnitFromDB(tx, i)
if u == nil {
u = &unitDB{}
u.NResult = make([]uint64, resultLast)
}
units = append(units, u)
}
_ = tx.Rollback()
if cur != nil {
units = append(units, cur.serialize())
}
if len(units) != int(limit) {
log.Fatalf("len(units) != limit: %d %d", len(units), limit)
}
return units, firstID
}
</s> add | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
<mask> }
<mask>
<mask> // serialize converts u to the *unitDB. It's safe for concurrent use.
<mask> func (u *unit) serialize() (udb *unitDB) {
<mask> u.mu.RLock()
<mask> defer u.mu.RUnlock()
<mask>
<mask> var timeAvg uint32 = 0
<mask> if u.nTotal != 0 {
<mask> timeAvg = uint32(u.timeSum / u.nTotal)
<mask> }
<mask>
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove // serialize converts u to the *unitDB. It's safe for concurrent use.
</s> add // serialize converts u to the *unitDB. It's safe for concurrent use. u must
// not be nil. </s> remove // ongoing returns the current unit. It's safe for concurrent use.
//
// Note that the unit itself should be locked before accessing.
func (s *StatsCtx) ongoing() (u *unit) {
s.currMu.Lock()
defer s.currMu.Unlock()
return s.curr
}
// swapCurrent swaps the current unit with another and returns it. It's safe
// for concurrent use.
func (s *StatsCtx) swapCurrent(with *unit) (old *unit) {
s.currMu.Lock()
defer s.currMu.Unlock()
old, s.curr = s.curr, with
return old
}
// database returns the database if it's opened. It's safe for concurrent use.
func (s *StatsCtx) database() (db *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
return s.db
}
// swapDatabase swaps the database with another one and returns it. It's safe
// for concurrent use.
func (s *StatsCtx) swapDatabase(with *bbolt.DB) (old *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
old, s.db = s.db, with
return old
</s> add // newUnit allocates the new *unit.
func newUnit(id uint32) (u *unit) {
return &unit{
id: id,
nResult: make([]uint64, resultLast),
domains: make(map[string]uint64),
blockedDomains: make(map[string]uint64),
clients: make(map[string]uint64),
} </s> remove func flushUnitToDB(tx *bbolt.Tx, id uint32, udb *unitDB) bool {
log.Tracef("Flushing unit %d", id)
</s> add // add adds new data to u. It's safe for concurrent use.
func (u *unit) add(res Result, domain, cli string, dur uint64) {
u.nResult[res]++
if res == RNotFiltered {
u.domains[domain]++
} else {
u.blockedDomains[domain]++
}
u.clients[cli]++
u.timeSum += dur
u.nTotal++
}
// flushUnitToDB puts udb to the database at id.
func (udb *unitDB) flushUnitToDB(tx *bbolt.Tx, id uint32) (err error) {
log.Debug("stats: flushing unit with id %d and total of %d", id, udb.NTotal) </s> remove // Entry is a statistics data entry.
type Entry struct {
// Clients is the client's primary ID.
//
// TODO(a.garipov): Make this a {net.IP, string} enum?
Client string
</s> add // httpRegister is used to set HTTP handlers.
httpRegister aghhttp.RegisterFunc
// configModified is called whenever the configuration is modified via web
// interface.
configModified func()
// filename is the name of database file.
filename string
}
var _ Interface = &StatsCtx{}
// New creates s from conf and properly initializes it. Don't use s before
// calling it's Start method.
func New(conf Config) (s *StatsCtx, err error) {
defer withRecovered(&err)
s = &StatsCtx{
currMu: &sync.RWMutex{},
dbMu: &sync.Mutex{},
filename: conf.Filename,
configModified: conf.ConfigModified,
httpRegister: conf.HTTPRegister,
}
if s.limitHours = conf.LimitDays * 24; !checkInterval(conf.LimitDays) {
s.limitHours = 24
}
if s.unitIDGen = newUnitID; conf.UnitID != nil {
s.unitIDGen = conf.UnitID
}
// TODO(e.burkov): Move the code below to the Start method.
err = s.openDB()
if err != nil {
return nil, fmt.Errorf("opening database: %w", err)
}
var udb *unitDB
id := s.unitIDGen()
tx, err := s.db.Begin(true)
if err != nil {
return nil, fmt.Errorf("stats: opening a transaction: %w", err)
}
deleted := deleteOldUnits(tx, id-s.limitHours-1)
udb = loadUnitFromDB(tx, id)
err = finishTxn(tx, deleted > 0)
if err != nil {
log.Error("stats: %s", err)
}
s.curr = newUnit(id)
s.curr.deserialize(udb)
log.Debug("stats: initialized")
return s, nil
}
// withRecovered turns the value recovered from panic if any into an error and
// combines it with the one pointed by orig. orig must be non-nil.
func withRecovered(orig *error) {
p := recover()
if p == nil {
return
}
var err error
switch p := p.(type) {
case error:
err = fmt.Errorf("panic: %w", p)
default:
err = fmt.Errorf("panic: recovered value of type %[1]T: %[1]v", p)
}
*orig = errors.WithDeferred(*orig, err)
}
// Start implements the Interface interface for *StatsCtx.
func (s *StatsCtx) Start() {
s.initWeb()
go s.periodicFlush()
}
// Close implements the io.Closer interface for *StatsCtx.
func (s *StatsCtx) Close() (err error) {
defer func() { err = errors.Annotate(err, "stats: closing: %w") }()
db := s.swapDatabase(nil)
if db == nil {
return nil
}
defer func() {
cerr := db.Close()
if cerr == nil {
log.Debug("stats: database closed")
}
err = errors.WithDeferred(err, cerr)
}()
tx, err := db.Begin(true)
if err != nil {
return fmt.Errorf("opening transaction: %w", err)
}
defer func() { err = errors.WithDeferred(err, finishTxn(tx, err == nil)) }()
s.currMu.RLock()
defer s.currMu.RUnlock()
udb := s.curr.serialize()
return udb.flushUnitToDB(tx, s.curr.id)
}
// Update implements the Interface interface for *StatsCtx.
func (s *StatsCtx) Update(e Entry) {
if atomic.LoadUint32(&s.limitHours) == 0 {
return
}
if e.Result == 0 || e.Result >= resultLast || e.Domain == "" || e.Client == "" {
log.Debug("stats: malformed entry")
return
}
s.currMu.Lock()
defer s.currMu.Unlock()
if s.curr == nil {
log.Error("stats: current unit is nil")
return
}
clientID := e.Client
if ip := net.ParseIP(clientID); ip != nil {
clientID = ip.String()
}
s.curr.add(e.Result, e.Domain, clientID, uint64(e.Time))
}
// WriteDiskConfig implements the Interface interface for *StatsCtx.
func (s *StatsCtx) WriteDiskConfig(dc *DiskConfig) {
dc.Interval = atomic.LoadUint32(&s.limitHours) / 24
}
// TopClientsIP implements the Interface interface for *StatsCtx.
func (s *StatsCtx) TopClientsIP(maxCount uint) (ips []net.IP) {
limit := atomic.LoadUint32(&s.limitHours)
if limit == 0 {
return nil
}
units, _ := s.loadUnits(limit)
if units == nil {
return nil
}
// Collect data for all the clients to sort and crop it afterwards.
m := map[string]uint64{}
for _, u := range units {
for _, it := range u.Clients {
m[it.Name] += it.Count
}
}
a := convertMapToSlice(m, int(maxCount))
ips = []net.IP{}
for _, it := range a {
ip := net.ParseIP(it.Name)
if ip != nil {
ips = append(ips, ip)
}
}
return ips
}
// database returns the database if it's opened. It's safe for concurrent use.
func (s *StatsCtx) database() (db *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
return s.db
}
// swapDatabase swaps the database with another one and returns it. It's safe
// for concurrent use.
func (s *StatsCtx) swapDatabase(with *bbolt.DB) (old *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
old, s.db = s.db, with
return old
}
// deleteOldUnits walks the buckets available to tx and deletes old units. It
// returns the number of deletions performed.
func deleteOldUnits(tx *bbolt.Tx, firstID uint32) (deleted int) {
log.Debug("stats: deleting old units until id %d", firstID)
// TODO(a.garipov): See if this is actually necessary. Looks like a rather
// bizarre solution.
const errStop errors.Error = "stop iteration"
walk := func(name []byte, _ *bbolt.Bucket) (err error) {
nameID, ok := unitNameToID(name)
if ok && nameID >= firstID {
return errStop
}
err = tx.DeleteBucket(name)
if err != nil {
log.Debug("stats: deleting bucket: %s", err)
return nil
}
log.Debug("stats: deleted unit %d (name %x)", nameID, name)
deleted++
return nil
}
err := tx.ForEach(walk)
if err != nil && !errors.Is(err, errStop) {
log.Debug("stats: deleting units: %s", err)
}
return deleted
}
// openDB returns an error if the database can't be opened from the specified
// file. It's safe for concurrent use.
func (s *StatsCtx) openDB() (err error) {
log.Debug("stats: opening database")
var db *bbolt.DB
db, err = bbolt.Open(s.filename, 0o644, nil)
if err != nil {
if err.Error() == "invalid argument" {
log.Error("AdGuard Home cannot be initialized due to an incompatible file system.\nPlease read the explanation here: https://github.com/AdguardTeam/AdGuardHome/wiki/Getting-Started#limitations")
}
return err
}
// Use defer to unlock the mutex as soon as possible.
defer log.Debug("stats: database opened")
s.dbMu.Lock()
defer s.dbMu.Unlock()
s.db = db
return nil
}
func (s *StatsCtx) flush() (cont bool, sleepFor time.Duration) {
id := s.unitIDGen()
s.currMu.Lock()
defer s.currMu.Unlock()
ptr := s.curr
if ptr == nil {
return false, 0
}
limit := atomic.LoadUint32(&s.limitHours)
if limit == 0 || ptr.id == id {
return true, time.Second
}
db := s.database()
if db == nil {
return true, 0
}
tx, err := db.Begin(true)
if err != nil {
log.Error("stats: opening transaction: %s", err)
return true, 0
}
s.curr = newUnit(id)
isCommitable := true
ferr := ptr.serialize().flushUnitToDB(tx, ptr.id)
if ferr != nil {
log.Error("stats: flushing unit: %s", ferr)
isCommitable = false
}
derr := tx.DeleteBucket(idToUnitName(id - limit))
if derr != nil {
log.Error("stats: deleting unit: %s", derr)
if !errors.Is(derr, bbolt.ErrBucketNotFound) {
isCommitable = false
}
}
err = finishTxn(tx, isCommitable)
if err != nil {
log.Error("stats: %s", err)
}
return true, 0
}
// periodicFlush checks and flushes the unit to the database if the freshly
// generated unit ID differs from the current's ID. Flushing process includes:
// - swapping the current unit with the new empty one;
// - writing the current unit to the database;
// - removing the stale unit from the database.
func (s *StatsCtx) periodicFlush() {
for cont, sleepFor := true, time.Duration(0); cont; time.Sleep(sleepFor) {
cont, sleepFor = s.flush()
}
log.Debug("periodic flushing finished")
}
func (s *StatsCtx) setLimit(limitDays int) {
atomic.StoreUint32(&s.limitHours, uint32(24*limitDays))
if limitDays == 0 {
if err := s.clear(); err != nil {
log.Error("stats: %s", err)
}
}
log.Debug("stats: set limit: %d days", limitDays)
}
// Reset counters and clear database
func (s *StatsCtx) clear() (err error) {
defer func() { err = errors.Annotate(err, "clearing: %w") }()
db := s.swapDatabase(nil)
if db != nil {
var tx *bbolt.Tx
tx, err = db.Begin(true)
if err != nil {
log.Error("stats: opening a transaction: %s", err)
} else if err = finishTxn(tx, false); err != nil {
// Don't wrap the error since it's informative enough as is.
return err
}
// Active transactions will continue using database, but new ones won't
// be created.
err = db.Close()
if err != nil {
return fmt.Errorf("closing database: %w", err)
}
// All active transactions are now closed.
log.Debug("stats: database closed")
}
err = os.Remove(s.filename)
if err != nil {
log.Error("stats: %s", err)
}
err = s.openDB()
if err != nil {
log.Error("stats: opening database: %s", err)
}
// Use defer to unlock the mutex as soon as possible.
defer log.Debug("stats: cleared")
s.currMu.Lock()
defer s.currMu.Unlock()
s.curr = newUnit(s.unitIDGen())
return nil
}
func (s *StatsCtx) loadUnits(limit uint32) (units []*unitDB, firstID uint32) {
db := s.database()
if db == nil {
return nil, 0
}
// Use writable transaction to ensure any ongoing writable transaction is
// taken into account.
tx, err := db.Begin(true)
if err != nil {
log.Error("stats: opening transaction: %s", err)
return nil, 0
}
s.currMu.RLock()
defer s.currMu.RUnlock()
cur := s.curr
var curID uint32
if cur != nil {
curID = cur.id
} else {
curID = s.unitIDGen()
}
// Per-hour units.
units = make([]*unitDB, 0, limit)
firstID = curID - limit + 1
for i := firstID; i != curID; i++ {
u := loadUnitFromDB(tx, i)
if u == nil {
u = &unitDB{NResult: make([]uint64, resultLast)}
}
units = append(units, u)
}
err = finishTxn(tx, false)
if err != nil {
log.Error("stats: %s", err)
} </s> remove func (s *StatsCtx) setLimit(limitDays int) {
atomic.StoreUint32(&s.limitHours, uint32(24*limitDays))
if limitDays == 0 {
s.clear()
}
log.Debug("stats: set limit: %d days", limitDays)
}
func (s *StatsCtx) WriteDiskConfig(dc *DiskConfig) {
dc.Interval = atomic.LoadUint32(&s.limitHours) / 24
}
func (s *StatsCtx) Close() {
u := s.swapCurrent(nil)
db := s.database()
if tx := beginTxn(db, true); tx != nil {
udb := u.serialize()
if flushUnitToDB(tx, u.id, udb) {
s.commitTxn(tx)
} else {
_ = tx.Rollback()
}
}
if db != nil {
log.Tracef("db.Close...")
_ = db.Close()
log.Tracef("db.Close")
}
log.Debug("stats: closed")
}
// Reset counters and clear database
func (s *StatsCtx) clear() {
db := s.database()
tx := beginTxn(db, true)
if tx != nil {
_ = s.swapDatabase(nil)
_ = tx.Rollback()
// the active transactions can continue using database,
// but no new transactions will be opened
_ = db.Close()
log.Tracef("db.Close")
// all active transactions are now closed
}
u := newUnit(s.unitIDGen())
_ = s.swapCurrent(u)
err := os.Remove(s.filename)
if err != nil {
log.Error("os.Remove: %s", err)
}
_ = s.dbOpen()
log.Debug("stats: cleared")
}
func (s *StatsCtx) Update(e Entry) {
if !s.isEnabled() {
return
}
if e.Result == 0 ||
e.Result >= resultLast ||
e.Domain == "" ||
e.Client == "" {
return
}
clientID := e.Client
if ip := net.ParseIP(clientID); ip != nil {
clientID = ip.String()
}
u := s.ongoing()
if u == nil {
return
}
u.mu.Lock()
defer u.mu.Unlock()
u.nResult[e.Result]++
if e.Result == RNotFiltered {
u.domains[e.Domain]++
} else {
u.blockedDomains[e.Domain]++
}
u.clients[clientID]++
u.timeSum += uint64(e.Time)
u.nTotal++
}
func (s *StatsCtx) loadUnits(limit uint32) ([]*unitDB, uint32) {
tx := beginTxn(s.database(), false)
if tx == nil {
return nil, 0
}
cur := s.ongoing()
var curID uint32
if cur != nil {
curID = atomic.LoadUint32(&cur.id)
} else {
curID = s.unitIDGen()
}
// Per-hour units.
units := []*unitDB{}
firstID := curID - limit + 1
for i := firstID; i != curID; i++ {
u := s.loadUnitFromDB(tx, i)
if u == nil {
u = &unitDB{}
u.NResult = make([]uint64, resultLast)
}
units = append(units, u)
}
_ = tx.Rollback()
if cur != nil {
units = append(units, cur.serialize())
}
if len(units) != int(limit) {
log.Fatalf("len(units) != limit: %d %d", len(units), limit)
}
return units, firstID
}
</s> add | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
|
<mask> if udb == nil {
<mask> return
<mask> }
<mask>
<mask> u.mu.Lock()
<mask> defer u.mu.Unlock()
<mask>
<mask> u.nTotal = udb.NTotal
<mask> u.nResult = make([]uint64, resultLast)
<mask> copy(u.nResult, udb.NResult)
<mask> u.domains = convertSliceToMap(udb.Domains)
<mask> u.blockedDomains = convertSliceToMap(udb.BlockedDomains)
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove func (s *StatsCtx) setLimit(limitDays int) {
atomic.StoreUint32(&s.limitHours, uint32(24*limitDays))
if limitDays == 0 {
s.clear()
}
log.Debug("stats: set limit: %d days", limitDays)
}
func (s *StatsCtx) WriteDiskConfig(dc *DiskConfig) {
dc.Interval = atomic.LoadUint32(&s.limitHours) / 24
}
func (s *StatsCtx) Close() {
u := s.swapCurrent(nil)
db := s.database()
if tx := beginTxn(db, true); tx != nil {
udb := u.serialize()
if flushUnitToDB(tx, u.id, udb) {
s.commitTxn(tx)
} else {
_ = tx.Rollback()
}
}
if db != nil {
log.Tracef("db.Close...")
_ = db.Close()
log.Tracef("db.Close")
}
log.Debug("stats: closed")
}
// Reset counters and clear database
func (s *StatsCtx) clear() {
db := s.database()
tx := beginTxn(db, true)
if tx != nil {
_ = s.swapDatabase(nil)
_ = tx.Rollback()
// the active transactions can continue using database,
// but no new transactions will be opened
_ = db.Close()
log.Tracef("db.Close")
// all active transactions are now closed
}
u := newUnit(s.unitIDGen())
_ = s.swapCurrent(u)
err := os.Remove(s.filename)
if err != nil {
log.Error("os.Remove: %s", err)
}
_ = s.dbOpen()
log.Debug("stats: cleared")
}
func (s *StatsCtx) Update(e Entry) {
if !s.isEnabled() {
return
}
if e.Result == 0 ||
e.Result >= resultLast ||
e.Domain == "" ||
e.Client == "" {
return
}
clientID := e.Client
if ip := net.ParseIP(clientID); ip != nil {
clientID = ip.String()
}
u := s.ongoing()
if u == nil {
return
}
u.mu.Lock()
defer u.mu.Unlock()
u.nResult[e.Result]++
if e.Result == RNotFiltered {
u.domains[e.Domain]++
} else {
u.blockedDomains[e.Domain]++
}
u.clients[clientID]++
u.timeSum += uint64(e.Time)
u.nTotal++
}
func (s *StatsCtx) loadUnits(limit uint32) ([]*unitDB, uint32) {
tx := beginTxn(s.database(), false)
if tx == nil {
return nil, 0
}
cur := s.ongoing()
var curID uint32
if cur != nil {
curID = atomic.LoadUint32(&cur.id)
} else {
curID = s.unitIDGen()
}
// Per-hour units.
units := []*unitDB{}
firstID := curID - limit + 1
for i := firstID; i != curID; i++ {
u := s.loadUnitFromDB(tx, i)
if u == nil {
u = &unitDB{}
u.NResult = make([]uint64, resultLast)
}
units = append(units, u)
}
_ = tx.Rollback()
if cur != nil {
units = append(units, cur.serialize())
}
if len(units) != int(limit) {
log.Fatalf("len(units) != limit: %d %d", len(units), limit)
}
return units, firstID
}
</s> add </s> remove u.mu.RLock()
defer u.mu.RUnlock()
</s> add </s> remove // Entry is a statistics data entry.
type Entry struct {
// Clients is the client's primary ID.
//
// TODO(a.garipov): Make this a {net.IP, string} enum?
Client string
</s> add // httpRegister is used to set HTTP handlers.
httpRegister aghhttp.RegisterFunc
// configModified is called whenever the configuration is modified via web
// interface.
configModified func()
// filename is the name of database file.
filename string
}
var _ Interface = &StatsCtx{}
// New creates s from conf and properly initializes it. Don't use s before
// calling it's Start method.
func New(conf Config) (s *StatsCtx, err error) {
defer withRecovered(&err)
s = &StatsCtx{
currMu: &sync.RWMutex{},
dbMu: &sync.Mutex{},
filename: conf.Filename,
configModified: conf.ConfigModified,
httpRegister: conf.HTTPRegister,
}
if s.limitHours = conf.LimitDays * 24; !checkInterval(conf.LimitDays) {
s.limitHours = 24
}
if s.unitIDGen = newUnitID; conf.UnitID != nil {
s.unitIDGen = conf.UnitID
}
// TODO(e.burkov): Move the code below to the Start method.
err = s.openDB()
if err != nil {
return nil, fmt.Errorf("opening database: %w", err)
}
var udb *unitDB
id := s.unitIDGen()
tx, err := s.db.Begin(true)
if err != nil {
return nil, fmt.Errorf("stats: opening a transaction: %w", err)
}
deleted := deleteOldUnits(tx, id-s.limitHours-1)
udb = loadUnitFromDB(tx, id)
err = finishTxn(tx, deleted > 0)
if err != nil {
log.Error("stats: %s", err)
}
s.curr = newUnit(id)
s.curr.deserialize(udb)
log.Debug("stats: initialized")
return s, nil
}
// withRecovered turns the value recovered from panic if any into an error and
// combines it with the one pointed by orig. orig must be non-nil.
func withRecovered(orig *error) {
p := recover()
if p == nil {
return
}
var err error
switch p := p.(type) {
case error:
err = fmt.Errorf("panic: %w", p)
default:
err = fmt.Errorf("panic: recovered value of type %[1]T: %[1]v", p)
}
*orig = errors.WithDeferred(*orig, err)
}
// Start implements the Interface interface for *StatsCtx.
func (s *StatsCtx) Start() {
s.initWeb()
go s.periodicFlush()
}
// Close implements the io.Closer interface for *StatsCtx.
func (s *StatsCtx) Close() (err error) {
defer func() { err = errors.Annotate(err, "stats: closing: %w") }()
db := s.swapDatabase(nil)
if db == nil {
return nil
}
defer func() {
cerr := db.Close()
if cerr == nil {
log.Debug("stats: database closed")
}
err = errors.WithDeferred(err, cerr)
}()
tx, err := db.Begin(true)
if err != nil {
return fmt.Errorf("opening transaction: %w", err)
}
defer func() { err = errors.WithDeferred(err, finishTxn(tx, err == nil)) }()
s.currMu.RLock()
defer s.currMu.RUnlock()
udb := s.curr.serialize()
return udb.flushUnitToDB(tx, s.curr.id)
}
// Update implements the Interface interface for *StatsCtx.
func (s *StatsCtx) Update(e Entry) {
if atomic.LoadUint32(&s.limitHours) == 0 {
return
}
if e.Result == 0 || e.Result >= resultLast || e.Domain == "" || e.Client == "" {
log.Debug("stats: malformed entry")
return
}
s.currMu.Lock()
defer s.currMu.Unlock()
if s.curr == nil {
log.Error("stats: current unit is nil")
return
}
clientID := e.Client
if ip := net.ParseIP(clientID); ip != nil {
clientID = ip.String()
}
s.curr.add(e.Result, e.Domain, clientID, uint64(e.Time))
}
// WriteDiskConfig implements the Interface interface for *StatsCtx.
func (s *StatsCtx) WriteDiskConfig(dc *DiskConfig) {
dc.Interval = atomic.LoadUint32(&s.limitHours) / 24
}
// TopClientsIP implements the Interface interface for *StatsCtx.
func (s *StatsCtx) TopClientsIP(maxCount uint) (ips []net.IP) {
limit := atomic.LoadUint32(&s.limitHours)
if limit == 0 {
return nil
}
units, _ := s.loadUnits(limit)
if units == nil {
return nil
}
// Collect data for all the clients to sort and crop it afterwards.
m := map[string]uint64{}
for _, u := range units {
for _, it := range u.Clients {
m[it.Name] += it.Count
}
}
a := convertMapToSlice(m, int(maxCount))
ips = []net.IP{}
for _, it := range a {
ip := net.ParseIP(it.Name)
if ip != nil {
ips = append(ips, ip)
}
}
return ips
}
// database returns the database if it's opened. It's safe for concurrent use.
func (s *StatsCtx) database() (db *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
return s.db
}
// swapDatabase swaps the database with another one and returns it. It's safe
// for concurrent use.
func (s *StatsCtx) swapDatabase(with *bbolt.DB) (old *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
old, s.db = s.db, with
return old
}
// deleteOldUnits walks the buckets available to tx and deletes old units. It
// returns the number of deletions performed.
func deleteOldUnits(tx *bbolt.Tx, firstID uint32) (deleted int) {
log.Debug("stats: deleting old units until id %d", firstID)
// TODO(a.garipov): See if this is actually necessary. Looks like a rather
// bizarre solution.
const errStop errors.Error = "stop iteration"
walk := func(name []byte, _ *bbolt.Bucket) (err error) {
nameID, ok := unitNameToID(name)
if ok && nameID >= firstID {
return errStop
}
err = tx.DeleteBucket(name)
if err != nil {
log.Debug("stats: deleting bucket: %s", err)
return nil
}
log.Debug("stats: deleted unit %d (name %x)", nameID, name)
deleted++
return nil
}
err := tx.ForEach(walk)
if err != nil && !errors.Is(err, errStop) {
log.Debug("stats: deleting units: %s", err)
}
return deleted
}
// openDB returns an error if the database can't be opened from the specified
// file. It's safe for concurrent use.
func (s *StatsCtx) openDB() (err error) {
log.Debug("stats: opening database")
var db *bbolt.DB
db, err = bbolt.Open(s.filename, 0o644, nil)
if err != nil {
if err.Error() == "invalid argument" {
log.Error("AdGuard Home cannot be initialized due to an incompatible file system.\nPlease read the explanation here: https://github.com/AdguardTeam/AdGuardHome/wiki/Getting-Started#limitations")
}
return err
}
// Use defer to unlock the mutex as soon as possible.
defer log.Debug("stats: database opened")
s.dbMu.Lock()
defer s.dbMu.Unlock()
s.db = db
return nil
}
func (s *StatsCtx) flush() (cont bool, sleepFor time.Duration) {
id := s.unitIDGen()
s.currMu.Lock()
defer s.currMu.Unlock()
ptr := s.curr
if ptr == nil {
return false, 0
}
limit := atomic.LoadUint32(&s.limitHours)
if limit == 0 || ptr.id == id {
return true, time.Second
}
db := s.database()
if db == nil {
return true, 0
}
tx, err := db.Begin(true)
if err != nil {
log.Error("stats: opening transaction: %s", err)
return true, 0
}
s.curr = newUnit(id)
isCommitable := true
ferr := ptr.serialize().flushUnitToDB(tx, ptr.id)
if ferr != nil {
log.Error("stats: flushing unit: %s", ferr)
isCommitable = false
}
derr := tx.DeleteBucket(idToUnitName(id - limit))
if derr != nil {
log.Error("stats: deleting unit: %s", derr)
if !errors.Is(derr, bbolt.ErrBucketNotFound) {
isCommitable = false
}
}
err = finishTxn(tx, isCommitable)
if err != nil {
log.Error("stats: %s", err)
}
return true, 0
}
// periodicFlush checks and flushes the unit to the database if the freshly
// generated unit ID differs from the current's ID. Flushing process includes:
// - swapping the current unit with the new empty one;
// - writing the current unit to the database;
// - removing the stale unit from the database.
func (s *StatsCtx) periodicFlush() {
for cont, sleepFor := true, time.Duration(0); cont; time.Sleep(sleepFor) {
cont, sleepFor = s.flush()
}
log.Debug("periodic flushing finished")
}
func (s *StatsCtx) setLimit(limitDays int) {
atomic.StoreUint32(&s.limitHours, uint32(24*limitDays))
if limitDays == 0 {
if err := s.clear(); err != nil {
log.Error("stats: %s", err)
}
}
log.Debug("stats: set limit: %d days", limitDays)
}
// Reset counters and clear database
func (s *StatsCtx) clear() (err error) {
defer func() { err = errors.Annotate(err, "clearing: %w") }()
db := s.swapDatabase(nil)
if db != nil {
var tx *bbolt.Tx
tx, err = db.Begin(true)
if err != nil {
log.Error("stats: opening a transaction: %s", err)
} else if err = finishTxn(tx, false); err != nil {
// Don't wrap the error since it's informative enough as is.
return err
}
// Active transactions will continue using database, but new ones won't
// be created.
err = db.Close()
if err != nil {
return fmt.Errorf("closing database: %w", err)
}
// All active transactions are now closed.
log.Debug("stats: database closed")
}
err = os.Remove(s.filename)
if err != nil {
log.Error("stats: %s", err)
}
err = s.openDB()
if err != nil {
log.Error("stats: opening database: %s", err)
}
// Use defer to unlock the mutex as soon as possible.
defer log.Debug("stats: cleared")
s.currMu.Lock()
defer s.currMu.Unlock()
s.curr = newUnit(s.unitIDGen())
return nil
}
func (s *StatsCtx) loadUnits(limit uint32) (units []*unitDB, firstID uint32) {
db := s.database()
if db == nil {
return nil, 0
}
// Use writable transaction to ensure any ongoing writable transaction is
// taken into account.
tx, err := db.Begin(true)
if err != nil {
log.Error("stats: opening transaction: %s", err)
return nil, 0
}
s.currMu.RLock()
defer s.currMu.RUnlock()
cur := s.curr
var curID uint32
if cur != nil {
curID = cur.id
} else {
curID = s.unitIDGen()
}
// Per-hour units.
units = make([]*unitDB, 0, limit)
firstID = curID - limit + 1
for i := firstID; i != curID; i++ {
u := loadUnitFromDB(tx, i)
if u == nil {
u = &unitDB{NResult: make([]uint64, resultLast)}
}
units = append(units, u)
}
err = finishTxn(tx, false)
if err != nil {
log.Error("stats: %s", err)
} </s> remove func flushUnitToDB(tx *bbolt.Tx, id uint32, udb *unitDB) bool {
log.Tracef("Flushing unit %d", id)
</s> add // add adds new data to u. It's safe for concurrent use.
func (u *unit) add(res Result, domain, cli string, dur uint64) {
u.nResult[res]++
if res == RNotFiltered {
u.domains[domain]++
} else {
u.blockedDomains[domain]++
}
u.clients[cli]++
u.timeSum += dur
u.nTotal++
}
// flushUnitToDB puts udb to the database at id.
func (udb *unitDB) flushUnitToDB(tx *bbolt.Tx, id uint32) (err error) {
log.Debug("stats: flushing unit with id %d and total of %d", id, udb.NTotal) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
|
// add adds new data to u. It's safe for concurrent use.
func (u *unit) add(res Result, domain, cli string, dur uint64) {
u.nResult[res]++
if res == RNotFiltered {
u.domains[domain]++
} else {
u.blockedDomains[domain]++
}
u.clients[cli]++
u.timeSum += dur
u.nTotal++
}
// flushUnitToDB puts udb to the database at id.
func (udb *unitDB) flushUnitToDB(tx *bbolt.Tx, id uint32) (err error) {
log.Debug("stats: flushing unit with id %d and total of %d", id, udb.NTotal) | <mask> u.clients = convertSliceToMap(udb.Clients)
<mask> u.timeSum = uint64(udb.TimeAvg) * udb.NTotal
<mask> }
<mask>
<mask> func flushUnitToDB(tx *bbolt.Tx, id uint32, udb *unitDB) bool {
<mask> log.Tracef("Flushing unit %d", id)
<mask>
<mask> bkt, err := tx.CreateBucketIfNotExists(idToUnitName(id))
<mask> if err != nil {
<mask> log.Error("tx.CreateBucketIfNotExists: %s", err)
<mask> return false
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove log.Error("tx.CreateBucketIfNotExists: %s", err)
return false
</s> add return fmt.Errorf("creating bucket: %w", err) </s> remove log.Tracef("periodicFlush() exited")
}
// deleteUnit removes the unit by it's id from the database the tx belongs to.
func (s *StatsCtx) deleteUnit(tx *bbolt.Tx, id uint32) bool {
err := tx.DeleteBucket(idToUnitName(id))
if err != nil {
log.Tracef("stats: bolt DeleteBucket: %s", err)
return false
</s> add sort.Slice(s, func(i, j int) bool {
return s[j].Count < s[i].Count
})
if max > len(s) {
max = len(s) </s> remove log.Error("bkt.Put: %s", err)
return false
}
return true
}
func (s *StatsCtx) loadUnitFromDB(tx *bbolt.Tx, id uint32) *unitDB {
bkt := tx.Bucket(idToUnitName(id))
if bkt == nil {
return nil
</s> add return fmt.Errorf("putting unit to database: %w", err) </s> remove // log.Tracef("Loading unit %d", id)
var buf bytes.Buffer
buf.Write(bkt.Get([]byte{0}))
dec := gob.NewDecoder(&buf)
udb := unitDB{}
err := dec.Decode(&udb)
if err != nil {
log.Error("gob Decode: %s", err)
return nil
}
return &udb
</s> add return nil </s> remove var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
err = enc.Encode(udb)
</s> add buf := &bytes.Buffer{}
err = gob.NewEncoder(buf).Encode(udb) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
return fmt.Errorf("creating bucket: %w", err) | <mask> log.Tracef("Flushing unit %d", id)
<mask>
<mask> bkt, err := tx.CreateBucketIfNotExists(idToUnitName(id))
<mask> if err != nil {
<mask> log.Error("tx.CreateBucketIfNotExists: %s", err)
<mask> return false
<mask> }
<mask>
<mask> var buf bytes.Buffer
<mask> enc := gob.NewEncoder(&buf)
<mask> err = enc.Encode(udb)
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
err = enc.Encode(udb)
</s> add buf := &bytes.Buffer{}
err = gob.NewEncoder(buf).Encode(udb) </s> remove log.Error("gob.Encode: %s", err)
return false
</s> add return fmt.Errorf("encoding unit: %w", err) </s> remove log.Error("bkt.Put: %s", err)
return false
}
return true
}
func (s *StatsCtx) loadUnitFromDB(tx *bbolt.Tx, id uint32) *unitDB {
bkt := tx.Bucket(idToUnitName(id))
if bkt == nil {
return nil
</s> add return fmt.Errorf("putting unit to database: %w", err) </s> remove func flushUnitToDB(tx *bbolt.Tx, id uint32, udb *unitDB) bool {
log.Tracef("Flushing unit %d", id)
</s> add // add adds new data to u. It's safe for concurrent use.
func (u *unit) add(res Result, domain, cli string, dur uint64) {
u.nResult[res]++
if res == RNotFiltered {
u.domains[domain]++
} else {
u.blockedDomains[domain]++
}
u.clients[cli]++
u.timeSum += dur
u.nTotal++
}
// flushUnitToDB puts udb to the database at id.
func (udb *unitDB) flushUnitToDB(tx *bbolt.Tx, id uint32) (err error) {
log.Debug("stats: flushing unit with id %d and total of %d", id, udb.NTotal) </s> remove // log.Tracef("Loading unit %d", id)
var buf bytes.Buffer
buf.Write(bkt.Get([]byte{0}))
dec := gob.NewDecoder(&buf)
udb := unitDB{}
err := dec.Decode(&udb)
if err != nil {
log.Error("gob Decode: %s", err)
return nil
}
return &udb
</s> add return nil | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
buf := &bytes.Buffer{}
err = gob.NewEncoder(buf).Encode(udb) | <mask> log.Error("tx.CreateBucketIfNotExists: %s", err)
<mask> return false
<mask> }
<mask>
<mask> var buf bytes.Buffer
<mask> enc := gob.NewEncoder(&buf)
<mask> err = enc.Encode(udb)
<mask> if err != nil {
<mask> log.Error("gob.Encode: %s", err)
<mask> return false
<mask> }
<mask>
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove log.Error("gob.Encode: %s", err)
return false
</s> add return fmt.Errorf("encoding unit: %w", err) </s> remove log.Error("tx.CreateBucketIfNotExists: %s", err)
return false
</s> add return fmt.Errorf("creating bucket: %w", err) </s> remove log.Error("bkt.Put: %s", err)
return false
}
return true
}
func (s *StatsCtx) loadUnitFromDB(tx *bbolt.Tx, id uint32) *unitDB {
bkt := tx.Bucket(idToUnitName(id))
if bkt == nil {
return nil
</s> add return fmt.Errorf("putting unit to database: %w", err) </s> remove // log.Tracef("Loading unit %d", id)
var buf bytes.Buffer
buf.Write(bkt.Get([]byte{0}))
dec := gob.NewDecoder(&buf)
udb := unitDB{}
err := dec.Decode(&udb)
if err != nil {
log.Error("gob Decode: %s", err)
return nil
}
return &udb
</s> add return nil </s> remove return
}
</s> add | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
return fmt.Errorf("encoding unit: %w", err) | <mask> var buf bytes.Buffer
<mask> enc := gob.NewEncoder(&buf)
<mask> err = enc.Encode(udb)
<mask> if err != nil {
<mask> log.Error("gob.Encode: %s", err)
<mask> return false
<mask> }
<mask>
<mask> err = bkt.Put([]byte{0}, buf.Bytes())
<mask> if err != nil {
<mask> log.Error("bkt.Put: %s", err)
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
err = enc.Encode(udb)
</s> add buf := &bytes.Buffer{}
err = gob.NewEncoder(buf).Encode(udb) </s> remove log.Error("tx.CreateBucketIfNotExists: %s", err)
return false
</s> add return fmt.Errorf("creating bucket: %w", err) </s> remove log.Error("bkt.Put: %s", err)
return false
}
return true
}
func (s *StatsCtx) loadUnitFromDB(tx *bbolt.Tx, id uint32) *unitDB {
bkt := tx.Bucket(idToUnitName(id))
if bkt == nil {
return nil
</s> add return fmt.Errorf("putting unit to database: %w", err) </s> remove // log.Tracef("Loading unit %d", id)
var buf bytes.Buffer
buf.Write(bkt.Get([]byte{0}))
dec := gob.NewDecoder(&buf)
udb := unitDB{}
err := dec.Decode(&udb)
if err != nil {
log.Error("gob Decode: %s", err)
return nil
}
return &udb
</s> add return nil </s> remove return
}
</s> add | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
return fmt.Errorf("putting unit to database: %w", err) | <mask> }
<mask>
<mask> err = bkt.Put([]byte{0}, buf.Bytes())
<mask> if err != nil {
<mask> log.Error("bkt.Put: %s", err)
<mask> return false
<mask> }
<mask>
<mask> return true
<mask> }
<mask>
<mask> func (s *StatsCtx) loadUnitFromDB(tx *bbolt.Tx, id uint32) *unitDB {
<mask> bkt := tx.Bucket(idToUnitName(id))
<mask> if bkt == nil {
<mask> return nil
<mask> }
<mask>
<mask> // log.Tracef("Loading unit %d", id)
<mask>
<mask> var buf bytes.Buffer
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove // log.Tracef("Loading unit %d", id)
var buf bytes.Buffer
buf.Write(bkt.Get([]byte{0}))
dec := gob.NewDecoder(&buf)
udb := unitDB{}
err := dec.Decode(&udb)
if err != nil {
log.Error("gob Decode: %s", err)
return nil
}
return &udb
</s> add return nil </s> remove log.Error("gob.Encode: %s", err)
return false
</s> add return fmt.Errorf("encoding unit: %w", err) </s> remove log.Tracef("periodicFlush() exited")
}
// deleteUnit removes the unit by it's id from the database the tx belongs to.
func (s *StatsCtx) deleteUnit(tx *bbolt.Tx, id uint32) bool {
err := tx.DeleteBucket(idToUnitName(id))
if err != nil {
log.Tracef("stats: bolt DeleteBucket: %s", err)
return false
</s> add sort.Slice(s, func(i, j int) bool {
return s[j].Count < s[i].Count
})
if max > len(s) {
max = len(s) </s> remove log.Error("tx.CreateBucketIfNotExists: %s", err)
return false
</s> add return fmt.Errorf("creating bucket: %w", err) </s> remove var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
err = enc.Encode(udb)
</s> add buf := &bytes.Buffer{}
err = gob.NewEncoder(buf).Encode(udb) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
return nil | <mask> if bkt == nil {
<mask> return nil
<mask> }
<mask>
<mask> // log.Tracef("Loading unit %d", id)
<mask>
<mask> var buf bytes.Buffer
<mask> buf.Write(bkt.Get([]byte{0}))
<mask> dec := gob.NewDecoder(&buf)
<mask> udb := unitDB{}
<mask> err := dec.Decode(&udb)
<mask> if err != nil {
<mask> log.Error("gob Decode: %s", err)
<mask> return nil
<mask> }
<mask>
<mask> return &udb
<mask> }
<mask>
<mask> func convertTopSlice(a []countPair) (m []map[string]uint64) {
<mask> m = make([]map[string]uint64, 0, len(a))
<mask> for _, it := range a {
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove log.Error("bkt.Put: %s", err)
return false
}
return true
}
func (s *StatsCtx) loadUnitFromDB(tx *bbolt.Tx, id uint32) *unitDB {
bkt := tx.Bucket(idToUnitName(id))
if bkt == nil {
return nil
</s> add return fmt.Errorf("putting unit to database: %w", err) </s> remove log.Error("tx.CreateBucketIfNotExists: %s", err)
return false
</s> add return fmt.Errorf("creating bucket: %w", err) </s> remove
func (s *StatsCtx) GetTopClientsIP(maxCount uint) []net.IP {
if !s.isEnabled() {
return nil
}
units, _ := s.loadUnits(atomic.LoadUint32(&s.limitHours))
if units == nil {
return nil
}
// top clients
m := map[string]uint64{}
for _, u := range units {
for _, it := range u.Clients {
m[it.Name] += it.Count
}
}
a := convertMapToSlice(m, int(maxCount))
d := []net.IP{}
for _, it := range a {
ip := net.ParseIP(it.Name)
if ip != nil {
d = append(d, ip)
}
}
return d
}
</s> add </s> remove func convertSliceToMap(a []countPair) map[string]uint64 {
m := map[string]uint64{}
</s> add func convertSliceToMap(a []countPair) (m map[string]uint64) {
m = map[string]uint64{} </s> remove var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
err = enc.Encode(udb)
</s> add buf := &bytes.Buffer{}
err = gob.NewEncoder(buf).Encode(udb) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
<mask>
<mask> return m
<mask> }
<mask>
<mask> func (s *StatsCtx) setLimit(limitDays int) {
<mask> atomic.StoreUint32(&s.limitHours, uint32(24*limitDays))
<mask> if limitDays == 0 {
<mask> s.clear()
<mask> }
<mask>
<mask> log.Debug("stats: set limit: %d days", limitDays)
<mask> }
<mask>
<mask> func (s *StatsCtx) WriteDiskConfig(dc *DiskConfig) {
<mask> dc.Interval = atomic.LoadUint32(&s.limitHours) / 24
<mask> }
<mask>
<mask> func (s *StatsCtx) Close() {
<mask> u := s.swapCurrent(nil)
<mask>
<mask> db := s.database()
<mask> if tx := beginTxn(db, true); tx != nil {
<mask> udb := u.serialize()
<mask> if flushUnitToDB(tx, u.id, udb) {
<mask> s.commitTxn(tx)
<mask> } else {
<mask> _ = tx.Rollback()
<mask> }
<mask> }
<mask>
<mask> if db != nil {
<mask> log.Tracef("db.Close...")
<mask> _ = db.Close()
<mask> log.Tracef("db.Close")
<mask> }
<mask>
<mask> log.Debug("stats: closed")
<mask> }
<mask>
<mask> // Reset counters and clear database
<mask> func (s *StatsCtx) clear() {
<mask> db := s.database()
<mask> tx := beginTxn(db, true)
<mask> if tx != nil {
<mask> _ = s.swapDatabase(nil)
<mask> _ = tx.Rollback()
<mask> // the active transactions can continue using database,
<mask> // but no new transactions will be opened
<mask> _ = db.Close()
<mask> log.Tracef("db.Close")
<mask> // all active transactions are now closed
<mask> }
<mask>
<mask> u := newUnit(s.unitIDGen())
<mask> _ = s.swapCurrent(u)
<mask>
<mask> err := os.Remove(s.filename)
<mask> if err != nil {
<mask> log.Error("os.Remove: %s", err)
<mask> }
<mask>
<mask> _ = s.dbOpen()
<mask>
<mask> log.Debug("stats: cleared")
<mask> }
<mask>
<mask> func (s *StatsCtx) Update(e Entry) {
<mask> if !s.isEnabled() {
<mask> return
<mask> }
<mask>
<mask> if e.Result == 0 ||
<mask> e.Result >= resultLast ||
<mask> e.Domain == "" ||
<mask> e.Client == "" {
<mask> return
<mask> }
<mask>
<mask> clientID := e.Client
<mask> if ip := net.ParseIP(clientID); ip != nil {
<mask> clientID = ip.String()
<mask> }
<mask>
<mask> u := s.ongoing()
<mask> if u == nil {
<mask> return
<mask> }
<mask>
<mask> u.mu.Lock()
<mask> defer u.mu.Unlock()
<mask>
<mask> u.nResult[e.Result]++
<mask> if e.Result == RNotFiltered {
<mask> u.domains[e.Domain]++
<mask> } else {
<mask> u.blockedDomains[e.Domain]++
<mask> }
<mask>
<mask> u.clients[clientID]++
<mask> u.timeSum += uint64(e.Time)
<mask> u.nTotal++
<mask> }
<mask>
<mask> func (s *StatsCtx) loadUnits(limit uint32) ([]*unitDB, uint32) {
<mask> tx := beginTxn(s.database(), false)
<mask> if tx == nil {
<mask> return nil, 0
<mask> }
<mask>
<mask> cur := s.ongoing()
<mask> var curID uint32
<mask> if cur != nil {
<mask> curID = atomic.LoadUint32(&cur.id)
<mask> } else {
<mask> curID = s.unitIDGen()
<mask> }
<mask>
<mask> // Per-hour units.
<mask> units := []*unitDB{}
<mask> firstID := curID - limit + 1
<mask> for i := firstID; i != curID; i++ {
<mask> u := s.loadUnitFromDB(tx, i)
<mask> if u == nil {
<mask> u = &unitDB{}
<mask> u.NResult = make([]uint64, resultLast)
<mask> }
<mask> units = append(units, u)
<mask> }
<mask>
<mask> _ = tx.Rollback()
<mask>
<mask> if cur != nil {
<mask> units = append(units, cur.serialize())
<mask> }
<mask>
<mask> if len(units) != int(limit) {
<mask> log.Fatalf("len(units) != limit: %d %d", len(units), limit)
<mask> }
<mask>
<mask> return units, firstID
<mask> }
<mask>
<mask> // numsGetter is a signature for statsCollector argument.
<mask> type numsGetter func(u *unitDB) (num uint64)
<mask>
<mask> // statsCollector collects statisctics for the given *unitDB slice by specified
<mask> // timeUnit using ng to retrieve data.
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove // Entry is a statistics data entry.
type Entry struct {
// Clients is the client's primary ID.
//
// TODO(a.garipov): Make this a {net.IP, string} enum?
Client string
</s> add // httpRegister is used to set HTTP handlers.
httpRegister aghhttp.RegisterFunc
// configModified is called whenever the configuration is modified via web
// interface.
configModified func()
// filename is the name of database file.
filename string
}
var _ Interface = &StatsCtx{}
// New creates s from conf and properly initializes it. Don't use s before
// calling it's Start method.
func New(conf Config) (s *StatsCtx, err error) {
defer withRecovered(&err)
s = &StatsCtx{
currMu: &sync.RWMutex{},
dbMu: &sync.Mutex{},
filename: conf.Filename,
configModified: conf.ConfigModified,
httpRegister: conf.HTTPRegister,
}
if s.limitHours = conf.LimitDays * 24; !checkInterval(conf.LimitDays) {
s.limitHours = 24
}
if s.unitIDGen = newUnitID; conf.UnitID != nil {
s.unitIDGen = conf.UnitID
}
// TODO(e.burkov): Move the code below to the Start method.
err = s.openDB()
if err != nil {
return nil, fmt.Errorf("opening database: %w", err)
}
var udb *unitDB
id := s.unitIDGen()
tx, err := s.db.Begin(true)
if err != nil {
return nil, fmt.Errorf("stats: opening a transaction: %w", err)
}
deleted := deleteOldUnits(tx, id-s.limitHours-1)
udb = loadUnitFromDB(tx, id)
err = finishTxn(tx, deleted > 0)
if err != nil {
log.Error("stats: %s", err)
}
s.curr = newUnit(id)
s.curr.deserialize(udb)
log.Debug("stats: initialized")
return s, nil
}
// withRecovered turns the value recovered from panic if any into an error and
// combines it with the one pointed by orig. orig must be non-nil.
func withRecovered(orig *error) {
p := recover()
if p == nil {
return
}
var err error
switch p := p.(type) {
case error:
err = fmt.Errorf("panic: %w", p)
default:
err = fmt.Errorf("panic: recovered value of type %[1]T: %[1]v", p)
}
*orig = errors.WithDeferred(*orig, err)
}
// Start implements the Interface interface for *StatsCtx.
func (s *StatsCtx) Start() {
s.initWeb()
go s.periodicFlush()
}
// Close implements the io.Closer interface for *StatsCtx.
func (s *StatsCtx) Close() (err error) {
defer func() { err = errors.Annotate(err, "stats: closing: %w") }()
db := s.swapDatabase(nil)
if db == nil {
return nil
}
defer func() {
cerr := db.Close()
if cerr == nil {
log.Debug("stats: database closed")
}
err = errors.WithDeferred(err, cerr)
}()
tx, err := db.Begin(true)
if err != nil {
return fmt.Errorf("opening transaction: %w", err)
}
defer func() { err = errors.WithDeferred(err, finishTxn(tx, err == nil)) }()
s.currMu.RLock()
defer s.currMu.RUnlock()
udb := s.curr.serialize()
return udb.flushUnitToDB(tx, s.curr.id)
}
// Update implements the Interface interface for *StatsCtx.
func (s *StatsCtx) Update(e Entry) {
if atomic.LoadUint32(&s.limitHours) == 0 {
return
}
if e.Result == 0 || e.Result >= resultLast || e.Domain == "" || e.Client == "" {
log.Debug("stats: malformed entry")
return
}
s.currMu.Lock()
defer s.currMu.Unlock()
if s.curr == nil {
log.Error("stats: current unit is nil")
return
}
clientID := e.Client
if ip := net.ParseIP(clientID); ip != nil {
clientID = ip.String()
}
s.curr.add(e.Result, e.Domain, clientID, uint64(e.Time))
}
// WriteDiskConfig implements the Interface interface for *StatsCtx.
func (s *StatsCtx) WriteDiskConfig(dc *DiskConfig) {
dc.Interval = atomic.LoadUint32(&s.limitHours) / 24
}
// TopClientsIP implements the Interface interface for *StatsCtx.
func (s *StatsCtx) TopClientsIP(maxCount uint) (ips []net.IP) {
limit := atomic.LoadUint32(&s.limitHours)
if limit == 0 {
return nil
}
units, _ := s.loadUnits(limit)
if units == nil {
return nil
}
// Collect data for all the clients to sort and crop it afterwards.
m := map[string]uint64{}
for _, u := range units {
for _, it := range u.Clients {
m[it.Name] += it.Count
}
}
a := convertMapToSlice(m, int(maxCount))
ips = []net.IP{}
for _, it := range a {
ip := net.ParseIP(it.Name)
if ip != nil {
ips = append(ips, ip)
}
}
return ips
}
// database returns the database if it's opened. It's safe for concurrent use.
func (s *StatsCtx) database() (db *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
return s.db
}
// swapDatabase swaps the database with another one and returns it. It's safe
// for concurrent use.
func (s *StatsCtx) swapDatabase(with *bbolt.DB) (old *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
old, s.db = s.db, with
return old
}
// deleteOldUnits walks the buckets available to tx and deletes old units. It
// returns the number of deletions performed.
func deleteOldUnits(tx *bbolt.Tx, firstID uint32) (deleted int) {
log.Debug("stats: deleting old units until id %d", firstID)
// TODO(a.garipov): See if this is actually necessary. Looks like a rather
// bizarre solution.
const errStop errors.Error = "stop iteration"
walk := func(name []byte, _ *bbolt.Bucket) (err error) {
nameID, ok := unitNameToID(name)
if ok && nameID >= firstID {
return errStop
}
err = tx.DeleteBucket(name)
if err != nil {
log.Debug("stats: deleting bucket: %s", err)
return nil
}
log.Debug("stats: deleted unit %d (name %x)", nameID, name)
deleted++
return nil
}
err := tx.ForEach(walk)
if err != nil && !errors.Is(err, errStop) {
log.Debug("stats: deleting units: %s", err)
}
return deleted
}
// openDB returns an error if the database can't be opened from the specified
// file. It's safe for concurrent use.
func (s *StatsCtx) openDB() (err error) {
log.Debug("stats: opening database")
var db *bbolt.DB
db, err = bbolt.Open(s.filename, 0o644, nil)
if err != nil {
if err.Error() == "invalid argument" {
log.Error("AdGuard Home cannot be initialized due to an incompatible file system.\nPlease read the explanation here: https://github.com/AdguardTeam/AdGuardHome/wiki/Getting-Started#limitations")
}
return err
}
// Use defer to unlock the mutex as soon as possible.
defer log.Debug("stats: database opened")
s.dbMu.Lock()
defer s.dbMu.Unlock()
s.db = db
return nil
}
func (s *StatsCtx) flush() (cont bool, sleepFor time.Duration) {
id := s.unitIDGen()
s.currMu.Lock()
defer s.currMu.Unlock()
ptr := s.curr
if ptr == nil {
return false, 0
}
limit := atomic.LoadUint32(&s.limitHours)
if limit == 0 || ptr.id == id {
return true, time.Second
}
db := s.database()
if db == nil {
return true, 0
}
tx, err := db.Begin(true)
if err != nil {
log.Error("stats: opening transaction: %s", err)
return true, 0
}
s.curr = newUnit(id)
isCommitable := true
ferr := ptr.serialize().flushUnitToDB(tx, ptr.id)
if ferr != nil {
log.Error("stats: flushing unit: %s", ferr)
isCommitable = false
}
derr := tx.DeleteBucket(idToUnitName(id - limit))
if derr != nil {
log.Error("stats: deleting unit: %s", derr)
if !errors.Is(derr, bbolt.ErrBucketNotFound) {
isCommitable = false
}
}
err = finishTxn(tx, isCommitable)
if err != nil {
log.Error("stats: %s", err)
}
return true, 0
}
// periodicFlush checks and flushes the unit to the database if the freshly
// generated unit ID differs from the current's ID. Flushing process includes:
// - swapping the current unit with the new empty one;
// - writing the current unit to the database;
// - removing the stale unit from the database.
func (s *StatsCtx) periodicFlush() {
for cont, sleepFor := true, time.Duration(0); cont; time.Sleep(sleepFor) {
cont, sleepFor = s.flush()
}
log.Debug("periodic flushing finished")
}
func (s *StatsCtx) setLimit(limitDays int) {
atomic.StoreUint32(&s.limitHours, uint32(24*limitDays))
if limitDays == 0 {
if err := s.clear(); err != nil {
log.Error("stats: %s", err)
}
}
log.Debug("stats: set limit: %d days", limitDays)
}
// Reset counters and clear database
func (s *StatsCtx) clear() (err error) {
defer func() { err = errors.Annotate(err, "clearing: %w") }()
db := s.swapDatabase(nil)
if db != nil {
var tx *bbolt.Tx
tx, err = db.Begin(true)
if err != nil {
log.Error("stats: opening a transaction: %s", err)
} else if err = finishTxn(tx, false); err != nil {
// Don't wrap the error since it's informative enough as is.
return err
}
// Active transactions will continue using database, but new ones won't
// be created.
err = db.Close()
if err != nil {
return fmt.Errorf("closing database: %w", err)
}
// All active transactions are now closed.
log.Debug("stats: database closed")
}
err = os.Remove(s.filename)
if err != nil {
log.Error("stats: %s", err)
}
err = s.openDB()
if err != nil {
log.Error("stats: opening database: %s", err)
}
// Use defer to unlock the mutex as soon as possible.
defer log.Debug("stats: cleared")
s.currMu.Lock()
defer s.currMu.Unlock()
s.curr = newUnit(s.unitIDGen())
return nil
}
func (s *StatsCtx) loadUnits(limit uint32) (units []*unitDB, firstID uint32) {
db := s.database()
if db == nil {
return nil, 0
}
// Use writable transaction to ensure any ongoing writable transaction is
// taken into account.
tx, err := db.Begin(true)
if err != nil {
log.Error("stats: opening transaction: %s", err)
return nil, 0
}
s.currMu.RLock()
defer s.currMu.RUnlock()
cur := s.curr
var curID uint32
if cur != nil {
curID = cur.id
} else {
curID = s.unitIDGen()
}
// Per-hour units.
units = make([]*unitDB, 0, limit)
firstID = curID - limit + 1
for i := firstID; i != curID; i++ {
u := loadUnitFromDB(tx, i)
if u == nil {
u = &unitDB{NResult: make([]uint64, resultLast)}
}
units = append(units, u)
}
err = finishTxn(tx, false)
if err != nil {
log.Error("stats: %s", err)
} </s> remove // Flush the current unit to DB and delete an old unit when a new hour is started
// If a unit must be flushed:
// . lock DB
// . atomically set a new empty unit as the current one and get the old unit
// This is important to do it inside DB lock, so the reader won't get inconsistent results.
// . write the unit to DB
// . remove the stale unit from DB
// . unlock DB
func (s *StatsCtx) periodicFlush() {
for ptr := s.ongoing(); ptr != nil; ptr = s.ongoing() {
id := s.unitIDGen()
// Access the unit's ID with atomic to avoid locking the whole unit.
if !s.isEnabled() || atomic.LoadUint32(&ptr.id) == id {
time.Sleep(time.Second)
continue
}
tx := beginTxn(s.database(), true)
nu := newUnit(id)
u := s.swapCurrent(nu)
udb := u.serialize()
if tx == nil {
continue
}
flushOK := flushUnitToDB(tx, u.id, udb)
delOK := s.deleteUnit(tx, id-atomic.LoadUint32(&s.limitHours))
if flushOK || delOK {
s.commitTxn(tx)
} else {
_ = tx.Rollback()
}
</s> add func convertMapToSlice(m map[string]uint64, max int) (s []countPair) {
s = make([]countPair, 0, len(m))
for k, v := range m {
s = append(s, countPair{Name: k, Count: v}) </s> remove // withRecovered turns the value recovered from panic if any into an error and
// combines it with the one pointed by orig. orig must be non-nil.
func withRecovered(orig *error) {
p := recover()
if p == nil {
return
}
var err error
switch p := p.(type) {
case error:
err = fmt.Errorf("panic: %w", p)
default:
err = fmt.Errorf("panic: recovered value of type %[1]T: %[1]v", p)
}
*orig = errors.WithDeferred(*orig, err)
}
// isEnabled is a helper that check if the statistics collecting is enabled.
func (s *StatsCtx) isEnabled() (ok bool) {
return atomic.LoadUint32(&s.limitHours) != 0
}
// New creates s from conf and properly initializes it. Don't use s before
// calling it's Start method.
func New(conf Config) (s *StatsCtx, err error) {
defer withRecovered(&err)
s = &StatsCtx{
currMu: &sync.Mutex{},
dbMu: &sync.Mutex{},
filename: conf.Filename,
configModified: conf.ConfigModified,
httpRegister: conf.HTTPRegister,
}
if s.limitHours = conf.LimitDays * 24; !checkInterval(conf.LimitDays) {
s.limitHours = 24
}
if s.unitIDGen = newUnitID; conf.UnitID != nil {
s.unitIDGen = conf.UnitID
}
if err = s.dbOpen(); err != nil {
return nil, fmt.Errorf("opening database: %w", err)
}
id := s.unitIDGen()
tx := beginTxn(s.db, true)
var udb *unitDB
if tx != nil {
log.Tracef("Deleting old units...")
firstID := id - s.limitHours - 1
unitDel := 0
err = tx.ForEach(newBucketWalker(tx, &unitDel, firstID))
if err != nil && !errors.Is(err, errStop) {
log.Debug("stats: deleting units: %s", err)
}
udb = s.loadUnitFromDB(tx, id)
if unitDel != 0 {
s.commitTxn(tx)
} else {
err = tx.Rollback()
if err != nil {
log.Debug("rolling back: %s", err)
}
}
}
u := newUnit(id)
// This use of deserialize is safe since the accessed unit has just been
// created.
u.deserialize(udb)
s.curr = u
log.Debug("stats: initialized")
return s, nil
}
// TODO(a.garipov): See if this is actually necessary. Looks like a rather
// bizarre solution.
const errStop errors.Error = "stop iteration"
// newBucketWalker returns a new bucket walker that deletes old units. The
// integer that unitDelPtr points to is incremented for every successful
// deletion. If the bucket isn't deleted, f returns errStop.
func newBucketWalker(
tx *bbolt.Tx,
unitDelPtr *int,
firstID uint32,
) (f func(name []byte, b *bbolt.Bucket) (err error)) {
return func(name []byte, _ *bbolt.Bucket) (err error) {
nameID, ok := unitNameToID(name)
if !ok || nameID < firstID {
err = tx.DeleteBucket(name)
if err != nil {
log.Debug("stats: tx.DeleteBucket: %s", err)
return nil
}
log.Debug("stats: deleted unit %d (name %x)", nameID, name)
*unitDelPtr++
return nil
}
return errStop
}
}
// Start makes s process the incoming data.
func (s *StatsCtx) Start() {
s.initWeb()
go s.periodicFlush()
}
// checkInterval returns true if days is valid to be used as statistics
// retention interval. The valid values are 0, 1, 7, 30 and 90.
func checkInterval(days uint32) (ok bool) {
return days == 0 || days == 1 || days == 7 || days == 30 || days == 90
}
// dbOpen returns an error if the database can't be opened from the specified
// file. It's safe for concurrent use.
func (s *StatsCtx) dbOpen() (err error) {
log.Tracef("db.Open...")
s.dbMu.Lock()
defer s.dbMu.Unlock()
s.db, err = bbolt.Open(s.filename, 0o644, nil)
if err != nil {
log.Error("stats: open DB: %s: %s", s.filename, err)
if err.Error() == "invalid argument" {
log.Error("AdGuard Home cannot be initialized due to an incompatible file system.\nPlease read the explanation here: https://github.com/AdguardTeam/AdGuardHome/wiki/Getting-Started#limitations")
}
return err
}
log.Tracef("db.Open")
return nil
}
</s> add </s> remove
func (s *StatsCtx) GetTopClientsIP(maxCount uint) []net.IP {
if !s.isEnabled() {
return nil
}
units, _ := s.loadUnits(atomic.LoadUint32(&s.limitHours))
if units == nil {
return nil
}
// top clients
m := map[string]uint64{}
for _, u := range units {
for _, it := range u.Clients {
m[it.Name] += it.Count
}
}
a := convertMapToSlice(m, int(maxCount))
d := []net.IP{}
for _, it := range a {
ip := net.ParseIP(it.Name)
if ip != nil {
d = append(d, ip)
}
}
return d
}
</s> add </s> remove log.Tracef("periodicFlush() exited")
}
// deleteUnit removes the unit by it's id from the database the tx belongs to.
func (s *StatsCtx) deleteUnit(tx *bbolt.Tx, id uint32) bool {
err := tx.DeleteBucket(idToUnitName(id))
if err != nil {
log.Tracef("stats: bolt DeleteBucket: %s", err)
return false
</s> add sort.Slice(s, func(i, j int) bool {
return s[j].Count < s[i].Count
})
if max > len(s) {
max = len(s) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
|
nums = make([]uint64, 0, len(units)) | <mask> func statsCollector(units []*unitDB, firstID uint32, timeUnit TimeUnit, ng numsGetter) (nums []uint64) {
<mask> if timeUnit == Hours {
<mask> for _, u := range units {
<mask> nums = append(nums, ng(u))
<mask> }
<mask> } else {
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove return statsResponse{}, false
</s> add return StatsResp{}, false </s> remove func (s *StatsCtx) setLimit(limitDays int) {
atomic.StoreUint32(&s.limitHours, uint32(24*limitDays))
if limitDays == 0 {
s.clear()
}
log.Debug("stats: set limit: %d days", limitDays)
}
func (s *StatsCtx) WriteDiskConfig(dc *DiskConfig) {
dc.Interval = atomic.LoadUint32(&s.limitHours) / 24
}
func (s *StatsCtx) Close() {
u := s.swapCurrent(nil)
db := s.database()
if tx := beginTxn(db, true); tx != nil {
udb := u.serialize()
if flushUnitToDB(tx, u.id, udb) {
s.commitTxn(tx)
} else {
_ = tx.Rollback()
}
}
if db != nil {
log.Tracef("db.Close...")
_ = db.Close()
log.Tracef("db.Close")
}
log.Debug("stats: closed")
}
// Reset counters and clear database
func (s *StatsCtx) clear() {
db := s.database()
tx := beginTxn(db, true)
if tx != nil {
_ = s.swapDatabase(nil)
_ = tx.Rollback()
// the active transactions can continue using database,
// but no new transactions will be opened
_ = db.Close()
log.Tracef("db.Close")
// all active transactions are now closed
}
u := newUnit(s.unitIDGen())
_ = s.swapCurrent(u)
err := os.Remove(s.filename)
if err != nil {
log.Error("os.Remove: %s", err)
}
_ = s.dbOpen()
log.Debug("stats: cleared")
}
func (s *StatsCtx) Update(e Entry) {
if !s.isEnabled() {
return
}
if e.Result == 0 ||
e.Result >= resultLast ||
e.Domain == "" ||
e.Client == "" {
return
}
clientID := e.Client
if ip := net.ParseIP(clientID); ip != nil {
clientID = ip.String()
}
u := s.ongoing()
if u == nil {
return
}
u.mu.Lock()
defer u.mu.Unlock()
u.nResult[e.Result]++
if e.Result == RNotFiltered {
u.domains[e.Domain]++
} else {
u.blockedDomains[e.Domain]++
}
u.clients[clientID]++
u.timeSum += uint64(e.Time)
u.nTotal++
}
func (s *StatsCtx) loadUnits(limit uint32) ([]*unitDB, uint32) {
tx := beginTxn(s.database(), false)
if tx == nil {
return nil, 0
}
cur := s.ongoing()
var curID uint32
if cur != nil {
curID = atomic.LoadUint32(&cur.id)
} else {
curID = s.unitIDGen()
}
// Per-hour units.
units := []*unitDB{}
firstID := curID - limit + 1
for i := firstID; i != curID; i++ {
u := s.loadUnitFromDB(tx, i)
if u == nil {
u = &unitDB{}
u.NResult = make([]uint64, resultLast)
}
units = append(units, u)
}
_ = tx.Rollback()
if cur != nil {
units = append(units, cur.serialize())
}
if len(units) != int(limit) {
log.Fatalf("len(units) != limit: %d %d", len(units), limit)
}
return units, firstID
}
</s> add </s> remove
func (s *StatsCtx) GetTopClientsIP(maxCount uint) []net.IP {
if !s.isEnabled() {
return nil
}
units, _ := s.loadUnits(atomic.LoadUint32(&s.limitHours))
if units == nil {
return nil
}
// top clients
m := map[string]uint64{}
for _, u := range units {
for _, it := range u.Clients {
m[it.Name] += it.Count
}
}
a := convertMapToSlice(m, int(maxCount))
d := []net.IP{}
for _, it := range a {
ip := net.ParseIP(it.Name)
if ip != nil {
d = append(d, ip)
}
}
return d
}
</s> add </s> remove for _, ip := range Context.stats.GetTopClientsIP(topClientsNumber) {
</s> add for _, ip := range Context.stats.TopClientsIP(topClientsNumber) { </s> remove // Entry is a statistics data entry.
type Entry struct {
// Clients is the client's primary ID.
//
// TODO(a.garipov): Make this a {net.IP, string} enum?
Client string
</s> add // httpRegister is used to set HTTP handlers.
httpRegister aghhttp.RegisterFunc
// configModified is called whenever the configuration is modified via web
// interface.
configModified func()
// filename is the name of database file.
filename string
}
var _ Interface = &StatsCtx{}
// New creates s from conf and properly initializes it. Don't use s before
// calling it's Start method.
func New(conf Config) (s *StatsCtx, err error) {
defer withRecovered(&err)
s = &StatsCtx{
currMu: &sync.RWMutex{},
dbMu: &sync.Mutex{},
filename: conf.Filename,
configModified: conf.ConfigModified,
httpRegister: conf.HTTPRegister,
}
if s.limitHours = conf.LimitDays * 24; !checkInterval(conf.LimitDays) {
s.limitHours = 24
}
if s.unitIDGen = newUnitID; conf.UnitID != nil {
s.unitIDGen = conf.UnitID
}
// TODO(e.burkov): Move the code below to the Start method.
err = s.openDB()
if err != nil {
return nil, fmt.Errorf("opening database: %w", err)
}
var udb *unitDB
id := s.unitIDGen()
tx, err := s.db.Begin(true)
if err != nil {
return nil, fmt.Errorf("stats: opening a transaction: %w", err)
}
deleted := deleteOldUnits(tx, id-s.limitHours-1)
udb = loadUnitFromDB(tx, id)
err = finishTxn(tx, deleted > 0)
if err != nil {
log.Error("stats: %s", err)
}
s.curr = newUnit(id)
s.curr.deserialize(udb)
log.Debug("stats: initialized")
return s, nil
}
// withRecovered turns the value recovered from panic if any into an error and
// combines it with the one pointed by orig. orig must be non-nil.
func withRecovered(orig *error) {
p := recover()
if p == nil {
return
}
var err error
switch p := p.(type) {
case error:
err = fmt.Errorf("panic: %w", p)
default:
err = fmt.Errorf("panic: recovered value of type %[1]T: %[1]v", p)
}
*orig = errors.WithDeferred(*orig, err)
}
// Start implements the Interface interface for *StatsCtx.
func (s *StatsCtx) Start() {
s.initWeb()
go s.periodicFlush()
}
// Close implements the io.Closer interface for *StatsCtx.
func (s *StatsCtx) Close() (err error) {
defer func() { err = errors.Annotate(err, "stats: closing: %w") }()
db := s.swapDatabase(nil)
if db == nil {
return nil
}
defer func() {
cerr := db.Close()
if cerr == nil {
log.Debug("stats: database closed")
}
err = errors.WithDeferred(err, cerr)
}()
tx, err := db.Begin(true)
if err != nil {
return fmt.Errorf("opening transaction: %w", err)
}
defer func() { err = errors.WithDeferred(err, finishTxn(tx, err == nil)) }()
s.currMu.RLock()
defer s.currMu.RUnlock()
udb := s.curr.serialize()
return udb.flushUnitToDB(tx, s.curr.id)
}
// Update implements the Interface interface for *StatsCtx.
func (s *StatsCtx) Update(e Entry) {
if atomic.LoadUint32(&s.limitHours) == 0 {
return
}
if e.Result == 0 || e.Result >= resultLast || e.Domain == "" || e.Client == "" {
log.Debug("stats: malformed entry")
return
}
s.currMu.Lock()
defer s.currMu.Unlock()
if s.curr == nil {
log.Error("stats: current unit is nil")
return
}
clientID := e.Client
if ip := net.ParseIP(clientID); ip != nil {
clientID = ip.String()
}
s.curr.add(e.Result, e.Domain, clientID, uint64(e.Time))
}
// WriteDiskConfig implements the Interface interface for *StatsCtx.
func (s *StatsCtx) WriteDiskConfig(dc *DiskConfig) {
dc.Interval = atomic.LoadUint32(&s.limitHours) / 24
}
// TopClientsIP implements the Interface interface for *StatsCtx.
func (s *StatsCtx) TopClientsIP(maxCount uint) (ips []net.IP) {
limit := atomic.LoadUint32(&s.limitHours)
if limit == 0 {
return nil
}
units, _ := s.loadUnits(limit)
if units == nil {
return nil
}
// Collect data for all the clients to sort and crop it afterwards.
m := map[string]uint64{}
for _, u := range units {
for _, it := range u.Clients {
m[it.Name] += it.Count
}
}
a := convertMapToSlice(m, int(maxCount))
ips = []net.IP{}
for _, it := range a {
ip := net.ParseIP(it.Name)
if ip != nil {
ips = append(ips, ip)
}
}
return ips
}
// database returns the database if it's opened. It's safe for concurrent use.
func (s *StatsCtx) database() (db *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
return s.db
}
// swapDatabase swaps the database with another one and returns it. It's safe
// for concurrent use.
func (s *StatsCtx) swapDatabase(with *bbolt.DB) (old *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
old, s.db = s.db, with
return old
}
// deleteOldUnits walks the buckets available to tx and deletes old units. It
// returns the number of deletions performed.
func deleteOldUnits(tx *bbolt.Tx, firstID uint32) (deleted int) {
log.Debug("stats: deleting old units until id %d", firstID)
// TODO(a.garipov): See if this is actually necessary. Looks like a rather
// bizarre solution.
const errStop errors.Error = "stop iteration"
walk := func(name []byte, _ *bbolt.Bucket) (err error) {
nameID, ok := unitNameToID(name)
if ok && nameID >= firstID {
return errStop
}
err = tx.DeleteBucket(name)
if err != nil {
log.Debug("stats: deleting bucket: %s", err)
return nil
}
log.Debug("stats: deleted unit %d (name %x)", nameID, name)
deleted++
return nil
}
err := tx.ForEach(walk)
if err != nil && !errors.Is(err, errStop) {
log.Debug("stats: deleting units: %s", err)
}
return deleted
}
// openDB returns an error if the database can't be opened from the specified
// file. It's safe for concurrent use.
func (s *StatsCtx) openDB() (err error) {
log.Debug("stats: opening database")
var db *bbolt.DB
db, err = bbolt.Open(s.filename, 0o644, nil)
if err != nil {
if err.Error() == "invalid argument" {
log.Error("AdGuard Home cannot be initialized due to an incompatible file system.\nPlease read the explanation here: https://github.com/AdguardTeam/AdGuardHome/wiki/Getting-Started#limitations")
}
return err
}
// Use defer to unlock the mutex as soon as possible.
defer log.Debug("stats: database opened")
s.dbMu.Lock()
defer s.dbMu.Unlock()
s.db = db
return nil
}
func (s *StatsCtx) flush() (cont bool, sleepFor time.Duration) {
id := s.unitIDGen()
s.currMu.Lock()
defer s.currMu.Unlock()
ptr := s.curr
if ptr == nil {
return false, 0
}
limit := atomic.LoadUint32(&s.limitHours)
if limit == 0 || ptr.id == id {
return true, time.Second
}
db := s.database()
if db == nil {
return true, 0
}
tx, err := db.Begin(true)
if err != nil {
log.Error("stats: opening transaction: %s", err)
return true, 0
}
s.curr = newUnit(id)
isCommitable := true
ferr := ptr.serialize().flushUnitToDB(tx, ptr.id)
if ferr != nil {
log.Error("stats: flushing unit: %s", ferr)
isCommitable = false
}
derr := tx.DeleteBucket(idToUnitName(id - limit))
if derr != nil {
log.Error("stats: deleting unit: %s", derr)
if !errors.Is(derr, bbolt.ErrBucketNotFound) {
isCommitable = false
}
}
err = finishTxn(tx, isCommitable)
if err != nil {
log.Error("stats: %s", err)
}
return true, 0
}
// periodicFlush checks and flushes the unit to the database if the freshly
// generated unit ID differs from the current's ID. Flushing process includes:
// - swapping the current unit with the new empty one;
// - writing the current unit to the database;
// - removing the stale unit from the database.
func (s *StatsCtx) periodicFlush() {
for cont, sleepFor := true, time.Duration(0); cont; time.Sleep(sleepFor) {
cont, sleepFor = s.flush()
}
log.Debug("periodic flushing finished")
}
func (s *StatsCtx) setLimit(limitDays int) {
atomic.StoreUint32(&s.limitHours, uint32(24*limitDays))
if limitDays == 0 {
if err := s.clear(); err != nil {
log.Error("stats: %s", err)
}
}
log.Debug("stats: set limit: %d days", limitDays)
}
// Reset counters and clear database
func (s *StatsCtx) clear() (err error) {
defer func() { err = errors.Annotate(err, "clearing: %w") }()
db := s.swapDatabase(nil)
if db != nil {
var tx *bbolt.Tx
tx, err = db.Begin(true)
if err != nil {
log.Error("stats: opening a transaction: %s", err)
} else if err = finishTxn(tx, false); err != nil {
// Don't wrap the error since it's informative enough as is.
return err
}
// Active transactions will continue using database, but new ones won't
// be created.
err = db.Close()
if err != nil {
return fmt.Errorf("closing database: %w", err)
}
// All active transactions are now closed.
log.Debug("stats: database closed")
}
err = os.Remove(s.filename)
if err != nil {
log.Error("stats: %s", err)
}
err = s.openDB()
if err != nil {
log.Error("stats: opening database: %s", err)
}
// Use defer to unlock the mutex as soon as possible.
defer log.Debug("stats: cleared")
s.currMu.Lock()
defer s.currMu.Unlock()
s.curr = newUnit(s.unitIDGen())
return nil
}
func (s *StatsCtx) loadUnits(limit uint32) (units []*unitDB, firstID uint32) {
db := s.database()
if db == nil {
return nil, 0
}
// Use writable transaction to ensure any ongoing writable transaction is
// taken into account.
tx, err := db.Begin(true)
if err != nil {
log.Error("stats: opening transaction: %s", err)
return nil, 0
}
s.currMu.RLock()
defer s.currMu.RUnlock()
cur := s.curr
var curID uint32
if cur != nil {
curID = cur.id
} else {
curID = s.unitIDGen()
}
// Per-hour units.
units = make([]*unitDB, 0, limit)
firstID = curID - limit + 1
for i := firstID; i != curID; i++ {
u := loadUnitFromDB(tx, i)
if u == nil {
u = &unitDB{NResult: make([]uint64, resultLast)}
}
units = append(units, u)
}
err = finishTxn(tx, false)
if err != nil {
log.Error("stats: %s", err)
} | [
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
func (s *StatsCtx) getData(limit uint32) (StatsResp, bool) { | <mask> * safesearch-blocked
<mask> * parental-blocked
<mask> These values are just the sum of data for all units.
<mask> */
<mask> func (s *StatsCtx) getData() (statsResponse, bool) {
<mask> limit := atomic.LoadUint32(&s.limitHours)
<mask> if limit == 0 {
<mask> return statsResponse{
<mask> TimeUnits: "days",
<mask>
<mask> TopBlocked: []topAddrs{},
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove return statsResponse{
</s> add return StatsResp{ </s> remove start := time.Now()
var resp statsResponse
var ok bool
resp, ok = s.getData()
</s> add limit := atomic.LoadUint32(&s.limitHours) </s> remove func (s *StatsCtx) setLimit(limitDays int) {
atomic.StoreUint32(&s.limitHours, uint32(24*limitDays))
if limitDays == 0 {
s.clear()
}
log.Debug("stats: set limit: %d days", limitDays)
}
func (s *StatsCtx) WriteDiskConfig(dc *DiskConfig) {
dc.Interval = atomic.LoadUint32(&s.limitHours) / 24
}
func (s *StatsCtx) Close() {
u := s.swapCurrent(nil)
db := s.database()
if tx := beginTxn(db, true); tx != nil {
udb := u.serialize()
if flushUnitToDB(tx, u.id, udb) {
s.commitTxn(tx)
} else {
_ = tx.Rollback()
}
}
if db != nil {
log.Tracef("db.Close...")
_ = db.Close()
log.Tracef("db.Close")
}
log.Debug("stats: closed")
}
// Reset counters and clear database
func (s *StatsCtx) clear() {
db := s.database()
tx := beginTxn(db, true)
if tx != nil {
_ = s.swapDatabase(nil)
_ = tx.Rollback()
// the active transactions can continue using database,
// but no new transactions will be opened
_ = db.Close()
log.Tracef("db.Close")
// all active transactions are now closed
}
u := newUnit(s.unitIDGen())
_ = s.swapCurrent(u)
err := os.Remove(s.filename)
if err != nil {
log.Error("os.Remove: %s", err)
}
_ = s.dbOpen()
log.Debug("stats: cleared")
}
func (s *StatsCtx) Update(e Entry) {
if !s.isEnabled() {
return
}
if e.Result == 0 ||
e.Result >= resultLast ||
e.Domain == "" ||
e.Client == "" {
return
}
clientID := e.Client
if ip := net.ParseIP(clientID); ip != nil {
clientID = ip.String()
}
u := s.ongoing()
if u == nil {
return
}
u.mu.Lock()
defer u.mu.Unlock()
u.nResult[e.Result]++
if e.Result == RNotFiltered {
u.domains[e.Domain]++
} else {
u.blockedDomains[e.Domain]++
}
u.clients[clientID]++
u.timeSum += uint64(e.Time)
u.nTotal++
}
func (s *StatsCtx) loadUnits(limit uint32) ([]*unitDB, uint32) {
tx := beginTxn(s.database(), false)
if tx == nil {
return nil, 0
}
cur := s.ongoing()
var curID uint32
if cur != nil {
curID = atomic.LoadUint32(&cur.id)
} else {
curID = s.unitIDGen()
}
// Per-hour units.
units := []*unitDB{}
firstID := curID - limit + 1
for i := firstID; i != curID; i++ {
u := s.loadUnitFromDB(tx, i)
if u == nil {
u = &unitDB{}
u.NResult = make([]uint64, resultLast)
}
units = append(units, u)
}
_ = tx.Rollback()
if cur != nil {
units = append(units, cur.serialize())
}
if len(units) != int(limit) {
log.Fatalf("len(units) != limit: %d %d", len(units), limit)
}
return units, firstID
}
</s> add </s> remove // Entry is a statistics data entry.
type Entry struct {
// Clients is the client's primary ID.
//
// TODO(a.garipov): Make this a {net.IP, string} enum?
Client string
</s> add // httpRegister is used to set HTTP handlers.
httpRegister aghhttp.RegisterFunc
// configModified is called whenever the configuration is modified via web
// interface.
configModified func()
// filename is the name of database file.
filename string
}
var _ Interface = &StatsCtx{}
// New creates s from conf and properly initializes it. Don't use s before
// calling it's Start method.
func New(conf Config) (s *StatsCtx, err error) {
defer withRecovered(&err)
s = &StatsCtx{
currMu: &sync.RWMutex{},
dbMu: &sync.Mutex{},
filename: conf.Filename,
configModified: conf.ConfigModified,
httpRegister: conf.HTTPRegister,
}
if s.limitHours = conf.LimitDays * 24; !checkInterval(conf.LimitDays) {
s.limitHours = 24
}
if s.unitIDGen = newUnitID; conf.UnitID != nil {
s.unitIDGen = conf.UnitID
}
// TODO(e.burkov): Move the code below to the Start method.
err = s.openDB()
if err != nil {
return nil, fmt.Errorf("opening database: %w", err)
}
var udb *unitDB
id := s.unitIDGen()
tx, err := s.db.Begin(true)
if err != nil {
return nil, fmt.Errorf("stats: opening a transaction: %w", err)
}
deleted := deleteOldUnits(tx, id-s.limitHours-1)
udb = loadUnitFromDB(tx, id)
err = finishTxn(tx, deleted > 0)
if err != nil {
log.Error("stats: %s", err)
}
s.curr = newUnit(id)
s.curr.deserialize(udb)
log.Debug("stats: initialized")
return s, nil
}
// withRecovered turns the value recovered from panic if any into an error and
// combines it with the one pointed by orig. orig must be non-nil.
func withRecovered(orig *error) {
p := recover()
if p == nil {
return
}
var err error
switch p := p.(type) {
case error:
err = fmt.Errorf("panic: %w", p)
default:
err = fmt.Errorf("panic: recovered value of type %[1]T: %[1]v", p)
}
*orig = errors.WithDeferred(*orig, err)
}
// Start implements the Interface interface for *StatsCtx.
func (s *StatsCtx) Start() {
s.initWeb()
go s.periodicFlush()
}
// Close implements the io.Closer interface for *StatsCtx.
func (s *StatsCtx) Close() (err error) {
defer func() { err = errors.Annotate(err, "stats: closing: %w") }()
db := s.swapDatabase(nil)
if db == nil {
return nil
}
defer func() {
cerr := db.Close()
if cerr == nil {
log.Debug("stats: database closed")
}
err = errors.WithDeferred(err, cerr)
}()
tx, err := db.Begin(true)
if err != nil {
return fmt.Errorf("opening transaction: %w", err)
}
defer func() { err = errors.WithDeferred(err, finishTxn(tx, err == nil)) }()
s.currMu.RLock()
defer s.currMu.RUnlock()
udb := s.curr.serialize()
return udb.flushUnitToDB(tx, s.curr.id)
}
// Update implements the Interface interface for *StatsCtx.
func (s *StatsCtx) Update(e Entry) {
if atomic.LoadUint32(&s.limitHours) == 0 {
return
}
if e.Result == 0 || e.Result >= resultLast || e.Domain == "" || e.Client == "" {
log.Debug("stats: malformed entry")
return
}
s.currMu.Lock()
defer s.currMu.Unlock()
if s.curr == nil {
log.Error("stats: current unit is nil")
return
}
clientID := e.Client
if ip := net.ParseIP(clientID); ip != nil {
clientID = ip.String()
}
s.curr.add(e.Result, e.Domain, clientID, uint64(e.Time))
}
// WriteDiskConfig implements the Interface interface for *StatsCtx.
func (s *StatsCtx) WriteDiskConfig(dc *DiskConfig) {
dc.Interval = atomic.LoadUint32(&s.limitHours) / 24
}
// TopClientsIP implements the Interface interface for *StatsCtx.
func (s *StatsCtx) TopClientsIP(maxCount uint) (ips []net.IP) {
limit := atomic.LoadUint32(&s.limitHours)
if limit == 0 {
return nil
}
units, _ := s.loadUnits(limit)
if units == nil {
return nil
}
// Collect data for all the clients to sort and crop it afterwards.
m := map[string]uint64{}
for _, u := range units {
for _, it := range u.Clients {
m[it.Name] += it.Count
}
}
a := convertMapToSlice(m, int(maxCount))
ips = []net.IP{}
for _, it := range a {
ip := net.ParseIP(it.Name)
if ip != nil {
ips = append(ips, ip)
}
}
return ips
}
// database returns the database if it's opened. It's safe for concurrent use.
func (s *StatsCtx) database() (db *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
return s.db
}
// swapDatabase swaps the database with another one and returns it. It's safe
// for concurrent use.
func (s *StatsCtx) swapDatabase(with *bbolt.DB) (old *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
old, s.db = s.db, with
return old
}
// deleteOldUnits walks the buckets available to tx and deletes old units. It
// returns the number of deletions performed.
func deleteOldUnits(tx *bbolt.Tx, firstID uint32) (deleted int) {
log.Debug("stats: deleting old units until id %d", firstID)
// TODO(a.garipov): See if this is actually necessary. Looks like a rather
// bizarre solution.
const errStop errors.Error = "stop iteration"
walk := func(name []byte, _ *bbolt.Bucket) (err error) {
nameID, ok := unitNameToID(name)
if ok && nameID >= firstID {
return errStop
}
err = tx.DeleteBucket(name)
if err != nil {
log.Debug("stats: deleting bucket: %s", err)
return nil
}
log.Debug("stats: deleted unit %d (name %x)", nameID, name)
deleted++
return nil
}
err := tx.ForEach(walk)
if err != nil && !errors.Is(err, errStop) {
log.Debug("stats: deleting units: %s", err)
}
return deleted
}
// openDB returns an error if the database can't be opened from the specified
// file. It's safe for concurrent use.
func (s *StatsCtx) openDB() (err error) {
log.Debug("stats: opening database")
var db *bbolt.DB
db, err = bbolt.Open(s.filename, 0o644, nil)
if err != nil {
if err.Error() == "invalid argument" {
log.Error("AdGuard Home cannot be initialized due to an incompatible file system.\nPlease read the explanation here: https://github.com/AdguardTeam/AdGuardHome/wiki/Getting-Started#limitations")
}
return err
}
// Use defer to unlock the mutex as soon as possible.
defer log.Debug("stats: database opened")
s.dbMu.Lock()
defer s.dbMu.Unlock()
s.db = db
return nil
}
func (s *StatsCtx) flush() (cont bool, sleepFor time.Duration) {
id := s.unitIDGen()
s.currMu.Lock()
defer s.currMu.Unlock()
ptr := s.curr
if ptr == nil {
return false, 0
}
limit := atomic.LoadUint32(&s.limitHours)
if limit == 0 || ptr.id == id {
return true, time.Second
}
db := s.database()
if db == nil {
return true, 0
}
tx, err := db.Begin(true)
if err != nil {
log.Error("stats: opening transaction: %s", err)
return true, 0
}
s.curr = newUnit(id)
isCommitable := true
ferr := ptr.serialize().flushUnitToDB(tx, ptr.id)
if ferr != nil {
log.Error("stats: flushing unit: %s", ferr)
isCommitable = false
}
derr := tx.DeleteBucket(idToUnitName(id - limit))
if derr != nil {
log.Error("stats: deleting unit: %s", derr)
if !errors.Is(derr, bbolt.ErrBucketNotFound) {
isCommitable = false
}
}
err = finishTxn(tx, isCommitable)
if err != nil {
log.Error("stats: %s", err)
}
return true, 0
}
// periodicFlush checks and flushes the unit to the database if the freshly
// generated unit ID differs from the current's ID. Flushing process includes:
// - swapping the current unit with the new empty one;
// - writing the current unit to the database;
// - removing the stale unit from the database.
func (s *StatsCtx) periodicFlush() {
for cont, sleepFor := true, time.Duration(0); cont; time.Sleep(sleepFor) {
cont, sleepFor = s.flush()
}
log.Debug("periodic flushing finished")
}
func (s *StatsCtx) setLimit(limitDays int) {
atomic.StoreUint32(&s.limitHours, uint32(24*limitDays))
if limitDays == 0 {
if err := s.clear(); err != nil {
log.Error("stats: %s", err)
}
}
log.Debug("stats: set limit: %d days", limitDays)
}
// Reset counters and clear database
func (s *StatsCtx) clear() (err error) {
defer func() { err = errors.Annotate(err, "clearing: %w") }()
db := s.swapDatabase(nil)
if db != nil {
var tx *bbolt.Tx
tx, err = db.Begin(true)
if err != nil {
log.Error("stats: opening a transaction: %s", err)
} else if err = finishTxn(tx, false); err != nil {
// Don't wrap the error since it's informative enough as is.
return err
}
// Active transactions will continue using database, but new ones won't
// be created.
err = db.Close()
if err != nil {
return fmt.Errorf("closing database: %w", err)
}
// All active transactions are now closed.
log.Debug("stats: database closed")
}
err = os.Remove(s.filename)
if err != nil {
log.Error("stats: %s", err)
}
err = s.openDB()
if err != nil {
log.Error("stats: opening database: %s", err)
}
// Use defer to unlock the mutex as soon as possible.
defer log.Debug("stats: cleared")
s.currMu.Lock()
defer s.currMu.Unlock()
s.curr = newUnit(s.unitIDGen())
return nil
}
func (s *StatsCtx) loadUnits(limit uint32) (units []*unitDB, firstID uint32) {
db := s.database()
if db == nil {
return nil, 0
}
// Use writable transaction to ensure any ongoing writable transaction is
// taken into account.
tx, err := db.Begin(true)
if err != nil {
log.Error("stats: opening transaction: %s", err)
return nil, 0
}
s.currMu.RLock()
defer s.currMu.RUnlock()
cur := s.curr
var curID uint32
if cur != nil {
curID = cur.id
} else {
curID = s.unitIDGen()
}
// Per-hour units.
units = make([]*unitDB, 0, limit)
firstID = curID - limit + 1
for i := firstID; i != curID; i++ {
u := loadUnitFromDB(tx, i)
if u == nil {
u = &unitDB{NResult: make([]uint64, resultLast)}
}
units = append(units, u)
}
err = finishTxn(tx, false)
if err != nil {
log.Error("stats: %s", err)
} | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
return StatsResp{ | <mask> */
<mask> func (s *StatsCtx) getData() (statsResponse, bool) {
<mask> limit := atomic.LoadUint32(&s.limitHours)
<mask> if limit == 0 {
<mask> return statsResponse{
<mask> TimeUnits: "days",
<mask>
<mask> TopBlocked: []topAddrs{},
<mask> TopClients: []topAddrs{},
<mask> TopQueried: []topAddrs{},
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove func (s *StatsCtx) getData() (statsResponse, bool) {
limit := atomic.LoadUint32(&s.limitHours)
</s> add func (s *StatsCtx) getData(limit uint32) (StatsResp, bool) { </s> remove m = d.TopClients
require.NotEmpty(t, m)
assert.EqualValues(t, 2, m[0]["127.0.0.1"])
</s> add t.Run("reset", func(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/control/stats_reset", nil)
assertSuccessAndUnmarshal(t, nil, handlers["/control/stats_reset"], req)
_24zeroes := [24]uint64{}
emptyData := &stats.StatsResp{
TimeUnits: "hours",
TopQueried: []map[string]uint64{},
TopClients: []map[string]uint64{},
TopBlocked: []map[string]uint64{},
DNSQueries: _24zeroes[:],
BlockedFiltering: _24zeroes[:],
ReplacedSafebrowsing: _24zeroes[:],
ReplacedParental: _24zeroes[:],
} </s> remove start := time.Now()
var resp statsResponse
var ok bool
resp, ok = s.getData()
</s> add limit := atomic.LoadUint32(&s.limitHours) </s> remove func (s *StatsCtx) setLimit(limitDays int) {
atomic.StoreUint32(&s.limitHours, uint32(24*limitDays))
if limitDays == 0 {
s.clear()
}
log.Debug("stats: set limit: %d days", limitDays)
}
func (s *StatsCtx) WriteDiskConfig(dc *DiskConfig) {
dc.Interval = atomic.LoadUint32(&s.limitHours) / 24
}
func (s *StatsCtx) Close() {
u := s.swapCurrent(nil)
db := s.database()
if tx := beginTxn(db, true); tx != nil {
udb := u.serialize()
if flushUnitToDB(tx, u.id, udb) {
s.commitTxn(tx)
} else {
_ = tx.Rollback()
}
}
if db != nil {
log.Tracef("db.Close...")
_ = db.Close()
log.Tracef("db.Close")
}
log.Debug("stats: closed")
}
// Reset counters and clear database
func (s *StatsCtx) clear() {
db := s.database()
tx := beginTxn(db, true)
if tx != nil {
_ = s.swapDatabase(nil)
_ = tx.Rollback()
// the active transactions can continue using database,
// but no new transactions will be opened
_ = db.Close()
log.Tracef("db.Close")
// all active transactions are now closed
}
u := newUnit(s.unitIDGen())
_ = s.swapCurrent(u)
err := os.Remove(s.filename)
if err != nil {
log.Error("os.Remove: %s", err)
}
_ = s.dbOpen()
log.Debug("stats: cleared")
}
func (s *StatsCtx) Update(e Entry) {
if !s.isEnabled() {
return
}
if e.Result == 0 ||
e.Result >= resultLast ||
e.Domain == "" ||
e.Client == "" {
return
}
clientID := e.Client
if ip := net.ParseIP(clientID); ip != nil {
clientID = ip.String()
}
u := s.ongoing()
if u == nil {
return
}
u.mu.Lock()
defer u.mu.Unlock()
u.nResult[e.Result]++
if e.Result == RNotFiltered {
u.domains[e.Domain]++
} else {
u.blockedDomains[e.Domain]++
}
u.clients[clientID]++
u.timeSum += uint64(e.Time)
u.nTotal++
}
func (s *StatsCtx) loadUnits(limit uint32) ([]*unitDB, uint32) {
tx := beginTxn(s.database(), false)
if tx == nil {
return nil, 0
}
cur := s.ongoing()
var curID uint32
if cur != nil {
curID = atomic.LoadUint32(&cur.id)
} else {
curID = s.unitIDGen()
}
// Per-hour units.
units := []*unitDB{}
firstID := curID - limit + 1
for i := firstID; i != curID; i++ {
u := s.loadUnitFromDB(tx, i)
if u == nil {
u = &unitDB{}
u.NResult = make([]uint64, resultLast)
}
units = append(units, u)
}
_ = tx.Rollback()
if cur != nil {
units = append(units, cur.serialize())
}
if len(units) != int(limit) {
log.Fatalf("len(units) != limit: %d %d", len(units), limit)
}
return units, firstID
}
</s> add | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
return StatsResp{}, false | <mask> }
<mask>
<mask> units, firstID := s.loadUnits(limit)
<mask> if units == nil {
<mask> return statsResponse{}, false
<mask> }
<mask>
<mask> dnsQueries := statsCollector(units, firstID, timeUnit, func(u *unitDB) (num uint64) { return u.NTotal })
<mask> if timeUnit != Hours && len(dnsQueries) != int(limit/24) {
<mask> log.Fatalf("len(dnsQueries) != limit: %d %d", len(dnsQueries), limit)
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove data := statsResponse{
</s> add data := StatsResp{ </s> remove func (s *StatsCtx) setLimit(limitDays int) {
atomic.StoreUint32(&s.limitHours, uint32(24*limitDays))
if limitDays == 0 {
s.clear()
}
log.Debug("stats: set limit: %d days", limitDays)
}
func (s *StatsCtx) WriteDiskConfig(dc *DiskConfig) {
dc.Interval = atomic.LoadUint32(&s.limitHours) / 24
}
func (s *StatsCtx) Close() {
u := s.swapCurrent(nil)
db := s.database()
if tx := beginTxn(db, true); tx != nil {
udb := u.serialize()
if flushUnitToDB(tx, u.id, udb) {
s.commitTxn(tx)
} else {
_ = tx.Rollback()
}
}
if db != nil {
log.Tracef("db.Close...")
_ = db.Close()
log.Tracef("db.Close")
}
log.Debug("stats: closed")
}
// Reset counters and clear database
func (s *StatsCtx) clear() {
db := s.database()
tx := beginTxn(db, true)
if tx != nil {
_ = s.swapDatabase(nil)
_ = tx.Rollback()
// the active transactions can continue using database,
// but no new transactions will be opened
_ = db.Close()
log.Tracef("db.Close")
// all active transactions are now closed
}
u := newUnit(s.unitIDGen())
_ = s.swapCurrent(u)
err := os.Remove(s.filename)
if err != nil {
log.Error("os.Remove: %s", err)
}
_ = s.dbOpen()
log.Debug("stats: cleared")
}
func (s *StatsCtx) Update(e Entry) {
if !s.isEnabled() {
return
}
if e.Result == 0 ||
e.Result >= resultLast ||
e.Domain == "" ||
e.Client == "" {
return
}
clientID := e.Client
if ip := net.ParseIP(clientID); ip != nil {
clientID = ip.String()
}
u := s.ongoing()
if u == nil {
return
}
u.mu.Lock()
defer u.mu.Unlock()
u.nResult[e.Result]++
if e.Result == RNotFiltered {
u.domains[e.Domain]++
} else {
u.blockedDomains[e.Domain]++
}
u.clients[clientID]++
u.timeSum += uint64(e.Time)
u.nTotal++
}
func (s *StatsCtx) loadUnits(limit uint32) ([]*unitDB, uint32) {
tx := beginTxn(s.database(), false)
if tx == nil {
return nil, 0
}
cur := s.ongoing()
var curID uint32
if cur != nil {
curID = atomic.LoadUint32(&cur.id)
} else {
curID = s.unitIDGen()
}
// Per-hour units.
units := []*unitDB{}
firstID := curID - limit + 1
for i := firstID; i != curID; i++ {
u := s.loadUnitFromDB(tx, i)
if u == nil {
u = &unitDB{}
u.NResult = make([]uint64, resultLast)
}
units = append(units, u)
}
_ = tx.Rollback()
if cur != nil {
units = append(units, cur.serialize())
}
if len(units) != int(limit) {
log.Fatalf("len(units) != limit: %d %d", len(units), limit)
}
return units, firstID
}
</s> add </s> remove func flushUnitToDB(tx *bbolt.Tx, id uint32, udb *unitDB) bool {
log.Tracef("Flushing unit %d", id)
</s> add // add adds new data to u. It's safe for concurrent use.
func (u *unit) add(res Result, domain, cli string, dur uint64) {
u.nResult[res]++
if res == RNotFiltered {
u.domains[domain]++
} else {
u.blockedDomains[domain]++
}
u.clients[cli]++
u.timeSum += dur
u.nTotal++
}
// flushUnitToDB puts udb to the database at id.
func (udb *unitDB) flushUnitToDB(tx *bbolt.Tx, id uint32) (err error) {
log.Debug("stats: flushing unit with id %d and total of %d", id, udb.NTotal) </s> remove
func (s *StatsCtx) GetTopClientsIP(maxCount uint) []net.IP {
if !s.isEnabled() {
return nil
}
units, _ := s.loadUnits(atomic.LoadUint32(&s.limitHours))
if units == nil {
return nil
}
// top clients
m := map[string]uint64{}
for _, u := range units {
for _, it := range u.Clients {
m[it.Name] += it.Count
}
}
a := convertMapToSlice(m, int(maxCount))
d := []net.IP{}
for _, it := range a {
ip := net.ParseIP(it.Name)
if ip != nil {
d = append(d, ip)
}
}
return d
}
</s> add | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
data := StatsResp{ | <mask> if timeUnit != Hours && len(dnsQueries) != int(limit/24) {
<mask> log.Fatalf("len(dnsQueries) != limit: %d %d", len(dnsQueries), limit)
<mask> }
<mask>
<mask> data := statsResponse{
<mask> DNSQueries: dnsQueries,
<mask> BlockedFiltering: statsCollector(units, firstID, timeUnit, func(u *unitDB) (num uint64) { return u.NResult[RFiltered] }),
<mask> ReplacedSafebrowsing: statsCollector(units, firstID, timeUnit, func(u *unitDB) (num uint64) { return u.NResult[RSafeBrowsing] }),
<mask> ReplacedParental: statsCollector(units, firstID, timeUnit, func(u *unitDB) (num uint64) { return u.NResult[RParental] }),
<mask> TopQueried: topsCollector(units, maxDomains, func(u *unitDB) (pairs []countPair) { return u.Domains }),
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove return statsResponse{}, false
</s> add return StatsResp{}, false </s> remove func flushUnitToDB(tx *bbolt.Tx, id uint32, udb *unitDB) bool {
log.Tracef("Flushing unit %d", id)
</s> add // add adds new data to u. It's safe for concurrent use.
func (u *unit) add(res Result, domain, cli string, dur uint64) {
u.nResult[res]++
if res == RNotFiltered {
u.domains[domain]++
} else {
u.blockedDomains[domain]++
}
u.clients[cli]++
u.timeSum += dur
u.nTotal++
}
// flushUnitToDB puts udb to the database at id.
func (udb *unitDB) flushUnitToDB(tx *bbolt.Tx, id uint32) (err error) {
log.Debug("stats: flushing unit with id %d and total of %d", id, udb.NTotal) </s> remove func (s *StatsCtx) setLimit(limitDays int) {
atomic.StoreUint32(&s.limitHours, uint32(24*limitDays))
if limitDays == 0 {
s.clear()
}
log.Debug("stats: set limit: %d days", limitDays)
}
func (s *StatsCtx) WriteDiskConfig(dc *DiskConfig) {
dc.Interval = atomic.LoadUint32(&s.limitHours) / 24
}
func (s *StatsCtx) Close() {
u := s.swapCurrent(nil)
db := s.database()
if tx := beginTxn(db, true); tx != nil {
udb := u.serialize()
if flushUnitToDB(tx, u.id, udb) {
s.commitTxn(tx)
} else {
_ = tx.Rollback()
}
}
if db != nil {
log.Tracef("db.Close...")
_ = db.Close()
log.Tracef("db.Close")
}
log.Debug("stats: closed")
}
// Reset counters and clear database
func (s *StatsCtx) clear() {
db := s.database()
tx := beginTxn(db, true)
if tx != nil {
_ = s.swapDatabase(nil)
_ = tx.Rollback()
// the active transactions can continue using database,
// but no new transactions will be opened
_ = db.Close()
log.Tracef("db.Close")
// all active transactions are now closed
}
u := newUnit(s.unitIDGen())
_ = s.swapCurrent(u)
err := os.Remove(s.filename)
if err != nil {
log.Error("os.Remove: %s", err)
}
_ = s.dbOpen()
log.Debug("stats: cleared")
}
func (s *StatsCtx) Update(e Entry) {
if !s.isEnabled() {
return
}
if e.Result == 0 ||
e.Result >= resultLast ||
e.Domain == "" ||
e.Client == "" {
return
}
clientID := e.Client
if ip := net.ParseIP(clientID); ip != nil {
clientID = ip.String()
}
u := s.ongoing()
if u == nil {
return
}
u.mu.Lock()
defer u.mu.Unlock()
u.nResult[e.Result]++
if e.Result == RNotFiltered {
u.domains[e.Domain]++
} else {
u.blockedDomains[e.Domain]++
}
u.clients[clientID]++
u.timeSum += uint64(e.Time)
u.nTotal++
}
func (s *StatsCtx) loadUnits(limit uint32) ([]*unitDB, uint32) {
tx := beginTxn(s.database(), false)
if tx == nil {
return nil, 0
}
cur := s.ongoing()
var curID uint32
if cur != nil {
curID = atomic.LoadUint32(&cur.id)
} else {
curID = s.unitIDGen()
}
// Per-hour units.
units := []*unitDB{}
firstID := curID - limit + 1
for i := firstID; i != curID; i++ {
u := s.loadUnitFromDB(tx, i)
if u == nil {
u = &unitDB{}
u.NResult = make([]uint64, resultLast)
}
units = append(units, u)
}
_ = tx.Rollback()
if cur != nil {
units = append(units, cur.serialize())
}
if len(units) != int(limit) {
log.Fatalf("len(units) != limit: %d %d", len(units), limit)
}
return units, firstID
}
</s> add </s> remove d, ok := s.getData()
require.True(t, ok)
assert.EqualValues(t, hour*n, d.NumDNSQueries)
}
func TestStatsCollector(t *testing.T) {
ng := func(_ *unitDB) uint64 {
return 0
}
units := make([]*unitDB, 720)
</s> add req := httptest.NewRequest(http.MethodGet, "/control/stats", nil) </s> remove t.Run("hours", func(t *testing.T) {
statsData := statsCollector(units, 0, Hours, ng)
assert.Len(t, statsData, 720)
})
</s> add for h := 0; h < hoursNum; h++ {
atomic.AddUint32(&curHour, 1) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
<mask> }
<mask>
<mask> return data, true
<mask> }
<mask>
<mask> func (s *StatsCtx) GetTopClientsIP(maxCount uint) []net.IP {
<mask> if !s.isEnabled() {
<mask> return nil
<mask> }
<mask>
<mask> units, _ := s.loadUnits(atomic.LoadUint32(&s.limitHours))
<mask> if units == nil {
<mask> return nil
<mask> }
<mask>
<mask> // top clients
<mask> m := map[string]uint64{}
<mask> for _, u := range units {
<mask> for _, it := range u.Clients {
<mask> m[it.Name] += it.Count
<mask> }
<mask> }
<mask> a := convertMapToSlice(m, int(maxCount))
<mask> d := []net.IP{}
<mask> for _, it := range a {
<mask> ip := net.ParseIP(it.Name)
<mask> if ip != nil {
<mask> d = append(d, ip)
<mask> }
<mask> }
<mask> return d
<mask> }
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove func convertSliceToMap(a []countPair) map[string]uint64 {
m := map[string]uint64{}
</s> add func convertSliceToMap(a []countPair) (m map[string]uint64) {
m = map[string]uint64{} </s> remove for _, ip := range Context.stats.GetTopClientsIP(topClientsNumber) {
</s> add for _, ip := range Context.stats.TopClientsIP(topClientsNumber) { </s> remove func (s *StatsCtx) setLimit(limitDays int) {
atomic.StoreUint32(&s.limitHours, uint32(24*limitDays))
if limitDays == 0 {
s.clear()
}
log.Debug("stats: set limit: %d days", limitDays)
}
func (s *StatsCtx) WriteDiskConfig(dc *DiskConfig) {
dc.Interval = atomic.LoadUint32(&s.limitHours) / 24
}
func (s *StatsCtx) Close() {
u := s.swapCurrent(nil)
db := s.database()
if tx := beginTxn(db, true); tx != nil {
udb := u.serialize()
if flushUnitToDB(tx, u.id, udb) {
s.commitTxn(tx)
} else {
_ = tx.Rollback()
}
}
if db != nil {
log.Tracef("db.Close...")
_ = db.Close()
log.Tracef("db.Close")
}
log.Debug("stats: closed")
}
// Reset counters and clear database
func (s *StatsCtx) clear() {
db := s.database()
tx := beginTxn(db, true)
if tx != nil {
_ = s.swapDatabase(nil)
_ = tx.Rollback()
// the active transactions can continue using database,
// but no new transactions will be opened
_ = db.Close()
log.Tracef("db.Close")
// all active transactions are now closed
}
u := newUnit(s.unitIDGen())
_ = s.swapCurrent(u)
err := os.Remove(s.filename)
if err != nil {
log.Error("os.Remove: %s", err)
}
_ = s.dbOpen()
log.Debug("stats: cleared")
}
func (s *StatsCtx) Update(e Entry) {
if !s.isEnabled() {
return
}
if e.Result == 0 ||
e.Result >= resultLast ||
e.Domain == "" ||
e.Client == "" {
return
}
clientID := e.Client
if ip := net.ParseIP(clientID); ip != nil {
clientID = ip.String()
}
u := s.ongoing()
if u == nil {
return
}
u.mu.Lock()
defer u.mu.Unlock()
u.nResult[e.Result]++
if e.Result == RNotFiltered {
u.domains[e.Domain]++
} else {
u.blockedDomains[e.Domain]++
}
u.clients[clientID]++
u.timeSum += uint64(e.Time)
u.nTotal++
}
func (s *StatsCtx) loadUnits(limit uint32) ([]*unitDB, uint32) {
tx := beginTxn(s.database(), false)
if tx == nil {
return nil, 0
}
cur := s.ongoing()
var curID uint32
if cur != nil {
curID = atomic.LoadUint32(&cur.id)
} else {
curID = s.unitIDGen()
}
// Per-hour units.
units := []*unitDB{}
firstID := curID - limit + 1
for i := firstID; i != curID; i++ {
u := s.loadUnitFromDB(tx, i)
if u == nil {
u = &unitDB{}
u.NResult = make([]uint64, resultLast)
}
units = append(units, u)
}
_ = tx.Rollback()
if cur != nil {
units = append(units, cur.serialize())
}
if len(units) != int(limit) {
log.Fatalf("len(units) != limit: %d %d", len(units), limit)
}
return units, firstID
}
</s> add </s> remove // log.Tracef("Loading unit %d", id)
var buf bytes.Buffer
buf.Write(bkt.Get([]byte{0}))
dec := gob.NewDecoder(&buf)
udb := unitDB{}
err := dec.Decode(&udb)
if err != nil {
log.Error("gob Decode: %s", err)
return nil
}
return &udb
</s> add return nil </s> remove log.Debug("stats: deleted unit %d", id)
return true
}
func convertMapToSlice(m map[string]uint64, max int) []countPair {
a := []countPair{}
for k, v := range m {
a = append(a, countPair{Name: k, Count: v})
}
less := func(i, j int) bool {
return a[j].Count < a[i].Count
}
sort.Slice(a, less)
if max > len(a) {
max = len(a)
}
return a[:max]
</s> add return s[:max] | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/unit.go |
|
http.HandleFunc("/control/dhcp/add_static_lease", postInstall(optionalAuth(ensurePOST(handleDHCPAddStaticLease))))
http.HandleFunc("/control/dhcp/remove_static_lease", postInstall(optionalAuth(ensurePOST(handleDHCPRemoveStaticLease)))) | <mask> http.HandleFunc("/control/dhcp/status", postInstall(optionalAuth(ensureGET(handleDHCPStatus))))
<mask> http.HandleFunc("/control/dhcp/interfaces", postInstall(optionalAuth(ensureGET(handleDHCPInterfaces))))
<mask> http.HandleFunc("/control/dhcp/set_config", postInstall(optionalAuth(ensurePOST(handleDHCPSetConfig))))
<mask> http.HandleFunc("/control/dhcp/find_active_dhcp", postInstall(optionalAuth(ensurePOST(handleDHCPFindActiveServer))))
<mask>
<mask> RegisterTLSHandlers()
<mask> RegisterClientsHandlers()
<mask>
<mask> http.HandleFunc("/dns-query", postInstall(handleDOH))
</s> + dhcp: /dhcp/add_static_lease, /dhcp/remove_static_lease: control static lease table </s> remove if lease.Expiry.Unix() <= now {
</s> add if lease.Expiry.Unix() <= now && lease.Expiry.Unix() != leaseExpireStatic { </s> remove Expiry time.Time `json:"expires"`
</s> add // Lease expiration time
// 1: static lease
Expiry time.Time `json:"expires"` | [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/725aeeb910eeb69fc7463cd2492eaf97e4863868 | control.go |
type leaseJSON struct {
HWAddr string `json:"mac"`
IP string `json:"ip"`
Hostname string `json:"hostname"`
}
| <mask> }
<mask>
<mask> type dhcpServerConfigJSON struct {
<mask> dhcpd.ServerConfig `json:",inline"`
<mask> StaticLeases []leaseJSON `json:"static_leases"`
<mask> }
</s> + dhcp: /dhcp/add_static_lease, /dhcp/remove_static_lease: control static lease table </s> remove Expiry time.Time `json:"expires"`
</s> add // Lease expiration time
// 1: static lease
Expiry time.Time `json:"expires"` </s> remove if lease.Expiry.Unix() <= now {
</s> add if lease.Expiry.Unix() <= now && lease.Expiry.Unix() != leaseExpireStatic { | [
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/725aeeb910eeb69fc7463cd2492eaf97e4863868 | dhcp.go |
StaticLeases []leaseJSON `json:"static_leases"` | <mask> type dhcpServerConfigJSON struct {
<mask> dhcpd.ServerConfig `json:",inline"`
<mask> }
<mask>
<mask> func handleDHCPSetConfig(w http.ResponseWriter, r *http.Request) {
<mask> log.Tracef("%s %v", r.Method, r.URL)
<mask> newconfig := dhcpServerConfigJSON{}
</s> + dhcp: /dhcp/add_static_lease, /dhcp/remove_static_lease: control static lease table </s> remove if lease.Expiry.Unix() <= now {
</s> add if lease.Expiry.Unix() <= now && lease.Expiry.Unix() != leaseExpireStatic { </s> remove Expiry time.Time `json:"expires"`
</s> add // Lease expiration time
// 1: static lease
Expiry time.Time `json:"expires"` | [
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/725aeeb910eeb69fc7463cd2492eaf97e4863868 | dhcp.go |
const leaseExpireStatic = 1 | <mask> )
<mask>
<mask> const defaultDiscoverTime = time.Second * 3
<mask>
<mask> // Lease contains the necessary information about a DHCP lease
<mask> // field ordering is important -- yaml fields will mirror ordering from here
<mask> type Lease struct {
<mask> HWAddr net.HardwareAddr `json:"mac" yaml:"hwaddr"`
</s> + dhcp: /dhcp/add_static_lease, /dhcp/remove_static_lease: control static lease table </s> remove Expiry time.Time `json:"expires"`
</s> add // Lease expiration time
// 1: static lease
Expiry time.Time `json:"expires"` </s> remove if lease.Expiry.Unix() <= now {
</s> add if lease.Expiry.Unix() <= now && lease.Expiry.Unix() != leaseExpireStatic { | [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/725aeeb910eeb69fc7463cd2492eaf97e4863868 | dhcpd/dhcpd.go |
// Lease expiration time
// 1: static lease
Expiry time.Time `json:"expires"` | <mask> type Lease struct {
<mask> HWAddr net.HardwareAddr `json:"mac" yaml:"hwaddr"`
<mask> IP net.IP `json:"ip"`
<mask> Hostname string `json:"hostname"`
<mask> Expiry time.Time `json:"expires"`
<mask> }
<mask>
<mask> // ServerConfig - DHCP server configuration
<mask> // field ordering is important -- yaml fields will mirror ordering from here
<mask> type ServerConfig struct {
</s> + dhcp: /dhcp/add_static_lease, /dhcp/remove_static_lease: control static lease table </s> remove if lease.Expiry.Unix() <= now {
</s> add if lease.Expiry.Unix() <= now && lease.Expiry.Unix() != leaseExpireStatic { | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/725aeeb910eeb69fc7463cd2492eaf97e4863868 | dhcpd/dhcpd.go |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.