From b40954dce598577413d93ce32cc005b57c6371bb Mon Sep 17 00:00:00 2001 From: Paul Gier Date: Thu, 20 Feb 2020 04:03:33 -0600 Subject: new flag to disable all default collectors (#1460) * new flag to disable all default collectors Signed-off-by: Paul Gier Co-authored-by: Ben Kochie --- collector/collector.go | 31 +++++++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) (limited to 'collector') diff --git a/collector/collector.go b/collector/collector.go index 0fec09c..e9ea14c 100644 --- a/collector/collector.go +++ b/collector/collector.go @@ -23,7 +23,7 @@ import ( "github.com/go-kit/kit/log" "github.com/go-kit/kit/log/level" "github.com/prometheus/client_golang/prometheus" - "gopkg.in/alecthomas/kingpin.v2" + kingpin "gopkg.in/alecthomas/kingpin.v2" ) // Namespace defines the common namespace to be used by all metrics. @@ -50,8 +50,9 @@ const ( ) var ( - factories = make(map[string]func(logger log.Logger) (Collector, error)) - collectorState = make(map[string]*bool) + factories = make(map[string]func(logger log.Logger) (Collector, error)) + collectorState = make(map[string]*bool) + forcedCollectors = map[string]bool{} // collectors which have been explicitly enabled or disabled ) func registerCollector(collector string, isDefaultEnabled bool, factory func(logger log.Logger) (Collector, error)) { @@ -66,7 +67,7 @@ func registerCollector(collector string, isDefaultEnabled bool, factory func(log flagHelp := fmt.Sprintf("Enable the %s collector (default: %s).", collector, helpDefaultState) defaultValue := fmt.Sprintf("%v", isDefaultEnabled) - flag := kingpin.Flag(flagName, flagHelp).Default(defaultValue).Bool() + flag := kingpin.Flag(flagName, flagHelp).Default(defaultValue).Action(collectorFlagAction(collector)).Bool() collectorState[collector] = flag factories[collector] = factory @@ -78,6 +79,28 @@ type NodeCollector struct { logger log.Logger } +// DisableDefaultCollectors sets the collector state to false for all collectors which +// have not been explicitly enabled on the command line. +func DisableDefaultCollectors() { + for c := range collectorState { + if _, ok := forcedCollectors[c]; !ok { + *collectorState[c] = false + } + } +} + +// collectorFlagAction generates a new action function for the given collector +// to track whether it has been explicitly enabled or disabled from the command line. +// A new action function is needed for each collector flag because the ParseContext +// does not contain information about which flag called the action. +// See: https://github.com/alecthomas/kingpin/issues/294 +func collectorFlagAction(collector string) func(ctx *kingpin.ParseContext) error { + return func(ctx *kingpin.ParseContext) error { + forcedCollectors[collector] = true + return nil + } +} + // NewNodeCollector creates a new NodeCollector. func NewNodeCollector(logger log.Logger, filters ...string) (*NodeCollector, error) { f := make(map[string]bool) -- cgit v1.2.3