safing-portmaster/service/resolver/metrics.go
Daniel Hååvi 80664d1a27
Restructure modules ()
* Move portbase into monorepo

* Add new simple module mgr

* [WIP] Switch to new simple module mgr

* Add StateMgr and more worker variants

* [WIP] Switch more modules

* [WIP] Switch more modules

* [WIP] swtich more modules

* [WIP] switch all SPN modules

* [WIP] switch all service modules

* [WIP] Convert all workers to the new module system

* [WIP] add new task system to module manager

* [WIP] Add second take for scheduling workers

* [WIP] Add FIXME for bugs in new scheduler

* [WIP] Add minor improvements to scheduler

* [WIP] Add new worker scheduler

* [WIP] Fix more bug related to new module system

* [WIP] Fix start handing of the new module system

* [WIP] Improve startup process

* [WIP] Fix minor issues

* [WIP] Fix missing subsystem in settings

* [WIP] Initialize managers in constructor

* [WIP] Move module event initialization to constrictors

* [WIP] Fix setting for enabling and disabling the SPN module

* [WIP] Move API registeration into module construction

* [WIP] Update states mgr for all modules

* [WIP] Add CmdLine operation support

* Add state helper methods to module group and instance

* Add notification and module status handling to status package

* Fix starting issues

* Remove pilot widget and update security lock to new status data

* Remove debug logs

* Improve http server shutdown

* Add workaround for cleanly shutting down firewall+netquery

* Improve logging

* Add syncing states with notifications for new module system

* Improve starting, stopping, shutdown; resolve FIXMEs/TODOs

* [WIP] Fix most unit tests

* Review new module system and fix minor issues

* Push shutdown and restart events again via API

* Set sleep mode via interface

* Update example/template module

* [WIP] Fix spn/cabin unit test

* Remove deprecated UI elements

* Make log output more similar for the logging transition phase

* Switch spn hub and observer cmds to new module system

* Fix log sources

* Make worker mgr less error prone

* Fix tests and minor issues

* Fix observation hub

* Improve shutdown and restart handling

* Split up big connection.go source file

* Move varint and dsd packages to structures repo

* Improve expansion test

* Fix linter warnings

* Fix interception module on windows

* Fix linter errors

---------

Co-authored-by: Vladimir Stoilov <vladimir@safing.io>
2024-08-09 18:15:48 +03:00

110 lines
3.4 KiB
Go

package resolver
import (
"sync/atomic"
"time"
"github.com/safing/portmaster/base/log"
"github.com/safing/portmaster/base/notifications"
"github.com/safing/portmaster/service/mgr"
)
var (
slowQueriesSensorCnt atomic.Int64
slowQueriesSensorSum atomic.Int64
)
// reportRequestDuration reports successful query request duration.
func reportRequestDuration(started time.Time, resolver *Resolver) {
// TODO: Record prometheus metrics for all resolvers separately.
// Add query times from system and configured resolvers to slow queries sensor.
switch resolver.Info.Source {
case ServerSourceConfigured, ServerSourceOperatingSystem:
slowQueriesSensorCnt.Add(1)
slowQueriesSensorSum.Add(int64(time.Since(started)))
default:
}
}
// getSlowQueriesSensorValue returns the current avg query time recorded by the
// slow queries sensor.
func getSlowQueriesSensorValue() (avgQueryTime time.Duration) {
// Get values and check them.
sum := slowQueriesSensorSum.Load()
cnt := slowQueriesSensorCnt.Load()
if cnt < 1 {
cnt = 1
}
return time.Duration(sum / cnt)
}
// resetSlowQueriesSensorValue reset the slow queries sensor values.
func resetSlowQueriesSensorValue() {
slowQueriesSensorCnt.Store(0)
slowQueriesSensorSum.Store(0)
}
var suggestUsingStaleCacheNotification *notifications.Notification
func suggestUsingStaleCacheTask(_ *mgr.WorkerCtx) error {
scheduleNextCall := true
switch {
case useStaleCache() || useStaleCacheConfigOption.IsSetByUser():
// If setting is already active, disable task repeating.
scheduleNextCall = false
// Delete local reference, if used.
if suggestUsingStaleCacheNotification != nil {
suggestUsingStaleCacheNotification.Delete()
suggestUsingStaleCacheNotification = nil
}
case suggestUsingStaleCacheNotification != nil:
// Check if notification is already active.
suggestUsingStaleCacheNotification.Lock()
defer suggestUsingStaleCacheNotification.Unlock()
if suggestUsingStaleCacheNotification.Meta().IsDeleted() {
// Reset local reference if notification was deleted.
suggestUsingStaleCacheNotification = nil
}
case getSlowQueriesSensorValue() > 100*time.Millisecond:
log.Warningf(
"resolver: suggesting user to use stale dns cache with avg query time of %s for config and system resolvers",
getSlowQueriesSensorValue().Round(time.Millisecond),
)
// Notify user.
suggestUsingStaleCacheNotification = &notifications.Notification{
EventID: "resolver:suggest-using-stale-cache",
Type: notifications.Info,
Title: "Speed Up Website Loading",
Message: "Portmaster has detected that websites may load slower because DNS queries are currently slower than expected. You may want to switch your DNS provider or enable using expired DNS cache entries for better performance.",
ShowOnSystem: getSlowQueriesSensorValue() > 500*time.Millisecond,
Expires: time.Now().Add(10 * time.Minute).Unix(),
AvailableActions: []*notifications.Action{
{
Text: "Open Setting",
Type: notifications.ActionTypeOpenSetting,
Payload: &notifications.ActionTypeOpenSettingPayload{
Key: CfgOptionUseStaleCacheKey,
},
},
{
ID: "ack",
Text: "Got it!",
},
},
}
notifications.Notify(suggestUsingStaleCacheNotification)
}
if scheduleNextCall {
_ = module.suggestUsingStaleCacheTask.Delay(2 * time.Minute)
}
resetSlowQueriesSensorValue()
return nil
}