docstring_tokens
stringlengths
18
16.9k
code_tokens
stringlengths
75
1.81M
html_url
stringlengths
74
116
file_name
stringlengths
3
311
keep replace keep keep keep replace keep keep
<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) { <mask> reqData := config{} </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 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 </s> remove _, err = w.Write(data) </s> add err := json.NewEncoder(w).Encode(resp)
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/http.go
keep keep keep keep replace keep keep keep keep keep
<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 </s> remove // Get configuration </s> add // handleStatsInfo handles requests to the GET /control/stats_info endpoint.
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/http.go
keep keep keep keep replace keep keep keep keep keep
<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. </s> remove start := time.Now() var resp statsResponse var ok bool resp, ok = s.getData() </s> add limit := atomic.LoadUint32(&s.limitHours)
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/http.go
keep keep replace keep keep replace keep
<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() { </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 // 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 reqData := config{} </s> add reqData := configResp{} </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)
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/http.go
keep keep add keep keep keep keep
<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> add "encoding/json" </s> remove "sync" "sync/atomic" </s> add </s> add "os" "sync" "sync/atomic" "time" </s> remove "net" "os" </s> add
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/stats.go
keep keep add keep keep keep keep
<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 </s> add "fmt" "io" </s> add "github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/log" "go.etcd.io/bbolt" </s> add "sync/atomic" </s> add "encoding/json"
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/stats.go
keep add keep keep keep keep
<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. </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
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/stats.go
keep keep keep keep replace replace replace replace keep keep keep keep keep
<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> add "github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/log" "go.etcd.io/bbolt" </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> add // 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 } </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 // 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
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/stats.go
keep add keep keep keep keep keep
<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 </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.
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/stats.go
keep keep keep keep replace replace keep keep keep keep keep
<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> add // 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 } </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 // 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.
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/stats.go
keep keep keep keep replace keep keep keep keep keep
<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 </s> add // // Must not be rewritten after creating to be accessed concurrently without // using mu.
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/stats.go
keep keep keep keep replace replace keep keep keep keep keep
<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 </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
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/stats.go
keep keep replace replace replace replace replace keep replace replace
<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 </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 // 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 // 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 // Time is the duration of the request processing in milliseconds. Time uint32 </s> add return units, firstID
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/stats.go
keep keep keep keep replace replace replace replace replace replace replace replace replace replace replace replace keep keep keep keep keep
<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()) } </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
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/stats.go
keep keep replace replace replace replace replace replace keep replace replace keep keep
<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
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/stats.go
keep keep keep keep replace replace keep keep keep keep
<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 </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
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/stats.go
keep keep keep keep replace replace keep
<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 </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
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/stats.go
replace keep keep keep keep keep
<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> add "fmt" "io" </s> add "encoding/json" </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 </s> add "os" "sync" "sync/atomic" "time"
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/stats_test.go
keep keep add keep keep keep keep
<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> add "fmt" "io" </s> add "sync/atomic" </s> remove "net" "os" </s> add </s> remove "sync" "sync/atomic" </s> add
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/stats_test.go
keep keep keep keep replace keep keep keep keep keep
<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> add "fmt" "io" </s> remove package stats </s> add package stats_test </s> remove "net" "os" </s> add </s> remove "sync" "sync/atomic" </s> add </s> add "os" "sync" "sync/atomic" "time" </s> add "encoding/json"
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/stats_test.go
keep add keep keep keep keep keep
<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> add "sync/atomic" </s> add "github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/log" "go.etcd.io/bbolt" </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 // 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.
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/stats_test.go
keep keep keep replace replace replace replace keep replace replace replace replace keep keep keep
<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> } <mask> } <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.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 </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 return statsResponse{}, false </s> add return StatsResp{}, false
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/stats_test.go
keep keep keep replace keep keep keep replace replace keep keep
<mask> } <mask> } <mask> <mask> return true <mask> } <mask> <mask> func TestStats(t *testing.T) { <mask> conf := Config{ <mask> Filename: "./stats.db", <mask> LimitDays: 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 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> add UnitID: constUnitID, HTTPRegister: func(_, url string, handler http.HandlerFunc) { handlers[url] = handler }, </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)
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/stats_test.go
keep add keep keep keep keep
<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) </s> remove testutil.CleanupAndRequireSuccess(t, func() (err error) { s.clear() s.Close() </s> add
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/stats_test.go
keep keep keep replace keep replace replace replace
<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() </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.Close() </s> add </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"), </s> add UnitID: constUnitID, HTTPRegister: func(_, url string, handler http.HandlerFunc) { handlers[url] = handler },
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/stats_test.go
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
<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) }) </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{}
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/stats_test.go
keep keep keep keep replace replace keep keep keep keep keep
<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{} </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) })
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/stats_test.go
keep keep keep keep replace replace keep keep keep keep keep
<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{} </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) })
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/stats_test.go
keep replace replace keep keep keep keep keep keep keep keep replace replace replace keep keep
<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> 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 </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, 1} assert.True(t, UIntArrayEquals(d.BlockedFiltering, a)) </s> add for _, e := range entries { s.Update(e) } </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 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 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[:], }
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/stats_test.go
keep keep replace replace replace keep replace replace replace keep
<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.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) }) </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 )
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/stats_test.go
keep keep keep keep replace replace replace replace replace replace keep replace replace replace
<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])) </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.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 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)
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/stats_test.go
keep keep keep keep replace replace replace replace keep keep replace replace replace replace replace replace keep
<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, <mask> UnitID: newID, <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 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 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 s, err := New(conf) </s> add s, err := stats.New(conf) </s> remove return true </s> add err := json.Unmarshal(data, to) require.NoError(t, err) </s> remove testutil.CleanupAndRequireSuccess(t, func() (err error) { s.Close() </s> add
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/stats_test.go
keep replace replace keep replace replace keep
<mask> require.NoError(t, err) <mask> testutil.CleanupAndRequireSuccess(t, func() (err error) { <mask> s.Close() <mask> <mask> return os.Remove(conf.Filename) <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 testutil.CleanupAndRequireSuccess(t, func() (err error) { s.clear() 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 s, err := New(conf) </s> add s, err := stats.New(conf) </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 // 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 )
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/stats_test.go
keep keep keep keep replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace keep replace replace replace replace replace replace replace replace replace replace
<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> } <mask> <mask> func TestStatsCollector(t *testing.T) { <mask> ng := func(_ *unitDB) uint64 { <mask> return 0 <mask> } <mask> units := make([]*unitDB, 720) </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 testutil.CleanupAndRequireSuccess(t, func() (err error) { s.Close() </s> add </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, }
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/stats_test.go
keep keep keep keep replace replace replace replace keep replace replace replace replace
<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 }) </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 </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) })
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/stats_test.go
keep keep keep keep replace keep
<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 </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
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/stats_test.go
keep keep replace replace keep replace replace keep keep keep
<mask> "encoding/gob" <mask> "fmt" <mask> "net" <mask> "os" <mask> "sort" <mask> "sync" <mask> "sync/atomic" <mask> "time" <mask> <mask> "github.com/AdguardTeam/AdGuardHome/internal/aghhttp" </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> add "os" "sync" "sync/atomic" "time" </s> add "fmt" "io" </s> remove "github.com/AdguardTeam/AdGuardHome/internal/aghhttp" </s> add </s> remove "os" </s> add "net/http" "net/http/httptest" "path/filepath" </s> add "sync/atomic"
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/unit.go
keep keep keep keep replace keep keep keep keep keep
<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> add "os" "sync" "sync/atomic" "time" </s> add "github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/log" "go.etcd.io/bbolt" </s> add "sync/atomic" </s> remove "net" "os" </s> add </s> add "fmt" "io"
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/unit.go
keep keep keep replace replace keep keep replace replace
<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. </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 // 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 for _, ip := range Context.stats.GetTopClientsIP(topClientsNumber) { </s> add for _, ip := range Context.stats.TopClientsIP(topClientsNumber) { </s> remove // mu protects all the fields of a unit. mu *sync.RWMutex </s> add
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/unit.go
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 replace replace replace keep
<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. <mask> mu *sync.RWMutex <mask> <mask> // id is the unique unit's identifier. It's set to an absolute hour number </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 // 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 </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
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/unit.go
keep keep add keep keep keep keep
<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 </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
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/unit.go
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
<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 </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})
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/unit.go
keep keep keep keep replace keep keep keep keep keep
<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> add // // Must not be rewritten after creating to be accessed concurrently without // using mu. </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 { </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
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/unit.go
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
<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> add // 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 } </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}) </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)
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/unit.go
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 keep keep keep replace keep
<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> <mask> return <mask> } <mask> <mask> log.Tracef("transaction has been committed") <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)
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/unit.go
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 replace replace replace replace replace replace replace replace replace replace keep keep keep
<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> <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) </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 // 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) </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)
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/unit.go
keep keep keep replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace keep keep replace replace keep keep keep keep
<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 { <mask> m[it.Name] = it.Count <mask> } <mask> return m </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("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 </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 }
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/unit.go
keep keep keep keep replace keep replace replace replace
<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> </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 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 </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
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/unit.go
keep keep keep keep replace replace replace keep keep keep keep keep
<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) </s> add nums = make([]uint64, 0, len(units)) </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
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/unit.go
keep replace replace keep keep keep replace replace keep keep
<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 <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.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) </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
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/unit.go
keep keep replace replace replace keep replace replace keep keep
<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("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 // 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 return } </s> add
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/unit.go
keep keep keep keep replace replace replace replace replace replace replace replace replace replace replace keep keep replace replace replace replace replace replace replace replace replace replace replace replace replace
<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 <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 </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.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 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 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)
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/unit.go
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
<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) </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")
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/unit.go
keep add keep keep keep keep
<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) } </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 }
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/unit.go
keep keep keep keep replace replace keep replace keep
<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", </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> add start := time.Now() resp, ok := s.getData(limit) </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) } </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
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/unit.go
keep keep keep keep replace keep keep keep keep keep
<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> add nums = make([]uint64, 0, len(units)) </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 </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) }
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/unit.go
keep keep keep keep replace keep keep keep keep keep
<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) </s> remove u.mu.RLock() defer u.mu.RUnlock() </s> add
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/unit.go
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
<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] </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) }
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
internal/stats/unit.go
keep keep keep add keep keep keep keep keep
<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"` </s> add const leaseExpireStatic = 1 </s> add StaticLeases []leaseJSON `json:"static_leases"` </s> add type leaseJSON struct { HWAddr string `json:"mac"` IP string `json:"ip"` Hostname string `json:"hostname"` }
https://github.com/AdguardTeam/AdGuardHome/commit/725aeeb910eeb69fc7463cd2492eaf97e4863868
control.go
keep add keep keep keep keep
<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> add StaticLeases []leaseJSON `json:"static_leases"` </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 { </s> add const leaseExpireStatic = 1 </s> add http.HandleFunc("/control/dhcp/add_static_lease", postInstall(optionalAuth(ensurePOST(handleDHCPAddStaticLease)))) http.HandleFunc("/control/dhcp/remove_static_lease", postInstall(optionalAuth(ensurePOST(handleDHCPRemoveStaticLease))))
https://github.com/AdguardTeam/AdGuardHome/commit/725aeeb910eeb69fc7463cd2492eaf97e4863868
dhcp.go
keep add keep keep keep keep keep
<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> add type leaseJSON struct { HWAddr string `json:"mac"` IP string `json:"ip"` Hostname string `json:"hostname"` } </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"` </s> add const leaseExpireStatic = 1 </s> add http.HandleFunc("/control/dhcp/add_static_lease", postInstall(optionalAuth(ensurePOST(handleDHCPAddStaticLease)))) http.HandleFunc("/control/dhcp/remove_static_lease", postInstall(optionalAuth(ensurePOST(handleDHCPRemoveStaticLease))))
https://github.com/AdguardTeam/AdGuardHome/commit/725aeeb910eeb69fc7463cd2492eaf97e4863868
dhcp.go
keep keep add keep keep keep keep keep
<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> add type leaseJSON struct { HWAddr string `json:"mac"` IP string `json:"ip"` Hostname string `json:"hostname"` } </s> add StaticLeases []leaseJSON `json:"static_leases"` </s> remove if lease.Expiry.Unix() <= now { </s> add if lease.Expiry.Unix() <= now && lease.Expiry.Unix() != leaseExpireStatic { </s> add http.HandleFunc("/control/dhcp/add_static_lease", postInstall(optionalAuth(ensurePOST(handleDHCPAddStaticLease)))) http.HandleFunc("/control/dhcp/remove_static_lease", postInstall(optionalAuth(ensurePOST(handleDHCPRemoveStaticLease))))
https://github.com/AdguardTeam/AdGuardHome/commit/725aeeb910eeb69fc7463cd2492eaf97e4863868
dhcpd/dhcpd.go
keep keep keep keep replace keep keep keep keep keep
<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> add const leaseExpireStatic = 1 </s> add type leaseJSON struct { HWAddr string `json:"mac"` IP string `json:"ip"` Hostname string `json:"hostname"` } </s> add StaticLeases []leaseJSON `json:"static_leases"` </s> remove if lease.Expiry.Unix() <= now { </s> add if lease.Expiry.Unix() <= now && lease.Expiry.Unix() != leaseExpireStatic { </s> add http.HandleFunc("/control/dhcp/add_static_lease", postInstall(optionalAuth(ensurePOST(handleDHCPAddStaticLease)))) http.HandleFunc("/control/dhcp/remove_static_lease", postInstall(optionalAuth(ensurePOST(handleDHCPRemoveStaticLease))))
https://github.com/AdguardTeam/AdGuardHome/commit/725aeeb910eeb69fc7463cd2492eaf97e4863868
dhcpd/dhcpd.go
keep keep keep keep replace keep keep keep keep keep
<mask> // Find an expired lease and return its index or -1 <mask> func (s *Server) findExpiredLease() int { <mask> now := time.Now().Unix() <mask> for i, lease := range s.leases { <mask> if lease.Expiry.Unix() <= now { <mask> return i <mask> } <mask> } <mask> return -1 <mask> } </s> + dhcp: /dhcp/add_static_lease, /dhcp/remove_static_lease: control static lease table </s> add StaticLeases []leaseJSON `json:"static_leases"` </s> add type leaseJSON struct { HWAddr string `json:"mac"` IP string `json:"ip"` Hostname string `json:"hostname"` } </s> remove Expiry time.Time `json:"expires"` </s> add // Lease expiration time // 1: static lease Expiry time.Time `json:"expires"` </s> add const leaseExpireStatic = 1 </s> add http.HandleFunc("/control/dhcp/add_static_lease", postInstall(optionalAuth(ensurePOST(handleDHCPAddStaticLease)))) http.HandleFunc("/control/dhcp/remove_static_lease", postInstall(optionalAuth(ensurePOST(handleDHCPRemoveStaticLease))))
https://github.com/AdguardTeam/AdGuardHome/commit/725aeeb910eeb69fc7463cd2492eaf97e4863868
dhcpd/dhcpd.go
keep keep keep keep replace keep keep keep keep keep
<mask> <mask> require ( <mask> github.com/AdguardTeam/dnsproxy v0.39.13 <mask> github.com/AdguardTeam/golibs v0.10.3 <mask> github.com/AdguardTeam/urlfilter v0.15.0 <mask> github.com/NYTimes/gziphandler v1.1.1 <mask> github.com/ameshkov/dnscrypt/v2 v2.2.2 <mask> github.com/digineo/go-ipset/v2 v2.2.1 <mask> github.com/fsnotify/fsnotify v1.4.9 <mask> github.com/go-ping/ping v0.0.0-20210506233800-ff8be3320020 </s> Pull request: all: do not apply $denyallow to ip addrs Closes #3175. Squashed commit of the following: commit e80e4610a1ce70787d758c718cc7171570bcdd72 Author: Ainar Garipov <[email protected]> Date: Tue Dec 14 18:03:26 2021 +0300 all: imp docs commit 3c73a727e91f7da3d4bbbbf9c019997af4bebd33 Author: Ainar Garipov <[email protected]> Date: Tue Dec 14 17:57:01 2021 +0300 all: do not apply $denyallow to ip addrs </s> remove github.com/AdguardTeam/urlfilter v0.15.0 h1:K3WWZE0K5nPTHe2l+TRXDFpYWJJnvkHdlWidt6NQUTk= github.com/AdguardTeam/urlfilter v0.15.0/go.mod h1:EwXwrYhowP7bedqmOrmKKmQtpBYFyDNEBFQ+lxdUgQU= </s> add github.com/AdguardTeam/urlfilter v0.15.1 h1:dP6S7J6eFAk8MN4IDpUq2fZoBo8K8fmc6pXpxNIv84M= github.com/AdguardTeam/urlfilter v0.15.1/go.mod h1:EwXwrYhowP7bedqmOrmKKmQtpBYFyDNEBFQ+lxdUgQU= </s> add require github.com/stretchr/objx v0.1.1 // indirect </s> remove github.com/stretchr/objx v0.1.1 // indirect </s> add
https://github.com/AdguardTeam/AdGuardHome/commit/72a160ac59395cd700d270eaf7234c95c62533ea
go.mod
keep keep keep keep replace keep keep keep keep keep
<mask> github.com/mdlayher/netlink v1.4.0 <mask> github.com/mdlayher/raw v0.0.0-20210412142147-51b895745faf <mask> github.com/miekg/dns v1.1.43 <mask> github.com/satori/go.uuid v1.2.0 <mask> github.com/stretchr/objx v0.1.1 // indirect <mask> github.com/stretchr/testify v1.7.0 <mask> github.com/ti-mo/netfilter v0.4.0 <mask> go.etcd.io/bbolt v1.3.6 <mask> golang.org/x/crypto v0.0.0-20210817164053-32db794688a5 <mask> golang.org/x/net v0.0.0-20210929193557-e81a3d93ecf6 </s> Pull request: all: do not apply $denyallow to ip addrs Closes #3175. Squashed commit of the following: commit e80e4610a1ce70787d758c718cc7171570bcdd72 Author: Ainar Garipov <[email protected]> Date: Tue Dec 14 18:03:26 2021 +0300 all: imp docs commit 3c73a727e91f7da3d4bbbbf9c019997af4bebd33 Author: Ainar Garipov <[email protected]> Date: Tue Dec 14 17:57:01 2021 +0300 all: do not apply $denyallow to ip addrs </s> remove github.com/AdguardTeam/urlfilter v0.15.0 h1:K3WWZE0K5nPTHe2l+TRXDFpYWJJnvkHdlWidt6NQUTk= github.com/AdguardTeam/urlfilter v0.15.0/go.mod h1:EwXwrYhowP7bedqmOrmKKmQtpBYFyDNEBFQ+lxdUgQU= </s> add github.com/AdguardTeam/urlfilter v0.15.1 h1:dP6S7J6eFAk8MN4IDpUq2fZoBo8K8fmc6pXpxNIv84M= github.com/AdguardTeam/urlfilter v0.15.1/go.mod h1:EwXwrYhowP7bedqmOrmKKmQtpBYFyDNEBFQ+lxdUgQU= </s> add require github.com/stretchr/objx v0.1.1 // indirect </s> remove github.com/AdguardTeam/urlfilter v0.15.0 </s> add github.com/AdguardTeam/urlfilter v0.15.1
https://github.com/AdguardTeam/AdGuardHome/commit/72a160ac59395cd700d270eaf7234c95c62533ea
go.mod
keep add keep keep
<mask> ) <mask> <mask> // TODO(e.burkov): Get rid of the fork in v0.108.0. <mask> replace github.com/insomniacslk/dhcp => github.com/AdguardTeam/dhcp v0.0.0-20210519141215-51808c73c0bf </s> Pull request: all: do not apply $denyallow to ip addrs Closes #3175. Squashed commit of the following: commit e80e4610a1ce70787d758c718cc7171570bcdd72 Author: Ainar Garipov <[email protected]> Date: Tue Dec 14 18:03:26 2021 +0300 all: imp docs commit 3c73a727e91f7da3d4bbbbf9c019997af4bebd33 Author: Ainar Garipov <[email protected]> Date: Tue Dec 14 17:57:01 2021 +0300 all: do not apply $denyallow to ip addrs </s> remove github.com/AdguardTeam/urlfilter v0.15.0 h1:K3WWZE0K5nPTHe2l+TRXDFpYWJJnvkHdlWidt6NQUTk= github.com/AdguardTeam/urlfilter v0.15.0/go.mod h1:EwXwrYhowP7bedqmOrmKKmQtpBYFyDNEBFQ+lxdUgQU= </s> add github.com/AdguardTeam/urlfilter v0.15.1 h1:dP6S7J6eFAk8MN4IDpUq2fZoBo8K8fmc6pXpxNIv84M= github.com/AdguardTeam/urlfilter v0.15.1/go.mod h1:EwXwrYhowP7bedqmOrmKKmQtpBYFyDNEBFQ+lxdUgQU= </s> remove github.com/stretchr/objx v0.1.1 // indirect </s> add </s> remove github.com/AdguardTeam/urlfilter v0.15.0 </s> add github.com/AdguardTeam/urlfilter v0.15.1
https://github.com/AdguardTeam/AdGuardHome/commit/72a160ac59395cd700d270eaf7234c95c62533ea
go.mod
keep keep keep keep replace replace keep keep keep keep keep
<mask> github.com/AdguardTeam/golibs v0.9.2/go.mod h1:fCAMwPBJ8S7YMYbTWvYS+eeTLblP5E04IDtNAo7y7IY= <mask> github.com/AdguardTeam/golibs v0.10.3 h1:FBgk17zf35ESVWQKIqEUiqqB2bDaCBC8X5vMU760yB4= <mask> github.com/AdguardTeam/golibs v0.10.3/go.mod h1:rSfQRGHIdgfxriDDNgNJ7HmE5zRoURq8R+VdR81Zuzw= <mask> github.com/AdguardTeam/gomitmproxy v0.2.0/go.mod h1:Qdv0Mktnzer5zpdpi5rAwixNJzW2FN91LjKJCkVbYGU= <mask> github.com/AdguardTeam/urlfilter v0.15.0 h1:K3WWZE0K5nPTHe2l+TRXDFpYWJJnvkHdlWidt6NQUTk= <mask> github.com/AdguardTeam/urlfilter v0.15.0/go.mod h1:EwXwrYhowP7bedqmOrmKKmQtpBYFyDNEBFQ+lxdUgQU= <mask> github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= <mask> github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= <mask> github.com/NYTimes/gziphandler v1.1.1 h1:ZUDjpQae29j0ryrS0u/B8HZfJBtBQHjqw2rQ2cqUQ3I= <mask> github.com/NYTimes/gziphandler v1.1.1/go.mod h1:n/CVRwUEOgIxrgPvAQhUUr9oeUtvrhMomdKFjzJNB0c= <mask> github.com/StackExchange/wmi v1.2.1 h1:VIkavFPXSjcnS+O8yTq7NI32k0R5Aj+v39y29VYDOSA= </s> Pull request: all: do not apply $denyallow to ip addrs Closes #3175. Squashed commit of the following: commit e80e4610a1ce70787d758c718cc7171570bcdd72 Author: Ainar Garipov <[email protected]> Date: Tue Dec 14 18:03:26 2021 +0300 all: imp docs commit 3c73a727e91f7da3d4bbbbf9c019997af4bebd33 Author: Ainar Garipov <[email protected]> Date: Tue Dec 14 17:57:01 2021 +0300 all: do not apply $denyallow to ip addrs </s> add require github.com/stretchr/objx v0.1.1 // indirect </s> remove github.com/stretchr/objx v0.1.1 // indirect </s> add </s> remove github.com/AdguardTeam/urlfilter v0.15.0 </s> add github.com/AdguardTeam/urlfilter v0.15.1
https://github.com/AdguardTeam/AdGuardHome/commit/72a160ac59395cd700d270eaf7234c95c62533ea
go.sum
keep keep keep keep replace replace replace replace replace replace
<mask> .logs__row:hover .button-action, <mask> .button-action--active { <mask> visibility: visible; <mask> } <mask> <mask> @media (max-width: 500px) { <mask> .dashboard .button-action { <mask> visibility: visible; <mask> } <mask> } </s> - client: 2152 Do not show dashboard buttons on mobile screen, fix buttons on DNS block/allow lists pages </s> remove > <Trans>check_updates_btn</Trans> </button> </div> ); </s> add > <Trans>check_updates_btn</Trans> </button> </div>; </s> remove }) => ( <div className="card-actions"> <button className="btn btn-success btn-standard mr-2 btn-large" </s> add }) => <div className="card-actions"> <button className="btn btn-success btn-standard mr-2 btn-large mb-2" </s> remove > {whitelist ? ( <Trans>add_allowlist</Trans> ) : ( <Trans>add_blocklist</Trans> )} </button> <button className="btn btn-primary btn-standard" </s> add > {whitelist ? <Trans>add_allowlist</Trans> : <Trans>add_blocklist</Trans>} </button> <button className="btn btn-primary btn-standard mb-2"
https://github.com/AdguardTeam/AdGuardHome/commit/72ab51bce0dd0b892acc797689f0cd32d779fd9f
client/src/components/App/index.css
keep keep keep replace replace replace replace keep keep replace replace replace replace replace replace replace replace replace keep keep keep keep
<mask> <mask> const Actions = ({ <mask> handleAdd, handleRefresh, processingRefreshFilters, whitelist, <mask> }) => ( <mask> <div className="card-actions"> <mask> <button <mask> className="btn btn-success btn-standard mr-2 btn-large" <mask> type="submit" <mask> onClick={handleAdd} <mask> > <mask> {whitelist ? ( <mask> <Trans>add_allowlist</Trans> <mask> ) : ( <mask> <Trans>add_blocklist</Trans> <mask> )} <mask> </button> <mask> <button <mask> className="btn btn-primary btn-standard" <mask> type="submit" <mask> onClick={handleRefresh} <mask> disabled={processingRefreshFilters} <mask> > </s> - client: 2152 Do not show dashboard buttons on mobile screen, fix buttons on DNS block/allow lists pages </s> remove > <Trans>check_updates_btn</Trans> </button> </div> ); </s> add > <Trans>check_updates_btn</Trans> </button> </div>; </s> remove @media (max-width: 500px) { .dashboard .button-action { visibility: visible; } } </s> add
https://github.com/AdguardTeam/AdGuardHome/commit/72ab51bce0dd0b892acc797689f0cd32d779fd9f
client/src/components/Filters/Actions.js
keep keep keep keep replace replace replace replace replace keep keep keep keep keep
<mask> className="btn btn-primary btn-standard" <mask> type="submit" <mask> onClick={handleRefresh} <mask> disabled={processingRefreshFilters} <mask> > <mask> <Trans>check_updates_btn</Trans> <mask> </button> <mask> </div> <mask> ); <mask> <mask> Actions.propTypes = { <mask> handleAdd: PropTypes.func.isRequired, <mask> handleRefresh: PropTypes.func.isRequired, <mask> processingRefreshFilters: PropTypes.bool.isRequired, </s> - client: 2152 Do not show dashboard buttons on mobile screen, fix buttons on DNS block/allow lists pages </s> remove > {whitelist ? ( <Trans>add_allowlist</Trans> ) : ( <Trans>add_blocklist</Trans> )} </button> <button className="btn btn-primary btn-standard" </s> add > {whitelist ? <Trans>add_allowlist</Trans> : <Trans>add_blocklist</Trans>} </button> <button className="btn btn-primary btn-standard mb-2" </s> remove }) => ( <div className="card-actions"> <button className="btn btn-success btn-standard mr-2 btn-large" </s> add }) => <div className="card-actions"> <button className="btn btn-success btn-standard mr-2 btn-large mb-2" </s> remove @media (max-width: 500px) { .dashboard .button-action { visibility: visible; } } </s> add
https://github.com/AdguardTeam/AdGuardHome/commit/72ab51bce0dd0b892acc797689f0cd32d779fd9f
client/src/components/Filters/Actions.js
keep keep keep add keep keep keep keep keep
<mask> type FilteringConfig struct { <mask> // Filtering callback function <mask> FilterHandler func(clientAddr string, settings *dnsfilter.RequestFilteringSettings) `yaml:"-"` <mask> <mask> ProtectionEnabled bool `yaml:"protection_enabled"` // whether or not use any of dnsfilter features <mask> <mask> BlockingMode string `yaml:"blocking_mode"` // mode how to answer filtered requests <mask> BlockedResponseTTL uint32 `yaml:"blocked_response_ttl"` // if 0, then default is used (3600) <mask> Ratelimit int `yaml:"ratelimit"` // max number of requests per second from a given IP (0 to disable) </s> + use per-client DNS servers </s> add Upstreams []string // list of upstream servers to be used for the client's requests </s> add Upstreams []string `json:"upstreams"` </s> remove // validateUpstreams validates each upstream and returns an error if any upstream is invalid or if there are no default upstreams specified func validateUpstreams(upstreams []string) error { </s> add // ValidateUpstreams validates each upstream and returns an error if any upstream is invalid or if there are no default upstreams specified func ValidateUpstreams(upstreams []string) error { </s> add func getUpstreamsByClient(clientAddr string) []string { c, ok := config.clients.Find(clientAddr) if !ok { return []string{} } log.Debug("Using upstreams %v for client %s (IP: %s)", c.Upstreams, c.Name, clientAddr) return c.Upstreams } </s> add if d.Addr != nil && s.conf.GetUpstreamsByClient != nil { clientIP, _, _ := net.SplitHostPort(d.Addr.String()) upstreams := s.conf.GetUpstreamsByClient(clientIP) for _, us := range upstreams { u, err := upstream.AddressToUpstream(us, upstream.Options{Timeout: 30 * time.Second}) if err != nil { log.Error("upstream.AddressToUpstream: %s: %s", us, err) continue } d.Upstreams = append(d.Upstreams, u) } } </s> remove err := validateUpstreams(upstreamsSet) </s> add err := ValidateUpstreams(upstreamsSet)
https://github.com/AdguardTeam/AdGuardHome/commit/7313c3bc5387cdc77f9f688e846a4a4aca5b1ec8
dnsforward/dnsforward.go
keep keep keep add keep keep keep keep keep
<mask> // resolve canonical name, not the original host name <mask> d.Req.Question[0].Name = dns.Fqdn(res.CanonName) <mask> } <mask> <mask> // request was not filtered so let it be processed further <mask> err = p.Resolve(d) <mask> if err != nil { <mask> return err <mask> } </s> + use per-client DNS servers </s> remove err = validateUpstreams(upstreamsSet) </s> add err = ValidateUpstreams(upstreamsSet) </s> add if len(c.Upstreams) != 0 { err := dnsforward.ValidateUpstreams(c.Upstreams) if err != nil { return fmt.Errorf("Invalid upstream servers: %s", err) } } </s> remove err = validateUpstreams(upstreamsSet) </s> add err = ValidateUpstreams(upstreamsSet) </s> add // This callback function returns the list of upstream servers for a client specified by IP address GetUpstreamsByClient func(clientAddr string) []string `yaml:"-"` </s> remove err = validateUpstreams(req.Upstreams) </s> add err = ValidateUpstreams(req.Upstreams) </s> add Upstreams []string // list of upstream servers to be used for the client's requests
https://github.com/AdguardTeam/AdGuardHome/commit/7313c3bc5387cdc77f9f688e846a4a4aca5b1ec8
dnsforward/dnsforward.go
keep keep keep keep replace keep keep keep keep keep
<mask> httpError(r, w, http.StatusBadRequest, "Failed to parse new upstreams config json: %s", err) <mask> return <mask> } <mask> <mask> err = validateUpstreams(req.Upstreams) <mask> if err != nil { <mask> httpError(r, w, http.StatusBadRequest, "wrong upstreams specification: %s", err) <mask> return <mask> } <mask> </s> + use per-client DNS servers </s> add if len(c.Upstreams) != 0 { err := dnsforward.ValidateUpstreams(c.Upstreams) if err != nil { return fmt.Errorf("Invalid upstream servers: %s", err) } } </s> add if d.Addr != nil && s.conf.GetUpstreamsByClient != nil { clientIP, _, _ := net.SplitHostPort(d.Addr.String()) upstreams := s.conf.GetUpstreamsByClient(clientIP) for _, us := range upstreams { u, err := upstream.AddressToUpstream(us, upstream.Options{Timeout: 30 * time.Second}) if err != nil { log.Error("upstream.AddressToUpstream: %s: %s", us, err) continue } d.Upstreams = append(d.Upstreams, u) } } </s> add Upstreams: cy.Upstreams, </s> remove err = validateUpstreams(upstreamsSet) </s> add err = ValidateUpstreams(upstreamsSet) </s> remove // validateUpstreams validates each upstream and returns an error if any upstream is invalid or if there are no default upstreams specified func validateUpstreams(upstreams []string) error { </s> add // ValidateUpstreams validates each upstream and returns an error if any upstream is invalid or if there are no default upstreams specified func ValidateUpstreams(upstreams []string) error { </s> add func getUpstreamsByClient(clientAddr string) []string { c, ok := config.clients.Find(clientAddr) if !ok { return []string{} } log.Debug("Using upstreams %v for client %s (IP: %s)", c.Upstreams, c.Name, clientAddr) return c.Upstreams }
https://github.com/AdguardTeam/AdGuardHome/commit/7313c3bc5387cdc77f9f688e846a4a4aca5b1ec8
dnsforward/dnsforward_http.go
keep keep keep keep replace replace keep keep keep keep keep
<mask> return <mask> } <mask> } <mask> <mask> // validateUpstreams validates each upstream and returns an error if any upstream is invalid or if there are no default upstreams specified <mask> func validateUpstreams(upstreams []string) error { <mask> var defaultUpstreamFound bool <mask> for _, u := range upstreams { <mask> d, err := validateUpstream(u) <mask> if err != nil { <mask> return err </s> + use per-client DNS servers </s> add if d.Addr != nil && s.conf.GetUpstreamsByClient != nil { clientIP, _, _ := net.SplitHostPort(d.Addr.String()) upstreams := s.conf.GetUpstreamsByClient(clientIP) for _, us := range upstreams { u, err := upstream.AddressToUpstream(us, upstream.Options{Timeout: 30 * time.Second}) if err != nil { log.Error("upstream.AddressToUpstream: %s: %s", us, err) continue } d.Upstreams = append(d.Upstreams, u) } } </s> remove err := validateUpstreams(upstreamsSet) </s> add err := ValidateUpstreams(upstreamsSet) </s> remove err = validateUpstreams(upstreamsSet) </s> add err = ValidateUpstreams(upstreamsSet) </s> remove err = validateUpstreams(upstreamsSet) </s> add err = ValidateUpstreams(upstreamsSet) </s> add if len(c.Upstreams) != 0 { err := dnsforward.ValidateUpstreams(c.Upstreams) if err != nil { return fmt.Errorf("Invalid upstream servers: %s", err) } } </s> remove err = validateUpstreams(req.Upstreams) </s> add err = ValidateUpstreams(req.Upstreams)
https://github.com/AdguardTeam/AdGuardHome/commit/7313c3bc5387cdc77f9f688e846a4a4aca5b1ec8
dnsforward/dnsforward_http.go
keep keep keep keep replace keep keep keep keep keep
<mask> "[/www.host.com/]#", <mask> "[/host.com/google.com/]8.8.8.8", <mask> "[/host/]sdns://AQMAAAAAAAAAFDE3Ni4xMDMuMTMwLjEzMDo1NDQzINErR_JS3PLCu_iZEIbq95zkSV2LFsigxDIuUso_OQhzIjIuZG5zY3J5cHQuZGVmYXVsdC5uczEuYWRndWFyZC5jb20", <mask> } <mask> err := validateUpstreams(upstreamsSet) <mask> if err == nil { <mask> t.Fatalf("there is no default upstream") <mask> } <mask> <mask> // Let's add default upstream </s> + use per-client DNS servers </s> remove err = validateUpstreams(upstreamsSet) </s> add err = ValidateUpstreams(upstreamsSet) </s> remove err = validateUpstreams(upstreamsSet) </s> add err = ValidateUpstreams(upstreamsSet) </s> remove // validateUpstreams validates each upstream and returns an error if any upstream is invalid or if there are no default upstreams specified func validateUpstreams(upstreams []string) error { </s> add // ValidateUpstreams validates each upstream and returns an error if any upstream is invalid or if there are no default upstreams specified func ValidateUpstreams(upstreams []string) error { </s> add if len(c.Upstreams) != 0 { err := dnsforward.ValidateUpstreams(c.Upstreams) if err != nil { return fmt.Errorf("Invalid upstream servers: %s", err) } } </s> add if d.Addr != nil && s.conf.GetUpstreamsByClient != nil { clientIP, _, _ := net.SplitHostPort(d.Addr.String()) upstreams := s.conf.GetUpstreamsByClient(clientIP) for _, us := range upstreams { u, err := upstream.AddressToUpstream(us, upstream.Options{Timeout: 30 * time.Second}) if err != nil { log.Error("upstream.AddressToUpstream: %s: %s", us, err) continue } d.Upstreams = append(d.Upstreams, u) } } </s> add Upstreams: cy.Upstreams,
https://github.com/AdguardTeam/AdGuardHome/commit/7313c3bc5387cdc77f9f688e846a4a4aca5b1ec8
dnsforward/dnsforward_test.go
keep keep keep keep replace keep keep keep keep keep
<mask> } <mask> <mask> // Let's add default upstream <mask> upstreamsSet = append(upstreamsSet, "8.8.8.8") <mask> err = validateUpstreams(upstreamsSet) <mask> if err != nil { <mask> t.Fatalf("upstreams set is valid, but doesn't pass through validation cause: %s", err) <mask> } <mask> <mask> // Let's add invalid upstream </s> + use per-client DNS servers </s> remove err = validateUpstreams(upstreamsSet) </s> add err = ValidateUpstreams(upstreamsSet) </s> remove err := validateUpstreams(upstreamsSet) </s> add err := ValidateUpstreams(upstreamsSet) </s> remove // validateUpstreams validates each upstream and returns an error if any upstream is invalid or if there are no default upstreams specified func validateUpstreams(upstreams []string) error { </s> add // ValidateUpstreams validates each upstream and returns an error if any upstream is invalid or if there are no default upstreams specified func ValidateUpstreams(upstreams []string) error { </s> add if len(c.Upstreams) != 0 { err := dnsforward.ValidateUpstreams(c.Upstreams) if err != nil { return fmt.Errorf("Invalid upstream servers: %s", err) } } </s> add if d.Addr != nil && s.conf.GetUpstreamsByClient != nil { clientIP, _, _ := net.SplitHostPort(d.Addr.String()) upstreams := s.conf.GetUpstreamsByClient(clientIP) for _, us := range upstreams { u, err := upstream.AddressToUpstream(us, upstream.Options{Timeout: 30 * time.Second}) if err != nil { log.Error("upstream.AddressToUpstream: %s: %s", us, err) continue } d.Upstreams = append(d.Upstreams, u) } } </s> remove err = validateUpstreams(req.Upstreams) </s> add err = ValidateUpstreams(req.Upstreams)
https://github.com/AdguardTeam/AdGuardHome/commit/7313c3bc5387cdc77f9f688e846a4a4aca5b1ec8
dnsforward/dnsforward_test.go
keep keep keep keep replace keep keep keep keep
<mask> } <mask> <mask> // Let's add invalid upstream <mask> upstreamsSet = append(upstreamsSet, "dhcp://fake.dns") <mask> err = validateUpstreams(upstreamsSet) <mask> if err == nil { <mask> t.Fatalf("there is an invalid upstream in set, but it pass through validation") <mask> } <mask> } </s> + use per-client DNS servers </s> remove err = validateUpstreams(upstreamsSet) </s> add err = ValidateUpstreams(upstreamsSet) </s> remove err := validateUpstreams(upstreamsSet) </s> add err := ValidateUpstreams(upstreamsSet) </s> remove // validateUpstreams validates each upstream and returns an error if any upstream is invalid or if there are no default upstreams specified func validateUpstreams(upstreams []string) error { </s> add // ValidateUpstreams validates each upstream and returns an error if any upstream is invalid or if there are no default upstreams specified func ValidateUpstreams(upstreams []string) error { </s> add if d.Addr != nil && s.conf.GetUpstreamsByClient != nil { clientIP, _, _ := net.SplitHostPort(d.Addr.String()) upstreams := s.conf.GetUpstreamsByClient(clientIP) for _, us := range upstreams { u, err := upstream.AddressToUpstream(us, upstream.Options{Timeout: 30 * time.Second}) if err != nil { log.Error("upstream.AddressToUpstream: %s: %s", us, err) continue } d.Upstreams = append(d.Upstreams, u) } } </s> add if len(c.Upstreams) != 0 { err := dnsforward.ValidateUpstreams(c.Upstreams) if err != nil { return fmt.Errorf("Invalid upstream servers: %s", err) } } </s> remove err = validateUpstreams(req.Upstreams) </s> add err = ValidateUpstreams(req.Upstreams)
https://github.com/AdguardTeam/AdGuardHome/commit/7313c3bc5387cdc77f9f688e846a4a4aca5b1ec8
dnsforward/dnsforward_test.go
keep keep keep add keep keep keep keep
<mask> "sync" <mask> "time" <mask> <mask> "github.com/AdguardTeam/AdGuardHome/dhcpd" <mask> "github.com/AdguardTeam/golibs/log" <mask> "github.com/AdguardTeam/golibs/utils" <mask> ) <mask> </s> + use per-client DNS servers </s> add func getUpstreamsByClient(clientAddr string) []string { c, ok := config.clients.Find(clientAddr) if !ok { return []string{} } log.Debug("Using upstreams %v for client %s (IP: %s)", c.Upstreams, c.Name, clientAddr) return c.Upstreams } </s> add newconfig.GetUpstreamsByClient = getUpstreamsByClient </s> add if d.Addr != nil && s.conf.GetUpstreamsByClient != nil { clientIP, _, _ := net.SplitHostPort(d.Addr.String()) upstreams := s.conf.GetUpstreamsByClient(clientIP) for _, us := range upstreams { u, err := upstream.AddressToUpstream(us, upstream.Options{Timeout: 30 * time.Second}) if err != nil { log.Error("upstream.AddressToUpstream: %s: %s", us, err) continue } d.Upstreams = append(d.Upstreams, u) } } </s> remove err = validateUpstreams(req.Upstreams) </s> add err = ValidateUpstreams(req.Upstreams) </s> remove // validateUpstreams validates each upstream and returns an error if any upstream is invalid or if there are no default upstreams specified func validateUpstreams(upstreams []string) error { </s> add // ValidateUpstreams validates each upstream and returns an error if any upstream is invalid or if there are no default upstreams specified func ValidateUpstreams(upstreams []string) error { </s> remove err := validateUpstreams(upstreamsSet) </s> add err := ValidateUpstreams(upstreamsSet)
https://github.com/AdguardTeam/AdGuardHome/commit/7313c3bc5387cdc77f9f688e846a4a4aca5b1ec8
home/clients.go
keep keep keep add keep keep keep keep keep
<mask> WhoisInfo [][]string // [[key,value], ...] <mask> <mask> UseOwnBlockedServices bool // false: use global settings <mask> BlockedServices []string <mask> } <mask> <mask> type clientSource uint <mask> <mask> // Client sources </s> + use per-client DNS servers </s> add // This callback function returns the list of upstream servers for a client specified by IP address GetUpstreamsByClient func(clientAddr string) []string `yaml:"-"` </s> add Upstreams []string `json:"upstreams"` </s> add Upstreams: cj.Upstreams, </s> add Upstreams []string `yaml:"upstreams"` </s> remove err = validateUpstreams(upstreamsSet) </s> add err = ValidateUpstreams(upstreamsSet) </s> remove // validateUpstreams validates each upstream and returns an error if any upstream is invalid or if there are no default upstreams specified func validateUpstreams(upstreams []string) error { </s> add // ValidateUpstreams validates each upstream and returns an error if any upstream is invalid or if there are no default upstreams specified func ValidateUpstreams(upstreams []string) error {
https://github.com/AdguardTeam/AdGuardHome/commit/7313c3bc5387cdc77f9f688e846a4a4aca5b1ec8
home/clients.go
keep keep keep add keep keep keep keep
<mask> SafeBrowsingEnabled bool `yaml:"safesearch_enabled"` <mask> <mask> UseGlobalBlockedServices bool `yaml:"use_global_blocked_services"` <mask> BlockedServices []string `yaml:"blocked_services"` <mask> } <mask> <mask> func (clients *clientsContainer) addFromConfig(objects []clientObject) { <mask> for _, cy := range objects { </s> + use per-client DNS servers </s> add Upstreams []string `json:"upstreams"` </s> add Upstreams: cli.Upstreams, </s> remove // validateUpstreams validates each upstream and returns an error if any upstream is invalid or if there are no default upstreams specified func validateUpstreams(upstreams []string) error { </s> add // ValidateUpstreams validates each upstream and returns an error if any upstream is invalid or if there are no default upstreams specified func ValidateUpstreams(upstreams []string) error { </s> add Upstreams []string // list of upstream servers to be used for the client's requests </s> add Upstreams: c.Upstreams, </s> add if d.Addr != nil && s.conf.GetUpstreamsByClient != nil { clientIP, _, _ := net.SplitHostPort(d.Addr.String()) upstreams := s.conf.GetUpstreamsByClient(clientIP) for _, us := range upstreams { u, err := upstream.AddressToUpstream(us, upstream.Options{Timeout: 30 * time.Second}) if err != nil { log.Error("upstream.AddressToUpstream: %s: %s", us, err) continue } d.Upstreams = append(d.Upstreams, u) } }
https://github.com/AdguardTeam/AdGuardHome/commit/7313c3bc5387cdc77f9f688e846a4a4aca5b1ec8
home/clients.go
keep keep keep add keep keep keep keep keep
<mask> SafeBrowsingEnabled: cy.SafeBrowsingEnabled, <mask> <mask> UseOwnBlockedServices: !cy.UseGlobalBlockedServices, <mask> BlockedServices: cy.BlockedServices, <mask> } <mask> _, err := clients.Add(cli) <mask> if err != nil { <mask> log.Tracef("clientAdd: %s", err) <mask> } </s> + use per-client DNS servers </s> add if len(c.Upstreams) != 0 { err := dnsforward.ValidateUpstreams(c.Upstreams) if err != nil { return fmt.Errorf("Invalid upstream servers: %s", err) } } </s> add if d.Addr != nil && s.conf.GetUpstreamsByClient != nil { clientIP, _, _ := net.SplitHostPort(d.Addr.String()) upstreams := s.conf.GetUpstreamsByClient(clientIP) for _, us := range upstreams { u, err := upstream.AddressToUpstream(us, upstream.Options{Timeout: 30 * time.Second}) if err != nil { log.Error("upstream.AddressToUpstream: %s: %s", us, err) continue } d.Upstreams = append(d.Upstreams, u) } } </s> remove err = validateUpstreams(req.Upstreams) </s> add err = ValidateUpstreams(req.Upstreams) </s> add Upstreams: cj.Upstreams, </s> add Upstreams: c.Upstreams, </s> remove err = validateUpstreams(upstreamsSet) </s> add err = ValidateUpstreams(upstreamsSet)
https://github.com/AdguardTeam/AdGuardHome/commit/7313c3bc5387cdc77f9f688e846a4a4aca5b1ec8
home/clients.go
keep keep keep add keep keep keep keep keep keep
<mask> SafeBrowsingEnabled: cli.SafeBrowsingEnabled, <mask> <mask> UseGlobalBlockedServices: !cli.UseOwnBlockedServices, <mask> BlockedServices: cli.BlockedServices, <mask> } <mask> *objects = append(*objects, cy) <mask> } <mask> } <mask> <mask> func (clients *clientsContainer) periodicUpdate() { </s> + use per-client DNS servers </s> add Upstreams: c.Upstreams, </s> add Upstreams []string `yaml:"upstreams"` </s> add Upstreams: cy.Upstreams, </s> add Upstreams: cj.Upstreams, </s> add newconfig.GetUpstreamsByClient = getUpstreamsByClient </s> add func getUpstreamsByClient(clientAddr string) []string { c, ok := config.clients.Find(clientAddr) if !ok { return []string{} } log.Debug("Using upstreams %v for client %s (IP: %s)", c.Upstreams, c.Name, clientAddr) return c.Upstreams }
https://github.com/AdguardTeam/AdGuardHome/commit/7313c3bc5387cdc77f9f688e846a4a4aca5b1ec8
home/clients.go
keep add keep keep keep keep
<mask> return fmt.Errorf("Invalid ID: %s", id) <mask> } <mask> return nil <mask> } <mask> <mask> // Add a new client object </s> + use per-client DNS servers </s> add func getUpstreamsByClient(clientAddr string) []string { c, ok := config.clients.Find(clientAddr) if !ok { return []string{} } log.Debug("Using upstreams %v for client %s (IP: %s)", c.Upstreams, c.Name, clientAddr) return c.Upstreams } </s> remove err = validateUpstreams(req.Upstreams) </s> add err = ValidateUpstreams(req.Upstreams) </s> add Upstreams: cj.Upstreams, </s> add if d.Addr != nil && s.conf.GetUpstreamsByClient != nil { clientIP, _, _ := net.SplitHostPort(d.Addr.String()) upstreams := s.conf.GetUpstreamsByClient(clientIP) for _, us := range upstreams { u, err := upstream.AddressToUpstream(us, upstream.Options{Timeout: 30 * time.Second}) if err != nil { log.Error("upstream.AddressToUpstream: %s: %s", us, err) continue } d.Upstreams = append(d.Upstreams, u) } } </s> add newconfig.GetUpstreamsByClient = getUpstreamsByClient </s> remove err = validateUpstreams(upstreamsSet) </s> add err = ValidateUpstreams(upstreamsSet)
https://github.com/AdguardTeam/AdGuardHome/commit/7313c3bc5387cdc77f9f688e846a4a4aca5b1ec8
home/clients.go
keep keep add keep keep keep keep
<mask> <mask> UseGlobalBlockedServices bool `json:"use_global_blocked_services"` <mask> BlockedServices []string `json:"blocked_services"` <mask> } <mask> <mask> type clientHostJSON struct { <mask> IP string `json:"ip"` </s> + use per-client DNS servers </s> add Upstreams []string `yaml:"upstreams"` </s> add // This callback function returns the list of upstream servers for a client specified by IP address GetUpstreamsByClient func(clientAddr string) []string `yaml:"-"` </s> add Upstreams []string // list of upstream servers to be used for the client's requests </s> add newconfig.GetUpstreamsByClient = getUpstreamsByClient </s> add func getUpstreamsByClient(clientAddr string) []string { c, ok := config.clients.Find(clientAddr) if !ok { return []string{} } log.Debug("Using upstreams %v for client %s (IP: %s)", c.Upstreams, c.Name, clientAddr) return c.Upstreams } </s> remove // validateUpstreams validates each upstream and returns an error if any upstream is invalid or if there are no default upstreams specified func validateUpstreams(upstreams []string) error { </s> add // ValidateUpstreams validates each upstream and returns an error if any upstream is invalid or if there are no default upstreams specified func ValidateUpstreams(upstreams []string) error {
https://github.com/AdguardTeam/AdGuardHome/commit/7313c3bc5387cdc77f9f688e846a4a4aca5b1ec8
home/clients_http.go
keep keep add keep keep keep keep keep keep
<mask> <mask> UseOwnBlockedServices: !cj.UseGlobalBlockedServices, <mask> BlockedServices: cj.BlockedServices, <mask> } <mask> return &c, nil <mask> } <mask> <mask> // Convert Client object to JSON <mask> func clientToJSON(c *Client) clientJSON { </s> + use per-client DNS servers </s> add Upstreams: cy.Upstreams, </s> add if len(c.Upstreams) != 0 { err := dnsforward.ValidateUpstreams(c.Upstreams) if err != nil { return fmt.Errorf("Invalid upstream servers: %s", err) } } </s> add Upstreams []string // list of upstream servers to be used for the client's requests </s> add Upstreams: cli.Upstreams, </s> add func getUpstreamsByClient(clientAddr string) []string { c, ok := config.clients.Find(clientAddr) if !ok { return []string{} } log.Debug("Using upstreams %v for client %s (IP: %s)", c.Upstreams, c.Name, clientAddr) return c.Upstreams } </s> add newconfig.GetUpstreamsByClient = getUpstreamsByClient
https://github.com/AdguardTeam/AdGuardHome/commit/7313c3bc5387cdc77f9f688e846a4a4aca5b1ec8
home/clients_http.go
keep keep keep add keep keep keep keep keep keep
<mask> SafeBrowsingEnabled: c.SafeBrowsingEnabled, <mask> <mask> UseGlobalBlockedServices: !c.UseOwnBlockedServices, <mask> BlockedServices: c.BlockedServices, <mask> } <mask> <mask> cj.WhoisInfo = make(map[string]interface{}) <mask> for _, wi := range c.WhoisInfo { <mask> cj.WhoisInfo[wi[0]] = wi[1] <mask> } </s> + use per-client DNS servers </s> add Upstreams: cli.Upstreams, </s> add Upstreams: cy.Upstreams, </s> add if d.Addr != nil && s.conf.GetUpstreamsByClient != nil { clientIP, _, _ := net.SplitHostPort(d.Addr.String()) upstreams := s.conf.GetUpstreamsByClient(clientIP) for _, us := range upstreams { u, err := upstream.AddressToUpstream(us, upstream.Options{Timeout: 30 * time.Second}) if err != nil { log.Error("upstream.AddressToUpstream: %s: %s", us, err) continue } d.Upstreams = append(d.Upstreams, u) } } </s> add Upstreams []string `yaml:"upstreams"` </s> add newconfig.GetUpstreamsByClient = getUpstreamsByClient </s> add Upstreams: cj.Upstreams,
https://github.com/AdguardTeam/AdGuardHome/commit/7313c3bc5387cdc77f9f688e846a4a4aca5b1ec8
home/clients_http.go
keep keep keep add keep keep keep keep keep
<mask> } <mask> } <mask> <mask> newconfig.FilterHandler = applyAdditionalFiltering <mask> return newconfig, nil <mask> } <mask> <mask> func getUpstreamsByClient(clientAddr string) []string { <mask> c, ok := config.clients.Find(clientAddr) </s> + use per-client DNS servers </s> add func getUpstreamsByClient(clientAddr string) []string { c, ok := config.clients.Find(clientAddr) if !ok { return []string{} } log.Debug("Using upstreams %v for client %s (IP: %s)", c.Upstreams, c.Name, clientAddr) return c.Upstreams } </s> add Upstreams: cj.Upstreams, </s> add if len(c.Upstreams) != 0 { err := dnsforward.ValidateUpstreams(c.Upstreams) if err != nil { return fmt.Errorf("Invalid upstream servers: %s", err) } } </s> add Upstreams: cli.Upstreams, </s> add if d.Addr != nil && s.conf.GetUpstreamsByClient != nil { clientIP, _, _ := net.SplitHostPort(d.Addr.String()) upstreams := s.conf.GetUpstreamsByClient(clientIP) for _, us := range upstreams { u, err := upstream.AddressToUpstream(us, upstream.Options{Timeout: 30 * time.Second}) if err != nil { log.Error("upstream.AddressToUpstream: %s: %s", us, err) continue } d.Upstreams = append(d.Upstreams, u) } } </s> remove err = validateUpstreams(req.Upstreams) </s> add err = ValidateUpstreams(req.Upstreams)
https://github.com/AdguardTeam/AdGuardHome/commit/7313c3bc5387cdc77f9f688e846a4a4aca5b1ec8
home/dns.go
keep keep add keep keep keep keep keep
<mask> return newconfig, nil <mask> } <mask> <mask> // If a client has his own settings, apply them <mask> func applyAdditionalFiltering(clientAddr string, setts *dnsfilter.RequestFilteringSettings) { <mask> <mask> ApplyBlockedServices(setts, config.DNS.BlockedServices) <mask> </s> + use per-client DNS servers </s> add if len(c.Upstreams) != 0 { err := dnsforward.ValidateUpstreams(c.Upstreams) if err != nil { return fmt.Errorf("Invalid upstream servers: %s", err) } } </s> add newconfig.GetUpstreamsByClient = getUpstreamsByClient </s> add // This callback function returns the list of upstream servers for a client specified by IP address GetUpstreamsByClient func(clientAddr string) []string `yaml:"-"` </s> add Upstreams: cj.Upstreams, </s> remove // validateUpstreams validates each upstream and returns an error if any upstream is invalid or if there are no default upstreams specified func validateUpstreams(upstreams []string) error { </s> add // ValidateUpstreams validates each upstream and returns an error if any upstream is invalid or if there are no default upstreams specified func ValidateUpstreams(upstreams []string) error { </s> add if d.Addr != nil && s.conf.GetUpstreamsByClient != nil { clientIP, _, _ := net.SplitHostPort(d.Addr.String()) upstreams := s.conf.GetUpstreamsByClient(clientIP) for _, us := range upstreams { u, err := upstream.AddressToUpstream(us, upstream.Options{Timeout: 30 * time.Second}) if err != nil { log.Error("upstream.AddressToUpstream: %s: %s", us, err) continue } d.Upstreams = append(d.Upstreams, u) } }
https://github.com/AdguardTeam/AdGuardHome/commit/7313c3bc5387cdc77f9f688e846a4a4aca5b1ec8
home/dns.go
keep keep add keep keep keep keep
<mask> } <mask> <mask> func TestError_Unwrap(t *testing.T) { <mask> const ( <mask> errSimple = iota <mask> errWrapped <mask> errNil </s> Pull request: all: fix lint and naming issues vol. 4 Merge in DNS/adguard-home from 2276-fix-lint-4 to master Updates #2276. Squashed commit of the following: commit 15d49184cd8ce1f8701bf3221e69418ca1778b36 Author: Ainar Garipov <[email protected]> Date: Tue Dec 8 15:51:34 2020 +0300 util: fix naming commit 3b9a86a0feb8c6e0b167e6e23105e8137b0dda76 Author: Ainar Garipov <[email protected]> Date: Tue Dec 8 15:41:10 2020 +0300 all: fix lint and naming issues vol. 4 </s> remove // // stats // // GetStats return dns filtering stats since startup. func (d *Dnsfilter) GetStats() Stats { return gctx.stats } </s> add </s> remove // NotFilteredError - there was a transitive error during check NotFilteredError </s> add </s> remove func FuncName() string { pc := make([]uintptr, 10) // at least 1 entry needed runtime.Callers(2, pc) f := runtime.FuncForPC(pc[0]) return path.Base(f.Name()) } </s> add </s> add "github.com/AdguardTeam/golibs/log" </s> remove "log" </s> add </s> add "github.com/AdguardTeam/golibs/log"
https://github.com/AdguardTeam/AdGuardHome/commit/73c30590e015f55e3de0a01f98a3c79761dce3b7
internal/agherr/agherr_test.go
keep keep keep keep replace replace keep keep keep keep keep
<mask> // NotFilteredNotFound - host was not find in any checks, default value for result <mask> NotFilteredNotFound Reason = iota <mask> // NotFilteredWhiteList - the host is explicitly whitelisted <mask> NotFilteredWhiteList <mask> // NotFilteredError - there was a transitive error during check <mask> NotFilteredError <mask> <mask> // reasons for filtering <mask> <mask> // FilteredBlackList - the host was matched to be advertising host <mask> FilteredBlackList </s> Pull request: all: fix lint and naming issues vol. 4 Merge in DNS/adguard-home from 2276-fix-lint-4 to master Updates #2276. Squashed commit of the following: commit 15d49184cd8ce1f8701bf3221e69418ca1778b36 Author: Ainar Garipov <[email protected]> Date: Tue Dec 8 15:51:34 2020 +0300 util: fix naming commit 3b9a86a0feb8c6e0b167e6e23105e8137b0dda76 Author: Ainar Garipov <[email protected]> Date: Tue Dec 8 15:41:10 2020 +0300 all: fix lint and naming issues vol. 4 </s> remove func FuncName() string { pc := make([]uintptr, 10) // at least 1 entry needed runtime.Callers(2, pc) f := runtime.FuncForPC(pc[0]) return path.Base(f.Name()) } </s> add </s> remove "path" </s> add </s> add var _ wrapper = &manyError{} </s> remove // // stats // // GetStats return dns filtering stats since startup. func (d *Dnsfilter) GetStats() Stats { return gctx.stats } </s> add </s> remove "log" </s> add </s> add "github.com/AdguardTeam/golibs/log"
https://github.com/AdguardTeam/AdGuardHome/commit/73c30590e015f55e3de0a01f98a3c79761dce3b7
internal/dnsfilter/dnsfilter.go
keep keep keep keep replace replace replace replace replace replace replace replace replace
<mask> d.registerRewritesHandlers() <mask> d.registerBlockedServicesHandlers() <mask> } <mask> } <mask> <mask> // <mask> // stats <mask> // <mask> <mask> // GetStats return dns filtering stats since startup. <mask> func (d *Dnsfilter) GetStats() Stats { <mask> return gctx.stats <mask> } </s> Pull request: all: fix lint and naming issues vol. 4 Merge in DNS/adguard-home from 2276-fix-lint-4 to master Updates #2276. Squashed commit of the following: commit 15d49184cd8ce1f8701bf3221e69418ca1778b36 Author: Ainar Garipov <[email protected]> Date: Tue Dec 8 15:51:34 2020 +0300 util: fix naming commit 3b9a86a0feb8c6e0b167e6e23105e8137b0dda76 Author: Ainar Garipov <[email protected]> Date: Tue Dec 8 15:41:10 2020 +0300 all: fix lint and naming issues vol. 4 </s> remove func FuncName() string { pc := make([]uintptr, 10) // at least 1 entry needed runtime.Callers(2, pc) f := runtime.FuncForPC(pc[0]) return path.Base(f.Name()) } </s> add </s> add var _ wrapper = &manyError{} </s> remove // NotFilteredError - there was a transitive error during check NotFilteredError </s> add </s> add "github.com/AdguardTeam/golibs/log" </s> remove "path" </s> add </s> remove "log" </s> add
https://github.com/AdguardTeam/AdGuardHome/commit/73c30590e015f55e3de0a01f98a3c79761dce3b7
internal/dnsfilter/dnsfilter.go
keep keep keep keep replace keep keep keep keep keep
<mask> <mask> package sysutil <mask> <mask> import ( <mask> "log" <mask> "log/syslog" <mask> ) <mask> <mask> func configureSyslog(serviceName string) error { <mask> w, err := syslog.New(syslog.LOG_NOTICE|syslog.LOG_USER, serviceName) </s> Pull request: all: fix lint and naming issues vol. 4 Merge in DNS/adguard-home from 2276-fix-lint-4 to master Updates #2276. Squashed commit of the following: commit 15d49184cd8ce1f8701bf3221e69418ca1778b36 Author: Ainar Garipov <[email protected]> Date: Tue Dec 8 15:51:34 2020 +0300 util: fix naming commit 3b9a86a0feb8c6e0b167e6e23105e8137b0dda76 Author: Ainar Garipov <[email protected]> Date: Tue Dec 8 15:41:10 2020 +0300 all: fix lint and naming issues vol. 4 </s> add "github.com/AdguardTeam/golibs/log" </s> remove "log" </s> add </s> remove func FuncName() string { pc := make([]uintptr, 10) // at least 1 entry needed runtime.Callers(2, pc) f := runtime.FuncForPC(pc[0]) return path.Base(f.Name()) } </s> add </s> add "github.com/AdguardTeam/golibs/log" </s> add var _ wrapper = &manyError{} </s> remove // // stats // // GetStats return dns filtering stats since startup. func (d *Dnsfilter) GetStats() Stats { return gctx.stats } </s> add
https://github.com/AdguardTeam/AdGuardHome/commit/73c30590e015f55e3de0a01f98a3c79761dce3b7
internal/sysutil/syslog_others.go
keep keep keep add keep keep keep keep keep
<mask> package sysutil <mask> <mask> import ( <mask> "log/syslog" <mask> ) <mask> <mask> func configureSyslog(serviceName string) error { <mask> w, err := syslog.New(syslog.LOG_NOTICE|syslog.LOG_USER, serviceName) <mask> if err != nil { </s> Pull request: all: fix lint and naming issues vol. 4 Merge in DNS/adguard-home from 2276-fix-lint-4 to master Updates #2276. Squashed commit of the following: commit 15d49184cd8ce1f8701bf3221e69418ca1778b36 Author: Ainar Garipov <[email protected]> Date: Tue Dec 8 15:51:34 2020 +0300 util: fix naming commit 3b9a86a0feb8c6e0b167e6e23105e8137b0dda76 Author: Ainar Garipov <[email protected]> Date: Tue Dec 8 15:41:10 2020 +0300 all: fix lint and naming issues vol. 4 </s> remove "log" </s> add </s> remove "log" </s> add </s> remove func FuncName() string { pc := make([]uintptr, 10) // at least 1 entry needed runtime.Callers(2, pc) f := runtime.FuncForPC(pc[0]) return path.Base(f.Name()) } </s> add </s> add var _ wrapper = &manyError{} </s> remove "path" </s> add </s> add "github.com/AdguardTeam/golibs/log"
https://github.com/AdguardTeam/AdGuardHome/commit/73c30590e015f55e3de0a01f98a3c79761dce3b7
internal/sysutil/syslog_others.go
keep keep keep keep replace keep keep keep keep keep
<mask> <mask> package sysutil <mask> <mask> import ( <mask> "log" <mask> "strings" <mask> <mask> "golang.org/x/sys/windows" <mask> "golang.org/x/sys/windows/svc/eventlog" <mask> ) </s> Pull request: all: fix lint and naming issues vol. 4 Merge in DNS/adguard-home from 2276-fix-lint-4 to master Updates #2276. Squashed commit of the following: commit 15d49184cd8ce1f8701bf3221e69418ca1778b36 Author: Ainar Garipov <[email protected]> Date: Tue Dec 8 15:51:34 2020 +0300 util: fix naming commit 3b9a86a0feb8c6e0b167e6e23105e8137b0dda76 Author: Ainar Garipov <[email protected]> Date: Tue Dec 8 15:41:10 2020 +0300 all: fix lint and naming issues vol. 4 </s> add "github.com/AdguardTeam/golibs/log" </s> remove "log" </s> add </s> add "github.com/AdguardTeam/golibs/log" </s> remove "path" </s> add </s> add var _ wrapper = &manyError{} </s> remove func FuncName() string { pc := make([]uintptr, 10) // at least 1 entry needed runtime.Callers(2, pc) f := runtime.FuncForPC(pc[0]) return path.Base(f.Name()) } </s> add
https://github.com/AdguardTeam/AdGuardHome/commit/73c30590e015f55e3de0a01f98a3c79761dce3b7
internal/sysutil/syslog_windows.go
keep keep keep add keep keep keep keep
<mask> <mask> import ( <mask> "strings" <mask> <mask> "golang.org/x/sys/windows" <mask> "golang.org/x/sys/windows/svc/eventlog" <mask> ) <mask> </s> Pull request: all: fix lint and naming issues vol. 4 Merge in DNS/adguard-home from 2276-fix-lint-4 to master Updates #2276. Squashed commit of the following: commit 15d49184cd8ce1f8701bf3221e69418ca1778b36 Author: Ainar Garipov <[email protected]> Date: Tue Dec 8 15:51:34 2020 +0300 util: fix naming commit 3b9a86a0feb8c6e0b167e6e23105e8137b0dda76 Author: Ainar Garipov <[email protected]> Date: Tue Dec 8 15:41:10 2020 +0300 all: fix lint and naming issues vol. 4 </s> remove "log" </s> add </s> remove "path" </s> add </s> remove "log" </s> add </s> add "github.com/AdguardTeam/golibs/log" </s> add var _ wrapper = &manyError{} </s> remove func FuncName() string { pc := make([]uintptr, 10) // at least 1 entry needed runtime.Callers(2, pc) f := runtime.FuncForPC(pc[0]) return path.Base(f.Name()) } </s> add
https://github.com/AdguardTeam/AdGuardHome/commit/73c30590e015f55e3de0a01f98a3c79761dce3b7
internal/sysutil/syslog_windows.go
keep keep keep keep replace keep keep keep keep keep
<mask> "fmt" <mask> "io/ioutil" <mask> "os" <mask> "os/exec" <mask> "path" <mask> "runtime" <mask> "strings" <mask> ) <mask> <mask> // ContainsString checks if string is in the slice of strings. </s> Pull request: all: fix lint and naming issues vol. 4 Merge in DNS/adguard-home from 2276-fix-lint-4 to master Updates #2276. Squashed commit of the following: commit 15d49184cd8ce1f8701bf3221e69418ca1778b36 Author: Ainar Garipov <[email protected]> Date: Tue Dec 8 15:51:34 2020 +0300 util: fix naming commit 3b9a86a0feb8c6e0b167e6e23105e8137b0dda76 Author: Ainar Garipov <[email protected]> Date: Tue Dec 8 15:41:10 2020 +0300 all: fix lint and naming issues vol. 4 </s> remove func FuncName() string { pc := make([]uintptr, 10) // at least 1 entry needed runtime.Callers(2, pc) f := runtime.FuncForPC(pc[0]) return path.Base(f.Name()) } </s> add </s> remove // NotFilteredError - there was a transitive error during check NotFilteredError </s> add </s> add "github.com/AdguardTeam/golibs/log" </s> add "github.com/AdguardTeam/golibs/log" </s> remove "log" </s> add </s> remove "log" </s> add
https://github.com/AdguardTeam/AdGuardHome/commit/73c30590e015f55e3de0a01f98a3c79761dce3b7
internal/util/helpers.go
keep keep keep keep replace replace replace replace replace replace replace keep keep keep keep keep
<mask> <mask> return cmd.ProcessState.ExitCode(), string(out), nil <mask> } <mask> <mask> func FuncName() string { <mask> pc := make([]uintptr, 10) // at least 1 entry needed <mask> runtime.Callers(2, pc) <mask> f := runtime.FuncForPC(pc[0]) <mask> return path.Base(f.Name()) <mask> } <mask> <mask> // SplitNext - split string by a byte and return the first chunk <mask> // Skip empty chunks <mask> // Whitespace is trimmed <mask> func SplitNext(str *string, splitBy byte) string { <mask> i := strings.IndexByte(*str, splitBy) </s> Pull request: all: fix lint and naming issues vol. 4 Merge in DNS/adguard-home from 2276-fix-lint-4 to master Updates #2276. Squashed commit of the following: commit 15d49184cd8ce1f8701bf3221e69418ca1778b36 Author: Ainar Garipov <[email protected]> Date: Tue Dec 8 15:51:34 2020 +0300 util: fix naming commit 3b9a86a0feb8c6e0b167e6e23105e8137b0dda76 Author: Ainar Garipov <[email protected]> Date: Tue Dec 8 15:41:10 2020 +0300 all: fix lint and naming issues vol. 4 </s> remove // // stats // // GetStats return dns filtering stats since startup. func (d *Dnsfilter) GetStats() Stats { return gctx.stats } </s> add </s> remove "path" </s> add </s> add "github.com/AdguardTeam/golibs/log" </s> remove // NotFilteredError - there was a transitive error during check NotFilteredError </s> add </s> remove "log" </s> add </s> add var _ wrapper = &manyError{}
https://github.com/AdguardTeam/AdGuardHome/commit/73c30590e015f55e3de0a01f98a3c79761dce3b7
internal/util/helpers.go
keep add keep keep keep keep
<mask> } <mask> <mask> // Apply new configuration, start DNS server, restart Web server <mask> func handleInstallConfigure(w http.ResponseWriter, r *http.Request) { <mask> log.Tracef("%s %v", r.Method, r.URL) <mask> newSettings := applyConfigReq{} </s> * control: /install/configure: reset configuration back to its current state on error </s> add returnOK(w) </s> remove if config.DNS.Port != 0 { err = startDNSServer() if err != nil { httpError(w, http.StatusInternalServerError, "Couldn't start DNS server: %s", err) return } </s> add err = startDNSServer() if err != nil { config.firstRun = true copyInstallSettings(&config, &curConfig) httpError(w, http.StatusInternalServerError, "Couldn't start DNS server: %s", err) return } err = config.write() if err != nil { config.firstRun = true copyInstallSettings(&config, &curConfig) httpError(w, http.StatusInternalServerError, "Couldn't write config: %s", err) return </s> remove httpUpdateConfigReloadDNSReturnOK(w, r) </s> add </s> add var curConfig configuration copyInstallSettings(&curConfig, &config)
https://github.com/AdguardTeam/AdGuardHome/commit/73fbe8b95aca6092b0beb7327a9c811a32464bcc
control.go
keep keep add keep keep keep keep keep
<mask> return <mask> } <mask> <mask> config.firstRun = false <mask> config.BindHost = newSettings.Web.IP <mask> config.BindPort = newSettings.Web.Port <mask> config.DNS.BindHost = newSettings.DNS.IP <mask> config.DNS.Port = newSettings.DNS.Port </s> * control: /install/configure: reset configuration back to its current state on error </s> remove if config.DNS.Port != 0 { err = startDNSServer() if err != nil { httpError(w, http.StatusInternalServerError, "Couldn't start DNS server: %s", err) return } </s> add err = startDNSServer() if err != nil { config.firstRun = true copyInstallSettings(&config, &curConfig) httpError(w, http.StatusInternalServerError, "Couldn't start DNS server: %s", err) return } err = config.write() if err != nil { config.firstRun = true copyInstallSettings(&config, &curConfig) httpError(w, http.StatusInternalServerError, "Couldn't write config: %s", err) return </s> add // Copy installation parameters between two configuration objects func copyInstallSettings(dst *configuration, src *configuration) { dst.BindHost = src.BindHost dst.BindPort = src.BindPort dst.DNS.BindHost = src.DNS.BindHost dst.DNS.Port = src.DNS.Port dst.AuthName = src.AuthName dst.AuthPass = src.AuthPass } </s> remove httpUpdateConfigReloadDNSReturnOK(w, r) </s> add </s> add returnOK(w)
https://github.com/AdguardTeam/AdGuardHome/commit/73fbe8b95aca6092b0beb7327a9c811a32464bcc
control.go