1
0
mirror of https://github.com/prometheus-community/windows_exporter.git synced 2025-04-18 19:24:05 +03:00

*: cleanup collector API 1 (#1547)

This commit is contained in:
Jan-Otto Kröpke 2024-08-05 15:50:41 +02:00 committed by GitHub
parent dffc53eff8
commit d1e3a63f93
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
86 changed files with 2162 additions and 1930 deletions

3
.gitattributes vendored Normal file
View File

@ -0,0 +1,3 @@
*.go text eol=lf
*.sh text eol=lf
Makefile text eol=lf

View File

@ -100,5 +100,5 @@ jobs:
- name: golangci-lint - name: golangci-lint
uses: golangci/golangci-lint-action@v6 uses: golangci/golangci-lint-action@v6
with: with:
version: v1.58 version: v1.59
args: "--timeout=5m --out-format github-actions,colored-line-number" args: "--timeout=5m"

View File

@ -37,10 +37,12 @@ jobs:
- name: check - name: check
run: | run: |
PR_TITLE_PREFIX=$(echo "$PR_TITLE" | cut -d':' -f1) PR_TITLE_PREFIX=$(echo "$PR_TITLE" | cut -d':' -f1)
if [[ ! -d "pkg/collector/$PR_TITLE_PREFIX" ]] || [[ "$PR_TITLE_PREFIX" == "chore(deps)" ]] || [[ "$PR_TITLE_PREFIX" == "chore" ]] || [[ "$PR_TITLE_PREFIX" == "*" ]]; then if [[ -d "pkg/collector/$PR_TITLE_PREFIX" ]] || [[ "$PR_TITLE_PREFIX" == "chore" ]] || [[ "$PR_TITLE_PREFIX" == "chore(deps)" ]] || [[ "$PR_TITLE_PREFIX" == "*" ]]; then
echo "PR title must start with an name of an collector package" exit 0
echo "Example: 'logical_disk: description'"
exit 1
fi fi
echo "PR title must start with an name of an collector package"
echo "Example: 'logical_disk: description'"
exit 1
env: env:
PR_TITLE: ${{ github.event.pull_request.title }} PR_TITLE: ${{ github.event.pull_request.title }}

View File

@ -1,14 +1,8 @@
linters: linters:
enable-all: true enable-all: true
disable: disable:
- asasalint
- asciicheck
- bidichk
- bodyclose
- canonicalheader
- containedctx - containedctx
- contextcheck - contextcheck
- copyloopvar
- cyclop - cyclop
- decorder - decorder
- depguard - depguard
@ -24,10 +18,7 @@ linters:
- exhaustruct - exhaustruct
- exportloopref - exportloopref
- fatcontext - fatcontext
- forbidigo
- forcetypeassert
- funlen - funlen
- gci
- ginkgolinter - ginkgolinter
- gocheckcompilerdirectives - gocheckcompilerdirectives
- gochecknoglobals - gochecknoglobals
@ -40,12 +31,9 @@ linters:
- godot - godot
- godox - godox
- gofumpt - gofumpt
- goheader
- goimports - goimports
- gomoddirectives - gomoddirectives
- gomodguard - gomodguard
- goprintffuncname
- gosec
- gosimple - gosimple
- gosmopolitan - gosmopolitan
- grouper - grouper
@ -56,7 +44,6 @@ linters:
- ireturn - ireturn
- lll - lll
- maintidx - maintidx
- makezero
- mirror - mirror
- misspell - misspell
- mnd - mnd
@ -65,7 +52,6 @@ linters:
- nestif - nestif
- nlreturn - nlreturn
- noctx - noctx
- nolintlint
- nonamedreturns - nonamedreturns
- nosprintfhostport - nosprintfhostport
- paralleltest - paralleltest
@ -86,13 +72,9 @@ linters:
- testpackage - testpackage
- thelper - thelper
- tparallel - tparallel
- usestdlibvars
- varnamelen - varnamelen
- wastedassign
- whitespace
- wrapcheck - wrapcheck
- wsl - wsl
- zerologlint
- execinquery - execinquery
- gomnd - gomnd

View File

@ -5,29 +5,30 @@
package main package main
import ( import (
// Its important that we do these first so that we can register with the Windows service control ASAP to avoid timeouts "context"
"github.com/prometheus-community/windows_exporter/pkg/initiate"
"encoding/json" "encoding/json"
"fmt" "fmt"
"net/http" "net/http"
"net/http/pprof" "net/http/pprof"
"os" "os"
"os/signal"
"os/user" "os/user"
"runtime" "runtime"
"sort" "sort"
"strings" "strings"
"time"
winlog "github.com/prometheus-community/windows_exporter/pkg/log"
"github.com/prometheus-community/windows_exporter/pkg/types"
"github.com/prometheus-community/windows_exporter/pkg/utils"
"github.com/prometheus-community/windows_exporter/pkg/wmi"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log/level" "github.com/go-kit/log/level"
"github.com/prometheus-community/windows_exporter/pkg/collector" "github.com/prometheus-community/windows_exporter/pkg/collector"
"github.com/prometheus-community/windows_exporter/pkg/config" "github.com/prometheus-community/windows_exporter/pkg/config"
// Its important that we do these first so that we can register with the Windows service control ASAP to avoid timeouts
"github.com/prometheus-community/windows_exporter/pkg/initiate"
winlog "github.com/prometheus-community/windows_exporter/pkg/log"
"github.com/prometheus-community/windows_exporter/pkg/log/flag" "github.com/prometheus-community/windows_exporter/pkg/log/flag"
"github.com/prometheus-community/windows_exporter/pkg/types"
"github.com/prometheus-community/windows_exporter/pkg/utils"
"github.com/prometheus-community/windows_exporter/pkg/wmi"
"github.com/prometheus/common/version" "github.com/prometheus/common/version"
"github.com/prometheus/exporter-toolkit/web" "github.com/prometheus/exporter-toolkit/web"
webflag "github.com/prometheus/exporter-toolkit/web/kingpinflag" webflag "github.com/prometheus/exporter-toolkit/web/kingpinflag"
@ -171,9 +172,9 @@ func main() {
collectorNames := collector.Available() collectorNames := collector.Available()
sort.Strings(collectorNames) sort.Strings(collectorNames)
fmt.Printf("Available collectors:\n") fmt.Printf("Available collectors:\n") //nolint:forbidigo
for _, n := range collectorNames { for _, n := range collectorNames {
fmt.Printf(" - %s\n", n) fmt.Printf(" - %s\n", n) //nolint:forbidigo
} }
return return
@ -259,20 +260,37 @@ func main() {
_ = level.Info(logger).Log("msg", "Build context", "build_context", version.BuildContext()) _ = level.Info(logger).Log("msg", "Build context", "build_context", version.BuildContext())
_ = level.Debug(logger).Log("msg", "Go MAXPROCS", "procs", runtime.GOMAXPROCS(0)) _ = level.Debug(logger).Log("msg", "Go MAXPROCS", "procs", runtime.GOMAXPROCS(0))
server := &http.Server{
ReadHeaderTimeout: 5 * time.Second,
IdleTimeout: 60 * time.Second,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Minute,
Handler: mux,
}
go func() { go func() {
server := &http.Server{Handler: mux}
if err := web.ListenAndServe(server, webConfig, logger); err != nil { if err := web.ListenAndServe(server, webConfig, logger); err != nil {
_ = level.Error(logger).Log("msg", "cannot start windows_exporter", "err", err) _ = level.Error(logger).Log("msg", "cannot start windows_exporter", "err", err)
os.Exit(1) os.Exit(1)
} }
}() }()
for { ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, os.Kill)
if <-initiate.StopCh { defer stop()
_ = level.Info(logger).Log("msg", "Shutting down windows_exporter")
break select {
} case <-ctx.Done():
_ = level.Info(logger).Log("msg", "Shutting down windows_exporter via kill signal")
case <-initiate.StopCh:
_ = level.Info(logger).Log("msg", "Shutting down windows_exporter via service control")
} }
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = server.Shutdown(ctx)
_ = level.Info(logger).Log("msg", "windows_exporter has shut down")
} }
func withConcurrencyLimit(n int, next http.HandlerFunc) http.HandlerFunc { func withConcurrencyLimit(n int, next http.HandlerFunc) http.HandlerFunc {

File diff suppressed because it is too large Load Diff

View File

@ -21,120 +21,125 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
RequestsPerSecond *prometheus.Desc challengeResponseProcessingTime *prometheus.Desc
RequestProcessingTime *prometheus.Desc challengeResponsesPerSecond *prometheus.Desc
RetrievalsPerSecond *prometheus.Desc failedRequestsPerSecond *prometheus.Desc
RetrievalProcessingTime *prometheus.Desc issuedRequestsPerSecond *prometheus.Desc
FailedRequestsPerSecond *prometheus.Desc pendingRequestsPerSecond *prometheus.Desc
IssuedRequestsPerSecond *prometheus.Desc requestCryptographicSigningTime *prometheus.Desc
PendingRequestsPerSecond *prometheus.Desc requestPolicyModuleProcessingTime *prometheus.Desc
RequestCryptographicSigningTime *prometheus.Desc requestProcessingTime *prometheus.Desc
RequestPolicyModuleProcessingTime *prometheus.Desc requestsPerSecond *prometheus.Desc
ChallengeResponsesPerSecond *prometheus.Desc retrievalProcessingTime *prometheus.Desc
ChallengeResponseProcessingTime *prometheus.Desc retrievalsPerSecond *prometheus.Desc
SignedCertificateTimestampListsPerSecond *prometheus.Desc signedCertificateTimestampListProcessingTime *prometheus.Desc
SignedCertificateTimestampListProcessingTime *prometheus.Desc signedCertificateTimestampListsPerSecond *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{"Certification Authority"}, nil return []string{"Certification Authority"}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
c.RequestsPerSecond = prometheus.NewDesc( return nil
}
func (c *Collector) Build() error {
c.requestsPerSecond = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "requests_total"), prometheus.BuildFQName(types.Namespace, Name, "requests_total"),
"Total certificate requests processed", "Total certificate requests processed",
[]string{"cert_template"}, []string{"cert_template"},
nil, nil,
) )
c.RequestProcessingTime = prometheus.NewDesc( c.requestProcessingTime = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "request_processing_time_seconds"), prometheus.BuildFQName(types.Namespace, Name, "request_processing_time_seconds"),
"Last time elapsed for certificate requests", "Last time elapsed for certificate requests",
[]string{"cert_template"}, []string{"cert_template"},
nil, nil,
) )
c.RetrievalsPerSecond = prometheus.NewDesc( c.retrievalsPerSecond = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "retrievals_total"), prometheus.BuildFQName(types.Namespace, Name, "retrievals_total"),
"Total certificate retrieval requests processed", "Total certificate retrieval requests processed",
[]string{"cert_template"}, []string{"cert_template"},
nil, nil,
) )
c.RetrievalProcessingTime = prometheus.NewDesc( c.retrievalProcessingTime = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "retrievals_processing_time_seconds"), prometheus.BuildFQName(types.Namespace, Name, "retrievals_processing_time_seconds"),
"Last time elapsed for certificate retrieval request", "Last time elapsed for certificate retrieval request",
[]string{"cert_template"}, []string{"cert_template"},
nil, nil,
) )
c.FailedRequestsPerSecond = prometheus.NewDesc( c.failedRequestsPerSecond = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "failed_requests_total"), prometheus.BuildFQName(types.Namespace, Name, "failed_requests_total"),
"Total failed certificate requests processed", "Total failed certificate requests processed",
[]string{"cert_template"}, []string{"cert_template"},
nil, nil,
) )
c.IssuedRequestsPerSecond = prometheus.NewDesc( c.issuedRequestsPerSecond = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "issued_requests_total"), prometheus.BuildFQName(types.Namespace, Name, "issued_requests_total"),
"Total issued certificate requests processed", "Total issued certificate requests processed",
[]string{"cert_template"}, []string{"cert_template"},
nil, nil,
) )
c.PendingRequestsPerSecond = prometheus.NewDesc( c.pendingRequestsPerSecond = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "pending_requests_total"), prometheus.BuildFQName(types.Namespace, Name, "pending_requests_total"),
"Total pending certificate requests processed", "Total pending certificate requests processed",
[]string{"cert_template"}, []string{"cert_template"},
nil, nil,
) )
c.RequestCryptographicSigningTime = prometheus.NewDesc( c.requestCryptographicSigningTime = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "request_cryptographic_signing_time_seconds"), prometheus.BuildFQName(types.Namespace, Name, "request_cryptographic_signing_time_seconds"),
"Last time elapsed for signing operation request", "Last time elapsed for signing operation request",
[]string{"cert_template"}, []string{"cert_template"},
nil, nil,
) )
c.RequestPolicyModuleProcessingTime = prometheus.NewDesc( c.requestPolicyModuleProcessingTime = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "request_policy_module_processing_time_seconds"), prometheus.BuildFQName(types.Namespace, Name, "request_policy_module_processing_time_seconds"),
"Last time elapsed for policy module processing request", "Last time elapsed for policy module processing request",
[]string{"cert_template"}, []string{"cert_template"},
nil, nil,
) )
c.ChallengeResponsesPerSecond = prometheus.NewDesc( c.challengeResponsesPerSecond = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "challenge_responses_total"), prometheus.BuildFQName(types.Namespace, Name, "challenge_responses_total"),
"Total certificate challenge responses processed", "Total certificate challenge responses processed",
[]string{"cert_template"}, []string{"cert_template"},
nil, nil,
) )
c.ChallengeResponseProcessingTime = prometheus.NewDesc( c.challengeResponseProcessingTime = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "challenge_response_processing_time_seconds"), prometheus.BuildFQName(types.Namespace, Name, "challenge_response_processing_time_seconds"),
"Last time elapsed for challenge response", "Last time elapsed for challenge response",
[]string{"cert_template"}, []string{"cert_template"},
nil, nil,
) )
c.SignedCertificateTimestampListsPerSecond = prometheus.NewDesc( c.signedCertificateTimestampListsPerSecond = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "signed_certificate_timestamp_lists_total"), prometheus.BuildFQName(types.Namespace, Name, "signed_certificate_timestamp_lists_total"),
"Total Signed Certificate Timestamp Lists processed", "Total Signed Certificate Timestamp Lists processed",
[]string{"cert_template"}, []string{"cert_template"},
nil, nil,
) )
c.SignedCertificateTimestampListProcessingTime = prometheus.NewDesc( c.signedCertificateTimestampListProcessingTime = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "signed_certificate_timestamp_list_processing_time_seconds"), prometheus.BuildFQName(types.Namespace, Name, "signed_certificate_timestamp_list_processing_time_seconds"),
"Last time elapsed for Signed Certificate Timestamp List", "Last time elapsed for Signed Certificate Timestamp List",
[]string{"cert_template"}, []string{"cert_template"},
@ -144,7 +149,7 @@ func (c *collector) Build() error {
return nil return nil
} }
func (c *collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collectADCSCounters(ctx, ch); err != nil { if err := c.collectADCSCounters(ctx, ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting ADCS metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting ADCS metrics", "err", err)
return err return err
@ -169,7 +174,7 @@ type perflibADCS struct {
SignedCertificateTimestampListProcessingTime float64 `perflib:"Signed Certificate Timestamp List processing time (ms)"` SignedCertificateTimestampListProcessingTime float64 `perflib:"Signed Certificate Timestamp List processing time (ms)"`
} }
func (c *collector) collectADCSCounters(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collectADCSCounters(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
dst := make([]perflibADCS, 0) dst := make([]perflibADCS, 0)
if _, ok := ctx.PerfObjects["Certification Authority"]; !ok { if _, ok := ctx.PerfObjects["Certification Authority"]; !ok {
return errors.New("perflib did not contain an entry for Certification Authority") return errors.New("perflib did not contain an entry for Certification Authority")
@ -188,79 +193,79 @@ func (c *collector) collectADCSCounters(ctx *types.ScrapeContext, ch chan<- prom
continue continue
} }
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.RequestsPerSecond, c.requestsPerSecond,
prometheus.CounterValue, prometheus.CounterValue,
d.RequestsPerSecond, d.RequestsPerSecond,
d.Name, d.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.RequestProcessingTime, c.requestProcessingTime,
prometheus.GaugeValue, prometheus.GaugeValue,
utils.MilliSecToSec(d.RequestProcessingTime), utils.MilliSecToSec(d.RequestProcessingTime),
d.Name, d.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.RetrievalsPerSecond, c.retrievalsPerSecond,
prometheus.CounterValue, prometheus.CounterValue,
d.RetrievalsPerSecond, d.RetrievalsPerSecond,
d.Name, d.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.RetrievalProcessingTime, c.retrievalProcessingTime,
prometheus.GaugeValue, prometheus.GaugeValue,
utils.MilliSecToSec(d.RetrievalProcessingTime), utils.MilliSecToSec(d.RetrievalProcessingTime),
d.Name, d.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.FailedRequestsPerSecond, c.failedRequestsPerSecond,
prometheus.CounterValue, prometheus.CounterValue,
d.FailedRequestsPerSecond, d.FailedRequestsPerSecond,
d.Name, d.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.IssuedRequestsPerSecond, c.issuedRequestsPerSecond,
prometheus.CounterValue, prometheus.CounterValue,
d.IssuedRequestsPerSecond, d.IssuedRequestsPerSecond,
d.Name, d.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.PendingRequestsPerSecond, c.pendingRequestsPerSecond,
prometheus.CounterValue, prometheus.CounterValue,
d.PendingRequestsPerSecond, d.PendingRequestsPerSecond,
d.Name, d.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.RequestCryptographicSigningTime, c.requestCryptographicSigningTime,
prometheus.GaugeValue, prometheus.GaugeValue,
utils.MilliSecToSec(d.RequestCryptographicSigningTime), utils.MilliSecToSec(d.RequestCryptographicSigningTime),
d.Name, d.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.RequestPolicyModuleProcessingTime, c.requestPolicyModuleProcessingTime,
prometheus.GaugeValue, prometheus.GaugeValue,
utils.MilliSecToSec(d.RequestPolicyModuleProcessingTime), utils.MilliSecToSec(d.RequestPolicyModuleProcessingTime),
d.Name, d.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.ChallengeResponsesPerSecond, c.challengeResponsesPerSecond,
prometheus.CounterValue, prometheus.CounterValue,
d.ChallengeResponsesPerSecond, d.ChallengeResponsesPerSecond,
d.Name, d.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.ChallengeResponseProcessingTime, c.challengeResponseProcessingTime,
prometheus.GaugeValue, prometheus.GaugeValue,
utils.MilliSecToSec(d.ChallengeResponseProcessingTime), utils.MilliSecToSec(d.ChallengeResponseProcessingTime),
d.Name, d.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.SignedCertificateTimestampListsPerSecond, c.signedCertificateTimestampListsPerSecond,
prometheus.CounterValue, prometheus.CounterValue,
d.SignedCertificateTimestampListsPerSecond, d.SignedCertificateTimestampListsPerSecond,
d.Name, d.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.SignedCertificateTimestampListProcessingTime, c.signedCertificateTimestampListProcessingTime,
prometheus.GaugeValue, prometheus.GaugeValue,
utils.MilliSecToSec(d.SignedCertificateTimestampListProcessingTime), utils.MilliSecToSec(d.SignedCertificateTimestampListProcessingTime),
d.Name, d.Name,

View File

@ -18,20 +18,21 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
adLoginConnectionFailures *prometheus.Desc adLoginConnectionFailures *prometheus.Desc
artifactDBFailures *prometheus.Desc
avgArtifactDBQueryTime *prometheus.Desc
avgConfigDBQueryTime *prometheus.Desc
certificateAuthentications *prometheus.Desc certificateAuthentications *prometheus.Desc
configDBFailures *prometheus.Desc
deviceAuthentications *prometheus.Desc deviceAuthentications *prometheus.Desc
externalAuthenticationFailures *prometheus.Desc
externalAuthentications *prometheus.Desc
extranetAccountLockouts *prometheus.Desc extranetAccountLockouts *prometheus.Desc
federatedAuthentications *prometheus.Desc federatedAuthentications *prometheus.Desc
passportAuthentications *prometheus.Desc federationMetadataRequests *prometheus.Desc
passiveRequests *prometheus.Desc
passwordChangeFailed *prometheus.Desc
passwordChangeSucceeded *prometheus.Desc
tokenRequests *prometheus.Desc
windowsIntegratedAuthentications *prometheus.Desc
oAuthAuthZRequests *prometheus.Desc oAuthAuthZRequests *prometheus.Desc
oAuthClientAuthentications *prometheus.Desc oAuthClientAuthentications *prometheus.Desc
oAuthClientAuthenticationsFailures *prometheus.Desc oAuthClientAuthenticationsFailures *prometheus.Desc
@ -50,45 +51,49 @@ type collector struct {
oAuthPasswordGrantRequestFailures *prometheus.Desc oAuthPasswordGrantRequestFailures *prometheus.Desc
oAuthPasswordGrantRequests *prometheus.Desc oAuthPasswordGrantRequests *prometheus.Desc
oAuthTokenRequests *prometheus.Desc oAuthTokenRequests *prometheus.Desc
passiveRequests *prometheus.Desc
passportAuthentications *prometheus.Desc
passwordChangeFailed *prometheus.Desc
passwordChangeSucceeded *prometheus.Desc
samlPTokenRequests *prometheus.Desc samlPTokenRequests *prometheus.Desc
ssoAuthenticationFailures *prometheus.Desc ssoAuthenticationFailures *prometheus.Desc
ssoAuthentications *prometheus.Desc ssoAuthentications *prometheus.Desc
wsfedTokenRequests *prometheus.Desc tokenRequests *prometheus.Desc
wstrustTokenRequests *prometheus.Desc
upAuthenticationFailures *prometheus.Desc upAuthenticationFailures *prometheus.Desc
upAuthentications *prometheus.Desc upAuthentications *prometheus.Desc
externalAuthenticationFailures *prometheus.Desc windowsIntegratedAuthentications *prometheus.Desc
externalAuthentications *prometheus.Desc wsfedTokenRequests *prometheus.Desc
artifactDBFailures *prometheus.Desc wstrustTokenRequests *prometheus.Desc
avgArtifactDBQueryTime *prometheus.Desc
configDBFailures *prometheus.Desc
avgConfigDBQueryTime *prometheus.Desc
federationMetadataRequests *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{"AD FS"}, nil return []string{"AD FS"}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.adLoginConnectionFailures = prometheus.NewDesc( c.adLoginConnectionFailures = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "ad_login_connection_failures_total"), prometheus.BuildFQName(types.Namespace, Name, "ad_login_connection_failures_total"),
"Total number of connection failures to an Active Directory domain controller", "Total number of connection failures to an Active Directory domain controller",
@ -397,7 +402,7 @@ type perflibADFS struct {
FederationMetadataRequests float64 `perflib:"Federation Metadata Requests"` FederationMetadataRequests float64 `perflib:"Federation Metadata Requests"`
} }
func (c *collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var adfsData []perflibADFS var adfsData []perflibADFS
err := perflib.UnmarshalObject(ctx.PerfObjects["AD FS"], &adfsData, c.logger) err := perflib.UnmarshalObject(ctx.PerfObjects["AD FS"], &adfsData, c.logger)
if err != nil { if err != nil {

View File

@ -6,6 +6,7 @@ import (
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/go-kit/log/level" "github.com/go-kit/log/level"
"github.com/pkg/errors"
"github.com/prometheus-community/windows_exporter/pkg/perflib" "github.com/prometheus-community/windows_exporter/pkg/perflib"
"github.com/prometheus-community/windows_exporter/pkg/types" "github.com/prometheus-community/windows_exporter/pkg/types"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
@ -17,233 +18,238 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
// A collector is a Prometheus collector for Perflib Cache metrics // A Collector is a Prometheus Collector for Perflib Cache metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
AsyncCopyReadsTotal *prometheus.Desc asyncCopyReadsTotal *prometheus.Desc
AsyncDataMapsTotal *prometheus.Desc asyncDataMapsTotal *prometheus.Desc
AsyncFastReadsTotal *prometheus.Desc asyncFastReadsTotal *prometheus.Desc
AsyncMDLReadsTotal *prometheus.Desc asyncMDLReadsTotal *prometheus.Desc
AsyncPinReadsTotal *prometheus.Desc asyncPinReadsTotal *prometheus.Desc
CopyReadHitsTotal *prometheus.Desc copyReadHitsTotal *prometheus.Desc
CopyReadsTotal *prometheus.Desc copyReadsTotal *prometheus.Desc
DataFlushesTotal *prometheus.Desc dataFlushesTotal *prometheus.Desc
DataFlushPagesTotal *prometheus.Desc dataFlushPagesTotal *prometheus.Desc
DataMapHitsPercent *prometheus.Desc dataMapHitsPercent *prometheus.Desc
DataMapPinsTotal *prometheus.Desc dataMapPinsTotal *prometheus.Desc
DataMapsTotal *prometheus.Desc dataMapsTotal *prometheus.Desc
DirtyPages *prometheus.Desc dirtyPages *prometheus.Desc
DirtyPageThreshold *prometheus.Desc dirtyPageThreshold *prometheus.Desc
FastReadNotPossiblesTotal *prometheus.Desc fastReadNotPossiblesTotal *prometheus.Desc
FastReadResourceMissesTotal *prometheus.Desc fastReadResourceMissesTotal *prometheus.Desc
FastReadsTotal *prometheus.Desc fastReadsTotal *prometheus.Desc
LazyWriteFlushesTotal *prometheus.Desc lazyWriteFlushesTotal *prometheus.Desc
LazyWritePagesTotal *prometheus.Desc lazyWritePagesTotal *prometheus.Desc
MDLReadHitsTotal *prometheus.Desc mdlReadHitsTotal *prometheus.Desc
MDLReadsTotal *prometheus.Desc mdlReadsTotal *prometheus.Desc
PinReadHitsTotal *prometheus.Desc pinReadHitsTotal *prometheus.Desc
PinReadsTotal *prometheus.Desc pinReadsTotal *prometheus.Desc
ReadAheadsTotal *prometheus.Desc readAheadsTotal *prometheus.Desc
SyncCopyReadsTotal *prometheus.Desc syncCopyReadsTotal *prometheus.Desc
SyncDataMapsTotal *prometheus.Desc syncDataMapsTotal *prometheus.Desc
SyncFastReadsTotal *prometheus.Desc syncFastReadsTotal *prometheus.Desc
SyncMDLReadsTotal *prometheus.Desc syncMDLReadsTotal *prometheus.Desc
SyncPinReadsTotal *prometheus.Desc syncPinReadsTotal *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{"Cache"}, nil return []string{"Cache"}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
c.AsyncCopyReadsTotal = prometheus.NewDesc( return nil
}
func (c *Collector) Build() error {
c.asyncCopyReadsTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "async_copy_reads_total"), prometheus.BuildFQName(types.Namespace, Name, "async_copy_reads_total"),
"(AsyncCopyReadsTotal)", "(AsyncCopyReadsTotal)",
nil, nil,
nil, nil,
) )
c.AsyncDataMapsTotal = prometheus.NewDesc( c.asyncDataMapsTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "async_data_maps_total"), prometheus.BuildFQName(types.Namespace, Name, "async_data_maps_total"),
"(AsyncDataMapsTotal)", "(AsyncDataMapsTotal)",
nil, nil,
nil, nil,
) )
c.AsyncFastReadsTotal = prometheus.NewDesc( c.asyncFastReadsTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "async_fast_reads_total"), prometheus.BuildFQName(types.Namespace, Name, "async_fast_reads_total"),
"(AsyncFastReadsTotal)", "(AsyncFastReadsTotal)",
nil, nil,
nil, nil,
) )
c.AsyncMDLReadsTotal = prometheus.NewDesc( c.asyncMDLReadsTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "async_mdl_reads_total"), prometheus.BuildFQName(types.Namespace, Name, "async_mdl_reads_total"),
"(AsyncMDLReadsTotal)", "(AsyncMDLReadsTotal)",
nil, nil,
nil, nil,
) )
c.AsyncPinReadsTotal = prometheus.NewDesc( c.asyncPinReadsTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "async_pin_reads_total"), prometheus.BuildFQName(types.Namespace, Name, "async_pin_reads_total"),
"(AsyncPinReadsTotal)", "(AsyncPinReadsTotal)",
nil, nil,
nil, nil,
) )
c.CopyReadHitsTotal = prometheus.NewDesc( c.copyReadHitsTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "copy_read_hits_total"), prometheus.BuildFQName(types.Namespace, Name, "copy_read_hits_total"),
"(CopyReadHitsTotal)", "(CopyReadHitsTotal)",
nil, nil,
nil, nil,
) )
c.CopyReadsTotal = prometheus.NewDesc( c.copyReadsTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "copy_reads_total"), prometheus.BuildFQName(types.Namespace, Name, "copy_reads_total"),
"(CopyReadsTotal)", "(CopyReadsTotal)",
nil, nil,
nil, nil,
) )
c.DataFlushesTotal = prometheus.NewDesc( c.dataFlushesTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "data_flushes_total"), prometheus.BuildFQName(types.Namespace, Name, "data_flushes_total"),
"(DataFlushesTotal)", "(DataFlushesTotal)",
nil, nil,
nil, nil,
) )
c.DataFlushPagesTotal = prometheus.NewDesc( c.dataFlushPagesTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "data_flush_pages_total"), prometheus.BuildFQName(types.Namespace, Name, "data_flush_pages_total"),
"(DataFlushPagesTotal)", "(DataFlushPagesTotal)",
nil, nil,
nil, nil,
) )
c.DataMapHitsPercent = prometheus.NewDesc( c.dataMapHitsPercent = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "data_map_hits_percent"), prometheus.BuildFQName(types.Namespace, Name, "data_map_hits_percent"),
"(DataMapHitsPercent)", "(DataMapHitsPercent)",
nil, nil,
nil, nil,
) )
c.DataMapPinsTotal = prometheus.NewDesc( c.dataMapPinsTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "data_map_pins_total"), prometheus.BuildFQName(types.Namespace, Name, "data_map_pins_total"),
"(DataMapPinsTotal)", "(DataMapPinsTotal)",
nil, nil,
nil, nil,
) )
c.DataMapsTotal = prometheus.NewDesc( c.dataMapsTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "data_maps_total"), prometheus.BuildFQName(types.Namespace, Name, "data_maps_total"),
"(DataMapsTotal)", "(DataMapsTotal)",
nil, nil,
nil, nil,
) )
c.DirtyPages = prometheus.NewDesc( c.dirtyPages = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "dirty_pages"), prometheus.BuildFQName(types.Namespace, Name, "dirty_pages"),
"(DirtyPages)", "(DirtyPages)",
nil, nil,
nil, nil,
) )
c.DirtyPageThreshold = prometheus.NewDesc( c.dirtyPageThreshold = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "dirty_page_threshold"), prometheus.BuildFQName(types.Namespace, Name, "dirty_page_threshold"),
"(DirtyPageThreshold)", "(DirtyPageThreshold)",
nil, nil,
nil, nil,
) )
c.FastReadNotPossiblesTotal = prometheus.NewDesc( c.fastReadNotPossiblesTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "fast_read_not_possibles_total"), prometheus.BuildFQName(types.Namespace, Name, "fast_read_not_possibles_total"),
"(FastReadNotPossiblesTotal)", "(FastReadNotPossiblesTotal)",
nil, nil,
nil, nil,
) )
c.FastReadResourceMissesTotal = prometheus.NewDesc( c.fastReadResourceMissesTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "fast_read_resource_misses_total"), prometheus.BuildFQName(types.Namespace, Name, "fast_read_resource_misses_total"),
"(FastReadResourceMissesTotal)", "(FastReadResourceMissesTotal)",
nil, nil,
nil, nil,
) )
c.FastReadsTotal = prometheus.NewDesc( c.fastReadsTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "fast_reads_total"), prometheus.BuildFQName(types.Namespace, Name, "fast_reads_total"),
"(FastReadsTotal)", "(FastReadsTotal)",
nil, nil,
nil, nil,
) )
c.LazyWriteFlushesTotal = prometheus.NewDesc( c.lazyWriteFlushesTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "lazy_write_flushes_total"), prometheus.BuildFQName(types.Namespace, Name, "lazy_write_flushes_total"),
"(LazyWriteFlushesTotal)", "(LazyWriteFlushesTotal)",
nil, nil,
nil, nil,
) )
c.LazyWritePagesTotal = prometheus.NewDesc( c.lazyWritePagesTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "lazy_write_pages_total"), prometheus.BuildFQName(types.Namespace, Name, "lazy_write_pages_total"),
"(LazyWritePagesTotal)", "(LazyWritePagesTotal)",
nil, nil,
nil, nil,
) )
c.MDLReadHitsTotal = prometheus.NewDesc( c.mdlReadHitsTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "mdl_read_hits_total"), prometheus.BuildFQName(types.Namespace, Name, "mdl_read_hits_total"),
"(MDLReadHitsTotal)", "(MDLReadHitsTotal)",
nil, nil,
nil, nil,
) )
c.MDLReadsTotal = prometheus.NewDesc( c.mdlReadsTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "mdl_reads_total"), prometheus.BuildFQName(types.Namespace, Name, "mdl_reads_total"),
"(MDLReadsTotal)", "(MDLReadsTotal)",
nil, nil,
nil, nil,
) )
c.PinReadHitsTotal = prometheus.NewDesc( c.pinReadHitsTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "pin_read_hits_total"), prometheus.BuildFQName(types.Namespace, Name, "pin_read_hits_total"),
"(PinReadHitsTotal)", "(PinReadHitsTotal)",
nil, nil,
nil, nil,
) )
c.PinReadsTotal = prometheus.NewDesc( c.pinReadsTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "pin_reads_total"), prometheus.BuildFQName(types.Namespace, Name, "pin_reads_total"),
"(PinReadsTotal)", "(PinReadsTotal)",
nil, nil,
nil, nil,
) )
c.ReadAheadsTotal = prometheus.NewDesc( c.readAheadsTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "read_aheads_total"), prometheus.BuildFQName(types.Namespace, Name, "read_aheads_total"),
"(ReadAheadsTotal)", "(ReadAheadsTotal)",
nil, nil,
nil, nil,
) )
c.SyncCopyReadsTotal = prometheus.NewDesc( c.syncCopyReadsTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "sync_copy_reads_total"), prometheus.BuildFQName(types.Namespace, Name, "sync_copy_reads_total"),
"(SyncCopyReadsTotal)", "(SyncCopyReadsTotal)",
nil, nil,
nil, nil,
) )
c.SyncDataMapsTotal = prometheus.NewDesc( c.syncDataMapsTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "sync_data_maps_total"), prometheus.BuildFQName(types.Namespace, Name, "sync_data_maps_total"),
"(SyncDataMapsTotal)", "(SyncDataMapsTotal)",
nil, nil,
nil, nil,
) )
c.SyncFastReadsTotal = prometheus.NewDesc( c.syncFastReadsTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "sync_fast_reads_total"), prometheus.BuildFQName(types.Namespace, Name, "sync_fast_reads_total"),
"(SyncFastReadsTotal)", "(SyncFastReadsTotal)",
nil, nil,
nil, nil,
) )
c.SyncMDLReadsTotal = prometheus.NewDesc( c.syncMDLReadsTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "sync_mdl_reads_total"), prometheus.BuildFQName(types.Namespace, Name, "sync_mdl_reads_total"),
"(SyncMDLReadsTotal)", "(SyncMDLReadsTotal)",
nil, nil,
nil, nil,
) )
c.SyncPinReadsTotal = prometheus.NewDesc( c.syncPinReadsTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "sync_pin_reads_total"), prometheus.BuildFQName(types.Namespace, Name, "sync_pin_reads_total"),
"(SyncPinReadsTotal)", "(SyncPinReadsTotal)",
nil, nil,
@ -253,11 +259,13 @@ func (c *collector) Build() error {
} }
// Collect implements the Collector interface // Collect implements the Collector interface
func (c *collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collect(ctx, ch); err != nil { if err := c.collect(ctx, ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting cache metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting cache metrics", "err", err)
return err return err
} }
return nil return nil
} }
@ -269,23 +277,20 @@ type perflibCache struct {
AsyncFastReadsTotal float64 `perflib:"Async Fast Reads/sec"` AsyncFastReadsTotal float64 `perflib:"Async Fast Reads/sec"`
AsyncMDLReadsTotal float64 `perflib:"Async MDL Reads/sec"` AsyncMDLReadsTotal float64 `perflib:"Async MDL Reads/sec"`
AsyncPinReadsTotal float64 `perflib:"Async Pin Reads/sec"` AsyncPinReadsTotal float64 `perflib:"Async Pin Reads/sec"`
CopyReadHitsTotal float64 `perflib:"Copy Read Hits %"` CopyReadHitsTotal float64 `perflib:"Copy Read Hits/sec"`
CopyReadsTotal float64 `perflib:"Copy Reads/sec"` CopyReadsTotal float64 `perflib:"Copy Reads/sec"`
DataFlushesTotal float64 `perflib:"Data Flushes/sec"` DataFlushesTotal float64 `perflib:"Data Flushes/sec"`
DataFlushPagesTotal float64 `perflib:"Data Flush Pages/sec"` DataFlushPagesTotal float64 `perflib:"Data Flush Pages/sec"`
DataMapHitsPercent float64 `perflib:"Data Map Hits %"`
DataMapPinsTotal float64 `perflib:"Data Map Pins/sec"` DataMapPinsTotal float64 `perflib:"Data Map Pins/sec"`
DataMapsTotal float64 `perflib:"Data Maps/sec"` DataMapsTotal float64 `perflib:"Data Maps/sec"`
DirtyPages float64 `perflib:"Dirty Pages"`
DirtyPageThreshold float64 `perflib:"Dirty Page Threshold"`
FastReadNotPossiblesTotal float64 `perflib:"Fast Read Not Possibles/sec"` FastReadNotPossiblesTotal float64 `perflib:"Fast Read Not Possibles/sec"`
FastReadResourceMissesTotal float64 `perflib:"Fast Read Resource Misses/sec"` FastReadResourceMissesTotal float64 `perflib:"Fast Read Resource Misses/sec"`
FastReadsTotal float64 `perflib:"Fast Reads/sec"` FastReadsTotal float64 `perflib:"Fast Reads/sec"`
LazyWriteFlushesTotal float64 `perflib:"Lazy Write Flushes/sec"` LazyWriteFlushesTotal float64 `perflib:"Lazy Write Flushes/sec"`
LazyWritePagesTotal float64 `perflib:"Lazy Write Pages/sec"` LazyWritePagesTotal float64 `perflib:"Lazy Write Pages/sec"`
MDLReadHitsTotal float64 `perflib:"MDL Read Hits %"` MDLReadHitsTotal float64 `perflib:"MDL Read Hits/sec"`
MDLReadsTotal float64 `perflib:"MDL Reads/sec"` MDLReadsTotal float64 `perflib:"MDL Reads/sec"`
PinReadHitsTotal float64 `perflib:"Pin Read Hits %"` PinReadHitsTotal float64 `perflib:"Pin Read Hits/sec"`
PinReadsTotal float64 `perflib:"Pin Reads/sec"` PinReadsTotal float64 `perflib:"Pin Reads/sec"`
ReadAheadsTotal float64 `perflib:"Read Aheads/sec"` ReadAheadsTotal float64 `perflib:"Read Aheads/sec"`
SyncCopyReadsTotal float64 `perflib:"Sync Copy Reads/sec"` SyncCopyReadsTotal float64 `perflib:"Sync Copy Reads/sec"`
@ -293,187 +298,166 @@ type perflibCache struct {
SyncFastReadsTotal float64 `perflib:"Sync Fast Reads/sec"` SyncFastReadsTotal float64 `perflib:"Sync Fast Reads/sec"`
SyncMDLReadsTotal float64 `perflib:"Sync MDL Reads/sec"` SyncMDLReadsTotal float64 `perflib:"Sync MDL Reads/sec"`
SyncPinReadsTotal float64 `perflib:"Sync Pin Reads/sec"` SyncPinReadsTotal float64 `perflib:"Sync Pin Reads/sec"`
DirtyPages float64 `perflib:"Dirty Pages"`
DirtyPageThreshold float64 `perflib:"Dirty Page Threshold"`
DataMapHitsPercent float64 `perflib:"Data Map Hits %"`
} }
func (c *collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var dst []perflibCache // Single-instance class, array is required but will have single entry. var dst []perflibCache // Single-instance class, array is required but will have single entry.
if err := perflib.UnmarshalObject(ctx.PerfObjects["Cache"], &dst, c.logger); err != nil { if err := perflib.UnmarshalObject(ctx.PerfObjects["Cache"], &dst, c.logger); err != nil {
return err return err
} }
if len(dst) != 1 {
return errors.New("expected single instance of Cache")
}
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.AsyncCopyReadsTotal, c.asyncCopyReadsTotal,
prometheus.CounterValue, prometheus.CounterValue,
dst[0].AsyncCopyReadsTotal, dst[0].AsyncCopyReadsTotal,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.AsyncDataMapsTotal, c.asyncDataMapsTotal,
prometheus.CounterValue, prometheus.CounterValue,
dst[0].AsyncDataMapsTotal, dst[0].AsyncDataMapsTotal,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.AsyncFastReadsTotal, c.asyncFastReadsTotal,
prometheus.CounterValue, prometheus.CounterValue,
dst[0].AsyncFastReadsTotal, dst[0].AsyncFastReadsTotal,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.AsyncMDLReadsTotal, c.asyncMDLReadsTotal,
prometheus.CounterValue, prometheus.CounterValue,
dst[0].AsyncMDLReadsTotal, dst[0].AsyncMDLReadsTotal,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.AsyncPinReadsTotal, c.asyncPinReadsTotal,
prometheus.CounterValue, prometheus.CounterValue,
dst[0].AsyncPinReadsTotal, dst[0].AsyncPinReadsTotal,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.CopyReadHitsTotal, c.copyReadHitsTotal,
prometheus.GaugeValue, prometheus.CounterValue,
dst[0].CopyReadHitsTotal, dst[0].CopyReadHitsTotal,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.CopyReadsTotal, c.copyReadsTotal,
prometheus.CounterValue, prometheus.CounterValue,
dst[0].CopyReadsTotal, dst[0].CopyReadsTotal,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.DataFlushesTotal, c.dataFlushesTotal,
prometheus.CounterValue, prometheus.CounterValue,
dst[0].DataFlushesTotal, dst[0].DataFlushesTotal,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.DataFlushPagesTotal, c.dataFlushPagesTotal,
prometheus.CounterValue, prometheus.CounterValue,
dst[0].DataFlushPagesTotal, dst[0].DataFlushPagesTotal,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.DataMapHitsPercent, c.dataMapPinsTotal,
prometheus.CounterValue,
dst[0].DataMapPinsTotal,
)
ch <- prometheus.MustNewConstMetric(
c.dataMapsTotal,
prometheus.CounterValue,
dst[0].DataMapsTotal,
)
ch <- prometheus.MustNewConstMetric(
c.fastReadNotPossiblesTotal,
prometheus.CounterValue,
dst[0].FastReadNotPossiblesTotal,
)
ch <- prometheus.MustNewConstMetric(
c.fastReadResourceMissesTotal,
prometheus.CounterValue,
dst[0].FastReadResourceMissesTotal,
)
ch <- prometheus.MustNewConstMetric(
c.fastReadsTotal,
prometheus.CounterValue,
dst[0].FastReadsTotal,
)
ch <- prometheus.MustNewConstMetric(
c.lazyWriteFlushesTotal,
prometheus.CounterValue,
dst[0].LazyWriteFlushesTotal,
)
ch <- prometheus.MustNewConstMetric(
c.lazyWritePagesTotal,
prometheus.CounterValue,
dst[0].LazyWritePagesTotal,
)
ch <- prometheus.MustNewConstMetric(
c.mdlReadHitsTotal,
prometheus.CounterValue,
dst[0].MDLReadHitsTotal,
)
ch <- prometheus.MustNewConstMetric(
c.mdlReadsTotal,
prometheus.CounterValue,
dst[0].MDLReadsTotal,
)
ch <- prometheus.MustNewConstMetric(
c.pinReadHitsTotal,
prometheus.CounterValue,
dst[0].PinReadHitsTotal,
)
ch <- prometheus.MustNewConstMetric(
c.pinReadsTotal,
prometheus.CounterValue,
dst[0].PinReadsTotal,
)
ch <- prometheus.MustNewConstMetric(
c.readAheadsTotal,
prometheus.CounterValue,
dst[0].ReadAheadsTotal,
)
ch <- prometheus.MustNewConstMetric(
c.syncCopyReadsTotal,
prometheus.CounterValue,
dst[0].SyncCopyReadsTotal,
)
ch <- prometheus.MustNewConstMetric(
c.syncDataMapsTotal,
prometheus.CounterValue,
dst[0].SyncDataMapsTotal,
)
ch <- prometheus.MustNewConstMetric(
c.syncFastReadsTotal,
prometheus.CounterValue,
dst[0].SyncFastReadsTotal,
)
ch <- prometheus.MustNewConstMetric(
c.syncMDLReadsTotal,
prometheus.CounterValue,
dst[0].SyncMDLReadsTotal,
)
ch <- prometheus.MustNewConstMetric(
c.syncPinReadsTotal,
prometheus.CounterValue,
dst[0].SyncPinReadsTotal,
)
ch <- prometheus.MustNewConstMetric(
c.dirtyPages,
prometheus.GaugeValue,
dst[0].DirtyPages,
)
ch <- prometheus.MustNewConstMetric(
c.dirtyPageThreshold,
prometheus.GaugeValue,
dst[0].DirtyPageThreshold,
)
ch <- prometheus.MustNewConstMetric(
c.dataMapHitsPercent,
prometheus.GaugeValue, prometheus.GaugeValue,
dst[0].DataMapHitsPercent, dst[0].DataMapHitsPercent,
) )
ch <- prometheus.MustNewConstMetric(
c.DataMapPinsTotal,
prometheus.CounterValue,
dst[0].DataMapPinsTotal,
)
ch <- prometheus.MustNewConstMetric(
c.DataMapsTotal,
prometheus.CounterValue,
dst[0].DataMapsTotal,
)
ch <- prometheus.MustNewConstMetric(
c.DirtyPages,
prometheus.GaugeValue,
dst[0].DirtyPages,
)
ch <- prometheus.MustNewConstMetric(
c.DirtyPageThreshold,
prometheus.GaugeValue,
dst[0].DirtyPageThreshold,
)
ch <- prometheus.MustNewConstMetric(
c.FastReadNotPossiblesTotal,
prometheus.CounterValue,
dst[0].FastReadNotPossiblesTotal,
)
ch <- prometheus.MustNewConstMetric(
c.FastReadResourceMissesTotal,
prometheus.CounterValue,
dst[0].FastReadResourceMissesTotal,
)
ch <- prometheus.MustNewConstMetric(
c.FastReadsTotal,
prometheus.CounterValue,
dst[0].FastReadsTotal,
)
ch <- prometheus.MustNewConstMetric(
c.LazyWriteFlushesTotal,
prometheus.CounterValue,
dst[0].LazyWriteFlushesTotal,
)
ch <- prometheus.MustNewConstMetric(
c.LazyWritePagesTotal,
prometheus.CounterValue,
dst[0].LazyWritePagesTotal,
)
ch <- prometheus.MustNewConstMetric(
c.MDLReadHitsTotal,
prometheus.CounterValue,
dst[0].MDLReadHitsTotal,
)
ch <- prometheus.MustNewConstMetric(
c.MDLReadsTotal,
prometheus.CounterValue,
dst[0].MDLReadsTotal,
)
ch <- prometheus.MustNewConstMetric(
c.PinReadHitsTotal,
prometheus.CounterValue,
dst[0].PinReadHitsTotal,
)
ch <- prometheus.MustNewConstMetric(
c.PinReadsTotal,
prometheus.CounterValue,
dst[0].PinReadsTotal,
)
ch <- prometheus.MustNewConstMetric(
c.ReadAheadsTotal,
prometheus.CounterValue,
dst[0].ReadAheadsTotal,
)
ch <- prometheus.MustNewConstMetric(
c.SyncCopyReadsTotal,
prometheus.CounterValue,
dst[0].SyncCopyReadsTotal,
)
ch <- prometheus.MustNewConstMetric(
c.SyncDataMapsTotal,
prometheus.CounterValue,
dst[0].SyncDataMapsTotal,
)
ch <- prometheus.MustNewConstMetric(
c.SyncFastReadsTotal,
prometheus.CounterValue,
dst[0].SyncFastReadsTotal,
)
ch <- prometheus.MustNewConstMetric(
c.SyncMDLReadsTotal,
prometheus.CounterValue,
dst[0].SyncMDLReadsTotal,
)
ch <- prometheus.MustNewConstMetric(
c.SyncPinReadsTotal,
prometheus.CounterValue,
dst[0].SyncPinReadsTotal,
)
return nil return nil
} }

12
pkg/collector/cache/cache_test.go vendored Normal file
View File

@ -0,0 +1,12 @@
package cache_test
import (
"testing"
"github.com/prometheus-community/windows_exporter/pkg/collector/cache"
"github.com/prometheus-community/windows_exporter/pkg/testutils"
)
func BenchmarkCollector(b *testing.B) {
testutils.FuncBenchmarkCollector(b, cache.Name, cache.NewWithFlags)
}

View File

@ -3,12 +3,12 @@
package collector package collector
import ( import (
"errors"
"slices" "slices"
"strings" "strings"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/prometheus-community/windows_exporter/pkg/collector/ad" "github.com/prometheus-community/windows_exporter/pkg/collector/ad"
"github.com/prometheus-community/windows_exporter/pkg/collector/adcs" "github.com/prometheus-community/windows_exporter/pkg/collector/adcs"
"github.com/prometheus-community/windows_exporter/pkg/collector/adfs" "github.com/prometheus-community/windows_exporter/pkg/collector/adfs"
@ -22,6 +22,7 @@ import (
"github.com/prometheus-community/windows_exporter/pkg/collector/diskdrive" "github.com/prometheus-community/windows_exporter/pkg/collector/diskdrive"
"github.com/prometheus-community/windows_exporter/pkg/collector/dns" "github.com/prometheus-community/windows_exporter/pkg/collector/dns"
"github.com/prometheus-community/windows_exporter/pkg/collector/exchange" "github.com/prometheus-community/windows_exporter/pkg/collector/exchange"
"github.com/prometheus-community/windows_exporter/pkg/collector/fsrmquota"
"github.com/prometheus-community/windows_exporter/pkg/collector/hyperv" "github.com/prometheus-community/windows_exporter/pkg/collector/hyperv"
"github.com/prometheus-community/windows_exporter/pkg/collector/iis" "github.com/prometheus-community/windows_exporter/pkg/collector/iis"
"github.com/prometheus-community/windows_exporter/pkg/collector/license" "github.com/prometheus-community/windows_exporter/pkg/collector/license"
@ -68,45 +69,44 @@ import (
"github.com/prometheus-community/windows_exporter/pkg/types" "github.com/prometheus-community/windows_exporter/pkg/types"
) )
type Collectors struct {
logger log.Logger
collectors map[string]types.Collector
perfCounterQuery string
}
// NewWithFlags To be called by the exporter for collector initialization before running kingpin.Parse // NewWithFlags To be called by the exporter for collector initialization before running kingpin.Parse
func NewWithFlags(app *kingpin.Application) Collectors { func NewWithFlags(app *kingpin.Application) Collectors {
collectors := map[string]types.Collector{} collectors := map[string]Collector{}
for name, builder := range Map { for name, builder := range BuildersWithFlags {
collectors[name] = builder(app) collectors[name] = builder(app)
} }
return New(collectors) return New(collectors)
} }
func NewBuilderWithFlags[C Collector](fn BuilderWithFlags[C]) BuilderWithFlags[Collector] {
return func(app *kingpin.Application) Collector {
return fn(app)
}
}
// NewWithConfig To be called by the external libraries for collector initialization without running kingpin.Parse // NewWithConfig To be called by the external libraries for collector initialization without running kingpin.Parse
// //
//goland:noinspection GoUnusedExportedFunction //goland:noinspection GoUnusedExportedFunction
func NewWithConfig(logger log.Logger, config Config) Collectors { func NewWithConfig(logger log.Logger, config Config) Collectors {
collectors := map[string]types.Collector{} collectors := map[string]Collector{}
collectors[ad.Name] = ad.New(logger, &config.Ad) collectors[ad.Name] = ad.New(logger, &config.AD)
collectors[adcs.Name] = adcs.New(logger, &config.Adcs) collectors[adcs.Name] = adcs.New(logger, &config.ADCS)
collectors[adfs.Name] = adfs.New(logger, &config.Adfs) collectors[adfs.Name] = adfs.New(logger, &config.ADFS)
collectors[cache.Name] = cache.New(logger, &config.Cache) collectors[cache.Name] = cache.New(logger, &config.Cache)
collectors[container.Name] = container.New(logger, &config.Container) collectors[container.Name] = container.New(logger, &config.Container)
collectors[cpu.Name] = cpu.New(logger, &config.Cpu) collectors[cpu.Name] = cpu.New(logger, &config.CPU)
collectors[cpu_info.Name] = cpu_info.New(logger, &config.CpuInfo) collectors[cpu_info.Name] = cpu_info.New(logger, &config.CPUInfo)
collectors[cs.Name] = cs.New(logger, &config.Cs) collectors[cs.Name] = cs.New(logger, &config.Cs)
collectors[dfsr.Name] = dfsr.New(logger, &config.Dfsr) collectors[dfsr.Name] = dfsr.New(logger, &config.DFSR)
collectors[dhcp.Name] = dhcp.New(logger, &config.Dhcp) collectors[dhcp.Name] = dhcp.New(logger, &config.Dhcp)
collectors[diskdrive.Name] = diskdrive.New(logger, &config.Diskdrive) collectors[diskdrive.Name] = diskdrive.New(logger, &config.DiskDrive)
collectors[dns.Name] = dns.New(logger, &config.Dns) collectors[dns.Name] = dns.New(logger, &config.DNS)
collectors[exchange.Name] = exchange.New(logger, &config.Exchange) collectors[exchange.Name] = exchange.New(logger, &config.Exchange)
collectors[exchange.Name] = exchange.New(logger, &config.Fsrmquota) collectors[fsrmquota.Name] = fsrmquota.New(logger, &config.Fsrmquota)
collectors[hyperv.Name] = hyperv.New(logger, &config.Hyperv) collectors[hyperv.Name] = hyperv.New(logger, &config.Hyperv)
collectors[iis.Name] = iis.New(logger, &config.Iis) collectors[iis.Name] = iis.New(logger, &config.IIS)
collectors[license.Name] = license.New(logger, &config.License) collectors[license.Name] = license.New(logger, &config.License)
collectors[logical_disk.Name] = logical_disk.New(logger, &config.LogicalDisk) collectors[logical_disk.Name] = logical_disk.New(logger, &config.LogicalDisk)
collectors[logon.Name] = logon.New(logger, &config.Logon) collectors[logon.Name] = logon.New(logger, &config.Logon)
@ -135,12 +135,12 @@ func NewWithConfig(logger log.Logger, config Config) Collectors {
collectors[remote_fx.Name] = remote_fx.New(logger, &config.RemoteFx) collectors[remote_fx.Name] = remote_fx.New(logger, &config.RemoteFx)
collectors[scheduled_task.Name] = scheduled_task.New(logger, &config.ScheduledTask) collectors[scheduled_task.Name] = scheduled_task.New(logger, &config.ScheduledTask)
collectors[service.Name] = service.New(logger, &config.Service) collectors[service.Name] = service.New(logger, &config.Service)
collectors[smb.Name] = smb.New(logger, &config.Smb) collectors[smb.Name] = smb.New(logger, &config.SMB)
collectors[smbclient.Name] = smbclient.New(logger, &config.SmbClient) collectors[smbclient.Name] = smbclient.New(logger, &config.SMBClient)
collectors[smtp.Name] = smtp.New(logger, &config.Smtp) collectors[smtp.Name] = smtp.New(logger, &config.SMTP)
collectors[system.Name] = system.New(logger, &config.System) collectors[system.Name] = system.New(logger, &config.System)
collectors[teradici_pcoip.Name] = teradici_pcoip.New(logger, &config.TeradiciPcoip) collectors[teradici_pcoip.Name] = teradici_pcoip.New(logger, &config.TeradiciPcoip)
collectors[tcp.Name] = tcp.New(logger, &config.Tcp) collectors[tcp.Name] = tcp.New(logger, &config.TCP)
collectors[terminal_services.Name] = terminal_services.New(logger, &config.TerminalServices) collectors[terminal_services.Name] = terminal_services.New(logger, &config.TerminalServices)
collectors[textfile.Name] = textfile.New(logger, &config.Textfile) collectors[textfile.Name] = textfile.New(logger, &config.Textfile)
collectors[thermalzone.Name] = thermalzone.New(logger, &config.Thermalzone) collectors[thermalzone.Name] = thermalzone.New(logger, &config.Thermalzone)
@ -151,8 +151,8 @@ func NewWithConfig(logger log.Logger, config Config) Collectors {
return New(collectors) return New(collectors)
} }
// New To be called by the external libraries for collector initialization // New To be called by the external libraries for collector initialization.
func New(collectors map[string]types.Collector) Collectors { func New(collectors Map) Collectors {
return Collectors{ return Collectors{
collectors: collectors, collectors: collectors,
} }
@ -207,6 +207,7 @@ func (c *Collectors) Enable(enabledCollectors []string) {
// Build To be called by the exporter for collector initialization // Build To be called by the exporter for collector initialization
func (c *Collectors) Build() error { func (c *Collectors) Build() error {
var err error var err error
for _, collector := range c.collectors { for _, collector := range c.collectors {
if err = collector.Build(); err != nil { if err = collector.Build(); err != nil {
return err return err
@ -225,3 +226,16 @@ func (c *Collectors) PrepareScrapeContext() (*types.ScrapeContext, error) {
return &types.ScrapeContext{PerfObjects: objs}, nil return &types.ScrapeContext{PerfObjects: objs}, nil
} }
// Close To be called by the exporter for collector cleanup
func (c *Collectors) Close() error {
errs := make([]error, 0, len(c.collectors))
for _, collector := range c.collectors {
if err := collector.Build(); err != nil {
errs = append(errs, err)
}
}
return errors.Join(errs...)
}

View File

@ -14,6 +14,7 @@ import (
"github.com/prometheus-community/windows_exporter/pkg/collector/diskdrive" "github.com/prometheus-community/windows_exporter/pkg/collector/diskdrive"
"github.com/prometheus-community/windows_exporter/pkg/collector/dns" "github.com/prometheus-community/windows_exporter/pkg/collector/dns"
"github.com/prometheus-community/windows_exporter/pkg/collector/exchange" "github.com/prometheus-community/windows_exporter/pkg/collector/exchange"
"github.com/prometheus-community/windows_exporter/pkg/collector/fsrmquota"
"github.com/prometheus-community/windows_exporter/pkg/collector/hyperv" "github.com/prometheus-community/windows_exporter/pkg/collector/hyperv"
"github.com/prometheus-community/windows_exporter/pkg/collector/iis" "github.com/prometheus-community/windows_exporter/pkg/collector/iis"
"github.com/prometheus-community/windows_exporter/pkg/collector/license" "github.com/prometheus-community/windows_exporter/pkg/collector/license"
@ -59,22 +60,22 @@ import (
) )
type Config struct { type Config struct {
Ad ad.Config `yaml:"ad"` AD ad.Config `yaml:"ad"`
Adcs adcs.Config `yaml:"adcs"` ADCS adcs.Config `yaml:"adcs"`
Adfs adfs.Config `yaml:"adfs"` ADFS adfs.Config `yaml:"adfs"`
Cache cache.Config `yaml:"cache"` Cache cache.Config `yaml:"cache"`
Container container.Config `yaml:"container"` Container container.Config `yaml:"container"`
Cpu cpu.Config `yaml:"cpu"` CPU cpu.Config `yaml:"cpu"`
CpuInfo cpu_info.Config `yaml:"cpu_info"` CPUInfo cpu_info.Config `yaml:"cpu_info"`
Cs cs.Config `yaml:"cs"` Cs cs.Config `yaml:"cs"`
Dfsr dfsr.Config `yaml:"dfsr"` DFSR dfsr.Config `yaml:"dfsr"`
Dhcp dhcp.Config `yaml:"dhcp"` Dhcp dhcp.Config `yaml:"dhcp"`
Diskdrive diskdrive.Config `yaml:"diskdrive"` DiskDrive diskdrive.Config `yaml:"diskdrive"`
Dns dns.Config `yaml:"dns"` DNS dns.Config `yaml:"dns"`
Exchange exchange.Config `yaml:"exchange"` Exchange exchange.Config `yaml:"exchange"`
Fsrmquota exchange.Config `yaml:"fsrmquota"` Fsrmquota fsrmquota.Config `yaml:"fsrmquota"`
Hyperv hyperv.Config `yaml:"hyperv"` Hyperv hyperv.Config `yaml:"hyperv"`
Iis iis.Config `yaml:"iis"` IIS iis.Config `yaml:"iis"`
License license.Config `yaml:"license"` License license.Config `yaml:"license"`
LogicalDisk logical_disk.Config `yaml:"logical_disk"` LogicalDisk logical_disk.Config `yaml:"logical_disk"`
Logon logon.Config `yaml:"logon"` Logon logon.Config `yaml:"logon"`
@ -103,12 +104,12 @@ type Config struct {
RemoteFx remote_fx.Config `yaml:"remote_fx"` RemoteFx remote_fx.Config `yaml:"remote_fx"`
ScheduledTask scheduled_task.Config `yaml:"scheduled_task"` ScheduledTask scheduled_task.Config `yaml:"scheduled_task"`
Service service.Config `yaml:"service"` Service service.Config `yaml:"service"`
Smb smb.Config `yaml:"smb"` SMB smb.Config `yaml:"smb"`
SmbClient smbclient.Config `yaml:"smbclient"` SMBClient smbclient.Config `yaml:"smbclient"`
Smtp smtp.Config `yaml:"smtp"` SMTP smtp.Config `yaml:"smtp"`
System system.Config `yaml:"system"` System system.Config `yaml:"system"`
TeradiciPcoip teradici_pcoip.Config `yaml:"teradici_pcoip"` TeradiciPcoip teradici_pcoip.Config `yaml:"teradici_pcoip"`
Tcp tcp.Config `yaml:"tcp"` TCP tcp.Config `yaml:"tcp"`
TerminalServices terminal_services.Config `yaml:"terminal_services"` TerminalServices terminal_services.Config `yaml:"terminal_services"`
Textfile textfile.Config `yaml:"textfile"` Textfile textfile.Config `yaml:"textfile"`
Thermalzone thermalzone.Config `yaml:"thermalzone"` Thermalzone thermalzone.Config `yaml:"thermalzone"`
@ -121,22 +122,22 @@ type Config struct {
// //
//goland:noinspection GoUnusedGlobalVariable //goland:noinspection GoUnusedGlobalVariable
var ConfigDefaults = Config{ var ConfigDefaults = Config{
Ad: ad.ConfigDefaults, AD: ad.ConfigDefaults,
Adcs: adcs.ConfigDefaults, ADCS: adcs.ConfigDefaults,
Adfs: adfs.ConfigDefaults, ADFS: adfs.ConfigDefaults,
Cache: cache.ConfigDefaults, Cache: cache.ConfigDefaults,
Container: container.ConfigDefaults, Container: container.ConfigDefaults,
Cpu: cpu.ConfigDefaults, CPU: cpu.ConfigDefaults,
CpuInfo: cpu_info.ConfigDefaults, CPUInfo: cpu_info.ConfigDefaults,
Cs: cs.ConfigDefaults, Cs: cs.ConfigDefaults,
Dfsr: dfsr.ConfigDefaults, DFSR: dfsr.ConfigDefaults,
Dhcp: dhcp.ConfigDefaults, Dhcp: dhcp.ConfigDefaults,
Diskdrive: diskdrive.ConfigDefaults, DiskDrive: diskdrive.ConfigDefaults,
Dns: dns.ConfigDefaults, DNS: dns.ConfigDefaults,
Exchange: exchange.ConfigDefaults, Exchange: exchange.ConfigDefaults,
Fsrmquota: exchange.ConfigDefaults, Fsrmquota: fsrmquota.ConfigDefaults,
Hyperv: hyperv.ConfigDefaults, Hyperv: hyperv.ConfigDefaults,
Iis: iis.ConfigDefaults, IIS: iis.ConfigDefaults,
License: license.ConfigDefaults, License: license.ConfigDefaults,
LogicalDisk: logical_disk.ConfigDefaults, LogicalDisk: logical_disk.ConfigDefaults,
Logon: logon.ConfigDefaults, Logon: logon.ConfigDefaults,
@ -165,12 +166,12 @@ var ConfigDefaults = Config{
RemoteFx: remote_fx.ConfigDefaults, RemoteFx: remote_fx.ConfigDefaults,
ScheduledTask: scheduled_task.ConfigDefaults, ScheduledTask: scheduled_task.ConfigDefaults,
Service: service.ConfigDefaults, Service: service.ConfigDefaults,
Smb: smb.ConfigDefaults, SMB: smb.ConfigDefaults,
SmbClient: smbclient.ConfigDefaults, SMBClient: smbclient.ConfigDefaults,
Smtp: smtp.ConfigDefaults, SMTP: smtp.ConfigDefaults,
System: system.ConfigDefaults, System: system.ConfigDefaults,
TeradiciPcoip: teradici_pcoip.ConfigDefaults, TeradiciPcoip: teradici_pcoip.ConfigDefaults,
Tcp: tcp.ConfigDefaults, TCP: tcp.ConfigDefaults,
TerminalServices: terminal_services.ConfigDefaults, TerminalServices: terminal_services.ConfigDefaults,
Textfile: textfile.ConfigDefaults, Textfile: textfile.ConfigDefaults,
Thermalzone: thermalzone.ConfigDefaults, Thermalzone: thermalzone.ConfigDefaults,

View File

@ -20,167 +20,173 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
// A collector is a Prometheus collector for containers metrics // A Collector is a Prometheus Collector for containers metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
// Presence // Presence
ContainerAvailable *prometheus.Desc containerAvailable *prometheus.Desc
// Number of containers // Number of containers
ContainersCount *prometheus.Desc containersCount *prometheus.Desc
// memory
UsageCommitBytes *prometheus.Desc // Memory
UsageCommitPeakBytes *prometheus.Desc usageCommitBytes *prometheus.Desc
UsagePrivateWorkingSetBytes *prometheus.Desc usageCommitPeakBytes *prometheus.Desc
usagePrivateWorkingSetBytes *prometheus.Desc
// CPU // CPU
RuntimeTotal *prometheus.Desc runtimeTotal *prometheus.Desc
RuntimeUser *prometheus.Desc runtimeUser *prometheus.Desc
RuntimeKernel *prometheus.Desc runtimeKernel *prometheus.Desc
// Network // Network
BytesReceived *prometheus.Desc bytesReceived *prometheus.Desc
BytesSent *prometheus.Desc bytesSent *prometheus.Desc
PacketsReceived *prometheus.Desc packetsReceived *prometheus.Desc
PacketsSent *prometheus.Desc packetsSent *prometheus.Desc
DroppedPacketsIncoming *prometheus.Desc droppedPacketsIncoming *prometheus.Desc
DroppedPacketsOutgoing *prometheus.Desc droppedPacketsOutgoing *prometheus.Desc
// Storage // Storage
ReadCountNormalized *prometheus.Desc readCountNormalized *prometheus.Desc
ReadSizeBytes *prometheus.Desc readSizeBytes *prometheus.Desc
WriteCountNormalized *prometheus.Desc writeCountNormalized *prometheus.Desc
WriteSizeBytes *prometheus.Desc writeSizeBytes *prometheus.Desc
} }
// New constructs a new collector // New constructs a new Collector
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{}, nil return []string{}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
c.ContainerAvailable = prometheus.NewDesc( return nil
}
func (c *Collector) Build() error {
c.containerAvailable = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "available"), prometheus.BuildFQName(types.Namespace, Name, "available"),
"Available", "Available",
[]string{"container_id"}, []string{"container_id"},
nil, nil,
) )
c.ContainersCount = prometheus.NewDesc( c.containersCount = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "count"), prometheus.BuildFQName(types.Namespace, Name, "count"),
"Number of containers", "Number of containers",
nil, nil,
nil, nil,
) )
c.UsageCommitBytes = prometheus.NewDesc( c.usageCommitBytes = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "memory_usage_commit_bytes"), prometheus.BuildFQName(types.Namespace, Name, "memory_usage_commit_bytes"),
"Memory Usage Commit Bytes", "Memory Usage Commit Bytes",
[]string{"container_id"}, []string{"container_id"},
nil, nil,
) )
c.UsageCommitPeakBytes = prometheus.NewDesc( c.usageCommitPeakBytes = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "memory_usage_commit_peak_bytes"), prometheus.BuildFQName(types.Namespace, Name, "memory_usage_commit_peak_bytes"),
"Memory Usage Commit Peak Bytes", "Memory Usage Commit Peak Bytes",
[]string{"container_id"}, []string{"container_id"},
nil, nil,
) )
c.UsagePrivateWorkingSetBytes = prometheus.NewDesc( c.usagePrivateWorkingSetBytes = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "memory_usage_private_working_set_bytes"), prometheus.BuildFQName(types.Namespace, Name, "memory_usage_private_working_set_bytes"),
"Memory Usage Private Working Set Bytes", "Memory Usage Private Working Set Bytes",
[]string{"container_id"}, []string{"container_id"},
nil, nil,
) )
c.RuntimeTotal = prometheus.NewDesc( c.runtimeTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "cpu_usage_seconds_total"), prometheus.BuildFQName(types.Namespace, Name, "cpu_usage_seconds_total"),
"Total Run time in Seconds", "Total Run time in Seconds",
[]string{"container_id"}, []string{"container_id"},
nil, nil,
) )
c.RuntimeUser = prometheus.NewDesc( c.runtimeUser = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "cpu_usage_seconds_usermode"), prometheus.BuildFQName(types.Namespace, Name, "cpu_usage_seconds_usermode"),
"Run Time in User mode in Seconds", "Run Time in User mode in Seconds",
[]string{"container_id"}, []string{"container_id"},
nil, nil,
) )
c.RuntimeKernel = prometheus.NewDesc( c.runtimeKernel = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "cpu_usage_seconds_kernelmode"), prometheus.BuildFQName(types.Namespace, Name, "cpu_usage_seconds_kernelmode"),
"Run time in Kernel mode in Seconds", "Run time in Kernel mode in Seconds",
[]string{"container_id"}, []string{"container_id"},
nil, nil,
) )
c.BytesReceived = prometheus.NewDesc( c.bytesReceived = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "network_receive_bytes_total"), prometheus.BuildFQName(types.Namespace, Name, "network_receive_bytes_total"),
"Bytes Received on Interface", "Bytes Received on Interface",
[]string{"container_id", "interface"}, []string{"container_id", "interface"},
nil, nil,
) )
c.BytesSent = prometheus.NewDesc( c.bytesSent = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "network_transmit_bytes_total"), prometheus.BuildFQName(types.Namespace, Name, "network_transmit_bytes_total"),
"Bytes Sent on Interface", "Bytes Sent on Interface",
[]string{"container_id", "interface"}, []string{"container_id", "interface"},
nil, nil,
) )
c.PacketsReceived = prometheus.NewDesc( c.packetsReceived = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "network_receive_packets_total"), prometheus.BuildFQName(types.Namespace, Name, "network_receive_packets_total"),
"Packets Received on Interface", "Packets Received on Interface",
[]string{"container_id", "interface"}, []string{"container_id", "interface"},
nil, nil,
) )
c.PacketsSent = prometheus.NewDesc( c.packetsSent = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "network_transmit_packets_total"), prometheus.BuildFQName(types.Namespace, Name, "network_transmit_packets_total"),
"Packets Sent on Interface", "Packets Sent on Interface",
[]string{"container_id", "interface"}, []string{"container_id", "interface"},
nil, nil,
) )
c.DroppedPacketsIncoming = prometheus.NewDesc( c.droppedPacketsIncoming = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "network_receive_packets_dropped_total"), prometheus.BuildFQName(types.Namespace, Name, "network_receive_packets_dropped_total"),
"Dropped Incoming Packets on Interface", "Dropped Incoming Packets on Interface",
[]string{"container_id", "interface"}, []string{"container_id", "interface"},
nil, nil,
) )
c.DroppedPacketsOutgoing = prometheus.NewDesc( c.droppedPacketsOutgoing = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "network_transmit_packets_dropped_total"), prometheus.BuildFQName(types.Namespace, Name, "network_transmit_packets_dropped_total"),
"Dropped Outgoing Packets on Interface", "Dropped Outgoing Packets on Interface",
[]string{"container_id", "interface"}, []string{"container_id", "interface"},
nil, nil,
) )
c.ReadCountNormalized = prometheus.NewDesc( c.readCountNormalized = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "storage_read_count_normalized_total"), prometheus.BuildFQName(types.Namespace, Name, "storage_read_count_normalized_total"),
"Read Count Normalized", "Read Count Normalized",
[]string{"container_id"}, []string{"container_id"},
nil, nil,
) )
c.ReadSizeBytes = prometheus.NewDesc( c.readSizeBytes = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "storage_read_size_bytes_total"), prometheus.BuildFQName(types.Namespace, Name, "storage_read_size_bytes_total"),
"Read Size Bytes", "Read Size Bytes",
[]string{"container_id"}, []string{"container_id"},
nil, nil,
) )
c.WriteCountNormalized = prometheus.NewDesc( c.writeCountNormalized = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "storage_write_count_normalized_total"), prometheus.BuildFQName(types.Namespace, Name, "storage_write_count_normalized_total"),
"Write Count Normalized", "Write Count Normalized",
[]string{"container_id"}, []string{"container_id"},
nil, nil,
) )
c.WriteSizeBytes = prometheus.NewDesc( c.writeSizeBytes = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "storage_write_size_bytes_total"), prometheus.BuildFQName(types.Namespace, Name, "storage_write_size_bytes_total"),
"Write Size Bytes", "Write Size Bytes",
[]string{"container_id"}, []string{"container_id"},
@ -191,7 +197,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collect(ch); err != nil { if err := c.collect(ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting collector metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting collector metrics", "err", err)
return err return err
@ -200,14 +206,14 @@ func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric)
} }
// containerClose closes the container resource // containerClose closes the container resource
func (c *collector) containerClose(container hcsshim.Container) { func (c *Collector) containerClose(container hcsshim.Container) {
err := container.Close() err := container.Close()
if err != nil { if err != nil {
_ = level.Error(c.logger).Log("err", err) _ = level.Error(c.logger).Log("err", err)
} }
} }
func (c *collector) collect(ch chan<- prometheus.Metric) error { func (c *Collector) collect(ch chan<- prometheus.Metric) error {
// Types Container is passed to get the containers compute systems only // Types Container is passed to get the containers compute systems only
containers, err := hcsshim.GetContainers(hcsshim.ComputeSystemQuery{Types: []string{"Container"}}) containers, err := hcsshim.GetContainers(hcsshim.ComputeSystemQuery{Types: []string{"Container"}})
if err != nil { if err != nil {
@ -218,7 +224,7 @@ func (c *collector) collect(ch chan<- prometheus.Metric) error {
count := len(containers) count := len(containers)
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.ContainersCount, c.containersCount,
prometheus.GaugeValue, prometheus.GaugeValue,
float64(count), float64(count),
) )
@ -250,67 +256,67 @@ func (c *collector) collect(ch chan<- prometheus.Metric) error {
containerPrefixes[containerDetails.ID] = containerIdWithPrefix containerPrefixes[containerDetails.ID] = containerIdWithPrefix
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.ContainerAvailable, c.containerAvailable,
prometheus.CounterValue, prometheus.CounterValue,
1, 1,
containerIdWithPrefix, containerIdWithPrefix,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.UsageCommitBytes, c.usageCommitBytes,
prometheus.GaugeValue, prometheus.GaugeValue,
float64(cstats.Memory.UsageCommitBytes), float64(cstats.Memory.UsageCommitBytes),
containerIdWithPrefix, containerIdWithPrefix,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.UsageCommitPeakBytes, c.usageCommitPeakBytes,
prometheus.GaugeValue, prometheus.GaugeValue,
float64(cstats.Memory.UsageCommitPeakBytes), float64(cstats.Memory.UsageCommitPeakBytes),
containerIdWithPrefix, containerIdWithPrefix,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.UsagePrivateWorkingSetBytes, c.usagePrivateWorkingSetBytes,
prometheus.GaugeValue, prometheus.GaugeValue,
float64(cstats.Memory.UsagePrivateWorkingSetBytes), float64(cstats.Memory.UsagePrivateWorkingSetBytes),
containerIdWithPrefix, containerIdWithPrefix,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.RuntimeTotal, c.runtimeTotal,
prometheus.CounterValue, prometheus.CounterValue,
float64(cstats.Processor.TotalRuntime100ns)*perflib.TicksToSecondScaleFactor, float64(cstats.Processor.TotalRuntime100ns)*perflib.TicksToSecondScaleFactor,
containerIdWithPrefix, containerIdWithPrefix,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.RuntimeUser, c.runtimeUser,
prometheus.CounterValue, prometheus.CounterValue,
float64(cstats.Processor.RuntimeUser100ns)*perflib.TicksToSecondScaleFactor, float64(cstats.Processor.RuntimeUser100ns)*perflib.TicksToSecondScaleFactor,
containerIdWithPrefix, containerIdWithPrefix,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.RuntimeKernel, c.runtimeKernel,
prometheus.CounterValue, prometheus.CounterValue,
float64(cstats.Processor.RuntimeKernel100ns)*perflib.TicksToSecondScaleFactor, float64(cstats.Processor.RuntimeKernel100ns)*perflib.TicksToSecondScaleFactor,
containerIdWithPrefix, containerIdWithPrefix,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.ReadCountNormalized, c.readCountNormalized,
prometheus.CounterValue, prometheus.CounterValue,
float64(cstats.Storage.ReadCountNormalized), float64(cstats.Storage.ReadCountNormalized),
containerIdWithPrefix, containerIdWithPrefix,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.ReadSizeBytes, c.readSizeBytes,
prometheus.CounterValue, prometheus.CounterValue,
float64(cstats.Storage.ReadSizeBytes), float64(cstats.Storage.ReadSizeBytes),
containerIdWithPrefix, containerIdWithPrefix,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.WriteCountNormalized, c.writeCountNormalized,
prometheus.CounterValue, prometheus.CounterValue,
float64(cstats.Storage.WriteCountNormalized), float64(cstats.Storage.WriteCountNormalized),
containerIdWithPrefix, containerIdWithPrefix,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.WriteSizeBytes, c.writeSizeBytes,
prometheus.CounterValue, prometheus.CounterValue,
float64(cstats.Storage.WriteSizeBytes), float64(cstats.Storage.WriteSizeBytes),
containerIdWithPrefix, containerIdWithPrefix,
@ -346,38 +352,38 @@ func (c *collector) collect(ch chan<- prometheus.Metric) error {
} }
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.BytesReceived, c.bytesReceived,
prometheus.CounterValue, prometheus.CounterValue,
float64(endpointStats.BytesReceived), float64(endpointStats.BytesReceived),
containerIdWithPrefix, endpointId, containerIdWithPrefix, endpointId,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.BytesSent, c.bytesSent,
prometheus.CounterValue, prometheus.CounterValue,
float64(endpointStats.BytesSent), float64(endpointStats.BytesSent),
containerIdWithPrefix, endpointId, containerIdWithPrefix, endpointId,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.PacketsReceived, c.packetsReceived,
prometheus.CounterValue, prometheus.CounterValue,
float64(endpointStats.PacketsReceived), float64(endpointStats.PacketsReceived),
containerIdWithPrefix, endpointId, containerIdWithPrefix, endpointId,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.PacketsSent, c.packetsSent,
prometheus.CounterValue, prometheus.CounterValue,
float64(endpointStats.PacketsSent), float64(endpointStats.PacketsSent),
containerIdWithPrefix, endpointId, containerIdWithPrefix, endpointId,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.DroppedPacketsIncoming, c.droppedPacketsIncoming,
prometheus.CounterValue, prometheus.CounterValue,
float64(endpointStats.DroppedPacketsIncoming), float64(endpointStats.DroppedPacketsIncoming),
containerIdWithPrefix, endpointId, containerIdWithPrefix, endpointId,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.DroppedPacketsOutgoing, c.droppedPacketsOutgoing,
prometheus.CounterValue, prometheus.CounterValue,
float64(endpointStats.DroppedPacketsOutgoing), float64(endpointStats.DroppedPacketsOutgoing),
containerIdWithPrefix, endpointId, containerIdWithPrefix, endpointId,

View File

@ -19,71 +19,74 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
CStateSecondsTotal *prometheus.Desc cStateSecondsTotal *prometheus.Desc
TimeTotal *prometheus.Desc timeTotal *prometheus.Desc
InterruptsTotal *prometheus.Desc interruptsTotal *prometheus.Desc
DPCsTotal *prometheus.Desc dpcsTotal *prometheus.Desc
clockInterruptsTotal *prometheus.Desc
ClockInterruptsTotal *prometheus.Desc idleBreakEventsTotal *prometheus.Desc
IdleBreakEventsTotal *prometheus.Desc parkingStatus *prometheus.Desc
ParkingStatus *prometheus.Desc processorFrequencyMHz *prometheus.Desc
ProcessorFrequencyMHz *prometheus.Desc processorPerformance *prometheus.Desc
ProcessorMaxFrequencyMHz *prometheus.Desc processorMPerf *prometheus.Desc
ProcessorPerformance *prometheus.Desc processorRTC *prometheus.Desc
ProcessorMPerf *prometheus.Desc processorUtility *prometheus.Desc
ProcessorRTC *prometheus.Desc processorPrivilegedUtility *prometheus.Desc
ProcessorUtility *prometheus.Desc
ProcessorPrivUtility *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
if winversion.WindowsVersionFloat > 6.05 { if winversion.WindowsVersionFloat > 6.05 {
return []string{"Processor Information"}, nil return []string{"Processor Information"}, nil
} }
return []string{"Processor"}, nil return []string{"Processor"}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
c.CStateSecondsTotal = prometheus.NewDesc( return nil
}
func (c *Collector) Build() error {
c.cStateSecondsTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "cstate_seconds_total"), prometheus.BuildFQName(types.Namespace, Name, "cstate_seconds_total"),
"Time spent in low-power idle state", "Time spent in low-power idle state",
[]string{"core", "state"}, []string{"core", "state"},
nil, nil,
) )
c.TimeTotal = prometheus.NewDesc( c.timeTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "time_total"), prometheus.BuildFQName(types.Namespace, Name, "time_total"),
"Time that processor spent in different modes (dpc, idle, interrupt, privileged, user)", "Time that processor spent in different modes (dpc, idle, interrupt, privileged, user)",
[]string{"core", "mode"}, []string{"core", "mode"},
nil, nil,
) )
c.InterruptsTotal = prometheus.NewDesc( c.interruptsTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "interrupts_total"), prometheus.BuildFQName(types.Namespace, Name, "interrupts_total"),
"Total number of received and serviced hardware interrupts", "Total number of received and serviced hardware interrupts",
[]string{"core"}, []string{"core"},
nil, nil,
) )
c.DPCsTotal = prometheus.NewDesc( c.dpcsTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "dpcs_total"), prometheus.BuildFQName(types.Namespace, Name, "dpcs_total"),
"Total number of received and serviced deferred procedure calls (DPCs)", "Total number of received and serviced deferred procedure calls (DPCs)",
[]string{"core"}, []string{"core"},
@ -100,79 +103,79 @@ func (c *collector) Build() error {
return nil return nil
} }
c.CStateSecondsTotal = prometheus.NewDesc( c.cStateSecondsTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "cstate_seconds_total"), prometheus.BuildFQName(types.Namespace, Name, "cstate_seconds_total"),
"Time spent in low-power idle state", "Time spent in low-power idle state",
[]string{"core", "state"}, []string{"core", "state"},
nil, nil,
) )
c.TimeTotal = prometheus.NewDesc( c.timeTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "time_total"), prometheus.BuildFQName(types.Namespace, Name, "time_total"),
"Time that processor spent in different modes (dpc, idle, interrupt, privileged, user)", "Time that processor spent in different modes (dpc, idle, interrupt, privileged, user)",
[]string{"core", "mode"}, []string{"core", "mode"},
nil, nil,
) )
c.InterruptsTotal = prometheus.NewDesc( c.interruptsTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "interrupts_total"), prometheus.BuildFQName(types.Namespace, Name, "interrupts_total"),
"Total number of received and serviced hardware interrupts", "Total number of received and serviced hardware interrupts",
[]string{"core"}, []string{"core"},
nil, nil,
) )
c.DPCsTotal = prometheus.NewDesc( c.dpcsTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "dpcs_total"), prometheus.BuildFQName(types.Namespace, Name, "dpcs_total"),
"Total number of received and serviced deferred procedure calls (DPCs)", "Total number of received and serviced deferred procedure calls (DPCs)",
[]string{"core"}, []string{"core"},
nil, nil,
) )
c.ClockInterruptsTotal = prometheus.NewDesc( c.clockInterruptsTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "clock_interrupts_total"), prometheus.BuildFQName(types.Namespace, Name, "clock_interrupts_total"),
"Total number of received and serviced clock tick interrupts", "Total number of received and serviced clock tick interrupts",
[]string{"core"}, []string{"core"},
nil, nil,
) )
c.IdleBreakEventsTotal = prometheus.NewDesc( c.idleBreakEventsTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "idle_break_events_total"), prometheus.BuildFQName(types.Namespace, Name, "idle_break_events_total"),
"Total number of time processor was woken from idle", "Total number of time processor was woken from idle",
[]string{"core"}, []string{"core"},
nil, nil,
) )
c.ParkingStatus = prometheus.NewDesc( c.parkingStatus = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "parking_status"), prometheus.BuildFQName(types.Namespace, Name, "parking_status"),
"Parking Status represents whether a processor is parked or not", "Parking Status represents whether a processor is parked or not",
[]string{"core"}, []string{"core"},
nil, nil,
) )
c.ProcessorFrequencyMHz = prometheus.NewDesc( c.processorFrequencyMHz = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "core_frequency_mhz"), prometheus.BuildFQName(types.Namespace, Name, "core_frequency_mhz"),
"Core frequency in megahertz", "Core frequency in megahertz",
[]string{"core"}, []string{"core"},
nil, nil,
) )
c.ProcessorPerformance = prometheus.NewDesc( c.processorPerformance = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "processor_performance_total"), prometheus.BuildFQName(types.Namespace, Name, "processor_performance_total"),
"Processor Performance is the average performance of the processor while it is executing instructions, as a percentage of the nominal performance of the processor. On some processors, Processor Performance may exceed 100%", "Processor Performance is the average performance of the processor while it is executing instructions, as a percentage of the nominal performance of the processor. On some processors, Processor Performance may exceed 100%",
[]string{"core"}, []string{"core"},
nil, nil,
) )
c.ProcessorMPerf = prometheus.NewDesc( c.processorMPerf = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "processor_mperf_total"), prometheus.BuildFQName(types.Namespace, Name, "processor_mperf_total"),
"Processor MPerf is the number of TSC ticks incremented while executing instructions", "Processor MPerf is the number of TSC ticks incremented while executing instructions",
[]string{"core"}, []string{"core"},
nil, nil,
) )
c.ProcessorRTC = prometheus.NewDesc( c.processorRTC = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "processor_rtc_total"), prometheus.BuildFQName(types.Namespace, Name, "processor_rtc_total"),
"Processor RTC represents the number of RTC ticks made since the system booted. It should consistently be 64e6, and can be used to properly derive Processor Utility Rate", "Processor RTC represents the number of RTC ticks made since the system booted. It should consistently be 64e6, and can be used to properly derive Processor Utility Rate",
[]string{"core"}, []string{"core"},
nil, nil,
) )
c.ProcessorUtility = prometheus.NewDesc( c.processorUtility = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "processor_utility_total"), prometheus.BuildFQName(types.Namespace, Name, "processor_utility_total"),
"Processor Utility represents is the amount of time the core spends executing instructions", "Processor Utility represents is the amount of time the core spends executing instructions",
[]string{"core"}, []string{"core"},
nil, nil,
) )
c.ProcessorPrivUtility = prometheus.NewDesc( c.processorPrivilegedUtility = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "processor_privileged_utility_total"), prometheus.BuildFQName(types.Namespace, Name, "processor_privileged_utility_total"),
"Processor Privileged Utility represents is the amount of time the core has spent executing instructions inside the kernel", "Processor Privileged Utility represents is the amount of time the core has spent executing instructions inside the kernel",
[]string{"core"}, []string{"core"},
@ -182,7 +185,7 @@ func (c *collector) Build() error {
return nil return nil
} }
func (c *collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if winversion.WindowsVersionFloat > 6.05 { if winversion.WindowsVersionFloat > 6.05 {
return c.CollectFull(ctx, ch) return c.CollectFull(ctx, ch)
} }
@ -209,7 +212,7 @@ type perflibProcessor struct {
PercentUserTime float64 `perflib:"% User Time"` PercentUserTime float64 `perflib:"% User Time"`
} }
func (c *collector) CollectBasic(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) CollectBasic(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
data := make([]perflibProcessor, 0) data := make([]perflibProcessor, 0)
err := perflib.UnmarshalObject(ctx.PerfObjects["Processor"], &data, c.logger) err := perflib.UnmarshalObject(ctx.PerfObjects["Processor"], &data, c.logger)
if err != nil { if err != nil {
@ -223,63 +226,63 @@ func (c *collector) CollectBasic(ctx *types.ScrapeContext, ch chan<- prometheus.
core := cpu.Name core := cpu.Name
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.CStateSecondsTotal, c.cStateSecondsTotal,
prometheus.CounterValue, prometheus.CounterValue,
cpu.PercentC1Time, cpu.PercentC1Time,
core, "c1", core, "c1",
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.CStateSecondsTotal, c.cStateSecondsTotal,
prometheus.CounterValue, prometheus.CounterValue,
cpu.PercentC2Time, cpu.PercentC2Time,
core, "c2", core, "c2",
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.CStateSecondsTotal, c.cStateSecondsTotal,
prometheus.CounterValue, prometheus.CounterValue,
cpu.PercentC3Time, cpu.PercentC3Time,
core, "c3", core, "c3",
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.TimeTotal, c.timeTotal,
prometheus.CounterValue, prometheus.CounterValue,
cpu.PercentIdleTime, cpu.PercentIdleTime,
core, "idle", core, "idle",
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.TimeTotal, c.timeTotal,
prometheus.CounterValue, prometheus.CounterValue,
cpu.PercentInterruptTime, cpu.PercentInterruptTime,
core, "interrupt", core, "interrupt",
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.TimeTotal, c.timeTotal,
prometheus.CounterValue, prometheus.CounterValue,
cpu.PercentDPCTime, cpu.PercentDPCTime,
core, "dpc", core, "dpc",
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.TimeTotal, c.timeTotal,
prometheus.CounterValue, prometheus.CounterValue,
cpu.PercentPrivilegedTime, cpu.PercentPrivilegedTime,
core, "privileged", core, "privileged",
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.TimeTotal, c.timeTotal,
prometheus.CounterValue, prometheus.CounterValue,
cpu.PercentUserTime, cpu.PercentUserTime,
core, "user", core, "user",
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.InterruptsTotal, c.interruptsTotal,
prometheus.CounterValue, prometheus.CounterValue,
cpu.Interrupts, cpu.Interrupts,
core, core,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.DPCsTotal, c.dpcsTotal,
prometheus.CounterValue, prometheus.CounterValue,
cpu.DPCsQueued, cpu.DPCsQueued,
core, core,
@ -318,7 +321,7 @@ type perflibProcessorInformation struct {
UserTimeSeconds float64 `perflib:"% User Time"` UserTimeSeconds float64 `perflib:"% User Time"`
} }
func (c *collector) CollectFull(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) CollectFull(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
data := make([]perflibProcessorInformation, 0) data := make([]perflibProcessorInformation, 0)
err := perflib.UnmarshalObject(ctx.PerfObjects["Processor Information"], &data, c.logger) err := perflib.UnmarshalObject(ctx.PerfObjects["Processor Information"], &data, c.logger)
if err != nil { if err != nil {
@ -332,119 +335,119 @@ func (c *collector) CollectFull(ctx *types.ScrapeContext, ch chan<- prometheus.M
core := cpu.Name core := cpu.Name
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.CStateSecondsTotal, c.cStateSecondsTotal,
prometheus.CounterValue, prometheus.CounterValue,
cpu.C1TimeSeconds, cpu.C1TimeSeconds,
core, "c1", core, "c1",
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.CStateSecondsTotal, c.cStateSecondsTotal,
prometheus.CounterValue, prometheus.CounterValue,
cpu.C2TimeSeconds, cpu.C2TimeSeconds,
core, "c2", core, "c2",
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.CStateSecondsTotal, c.cStateSecondsTotal,
prometheus.CounterValue, prometheus.CounterValue,
cpu.C3TimeSeconds, cpu.C3TimeSeconds,
core, "c3", core, "c3",
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.TimeTotal, c.timeTotal,
prometheus.CounterValue, prometheus.CounterValue,
cpu.IdleTimeSeconds, cpu.IdleTimeSeconds,
core, "idle", core, "idle",
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.TimeTotal, c.timeTotal,
prometheus.CounterValue, prometheus.CounterValue,
cpu.InterruptTimeSeconds, cpu.InterruptTimeSeconds,
core, "interrupt", core, "interrupt",
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.TimeTotal, c.timeTotal,
prometheus.CounterValue, prometheus.CounterValue,
cpu.DPCTimeSeconds, cpu.DPCTimeSeconds,
core, "dpc", core, "dpc",
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.TimeTotal, c.timeTotal,
prometheus.CounterValue, prometheus.CounterValue,
cpu.PrivilegedTimeSeconds, cpu.PrivilegedTimeSeconds,
core, "privileged", core, "privileged",
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.TimeTotal, c.timeTotal,
prometheus.CounterValue, prometheus.CounterValue,
cpu.UserTimeSeconds, cpu.UserTimeSeconds,
core, "user", core, "user",
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.InterruptsTotal, c.interruptsTotal,
prometheus.CounterValue, prometheus.CounterValue,
cpu.InterruptsTotal, cpu.InterruptsTotal,
core, core,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.DPCsTotal, c.dpcsTotal,
prometheus.CounterValue, prometheus.CounterValue,
cpu.DPCsQueuedTotal, cpu.DPCsQueuedTotal,
core, core,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.ClockInterruptsTotal, c.clockInterruptsTotal,
prometheus.CounterValue, prometheus.CounterValue,
cpu.ClockInterruptsTotal, cpu.ClockInterruptsTotal,
core, core,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.IdleBreakEventsTotal, c.idleBreakEventsTotal,
prometheus.CounterValue, prometheus.CounterValue,
cpu.IdleBreakEventsTotal, cpu.IdleBreakEventsTotal,
core, core,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.ParkingStatus, c.parkingStatus,
prometheus.GaugeValue, prometheus.GaugeValue,
cpu.ParkingStatus, cpu.ParkingStatus,
core, core,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.ProcessorFrequencyMHz, c.processorFrequencyMHz,
prometheus.GaugeValue, prometheus.GaugeValue,
cpu.ProcessorFrequencyMHz, cpu.ProcessorFrequencyMHz,
core, core,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.ProcessorPerformance, c.processorPerformance,
prometheus.CounterValue, prometheus.CounterValue,
cpu.ProcessorPerformance, cpu.ProcessorPerformance,
core, core,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.ProcessorMPerf, c.processorMPerf,
prometheus.CounterValue, prometheus.CounterValue,
cpu.ProcessorMPerf, cpu.ProcessorMPerf,
core, core,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.ProcessorRTC, c.processorRTC,
prometheus.CounterValue, prometheus.CounterValue,
cpu.ProcessorRTC, cpu.ProcessorRTC,
core, core,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.ProcessorUtility, c.processorUtility,
prometheus.CounterValue, prometheus.CounterValue,
cpu.ProcessorUtilityRate, cpu.ProcessorUtilityRate,
core, core,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.ProcessorPrivUtility, c.processorPrivilegedUtility,
prometheus.CounterValue, prometheus.CounterValue,
cpu.PrivilegedUtilitySeconds, cpu.PrivilegedUtilitySeconds,
core, core,

View File

@ -25,37 +25,42 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
// A collector is a Prometheus collector for a few WMI metrics in Win32_Processor // A Collector is a Prometheus Collector for a few WMI metrics in Win32_Processor
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
CpuInfo *prometheus.Desc cpuInfo *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{}, nil return []string{}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
c.CpuInfo = prometheus.NewDesc( return nil
}
func (c *Collector) Build() error {
c.cpuInfo = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, "", Name), prometheus.BuildFQName(types.Namespace, "", Name),
"Labelled CPU information as provided provided by Win32_Processor", "Labelled CPU information as provided provided by Win32_Processor",
[]string{ []string{
@ -85,7 +90,7 @@ type win32_Processor struct {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collect(ch); err != nil { if err := c.collect(ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting cpu_info metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting cpu_info metrics", "err", err)
return err return err
@ -93,7 +98,7 @@ func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric)
return nil return nil
} }
func (c *collector) collect(ch chan<- prometheus.Metric) error { func (c *Collector) collect(ch chan<- prometheus.Metric) error {
var dst []win32_Processor var dst []win32_Processor
// We use a static query here because the provided methods in wmi.go all issue a SELECT *; // We use a static query here because the provided methods in wmi.go all issue a SELECT *;
// This results in the time-consuming LoadPercentage field being read which seems to measure each CPU // This results in the time-consuming LoadPercentage field being read which seems to measure each CPU
@ -108,7 +113,7 @@ func (c *collector) collect(ch chan<- prometheus.Metric) error {
// Some CPUs end up exposing trailing spaces for certain strings, so clean them up // Some CPUs end up exposing trailing spaces for certain strings, so clean them up
for _, processor := range dst { for _, processor := range dst {
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.CpuInfo, c.cpuInfo,
prometheus.GaugeValue, prometheus.GaugeValue,
1.0, 1.0,
strconv.Itoa(int(processor.Architecture)), strconv.Itoa(int(processor.Architecture)),

View File

@ -0,0 +1,12 @@
package cpu_info_test
import (
"testing"
"github.com/prometheus-community/windows_exporter/pkg/collector/cpu_info"
"github.com/prometheus-community/windows_exporter/pkg/testutils"
)
func BenchmarkCollector(b *testing.B) {
testutils.FuncBenchmarkCollector(b, cpu_info.Name, cpu_info.NewWithFlags)
}

View File

@ -17,38 +17,43 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
// A collector is a Prometheus collector for WMI metrics // A Collector is a Prometheus Collector for WMI metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
PhysicalMemoryBytes *prometheus.Desc PhysicalMemoryBytes *prometheus.Desc
LogicalProcessors *prometheus.Desc LogicalProcessors *prometheus.Desc
Hostname *prometheus.Desc hostname *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{}, nil return []string{}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.LogicalProcessors = prometheus.NewDesc( c.LogicalProcessors = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "logical_processors"), prometheus.BuildFQName(types.Namespace, Name, "logical_processors"),
"ComputerSystem.NumberOfLogicalProcessors", "ComputerSystem.NumberOfLogicalProcessors",
@ -61,7 +66,7 @@ func (c *collector) Build() error {
nil, nil,
nil, nil,
) )
c.Hostname = prometheus.NewDesc( c.hostname = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "hostname"), prometheus.BuildFQName(types.Namespace, Name, "hostname"),
"Labelled system hostname information as provided by ComputerSystem.DNSHostName and ComputerSystem.Domain", "Labelled system hostname information as provided by ComputerSystem.DNSHostName and ComputerSystem.Domain",
[]string{ []string{
@ -76,7 +81,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collect(ch); err != nil { if err := c.collect(ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting cs metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting cs metrics", "err", err)
return err return err
@ -84,7 +89,7 @@ func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric)
return nil return nil
} }
func (c *collector) collect(ch chan<- prometheus.Metric) error { func (c *Collector) collect(ch chan<- prometheus.Metric) error {
// Get systeminfo for number of processors // Get systeminfo for number of processors
systemInfo := sysinfoapi.GetSystemInfo() systemInfo := sysinfoapi.GetSystemInfo()
@ -120,7 +125,7 @@ func (c *collector) collect(ch chan<- prometheus.Metric) error {
} }
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.Hostname, c.hostname,
prometheus.GaugeValue, prometheus.GaugeValue,
1.0, 1.0,
hostname, hostname,

View File

@ -12,79 +12,76 @@ import (
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
const ( const Name = "dfsr"
Name = "dfsr"
FlagDfsrEnabledCollectors = "collectors.dfsr.sources-enabled"
)
type Config struct { type Config struct {
DfsrEnabledCollectors string `yaml:"enabled_collectors"` EnabledCollectors string `yaml:"enabled_collectors"`
} }
var ConfigDefaults = Config{ var ConfigDefaults = Config{
DfsrEnabledCollectors: "connection,folder,volume", EnabledCollectors: "connection,folder,volume",
} }
// collector contains the metric and state data of the DFSR collectors. // Collector contains the metric and state data of the DFSR collectors.
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
dfsrEnabledCollectors *string dfsrEnabledCollectors *string
// Connection source // connection source
ConnectionBandwidthSavingsUsingDFSReplicationTotal *prometheus.Desc connectionBandwidthSavingsUsingDFSReplicationTotal *prometheus.Desc
ConnectionBytesReceivedTotal *prometheus.Desc connectionBytesReceivedTotal *prometheus.Desc
ConnectionCompressedSizeOfFilesReceivedTotal *prometheus.Desc connectionCompressedSizeOfFilesReceivedTotal *prometheus.Desc
ConnectionFilesReceivedTotal *prometheus.Desc connectionFilesReceivedTotal *prometheus.Desc
ConnectionRDCBytesReceivedTotal *prometheus.Desc connectionRDCBytesReceivedTotal *prometheus.Desc
ConnectionRDCCompressedSizeOfFilesReceivedTotal *prometheus.Desc connectionRDCCompressedSizeOfFilesReceivedTotal *prometheus.Desc
ConnectionRDCSizeOfFilesReceivedTotal *prometheus.Desc connectionRDCSizeOfFilesReceivedTotal *prometheus.Desc
ConnectionRDCNumberofFilesReceivedTotal *prometheus.Desc connectionRDCNumberofFilesReceivedTotal *prometheus.Desc
ConnectionSizeOfFilesReceivedTotal *prometheus.Desc connectionSizeOfFilesReceivedTotal *prometheus.Desc
// Folder source // folder source
FolderBandwidthSavingsUsingDFSReplicationTotal *prometheus.Desc folderBandwidthSavingsUsingDFSReplicationTotal *prometheus.Desc
FolderCompressedSizeOfFilesReceivedTotal *prometheus.Desc folderCompressedSizeOfFilesReceivedTotal *prometheus.Desc
FolderConflictBytesCleanedupTotal *prometheus.Desc folderConflictBytesCleanedupTotal *prometheus.Desc
FolderConflictBytesGeneratedTotal *prometheus.Desc folderConflictBytesGeneratedTotal *prometheus.Desc
FolderConflictFilesCleanedUpTotal *prometheus.Desc folderConflictFilesCleanedUpTotal *prometheus.Desc
FolderConflictFilesGeneratedTotal *prometheus.Desc folderConflictFilesGeneratedTotal *prometheus.Desc
FolderConflictFolderCleanupsCompletedTotal *prometheus.Desc folderConflictfolderCleanupsCompletedTotal *prometheus.Desc
FolderConflictSpaceInUse *prometheus.Desc folderConflictSpaceInUse *prometheus.Desc
FolderDeletedSpaceInUse *prometheus.Desc folderDeletedSpaceInUse *prometheus.Desc
FolderDeletedBytesCleanedUpTotal *prometheus.Desc folderDeletedBytesCleanedUpTotal *prometheus.Desc
FolderDeletedBytesGeneratedTotal *prometheus.Desc folderDeletedBytesGeneratedTotal *prometheus.Desc
FolderDeletedFilesCleanedUpTotal *prometheus.Desc folderDeletedFilesCleanedUpTotal *prometheus.Desc
FolderDeletedFilesGeneratedTotal *prometheus.Desc folderDeletedFilesGeneratedTotal *prometheus.Desc
FolderFileInstallsRetriedTotal *prometheus.Desc folderFileInstallsRetriedTotal *prometheus.Desc
FolderFileInstallsSucceededTotal *prometheus.Desc folderFileInstallsSucceededTotal *prometheus.Desc
FolderFilesReceivedTotal *prometheus.Desc folderFilesReceivedTotal *prometheus.Desc
FolderRDCBytesReceivedTotal *prometheus.Desc folderRDCBytesReceivedTotal *prometheus.Desc
FolderRDCCompressedSizeOfFilesReceivedTotal *prometheus.Desc folderRDCCompressedSizeOfFilesReceivedTotal *prometheus.Desc
FolderRDCNumberofFilesReceivedTotal *prometheus.Desc folderRDCNumberofFilesReceivedTotal *prometheus.Desc
FolderRDCSizeOfFilesReceivedTotal *prometheus.Desc folderRDCSizeOfFilesReceivedTotal *prometheus.Desc
FolderSizeOfFilesReceivedTotal *prometheus.Desc folderSizeOfFilesReceivedTotal *prometheus.Desc
FolderStagingSpaceInUse *prometheus.Desc folderStagingSpaceInUse *prometheus.Desc
FolderStagingBytesCleanedUpTotal *prometheus.Desc folderStagingBytesCleanedUpTotal *prometheus.Desc
FolderStagingBytesGeneratedTotal *prometheus.Desc folderStagingBytesGeneratedTotal *prometheus.Desc
FolderStagingFilesCleanedUpTotal *prometheus.Desc folderStagingFilesCleanedUpTotal *prometheus.Desc
FolderStagingFilesGeneratedTotal *prometheus.Desc folderStagingFilesGeneratedTotal *prometheus.Desc
FolderUpdatesDroppedTotal *prometheus.Desc folderUpdatesDroppedTotal *prometheus.Desc
// Volume source // volume source
VolumeDatabaseLookupsTotal *prometheus.Desc volumeDatabaseLookupsTotal *prometheus.Desc
VolumeDatabaseCommitsTotal *prometheus.Desc volumeDatabaseCommitsTotal *prometheus.Desc
VolumeUSNJournalUnreadPercentage *prometheus.Desc volumeUSNJournalUnreadPercentage *prometheus.Desc
VolumeUSNJournalRecordsAcceptedTotal *prometheus.Desc volumeUSNJournalRecordsAcceptedTotal *prometheus.Desc
VolumeUSNJournalRecordsReadTotal *prometheus.Desc volumeUSNJournalRecordsReadTotal *prometheus.Desc
// Map of child collector functions used during collection // Map of child Collector functions used during collection
dfsrChildCollectors []dfsrCollectorFunc dfsrChildCollectors []dfsrCollectorFunc
} }
type dfsrCollectorFunc func(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error type dfsrCollectorFunc func(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error
// Map Perflib sources to DFSR collector names // Map Perflib sources to DFSR Collector names
// e.g, volume -> DFS Replication Service Volumes // e.g, volume -> DFS Replication Service Volumes
func dfsrGetPerfObjectName(collector string) string { func dfsrGetPerfObjectName(collector string) string {
prefix := "DFS " prefix := "DFS "
@ -100,35 +97,37 @@ func dfsrGetPerfObjectName(collector string) string {
return prefix + suffix return prefix + suffix
} }
func New(logger log.Logger, config *Config) types.Collector { func New(logger log.Logger, config *Config) *Collector {
if config == nil { if config == nil {
config = &ConfigDefaults config = &ConfigDefaults
} }
c := &collector{ c := &Collector{
dfsrEnabledCollectors: &config.DfsrEnabledCollectors, dfsrEnabledCollectors: &config.EnabledCollectors,
} }
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(app *kingpin.Application) types.Collector { func NewWithFlags(app *kingpin.Application) *Collector {
return &collector{ return &Collector{
dfsrEnabledCollectors: app. dfsrEnabledCollectors: app.
Flag(FlagDfsrEnabledCollectors, "Comma-seperated list of DFSR Perflib sources to use.").Default("connection,folder,volume"). Flag("collectors.dfsr.sources-enabled", "Comma-seperated list of DFSR Perflib sources to use.").
Default(ConfigDefaults.DfsrEnabledCollectors).String(), Default(ConfigDefaults.EnabledCollectors).
String(),
} }
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
// Perflib sources are dynamic, depending on the enabled child collectors // Perflib sources are dynamic, depending on the enabled child collectors
expandedChildCollectors := utils.ExpandEnabledChildCollectors(*c.dfsrEnabledCollectors) expandedChildCollectors := utils.ExpandEnabledChildCollectors(*c.dfsrEnabledCollectors)
perflibDependencies := make([]string, 0, len(expandedChildCollectors)) perflibDependencies := make([]string, 0, len(expandedChildCollectors))
@ -139,295 +138,299 @@ func (c *collector) GetPerfCounter() ([]string, error) {
return perflibDependencies, nil return perflibDependencies, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
_ = level.Info(c.logger).Log("msg", "dfsr collector is in an experimental state! Metrics for this collector have not been tested.") _ = level.Info(c.logger).Log("msg", "dfsr collector is in an experimental state! Metrics for this collector have not been tested.")
// Connection // connection
c.ConnectionBandwidthSavingsUsingDFSReplicationTotal = prometheus.NewDesc( c.connectionBandwidthSavingsUsingDFSReplicationTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "connection_bandwidth_savings_using_dfs_replication_bytes_total"), prometheus.BuildFQName(types.Namespace, Name, "connection_bandwidth_savings_using_dfs_replication_bytes_total"),
"Total bytes of bandwidth saved using DFS Replication for this connection", "Total bytes of bandwidth saved using DFS Replication for this connection",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.ConnectionBytesReceivedTotal = prometheus.NewDesc( c.connectionBytesReceivedTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "connection_bytes_received_total"), prometheus.BuildFQName(types.Namespace, Name, "connection_bytes_received_total"),
"Total bytes received for connection", "Total bytes received for connection",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.ConnectionCompressedSizeOfFilesReceivedTotal = prometheus.NewDesc( c.connectionCompressedSizeOfFilesReceivedTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "connection_compressed_size_of_files_received_bytes_total"), prometheus.BuildFQName(types.Namespace, Name, "connection_compressed_size_of_files_received_bytes_total"),
"Total compressed size of files received on the connection, in bytes", "Total compressed size of files received on the connection, in bytes",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.ConnectionFilesReceivedTotal = prometheus.NewDesc( c.connectionFilesReceivedTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "connection_received_files_total"), prometheus.BuildFQName(types.Namespace, Name, "connection_received_files_total"),
"Total number of files received for connection", "Total number of files received for connection",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.ConnectionRDCBytesReceivedTotal = prometheus.NewDesc( c.connectionRDCBytesReceivedTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "connection_rdc_received_bytes_total"), prometheus.BuildFQName(types.Namespace, Name, "connection_rdc_received_bytes_total"),
"Total bytes received on the connection while replicating files using Remote Differential Compression", "Total bytes received on the connection while replicating files using Remote Differential Compression",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.ConnectionRDCCompressedSizeOfFilesReceivedTotal = prometheus.NewDesc( c.connectionRDCCompressedSizeOfFilesReceivedTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "connection_rdc_compressed_size_of_received_files_bytes_total"), prometheus.BuildFQName(types.Namespace, Name, "connection_rdc_compressed_size_of_received_files_bytes_total"),
"Total uncompressed size of files received with Remote Differential Compression for connection", "Total uncompressed size of files received with Remote Differential Compression for connection",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.ConnectionRDCNumberofFilesReceivedTotal = prometheus.NewDesc( c.connectionRDCNumberofFilesReceivedTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "connection_rdc_received_files_total"), prometheus.BuildFQName(types.Namespace, Name, "connection_rdc_received_files_total"),
"Total number of files received using remote differential compression", "Total number of files received using remote differential compression",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.ConnectionRDCSizeOfFilesReceivedTotal = prometheus.NewDesc( c.connectionRDCSizeOfFilesReceivedTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "connection_rdc_size_of_received_files_bytes_total"), prometheus.BuildFQName(types.Namespace, Name, "connection_rdc_size_of_received_files_bytes_total"),
"Total size of received Remote Differential Compression files, in bytes.", "Total size of received Remote Differential Compression files, in bytes.",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.ConnectionSizeOfFilesReceivedTotal = prometheus.NewDesc( c.connectionSizeOfFilesReceivedTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "connection_files_received_bytes_total"), prometheus.BuildFQName(types.Namespace, Name, "connection_files_received_bytes_total"),
"Total size of files received, in bytes", "Total size of files received, in bytes",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c. // Folder c. // folder
FolderBandwidthSavingsUsingDFSReplicationTotal = prometheus.NewDesc( folderBandwidthSavingsUsingDFSReplicationTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "folder_bandwidth_savings_using_dfs_replication_bytes_total"), prometheus.BuildFQName(types.Namespace, Name, "folder_bandwidth_savings_using_dfs_replication_bytes_total"),
"Total bytes of bandwidth saved using DFS Replication for this folder", "Total bytes of bandwidth saved using DFS Replication for this folder",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.FolderCompressedSizeOfFilesReceivedTotal = prometheus.NewDesc( c.folderCompressedSizeOfFilesReceivedTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "folder_compressed_size_of_received_files_bytes_total"), prometheus.BuildFQName(types.Namespace, Name, "folder_compressed_size_of_received_files_bytes_total"),
"Total compressed size of files received on the folder, in bytes", "Total compressed size of files received on the folder, in bytes",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.FolderConflictBytesCleanedupTotal = prometheus.NewDesc( c.folderConflictBytesCleanedupTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "folder_conflict_cleaned_up_bytes_total"), prometheus.BuildFQName(types.Namespace, Name, "folder_conflict_cleaned_up_bytes_total"),
"Total size of conflict loser files and folders deleted from the Conflict and Deleted folder, in bytes", "Total size of conflict loser files and folders deleted from the Conflict and Deleted folder, in bytes",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.FolderConflictBytesGeneratedTotal = prometheus.NewDesc( c.folderConflictBytesGeneratedTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "folder_conflict_generated_bytes_total"), prometheus.BuildFQName(types.Namespace, Name, "folder_conflict_generated_bytes_total"),
"Total size of conflict loser files and folders moved to the Conflict and Deleted folder, in bytes", "Total size of conflict loser files and folders moved to the Conflict and Deleted folder, in bytes",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.FolderConflictFilesCleanedUpTotal = prometheus.NewDesc( c.folderConflictFilesCleanedUpTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "folder_conflict_cleaned_up_files_total"), prometheus.BuildFQName(types.Namespace, Name, "folder_conflict_cleaned_up_files_total"),
"Number of conflict loser files deleted from the Conflict and Deleted folder", "Number of conflict loser files deleted from the Conflict and Deleted folder",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.FolderConflictFilesGeneratedTotal = prometheus.NewDesc( c.folderConflictFilesGeneratedTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "folder_conflict_generated_files_total"), prometheus.BuildFQName(types.Namespace, Name, "folder_conflict_generated_files_total"),
"Number of files and folders moved to the Conflict and Deleted folder", "Number of files and folders moved to the Conflict and Deleted folder",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.FolderConflictFolderCleanupsCompletedTotal = prometheus.NewDesc( c.folderConflictfolderCleanupsCompletedTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "folder_conflict_folder_cleanups_total"), prometheus.BuildFQName(types.Namespace, Name, "folder_conflict_folder_cleanups_total"),
"Number of deletions of conflict loser files and folders in the Conflict and Deleted", "Number of deletions of conflict loser files and folders in the Conflict and Deleted",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.FolderConflictSpaceInUse = prometheus.NewDesc( c.folderConflictSpaceInUse = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "folder_conflict_space_in_use_bytes"), prometheus.BuildFQName(types.Namespace, Name, "folder_conflict_space_in_use_bytes"),
"Total size of the conflict loser files and folders currently in the Conflict and Deleted folder", "Total size of the conflict loser files and folders currently in the Conflict and Deleted folder",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.FolderDeletedSpaceInUse = prometheus.NewDesc( c.folderDeletedSpaceInUse = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "folder_deleted_space_in_use_bytes"), prometheus.BuildFQName(types.Namespace, Name, "folder_deleted_space_in_use_bytes"),
"Total size (in bytes) of the deleted files and folders currently in the Conflict and Deleted folder", "Total size (in bytes) of the deleted files and folders currently in the Conflict and Deleted folder",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.FolderDeletedBytesCleanedUpTotal = prometheus.NewDesc( c.folderDeletedBytesCleanedUpTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "folder_deleted_cleaned_up_bytes_total"), prometheus.BuildFQName(types.Namespace, Name, "folder_deleted_cleaned_up_bytes_total"),
"Total size (in bytes) of replicating deleted files and folders that were cleaned up from the Conflict and Deleted folder", "Total size (in bytes) of replicating deleted files and folders that were cleaned up from the Conflict and Deleted folder",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.FolderDeletedBytesGeneratedTotal = prometheus.NewDesc( c.folderDeletedBytesGeneratedTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "folder_deleted_generated_bytes_total"), prometheus.BuildFQName(types.Namespace, Name, "folder_deleted_generated_bytes_total"),
"Total size (in bytes) of replicated deleted files and folders that were moved to the Conflict and Deleted folder after they were deleted from a replicated folder on a sending member", "Total size (in bytes) of replicated deleted files and folders that were moved to the Conflict and Deleted folder after they were deleted from a replicated folder on a sending member",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.FolderDeletedFilesCleanedUpTotal = prometheus.NewDesc( c.folderDeletedFilesCleanedUpTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "folder_deleted_cleaned_up_files_total"), prometheus.BuildFQName(types.Namespace, Name, "folder_deleted_cleaned_up_files_total"),
"Number of files and folders that were cleaned up from the Conflict and Deleted folder", "Number of files and folders that were cleaned up from the Conflict and Deleted folder",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.FolderDeletedFilesGeneratedTotal = prometheus.NewDesc( c.folderDeletedFilesGeneratedTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "folder_deleted_generated_files_total"), prometheus.BuildFQName(types.Namespace, Name, "folder_deleted_generated_files_total"),
"Number of deleted files and folders that were moved to the Conflict and Deleted folder", "Number of deleted files and folders that were moved to the Conflict and Deleted folder",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.FolderFileInstallsRetriedTotal = prometheus.NewDesc( c.folderFileInstallsRetriedTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "folder_file_installs_retried_total"), prometheus.BuildFQName(types.Namespace, Name, "folder_file_installs_retried_total"),
"Total number of file installs that are being retried due to sharing violations or other errors encountered when installing the files", "Total number of file installs that are being retried due to sharing violations or other errors encountered when installing the files",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.FolderFileInstallsSucceededTotal = prometheus.NewDesc( c.folderFileInstallsSucceededTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "folder_file_installs_succeeded_total"), prometheus.BuildFQName(types.Namespace, Name, "folder_file_installs_succeeded_total"),
"Total number of files that were successfully received from sending members and installed locally on this server", "Total number of files that were successfully received from sending members and installed locally on this server",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.FolderFilesReceivedTotal = prometheus.NewDesc( c.folderFilesReceivedTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "folder_received_files_total"), prometheus.BuildFQName(types.Namespace, Name, "folder_received_files_total"),
"Total number of files received", "Total number of files received",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.FolderRDCBytesReceivedTotal = prometheus.NewDesc( c.folderRDCBytesReceivedTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "folder_rdc_received_bytes_total"), prometheus.BuildFQName(types.Namespace, Name, "folder_rdc_received_bytes_total"),
"Total number of bytes received in replicating files using Remote Differential Compression", "Total number of bytes received in replicating files using Remote Differential Compression",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.FolderRDCCompressedSizeOfFilesReceivedTotal = prometheus.NewDesc( c.folderRDCCompressedSizeOfFilesReceivedTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "folder_rdc_compressed_size_of_received_files_bytes_total"), prometheus.BuildFQName(types.Namespace, Name, "folder_rdc_compressed_size_of_received_files_bytes_total"),
"Total compressed size (in bytes) of the files received with Remote Differential Compression", "Total compressed size (in bytes) of the files received with Remote Differential Compression",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.FolderRDCNumberofFilesReceivedTotal = prometheus.NewDesc( c.folderRDCNumberofFilesReceivedTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "folder_rdc_received_files_total"), prometheus.BuildFQName(types.Namespace, Name, "folder_rdc_received_files_total"),
"Total number of files received with Remote Differential Compression", "Total number of files received with Remote Differential Compression",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.FolderRDCSizeOfFilesReceivedTotal = prometheus.NewDesc( c.folderRDCSizeOfFilesReceivedTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "folder_rdc_files_received_bytes_total"), prometheus.BuildFQName(types.Namespace, Name, "folder_rdc_files_received_bytes_total"),
"Total uncompressed size (in bytes) of the files received with Remote Differential Compression", "Total uncompressed size (in bytes) of the files received with Remote Differential Compression",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.FolderSizeOfFilesReceivedTotal = prometheus.NewDesc( c.folderSizeOfFilesReceivedTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "folder_files_received_bytes_total"), prometheus.BuildFQName(types.Namespace, Name, "folder_files_received_bytes_total"),
"Total uncompressed size (in bytes) of the files received", "Total uncompressed size (in bytes) of the files received",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.FolderStagingSpaceInUse = prometheus.NewDesc( c.folderStagingSpaceInUse = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "folder_staging_space_in_use_bytes"), prometheus.BuildFQName(types.Namespace, Name, "folder_staging_space_in_use_bytes"),
"Total size of files and folders currently in the staging folder.", "Total size of files and folders currently in the staging folder.",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.FolderStagingBytesCleanedUpTotal = prometheus.NewDesc( c.folderStagingBytesCleanedUpTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "folder_staging_cleaned_up_bytes_total"), prometheus.BuildFQName(types.Namespace, Name, "folder_staging_cleaned_up_bytes_total"),
"Total size (in bytes) of the files and folders that have been cleaned up from the staging folder", "Total size (in bytes) of the files and folders that have been cleaned up from the staging folder",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.FolderStagingBytesGeneratedTotal = prometheus.NewDesc( c.folderStagingBytesGeneratedTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "folder_staging_generated_bytes_total"), prometheus.BuildFQName(types.Namespace, Name, "folder_staging_generated_bytes_total"),
"Total size (in bytes) of replicated files and folders in the staging folder created by the DFS Replication service since last restart", "Total size (in bytes) of replicated files and folders in the staging folder created by the DFS Replication service since last restart",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.FolderStagingFilesCleanedUpTotal = prometheus.NewDesc( c.folderStagingFilesCleanedUpTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "folder_staging_cleaned_up_files_total"), prometheus.BuildFQName(types.Namespace, Name, "folder_staging_cleaned_up_files_total"),
"Total number of files and folders that have been cleaned up from the staging folder", "Total number of files and folders that have been cleaned up from the staging folder",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.FolderStagingFilesGeneratedTotal = prometheus.NewDesc( c.folderStagingFilesGeneratedTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "folder_staging_generated_files_total"), prometheus.BuildFQName(types.Namespace, Name, "folder_staging_generated_files_total"),
"Total number of times replicated files and folders have been staged by the DFS Replication service", "Total number of times replicated files and folders have been staged by the DFS Replication service",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.FolderUpdatesDroppedTotal = prometheus.NewDesc( c.folderUpdatesDroppedTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "folder_dropped_updates_total"), prometheus.BuildFQName(types.Namespace, Name, "folder_dropped_updates_total"),
"Total number of redundant file replication update records that have been ignored by the DFS Replication service because they did not change the replicated file or folder", "Total number of redundant file replication update records that have been ignored by the DFS Replication service because they did not change the replicated file or folder",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c. // Volume // volume
VolumeDatabaseCommitsTotal = prometheus.NewDesc( c.volumeDatabaseCommitsTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "volume_database_commits_total"), prometheus.BuildFQName(types.Namespace, Name, "volume_database_commits_total"),
"Total number of DFSR Volume database commits", "Total number of DFSR volume database commits",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.VolumeDatabaseLookupsTotal = prometheus.NewDesc( c.volumeDatabaseLookupsTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "volume_database_lookups_total"), prometheus.BuildFQName(types.Namespace, Name, "volume_database_lookups_total"),
"Total number of DFSR Volume database lookups", "Total number of DFSR volume database lookups",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.VolumeUSNJournalUnreadPercentage = prometheus.NewDesc( c.volumeUSNJournalUnreadPercentage = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "volume_usn_journal_unread_percentage"), prometheus.BuildFQName(types.Namespace, Name, "volume_usn_journal_unread_percentage"),
"Percentage of DFSR Volume USN journal records that are unread", "Percentage of DFSR volume USN journal records that are unread",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.VolumeUSNJournalRecordsAcceptedTotal = prometheus.NewDesc( c.volumeUSNJournalRecordsAcceptedTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "volume_usn_journal_accepted_records_total"), prometheus.BuildFQName(types.Namespace, Name, "volume_usn_journal_accepted_records_total"),
"Total number of USN journal records accepted", "Total number of USN journal records accepted",
[]string{"name"}, []string{"name"},
nil, nil,
) )
c.VolumeUSNJournalRecordsReadTotal = prometheus.NewDesc( c.volumeUSNJournalRecordsReadTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "volume_usn_journal_read_records_total"), prometheus.BuildFQName(types.Namespace, Name, "volume_usn_journal_read_records_total"),
"Total number of DFSR Volume USN journal records read", "Total number of DFSR volume USN journal records read",
[]string{"name"}, []string{"name"},
nil, nil,
) )
@ -438,8 +441,8 @@ func (c *collector) Build() error {
} }
// Maps enabled child collectors names to their relevant collection function, // Maps enabled child collectors names to their relevant collection function,
// for use in collector.Collect() // for use in Collector.Collect()
func (c *collector) getDFSRChildCollectors(enabledCollectors []string) []dfsrCollectorFunc { func (c *Collector) getDFSRChildCollectors(enabledCollectors []string) []dfsrCollectorFunc {
var dfsrCollectors []dfsrCollectorFunc var dfsrCollectors []dfsrCollectorFunc
for _, collector := range enabledCollectors { for _, collector := range enabledCollectors {
switch collector { switch collector {
@ -457,7 +460,7 @@ func (c *collector) getDFSRChildCollectors(enabledCollectors []string) []dfsrCol
// Collect implements the Collector interface. // Collect implements the Collector interface.
// Sends metric values for each metric to the provided prometheus Metric channel. // Sends metric values for each metric to the provided prometheus Metric channel.
func (c *collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
for _, fn := range c.dfsrChildCollectors { for _, fn := range c.dfsrChildCollectors {
err := fn(ctx, ch) err := fn(ctx, ch)
if err != nil { if err != nil {
@ -482,7 +485,7 @@ type PerflibDFSRConnection struct {
SizeOfFilesReceivedTotal float64 `perflib:"Size of Files Received"` SizeOfFilesReceivedTotal float64 `perflib:"Size of Files Received"`
} }
func (c *collector) collectConnection(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collectConnection(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var dst []PerflibDFSRConnection var dst []PerflibDFSRConnection
if err := perflib.UnmarshalObject(ctx.PerfObjects["DFS Replication Connections"], &dst, c.logger); err != nil { if err := perflib.UnmarshalObject(ctx.PerfObjects["DFS Replication Connections"], &dst, c.logger); err != nil {
return err return err
@ -490,74 +493,73 @@ func (c *collector) collectConnection(ctx *types.ScrapeContext, ch chan<- promet
for _, connection := range dst { for _, connection := range dst {
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.ConnectionBandwidthSavingsUsingDFSReplicationTotal, c.connectionBandwidthSavingsUsingDFSReplicationTotal,
prometheus.CounterValue, prometheus.CounterValue,
connection.BandwidthSavingsUsingDFSReplicationTotal, connection.BandwidthSavingsUsingDFSReplicationTotal,
connection.Name, connection.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.ConnectionBytesReceivedTotal, c.connectionBytesReceivedTotal,
prometheus.CounterValue, prometheus.CounterValue,
connection.BytesReceivedTotal, connection.BytesReceivedTotal,
connection.Name, connection.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.ConnectionCompressedSizeOfFilesReceivedTotal, c.connectionCompressedSizeOfFilesReceivedTotal,
prometheus.CounterValue, prometheus.CounterValue,
connection.CompressedSizeOfFilesReceivedTotal, connection.CompressedSizeOfFilesReceivedTotal,
connection.Name, connection.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.ConnectionFilesReceivedTotal, c.connectionFilesReceivedTotal,
prometheus.CounterValue, prometheus.CounterValue,
connection.FilesReceivedTotal, connection.FilesReceivedTotal,
connection.Name, connection.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.ConnectionRDCBytesReceivedTotal, c.connectionRDCBytesReceivedTotal,
prometheus.CounterValue, prometheus.CounterValue,
connection.RDCBytesReceivedTotal, connection.RDCBytesReceivedTotal,
connection.Name, connection.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.ConnectionRDCCompressedSizeOfFilesReceivedTotal, c.connectionRDCCompressedSizeOfFilesReceivedTotal,
prometheus.CounterValue, prometheus.CounterValue,
connection.RDCCompressedSizeOfFilesReceivedTotal, connection.RDCCompressedSizeOfFilesReceivedTotal,
connection.Name, connection.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.ConnectionRDCSizeOfFilesReceivedTotal, c.connectionRDCSizeOfFilesReceivedTotal,
prometheus.CounterValue, prometheus.CounterValue,
connection.RDCSizeOfFilesReceivedTotal, connection.RDCSizeOfFilesReceivedTotal,
connection.Name, connection.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.ConnectionRDCNumberofFilesReceivedTotal, c.connectionRDCNumberofFilesReceivedTotal,
prometheus.CounterValue, prometheus.CounterValue,
connection.RDCNumberofFilesReceivedTotal, connection.RDCNumberofFilesReceivedTotal,
connection.Name, connection.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.ConnectionSizeOfFilesReceivedTotal, c.connectionSizeOfFilesReceivedTotal,
prometheus.CounterValue, prometheus.CounterValue,
connection.SizeOfFilesReceivedTotal, connection.SizeOfFilesReceivedTotal,
connection.Name, connection.Name,
) )
} }
return nil return nil
} }
// PerflibDFSRFolder Perflib: "DFS Replicated Folder" // perflibDFSRFolder Perflib: "DFS Replicated Folder"
type PerflibDFSRFolder struct { type perflibDFSRFolder struct {
Name string Name string
BandwidthSavingsUsingDFSReplicationTotal float64 `perflib:"Bandwidth Savings Using DFS Replication"` BandwidthSavingsUsingDFSReplicationTotal float64 `perflib:"Bandwidth Savings Using DFS Replication"`
@ -566,7 +568,7 @@ type PerflibDFSRFolder struct {
ConflictBytesGeneratedTotal float64 `perflib:"Conflict Bytes Generated"` ConflictBytesGeneratedTotal float64 `perflib:"Conflict Bytes Generated"`
ConflictFilesCleanedUpTotal float64 `perflib:"Conflict Files Cleaned Up"` ConflictFilesCleanedUpTotal float64 `perflib:"Conflict Files Cleaned Up"`
ConflictFilesGeneratedTotal float64 `perflib:"Conflict Files Generated"` ConflictFilesGeneratedTotal float64 `perflib:"Conflict Files Generated"`
ConflictFolderCleanupsCompletedTotal float64 `perflib:"Conflict Folder Cleanups Completed"` ConflictFolderCleanupsCompletedTotal float64 `perflib:"Conflict folder Cleanups Completed"`
ConflictSpaceInUse float64 `perflib:"Conflict Space In Use"` ConflictSpaceInUse float64 `perflib:"Conflict Space In Use"`
DeletedSpaceInUse float64 `perflib:"Deleted Space In Use"` DeletedSpaceInUse float64 `perflib:"Deleted Space In Use"`
DeletedBytesCleanedUpTotal float64 `perflib:"Deleted Bytes Cleaned Up"` DeletedBytesCleanedUpTotal float64 `perflib:"Deleted Bytes Cleaned Up"`
@ -589,197 +591,197 @@ type PerflibDFSRFolder struct {
UpdatesDroppedTotal float64 `perflib:"Updates Dropped"` UpdatesDroppedTotal float64 `perflib:"Updates Dropped"`
} }
func (c *collector) collectFolder(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collectFolder(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var dst []PerflibDFSRFolder var dst []perflibDFSRFolder
if err := perflib.UnmarshalObject(ctx.PerfObjects["DFS Replicated Folders"], &dst, c.logger); err != nil { if err := perflib.UnmarshalObject(ctx.PerfObjects["DFS Replicated Folders"], &dst, c.logger); err != nil {
return err return err
} }
for _, folder := range dst { for _, folder := range dst {
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.FolderBandwidthSavingsUsingDFSReplicationTotal, c.folderBandwidthSavingsUsingDFSReplicationTotal,
prometheus.CounterValue, prometheus.CounterValue,
folder.BandwidthSavingsUsingDFSReplicationTotal, folder.BandwidthSavingsUsingDFSReplicationTotal,
folder.Name, folder.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.FolderCompressedSizeOfFilesReceivedTotal, c.folderCompressedSizeOfFilesReceivedTotal,
prometheus.CounterValue, prometheus.CounterValue,
folder.CompressedSizeOfFilesReceivedTotal, folder.CompressedSizeOfFilesReceivedTotal,
folder.Name, folder.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.FolderConflictBytesCleanedupTotal, c.folderConflictBytesCleanedupTotal,
prometheus.CounterValue, prometheus.CounterValue,
folder.ConflictBytesCleanedupTotal, folder.ConflictBytesCleanedupTotal,
folder.Name, folder.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.FolderConflictBytesGeneratedTotal, c.folderConflictBytesGeneratedTotal,
prometheus.CounterValue, prometheus.CounterValue,
folder.ConflictBytesGeneratedTotal, folder.ConflictBytesGeneratedTotal,
folder.Name, folder.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.FolderConflictFilesCleanedUpTotal, c.folderConflictFilesCleanedUpTotal,
prometheus.CounterValue, prometheus.CounterValue,
folder.ConflictFilesCleanedUpTotal, folder.ConflictFilesCleanedUpTotal,
folder.Name, folder.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.FolderConflictFilesGeneratedTotal, c.folderConflictFilesGeneratedTotal,
prometheus.CounterValue, prometheus.CounterValue,
folder.ConflictFilesGeneratedTotal, folder.ConflictFilesGeneratedTotal,
folder.Name, folder.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.FolderConflictFolderCleanupsCompletedTotal, c.folderConflictfolderCleanupsCompletedTotal,
prometheus.CounterValue, prometheus.CounterValue,
folder.ConflictFolderCleanupsCompletedTotal, folder.ConflictFolderCleanupsCompletedTotal,
folder.Name, folder.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.FolderConflictSpaceInUse, c.folderConflictSpaceInUse,
prometheus.GaugeValue, prometheus.GaugeValue,
folder.ConflictSpaceInUse, folder.ConflictSpaceInUse,
folder.Name, folder.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.FolderDeletedSpaceInUse, c.folderDeletedSpaceInUse,
prometheus.GaugeValue, prometheus.GaugeValue,
folder.DeletedSpaceInUse, folder.DeletedSpaceInUse,
folder.Name, folder.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.FolderDeletedBytesCleanedUpTotal, c.folderDeletedBytesCleanedUpTotal,
prometheus.CounterValue, prometheus.CounterValue,
folder.DeletedBytesCleanedUpTotal, folder.DeletedBytesCleanedUpTotal,
folder.Name, folder.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.FolderDeletedBytesGeneratedTotal, c.folderDeletedBytesGeneratedTotal,
prometheus.CounterValue, prometheus.CounterValue,
folder.DeletedBytesGeneratedTotal, folder.DeletedBytesGeneratedTotal,
folder.Name, folder.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.FolderDeletedFilesCleanedUpTotal, c.folderDeletedFilesCleanedUpTotal,
prometheus.CounterValue, prometheus.CounterValue,
folder.DeletedFilesCleanedUpTotal, folder.DeletedFilesCleanedUpTotal,
folder.Name, folder.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.FolderDeletedFilesGeneratedTotal, c.folderDeletedFilesGeneratedTotal,
prometheus.CounterValue, prometheus.CounterValue,
folder.DeletedFilesGeneratedTotal, folder.DeletedFilesGeneratedTotal,
folder.Name, folder.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.FolderFileInstallsRetriedTotal, c.folderFileInstallsRetriedTotal,
prometheus.CounterValue, prometheus.CounterValue,
folder.FileInstallsRetriedTotal, folder.FileInstallsRetriedTotal,
folder.Name, folder.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.FolderFileInstallsSucceededTotal, c.folderFileInstallsSucceededTotal,
prometheus.CounterValue, prometheus.CounterValue,
folder.FileInstallsSucceededTotal, folder.FileInstallsSucceededTotal,
folder.Name, folder.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.FolderFilesReceivedTotal, c.folderFilesReceivedTotal,
prometheus.CounterValue, prometheus.CounterValue,
folder.FilesReceivedTotal, folder.FilesReceivedTotal,
folder.Name, folder.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.FolderRDCBytesReceivedTotal, c.folderRDCBytesReceivedTotal,
prometheus.CounterValue, prometheus.CounterValue,
folder.RDCBytesReceivedTotal, folder.RDCBytesReceivedTotal,
folder.Name, folder.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.FolderRDCCompressedSizeOfFilesReceivedTotal, c.folderRDCCompressedSizeOfFilesReceivedTotal,
prometheus.CounterValue, prometheus.CounterValue,
folder.RDCCompressedSizeOfFilesReceivedTotal, folder.RDCCompressedSizeOfFilesReceivedTotal,
folder.Name, folder.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.FolderRDCNumberofFilesReceivedTotal, c.folderRDCNumberofFilesReceivedTotal,
prometheus.CounterValue, prometheus.CounterValue,
folder.RDCNumberofFilesReceivedTotal, folder.RDCNumberofFilesReceivedTotal,
folder.Name, folder.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.FolderRDCSizeOfFilesReceivedTotal, c.folderRDCSizeOfFilesReceivedTotal,
prometheus.CounterValue, prometheus.CounterValue,
folder.RDCSizeOfFilesReceivedTotal, folder.RDCSizeOfFilesReceivedTotal,
folder.Name, folder.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.FolderSizeOfFilesReceivedTotal, c.folderSizeOfFilesReceivedTotal,
prometheus.CounterValue, prometheus.CounterValue,
folder.SizeOfFilesReceivedTotal, folder.SizeOfFilesReceivedTotal,
folder.Name, folder.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.FolderStagingSpaceInUse, c.folderStagingSpaceInUse,
prometheus.GaugeValue, prometheus.GaugeValue,
folder.StagingSpaceInUse, folder.StagingSpaceInUse,
folder.Name, folder.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.FolderStagingBytesCleanedUpTotal, c.folderStagingBytesCleanedUpTotal,
prometheus.CounterValue, prometheus.CounterValue,
folder.StagingBytesCleanedUpTotal, folder.StagingBytesCleanedUpTotal,
folder.Name, folder.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.FolderStagingBytesGeneratedTotal, c.folderStagingBytesGeneratedTotal,
prometheus.CounterValue, prometheus.CounterValue,
folder.StagingBytesGeneratedTotal, folder.StagingBytesGeneratedTotal,
folder.Name, folder.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.FolderStagingFilesCleanedUpTotal, c.folderStagingFilesCleanedUpTotal,
prometheus.CounterValue, prometheus.CounterValue,
folder.StagingFilesCleanedUpTotal, folder.StagingFilesCleanedUpTotal,
folder.Name, folder.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.FolderStagingFilesGeneratedTotal, c.folderStagingFilesGeneratedTotal,
prometheus.CounterValue, prometheus.CounterValue,
folder.StagingFilesGeneratedTotal, folder.StagingFilesGeneratedTotal,
folder.Name, folder.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.FolderUpdatesDroppedTotal, c.folderUpdatesDroppedTotal,
prometheus.CounterValue, prometheus.CounterValue,
folder.UpdatesDroppedTotal, folder.UpdatesDroppedTotal,
folder.Name, folder.Name,
@ -788,8 +790,8 @@ func (c *collector) collectFolder(ctx *types.ScrapeContext, ch chan<- prometheus
return nil return nil
} }
// PerflibDFSRVolume Perflib: "DFS Replication Service Volumes" // perflibDFSRVolume Perflib: "DFS Replication Service Volumes"
type PerflibDFSRVolume struct { type perflibDFSRVolume struct {
Name string Name string
DatabaseCommitsTotal float64 `perflib:"Database Commits"` DatabaseCommitsTotal float64 `perflib:"Database Commits"`
@ -799,48 +801,47 @@ type PerflibDFSRVolume struct {
USNJournalUnreadPercentage float64 `perflib:"USN Journal Records Unread Percentage"` USNJournalUnreadPercentage float64 `perflib:"USN Journal Records Unread Percentage"`
} }
func (c *collector) collectVolume(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collectVolume(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var dst []PerflibDFSRVolume var dst []perflibDFSRVolume
if err := perflib.UnmarshalObject(ctx.PerfObjects["DFS Replication Service Volumes"], &dst, c.logger); err != nil { if err := perflib.UnmarshalObject(ctx.PerfObjects["DFS Replication Service volumes"], &dst, c.logger); err != nil {
return err return err
} }
for _, volume := range dst { for _, volume := range dst {
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.VolumeDatabaseLookupsTotal, c.volumeDatabaseLookupsTotal,
prometheus.CounterValue, prometheus.CounterValue,
volume.DatabaseLookupsTotal, volume.DatabaseLookupsTotal,
volume.Name, volume.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.VolumeDatabaseCommitsTotal, c.volumeDatabaseCommitsTotal,
prometheus.CounterValue, prometheus.CounterValue,
volume.DatabaseCommitsTotal, volume.DatabaseCommitsTotal,
volume.Name, volume.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.VolumeUSNJournalRecordsAcceptedTotal, c.volumeUSNJournalRecordsAcceptedTotal,
prometheus.CounterValue, prometheus.CounterValue,
volume.USNJournalRecordsAcceptedTotal, volume.USNJournalRecordsAcceptedTotal,
volume.Name, volume.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.VolumeUSNJournalRecordsReadTotal, c.volumeUSNJournalRecordsReadTotal,
prometheus.CounterValue, prometheus.CounterValue,
volume.USNJournalRecordsReadTotal, volume.USNJournalRecordsReadTotal,
volume.Name, volume.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.VolumeUSNJournalUnreadPercentage, c.volumeUSNJournalUnreadPercentage,
prometheus.GaugeValue, prometheus.GaugeValue,
volume.USNJournalUnreadPercentage, volume.USNJournalUnreadPercentage,
volume.Name, volume.Name,
) )
} }
return nil return nil
} }

View File

@ -16,8 +16,8 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
// A collector is a Prometheus collector perflib DHCP metrics // A Collector is a Prometheus Collector perflib DHCP metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
PacketsReceivedTotal *prometheus.Desc PacketsReceivedTotal *prometheus.Desc
@ -47,29 +47,34 @@ type collector struct {
FailoverBndupdDropped *prometheus.Desc FailoverBndupdDropped *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{"DHCP Server"}, nil return []string{"DHCP Server"}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.PacketsReceivedTotal = prometheus.NewDesc( c.PacketsReceivedTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "packets_received_total"), prometheus.BuildFQName(types.Namespace, Name, "packets_received_total"),
"Total number of packets received by the DHCP server (PacketsReceivedTotal)", "Total number of packets received by the DHCP server (PacketsReceivedTotal)",
@ -254,7 +259,7 @@ type dhcpPerf struct {
FailoverBndupdDropped float64 `perflib:"Failover: BndUpd Dropped."` FailoverBndupdDropped float64 `perflib:"Failover: BndUpd Dropped."`
} }
func (c *collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var dhcpPerfs []dhcpPerf var dhcpPerfs []dhcpPerf
if err := perflib.UnmarshalObject(ctx.PerfObjects["DHCP Server"], &dhcpPerfs, c.logger); err != nil { if err := perflib.UnmarshalObject(ctx.PerfObjects["DHCP Server"], &dhcpPerfs, c.logger); err != nil {
return err return err

View File

@ -23,8 +23,8 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
// A collector is a Prometheus collector for a few WMI metrics in Win32_DiskDrive // A Collector is a Prometheus Collector for a few WMI metrics in Win32_DiskDrive
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
DiskInfo *prometheus.Desc DiskInfo *prometheus.Desc
@ -34,29 +34,34 @@ type collector struct {
Availability *prometheus.Desc Availability *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{}, nil return []string{}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.DiskInfo = prometheus.NewDesc( c.DiskInfo = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "info"), prometheus.BuildFQName(types.Namespace, Name, "info"),
"General drive information", "General drive information",
@ -149,7 +154,7 @@ var (
) )
// Collect sends the metric values for each metric to the provided prometheus Metric channel. // Collect sends the metric values for each metric to the provided prometheus Metric channel.
func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collect(ch); err != nil { if err := c.collect(ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting disk_drive_info metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting disk_drive_info metrics", "err", err)
return err return err
@ -157,7 +162,7 @@ func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric)
return nil return nil
} }
func (c *collector) collect(ch chan<- prometheus.Metric) error { func (c *Collector) collect(ch chan<- prometheus.Metric) error {
var dst []Win32_DiskDrive var dst []Win32_DiskDrive
if err := wmi.Query(win32DiskQuery, &dst); err != nil { if err := wmi.Query(win32DiskQuery, &dst); err != nil {

View File

@ -19,8 +19,8 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
// A collector is a Prometheus collector for WMI Win32_PerfRawData_DNS_DNS metrics // A Collector is a Prometheus Collector for WMI Win32_PerfRawData_DNS_DNS metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
ZoneTransferRequestsReceived *prometheus.Desc ZoneTransferRequestsReceived *prometheus.Desc
@ -47,29 +47,34 @@ type collector struct {
UnmatchedResponsesReceived *prometheus.Desc UnmatchedResponsesReceived *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{}, nil return []string{}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.ZoneTransferRequestsReceived = prometheus.NewDesc( c.ZoneTransferRequestsReceived = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "zone_transfer_requests_received_total"), prometheus.BuildFQName(types.Namespace, Name, "zone_transfer_requests_received_total"),
"Number of zone transfer requests (AXFR/IXFR) received by the master DNS server", "Number of zone transfer requests (AXFR/IXFR) received by the master DNS server",
@ -207,7 +212,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collect(ch); err != nil { if err := c.collect(ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting dns metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting dns metrics", "err", err)
return err return err
@ -261,7 +266,7 @@ type Win32_PerfRawData_DNS_DNS struct {
ZoneTransferSOARequestSent uint32 ZoneTransferSOARequestSent uint32
} }
func (c *collector) collect(ch chan<- prometheus.Metric) error { func (c *Collector) collect(ch chan<- prometheus.Metric) error {
var dst []Win32_PerfRawData_DNS_DNS var dst []Win32_PerfRawData_DNS_DNS
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {

View File

@ -17,11 +17,7 @@ import (
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
const ( const Name = "exchange"
Name = "exchange"
FlagExchangeListAllCollectors = "collectors.exchange.list"
FlagExchangeCollectorsEnabled = "collectors.exchange.enabled"
)
type Config struct { type Config struct {
CollectorsEnabled string `yaml:"collectors_enabled"` CollectorsEnabled string `yaml:"collectors_enabled"`
@ -31,7 +27,7 @@ var ConfigDefaults = Config{
CollectorsEnabled: "", CollectorsEnabled: "",
} }
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
exchangeListAllCollectors *bool exchangeListAllCollectors *bool
@ -79,7 +75,7 @@ type collector struct {
enabledCollectors []string enabledCollectors []string
} }
// All available collector functions // All available Collector functions
var exchangeAllCollectorNames = []string{ var exchangeAllCollectorNames = []string{
"ADAccessProcesses", "ADAccessProcesses",
"TransportQueues", "TransportQueues",
@ -93,43 +89,44 @@ var exchangeAllCollectorNames = []string{
"MapiHttpEmsmdb", "MapiHttpEmsmdb",
} }
func New(logger log.Logger, config *Config) types.Collector { func New(logger log.Logger, config *Config) *Collector {
if config == nil { if config == nil {
config = &ConfigDefaults config = &ConfigDefaults
} }
exchangeListAllCollectors := false exchangeListAllCollectors := false
c := &collector{ c := &Collector{
exchangeCollectorsEnabled: &config.CollectorsEnabled, exchangeCollectorsEnabled: &config.CollectorsEnabled,
exchangeListAllCollectors: &exchangeListAllCollectors, exchangeListAllCollectors: &exchangeListAllCollectors,
} }
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(app *kingpin.Application) types.Collector { func NewWithFlags(app *kingpin.Application) *Collector {
return &collector{ return &Collector{
exchangeListAllCollectors: app.Flag( exchangeListAllCollectors: app.Flag(
FlagExchangeListAllCollectors, "collectors.exchange.list",
"List the collectors along with their perflib object name/ids", "List the collectors along with their perflib object name/ids",
).Bool(), ).Bool(),
exchangeCollectorsEnabled: app.Flag( exchangeCollectorsEnabled: app.Flag(
FlagExchangeCollectorsEnabled, "collectors.exchange.enabled",
"Comma-separated list of collectors to use. Defaults to all, if not specified.", "Comma-separated list of collectors to use. Defaults to all, if not specified.",
).Default(ConfigDefaults.CollectorsEnabled).String(), ).Default(ConfigDefaults.CollectorsEnabled).String(),
} }
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{ return []string{
"MSExchange ADAccess Processes", "MSExchange ADAccess Processes",
"MSExchangeTransport Queues", "MSExchangeTransport Queues",
@ -144,7 +141,11 @@ func (c *collector) GetPerfCounter() ([]string, error) {
}, nil }, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
// desc creates a new prometheus description // desc creates a new prometheus description
desc := func(metricName string, description string, labels ...string) *prometheus.Desc { desc := func(metricName string, description string, labels ...string) *prometheus.Desc {
return prometheus.NewDesc( return prometheus.NewDesc(
@ -210,10 +211,11 @@ func (c *collector) Build() error {
} }
if *c.exchangeListAllCollectors { if *c.exchangeListAllCollectors {
fmt.Printf("%-32s %-32s\n", "Collector Name", "[PerfID] Perflib Object") fmt.Printf("%-32s %-32s\n", "Collector Name", "[PerfID] Perflib Object") //nolint:forbidigo
for _, cname := range exchangeAllCollectorNames { for _, cname := range exchangeAllCollectorNames {
fmt.Printf("%-32s %-32s\n", cname, collectorDesc[cname]) fmt.Printf("%-32s %-32s\n", cname, collectorDesc[cname]) //nolint:forbidigo
} }
os.Exit(0) os.Exit(0)
} }
@ -235,7 +237,7 @@ func (c *collector) Build() error {
} }
// Collect collects exchange metrics and sends them to prometheus // Collect collects exchange metrics and sends them to prometheus
func (c *collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
collectorFuncs := map[string]func(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error{ collectorFuncs := map[string]func(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error{
"ADAccessProcesses": c.collectADAccessProcesses, "ADAccessProcesses": c.collectADAccessProcesses,
"TransportQueues": c.collectTransportQueues, "TransportQueues": c.collectTransportQueues,
@ -269,7 +271,7 @@ type perflibADAccessProcesses struct {
LongRunningLDAPOperationsPerMin float64 `perflib:"Long Running LDAP Operations/min"` LongRunningLDAPOperationsPerMin float64 `perflib:"Long Running LDAP Operations/min"`
} }
func (c *collector) collectADAccessProcesses(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collectADAccessProcesses(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var data []perflibADAccessProcesses var data []perflibADAccessProcesses
if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchange ADAccess Processes"], &data, c.logger); err != nil { if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchange ADAccess Processes"], &data, c.logger); err != nil {
return err return err
@ -327,7 +329,7 @@ type perflibAvailabilityService struct {
RequestsSec float64 `perflib:"Availability Requests (sec)"` RequestsSec float64 `perflib:"Availability Requests (sec)"`
} }
func (c *collector) collectAvailabilityService(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collectAvailabilityService(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var data []perflibAvailabilityService var data []perflibAvailabilityService
if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchange Availability Service"], &data, c.logger); err != nil { if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchange Availability Service"], &data, c.logger); err != nil {
return err return err
@ -355,7 +357,7 @@ type perflibHTTPProxy struct {
ProxyRequestsPerSec float64 `perflib:"Proxy Requests/Sec"` ProxyRequestsPerSec float64 `perflib:"Proxy Requests/Sec"`
} }
func (c *collector) collectHTTPProxy(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collectHTTPProxy(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var data []perflibHTTPProxy var data []perflibHTTPProxy
if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchange HttpProxy"], &data, c.logger); err != nil { if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchange HttpProxy"], &data, c.logger); err != nil {
return err return err
@ -409,7 +411,7 @@ type perflibOWA struct {
RequestsPerSec float64 `perflib:"Requests/sec"` RequestsPerSec float64 `perflib:"Requests/sec"`
} }
func (c *collector) collectOWA(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collectOWA(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var data []perflibOWA var data []perflibOWA
if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchange OWA"], &data, c.logger); err != nil { if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchange OWA"], &data, c.logger); err != nil {
return err return err
@ -437,7 +439,7 @@ type perflibActiveSync struct {
SyncCommandsPerSec float64 `perflib:"Sync Commands/sec"` SyncCommandsPerSec float64 `perflib:"Sync Commands/sec"`
} }
func (c *collector) collectActiveSync(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collectActiveSync(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var data []perflibActiveSync var data []perflibActiveSync
if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchange ActiveSync"], &data, c.logger); err != nil { if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchange ActiveSync"], &data, c.logger); err != nil {
return err return err
@ -473,7 +475,7 @@ type perflibRPCClientAccess struct {
UserCount float64 `perflib:"User Count"` UserCount float64 `perflib:"User Count"`
} }
func (c *collector) collectRPC(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collectRPC(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var data []perflibRPCClientAccess var data []perflibRPCClientAccess
if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchange RpcClientAccess"], &data, c.logger); err != nil { if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchange RpcClientAccess"], &data, c.logger); err != nil {
return err return err
@ -529,7 +531,7 @@ type perflibTransportQueues struct {
PoisonQueueLength float64 `perflib:"Poison Queue Length"` PoisonQueueLength float64 `perflib:"Poison Queue Length"`
} }
func (c *collector) collectTransportQueues(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collectTransportQueues(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var data []perflibTransportQueues var data []perflibTransportQueues
if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchangeTransport Queues"], &data, c.logger); err != nil { if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchangeTransport Queues"], &data, c.logger); err != nil {
return err return err
@ -603,7 +605,7 @@ type perflibWorkloadManagementWorkloads struct {
IsActive float64 `perflib:"Active"` IsActive float64 `perflib:"Active"`
} }
func (c *collector) collectWorkloadManagementWorkloads(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collectWorkloadManagementWorkloads(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var data []perflibWorkloadManagementWorkloads var data []perflibWorkloadManagementWorkloads
if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchange WorkloadManagement Workloads"], &data, c.logger); err != nil { if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchange WorkloadManagement Workloads"], &data, c.logger); err != nil {
return err return err
@ -654,7 +656,7 @@ type perflibAutodiscover struct {
RequestsPerSec float64 `perflib:"Requests/sec"` RequestsPerSec float64 `perflib:"Requests/sec"`
} }
func (c *collector) collectAutoDiscover(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collectAutoDiscover(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var data []perflibAutodiscover var data []perflibAutodiscover
if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchangeAutodiscover"], &data, c.logger); err != nil { if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchangeAutodiscover"], &data, c.logger); err != nil {
return err return err
@ -674,7 +676,7 @@ type perflibMapiHttpEmsmdb struct {
ActiveUserCount float64 `perflib:"Active User Count"` ActiveUserCount float64 `perflib:"Active User Count"`
} }
func (c *collector) collectMapiHttpEmsmdb(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collectMapiHttpEmsmdb(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var data []perflibMapiHttpEmsmdb var data []perflibMapiHttpEmsmdb
if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchange MapiHttp Emsmdb"], &data, c.logger); err != nil { if err := perflib.UnmarshalObject(ctx.PerfObjects["MSExchange MapiHttp Emsmdb"], &data, c.logger); err != nil {
return err return err
@ -692,13 +694,13 @@ func (c *collector) collectMapiHttpEmsmdb(ctx *types.ScrapeContext, ch chan<- pr
} }
// toLabelName converts strings to lowercase and replaces all whitespaces and dots with underscores // toLabelName converts strings to lowercase and replaces all whitespaces and dots with underscores
func (c *collector) toLabelName(name string) string { func (c *Collector) toLabelName(name string) string {
s := strings.ReplaceAll(strings.Join(strings.Fields(strings.ToLower(name)), "_"), ".", "_") s := strings.ReplaceAll(strings.Join(strings.Fields(strings.ToLower(name)), "_"), ".", "_")
s = strings.ReplaceAll(s, "__", "_") s = strings.ReplaceAll(s, "__", "_")
return s return s
} }
// msToSec converts from ms to seconds // msToSec converts from ms to seconds
func (c *collector) msToSec(t float64) float64 { func (c *Collector) msToSec(t float64) float64 {
return t / 1000 return t / 1000
} }

View File

@ -3,13 +3,12 @@
package fsrmquota package fsrmquota
import ( import (
"github.com/prometheus-community/windows_exporter/pkg/types"
"github.com/prometheus-community/windows_exporter/pkg/utils"
"github.com/prometheus-community/windows_exporter/pkg/wmi"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/go-kit/log/level" "github.com/go-kit/log/level"
"github.com/prometheus-community/windows_exporter/pkg/types"
"github.com/prometheus-community/windows_exporter/pkg/utils"
"github.com/prometheus-community/windows_exporter/pkg/wmi"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -19,7 +18,7 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
QuotasCount *prometheus.Desc QuotasCount *prometheus.Desc
@ -35,29 +34,34 @@ type collector struct {
Template *prometheus.Desc Template *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{}, nil return []string{}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.QuotasCount = prometheus.NewDesc( c.QuotasCount = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "count"), prometheus.BuildFQName(types.Namespace, Name, "count"),
"Number of Quotas", "Number of Quotas",
@ -117,7 +121,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collect(ch); err != nil { if err := c.collect(ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting fsrmquota metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting fsrmquota metrics", "err", err)
return err return err
@ -142,7 +146,7 @@ type MSFT_FSRMQuota struct {
SoftLimit bool SoftLimit bool
} }
func (c *collector) collect(ch chan<- prometheus.Metric) error { func (c *Collector) collect(ch chan<- prometheus.Metric) error {
var dst []MSFT_FSRMQuota var dst []MSFT_FSRMQuota
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
@ -153,7 +157,6 @@ func (c *collector) collect(ch chan<- prometheus.Metric) error {
} }
for _, quota := range dst { for _, quota := range dst {
count++ count++
path := quota.Path path := quota.Path
template := quota.Template template := quota.Template

View File

@ -11,7 +11,6 @@ import (
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/go-kit/log/level" "github.com/go-kit/log/level"
"github.com/prometheus-community/windows_exporter/pkg/types"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors" "github.com/prometheus/client_golang/prometheus/collectors"
"github.com/prometheus/client_golang/prometheus/collectors/version" "github.com/prometheus/client_golang/prometheus/collectors/version"
@ -20,7 +19,7 @@ import (
func (c *Collectors) BuildServeHTTP(disableExporterMetrics bool, timeoutMargin float64) http.HandlerFunc { func (c *Collectors) BuildServeHTTP(disableExporterMetrics bool, timeoutMargin float64) http.HandlerFunc {
collectorFactory := func(timeout time.Duration, requestedCollectors []string) (error, *Prometheus) { collectorFactory := func(timeout time.Duration, requestedCollectors []string) (error, *Prometheus) {
filteredCollectors := make(map[string]types.Collector) filteredCollectors := make(map[string]Collector)
// scrape all enabled collectors if no collector is requested // scrape all enabled collectors if no collector is requested
if len(requestedCollectors) == 0 { if len(requestedCollectors) == 0 {
filteredCollectors = c.collectors filteredCollectors = c.collectors

View File

@ -6,12 +6,11 @@ import (
"fmt" "fmt"
"strings" "strings"
"github.com/prometheus-community/windows_exporter/pkg/types"
"github.com/prometheus-community/windows_exporter/pkg/wmi"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/go-kit/log/level" "github.com/go-kit/log/level"
"github.com/prometheus-community/windows_exporter/pkg/types"
"github.com/prometheus-community/windows_exporter/pkg/wmi"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -21,8 +20,8 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
// collector is a Prometheus collector for hyper-v // Collector is a Prometheus Collector for hyper-v
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
// Win32_PerfRawData_VmmsVirtualMachineStats_HyperVVirtualMachineHealthSummary // Win32_PerfRawData_VmmsVirtualMachineStats_HyperVVirtualMachineHealthSummary
@ -140,29 +139,34 @@ type collector struct {
VMMemoryRemovedMemory *prometheus.Desc VMMemoryRemovedMemory *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{}, nil return []string{}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
buildSubsystemName := func(component string) string { return "hyperv_" + component } buildSubsystemName := func(component string) string { return "hyperv_" + component }
c.HealthCritical = prometheus.NewDesc( c.HealthCritical = prometheus.NewDesc(
@ -742,7 +746,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collectVmHealth(ch); err != nil { if err := c.collectVmHealth(ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting hyperV health status metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting hyperV health status metrics", "err", err)
return err return err
@ -812,7 +816,7 @@ type Win32_PerfRawData_VmmsVirtualMachineStats_HyperVVirtualMachineHealthSummary
HealthOk uint32 HealthOk uint32
} }
func (c *collector) collectVmHealth(ch chan<- prometheus.Metric) error { func (c *Collector) collectVmHealth(ch chan<- prometheus.Metric) error {
var dst []Win32_PerfRawData_VmmsVirtualMachineStats_HyperVVirtualMachineHealthSummary var dst []Win32_PerfRawData_VmmsVirtualMachineStats_HyperVVirtualMachineHealthSummary
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -831,7 +835,6 @@ func (c *collector) collectVmHealth(ch chan<- prometheus.Metric) error {
prometheus.GaugeValue, prometheus.GaugeValue,
float64(health.HealthOk), float64(health.HealthOk),
) )
} }
return nil return nil
@ -845,7 +848,7 @@ type Win32_PerfRawData_VidPerfProvider_HyperVVMVidPartition struct {
RemotePhysicalPages uint64 RemotePhysicalPages uint64
} }
func (c *collector) collectVmVid(ch chan<- prometheus.Metric) error { func (c *Collector) collectVmVid(ch chan<- prometheus.Metric) error {
var dst []Win32_PerfRawData_VidPerfProvider_HyperVVMVidPartition var dst []Win32_PerfRawData_VidPerfProvider_HyperVVMVidPartition
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -877,7 +880,6 @@ func (c *collector) collectVmVid(ch chan<- prometheus.Metric) error {
float64(page.RemotePhysicalPages), float64(page.RemotePhysicalPages),
page.Name, page.Name,
) )
} }
return nil return nil
@ -909,7 +911,7 @@ type Win32_PerfRawData_HvStats_HyperVHypervisorRootPartition struct {
VirtualTLBPages uint64 VirtualTLBPages uint64
} }
func (c *collector) collectVmHv(ch chan<- prometheus.Metric) error { func (c *Collector) collectVmHv(ch chan<- prometheus.Metric) error {
var dst []Win32_PerfRawData_HvStats_HyperVHypervisorRootPartition var dst []Win32_PerfRawData_HvStats_HyperVHypervisorRootPartition
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -1035,7 +1037,6 @@ func (c *collector) collectVmHv(ch chan<- prometheus.Metric) error {
prometheus.GaugeValue, prometheus.GaugeValue,
float64(obj.VirtualTLBPages), float64(obj.VirtualTLBPages),
) )
} }
return nil return nil
@ -1047,7 +1048,7 @@ type Win32_PerfRawData_HvStats_HyperVHypervisor struct {
VirtualProcessors uint64 VirtualProcessors uint64
} }
func (c *collector) collectVmProcessor(ch chan<- prometheus.Metric) error { func (c *Collector) collectVmProcessor(ch chan<- prometheus.Metric) error {
var dst []Win32_PerfRawData_HvStats_HyperVHypervisor var dst []Win32_PerfRawData_HvStats_HyperVHypervisor
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -1055,7 +1056,6 @@ func (c *collector) collectVmProcessor(ch chan<- prometheus.Metric) error {
} }
for _, obj := range dst { for _, obj := range dst {
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.LogicalProcessors, c.LogicalProcessors,
prometheus.GaugeValue, prometheus.GaugeValue,
@ -1067,7 +1067,6 @@ func (c *collector) collectVmProcessor(ch chan<- prometheus.Metric) error {
prometheus.GaugeValue, prometheus.GaugeValue,
float64(obj.VirtualProcessors), float64(obj.VirtualProcessors),
) )
} }
return nil return nil
@ -1081,7 +1080,7 @@ type Win32_PerfRawData_HvStats_HyperVHypervisorLogicalProcessor struct {
PercentTotalRunTime uint PercentTotalRunTime uint
} }
func (c *collector) collectHostLPUsage(ch chan<- prometheus.Metric) error { func (c *Collector) collectHostLPUsage(ch chan<- prometheus.Metric) error {
var dst []Win32_PerfRawData_HvStats_HyperVHypervisorLogicalProcessor var dst []Win32_PerfRawData_HvStats_HyperVHypervisorLogicalProcessor
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -1120,7 +1119,6 @@ func (c *collector) collectHostLPUsage(ch chan<- prometheus.Metric) error {
float64(obj.PercentTotalRunTime), float64(obj.PercentTotalRunTime),
coreId, coreId,
) )
} }
return nil return nil
@ -1136,7 +1134,7 @@ type Win32_PerfRawData_HvStats_HyperVHypervisorRootVirtualProcessor struct {
CPUWaitTimePerDispatch uint64 CPUWaitTimePerDispatch uint64
} }
func (c *collector) collectHostCpuUsage(ch chan<- prometheus.Metric) error { func (c *Collector) collectHostCpuUsage(ch chan<- prometheus.Metric) error {
var dst []Win32_PerfRawData_HvStats_HyperVHypervisorRootVirtualProcessor var dst []Win32_PerfRawData_HvStats_HyperVHypervisorRootVirtualProcessor
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -1204,7 +1202,7 @@ type Win32_PerfRawData_HvStats_HyperVHypervisorVirtualProcessor struct {
CPUWaitTimePerDispatch uint64 CPUWaitTimePerDispatch uint64
} }
func (c *collector) collectVmCpuUsage(ch chan<- prometheus.Metric) error { func (c *Collector) collectVmCpuUsage(ch chan<- prometheus.Metric) error {
var dst []Win32_PerfRawData_HvStats_HyperVHypervisorVirtualProcessor var dst []Win32_PerfRawData_HvStats_HyperVHypervisorVirtualProcessor
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -1263,7 +1261,6 @@ func (c *collector) collectVmCpuUsage(ch chan<- prometheus.Metric) error {
float64(obj.CPUWaitTimePerDispatch), float64(obj.CPUWaitTimePerDispatch),
vmName, coreId, vmName, coreId,
) )
} }
return nil return nil
@ -1298,7 +1295,7 @@ type Win32_PerfRawData_NvspSwitchStats_HyperVVirtualSwitch struct {
PurgedMacAddressesPersec uint64 PurgedMacAddressesPersec uint64
} }
func (c *collector) collectVmSwitch(ch chan<- prometheus.Metric) error { func (c *Collector) collectVmSwitch(ch chan<- prometheus.Metric) error {
var dst []Win32_PerfRawData_NvspSwitchStats_HyperVVirtualSwitch var dst []Win32_PerfRawData_NvspSwitchStats_HyperVVirtualSwitch
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -1463,7 +1460,7 @@ type Win32_PerfRawData_EthernetPerfProvider_HyperVLegacyNetworkAdapter struct {
FramesSentPersec uint64 FramesSentPersec uint64
} }
func (c *collector) collectVmEthernet(ch chan<- prometheus.Metric) error { func (c *Collector) collectVmEthernet(ch chan<- prometheus.Metric) error {
var dst []Win32_PerfRawData_EthernetPerfProvider_HyperVLegacyNetworkAdapter var dst []Win32_PerfRawData_EthernetPerfProvider_HyperVLegacyNetworkAdapter
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -1516,7 +1513,6 @@ func (c *collector) collectVmEthernet(ch chan<- prometheus.Metric) error {
float64(obj.FramesSentPersec), float64(obj.FramesSentPersec),
obj.Name, obj.Name,
) )
} }
return nil return nil
@ -1533,7 +1529,7 @@ type Win32_PerfRawData_Counters_HyperVVirtualStorageDevice struct {
WriteOperationsPerSec uint64 WriteOperationsPerSec uint64
} }
func (c *collector) collectVmStorage(ch chan<- prometheus.Metric) error { func (c *Collector) collectVmStorage(ch chan<- prometheus.Metric) error {
var dst []Win32_PerfRawData_Counters_HyperVVirtualStorageDevice var dst []Win32_PerfRawData_Counters_HyperVVirtualStorageDevice
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -1602,7 +1598,7 @@ type Win32_PerfRawData_NvspNicStats_HyperVVirtualNetworkAdapter struct {
PacketsSentPersec uint64 PacketsSentPersec uint64
} }
func (c *collector) collectVmNetwork(ch chan<- prometheus.Metric) error { func (c *Collector) collectVmNetwork(ch chan<- prometheus.Metric) error {
var dst []Win32_PerfRawData_NvspNicStats_HyperVVirtualNetworkAdapter var dst []Win32_PerfRawData_NvspNicStats_HyperVVirtualNetworkAdapter
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -1675,7 +1671,7 @@ type Win32_PerfRawData_BalancerStats_HyperVDynamicMemoryVM struct {
RemovedMemory uint64 RemovedMemory uint64
} }
func (c *collector) collectVmMemory(ch chan<- prometheus.Metric) error { func (c *Collector) collectVmMemory(ch chan<- prometheus.Metric) error {
var dst []Win32_PerfRawData_BalancerStats_HyperVDynamicMemoryVM var dst []Win32_PerfRawData_BalancerStats_HyperVDynamicMemoryVM
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {

View File

@ -17,14 +17,7 @@ import (
"golang.org/x/sys/windows/registry" "golang.org/x/sys/windows/registry"
) )
const ( const Name = "iis"
Name = "iis"
FlagIISSiteExclude = "collector.iis.site-exclude"
FlagIISSiteInclude = "collector.iis.site-include"
FlagIISAppExclude = "collector.iis.app-exclude"
FlagIISAppInclude = "collector.iis.app-include"
)
type Config struct { type Config struct {
SiteInclude string `yaml:"site_include"` SiteInclude string `yaml:"site_include"`
@ -77,7 +70,7 @@ func getIISVersion(logger log.Logger) simple_version {
} }
} }
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
siteInclude *string siteInclude *string
@ -220,40 +213,41 @@ type collector struct {
iis_version simple_version iis_version simple_version
} }
func New(logger log.Logger, config *Config) types.Collector { func New(logger log.Logger, config *Config) *Collector {
if config == nil { if config == nil {
config = &ConfigDefaults config = &ConfigDefaults
} }
c := &collector{ c := &Collector{
appInclude: &config.AppInclude, appInclude: &config.AppInclude,
appExclude: &config.AppExclude, appExclude: &config.AppExclude,
siteInclude: &config.SiteInclude, siteInclude: &config.SiteInclude,
siteExclude: &config.SiteExclude, siteExclude: &config.SiteExclude,
} }
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(app *kingpin.Application) types.Collector { func NewWithFlags(app *kingpin.Application) *Collector {
c := &collector{ c := &Collector{
siteInclude: app.Flag( siteInclude: app.Flag(
FlagIISSiteInclude, "collector.iis.site-include",
"Regexp of sites to include. Site name must both match include and not match exclude to be included.", "Regexp of sites to include. Site name must both match include and not match exclude to be included.",
).Default(ConfigDefaults.SiteInclude).String(), ).Default(ConfigDefaults.SiteInclude).String(),
siteExclude: app.Flag( siteExclude: app.Flag(
FlagIISSiteExclude, "collector.iis.site-exclude",
"Regexp of sites to exclude. Site name must both match include and not match exclude to be included.", "Regexp of sites to exclude. Site name must both match include and not match exclude to be included.",
).Default(ConfigDefaults.SiteExclude).String(), ).Default(ConfigDefaults.SiteExclude).String(),
appInclude: app.Flag( appInclude: app.Flag(
FlagIISAppInclude, "collector.iis.app-include",
"Regexp of apps to include. App name must both match include and not match exclude to be included.", "Regexp of apps to include. App name must both match include and not match exclude to be included.",
).Default(ConfigDefaults.AppInclude).String(), ).Default(ConfigDefaults.AppInclude).String(),
appExclude: app.Flag( appExclude: app.Flag(
FlagIISAppExclude, "collector.iis.app-exclude",
"Regexp of apps to exclude. App name must both match include and not match exclude to be included.", "Regexp of apps to exclude. App name must both match include and not match exclude to be included.",
).Default(ConfigDefaults.AppExclude).String(), ).Default(ConfigDefaults.AppExclude).String(),
} }
@ -261,15 +255,15 @@ func NewWithFlags(app *kingpin.Application) types.Collector {
return c return c
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{ return []string{
"Web Service", "Web Service",
"APP_POOL_WAS", "APP_POOL_WAS",
@ -278,7 +272,11 @@ func (c *collector) GetPerfCounter() ([]string, error) {
}, nil }, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.iis_version = getIISVersion(c.logger) c.iis_version = getIISVersion(c.logger)
var err error var err error
@ -925,7 +923,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collectWebService(ctx, ch); err != nil { if err := c.collectWebService(ctx, ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting iis metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting iis metrics", "err", err)
return err return err
@ -1021,7 +1019,7 @@ type hasGetIISName interface {
// //
// E.G. Given the following list of site names, "Site_B" would be // E.G. Given the following list of site names, "Site_B" would be
// discarded, and "Site_B#2" would be kept and presented as "Site_B" in the // discarded, and "Site_B#2" would be kept and presented as "Site_B" in the
// collector metrics. // Collector metrics.
// [ "Site_A", "Site_B", "Site_C", "Site_B#2" ] // [ "Site_A", "Site_B", "Site_C", "Site_B#2" ]
func dedupIISNames[V hasGetIISName](services []V) map[string]V { func dedupIISNames[V hasGetIISName](services []V) map[string]V {
// Ensure IIS entry with the highest suffix occurs last // Ensure IIS entry with the highest suffix occurs last
@ -1039,7 +1037,7 @@ func dedupIISNames[V hasGetIISName](services []V) map[string]V {
return webServiceDeDuplicated return webServiceDeDuplicated
} }
func (c *collector) collectWebService(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collectWebService(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var webService []perflibWebService var webService []perflibWebService
if err := perflib.UnmarshalObject(ctx.PerfObjects["Web Service"], &webService, c.logger); err != nil { if err := perflib.UnmarshalObject(ctx.PerfObjects["Web Service"], &webService, c.logger); err != nil {
return err return err
@ -1331,7 +1329,7 @@ var applicationStates = map[uint32]string{
7: "Delete Pending", 7: "Delete Pending",
} }
func (c *collector) collectAPP_POOL_WAS(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collectAPP_POOL_WAS(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var APP_POOL_WAS []perflibAPP_POOL_WAS var APP_POOL_WAS []perflibAPP_POOL_WAS
if err := perflib.UnmarshalObject(ctx.PerfObjects["APP_POOL_WAS"], &APP_POOL_WAS, c.logger); err != nil { if err := perflib.UnmarshalObject(ctx.PerfObjects["APP_POOL_WAS"], &APP_POOL_WAS, c.logger); err != nil {
return err return err
@ -1508,7 +1506,7 @@ type perflibW3SVC_W3WP_IIS8 struct {
WebSocketConnectionsRejected float64 `perflib:"WebSocket Connections Rejected / Sec"` WebSocketConnectionsRejected float64 `perflib:"WebSocket Connections Rejected / Sec"`
} }
func (c *collector) collectW3SVC_W3WP(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collectW3SVC_W3WP(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var W3SVC_W3WP []perflibW3SVC_W3WP var W3SVC_W3WP []perflibW3SVC_W3WP
if err := perflib.UnmarshalObject(ctx.PerfObjects["W3SVC_W3WP"], &W3SVC_W3WP, c.logger); err != nil { if err := perflib.UnmarshalObject(ctx.PerfObjects["W3SVC_W3WP"], &W3SVC_W3WP, c.logger); err != nil {
return err return err
@ -1764,7 +1762,6 @@ func (c *collector) collectW3SVC_W3WP(ctx *types.ScrapeContext, ch chan<- promet
name, name,
pid, pid,
) )
} }
if c.iis_version.major >= 8 { if c.iis_version.major >= 8 {
@ -1906,7 +1903,7 @@ type perflibWebServiceCache struct {
ServiceCache_OutputCacheQueriesTotal float64 ServiceCache_OutputCacheQueriesTotal float64
} }
func (c *collector) collectWebServiceCache(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collectWebServiceCache(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var WebServiceCache []perflibWebServiceCache var WebServiceCache []perflibWebServiceCache
if err := perflib.UnmarshalObject(ctx.PerfObjects["Web Service Cache"], &WebServiceCache, c.logger); err != nil { if err := perflib.UnmarshalObject(ctx.PerfObjects["Web Service Cache"], &WebServiceCache, c.logger); err != nil {
return err return err

View File

@ -6,10 +6,9 @@ import (
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/go-kit/log/level" "github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus-community/windows_exporter/pkg/headers/slc" "github.com/prometheus-community/windows_exporter/pkg/headers/slc"
"github.com/prometheus-community/windows_exporter/pkg/types" "github.com/prometheus-community/windows_exporter/pkg/types"
"github.com/prometheus/client_golang/prometheus"
) )
const Name = "license" const Name = "license"
@ -26,36 +25,41 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
// A collector is a Prometheus collector for WMI Win32_PerfRawData_DNS_DNS metrics // A Collector is a Prometheus Collector for WMI Win32_PerfRawData_DNS_DNS metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
LicenseStatus *prometheus.Desc LicenseStatus *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{}, nil return []string{}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.LicenseStatus = prometheus.NewDesc( c.LicenseStatus = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "status"), prometheus.BuildFQName(types.Namespace, Name, "status"),
"Status of windows license", "Status of windows license",
@ -68,7 +72,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collect(ch); err != nil { if err := c.collect(ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting license metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting license metrics", "err", err)
return err return err
@ -76,7 +80,7 @@ func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric)
return nil return nil
} }
func (c *collector) collect(ch chan<- prometheus.Metric) error { func (c *Collector) collect(ch chan<- prometheus.Metric) error {
status, err := slc.SLIsWindowsGenuineLocal() status, err := slc.SLIsWindowsGenuineLocal()
if err != nil { if err != nil {
return err return err

View File

@ -10,22 +10,16 @@ import (
"strconv" "strconv"
"strings" "strings"
"golang.org/x/sys/windows"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/go-kit/log/level" "github.com/go-kit/log/level"
"github.com/prometheus-community/windows_exporter/pkg/perflib" "github.com/prometheus-community/windows_exporter/pkg/perflib"
"github.com/prometheus-community/windows_exporter/pkg/types" "github.com/prometheus-community/windows_exporter/pkg/types"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"golang.org/x/sys/windows"
) )
const ( const Name = "logical_disk"
Name = "logical_disk"
FlagLogicalDiskVolumeExclude = "collector.logical_disk.volume-exclude"
FlagLogicalDiskVolumeInclude = "collector.logical_disk.volume-include"
)
type Config struct { type Config struct {
VolumeInclude string `yaml:"volume_include"` VolumeInclude string `yaml:"volume_include"`
@ -37,8 +31,8 @@ var ConfigDefaults = Config{
VolumeExclude: "", VolumeExclude: "",
} }
// A collector is a Prometheus collector for perflib logicalDisk metrics // A Collector is a Prometheus Collector for perflib logicalDisk metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
volumeInclude *string volumeInclude *string
@ -75,27 +69,28 @@ type volumeInfo struct {
readonly float64 readonly float64
} }
func New(logger log.Logger, config *Config) types.Collector { func New(logger log.Logger, config *Config) *Collector {
if config == nil { if config == nil {
config = &ConfigDefaults config = &ConfigDefaults
} }
c := &collector{ c := &Collector{
volumeExclude: &config.VolumeExclude, volumeExclude: &config.VolumeExclude,
volumeInclude: &config.VolumeInclude, volumeInclude: &config.VolumeInclude,
} }
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(app *kingpin.Application) types.Collector { func NewWithFlags(app *kingpin.Application) *Collector {
c := &collector{ c := &Collector{
volumeInclude: app.Flag( volumeInclude: app.Flag(
FlagLogicalDiskVolumeInclude, "collector.logical_disk.volume-include",
"Regexp of volumes to include. Volume name must both match include and not match exclude to be included.", "Regexp of volumes to include. Volume name must both match include and not match exclude to be included.",
).Default(ConfigDefaults.VolumeInclude).String(), ).Default(ConfigDefaults.VolumeInclude).String(),
volumeExclude: app.Flag( volumeExclude: app.Flag(
FlagLogicalDiskVolumeExclude, "collector.logical_disk.volume-exclude",
"Regexp of volumes to exclude. Volume name must both match include and not match exclude to be included.", "Regexp of volumes to exclude. Volume name must both match include and not match exclude to be included.",
).Default(ConfigDefaults.VolumeExclude).String(), ).Default(ConfigDefaults.VolumeExclude).String(),
} }
@ -103,19 +98,23 @@ func NewWithFlags(app *kingpin.Application) types.Collector {
return c return c
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{"LogicalDisk"}, nil return []string{"LogicalDisk"}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.Information = prometheus.NewDesc( c.Information = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "info"), prometheus.BuildFQName(types.Namespace, Name, "info"),
"A metric with a constant '1' value labeled with logical disk information", "A metric with a constant '1' value labeled with logical disk information",
@ -256,7 +255,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collect(ctx, ch); err != nil { if err := c.collect(ctx, ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting logical_disk metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting logical_disk metrics", "err", err)
return err return err
@ -287,7 +286,7 @@ type logicalDisk struct {
AvgDiskSecPerTransfer float64 `perflib:"Avg. Disk sec/Transfer"` AvgDiskSecPerTransfer float64 `perflib:"Avg. Disk sec/Transfer"`
} }
func (c *collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var ( var (
err error err error
diskID string diskID string

View File

@ -9,8 +9,8 @@ import (
) )
func BenchmarkCollector(b *testing.B) { func BenchmarkCollector(b *testing.B) {
// Whitelist is not set in testing context (kingpin flags not parsed), causing the collector to skip all disks. // Whitelist is not set in testing context (kingpin flags not parsed), causing the Collector to skip all disks.
localVolumeInclude := ".+" localVolumeInclude := ".+"
kingpin.CommandLine.GetArg(logical_disk.FlagLogicalDiskVolumeInclude).StringVar(&localVolumeInclude) kingpin.CommandLine.GetArg("collector.logical_disk.volume-include").StringVar(&localVolumeInclude)
testutils.FuncBenchmarkCollector(b, "logical_disk", logical_disk.NewWithFlags) testutils.FuncBenchmarkCollector(b, "logical_disk", logical_disk.NewWithFlags)
} }

View File

@ -5,12 +5,11 @@ package logon
import ( import (
"errors" "errors"
"github.com/prometheus-community/windows_exporter/pkg/types"
"github.com/prometheus-community/windows_exporter/pkg/wmi"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/go-kit/log/level" "github.com/go-kit/log/level"
"github.com/prometheus-community/windows_exporter/pkg/types"
"github.com/prometheus-community/windows_exporter/pkg/wmi"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -20,36 +19,41 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
// A collector is a Prometheus collector for WMI metrics // A Collector is a Prometheus Collector for WMI metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
LogonType *prometheus.Desc LogonType *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{}, nil return []string{}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.LogonType = prometheus.NewDesc( c.LogonType = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "logon_type"), prometheus.BuildFQName(types.Namespace, Name, "logon_type"),
"Number of active logon sessions (LogonSession.LogonType)", "Number of active logon sessions (LogonSession.LogonType)",
@ -61,7 +65,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collect(ch); err != nil { if err := c.collect(ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting user metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting user metrics", "err", err)
return err return err
@ -75,7 +79,7 @@ type Win32_LogonSession struct {
LogonType uint32 LogonType uint32
} }
func (c *collector) collect(ch chan<- prometheus.Metric) error { func (c *Collector) collect(ch chan<- prometheus.Metric) error {
var dst []Win32_LogonSession var dst []Win32_LogonSession
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {

View File

@ -8,6 +8,6 @@ import (
) )
func BenchmarkCollector(b *testing.B) { func BenchmarkCollector(b *testing.B) {
// No context name required as collector source is WMI // No context name required as Collector source is WMI
testutils.FuncBenchmarkCollector(b, logon.Name, logon.NewWithFlags) testutils.FuncBenchmarkCollector(b, logon.Name, logon.NewWithFlags)
} }

View File

@ -57,70 +57,68 @@ import (
"github.com/prometheus-community/windows_exporter/pkg/collector/time" "github.com/prometheus-community/windows_exporter/pkg/collector/time"
"github.com/prometheus-community/windows_exporter/pkg/collector/vmware" "github.com/prometheus-community/windows_exporter/pkg/collector/vmware"
"github.com/prometheus-community/windows_exporter/pkg/collector/vmware_blast" "github.com/prometheus-community/windows_exporter/pkg/collector/vmware_blast"
"github.com/prometheus-community/windows_exporter/pkg/types"
"golang.org/x/exp/maps" "golang.org/x/exp/maps"
) )
var Map = map[string]types.CollectorBuilderWithFlags{ var BuildersWithFlags = map[string]BuilderWithFlags[Collector]{
ad.Name: ad.NewWithFlags, ad.Name: NewBuilderWithFlags(ad.NewWithFlags),
adcs.Name: adcs.NewWithFlags, adcs.Name: NewBuilderWithFlags(adcs.NewWithFlags),
adfs.Name: adfs.NewWithFlags, adfs.Name: NewBuilderWithFlags(adfs.NewWithFlags),
cache.Name: cache.NewWithFlags, cache.Name: NewBuilderWithFlags(cache.NewWithFlags),
container.Name: container.NewWithFlags, container.Name: NewBuilderWithFlags(container.NewWithFlags),
cpu.Name: cpu.NewWithFlags, cpu.Name: NewBuilderWithFlags(cpu.NewWithFlags),
cpu_info.Name: cpu_info.NewWithFlags, cpu_info.Name: NewBuilderWithFlags(cpu_info.NewWithFlags),
cs.Name: cs.NewWithFlags, cs.Name: NewBuilderWithFlags(cs.NewWithFlags),
dfsr.Name: dfsr.NewWithFlags, dfsr.Name: NewBuilderWithFlags(dfsr.NewWithFlags),
dhcp.Name: dhcp.NewWithFlags, dhcp.Name: NewBuilderWithFlags(dhcp.NewWithFlags),
diskdrive.Name: diskdrive.NewWithFlags, diskdrive.Name: NewBuilderWithFlags(diskdrive.NewWithFlags),
dns.Name: dns.NewWithFlags, dns.Name: NewBuilderWithFlags(dns.NewWithFlags),
exchange.Name: exchange.NewWithFlags, exchange.Name: NewBuilderWithFlags(exchange.NewWithFlags),
fsrmquota.Name: fsrmquota.NewWithFlags, fsrmquota.Name: NewBuilderWithFlags(fsrmquota.NewWithFlags),
hyperv.Name: hyperv.NewWithFlags, hyperv.Name: NewBuilderWithFlags(hyperv.NewWithFlags),
iis.Name: iis.NewWithFlags, iis.Name: NewBuilderWithFlags(iis.NewWithFlags),
license.Name: license.NewWithFlags, license.Name: NewBuilderWithFlags(license.NewWithFlags),
logical_disk.Name: logical_disk.NewWithFlags, logical_disk.Name: NewBuilderWithFlags(logical_disk.NewWithFlags),
logon.Name: logon.NewWithFlags, logon.Name: NewBuilderWithFlags(logon.NewWithFlags),
memory.Name: memory.NewWithFlags, memory.Name: NewBuilderWithFlags(memory.NewWithFlags),
mscluster_cluster.Name: mscluster_cluster.NewWithFlags, mscluster_cluster.Name: NewBuilderWithFlags(mscluster_cluster.NewWithFlags),
mscluster_network.Name: mscluster_network.NewWithFlags, mscluster_network.Name: NewBuilderWithFlags(mscluster_network.NewWithFlags),
mscluster_node.Name: mscluster_node.NewWithFlags, mscluster_node.Name: NewBuilderWithFlags(mscluster_node.NewWithFlags),
mscluster_resource.Name: mscluster_resource.NewWithFlags, mscluster_resource.Name: NewBuilderWithFlags(mscluster_resource.NewWithFlags),
mscluster_resourcegroup.Name: mscluster_resourcegroup.NewWithFlags, mscluster_resourcegroup.Name: NewBuilderWithFlags(mscluster_resourcegroup.NewWithFlags),
msmq.Name: msmq.NewWithFlags, msmq.Name: NewBuilderWithFlags(msmq.NewWithFlags),
mssql.Name: mssql.NewWithFlags, mssql.Name: NewBuilderWithFlags(mssql.NewWithFlags),
net.Name: net.NewWithFlags, net.Name: NewBuilderWithFlags(net.NewWithFlags),
netframework_clrexceptions.Name: netframework_clrexceptions.NewWithFlags, netframework_clrexceptions.Name: NewBuilderWithFlags(netframework_clrexceptions.NewWithFlags),
netframework_clrinterop.Name: netframework_clrinterop.NewWithFlags, netframework_clrinterop.Name: NewBuilderWithFlags(netframework_clrinterop.NewWithFlags),
netframework_clrjit.Name: netframework_clrjit.NewWithFlags, netframework_clrjit.Name: NewBuilderWithFlags(netframework_clrjit.NewWithFlags),
netframework_clrloading.Name: netframework_clrloading.NewWithFlags, netframework_clrloading.Name: NewBuilderWithFlags(netframework_clrloading.NewWithFlags),
netframework_clrlocksandthreads.Name: netframework_clrlocksandthreads.NewWithFlags, netframework_clrlocksandthreads.Name: NewBuilderWithFlags(netframework_clrlocksandthreads.NewWithFlags),
netframework_clrmemory.Name: netframework_clrmemory.NewWithFlags, netframework_clrmemory.Name: NewBuilderWithFlags(netframework_clrmemory.NewWithFlags),
netframework_clrremoting.Name: netframework_clrremoting.NewWithFlags, netframework_clrremoting.Name: NewBuilderWithFlags(netframework_clrremoting.NewWithFlags),
netframework_clrsecurity.Name: netframework_clrsecurity.NewWithFlags, netframework_clrsecurity.Name: NewBuilderWithFlags(netframework_clrsecurity.NewWithFlags),
nps.Name: nps.NewWithFlags, nps.Name: NewBuilderWithFlags(nps.NewWithFlags),
os.Name: os.NewWithFlags, os.Name: NewBuilderWithFlags(os.NewWithFlags),
physical_disk.Name: physical_disk.NewWithFlags, physical_disk.Name: NewBuilderWithFlags(physical_disk.NewWithFlags),
printer.Name: printer.NewWithFlags, printer.Name: NewBuilderWithFlags(printer.NewWithFlags),
process.Name: process.NewWithFlags, process.Name: NewBuilderWithFlags(process.NewWithFlags),
remote_fx.Name: remote_fx.NewWithFlags, remote_fx.Name: NewBuilderWithFlags(remote_fx.NewWithFlags),
scheduled_task.Name: scheduled_task.NewWithFlags, scheduled_task.Name: NewBuilderWithFlags(scheduled_task.NewWithFlags),
service.Name: service.NewWithFlags, service.Name: NewBuilderWithFlags(service.NewWithFlags),
smb.Name: smb.NewWithFlags, smb.Name: NewBuilderWithFlags(smb.NewWithFlags),
smbclient.Name: smbclient.NewWithFlags, smbclient.Name: NewBuilderWithFlags(smbclient.NewWithFlags),
smtp.Name: smtp.NewWithFlags, smtp.Name: NewBuilderWithFlags(smtp.NewWithFlags),
system.Name: system.NewWithFlags, system.Name: NewBuilderWithFlags(system.NewWithFlags),
teradici_pcoip.Name: teradici_pcoip.NewWithFlags, teradici_pcoip.Name: NewBuilderWithFlags(teradici_pcoip.NewWithFlags),
tcp.Name: tcp.NewWithFlags, tcp.Name: NewBuilderWithFlags(tcp.NewWithFlags),
terminal_services.Name: terminal_services.NewWithFlags, terminal_services.Name: NewBuilderWithFlags(terminal_services.NewWithFlags),
textfile.Name: textfile.NewWithFlags, textfile.Name: NewBuilderWithFlags(textfile.NewWithFlags),
thermalzone.Name: thermalzone.NewWithFlags, thermalzone.Name: NewBuilderWithFlags(thermalzone.NewWithFlags),
time.Name: time.NewWithFlags, time.Name: NewBuilderWithFlags(time.NewWithFlags),
vmware.Name: vmware.NewWithFlags, vmware.Name: NewBuilderWithFlags(vmware.NewWithFlags),
vmware_blast.Name: vmware_blast.NewWithFlags, vmware_blast.Name: NewBuilderWithFlags(vmware_blast.NewWithFlags),
} }
func Available() []string { func Available() []string {
return maps.Keys(Map) return maps.Keys(BuildersWithFlags)
} }

View File

@ -20,8 +20,8 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
// A collector is a Prometheus collector for perflib Memory metrics // A Collector is a Prometheus Collector for perflib Memory metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
AvailableBytes *prometheus.Desc AvailableBytes *prometheus.Desc
@ -58,29 +58,34 @@ type collector struct {
WriteCopiesTotal *prometheus.Desc WriteCopiesTotal *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{"Memory"}, nil return []string{"Memory"}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.AvailableBytes = prometheus.NewDesc( c.AvailableBytes = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "available_bytes"), prometheus.BuildFQName(types.Namespace, Name, "available_bytes"),
"The amount of physical memory immediately available for allocation to a process or for system use. It is equal to the sum of memory assigned to"+ "The amount of physical memory immediately available for allocation to a process or for system use. It is equal to the sum of memory assigned to"+
@ -290,7 +295,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collect(ctx, ch); err != nil { if err := c.collect(ctx, ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting memory metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting memory metrics", "err", err)
return err return err
@ -335,7 +340,7 @@ type memory struct {
WriteCopiesPersec float64 `perflib:"Write Copies/sec"` WriteCopiesPersec float64 `perflib:"Write Copies/sec"`
} }
func (c *collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var dst []memory var dst []memory
if err := perflib.UnmarshalObject(ctx.PerfObjects["Memory"], &dst, c.logger); err != nil { if err := perflib.UnmarshalObject(ctx.PerfObjects["Memory"], &dst, c.logger); err != nil {
return err return err

View File

@ -1,11 +1,10 @@
package mscluster_cluster package mscluster_cluster
import ( import (
"github.com/prometheus-community/windows_exporter/pkg/types"
"github.com/prometheus-community/windows_exporter/pkg/wmi"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/prometheus-community/windows_exporter/pkg/types"
"github.com/prometheus-community/windows_exporter/pkg/wmi"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -15,8 +14,8 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
// A collector is a Prometheus collector for WMI MSCluster_Cluster metrics // A Collector is a Prometheus Collector for WMI MSCluster_Cluster metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
AddEvictDelay *prometheus.Desc AddEvictDelay *prometheus.Desc
@ -98,29 +97,34 @@ type collector struct {
WitnessRestartInterval *prometheus.Desc WitnessRestartInterval *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{"Memory"}, nil return []string{"Memory"}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.AddEvictDelay = prometheus.NewDesc( c.AddEvictDelay = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "add_evict_delay"), prometheus.BuildFQName(types.Namespace, Name, "add_evict_delay"),
"Provides access to the cluster's AddEvictDelay property, which is the number a seconds that a new node is delayed after an eviction of another node.", "Provides access to the cluster's AddEvictDelay property, which is the number a seconds that a new node is delayed after an eviction of another node.",
@ -672,7 +676,7 @@ type MSCluster_Cluster struct {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var dst []MSCluster_Cluster var dst []MSCluster_Cluster
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.QueryNamespace(q, &dst, "root/MSCluster"); err != nil { if err := wmi.QueryNamespace(q, &dst, "root/MSCluster"); err != nil {
@ -680,7 +684,6 @@ func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric)
} }
for _, v := range dst { for _, v := range dst {
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.AddEvictDelay, c.AddEvictDelay,
prometheus.GaugeValue, prometheus.GaugeValue,
@ -1219,7 +1222,6 @@ func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric)
float64(v.WitnessRestartInterval), float64(v.WitnessRestartInterval),
v.Name, v.Name,
) )
} }
return nil return nil

View File

@ -1,11 +1,10 @@
package mscluster_network package mscluster_network
import ( import (
"github.com/prometheus-community/windows_exporter/pkg/types"
"github.com/prometheus-community/windows_exporter/pkg/wmi"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/prometheus-community/windows_exporter/pkg/types"
"github.com/prometheus-community/windows_exporter/pkg/wmi"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -15,8 +14,8 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
// A collector is a Prometheus collector for WMI MSCluster_Network metrics // A Collector is a Prometheus Collector for WMI MSCluster_Network metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
Characteristics *prometheus.Desc Characteristics *prometheus.Desc
@ -26,29 +25,34 @@ type collector struct {
State *prometheus.Desc State *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{"Memory"}, nil return []string{"Memory"}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.Characteristics = prometheus.NewDesc( c.Characteristics = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "characteristics"), prometheus.BuildFQName(types.Namespace, Name, "characteristics"),
"Provides the characteristics of the network.", "Provides the characteristics of the network.",
@ -96,7 +100,7 @@ type MSCluster_Network struct {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var dst []MSCluster_Network var dst []MSCluster_Network
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.QueryNamespace(q, &dst, "root/MSCluster"); err != nil { if err := wmi.QueryNamespace(q, &dst, "root/MSCluster"); err != nil {

View File

@ -1,11 +1,10 @@
package mscluster_node package mscluster_node
import ( import (
"github.com/prometheus-community/windows_exporter/pkg/types"
"github.com/prometheus-community/windows_exporter/pkg/wmi"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/prometheus-community/windows_exporter/pkg/types"
"github.com/prometheus-community/windows_exporter/pkg/wmi"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -18,8 +17,8 @@ var ConfigDefaults = Config{}
// Variable used by mscluster_resource and mscluster_resourcegroup // Variable used by mscluster_resource and mscluster_resourcegroup
var NodeName []string var NodeName []string
// A collector is a Prometheus collector for WMI MSCluster_Node metrics // A Collector is a Prometheus Collector for WMI MSCluster_Node metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
BuildNumber *prometheus.Desc BuildNumber *prometheus.Desc
@ -38,29 +37,34 @@ type collector struct {
StatusInformation *prometheus.Desc StatusInformation *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{"Memory"}, nil return []string{"Memory"}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.BuildNumber = prometheus.NewDesc( c.BuildNumber = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "build_number"), prometheus.BuildFQName(types.Namespace, Name, "build_number"),
"Provides access to the node's BuildNumber property.", "Provides access to the node's BuildNumber property.",
@ -171,7 +175,7 @@ type MSCluster_Node struct {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var dst []MSCluster_Node var dst []MSCluster_Node
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.QueryNamespace(q, &dst, "root/MSCluster"); err != nil { if err := wmi.QueryNamespace(q, &dst, "root/MSCluster"); err != nil {
@ -181,7 +185,6 @@ func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric)
NodeName = []string{} NodeName = []string{}
for _, v := range dst { for _, v := range dst {
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.BuildNumber, c.BuildNumber,
prometheus.GaugeValue, prometheus.GaugeValue,

View File

@ -1,12 +1,11 @@
package mscluster_resource package mscluster_resource
import ( import (
"github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log"
"github.com/prometheus-community/windows_exporter/pkg/collector/mscluster_node" "github.com/prometheus-community/windows_exporter/pkg/collector/mscluster_node"
"github.com/prometheus-community/windows_exporter/pkg/types" "github.com/prometheus-community/windows_exporter/pkg/types"
"github.com/prometheus-community/windows_exporter/pkg/wmi" "github.com/prometheus-community/windows_exporter/pkg/wmi"
"github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -16,8 +15,8 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
// A collector is a Prometheus collector for WMI MSCluster_Resource metrics // A Collector is a Prometheus Collector for WMI MSCluster_Resource metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
Characteristics *prometheus.Desc Characteristics *prometheus.Desc
@ -39,29 +38,34 @@ type collector struct {
Subclass *prometheus.Desc Subclass *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{"Memory"}, nil return []string{"Memory"}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.Characteristics = prometheus.NewDesc( c.Characteristics = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "characteristics"), prometheus.BuildFQName(types.Namespace, Name, "characteristics"),
"Provides the characteristics of the object.", "Provides the characteristics of the object.",
@ -201,7 +205,7 @@ type MSCluster_Resource struct {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var dst []MSCluster_Resource var dst []MSCluster_Resource
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.QueryNamespace(q, &dst, "root/MSCluster"); err != nil { if err := wmi.QueryNamespace(q, &dst, "root/MSCluster"); err != nil {
@ -209,7 +213,6 @@ func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric)
} }
for _, v := range dst { for _, v := range dst {
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.Characteristics, c.Characteristics,
prometheus.GaugeValue, prometheus.GaugeValue,

View File

@ -1,12 +1,11 @@
package mscluster_resourcegroup package mscluster_resourcegroup
import ( import (
"github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log"
"github.com/prometheus-community/windows_exporter/pkg/collector/mscluster_node" "github.com/prometheus-community/windows_exporter/pkg/collector/mscluster_node"
"github.com/prometheus-community/windows_exporter/pkg/types" "github.com/prometheus-community/windows_exporter/pkg/types"
"github.com/prometheus-community/windows_exporter/pkg/wmi" "github.com/prometheus-community/windows_exporter/pkg/wmi"
"github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -16,8 +15,8 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
// A collector is a Prometheus collector for WMI MSCluster_ResourceGroup metrics // A Collector is a Prometheus Collector for WMI MSCluster_ResourceGroup metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
AutoFailbackType *prometheus.Desc AutoFailbackType *prometheus.Desc
@ -38,29 +37,34 @@ type collector struct {
State *prometheus.Desc State *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{"Memory"}, nil return []string{"Memory"}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.AutoFailbackType = prometheus.NewDesc( c.AutoFailbackType = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "auto_failback_type"), prometheus.BuildFQName(types.Namespace, Name, "auto_failback_type"),
"Provides access to the group's AutoFailbackType property.", "Provides access to the group's AutoFailbackType property.",
@ -177,7 +181,7 @@ type MSCluster_ResourceGroup struct {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var dst []MSCluster_ResourceGroup var dst []MSCluster_ResourceGroup
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.QueryNamespace(q, &dst, "root/MSCluster"); err != nil { if err := wmi.QueryNamespace(q, &dst, "root/MSCluster"); err != nil {
@ -185,7 +189,6 @@ func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric)
} }
for _, v := range dst { for _, v := range dst {
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.AutoFailbackType, c.AutoFailbackType,
prometheus.GaugeValue, prometheus.GaugeValue,
@ -291,7 +294,6 @@ func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric)
float64(v.State), float64(v.State),
v.Name, v.Name,
) )
} }
return nil return nil

View File

@ -14,10 +14,7 @@ import (
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
const ( const Name = "msmq"
Name = "msmq"
FlagMsmqWhereClause = "collector.msmq.msmq-where"
)
type Config struct { type Config struct {
QueryWhereClause string `yaml:"query_where_clause"` QueryWhereClause string `yaml:"query_where_clause"`
@ -27,8 +24,8 @@ var ConfigDefaults = Config{
QueryWhereClause: "", QueryWhereClause: "",
} }
// A collector is a Prometheus collector for WMI Win32_PerfRawData_MSMQ_MSMQQueue metrics // A Collector is a Prometheus Collector for WMI Win32_PerfRawData_MSMQ_MSMQQueue metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
queryWhereClause *string queryWhereClause *string
@ -39,39 +36,44 @@ type collector struct {
MessagesinQueue *prometheus.Desc MessagesinQueue *prometheus.Desc
} }
func New(logger log.Logger, config *Config) types.Collector { func New(logger log.Logger, config *Config) *Collector {
if config == nil { if config == nil {
config = &ConfigDefaults config = &ConfigDefaults
} }
c := &collector{ c := &Collector{
queryWhereClause: &config.QueryWhereClause, queryWhereClause: &config.QueryWhereClause,
} }
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(app *kingpin.Application) types.Collector { func NewWithFlags(app *kingpin.Application) *Collector {
return &collector{ return &Collector{
queryWhereClause: app. queryWhereClause: app.
Flag(FlagMsmqWhereClause, "WQL 'where' clause to use in WMI metrics query. Limits the response to the msmqs you specify and reduces the size of the response."). Flag("collector.msmq.msmq-where", "WQL 'where' clause to use in WMI metrics query. Limits the response to the msmqs you specify and reduces the size of the response.").
Default(ConfigDefaults.QueryWhereClause).String(), Default(ConfigDefaults.QueryWhereClause).String(),
} }
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{}, nil return []string{}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
if utils.IsEmpty(c.queryWhereClause) { if utils.IsEmpty(c.queryWhereClause) {
_ = level.Warn(c.logger).Log("msg", "No where-clause specified for msmq collector. This will generate a very large number of metrics!") _ = level.Warn(c.logger).Log("msg", "No where-clause specified for msmq collector. This will generate a very large number of metrics!")
} }
@ -105,7 +107,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collect(ch); err != nil { if err := c.collect(ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting msmq metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting msmq metrics", "err", err)
return err return err
@ -122,7 +124,7 @@ type Win32_PerfRawData_MSMQ_MSMQQueue struct {
MessagesinQueue uint64 MessagesinQueue uint64
} }
func (c *collector) collect(ch chan<- prometheus.Metric) error { func (c *Collector) collect(ch chan<- prometheus.Metric) error {
var dst []Win32_PerfRawData_MSMQ_MSMQQueue var dst []Win32_PerfRawData_MSMQ_MSMQQueue
q := wmi.QueryAllWhere(&dst, *c.queryWhereClause, c.logger) q := wmi.QueryAllWhere(&dst, *c.queryWhereClause, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {

View File

@ -8,6 +8,6 @@ import (
) )
func BenchmarkCollector(b *testing.B) { func BenchmarkCollector(b *testing.B) {
// No context name required as collector source is WMI // No context name required as Collector source is WMI
testutils.FuncBenchmarkCollector(b, msmq.Name, msmq.NewWithFlags) testutils.FuncBenchmarkCollector(b, msmq.Name, msmq.NewWithFlags)
} }

View File

@ -20,11 +20,7 @@ import (
"golang.org/x/sys/windows/registry" "golang.org/x/sys/windows/registry"
) )
const ( const Name = "mssql"
Name = "mssql"
FlagMssqlEnabledCollectors = "collectors.mssql.classes-enabled"
FlagMssqlPrintCollectors = "collectors.mssql.class-print"
)
type Config struct { type Config struct {
EnabledCollectors string `yaml:"collectors_enabled"` EnabledCollectors string `yaml:"collectors_enabled"`
@ -75,7 +71,7 @@ func getMSSQLInstances(logger log.Logger) mssqlInstancesType {
type mssqlCollectorsMap map[string]mssqlCollectorFunc type mssqlCollectorsMap map[string]mssqlCollectorFunc
func (c *collector) getMSSQLCollectors() mssqlCollectorsMap { func (c *Collector) getMSSQLCollectors() mssqlCollectorsMap {
mssqlCollectors := make(mssqlCollectorsMap) mssqlCollectors := make(mssqlCollectorsMap)
mssqlCollectors["accessmethods"] = c.collectAccessMethods mssqlCollectors["accessmethods"] = c.collectAccessMethods
mssqlCollectors["availreplica"] = c.collectAvailabilityReplica mssqlCollectors["availreplica"] = c.collectAvailabilityReplica
@ -94,7 +90,7 @@ func (c *collector) getMSSQLCollectors() mssqlCollectorsMap {
} }
// mssqlGetPerfObjectName - Returns the name of the Windows Performance // mssqlGetPerfObjectName - Returns the name of the Windows Performance
// Counter object for the given SQL instance and collector. // Counter object for the given SQL instance and Collector.
func mssqlGetPerfObjectName(sqlInstance string, collector string) string { func mssqlGetPerfObjectName(sqlInstance string, collector string) string {
prefix := "SQLServer:" prefix := "SQLServer:"
if sqlInstance != "MSSQLSERVER" { if sqlInstance != "MSSQLSERVER" {
@ -130,8 +126,8 @@ func mssqlGetPerfObjectName(sqlInstance string, collector string) string {
return prefix + suffix return prefix + suffix
} }
// A collector is a Prometheus collector for various WMI Win32_PerfRawData_MSSQLSERVER_* metrics // A Collector is a Prometheus Collector for various WMI Win32_PerfRawData_MSSQLSERVER_* metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
mssqlEnabledCollectors *string mssqlEnabledCollectors *string
@ -407,44 +403,45 @@ type collector struct {
mssqlChildCollectorFailure int mssqlChildCollectorFailure int
} }
func New(logger log.Logger, config *Config) types.Collector { func New(logger log.Logger, config *Config) *Collector {
if config == nil { if config == nil {
config = &ConfigDefaults config = &ConfigDefaults
} }
printCollectors := false printCollectors := false
c := &collector{ c := &Collector{
mssqlEnabledCollectors: &config.EnabledCollectors, mssqlEnabledCollectors: &config.EnabledCollectors,
mssqlPrintCollectors: &printCollectors, mssqlPrintCollectors: &printCollectors,
} }
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(app *kingpin.Application) types.Collector { func NewWithFlags(app *kingpin.Application) *Collector {
return &collector{ return &Collector{
mssqlEnabledCollectors: app.Flag( mssqlEnabledCollectors: app.Flag(
FlagMssqlEnabledCollectors, "collectors.mssql.classes-enabled",
"Comma-separated list of mssql WMI classes to use."). "Comma-separated list of mssql WMI classes to use.").
Default(ConfigDefaults.EnabledCollectors).String(), Default(ConfigDefaults.EnabledCollectors).String(),
mssqlPrintCollectors: app.Flag( mssqlPrintCollectors: app.Flag(
FlagMssqlPrintCollectors, "collectors.mssql.class-print",
"If true, print available mssql WMI classes and exit. Only displays if the mssql collector is enabled.", "If true, print available mssql WMI classes and exit. Only displays if the mssql collector is enabled.",
).Bool(), ).Bool(),
} }
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
enabled := utils.ExpandEnabledChildCollectors(*c.mssqlEnabledCollectors) enabled := utils.ExpandEnabledChildCollectors(*c.mssqlEnabledCollectors)
c.mssqlInstances = getMSSQLInstances(c.logger) c.mssqlInstances = getMSSQLInstances(c.logger)
perfCounters := make([]string, 0, len(c.mssqlInstances)*len(enabled)) perfCounters := make([]string, 0, len(c.mssqlInstances)*len(enabled))
@ -457,7 +454,11 @@ func (c *collector) GetPerfCounter() ([]string, error) {
return perfCounters, nil return perfCounters, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
// meta // meta
c.mssqlScrapeDurationDesc = prometheus.NewDesc( c.mssqlScrapeDurationDesc = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "collector_duration_seconds"), prometheus.BuildFQName(types.Namespace, Name, "collector_duration_seconds"),
@ -1922,10 +1923,11 @@ func (c *collector) Build() error {
c.mssqlCollectors = c.getMSSQLCollectors() c.mssqlCollectors = c.getMSSQLCollectors()
if *c.mssqlPrintCollectors { if *c.mssqlPrintCollectors {
fmt.Printf("Available SQLServer Classes:\n") fmt.Printf("Available SQLServer Classes:\n") //nolint:forbidigo
for name := range c.mssqlCollectors { for name := range c.mssqlCollectors {
fmt.Printf(" - %s\n", name) fmt.Printf(" - %s\n", name) //nolint:forbidigo
} }
os.Exit(0) os.Exit(0)
} }
@ -1934,7 +1936,7 @@ func (c *collector) Build() error {
type mssqlCollectorFunc func(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error type mssqlCollectorFunc func(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error
func (c *collector) execute(ctx *types.ScrapeContext, name string, fn mssqlCollectorFunc, ch chan<- prometheus.Metric, sqlInstance string, wg *sync.WaitGroup) { func (c *Collector) execute(ctx *types.ScrapeContext, name string, fn mssqlCollectorFunc, ch chan<- prometheus.Metric, sqlInstance string, wg *sync.WaitGroup) {
// Reset failure counter on each scrape // Reset failure counter on each scrape
c.mssqlChildCollectorFailure = 0 c.mssqlChildCollectorFailure = 0
defer wg.Done() defer wg.Done()
@ -1968,7 +1970,7 @@ func (c *collector) execute(ctx *types.ScrapeContext, name string, fn mssqlColle
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
wg := sync.WaitGroup{} wg := sync.WaitGroup{}
enabled := utils.ExpandEnabledChildCollectors(*c.mssqlEnabledCollectors) enabled := utils.ExpandEnabledChildCollectors(*c.mssqlEnabledCollectors)
@ -2038,7 +2040,7 @@ type mssqlAccessMethods struct {
WorktablesFromCacheRatio_Base float64 `perflib:"Worktables From Cache Base_Base"` WorktablesFromCacheRatio_Base float64 `perflib:"Worktables From Cache Base_Base"`
} }
func (c *collector) collectAccessMethods(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error { func (c *Collector) collectAccessMethods(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error {
var dst []mssqlAccessMethods var dst []mssqlAccessMethods
_ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_accessmethods collector iterating sql instance %s.", sqlInstance)) _ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_accessmethods collector iterating sql instance %s.", sqlInstance))
@ -2373,7 +2375,7 @@ type mssqlAvailabilityReplica struct {
SendstoTransportPersec float64 `perflib:"Sends to Transport/sec"` SendstoTransportPersec float64 `perflib:"Sends to Transport/sec"`
} }
func (c *collector) collectAvailabilityReplica(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error { func (c *Collector) collectAvailabilityReplica(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error {
var dst []mssqlAvailabilityReplica var dst []mssqlAvailabilityReplica
_ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_availreplica collector iterating sql instance %s.", sqlInstance)) _ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_availreplica collector iterating sql instance %s.", sqlInstance))
@ -2481,7 +2483,7 @@ type mssqlBufferManager struct {
Targetpages float64 `perflib:"Target pages"` Targetpages float64 `perflib:"Target pages"`
} }
func (c *collector) collectBufferManager(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error { func (c *Collector) collectBufferManager(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error {
var dst []mssqlBufferManager var dst []mssqlBufferManager
_ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_bufman collector iterating sql instance %s.", sqlInstance)) _ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_bufman collector iterating sql instance %s.", sqlInstance))
@ -2685,7 +2687,7 @@ type mssqlDatabaseReplica struct {
TransactionDelay float64 `perflib:"Transaction Delay"` TransactionDelay float64 `perflib:"Transaction Delay"`
} }
func (c *collector) collectDatabaseReplica(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error { func (c *Collector) collectDatabaseReplica(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error {
var dst []mssqlDatabaseReplica var dst []mssqlDatabaseReplica
_ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_dbreplica collector iterating sql instance %s.", sqlInstance)) _ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_dbreplica collector iterating sql instance %s.", sqlInstance))
@ -2924,7 +2926,7 @@ type mssqlDatabases struct {
XTPMemoryUsedKB float64 `perflib:"XTP Memory Used (KB)"` XTPMemoryUsedKB float64 `perflib:"XTP Memory Used (KB)"`
} }
func (c *collector) collectDatabases(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error { func (c *Collector) collectDatabases(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error {
var dst []mssqlDatabases var dst []mssqlDatabases
_ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_databases collector iterating sql instance %s.", sqlInstance)) _ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_databases collector iterating sql instance %s.", sqlInstance))
@ -3306,7 +3308,7 @@ type mssqlGeneralStatistics struct {
UserConnections float64 `perflib:"User Connections"` UserConnections float64 `perflib:"User Connections"`
} }
func (c *collector) collectGeneralStatistics(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error { func (c *Collector) collectGeneralStatistics(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error {
var dst []mssqlGeneralStatistics var dst []mssqlGeneralStatistics
_ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_genstats collector iterating sql instance %s.", sqlInstance)) _ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_genstats collector iterating sql instance %s.", sqlInstance))
@ -3501,7 +3503,7 @@ type mssqlLocks struct {
NumberofDeadlocksPersec float64 `perflib:"Number of Deadlocks/sec"` NumberofDeadlocksPersec float64 `perflib:"Number of Deadlocks/sec"`
} }
func (c *collector) collectLocks(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error { func (c *Collector) collectLocks(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error {
var dst []mssqlLocks var dst []mssqlLocks
_ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_locks collector iterating sql instance %s.", sqlInstance)) _ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_locks collector iterating sql instance %s.", sqlInstance))
@ -3599,7 +3601,7 @@ type mssqlMemoryManager struct {
TotalServerMemoryKB float64 `perflib:"Total Server Memory (KB)"` TotalServerMemoryKB float64 `perflib:"Total Server Memory (KB)"`
} }
func (c *collector) collectMemoryManager(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error { func (c *Collector) collectMemoryManager(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error {
var dst []mssqlMemoryManager var dst []mssqlMemoryManager
_ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_memmgr collector iterating sql instance %s.", sqlInstance)) _ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_memmgr collector iterating sql instance %s.", sqlInstance))
@ -3768,7 +3770,7 @@ type mssqlSQLStatistics struct {
UnsafeAutoParamsPersec float64 `perflib:"Unsafe Auto-Params/sec"` UnsafeAutoParamsPersec float64 `perflib:"Unsafe Auto-Params/sec"`
} }
func (c *collector) collectSQLStats(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error { func (c *Collector) collectSQLStats(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error {
var dst []mssqlSQLStatistics var dst []mssqlSQLStatistics
_ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_sqlstats collector iterating sql instance %s.", sqlInstance)) _ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_sqlstats collector iterating sql instance %s.", sqlInstance))
@ -3876,7 +3878,7 @@ type mssqlWaitStatistics struct {
WaitStatsTransactionOwnershipWaits float64 `perflib:"Transaction ownership waits"` WaitStatsTransactionOwnershipWaits float64 `perflib:"Transaction ownership waits"`
} }
func (c *collector) collectWaitStats(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error { func (c *Collector) collectWaitStats(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error {
var dst []mssqlWaitStatistics var dst []mssqlWaitStatistics
_ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_waitstats collector iterating sql instance %s.", sqlInstance)) _ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_waitstats collector iterating sql instance %s.", sqlInstance))
@ -3982,7 +3984,7 @@ type mssqlSQLErrors struct {
// Win32_PerfRawData_MSSQLSERVER_SQLServerErrors docs: // Win32_PerfRawData_MSSQLSERVER_SQLServerErrors docs:
// - https://docs.microsoft.com/en-us/sql/relational-databases/performance-monitor/sql-server-sql-errors-object // - https://docs.microsoft.com/en-us/sql/relational-databases/performance-monitor/sql-server-sql-errors-object
func (c *collector) collectSQLErrors(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error { func (c *Collector) collectSQLErrors(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error {
var dst []mssqlSQLErrors var dst []mssqlSQLErrors
_ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_sqlerrors collector iterating sql instance %s.", sqlInstance)) _ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_sqlerrors collector iterating sql instance %s.", sqlInstance))
@ -4025,7 +4027,7 @@ type mssqlTransactions struct {
// Win32_PerfRawData_MSSQLSERVER_Transactions docs: // Win32_PerfRawData_MSSQLSERVER_Transactions docs:
// - https://docs.microsoft.com/en-us/sql/relational-databases/performance-monitor/sql-server-transactions-object // - https://docs.microsoft.com/en-us/sql/relational-databases/performance-monitor/sql-server-transactions-object
func (c *collector) collectTransactions(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error { func (c *Collector) collectTransactions(ctx *types.ScrapeContext, ch chan<- prometheus.Metric, sqlInstance string) error {
var dst []mssqlTransactions var dst []mssqlTransactions
_ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_transactions collector iterating sql instance %s.", sqlInstance)) _ = level.Debug(c.logger).Log("msg", fmt.Sprintf("mssql_transactions collector iterating sql instance %s.", sqlInstance))

View File

@ -14,12 +14,7 @@ import (
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
const ( const Name = "net"
Name = "net"
FlagNicExclude = "collector.net.nic-exclude"
FlagNicInclude = "collector.net.nic-include"
)
type Config struct { type Config struct {
NicInclude string `yaml:"nic_include"` NicInclude string `yaml:"nic_include"`
@ -33,8 +28,8 @@ var ConfigDefaults = Config{
var nicNameToUnderscore = regexp.MustCompile("[^a-zA-Z0-9]") var nicNameToUnderscore = regexp.MustCompile("[^a-zA-Z0-9]")
// A collector is a Prometheus collector for Perflib Network Interface metrics // A Collector is a Prometheus Collector for Perflib Network Interface metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
nicInclude *string nicInclude *string
@ -58,28 +53,29 @@ type collector struct {
nicExcludePattern *regexp.Regexp nicExcludePattern *regexp.Regexp
} }
func New(logger log.Logger, config *Config) types.Collector { func New(logger log.Logger, config *Config) *Collector {
if config == nil { if config == nil {
config = &ConfigDefaults config = &ConfigDefaults
} }
c := &collector{ c := &Collector{
nicExclude: &config.NicExclude, nicExclude: &config.NicExclude,
nicInclude: &config.NicInclude, nicInclude: &config.NicInclude,
} }
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(app *kingpin.Application) types.Collector { func NewWithFlags(app *kingpin.Application) *Collector {
c := &collector{ c := &Collector{
nicInclude: app.Flag( nicInclude: app.Flag(
FlagNicInclude, "collector.net.nic-include",
"Regexp of NIC:s to include. NIC name must both match include and not match exclude to be included.", "Regexp of NIC:s to include. NIC name must both match include and not match exclude to be included.",
).Default(ConfigDefaults.NicInclude).String(), ).Default(ConfigDefaults.NicInclude).String(),
nicExclude: app.Flag( nicExclude: app.Flag(
FlagNicExclude, "collector.net.nic-exclude",
"Regexp of NIC:s to exclude. NIC name must both match include and not match exclude to be included.", "Regexp of NIC:s to exclude. NIC name must both match include and not match exclude to be included.",
).Default(ConfigDefaults.NicExclude).String(), ).Default(ConfigDefaults.NicExclude).String(),
} }
@ -87,19 +83,23 @@ func NewWithFlags(app *kingpin.Application) types.Collector {
return c return c
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{"Network Interface"}, nil return []string{"Network Interface"}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.BytesReceivedTotal = prometheus.NewDesc( c.BytesReceivedTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "bytes_received_total"), prometheus.BuildFQName(types.Namespace, Name, "bytes_received_total"),
"(Network.BytesReceivedPerSec)", "(Network.BytesReceivedPerSec)",
@ -195,7 +195,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collect(ctx, ch); err != nil { if err := c.collect(ctx, ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting net metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting net metrics", "err", err)
return err return err
@ -228,7 +228,7 @@ type networkInterface struct {
CurrentBandwidth float64 `perflib:"Current Bandwidth"` CurrentBandwidth float64 `perflib:"Current Bandwidth"`
} }
func (c *collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var dst []networkInterface var dst []networkInterface
if err := perflib.UnmarshalObject(ctx.PerfObjects["Network Interface"], &dst, c.logger); err != nil { if err := perflib.UnmarshalObject(ctx.PerfObjects["Network Interface"], &dst, c.logger); err != nil {

View File

@ -11,9 +11,9 @@ import (
) )
func BenchmarkCollector(b *testing.B) { func BenchmarkCollector(b *testing.B) {
// Include is not set in testing context (kingpin flags not parsed), causing the collector to skip all interfaces. // PrinterInclude is not set in testing context (kingpin flags not parsed), causing the collector to skip all interfaces.
localNicInclude := ".+" localNicInclude := ".+"
kingpin.CommandLine.GetArg(net.FlagNicInclude).StringVar(&localNicInclude) kingpin.CommandLine.GetArg("collector.net.nic-include").StringVar(&localNicInclude)
testutils.FuncBenchmarkCollector(b, net.Name, net.NewWithFlags) testutils.FuncBenchmarkCollector(b, net.Name, net.NewWithFlags)
} }

View File

@ -3,12 +3,11 @@
package netframework_clrexceptions package netframework_clrexceptions
import ( import (
"github.com/prometheus-community/windows_exporter/pkg/types"
"github.com/prometheus-community/windows_exporter/pkg/wmi"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/go-kit/log/level" "github.com/go-kit/log/level"
"github.com/prometheus-community/windows_exporter/pkg/types"
"github.com/prometheus-community/windows_exporter/pkg/wmi"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -18,52 +17,57 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
// A collector is a Prometheus collector for WMI Win32_PerfRawData_NETFramework_NETCLRExceptions metrics // A Collector is a Prometheus Collector for WMI Win32_PerfRawData_NETFramework_NETCLRExceptions metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
NumberofExcepsThrown *prometheus.Desc NumberOfExceptionsThrown *prometheus.Desc
NumberofFilters *prometheus.Desc NumberOfFilters *prometheus.Desc
NumberofFinallys *prometheus.Desc NumberOfFinally *prometheus.Desc
ThrowToCatchDepth *prometheus.Desc ThrowToCatchDepth *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{}, nil return []string{}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
c.NumberofExcepsThrown = prometheus.NewDesc( return nil
}
func (c *Collector) Build() error {
c.NumberOfExceptionsThrown = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "exceptions_thrown_total"), prometheus.BuildFQName(types.Namespace, Name, "exceptions_thrown_total"),
"Displays the total number of exceptions thrown since the application started. This includes both .NET exceptions and unmanaged exceptions that are converted into .NET exceptions.", "Displays the total number of exceptions thrown since the application started. This includes both .NET exceptions and unmanaged exceptions that are converted into .NET exceptions.",
[]string{"process"}, []string{"process"},
nil, nil,
) )
c.NumberofFilters = prometheus.NewDesc( c.NumberOfFilters = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "exceptions_filters_total"), prometheus.BuildFQName(types.Namespace, Name, "exceptions_filters_total"),
"Displays the total number of .NET exception filters executed. An exception filter evaluates regardless of whether an exception is handled.", "Displays the total number of .NET exception filters executed. An exception filter evaluates regardless of whether an exception is handled.",
[]string{"process"}, []string{"process"},
nil, nil,
) )
c.NumberofFinallys = prometheus.NewDesc( c.NumberOfFinally = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "exceptions_finallys_total"), prometheus.BuildFQName(types.Namespace, Name, "exceptions_finallys_total"),
"Displays the total number of finally blocks executed. Only the finally blocks executed for an exception are counted; finally blocks on normal code paths are not counted by this counter.", "Displays the total number of finally blocks executed. Only the finally blocks executed for an exception are counted; finally blocks on normal code paths are not counted by this counter.",
[]string{"process"}, []string{"process"},
@ -80,7 +84,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collect(ch); err != nil { if err := c.collect(ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting win32_perfrawdata_netframework_netclrexceptions metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting win32_perfrawdata_netframework_netclrexceptions metrics", "err", err)
return err return err
@ -98,7 +102,7 @@ type Win32_PerfRawData_NETFramework_NETCLRExceptions struct {
ThrowToCatchDepthPersec uint32 ThrowToCatchDepthPersec uint32
} }
func (c *collector) collect(ch chan<- prometheus.Metric) error { func (c *Collector) collect(ch chan<- prometheus.Metric) error {
var dst []Win32_PerfRawData_NETFramework_NETCLRExceptions var dst []Win32_PerfRawData_NETFramework_NETCLRExceptions
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -106,27 +110,26 @@ func (c *collector) collect(ch chan<- prometheus.Metric) error {
} }
for _, process := range dst { for _, process := range dst {
if process.Name == "_Global_" { if process.Name == "_Global_" {
continue continue
} }
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.NumberofExcepsThrown, c.NumberOfExceptionsThrown,
prometheus.CounterValue, prometheus.CounterValue,
float64(process.NumberofExcepsThrown), float64(process.NumberofExcepsThrown),
process.Name, process.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.NumberofFilters, c.NumberOfFilters,
prometheus.CounterValue, prometheus.CounterValue,
float64(process.NumberofFiltersPersec), float64(process.NumberofFiltersPersec),
process.Name, process.Name,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.NumberofFinallys, c.NumberOfFinally,
prometheus.CounterValue, prometheus.CounterValue,
float64(process.NumberofFinallysPersec), float64(process.NumberofFinallysPersec),
process.Name, process.Name,

View File

@ -8,6 +8,6 @@ import (
) )
func BenchmarkCollector(b *testing.B) { func BenchmarkCollector(b *testing.B) {
// No context name required as collector source is WMI // No context name required as Collector source is WMI
testutils.FuncBenchmarkCollector(b, netframework_clrexceptions.Name, netframework_clrexceptions.NewWithFlags) testutils.FuncBenchmarkCollector(b, netframework_clrexceptions.Name, netframework_clrexceptions.NewWithFlags)
} }

View File

@ -3,12 +3,11 @@
package netframework_clrinterop package netframework_clrinterop
import ( import (
"github.com/prometheus-community/windows_exporter/pkg/types"
"github.com/prometheus-community/windows_exporter/pkg/wmi"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/go-kit/log/level" "github.com/go-kit/log/level"
"github.com/prometheus-community/windows_exporter/pkg/types"
"github.com/prometheus-community/windows_exporter/pkg/wmi"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -18,8 +17,8 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
// A collector is a Prometheus collector for WMI Win32_PerfRawData_NETFramework_NETCLRInterop metrics // A Collector is a Prometheus Collector for WMI Win32_PerfRawData_NETFramework_NETCLRInterop metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
NumberofCCWs *prometheus.Desc NumberofCCWs *prometheus.Desc
@ -27,29 +26,34 @@ type collector struct {
NumberofStubs *prometheus.Desc NumberofStubs *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{}, nil return []string{}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.NumberofCCWs = prometheus.NewDesc( c.NumberofCCWs = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "com_callable_wrappers_total"), prometheus.BuildFQName(types.Namespace, Name, "com_callable_wrappers_total"),
"Displays the current number of COM callable wrappers (CCWs). A CCW is a proxy for a managed object being referenced from an unmanaged COM client.", "Displays the current number of COM callable wrappers (CCWs). A CCW is a proxy for a managed object being referenced from an unmanaged COM client.",
@ -73,7 +77,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collect(ch); err != nil { if err := c.collect(ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting win32_perfrawdata_netframework_netclrinterop metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting win32_perfrawdata_netframework_netclrinterop metrics", "err", err)
return err return err
@ -91,7 +95,7 @@ type Win32_PerfRawData_NETFramework_NETCLRInterop struct {
NumberofTLBimportsPersec uint32 NumberofTLBimportsPersec uint32
} }
func (c *collector) collect(ch chan<- prometheus.Metric) error { func (c *Collector) collect(ch chan<- prometheus.Metric) error {
var dst []Win32_PerfRawData_NETFramework_NETCLRInterop var dst []Win32_PerfRawData_NETFramework_NETCLRInterop
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -99,7 +103,6 @@ func (c *collector) collect(ch chan<- prometheus.Metric) error {
} }
for _, process := range dst { for _, process := range dst {
if process.Name == "_Global_" { if process.Name == "_Global_" {
continue continue
} }

View File

@ -17,8 +17,8 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
// A collector is a Prometheus collector for WMI Win32_PerfRawData_NETFramework_NETCLRJit metrics // A Collector is a Prometheus Collector for WMI Win32_PerfRawData_NETFramework_NETCLRJit metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
NumberofMethodsJitted *prometheus.Desc NumberofMethodsJitted *prometheus.Desc
@ -27,29 +27,34 @@ type collector struct {
TotalNumberofILBytesJitted *prometheus.Desc TotalNumberofILBytesJitted *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{}, nil return []string{}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.NumberofMethodsJitted = prometheus.NewDesc( c.NumberofMethodsJitted = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "jit_methods_total"), prometheus.BuildFQName(types.Namespace, Name, "jit_methods_total"),
"Displays the total number of methods JIT-compiled since the application started. This counter does not include pre-JIT-compiled methods.", "Displays the total number of methods JIT-compiled since the application started. This counter does not include pre-JIT-compiled methods.",
@ -79,7 +84,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collect(ch); err != nil { if err := c.collect(ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting win32_perfrawdata_netframework_netclrjit metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting win32_perfrawdata_netframework_netclrjit metrics", "err", err)
return err return err
@ -99,7 +104,7 @@ type Win32_PerfRawData_NETFramework_NETCLRJit struct {
TotalNumberofILBytesJitted uint32 TotalNumberofILBytesJitted uint32
} }
func (c *collector) collect(ch chan<- prometheus.Metric) error { func (c *Collector) collect(ch chan<- prometheus.Metric) error {
var dst []Win32_PerfRawData_NETFramework_NETCLRJit var dst []Win32_PerfRawData_NETFramework_NETCLRJit
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -107,7 +112,6 @@ func (c *collector) collect(ch chan<- prometheus.Metric) error {
} }
for _, process := range dst { for _, process := range dst {
if process.Name == "_Global_" { if process.Name == "_Global_" {
continue continue
} }

View File

@ -17,8 +17,8 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
// A collector is a Prometheus collector for WMI Win32_PerfRawData_NETFramework_NETCLRLoading metrics // A Collector is a Prometheus Collector for WMI Win32_PerfRawData_NETFramework_NETCLRLoading metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
BytesinLoaderHeap *prometheus.Desc BytesinLoaderHeap *prometheus.Desc
@ -32,29 +32,34 @@ type collector struct {
TotalNumberofLoadFailures *prometheus.Desc TotalNumberofLoadFailures *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{}, nil return []string{}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.BytesinLoaderHeap = prometheus.NewDesc( c.BytesinLoaderHeap = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "loader_heap_size_bytes"), prometheus.BuildFQName(types.Namespace, Name, "loader_heap_size_bytes"),
"Displays the current size, in bytes, of the memory committed by the class loader across all application domains. Committed memory is the physical space reserved in the disk paging file.", "Displays the current size, in bytes, of the memory committed by the class loader across all application domains. Committed memory is the physical space reserved in the disk paging file.",
@ -114,7 +119,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collect(ch); err != nil { if err := c.collect(ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting win32_perfrawdata_netframework_netclrloading metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting win32_perfrawdata_netframework_netclrloading metrics", "err", err)
return err return err
@ -143,7 +148,7 @@ type Win32_PerfRawData_NETFramework_NETCLRLoading struct {
TotalNumberofLoadFailures uint32 TotalNumberofLoadFailures uint32
} }
func (c *collector) collect(ch chan<- prometheus.Metric) error { func (c *Collector) collect(ch chan<- prometheus.Metric) error {
var dst []Win32_PerfRawData_NETFramework_NETCLRLoading var dst []Win32_PerfRawData_NETFramework_NETCLRLoading
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -151,7 +156,6 @@ func (c *collector) collect(ch chan<- prometheus.Metric) error {
} }
for _, process := range dst { for _, process := range dst {
if process.Name == "_Global_" { if process.Name == "_Global_" {
continue continue
} }

View File

@ -17,8 +17,8 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
// A collector is a Prometheus collector for WMI Win32_PerfRawData_NETFramework_NETCLRLocksAndThreads metrics // A Collector is a Prometheus Collector for WMI Win32_PerfRawData_NETFramework_NETCLRLocksAndThreads metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
CurrentQueueLength *prometheus.Desc CurrentQueueLength *prometheus.Desc
@ -30,29 +30,34 @@ type collector struct {
TotalNumberofContentions *prometheus.Desc TotalNumberofContentions *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{}, nil return []string{}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.CurrentQueueLength = prometheus.NewDesc( c.CurrentQueueLength = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "current_queue_length"), prometheus.BuildFQName(types.Namespace, Name, "current_queue_length"),
"Displays the total number of threads that are currently waiting to acquire a managed lock in the application.", "Displays the total number of threads that are currently waiting to acquire a managed lock in the application.",
@ -100,7 +105,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collect(ch); err != nil { if err := c.collect(ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting win32_perfrawdata_netframework_netclrlocksandthreads metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting win32_perfrawdata_netframework_netclrlocksandthreads metrics", "err", err)
return err return err
@ -123,7 +128,7 @@ type Win32_PerfRawData_NETFramework_NETCLRLocksAndThreads struct {
TotalNumberofContentions uint32 TotalNumberofContentions uint32
} }
func (c *collector) collect(ch chan<- prometheus.Metric) error { func (c *Collector) collect(ch chan<- prometheus.Metric) error {
var dst []Win32_PerfRawData_NETFramework_NETCLRLocksAndThreads var dst []Win32_PerfRawData_NETFramework_NETCLRLocksAndThreads
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -131,7 +136,6 @@ func (c *collector) collect(ch chan<- prometheus.Metric) error {
} }
for _, process := range dst { for _, process := range dst {
if process.Name == "_Global_" { if process.Name == "_Global_" {
continue continue
} }

View File

@ -17,8 +17,8 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
// A collector is a Prometheus collector for WMI Win32_PerfRawData_NETFramework_NETCLRMemory metrics // A Collector is a Prometheus Collector for WMI Win32_PerfRawData_NETFramework_NETCLRMemory metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
AllocatedBytes *prometheus.Desc AllocatedBytes *prometheus.Desc
@ -38,29 +38,34 @@ type collector struct {
PromotedMemoryfromGen1 *prometheus.Desc PromotedMemoryfromGen1 *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{}, nil return []string{}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.AllocatedBytes = prometheus.NewDesc( c.AllocatedBytes = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "allocated_bytes_total"), prometheus.BuildFQName(types.Namespace, Name, "allocated_bytes_total"),
"Displays the total number of bytes allocated on the garbage collection heap.", "Displays the total number of bytes allocated on the garbage collection heap.",
@ -138,7 +143,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collect(ch); err != nil { if err := c.collect(ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting win32_perfrawdata_netframework_netclrmemory metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting win32_perfrawdata_netframework_netclrmemory metrics", "err", err)
return err return err
@ -180,7 +185,7 @@ type Win32_PerfRawData_NETFramework_NETCLRMemory struct {
PromotedMemoryfromGen1 uint64 PromotedMemoryfromGen1 uint64
} }
func (c *collector) collect(ch chan<- prometheus.Metric) error { func (c *Collector) collect(ch chan<- prometheus.Metric) error {
var dst []Win32_PerfRawData_NETFramework_NETCLRMemory var dst []Win32_PerfRawData_NETFramework_NETCLRMemory
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -188,7 +193,6 @@ func (c *collector) collect(ch chan<- prometheus.Metric) error {
} }
for _, process := range dst { for _, process := range dst {
if process.Name == "_Global_" { if process.Name == "_Global_" {
continue continue
} }

View File

@ -17,8 +17,8 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
// A collector is a Prometheus collector for WMI Win32_PerfRawData_NETFramework_NETCLRRemoting metrics // A Collector is a Prometheus Collector for WMI Win32_PerfRawData_NETFramework_NETCLRRemoting metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
Channels *prometheus.Desc Channels *prometheus.Desc
@ -29,29 +29,34 @@ type collector struct {
TotalRemoteCalls *prometheus.Desc TotalRemoteCalls *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{}, nil return []string{}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.Channels = prometheus.NewDesc( c.Channels = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "channels_total"), prometheus.BuildFQName(types.Namespace, Name, "channels_total"),
"Displays the total number of remoting channels registered across all application domains since application started.", "Displays the total number of remoting channels registered across all application domains since application started.",
@ -93,7 +98,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collect(ch); err != nil { if err := c.collect(ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting win32_perfrawdata_netframework_netclrremoting metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting win32_perfrawdata_netframework_netclrremoting metrics", "err", err)
return err return err
@ -113,7 +118,7 @@ type Win32_PerfRawData_NETFramework_NETCLRRemoting struct {
TotalRemoteCalls uint32 TotalRemoteCalls uint32
} }
func (c *collector) collect(ch chan<- prometheus.Metric) error { func (c *Collector) collect(ch chan<- prometheus.Metric) error {
var dst []Win32_PerfRawData_NETFramework_NETCLRRemoting var dst []Win32_PerfRawData_NETFramework_NETCLRRemoting
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -121,7 +126,6 @@ func (c *collector) collect(ch chan<- prometheus.Metric) error {
} }
for _, process := range dst { for _, process := range dst {
if process.Name == "_Global_" { if process.Name == "_Global_" {
continue continue
} }

View File

@ -17,8 +17,8 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
// A collector is a Prometheus collector for WMI Win32_PerfRawData_NETFramework_NETCLRSecurity metrics // A Collector is a Prometheus Collector for WMI Win32_PerfRawData_NETFramework_NETCLRSecurity metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
NumberLinkTimeChecks *prometheus.Desc NumberLinkTimeChecks *prometheus.Desc
@ -27,29 +27,34 @@ type collector struct {
TotalRuntimeChecks *prometheus.Desc TotalRuntimeChecks *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{}, nil return []string{}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.NumberLinkTimeChecks = prometheus.NewDesc( c.NumberLinkTimeChecks = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "link_time_checks_total"), prometheus.BuildFQName(types.Namespace, Name, "link_time_checks_total"),
"Displays the total number of link-time code access security checks since the application started.", "Displays the total number of link-time code access security checks since the application started.",
@ -79,7 +84,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collect(ch); err != nil { if err := c.collect(ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting win32_perfrawdata_netframework_netclrsecurity metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting win32_perfrawdata_netframework_netclrsecurity metrics", "err", err)
return err return err
@ -98,7 +103,7 @@ type Win32_PerfRawData_NETFramework_NETCLRSecurity struct {
TotalRuntimeChecks uint32 TotalRuntimeChecks uint32
} }
func (c *collector) collect(ch chan<- prometheus.Metric) error { func (c *Collector) collect(ch chan<- prometheus.Metric) error {
var dst []Win32_PerfRawData_NETFramework_NETCLRSecurity var dst []Win32_PerfRawData_NETFramework_NETCLRSecurity
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -106,7 +111,6 @@ func (c *collector) collect(ch chan<- prometheus.Metric) error {
} }
for _, process := range dst { for _, process := range dst {
if process.Name == "_Global_" { if process.Name == "_Global_" {
continue continue
} }

View File

@ -17,8 +17,8 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
// collector is a Prometheus collector for WMI Win32_PerfRawData_IAS_NPSAuthenticationServer and Win32_PerfRawData_IAS_NPSAccountingServer metrics // Collector is a Prometheus Collector for WMI Win32_PerfRawData_IAS_NPSAuthenticationServer and Win32_PerfRawData_IAS_NPSAccountingServer metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
AccessAccepts *prometheus.Desc AccessAccepts *prometheus.Desc
@ -49,29 +49,34 @@ type collector struct {
AccountingUnknownType *prometheus.Desc AccountingUnknownType *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{}, nil return []string{}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.AccessAccepts = prometheus.NewDesc( c.AccessAccepts = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "access_accepts"), prometheus.BuildFQName(types.Namespace, Name, "access_accepts"),
"(AccessAccepts)", "(AccessAccepts)",
@ -228,7 +233,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.CollectAccept(ch); err != nil { if err := c.CollectAccept(ch); err != nil {
_ = level.Error(c.logger).Log("msg", fmt.Sprintf("failed collecting NPS accept data: %s", err)) _ = level.Error(c.logger).Log("msg", fmt.Sprintf("failed collecting NPS accept data: %s", err))
return err return err
@ -279,7 +284,7 @@ type Win32_PerfRawData_IAS_NPSAccountingServer struct {
// CollectAccept sends the metric values for each metric // CollectAccept sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) CollectAccept(ch chan<- prometheus.Metric) error { func (c *Collector) CollectAccept(ch chan<- prometheus.Metric) error {
var dst []Win32_PerfRawData_IAS_NPSAuthenticationServer var dst []Win32_PerfRawData_IAS_NPSAuthenticationServer
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -367,7 +372,7 @@ func (c *collector) CollectAccept(ch chan<- prometheus.Metric) error {
return nil return nil
} }
func (c *collector) CollectAccounting(ch chan<- prometheus.Metric) error { func (c *Collector) CollectAccounting(ch chan<- prometheus.Metric) error {
var dst []Win32_PerfRawData_IAS_NPSAccountingServer var dst []Win32_PerfRawData_IAS_NPSAccountingServer
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {

View File

@ -11,16 +11,15 @@ import (
"syscall" "syscall"
"time" "time"
"github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus-community/windows_exporter/pkg/headers/kernel32" "github.com/prometheus-community/windows_exporter/pkg/headers/kernel32"
"github.com/prometheus-community/windows_exporter/pkg/headers/netapi32" "github.com/prometheus-community/windows_exporter/pkg/headers/netapi32"
"github.com/prometheus-community/windows_exporter/pkg/headers/psapi" "github.com/prometheus-community/windows_exporter/pkg/headers/psapi"
"github.com/prometheus-community/windows_exporter/pkg/headers/sysinfoapi" "github.com/prometheus-community/windows_exporter/pkg/headers/sysinfoapi"
"github.com/prometheus-community/windows_exporter/pkg/perflib" "github.com/prometheus-community/windows_exporter/pkg/perflib"
"github.com/prometheus-community/windows_exporter/pkg/types" "github.com/prometheus-community/windows_exporter/pkg/types"
"github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"golang.org/x/sys/windows/registry" "golang.org/x/sys/windows/registry"
) )
@ -31,8 +30,8 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
// A collector is a Prometheus collector for WMI metrics // A Collector is a Prometheus Collector for WMI metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
OSInformation *prometheus.Desc OSInformation *prometheus.Desc
@ -56,29 +55,34 @@ type pagingFileCounter struct {
UsagePeak float64 `perflib:"% Usage Peak"` UsagePeak float64 `perflib:"% Usage Peak"`
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{"Paging File"}, nil return []string{"Paging File"}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.OSInformation = prometheus.NewDesc( c.OSInformation = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "info"), prometheus.BuildFQName(types.Namespace, Name, "info"),
"OperatingSystem.Caption, OperatingSystem.Version", "OperatingSystem.Caption, OperatingSystem.Version",
@ -162,7 +166,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collect(ctx, ch); err != nil { if err := c.collect(ctx, ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting os metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting os metrics", "err", err)
return err return err
@ -188,7 +192,7 @@ type Win32_OperatingSystem struct {
Version string Version string
} }
func (c *collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
nwgi, err := netapi32.GetWorkstationInfo() nwgi, err := netapi32.GetWorkstationInfo()
if err != nil { if err != nil {
return err return err

View File

@ -15,11 +15,7 @@ import (
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
const ( const Name = "physical_disk"
Name = "physical_disk"
FlagPhysicalDiskExclude = "collector.physical_disk.disk-exclude"
FlagPhysicalDiskInclude = "collector.physical_disk.disk-include"
)
type Config struct { type Config struct {
DiskInclude string `yaml:"disk_include"` DiskInclude string `yaml:"disk_include"`
@ -31,8 +27,8 @@ var ConfigDefaults = Config{
DiskExclude: "", DiskExclude: "",
} }
// A collector is a Prometheus collector for perflib PhysicalDisk metrics // A Collector is a Prometheus Collector for perflib PhysicalDisk metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
diskInclude *string diskInclude *string
@ -58,24 +54,25 @@ type collector struct {
diskExcludePattern *regexp.Regexp diskExcludePattern *regexp.Regexp
} }
func New(logger log.Logger, config *Config) types.Collector { func New(logger log.Logger, config *Config) *Collector {
if config == nil { if config == nil {
config = &ConfigDefaults config = &ConfigDefaults
} }
c := &collector{ c := &Collector{
diskExclude: &config.DiskExclude, diskExclude: &config.DiskExclude,
diskInclude: &config.DiskInclude, diskInclude: &config.DiskInclude,
} }
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(app *kingpin.Application) types.Collector { func NewWithFlags(app *kingpin.Application) *Collector {
c := &collector{} c := &Collector{}
c.diskInclude = app.Flag( c.diskInclude = app.Flag(
FlagPhysicalDiskInclude, "collector.physical_disk.disk-include",
"Regexp of disks to include. Disk number must both match include and not match exclude to be included.", "Regexp of disks to include. Disk number must both match include and not match exclude to be included.",
).Default(ConfigDefaults.DiskInclude).PreAction(func(_ *kingpin.ParseContext) error { ).Default(ConfigDefaults.DiskInclude).PreAction(func(_ *kingpin.ParseContext) error {
c.diskIncludeSet = true c.diskIncludeSet = true
@ -83,28 +80,33 @@ func NewWithFlags(app *kingpin.Application) types.Collector {
}).String() }).String()
c.diskExclude = app.Flag( c.diskExclude = app.Flag(
FlagPhysicalDiskExclude, "collector.physical_disk.disk-exclude",
"Regexp of disks to exclude. Disk number must both match include and not match exclude to be included.", "Regexp of disks to exclude. Disk number must both match include and not match exclude to be included.",
).Default(ConfigDefaults.DiskExclude).PreAction(func(_ *kingpin.ParseContext) error { ).Default(ConfigDefaults.DiskExclude).PreAction(func(_ *kingpin.ParseContext) error {
c.diskExcludeSet = true c.diskExcludeSet = true
return nil return nil
}).String() }).String()
return c return c
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{"PhysicalDisk"}, nil return []string{"PhysicalDisk"}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.RequestsQueued = prometheus.NewDesc( c.RequestsQueued = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "requests_queued"), prometheus.BuildFQName(types.Namespace, Name, "requests_queued"),
"The number of requests queued to the disk (PhysicalDisk.CurrentDiskQueueLength)", "The number of requests queued to the disk (PhysicalDisk.CurrentDiskQueueLength)",
@ -205,7 +207,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collect(ctx, ch); err != nil { if err := c.collect(ctx, ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting physical_disk metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting physical_disk metrics", "err", err)
return err return err
@ -232,7 +234,7 @@ type PhysicalDisk struct {
AvgDiskSecPerTransfer float64 `perflib:"Avg. Disk sec/Transfer"` AvgDiskSecPerTransfer float64 `perflib:"Avg. Disk sec/Transfer"`
} }
func (c *collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var dst []PhysicalDisk var dst []PhysicalDisk
if err := perflib.UnmarshalObject(ctx.PerfObjects["PhysicalDisk"], &dst, c.logger); err != nil { if err := perflib.UnmarshalObject(ctx.PerfObjects["PhysicalDisk"], &dst, c.logger); err != nil {
return err return err

View File

@ -10,18 +10,12 @@ import (
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/go-kit/log/level" "github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus-community/windows_exporter/pkg/types" "github.com/prometheus-community/windows_exporter/pkg/types"
"github.com/prometheus-community/windows_exporter/pkg/wmi" "github.com/prometheus-community/windows_exporter/pkg/wmi"
"github.com/prometheus/client_golang/prometheus"
) )
const ( const Name = "printer"
Name = "printer"
FlagPrinterInclude = "collector.printer.include"
FlagPrinterExclude = "collector.printer.exclude"
)
// printerStatusMap source: https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-printer#:~:text=Power%20Save-,PrinterStatus,Offline%20(7),-PrintJobDataType // printerStatusMap source: https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-printer#:~:text=Power%20Save-,PrinterStatus,Offline%20(7),-PrintJobDataType
var printerStatusMap = map[uint16]string{ var printerStatusMap = map[uint16]string{
@ -35,16 +29,16 @@ var printerStatusMap = map[uint16]string{
} }
type Config struct { type Config struct {
Include string `yaml:"printer_include"` PrinterInclude string `yaml:"printer_include"`
Exclude string `yaml:"printer_exclude"` PrinterExclude string `yaml:"printer_exclude"`
} }
var ConfigDefaults = Config{ var ConfigDefaults = Config{
Include: ".+", PrinterInclude: ".+",
Exclude: "", PrinterExclude: "",
} }
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
printerInclude *string printerInclude *string
@ -58,37 +52,44 @@ type collector struct {
printerExcludePattern *regexp.Regexp printerExcludePattern *regexp.Regexp
} }
func New(logger log.Logger, config *Config) types.Collector { func New(logger log.Logger, config *Config) *Collector {
if config == nil { if config == nil {
config = &ConfigDefaults config = &ConfigDefaults
} }
c := &collector{ c := &Collector{
printerInclude: &config.Include, printerInclude: &config.PrinterInclude,
printerExclude: &config.Exclude, printerExclude: &config.PrinterExclude,
} }
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(app *kingpin.Application) types.Collector { func NewWithFlags(app *kingpin.Application) *Collector {
c := &collector{ c := &Collector{
printerInclude: app.Flag( printerInclude: app.Flag(
FlagPrinterInclude, "collector.printer.include",
"Regular expression to match printers to collect metrics for", "Regular expression to match printers to collect metrics for",
).Default(ConfigDefaults.Include).String(), ).Default(ConfigDefaults.PrinterInclude).String(),
printerExclude: app.Flag( printerExclude: app.Flag(
FlagPrinterExclude, "collector.printer.exclude",
"Regular expression to match printers to exclude", "Regular expression to match printers to exclude",
).Default(ConfigDefaults.Exclude).String(), ).Default(ConfigDefaults.PrinterExclude).String(),
} }
return c return c
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.printerJobStatus = prometheus.NewDesc( c.printerJobStatus = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "job_status"), prometheus.BuildFQName(types.Namespace, Name, "job_status"),
"A counter of printer jobs by status", "A counter of printer jobs by status",
@ -117,9 +118,9 @@ func (c *collector) Build() error {
return err return err
} }
func (c *collector) GetName() string { return Name } func (c *Collector) GetName() string { return Name }
func (c *collector) GetPerfCounter() ([]string, error) { return []string{"Printer"}, nil } func (c *Collector) GetPerfCounter() ([]string, error) { return []string{"Printer"}, nil }
type win32_Printer struct { type win32_Printer struct {
Name string Name string
@ -133,7 +134,7 @@ type win32_PrintJob struct {
Status string Status string
} }
func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collectPrinterStatus(ch); err != nil { if err := c.collectPrinterStatus(ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed to collect printer status metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed to collect printer status metrics", "err", err)
return err return err
@ -145,7 +146,7 @@ func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric)
return nil return nil
} }
func (c *collector) collectPrinterStatus(ch chan<- prometheus.Metric) error { func (c *Collector) collectPrinterStatus(ch chan<- prometheus.Metric) error {
var printers []win32_Printer var printers []win32_Printer
q := wmi.QueryAll(&printers, c.logger) q := wmi.QueryAll(&printers, c.logger)
if err := wmi.Query(q, &printers); err != nil { if err := wmi.Query(q, &printers); err != nil {
@ -184,7 +185,7 @@ func (c *collector) collectPrinterStatus(ch chan<- prometheus.Metric) error {
return nil return nil
} }
func (c *collector) collectPrinterJobStatus(ch chan<- prometheus.Metric) error { func (c *Collector) collectPrinterJobStatus(ch chan<- prometheus.Metric) error {
var printJobs []win32_PrintJob var printJobs []win32_PrintJob
q := wmi.QueryAll(&printJobs, c.logger) q := wmi.QueryAll(&printJobs, c.logger)
if err := wmi.Query(q, &printJobs); err != nil { if err := wmi.Query(q, &printJobs); err != nil {
@ -209,7 +210,7 @@ type PrintJobStatusGroup struct {
status string status string
} }
func (c *collector) groupPrintJobs(printJobs []win32_PrintJob) map[PrintJobStatusGroup]int { func (c *Collector) groupPrintJobs(printJobs []win32_PrintJob) map[PrintJobStatusGroup]int {
groupedPrintJobs := make(map[PrintJobStatusGroup]int) groupedPrintJobs := make(map[PrintJobStatusGroup]int)
for _, printJob := range printJobs { for _, printJob := range printJobs {
printerName := strings.Split(printJob.Name, ",")[0] printerName := strings.Split(printJob.Name, ",")[0]

View File

@ -4,7 +4,6 @@ import (
"testing" "testing"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/prometheus-community/windows_exporter/pkg/collector/printer" "github.com/prometheus-community/windows_exporter/pkg/collector/printer"
"github.com/prometheus-community/windows_exporter/pkg/testutils" "github.com/prometheus-community/windows_exporter/pkg/testutils"
) )
@ -12,6 +11,6 @@ import (
func BenchmarkCollector(b *testing.B) { func BenchmarkCollector(b *testing.B) {
// Whitelist is not set in testing context (kingpin flags not parsed), causing the collector to skip all printers. // Whitelist is not set in testing context (kingpin flags not parsed), causing the collector to skip all printers.
printersInclude := ".+" printersInclude := ".+"
kingpin.CommandLine.GetArg(printer.FlagPrinterInclude).StringVar(&printersInclude) kingpin.CommandLine.GetArg("collector.printer.include").StringVar(&printersInclude)
testutils.FuncBenchmarkCollector(b, "printer", printer.NewWithFlags) testutils.FuncBenchmarkCollector(b, "printer", printer.NewWithFlags)
} }

View File

@ -5,7 +5,6 @@ package process
import ( import (
"errors" "errors"
"fmt" "fmt"
"golang.org/x/sys/windows"
"regexp" "regexp"
"strconv" "strconv"
"strings" "strings"
@ -19,15 +18,10 @@ import (
"github.com/prometheus-community/windows_exporter/pkg/utils" "github.com/prometheus-community/windows_exporter/pkg/utils"
"github.com/prometheus-community/windows_exporter/pkg/wmi" "github.com/prometheus-community/windows_exporter/pkg/wmi"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"golang.org/x/sys/windows"
) )
const ( const Name = "process"
Name = "process"
FlagProcessExclude = "collector.process.exclude"
FlagProcessInclude = "collector.process.include"
FlagEnableWorkerProcess = "collector.process.iis"
FlagEnableReportOwner = "collector.process.report-owner"
)
type Config struct { type Config struct {
ProcessInclude string `yaml:"process_include"` ProcessInclude string `yaml:"process_include"`
@ -43,7 +37,7 @@ var ConfigDefaults = Config{
EnableReportOwner: false, EnableReportOwner: false,
} }
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
processInclude *string processInclude *string
@ -74,58 +68,63 @@ type collector struct {
lookupCache map[string]string lookupCache map[string]string
} }
func New(logger log.Logger, config *Config) types.Collector { func New(logger log.Logger, config *Config) *Collector {
if config == nil { if config == nil {
config = &ConfigDefaults config = &ConfigDefaults
} }
c := &collector{ c := &Collector{
processExclude: &config.ProcessExclude, processExclude: &config.ProcessExclude,
processInclude: &config.ProcessInclude, processInclude: &config.ProcessInclude,
enableWorkerProcess: &config.EnableWorkerProcess, enableWorkerProcess: &config.EnableWorkerProcess,
} }
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(app *kingpin.Application) types.Collector { func NewWithFlags(app *kingpin.Application) *Collector {
c := &collector{ c := &Collector{
processInclude: app.Flag( processInclude: app.Flag(
FlagProcessInclude, "collector.process.include",
"Regexp of processes to include. Process name must both match include and not match exclude to be included.", "Regexp of processes to include. Process name must both match include and not match exclude to be included.",
).Default(ConfigDefaults.ProcessInclude).String(), ).Default(ConfigDefaults.ProcessInclude).String(),
processExclude: app.Flag( processExclude: app.Flag(
FlagProcessExclude, "collector.process.exclude",
"Regexp of processes to exclude. Process name must both match include and not match exclude to be included.", "Regexp of processes to exclude. Process name must both match include and not match exclude to be included.",
).Default(ConfigDefaults.ProcessExclude).String(), ).Default(ConfigDefaults.ProcessExclude).String(),
enableWorkerProcess: app.Flag( enableWorkerProcess: app.Flag(
FlagEnableWorkerProcess, "collector.process.iis",
"Enable IIS worker process name queries. May cause the collector to leak memory.", "Enable IIS worker process name queries. May cause the collector to leak memory.",
).Default("false").Bool(), ).Default("false").Bool(),
enableReportOwner: app.Flag( enableReportOwner: app.Flag(
FlagEnableReportOwner, "collector.process.report-owner",
"Enable reporting of process owner.", "Enable reporting of process owner.",
).Default("false").Bool(), ).Default("false").Bool(),
} }
return c return c
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{"Process"}, nil return []string{"Process"}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
if c.processInclude != nil && *c.processInclude == ".*" && utils.IsEmpty(c.processExclude) { if c.processInclude != nil && *c.processInclude == ".*" && utils.IsEmpty(c.processExclude) {
_ = level.Warn(c.logger).Log("msg", "No filters specified for process collector. This will generate a very large number of metrics!") _ = level.Warn(c.logger).Log("msg", "No filters specified for process collector. This will generate a very large number of metrics!")
} }
@ -280,7 +279,7 @@ type WorkerProcess struct {
ProcessId uint64 ProcessId uint64
} }
func (c *collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
data := make([]perflibProcess, 0) data := make([]perflibProcess, 0)
err := perflib.UnmarshalObject(ctx.PerfObjects["Process"], &data, c.logger) err := perflib.UnmarshalObject(ctx.PerfObjects["Process"], &data, c.logger)
if err != nil { if err != nil {
@ -482,7 +481,7 @@ func (c *collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metri
} }
// ref: https://github.com/microsoft/hcsshim/blob/8beabacfc2d21767a07c20f8dd5f9f3932dbf305/internal/uvm/stats.go#L25 // ref: https://github.com/microsoft/hcsshim/blob/8beabacfc2d21767a07c20f8dd5f9f3932dbf305/internal/uvm/stats.go#L25
func (c *collector) getProcessOwner(pid int) (string, error) { func (c *Collector) getProcessOwner(pid int) (string, error) {
p, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid)) p, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid))
if errors.Is(err, syscall.Errno(0x57)) { // invalid parameter, for PIDs that don't exist if errors.Is(err, syscall.Errno(0x57)) { // invalid parameter, for PIDs that don't exist
return "", errors.New("process not found") return "", errors.New("process not found")

View File

@ -9,9 +9,9 @@ import (
) )
func BenchmarkProcessCollector(b *testing.B) { func BenchmarkProcessCollector(b *testing.B) {
// Include is not set in testing context (kingpin flags not parsed), causing the collector to skip all processes. // PrinterInclude is not set in testing context (kingpin flags not parsed), causing the collector to skip all processes.
localProcessInclude := ".+" localProcessInclude := ".+"
kingpin.CommandLine.GetArg(process.FlagProcessInclude).StringVar(&localProcessInclude) kingpin.CommandLine.GetArg("collector.process.include").StringVar(&localProcessInclude)
// No context name required as collector source is WMI // No context name required as collector source is WMI
testutils.FuncBenchmarkCollector(b, process.Name, process.NewWithFlags) testutils.FuncBenchmarkCollector(b, process.Name, process.NewWithFlags)
} }

View File

@ -112,7 +112,7 @@ func (coll *Prometheus) Collect(ch chan<- prometheus.Metric) {
}() }()
for name, c := range coll.collectors.collectors { for name, c := range coll.collectors.collectors {
go func(name string, c types.Collector) { go func(name string, c Collector) {
defer wg.Done() defer wg.Done()
outcome := coll.execute(name, c, scrapeContext, metricsBuffer) outcome := coll.execute(name, c, scrapeContext, metricsBuffer)
l.Lock() l.Lock()
@ -171,7 +171,7 @@ func (coll *Prometheus) Collect(ch chan<- prometheus.Metric) {
l.Unlock() l.Unlock()
} }
func (coll *Prometheus) execute(name string, c types.Collector, ctx *types.ScrapeContext, ch chan<- prometheus.Metric) collectorOutcome { func (coll *Prometheus) execute(name string, c Collector, ctx *types.ScrapeContext, ch chan<- prometheus.Metric) collectorOutcome {
t := time.Now() t := time.Now()
err := c.Collect(ctx, ch) err := c.Collect(ctx, ch)
duration := time.Since(t).Seconds() duration := time.Since(t).Seconds()

View File

@ -20,12 +20,12 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
// collector // Collector
// A RemoteFxNetworkCollector is a Prometheus collector for // A RemoteFxNetworkCollector is a Prometheus Collector for
// WMI Win32_PerfRawData_Counters_RemoteFXNetwork & Win32_PerfRawData_Counters_RemoteFXGraphics metrics // WMI Win32_PerfRawData_Counters_RemoteFXNetwork & Win32_PerfRawData_Counters_RemoteFXGraphics metrics
// https://wutils.com/wmi/root/cimv2/win32_perfrawdata_counters_remotefxnetwork/ // https://wutils.com/wmi/root/cimv2/win32_perfrawdata_counters_remotefxnetwork/
// https://wutils.com/wmi/root/cimv2/win32_perfrawdata_counters_remotefxgraphics/ // https://wutils.com/wmi/root/cimv2/win32_perfrawdata_counters_remotefxgraphics/
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
// net // net
@ -53,29 +53,34 @@ type collector struct {
SourceFramesPerSecond *prometheus.Desc SourceFramesPerSecond *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{"RemoteFX Network", "RemoteFX Graphics"}, nil return []string{"RemoteFX Network", "RemoteFX Graphics"}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
// net // net
c.BaseTCPRTT = prometheus.NewDesc( c.BaseTCPRTT = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "net_base_tcp_rtt_seconds"), prometheus.BuildFQName(types.Namespace, Name, "net_base_tcp_rtt_seconds"),
@ -204,7 +209,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collectRemoteFXNetworkCount(ctx, ch); err != nil { if err := c.collectRemoteFXNetworkCount(ctx, ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting terminal services session count metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting terminal services session count metrics", "err", err)
return err return err
@ -233,7 +238,7 @@ type perflibRemoteFxNetwork struct {
RetransmissionRate float64 `perflib:"Percentage of packets that have been retransmitted"` RetransmissionRate float64 `perflib:"Percentage of packets that have been retransmitted"`
} }
func (c *collector) collectRemoteFXNetworkCount(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collectRemoteFXNetworkCount(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
dst := make([]perflibRemoteFxNetwork, 0) dst := make([]perflibRemoteFxNetwork, 0)
err := perflib.UnmarshalObject(ctx.PerfObjects["RemoteFX Network"], &dst, c.logger) err := perflib.UnmarshalObject(ctx.PerfObjects["RemoteFX Network"], &dst, c.logger)
if err != nil { if err != nil {
@ -343,7 +348,7 @@ type perflibRemoteFxGraphics struct {
SourceFramesPerSecond float64 `perflib:"Source Frames/Second"` SourceFramesPerSecond float64 `perflib:"Source Frames/Second"`
} }
func (c *collector) collectRemoteFXGraphicsCounters(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collectRemoteFXGraphicsCounters(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
dst := make([]perflibRemoteFxGraphics, 0) dst := make([]perflibRemoteFxGraphics, 0)
err := perflib.UnmarshalObject(ctx.PerfObjects["RemoteFX Graphics"], &dst, c.logger) err := perflib.UnmarshalObject(ctx.PerfObjects["RemoteFX Graphics"], &dst, c.logger)
if err != nil { if err != nil {

View File

@ -9,13 +9,12 @@ import (
"runtime" "runtime"
"strings" "strings"
"github.com/prometheus-community/windows_exporter/pkg/types"
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/go-kit/log/level" "github.com/go-kit/log/level"
"github.com/go-ole/go-ole" "github.com/go-ole/go-ole"
"github.com/go-ole/go-ole/oleutil" "github.com/go-ole/go-ole/oleutil"
"github.com/prometheus-community/windows_exporter/pkg/types"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
@ -36,7 +35,7 @@ var ConfigDefaults = Config{
TaskInclude: ".+", TaskInclude: ".+",
} }
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
taskExclude *string taskExclude *string
@ -76,21 +75,22 @@ type ScheduledTask struct {
type ScheduledTasks []ScheduledTask type ScheduledTasks []ScheduledTask
func New(logger log.Logger, config *Config) types.Collector { func New(logger log.Logger, config *Config) *Collector {
if config == nil { if config == nil {
config = &ConfigDefaults config = &ConfigDefaults
} }
c := &collector{ c := &Collector{
taskExclude: &config.TaskExclude, taskExclude: &config.TaskExclude,
taskInclude: &config.TaskInclude, taskInclude: &config.TaskInclude,
} }
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(app *kingpin.Application) types.Collector { func NewWithFlags(app *kingpin.Application) *Collector {
c := &collector{ c := &Collector{
taskInclude: app.Flag( taskInclude: app.Flag(
FlagScheduledTaskInclude, FlagScheduledTaskInclude,
"Regexp of tasks to include. Task path must both match include and not match exclude to be included.", "Regexp of tasks to include. Task path must both match include and not match exclude to be included.",
@ -105,19 +105,23 @@ func NewWithFlags(app *kingpin.Application) types.Collector {
return c return c
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{}, nil return []string{}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.LastResult = prometheus.NewDesc( c.LastResult = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "last_result"), prometheus.BuildFQName(types.Namespace, Name, "last_result"),
"The result that was returned the last time the registered task was run", "The result that was returned the last time the registered task was run",
@ -154,7 +158,7 @@ func (c *collector) Build() error {
return nil return nil
} }
func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collect(ch); err != nil { if err := c.collect(ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting user metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting user metrics", "err", err)
return err return err
@ -165,7 +169,7 @@ func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric)
var TASK_STATES = []string{"disabled", "queued", "ready", "running", "unknown"} var TASK_STATES = []string{"disabled", "queued", "ready", "running", "unknown"}
func (c *collector) collect(ch chan<- prometheus.Metric) error { func (c *Collector) collect(ch chan<- prometheus.Metric) error {
scheduledTasks, err := getScheduledTasks() scheduledTasks, err := getScheduledTasks()
if err != nil { if err != nil {
return err return err
@ -379,7 +383,9 @@ func parseTask(task *ole.IDispatch) (scheduledTask ScheduledTask, err error) {
scheduledTask.Name = taskNameVar.ToString() scheduledTask.Name = taskNameVar.ToString()
scheduledTask.Path = strings.ReplaceAll(taskPathVar.ToString(), "\\", "/") scheduledTask.Path = strings.ReplaceAll(taskPathVar.ToString(), "\\", "/")
scheduledTask.Enabled = taskEnabledVar.Value().(bool) if val, ok := taskEnabledVar.Value().(bool); ok {
scheduledTask.Enabled = val
}
scheduledTask.State = TaskState(taskStateVar.Val) scheduledTask.State = TaskState(taskStateVar.Val)
scheduledTask.MissedRunsCount = float64(taskNumberOfMissedRunsVar.Val) scheduledTask.MissedRunsCount = float64(taskNumberOfMissedRunsVar.Val)
scheduledTask.LastTaskResult = TaskResult(taskLastTaskResultVar.Val) scheduledTask.LastTaskResult = TaskResult(taskLastTaskResultVar.Val)

View File

@ -21,12 +21,7 @@ import (
"golang.org/x/sys/windows/svc/mgr" "golang.org/x/sys/windows/svc/mgr"
) )
const ( const Name = "service"
Name = "service"
FlagServiceWhereClause = "collector.service.services-where"
FlagServiceUseAPI = "collector.service.use-api"
FlagServiceCollectorV2 = "collector.service.v2"
)
type Config struct { type Config struct {
ServiceWhereClause string `yaml:"service_where_clause"` ServiceWhereClause string `yaml:"service_where_clause"`
@ -40,8 +35,8 @@ var ConfigDefaults = Config{
V2: false, V2: false,
} }
// A collector is a Prometheus collector for WMI Win32_Service metrics // A Collector is a Prometheus Collector for WMI Win32_Service metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
serviceWhereClause *string serviceWhereClause *string
@ -55,49 +50,54 @@ type collector struct {
StateV2 *prometheus.Desc StateV2 *prometheus.Desc
} }
func New(logger log.Logger, config *Config) types.Collector { func New(logger log.Logger, config *Config) *Collector {
if config == nil { if config == nil {
config = &ConfigDefaults config = &ConfigDefaults
} }
c := &collector{ c := &Collector{
serviceWhereClause: &config.ServiceWhereClause, serviceWhereClause: &config.ServiceWhereClause,
useAPI: &config.UseAPI, useAPI: &config.UseAPI,
} }
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(app *kingpin.Application) types.Collector { func NewWithFlags(app *kingpin.Application) *Collector {
return &collector{ return &Collector{
serviceWhereClause: app.Flag( serviceWhereClause: app.Flag(
FlagServiceWhereClause, "collector.service.services-where",
"WQL 'where' clause to use in WMI metrics query. Limits the response to the services you specify and reduces the size of the response.", "WQL 'where' clause to use in WMI metrics query. Limits the response to the services you specify and reduces the size of the response.",
).Default(ConfigDefaults.ServiceWhereClause).String(), ).Default(ConfigDefaults.ServiceWhereClause).String(),
useAPI: app.Flag( useAPI: app.Flag(
FlagServiceUseAPI, "collector.service.use-api",
"Use API calls to collect service data instead of WMI. Flag 'collector.service.services-where' won't be effective.", "Use API calls to collect service data instead of WMI. Flag 'collector.service.services-where' won't be effective.",
).Default(strconv.FormatBool(ConfigDefaults.UseAPI)).Bool(), ).Default(strconv.FormatBool(ConfigDefaults.UseAPI)).Bool(),
v2: app.Flag( v2: app.Flag(
FlagServiceCollectorV2, "collector.service.v2",
"Enable V2 service collector. This collector can services state much more efficiently, can't provide general service information.", "Enable V2 service collector. This collector can services state much more efficiently, can't provide general service information.",
).Default(strconv.FormatBool(ConfigDefaults.V2)).Bool(), ).Default(strconv.FormatBool(ConfigDefaults.V2)).Bool(),
} }
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{}, nil return []string{}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
if utils.IsEmpty(c.serviceWhereClause) { if utils.IsEmpty(c.serviceWhereClause) {
_ = level.Warn(c.logger).Log("msg", "No where-clause specified for service collector. This will generate a very large number of metrics!") _ = level.Warn(c.logger).Log("msg", "No where-clause specified for service collector. This will generate a very large number of metrics!")
} }
@ -141,7 +141,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var err error var err error
switch { switch {
@ -224,7 +224,7 @@ var (
} }
) )
func (c *collector) collectWMI(ch chan<- prometheus.Metric) error { func (c *Collector) collectWMI(ch chan<- prometheus.Metric) error {
var dst []Win32_Service var dst []Win32_Service
q := wmi.QueryAllWhere(&dst, *c.serviceWhereClause, c.logger) q := wmi.QueryAllWhere(&dst, *c.serviceWhereClause, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -292,7 +292,7 @@ func (c *collector) collectWMI(ch chan<- prometheus.Metric) error {
return nil return nil
} }
func (c *collector) collectAPI(ch chan<- prometheus.Metric) error { func (c *Collector) collectAPI(ch chan<- prometheus.Metric) error {
svcmgrConnection, err := mgr.Connect() svcmgrConnection, err := mgr.Connect()
if err != nil { if err != nil {
return err return err
@ -384,7 +384,7 @@ func (c *collector) collectAPI(ch chan<- prometheus.Metric) error {
return nil return nil
} }
func (c *collector) collectAPIV2(ch chan<- prometheus.Metric) error { func (c *Collector) collectAPIV2(ch chan<- prometheus.Metric) error {
services, err := c.queryAllServiceStates() services, err := c.queryAllServiceStates()
if err != nil { if err != nil {
_ = level.Warn(c.logger).Log("msg", "Failed to query services", "err", err) _ = level.Warn(c.logger).Log("msg", "Failed to query services", "err", err)
@ -428,7 +428,7 @@ func (c *collector) collectAPIV2(ch chan<- prometheus.Metric) error {
// Copyright 2016-present Datadog, Inc. // Copyright 2016-present Datadog, Inc.
// //
// Source: https://github.com/DataDog/datadog-agent/blob/afbd8b6c87939c92610c654cb07fdfd439e4fb27/pkg/util/winutil/scmmonitor.go#L61-L96 // Source: https://github.com/DataDog/datadog-agent/blob/afbd8b6c87939c92610c654cb07fdfd439e4fb27/pkg/util/winutil/scmmonitor.go#L61-L96
func (c *collector) queryAllServiceStates() ([]windows.ENUM_SERVICE_STATUS_PROCESS, error) { func (c *Collector) queryAllServiceStates() ([]windows.ENUM_SERVICE_STATUS_PROCESS, error) {
// EnumServiceStatusEx requires only SC_MANAGER_ENUM_SERVICE. // EnumServiceStatusEx requires only SC_MANAGER_ENUM_SERVICE.
h, err := windows.OpenSCManager(nil, nil, windows.SC_MANAGER_ENUMERATE_SERVICE) h, err := windows.OpenSCManager(nil, nil, windows.SC_MANAGER_ENUMERATE_SERVICE)
if err != nil { if err != nil {

View File

@ -16,11 +16,7 @@ import (
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
const ( const Name = "smb"
Name = "smb"
FlagSmbListAllCollectors = "collectors.smb.list"
FlagSmbCollectorsEnabled = "collectors.smb.enabled"
)
type Config struct { type Config struct {
CollectorsEnabled string `yaml:"collectors_enabled"` CollectorsEnabled string `yaml:"collectors_enabled"`
@ -30,66 +26,72 @@ var ConfigDefaults = Config{
CollectorsEnabled: "", CollectorsEnabled: "",
} }
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
smbListAllCollectors *bool smbListAllCollectors *bool
smbCollectorsEnabled *string smbCollectorsEnabled *string
TreeConnectCount *prometheus.Desc treeConnectCount *prometheus.Desc
CurrentOpenFileCount *prometheus.Desc currentOpenFileCount *prometheus.Desc
enabledCollectors []string enabledCollectors []string
} }
// All available collector functions // All available Collector functions
var smbAllCollectorNames = []string{ var smbAllCollectorNames = []string{
"ServerShares", "ServerShares",
} }
func New(logger log.Logger, config *Config) types.Collector { func New(logger log.Logger, config *Config) *Collector {
if config == nil { if config == nil {
config = &ConfigDefaults config = &ConfigDefaults
} }
smbListAllCollectors := false smbListAllCollectors := false
c := &collector{ c := &Collector{
smbCollectorsEnabled: &config.CollectorsEnabled, smbCollectorsEnabled: &config.CollectorsEnabled,
smbListAllCollectors: &smbListAllCollectors, smbListAllCollectors: &smbListAllCollectors,
} }
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(app *kingpin.Application) types.Collector { func NewWithFlags(app *kingpin.Application) *Collector {
return &collector{ return &Collector{
smbListAllCollectors: app.Flag( smbListAllCollectors: app.Flag(
FlagSmbListAllCollectors, "collectors.smb.list",
"List the collectors along with their perflib object name/ids", "List the collectors along with their perflib object name/ids",
).Bool(), ).Bool(),
smbCollectorsEnabled: app.Flag( smbCollectorsEnabled: app.Flag(
FlagSmbCollectorsEnabled, "collectors.smb.enabled",
"Comma-separated list of collectors to use. Defaults to all, if not specified.", "Comma-separated list of collectors to use. Defaults to all, if not specified.",
).Default(ConfigDefaults.CollectorsEnabled).String(), ).Default(ConfigDefaults.CollectorsEnabled).String(),
} }
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{ return []string{
"SMB Server Shares", "SMB Server Shares",
}, nil }, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
// desc creates a new prometheus description // desc creates a new prometheus description
desc := func(metricName string, description string, labels ...string) *prometheus.Desc { desc := func(metricName string, description string, labels ...string) *prometheus.Desc {
return prometheus.NewDesc( return prometheus.NewDesc(
@ -100,8 +102,8 @@ func (c *collector) Build() error {
) )
} }
c.CurrentOpenFileCount = desc("server_shares_current_open_file_count", "Current total count open files on the SMB Server") c.currentOpenFileCount = desc("server_shares_current_open_file_count", "Current total count open files on the SMB Server")
c.TreeConnectCount = desc("server_shares_tree_connect_count", "Count of user connections to the SMB Server") c.treeConnectCount = desc("server_shares_tree_connect_count", "Count of user connections to the SMB Server")
c.enabledCollectors = make([]string, 0, len(smbAllCollectorNames)) c.enabledCollectors = make([]string, 0, len(smbAllCollectorNames))
@ -110,10 +112,11 @@ func (c *collector) Build() error {
} }
if *c.smbListAllCollectors { if *c.smbListAllCollectors {
fmt.Printf("%-32s %-32s\n", "Collector Name", "Perflib Object") fmt.Printf("%-32s %-32s\n", "Collector Name", "Perflib Object") //nolint:forbidigo
for _, cname := range smbAllCollectorNames { for _, cname := range smbAllCollectorNames {
fmt.Printf("%-32s %-32s\n", cname, collectorDesc[cname]) fmt.Printf("%-32s %-32s\n", cname, collectorDesc[cname]) //nolint:forbidigo
} }
os.Exit(0) os.Exit(0)
} }
@ -135,7 +138,7 @@ func (c *collector) Build() error {
} }
// Collect collects smb metrics and sends them to prometheus // Collect collects smb metrics and sends them to prometheus
func (c *collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
collectorFuncs := map[string]func(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error{ collectorFuncs := map[string]func(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error{
"ServerShares": c.collectServerShares, "ServerShares": c.collectServerShares,
} }
@ -157,7 +160,7 @@ type perflibServerShares struct {
TreeConnectCount float64 `perflib:"Tree Connect Count"` TreeConnectCount float64 `perflib:"Tree Connect Count"`
} }
func (c *collector) collectServerShares(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collectServerShares(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var data []perflibServerShares var data []perflibServerShares
if err := perflib.UnmarshalObject(ctx.PerfObjects["SMB Server Shares"], &data, c.logger); err != nil { if err := perflib.UnmarshalObject(ctx.PerfObjects["SMB Server Shares"], &data, c.logger); err != nil {
return err return err
@ -169,23 +172,22 @@ func (c *collector) collectServerShares(ctx *types.ScrapeContext, ch chan<- prom
} }
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.CurrentOpenFileCount, c.currentOpenFileCount,
prometheus.CounterValue, prometheus.CounterValue,
instance.CurrentOpenFileCount, instance.CurrentOpenFileCount,
) )
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.TreeConnectCount, c.treeConnectCount,
prometheus.CounterValue, prometheus.CounterValue,
instance.TreeConnectCount, instance.TreeConnectCount,
) )
} }
return nil return nil
} }
// toLabelName converts strings to lowercase and replaces all whitespaces and dots with underscores // toLabelName converts strings to lowercase and replaces all whitespaces and dots with underscores
func (c *collector) toLabelName(name string) string { func (c *Collector) toLabelName(name string) string {
s := strings.ReplaceAll(strings.Join(strings.Fields(strings.ToLower(name)), "_"), ".", "_") s := strings.ReplaceAll(strings.Join(strings.Fields(strings.ToLower(name)), "_"), ".", "_")
s = strings.ReplaceAll(s, "__", "_") s = strings.ReplaceAll(s, "__", "_")
return s return s

View File

@ -17,9 +17,7 @@ import (
) )
const ( const (
Name = "smbclient" Name = "smbclient"
FlagSmbClientListAllCollectors = "collectors.smbclient.list"
FlagSmbClientCollectorsEnabled = "collectors.smbclient.enabled"
) )
type Config struct { type Config struct {
@ -30,7 +28,7 @@ var ConfigDefaults = Config{
CollectorsEnabled: "", CollectorsEnabled: "",
} }
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
smbclientListAllCollectors *bool smbclientListAllCollectors *bool
@ -68,49 +66,54 @@ var smbclientAllCollectorNames = []string{
"ClientShares", "ClientShares",
} }
func New(logger log.Logger, config *Config) types.Collector { func New(logger log.Logger, config *Config) *Collector {
if config == nil { if config == nil {
config = &ConfigDefaults config = &ConfigDefaults
} }
smbclientListAllCollectors := false smbclientListAllCollectors := false
c := &collector{ c := &Collector{
smbclientCollectorsEnabled: &config.CollectorsEnabled, smbclientCollectorsEnabled: &config.CollectorsEnabled,
smbclientListAllCollectors: &smbclientListAllCollectors, smbclientListAllCollectors: &smbclientListAllCollectors,
} }
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(app *kingpin.Application) types.Collector { func NewWithFlags(app *kingpin.Application) *Collector {
return &collector{ return &Collector{
smbclientListAllCollectors: app.Flag( smbclientListAllCollectors: app.Flag(
FlagSmbClientListAllCollectors, "collectors.smbclient.list",
"List the collectors along with their perflib object name/ids", "List the collectors along with their perflib object name/ids",
).Bool(), ).Bool(),
smbclientCollectorsEnabled: app.Flag( smbclientCollectorsEnabled: app.Flag(
FlagSmbClientCollectorsEnabled, "collectors.smbclient.enabled",
"Comma-separated list of collectors to use. Defaults to all, if not specified.", "Comma-separated list of collectors to use. Defaults to all, if not specified.",
).Default(ConfigDefaults.CollectorsEnabled).String(), ).Default(ConfigDefaults.CollectorsEnabled).String(),
} }
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{ return []string{
"SMB Client Shares", "SMB Client Shares",
}, nil }, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
// desc creates a new prometheus description // desc creates a new prometheus description
desc := func(metricName string, description string, labels []string) *prometheus.Desc { desc := func(metricName string, description string, labels []string) *prometheus.Desc {
return prometheus.NewDesc( return prometheus.NewDesc(
@ -213,10 +216,11 @@ func (c *collector) Build() error {
} }
if *c.smbclientListAllCollectors { if *c.smbclientListAllCollectors {
fmt.Printf("%-32s %-32s\n", "Collector Name", "Perflib Object") fmt.Printf("%-32s %-32s\n", "Collector Name", "Perflib Object") //nolint:forbidigo
for _, cname := range smbclientAllCollectorNames { for _, cname := range smbclientAllCollectorNames {
fmt.Printf("%-32s %-32s\n", cname, collectorDesc[cname]) fmt.Printf("%-32s %-32s\n", cname, collectorDesc[cname]) //nolint:forbidigo
} }
os.Exit(0) os.Exit(0)
} }
@ -229,7 +233,7 @@ func (c *collector) Build() error {
if slices.Contains(smbclientAllCollectorNames, collectorName) { if slices.Contains(smbclientAllCollectorNames, collectorName) {
c.enabledCollectors = append(c.enabledCollectors, collectorName) c.enabledCollectors = append(c.enabledCollectors, collectorName)
} else { } else {
return fmt.Errorf("unknown smbclient collector: %s", collectorName) return fmt.Errorf("unknown smbclient Collector: %s", collectorName)
} }
} }
} }
@ -238,7 +242,7 @@ func (c *collector) Build() error {
} }
// Collect collects smb client metrics and sends them to prometheus // Collect collects smb client metrics and sends them to prometheus
func (c *collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
collectorFuncs := map[string]func(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error{ collectorFuncs := map[string]func(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error{
"ClientShares": c.collectClientShares, "ClientShares": c.collectClientShares,
} }
@ -279,7 +283,7 @@ type perflibClientShares struct {
WriteRequestsPerSec float64 `perflib:"Write Requests/sec"` WriteRequestsPerSec float64 `perflib:"Write Requests/sec"`
} }
func (c *collector) collectClientShares(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collectClientShares(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var data []perflibClientShares var data []perflibClientShares
if err := perflib.UnmarshalObject(ctx.PerfObjects["SMB Client Shares"], &data, c.logger); err != nil { if err := perflib.UnmarshalObject(ctx.PerfObjects["SMB Client Shares"], &data, c.logger); err != nil {
return err return err
@ -441,7 +445,6 @@ func (c *collector) collectClientShares(ctx *types.ScrapeContext, ch chan<- prom
instance.WriteRequestsPerSec, instance.WriteRequestsPerSec,
serverValue, shareValue, serverValue, shareValue,
) )
} }
return nil return nil
} }

View File

@ -14,12 +14,7 @@ import (
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
) )
const ( const Name = "smtp"
Name = "smtp"
FlagSmtpServerExclude = "collector.smtp.server-exclude"
FlagSmtpServerInclude = "collector.smtp.server-include"
)
type Config struct { type Config struct {
ServerInclude string `yaml:"server_include"` ServerInclude string `yaml:"server_include"`
@ -31,7 +26,7 @@ var ConfigDefaults = Config{
ServerExclude: "", ServerExclude: "",
} }
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
serverInclude *string serverInclude *string
@ -84,28 +79,29 @@ type collector struct {
serverExcludePattern *regexp.Regexp serverExcludePattern *regexp.Regexp
} }
func New(logger log.Logger, config *Config) types.Collector { func New(logger log.Logger, config *Config) *Collector {
if config == nil { if config == nil {
config = &ConfigDefaults config = &ConfigDefaults
} }
c := &collector{ c := &Collector{
serverExclude: &config.ServerExclude, serverExclude: &config.ServerExclude,
serverInclude: &config.ServerInclude, serverInclude: &config.ServerInclude,
} }
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(app *kingpin.Application) types.Collector { func NewWithFlags(app *kingpin.Application) *Collector {
c := &collector{ c := &Collector{
serverInclude: app.Flag( serverInclude: app.Flag(
FlagSmtpServerInclude, "collector.smtp.server-include",
"Regexp of virtual servers to include. Server name must both match include and not match exclude to be included.", "Regexp of virtual servers to include. Server name must both match include and not match exclude to be included.",
).Default(ConfigDefaults.ServerInclude).String(), ).Default(ConfigDefaults.ServerInclude).String(),
serverExclude: app.Flag( serverExclude: app.Flag(
FlagSmtpServerExclude, "collector.smtp.server-exclude",
"Regexp of virtual servers to exclude. Server name must both match include and not match exclude to be included.", "Regexp of virtual servers to exclude. Server name must both match include and not match exclude to be included.",
).Default(ConfigDefaults.ServerExclude).String(), ).Default(ConfigDefaults.ServerExclude).String(),
} }
@ -113,19 +109,23 @@ func NewWithFlags(app *kingpin.Application) types.Collector {
return c return c
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{"SMTP Server"}, nil return []string{"SMTP Server"}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
_ = level.Info(c.logger).Log("msg", "smtp collector is in an experimental state! Metrics for this collector have not been tested.") _ = level.Info(c.logger).Log("msg", "smtp collector is in an experimental state! Metrics for this collector have not been tested.")
c.BadmailedMessagesBadPickupFileTotal = prometheus.NewDesc( c.BadmailedMessagesBadPickupFileTotal = prometheus.NewDesc(
@ -398,7 +398,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collect(ctx, ch); err != nil { if err := c.collect(ctx, ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting smtp metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting smtp metrics", "err", err)
return err return err
@ -454,7 +454,7 @@ type PerflibSMTPServer struct {
RoutingTableLookupsTotal float64 `perflib:"Routing Table Lookups Total"` RoutingTableLookupsTotal float64 `perflib:"Routing Table Lookups Total"`
} }
func (c *collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var dst []PerflibSMTPServer var dst []PerflibSMTPServer
if err := perflib.UnmarshalObject(ctx.PerfObjects["SMTP Server"], &dst, c.logger); err != nil { if err := perflib.UnmarshalObject(ctx.PerfObjects["SMTP Server"], &dst, c.logger); err != nil {
return err return err
@ -753,7 +753,6 @@ func (c *collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metri
server.RoutingTableLookupsTotal, server.RoutingTableLookupsTotal,
server.Name, server.Name,
) )
} }
return nil return nil
} }

View File

@ -17,8 +17,8 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
// A collector is a Prometheus collector for WMI metrics // A Collector is a Prometheus Collector for WMI metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
ContextSwitchesTotal *prometheus.Desc ContextSwitchesTotal *prometheus.Desc
@ -29,29 +29,34 @@ type collector struct {
Threads *prometheus.Desc Threads *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{"System"}, nil return []string{"System"}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.ContextSwitchesTotal = prometheus.NewDesc( c.ContextSwitchesTotal = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "context_switches_total"), prometheus.BuildFQName(types.Namespace, Name, "context_switches_total"),
"Total number of context switches (WMI source: PerfOS_System.ContextSwitchesPersec)", "Total number of context switches (WMI source: PerfOS_System.ContextSwitchesPersec)",
@ -93,7 +98,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collect(ctx, ch); err != nil { if err := c.collect(ctx, ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting system metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting system metrics", "err", err)
return err return err
@ -112,7 +117,7 @@ type system struct {
Threads float64 `perflib:"Threads"` Threads float64 `perflib:"Threads"`
} }
func (c *collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var dst []system var dst []system
if err := perflib.UnmarshalObject(ctx.PerfObjects["System"], &dst, c.logger); err != nil { if err := perflib.UnmarshalObject(ctx.PerfObjects["System"], &dst, c.logger); err != nil {
return err return err

View File

@ -17,8 +17,8 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
// A collector is a Prometheus collector for WMI Win32_PerfRawData_Tcpip_TCPv{4,6} metrics // A Collector is a Prometheus Collector for WMI Win32_PerfRawData_Tcpip_TCPv{4,6} metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
ConnectionFailures *prometheus.Desc ConnectionFailures *prometheus.Desc
@ -32,29 +32,34 @@ type collector struct {
SegmentsSentTotal *prometheus.Desc SegmentsSentTotal *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{"TCPv4"}, nil return []string{"TCPv4"}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.ConnectionFailures = prometheus.NewDesc( c.ConnectionFailures = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "connection_failures_total"), prometheus.BuildFQName(types.Namespace, Name, "connection_failures_total"),
"(TCP.ConnectionFailures)", "(TCP.ConnectionFailures)",
@ -114,7 +119,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collect(ctx, ch); err != nil { if err := c.collect(ctx, ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting tcp metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting tcp metrics", "err", err)
return err return err
@ -137,7 +142,7 @@ type tcp struct {
SegmentsSentPersec float64 `perflib:"Segments Sent/sec"` SegmentsSentPersec float64 `perflib:"Segments Sent/sec"`
} }
func writeTCPCounters(metrics tcp, labels []string, c *collector, ch chan<- prometheus.Metric) { func writeTCPCounters(metrics tcp, labels []string, c *Collector, ch chan<- prometheus.Metric) {
ch <- prometheus.MustNewConstMetric( ch <- prometheus.MustNewConstMetric(
c.ConnectionFailures, c.ConnectionFailures,
prometheus.CounterValue, prometheus.CounterValue,
@ -194,7 +199,7 @@ func writeTCPCounters(metrics tcp, labels []string, c *collector, ch chan<- prom
) )
} }
func (c *collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var dst []tcp var dst []tcp
// TCPv4 counters // TCPv4 counters

View File

@ -19,13 +19,13 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
// collector is a Prometheus collector for WMI metrics: // Collector is a Prometheus Collector for WMI metrics:
// win32_PerfRawData_TeradiciPerf_PCoIPSessionAudioStatistics // win32_PerfRawData_TeradiciPerf_PCoIPSessionAudioStatistics
// win32_PerfRawData_TeradiciPerf_PCoIPSessionGeneralStatistics // win32_PerfRawData_TeradiciPerf_PCoIPSessionGeneralStatistics
// win32_PerfRawData_TeradiciPerf_PCoIPSessionImagingStatistics // win32_PerfRawData_TeradiciPerf_PCoIPSessionImagingStatistics
// win32_PerfRawData_TeradiciPerf_PCoIPSessionNetworkStatistics // win32_PerfRawData_TeradiciPerf_PCoIPSessionNetworkStatistics
// win32_PerfRawData_TeradiciPerf_PCoIPSessionUsbStatistics // win32_PerfRawData_TeradiciPerf_PCoIPSessionUsbStatistics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
AudioBytesReceived *prometheus.Desc AudioBytesReceived *prometheus.Desc
@ -71,29 +71,34 @@ type collector struct {
USBTXBWkbitPersec *prometheus.Desc USBTXBWkbitPersec *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{}, nil return []string{}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.AudioBytesReceived = prometheus.NewDesc( c.AudioBytesReceived = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "audio_bytes_received_total"), prometheus.BuildFQName(types.Namespace, Name, "audio_bytes_received_total"),
"(AudioBytesReceived)", "(AudioBytesReceived)",
@ -325,7 +330,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collectAudio(ch); err != nil { if err := c.collectAudio(ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting teradici session audio metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting teradici session audio metrics", "err", err)
return err return err
@ -401,7 +406,7 @@ type win32_PerfRawData_TeradiciPerf_PCoIPSessionUsbStatistics struct {
USBTXBWkbitPersec uint64 USBTXBWkbitPersec uint64
} }
func (c *collector) collectAudio(ch chan<- prometheus.Metric) error { func (c *Collector) collectAudio(ch chan<- prometheus.Metric) error {
var dst []win32_PerfRawData_TeradiciPerf_PCoIPSessionAudioStatistics var dst []win32_PerfRawData_TeradiciPerf_PCoIPSessionAudioStatistics
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -444,7 +449,7 @@ func (c *collector) collectAudio(ch chan<- prometheus.Metric) error {
return nil return nil
} }
func (c *collector) collectGeneral(ch chan<- prometheus.Metric) error { func (c *Collector) collectGeneral(ch chan<- prometheus.Metric) error {
var dst []win32_PerfRawData_TeradiciPerf_PCoIPSessionGeneralStatistics var dst []win32_PerfRawData_TeradiciPerf_PCoIPSessionGeneralStatistics
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -499,7 +504,7 @@ func (c *collector) collectGeneral(ch chan<- prometheus.Metric) error {
return nil return nil
} }
func (c *collector) collectImaging(ch chan<- prometheus.Metric) error { func (c *Collector) collectImaging(ch chan<- prometheus.Metric) error {
var dst []win32_PerfRawData_TeradiciPerf_PCoIPSessionImagingStatistics var dst []win32_PerfRawData_TeradiciPerf_PCoIPSessionImagingStatistics
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -578,7 +583,7 @@ func (c *collector) collectImaging(ch chan<- prometheus.Metric) error {
return nil return nil
} }
func (c *collector) collectNetwork(ch chan<- prometheus.Metric) error { func (c *Collector) collectNetwork(ch chan<- prometheus.Metric) error {
var dst []win32_PerfRawData_TeradiciPerf_PCoIPSessionNetworkStatistics var dst []win32_PerfRawData_TeradiciPerf_PCoIPSessionNetworkStatistics
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -651,7 +656,7 @@ func (c *collector) collectNetwork(ch chan<- prometheus.Metric) error {
return nil return nil
} }
func (c *collector) collectUsb(ch chan<- prometheus.Metric) error { func (c *Collector) collectUsb(ch chan<- prometheus.Metric) error {
var dst []win32_PerfRawData_TeradiciPerf_PCoIPSessionUsbStatistics var dst []win32_PerfRawData_TeradiciPerf_PCoIPSessionUsbStatistics
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {

View File

@ -46,11 +46,11 @@ func isConnectionBrokerServer(logger log.Logger) bool {
return false return false
} }
// A collector is a Prometheus collector for WMI // A Collector is a Prometheus Collector for WMI
// Win32_PerfRawData_LocalSessionManager_TerminalServices & Win32_PerfRawData_TermService_TerminalServicesSession metrics // Win32_PerfRawData_LocalSessionManager_TerminalServices & Win32_PerfRawData_TermService_TerminalServicesSession metrics
// https://docs.microsoft.com/en-us/previous-versions/aa394344(v%3Dvs.85) // https://docs.microsoft.com/en-us/previous-versions/aa394344(v%3Dvs.85)
// https://wutils.com/wmi/root/cimv2/win32_perfrawdata_localsessionmanager_terminalservices/ // https://wutils.com/wmi/root/cimv2/win32_perfrawdata_localsessionmanager_terminalservices/
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
connectionBrokerEnabled bool connectionBrokerEnabled bool
@ -75,32 +75,43 @@ type collector struct {
WorkingSetPeak *prometheus.Desc WorkingSetPeak *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{ return []string{
"Terminal Services Session", "Terminal Services Session",
"Remote Desktop Connection Broker Counterset", "Remote Desktop Connection Broker Counterset",
}, nil }, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
err := wtsapi32.WTSCloseServer(c.hServer)
if err != nil {
return fmt.Errorf("failed to close WTS server: %w", err)
}
return nil
}
func (c *Collector) Build() error {
c.connectionBrokerEnabled = isConnectionBrokerServer(c.logger) c.connectionBrokerEnabled = isConnectionBrokerServer(c.logger)
c.SessionInfo = prometheus.NewDesc( c.SessionInfo = prometheus.NewDesc(
@ -206,7 +217,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collectWTSSessions(ch); err != nil { if err := c.collectWTSSessions(ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting terminal services session infos", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting terminal services session infos", "err", err)
return err return err
@ -245,7 +256,7 @@ type perflibTerminalServicesSession struct {
WorkingSetPeak float64 `perflib:"Working Set Peak"` WorkingSetPeak float64 `perflib:"Working Set Peak"`
} }
func (c *collector) collectTSSessionCounters(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collectTSSessionCounters(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
dst := make([]perflibTerminalServicesSession, 0) dst := make([]perflibTerminalServicesSession, 0)
err := perflib.UnmarshalObject(ctx.PerfObjects["Terminal Services Session"], &dst, c.logger) err := perflib.UnmarshalObject(ctx.PerfObjects["Terminal Services Session"], &dst, c.logger)
if err != nil { if err != nil {
@ -368,7 +379,7 @@ type perflibRemoteDesktopConnectionBrokerCounterset struct {
FailedConnections float64 `perflib:"Failed Connections"` FailedConnections float64 `perflib:"Failed Connections"`
} }
func (c *collector) collectCollectionBrokerPerformanceCounter(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collectCollectionBrokerPerformanceCounter(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
dst := make([]perflibRemoteDesktopConnectionBrokerCounterset, 0) dst := make([]perflibRemoteDesktopConnectionBrokerCounterset, 0)
err := perflib.UnmarshalObject(ctx.PerfObjects["Remote Desktop Connection Broker Counterset"], &dst, c.logger) err := perflib.UnmarshalObject(ctx.PerfObjects["Remote Desktop Connection Broker Counterset"], &dst, c.logger)
if err != nil { if err != nil {
@ -402,7 +413,7 @@ func (c *collector) collectCollectionBrokerPerformanceCounter(ctx *types.ScrapeC
return nil return nil
} }
func (c *collector) collectWTSSessions(ch chan<- prometheus.Metric) error { func (c *Collector) collectWTSSessions(ch chan<- prometheus.Metric) error {
sessions, err := wtsapi32.WTSEnumerateSessionsEx(c.hServer, c.logger) sessions, err := wtsapi32.WTSEnumerateSessionsEx(c.hServer, c.logger)
if err != nil { if err != nil {
return fmt.Errorf("failed to enumerate WTS sessions: %w", err) return fmt.Errorf("failed to enumerate WTS sessions: %w", err)

View File

@ -8,7 +8,5 @@ import (
) )
func BenchmarkCollector(b *testing.B) { func BenchmarkCollector(b *testing.B) {
testutils.FuncBenchmarkCollector(b, terminal_services.Name, terminal_services.NewWithFlags) testutils.FuncBenchmarkCollector(b, terminal_services.Name, terminal_services.NewWithFlags)
} }

View File

@ -37,10 +37,7 @@ import (
"github.com/prometheus/common/expfmt" "github.com/prometheus/common/expfmt"
) )
const ( const Name = "textfile"
Name = "textfile"
FlagTextFileDirectories = "collector.textfile.directories"
)
type Config struct { type Config struct {
TextFileDirectories string `yaml:"text_file_directories"` TextFileDirectories string `yaml:"text_file_directories"`
@ -50,7 +47,7 @@ var ConfigDefaults = Config{
TextFileDirectories: getDefaultPath(), TextFileDirectories: getDefaultPath(),
} }
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
textFileDirectories *string textFileDirectories *string
@ -59,51 +56,56 @@ type collector struct {
// Only set for testing to get predictable output. // Only set for testing to get predictable output.
mtime *float64 mtime *float64
MtimeDesc *prometheus.Desc mtimeDesc *prometheus.Desc
} }
func New(logger log.Logger, config *Config) types.Collector { func New(logger log.Logger, config *Config) *Collector {
if config == nil { if config == nil {
config = &ConfigDefaults config = &ConfigDefaults
} }
c := &collector{ c := &Collector{
textFileDirectories: &config.TextFileDirectories, textFileDirectories: &config.TextFileDirectories,
} }
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(app *kingpin.Application) types.Collector { func NewWithFlags(app *kingpin.Application) *Collector {
return &collector{ return &Collector{
textFileDirectories: app.Flag( textFileDirectories: app.Flag(
FlagTextFileDirectories, "collector.textfile.directories",
"Directory or Directories to read text files with metrics from.", "Directory or Directories to read text files with metrics from.",
).Default(ConfigDefaults.TextFileDirectories).String(), ).Default(ConfigDefaults.TextFileDirectories).String(),
} }
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{}, nil return []string{}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.directories = "" c.directories = ""
if utils.HasValue(c.textFileDirectories) { if utils.HasValue(c.textFileDirectories) {
c.directories = strings.Trim(*c.textFileDirectories, ",") c.directories = strings.Trim(*c.textFileDirectories, ",")
} }
_ = level.Info(c.logger).Log("msg", "textfile collector directories: "+c.directories) _ = level.Info(c.logger).Log("msg", "textfile Collector directories: "+c.directories)
c.MtimeDesc = prometheus.NewDesc( c.mtimeDesc = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, "textfile", "mtime_seconds"), prometheus.BuildFQName(types.Namespace, "textfile", "mtime_seconds"),
"Unixtime mtime of textfiles successfully read.", "Unixtime mtime of textfiles successfully read.",
[]string{"file"}, []string{"file"},
@ -138,7 +140,7 @@ func duplicateMetricEntry(metricFamilies []*dto.MetricFamily) bool {
return false return false
} }
func (c *collector) convertMetricFamily(metricFamily *dto.MetricFamily, ch chan<- prometheus.Metric) { func (c *Collector) convertMetricFamily(metricFamily *dto.MetricFamily, ch chan<- prometheus.Metric) {
var valType prometheus.ValueType var valType prometheus.ValueType
var val float64 var val float64
@ -154,7 +156,7 @@ func (c *collector) convertMetricFamily(metricFamily *dto.MetricFamily, ch chan<
for _, metric := range metricFamily.Metric { for _, metric := range metricFamily.Metric {
if metric.TimestampMs != nil { if metric.TimestampMs != nil {
_ = level.Warn(c.logger).Log("msg", fmt.Sprintf("Ignoring unsupported custom timestamp on textfile collector metric %v", metric)) _ = level.Warn(c.logger).Log("msg", fmt.Sprintf("Ignoring unsupported custom timestamp on textfile Collector metric %v", metric))
} }
labels := metric.GetLabel() labels := metric.GetLabel()
@ -240,7 +242,7 @@ func (c *collector) convertMetricFamily(metricFamily *dto.MetricFamily, ch chan<
} }
} }
func (c *collector) exportMTimes(mtimes map[string]time.Time, ch chan<- prometheus.Metric) { func (c *Collector) exportMTimes(mtimes map[string]time.Time, ch chan<- prometheus.Metric) {
// Export the mtimes of the successful files. // Export the mtimes of the successful files.
if len(mtimes) > 0 { if len(mtimes) > 0 {
// Sorting is needed for predictable output comparison in tests. // Sorting is needed for predictable output comparison in tests.
@ -255,7 +257,7 @@ func (c *collector) exportMTimes(mtimes map[string]time.Time, ch chan<- promethe
if c.mtime != nil { if c.mtime != nil {
mtime = *c.mtime mtime = *c.mtime
} }
ch <- prometheus.MustNewConstMetric(c.MtimeDesc, prometheus.GaugeValue, mtime, filename) ch <- prometheus.MustNewConstMetric(c.mtimeDesc, prometheus.GaugeValue, mtime, filename)
} }
} }
} }
@ -285,7 +287,7 @@ func (cr carriageReturnFilteringReader) Read(p []byte) (int, error) {
} }
// Collect implements the Collector interface. // Collect implements the Collector interface.
func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error {
errorMetric := 0.0 errorMetric := 0.0
mtimes := map[string]time.Time{} mtimes := map[string]time.Time{}
// Create empty metricFamily slice here and append parsedFamilies to it inside the loop. // Create empty metricFamily slice here and append parsedFamilies to it inside the loop.
@ -326,7 +328,7 @@ func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric)
return nil return nil
}) })
if err != nil && directory != "" { if err != nil && directory != "" {
_ = level.Error(c.logger).Log("msg", "Error reading textfile collector directory: "+c.directories, "err", err) _ = level.Error(c.logger).Log("msg", "Error reading textfile Collector directory: "+c.directories, "err", err)
errorMetric = 1.0 errorMetric = 1.0
} }
} }

View File

@ -6,15 +6,12 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/stretchr/testify/require" "github.com/go-kit/log"
"github.com/prometheus-community/windows_exporter/pkg/collector" "github.com/prometheus-community/windows_exporter/pkg/collector"
"github.com/prometheus-community/windows_exporter/pkg/collector/textfile" "github.com/prometheus-community/windows_exporter/pkg/collector/textfile"
"github.com/prometheus-community/windows_exporter/pkg/types"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
dto "github.com/prometheus/client_model/go" dto "github.com/prometheus/client_model/go"
"github.com/stretchr/testify/require"
) )
var baseDir = "../../../tools/textfile-test" var baseDir = "../../../tools/textfile-test"
@ -27,7 +24,7 @@ func TestMultipleDirectories(t *testing.T) {
TextFileDirectories: testDirs, TextFileDirectories: testDirs,
}) })
collectors := collector.New(map[string]types.Collector{textfile.Name: textfileCollector}) collectors := collector.New(map[string]collector.Collector{textfile.Name: textfileCollector})
require.NoError(t, collectors.Build()) require.NoError(t, collectors.Build())
scrapeContext, err := collectors.PrepareScrapeContext() scrapeContext, err := collectors.PrepareScrapeContext()
@ -66,7 +63,7 @@ func TestDuplicateFileName(t *testing.T) {
TextFileDirectories: testDir, TextFileDirectories: testDir,
}) })
collectors := collector.New(map[string]types.Collector{textfile.Name: textfileCollector}) collectors := collector.New(map[string]collector.Collector{textfile.Name: textfileCollector})
require.NoError(t, collectors.Build()) require.NoError(t, collectors.Build())
scrapeContext, err := collectors.PrepareScrapeContext() scrapeContext, err := collectors.PrepareScrapeContext()

View File

@ -19,8 +19,8 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
// A collector is a Prometheus collector for WMI Win32_PerfRawData_Counters_ThermalZoneInformation metrics // A Collector is a Prometheus Collector for WMI Win32_PerfRawData_Counters_ThermalZoneInformation metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
PercentPassiveLimit *prometheus.Desc PercentPassiveLimit *prometheus.Desc
@ -28,29 +28,34 @@ type collector struct {
ThrottleReasons *prometheus.Desc ThrottleReasons *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{}, nil return []string{}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.Temperature = prometheus.NewDesc( c.Temperature = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "temperature_celsius"), prometheus.BuildFQName(types.Namespace, Name, "temperature_celsius"),
"(Temperature)", "(Temperature)",
@ -80,7 +85,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collect(ch); err != nil { if err := c.collect(ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting thermalzone metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting thermalzone metrics", "err", err)
return err return err
@ -98,7 +103,7 @@ type Win32_PerfRawData_Counters_ThermalZoneInformation struct {
ThrottleReasons uint32 ThrottleReasons uint32
} }
func (c *collector) collect(ch chan<- prometheus.Metric) error { func (c *Collector) collect(ch chan<- prometheus.Metric) error {
var dst []Win32_PerfRawData_Counters_ThermalZoneInformation var dst []Win32_PerfRawData_Counters_ThermalZoneInformation
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {

View File

@ -20,8 +20,8 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
// collector is a Prometheus collector for Perflib counter metrics // Collector is a Prometheus Collector for Perflib counter metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
ClockFrequencyAdjustmentPPBTotal *prometheus.Desc ClockFrequencyAdjustmentPPBTotal *prometheus.Desc
@ -32,29 +32,34 @@ type collector struct {
NTPServerOutgoingResponsesTotal *prometheus.Desc NTPServerOutgoingResponsesTotal *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{"Windows Time Service"}, nil return []string{"Windows Time Service"}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
if winversion.WindowsVersionFloat <= 6.1 { if winversion.WindowsVersionFloat <= 6.1 {
return errors.New("Windows version older than Server 2016 detected. The time collector will not run and should be disabled via CLI flags or configuration file") return errors.New("Windows version older than Server 2016 detected. The time collector will not run and should be disabled via CLI flags or configuration file")
} }
@ -100,7 +105,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collect(ctx, ch); err != nil { if err := c.collect(ctx, ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting time metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting time metrics", "err", err)
return err return err
@ -118,7 +123,7 @@ type windowsTime struct {
NTPServerOutgoingResponsesTotal float64 `perflib:"NTP Server Outgoing Responses"` NTPServerOutgoingResponsesTotal float64 `perflib:"NTP Server Outgoing Responses"`
} }
func (c *collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) error {
var dst []windowsTime // Single-instance class, array is required but will have single entry. var dst []windowsTime // Single-instance class, array is required but will have single entry.
if err := perflib.UnmarshalObject(ctx.PerfObjects["Windows Time Service"], &dst, c.logger); err != nil { if err := perflib.UnmarshalObject(ctx.PerfObjects["Windows Time Service"], &dst, c.logger); err != nil {
return err return err

34
pkg/collector/types.go Normal file
View File

@ -0,0 +1,34 @@
package collector
import (
"github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log"
"github.com/prometheus-community/windows_exporter/pkg/types"
"github.com/prometheus/client_golang/prometheus"
)
type Collectors struct {
logger log.Logger
collectors Map
perfCounterQuery string
}
type Map map[string]Collector
type Builder func(logger log.Logger) Collector
type BuilderWithFlags[C Collector] func(*kingpin.Application) C
// Collector interface that a collector has to implement.
type Collector interface {
Build() error
// Close closes the collector
Close() error
// GetName get the name of the collector
GetName() string
// GetPerfCounter returns the perf counter required by the collector
GetPerfCounter() ([]string, error)
// Collect Get new metrics and expose them via prometheus registry.
Collect(ctx *types.ScrapeContext, ch chan<- prometheus.Metric) (err error)
SetLogger(logger log.Logger)
}

View File

@ -20,8 +20,8 @@ type Config struct{}
var ConfigDefaults = Config{} var ConfigDefaults = Config{}
// A collector is a Prometheus collector for WMI Win32_PerfRawData_vmGuestLib_VMem/Win32_PerfRawData_vmGuestLib_VCPU metrics // A Collector is a Prometheus Collector for WMI Win32_PerfRawData_vmGuestLib_VMem/Win32_PerfRawData_vmGuestLib_VCPU metrics
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
MemActive *prometheus.Desc MemActive *prometheus.Desc
@ -46,29 +46,34 @@ type collector struct {
HostProcessorSpeedMHz *prometheus.Desc HostProcessorSpeedMHz *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{}, nil return []string{}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.MemActive = prometheus.NewDesc( c.MemActive = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "mem_active_bytes"), prometheus.BuildFQName(types.Namespace, Name, "mem_active_bytes"),
"(MemActiveMB)", "(MemActiveMB)",
@ -189,7 +194,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collectMem(ch); err != nil { if err := c.collectMem(ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting vmware memory metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting vmware memory metrics", "err", err)
return err return err
@ -226,7 +231,7 @@ type Win32_PerfRawData_vmGuestLib_VCPU struct {
HostProcessorSpeedMHz uint64 HostProcessorSpeedMHz uint64
} }
func (c *collector) collectMem(ch chan<- prometheus.Metric) error { func (c *Collector) collectMem(ch chan<- prometheus.Metric) error {
var dst []Win32_PerfRawData_vmGuestLib_VMem var dst []Win32_PerfRawData_vmGuestLib_VMem
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -315,7 +320,7 @@ func mbToBytes(mb uint64) float64 {
return float64(mb * 1024 * 1024) return float64(mb * 1024 * 1024)
} }
func (c *collector) collectCpu(ch chan<- prometheus.Metric) error { func (c *Collector) collectCpu(ch chan<- prometheus.Metric) error {
var dst []Win32_PerfRawData_vmGuestLib_VCPU var dst []Win32_PerfRawData_vmGuestLib_VCPU
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {

View File

@ -31,7 +31,7 @@ var ConfigDefaults = Config{}
// win32_PerfRawData_Counters_VMwareBlastUSBCounters // win32_PerfRawData_Counters_VMwareBlastUSBCounters
// win32_PerfRawData_Counters_VMwareBlastWindowsMediaMMRCounters // win32_PerfRawData_Counters_VMwareBlastWindowsMediaMMRCounters
type collector struct { type Collector struct {
logger log.Logger logger log.Logger
AudioReceivedBytes *prometheus.Desc AudioReceivedBytes *prometheus.Desc
@ -116,29 +116,34 @@ type collector struct {
WindowsMediaMMRTransmittedPackets *prometheus.Desc WindowsMediaMMRTransmittedPackets *prometheus.Desc
} }
func New(logger log.Logger, _ *Config) types.Collector { func New(logger log.Logger, _ *Config) *Collector {
c := &collector{} c := &Collector{}
c.SetLogger(logger) c.SetLogger(logger)
return c return c
} }
func NewWithFlags(_ *kingpin.Application) types.Collector { func NewWithFlags(_ *kingpin.Application) *Collector {
return &collector{} return &Collector{}
} }
func (c *collector) GetName() string { func (c *Collector) GetName() string {
return Name return Name
} }
func (c *collector) SetLogger(logger log.Logger) { func (c *Collector) SetLogger(logger log.Logger) {
c.logger = log.With(logger, "collector", Name) c.logger = log.With(logger, "collector", Name)
} }
func (c *collector) GetPerfCounter() ([]string, error) { func (c *Collector) GetPerfCounter() ([]string, error) {
return []string{}, nil return []string{}, nil
} }
func (c *collector) Build() error { func (c *Collector) Close() error {
return nil
}
func (c *Collector) Build() error {
c.AudioReceivedBytes = prometheus.NewDesc( c.AudioReceivedBytes = prometheus.NewDesc(
prometheus.BuildFQName(types.Namespace, Name, "audio_received_bytes_total"), prometheus.BuildFQName(types.Namespace, Name, "audio_received_bytes_total"),
"(AudioReceivedBytes)", "(AudioReceivedBytes)",
@ -569,7 +574,7 @@ func (c *collector) Build() error {
// Collect sends the metric values for each metric // Collect sends the metric values for each metric
// to the provided prometheus Metric channel. // to the provided prometheus Metric channel.
func (c *collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error { func (c *Collector) Collect(_ *types.ScrapeContext, ch chan<- prometheus.Metric) error {
if err := c.collectAudio(ch); err != nil { if err := c.collectAudio(ch); err != nil {
_ = level.Error(c.logger).Log("msg", "failed collecting vmware blast audio metrics", "err", err) _ = level.Error(c.logger).Log("msg", "failed collecting vmware blast audio metrics", "err", err)
return err return err
@ -726,7 +731,7 @@ type win32_PerfRawData_Counters_VMwareBlastWindowsMediaMMRCounters struct {
TransmittedPackets uint32 TransmittedPackets uint32
} }
func (c *collector) collectAudio(ch chan<- prometheus.Metric) error { func (c *Collector) collectAudio(ch chan<- prometheus.Metric) error {
var dst []win32_PerfRawData_Counters_VMwareBlastAudioCounters var dst []win32_PerfRawData_Counters_VMwareBlastAudioCounters
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -765,7 +770,7 @@ func (c *collector) collectAudio(ch chan<- prometheus.Metric) error {
return nil return nil
} }
func (c *collector) collectCdr(ch chan<- prometheus.Metric) error { func (c *Collector) collectCdr(ch chan<- prometheus.Metric) error {
var dst []win32_PerfRawData_Counters_VMwareBlastCDRCounters var dst []win32_PerfRawData_Counters_VMwareBlastCDRCounters
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -804,7 +809,7 @@ func (c *collector) collectCdr(ch chan<- prometheus.Metric) error {
return nil return nil
} }
func (c *collector) collectClipboard(ch chan<- prometheus.Metric) error { func (c *Collector) collectClipboard(ch chan<- prometheus.Metric) error {
var dst []win32_PerfRawData_Counters_VMwareBlastClipboardCounters var dst []win32_PerfRawData_Counters_VMwareBlastClipboardCounters
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -843,7 +848,7 @@ func (c *collector) collectClipboard(ch chan<- prometheus.Metric) error {
return nil return nil
} }
func (c *collector) collectHtml5Mmr(ch chan<- prometheus.Metric) error { func (c *Collector) collectHtml5Mmr(ch chan<- prometheus.Metric) error {
var dst []win32_PerfRawData_Counters_VMwareBlastHTML5MMRcounters var dst []win32_PerfRawData_Counters_VMwareBlastHTML5MMRcounters
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -882,7 +887,7 @@ func (c *collector) collectHtml5Mmr(ch chan<- prometheus.Metric) error {
return nil return nil
} }
func (c *collector) collectImaging(ch chan<- prometheus.Metric) error { func (c *Collector) collectImaging(ch chan<- prometheus.Metric) error {
var dst []win32_PerfRawData_Counters_VMwareBlastImagingCounters var dst []win32_PerfRawData_Counters_VMwareBlastImagingCounters
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -969,7 +974,7 @@ func (c *collector) collectImaging(ch chan<- prometheus.Metric) error {
return nil return nil
} }
func (c *collector) collectRtav(ch chan<- prometheus.Metric) error { func (c *Collector) collectRtav(ch chan<- prometheus.Metric) error {
var dst []win32_PerfRawData_Counters_VMwareBlastRTAVCounters var dst []win32_PerfRawData_Counters_VMwareBlastRTAVCounters
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -1008,7 +1013,7 @@ func (c *collector) collectRtav(ch chan<- prometheus.Metric) error {
return nil return nil
} }
func (c *collector) collectSerialPortandScanner(ch chan<- prometheus.Metric) error { func (c *Collector) collectSerialPortandScanner(ch chan<- prometheus.Metric) error {
var dst []win32_PerfRawData_Counters_VMwareBlastSerialPortandScannerCounters var dst []win32_PerfRawData_Counters_VMwareBlastSerialPortandScannerCounters
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -1047,7 +1052,7 @@ func (c *collector) collectSerialPortandScanner(ch chan<- prometheus.Metric) err
return nil return nil
} }
func (c *collector) collectSession(ch chan<- prometheus.Metric) error { func (c *Collector) collectSession(ch chan<- prometheus.Metric) error {
var dst []win32_PerfRawData_Counters_VMwareBlastSessionCounters var dst []win32_PerfRawData_Counters_VMwareBlastSessionCounters
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -1164,7 +1169,7 @@ func (c *collector) collectSession(ch chan<- prometheus.Metric) error {
return nil return nil
} }
func (c *collector) collectSkypeforBusinessControl(ch chan<- prometheus.Metric) error { func (c *Collector) collectSkypeforBusinessControl(ch chan<- prometheus.Metric) error {
var dst []win32_PerfRawData_Counters_VMwareBlastSkypeforBusinessControlCounters var dst []win32_PerfRawData_Counters_VMwareBlastSkypeforBusinessControlCounters
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -1203,7 +1208,7 @@ func (c *collector) collectSkypeforBusinessControl(ch chan<- prometheus.Metric)
return nil return nil
} }
func (c *collector) collectThinPrint(ch chan<- prometheus.Metric) error { func (c *Collector) collectThinPrint(ch chan<- prometheus.Metric) error {
var dst []win32_PerfRawData_Counters_VMwareBlastThinPrintCounters var dst []win32_PerfRawData_Counters_VMwareBlastThinPrintCounters
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -1242,7 +1247,7 @@ func (c *collector) collectThinPrint(ch chan<- prometheus.Metric) error {
return nil return nil
} }
func (c *collector) collectUsb(ch chan<- prometheus.Metric) error { func (c *Collector) collectUsb(ch chan<- prometheus.Metric) error {
var dst []win32_PerfRawData_Counters_VMwareBlastUSBCounters var dst []win32_PerfRawData_Counters_VMwareBlastUSBCounters
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {
@ -1281,7 +1286,7 @@ func (c *collector) collectUsb(ch chan<- prometheus.Metric) error {
return nil return nil
} }
func (c *collector) collectWindowsMediaMmr(ch chan<- prometheus.Metric) error { func (c *Collector) collectWindowsMediaMmr(ch chan<- prometheus.Metric) error {
var dst []win32_PerfRawData_Counters_VMwareBlastWindowsMediaMMRCounters var dst []win32_PerfRawData_Counters_VMwareBlastWindowsMediaMMRCounters
q := wmi.QueryAll(&dst, c.logger) q := wmi.QueryAll(&dst, c.logger)
if err := wmi.Query(q, &dst); err != nil { if err := wmi.Query(q, &dst); err != nil {

View File

@ -37,16 +37,16 @@ type Resolver struct {
} }
// NewResolver returns a Resolver structure. // NewResolver returns a Resolver structure.
func NewResolver(file string, logger log.Logger, insecure_skip_verify bool) (*Resolver, error) { func NewResolver(file string, logger log.Logger, insecureSkipVerify bool) (*Resolver, error) {
flags := map[string]string{} flags := map[string]string{}
var fileBytes []byte var fileBytes []byte
var err error var err error
if strings.HasPrefix(file, "http://") || strings.HasPrefix(file, "https://") { if strings.HasPrefix(file, "http://") || strings.HasPrefix(file, "https://") {
_ = level.Info(logger).Log("msg", fmt.Sprintf("Loading configuration file from URL: %v", file)) _ = level.Info(logger).Log("msg", fmt.Sprintf("Loading configuration file from URL: %v", file))
tr := &http.Transport{ tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure_skip_verify}, TLSClientConfig: &tls.Config{InsecureSkipVerify: insecureSkipVerify}, //nolint:gosec
} }
if insecure_skip_verify { if insecureSkipVerify {
_ = level.Warn(logger).Log("msg", "Loading configuration file with TLS verification disabled") _ = level.Warn(logger).Log("msg", "Loading configuration file with TLS verification disabled")
} }
client := &http.Client{Transport: tr} client := &http.Client{Transport: tr}

View File

@ -58,7 +58,9 @@ func flattenSlice(data []interface{}) map[string]string {
func convertMap(originalMap map[interface{}]interface{}) map[string]interface{} { func convertMap(originalMap map[interface{}]interface{}) map[string]interface{} {
convertedMap := map[string]interface{}{} convertedMap := map[string]interface{}{}
for key, value := range originalMap { for key, value := range originalMap {
convertedMap[key.(string)] = value if keyString, ok := key.(string); ok {
convertedMap[keyString] = value
}
} }
return convertedMap return convertedMap
} }

View File

@ -129,12 +129,13 @@ func WTSOpenServer(server string) (syscall.Handle, error) {
} }
func WTSCloseServer(server syscall.Handle) error { func WTSCloseServer(server syscall.Handle) error {
_, _, err := procWTSCloseServer.Call(uintptr(server)) r1, _, err := procWTSCloseServer.Call(uintptr(server))
if err != nil {
if r1 != 1 {
return fmt.Errorf("failed to close server: %w", err) return fmt.Errorf("failed to close server: %w", err)
} }
return err return nil
} }
func WTSFreeMemoryEx(class WTSTypeClass, pMemory uintptr, NumberOfEntries uint32) error { func WTSFreeMemoryEx(class WTSTypeClass, pMemory uintptr, NumberOfEntries uint32) error {

View File

@ -6,6 +6,7 @@ package eventlog
import ( import (
"bytes" "bytes"
"errors"
"fmt" "fmt"
"io" "io"
"sync" "sync"
@ -54,7 +55,11 @@ type eventlogLogger struct {
func (l *eventlogLogger) Log(keyvals ...interface{}) error { func (l *eventlogLogger) Log(keyvals ...interface{}) error {
priority := l.prioritySelector(keyvals...) priority := l.prioritySelector(keyvals...)
lb := l.getLoggerBuf() lb, err := l.getLoggerBuf()
if err != nil {
return err
}
defer l.putLoggerBuf(lb) defer l.putLoggerBuf(lb)
if err := lb.logger.Log(keyvals...); err != nil { if err := lb.logger.Log(keyvals...); err != nil {
return err return err
@ -77,15 +82,19 @@ type loggerBuf struct {
logger log.Logger logger log.Logger
} }
func (l *eventlogLogger) getLoggerBuf() *loggerBuf { func (l *eventlogLogger) getLoggerBuf() (*loggerBuf, error) {
lb := l.bufPool.Get().(*loggerBuf) lb, ok := l.bufPool.Get().(*loggerBuf)
if !ok {
return nil, errors.New("failed to get loggerBuf from pool")
}
if lb.buf == nil { if lb.buf == nil {
lb.buf = &bytes.Buffer{} lb.buf = &bytes.Buffer{}
lb.logger = l.newLogger(lb.buf) lb.logger = l.newLogger(lb.buf)
} else { } else {
lb.buf.Reset() lb.buf.Reset()
} }
return lb return lb, nil
} }
func (l *eventlogLogger) putLoggerBuf(lb *loggerBuf) { func (l *eventlogLogger) putLoggerBuf(lb *loggerBuf) {

View File

@ -8,14 +8,13 @@ import (
"github.com/alecthomas/kingpin/v2" "github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/prometheus-community/windows_exporter/pkg/collector" "github.com/prometheus-community/windows_exporter/pkg/collector"
"github.com/prometheus-community/windows_exporter/pkg/types"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
func FuncBenchmarkCollector(b *testing.B, name string, collectFunc types.CollectorBuilderWithFlags) { func FuncBenchmarkCollector[C collector.Collector](b *testing.B, name string, collectFunc collector.BuilderWithFlags[C]) {
c := collectFunc(kingpin.CommandLine) c := collectFunc(kingpin.CommandLine)
collectors := collector.New(map[string]types.Collector{name: c}) collectors := collector.New(map[string]collector.Collector{name: c})
require.NoError(b, collectors.Build()) require.NoError(b, collectors.Build())
collectors.SetLogger(log.NewNopLogger()) collectors.SetLogger(log.NewNopLogger())

View File

@ -1,28 +1,6 @@
//go:build windows
package types package types
import ( import "github.com/prometheus-community/windows_exporter/pkg/perflib"
"github.com/alecthomas/kingpin/v2"
"github.com/go-kit/log"
"github.com/prometheus-community/windows_exporter/pkg/perflib"
"github.com/prometheus/client_golang/prometheus"
)
type CollectorBuilder func(logger log.Logger) Collector
type CollectorBuilderWithFlags func(*kingpin.Application) Collector
// Collector is the interface a collector has to implement.
type Collector interface {
Build() error
// GetName get the name of the collector
GetName() string
// GetPerfCounter returns the perf counter required by the collector
GetPerfCounter() ([]string, error)
// Collect Get new metrics and expose them via prometheus registry.
Collect(ctx *ScrapeContext, ch chan<- prometheus.Metric) (err error)
SetLogger(logger log.Logger)
}
type ScrapeContext struct { type ScrapeContext struct {
PerfObjects map[string]*perflib.PerfObject PerfObjects map[string]*perflib.PerfObject

View File

@ -2,7 +2,6 @@ package wmi
import ( import (
"bytes" "bytes"
"reflect" "reflect"
"github.com/go-kit/log" "github.com/go-kit/log"

View File

@ -41,7 +41,16 @@ for ($i=1; $i -le 5; $i++) {
Write-Host "Waiting for exporter to start" Write-Host "Waiting for exporter to start"
} }
$response = Invoke-WebRequest -UseBasicParsing -URI http://127.0.0.1:9182/metrics try {
$response = Invoke-WebRequest -UseBasicParsing -URI http://127.0.0.1:9182/metrics
} catch {
Write-Host "STDOUT"
Get-Content "$($temp_dir)/windows_exporter.log"
Write-Host "STDERR"
Get-Content "$($temp_dir)/windows_exporter_error.log"
throw $_
}
# Response output must be split and saved as UTF-8. # Response output must be split and saved as UTF-8.
$response.content -split "[`r`n]"| Select-String -NotMatch $skip_re | Set-Content -Encoding utf8 "$($temp_dir)/e2e-output.txt" $response.content -split "[`r`n]"| Select-String -NotMatch $skip_re | Set-Content -Encoding utf8 "$($temp_dir)/e2e-output.txt"
Stop-Process -Id $exporter_proc.Id Stop-Process -Id $exporter_proc.Id