-
Notifications
You must be signed in to change notification settings - Fork 0
feat: Add new Emitter API to start and stop metrics #18
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
felixge
wants to merge
3
commits into
main
Choose a base branch
from
push-ltsptlnlnkpt
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+113
−108
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,7 +2,7 @@ | |
package runtimemetrics | ||
|
||
import ( | ||
"errors" | ||
"cmp" | ||
"fmt" | ||
"log/slog" | ||
"math" | ||
|
@@ -13,48 +13,63 @@ import ( | |
"time" | ||
) | ||
|
||
// pollFrequency is the frequency at which we poll runtime/metrics and report | ||
// them to statsd. The statsd client aggregates this data, usually over a 2s | ||
// window [1], and so does the agent, usually over a 10s window [2]. | ||
// | ||
// Our goal is to submit one data point per aggregation window, using the | ||
// CountWithTimestamp / GaugeWithTimestamp APIs for submitting precisely aligned | ||
// metrics, to enable comparing them with one another. | ||
// | ||
// [1] https://github.com/DataDog/datadog-go/blob/e612112c8bb396b33ad5d9edd645d289b07d0e40/statsd/options.go/#L23 | ||
// [2] https://docs.datadoghq.com/developers/dogstatsd/data_aggregation/#how-is-aggregation-performed-with-the-dogstatsd-server | ||
var pollFrequency = 10 * time.Second | ||
|
||
var unknownMetricLogOnce, unsupportedKindLogOnce sync.Once | ||
|
||
// mu protects the variables below | ||
var mu sync.Mutex | ||
var enabled bool | ||
|
||
// NOTE: The Start method below is intentionally minimal for now. We probably want to think about | ||
// this API a bit more before we publish it in dd-trace-go. I.e. do we want to make the | ||
// pollFrequency configurable (higher resolution at the cost of higher overhead on the agent and | ||
// statsd library)? Do we want to support multiple instances? We probably also want a (flushing?) | ||
// stop method. | ||
|
||
// Start starts reporting runtime/metrics to the given statsd client. | ||
func Start(statsd partialStatsdClientInterface, logger *slog.Logger) error { | ||
mu.Lock() | ||
defer mu.Unlock() | ||
|
||
if enabled { | ||
// We could support multiple instances, but the use cases for it are not | ||
// clear, so for now let's consider this to be a misconfiguration. | ||
return errors.New("runtimemetrics has already been started") | ||
// Options are the options for the runtime metrics emitter. | ||
type Options struct { | ||
// Logger is used to log errors. Defaults to slog.Default() if nil. | ||
Logger *slog.Logger | ||
// Tags are added to all metrics. | ||
Tags []string | ||
// Period is the period at which we poll runtime/metrics and report | ||
// them to statsd. Defaults to 10s. | ||
// | ||
// The statsd client aggregates this data, usually over a 2s window [1], and | ||
// so does the agent, usually over a 10s window [2]. | ||
// | ||
// We submit one data point per aggregation window, using the | ||
// CountWithTimestamp / GaugeWithTimestamp APIs for submitting precisely | ||
// aligned metrics, to enable comparing them with one another. | ||
// | ||
// [1] https://github.com/DataDog/datadog-go/blob/e612112c8bb396b33ad5d9edd645d289b07d0e40/statsd/options.go/#L23 | ||
// [2] https://docs.datadoghq.com/developers/dogstatsd/data_aggregation/#how-is-aggregation-performed-with-the-dogstatsd-server | ||
Period time.Duration | ||
} | ||
|
||
// NewEmitter creates a new runtime metrics emitter and starts it. | ||
func NewEmitter(statsd partialStatsdClientInterface, opts *Options) *Emitter { | ||
if opts == nil { | ||
opts = &Options{} | ||
} | ||
e := &Emitter{ | ||
statsd: statsd, | ||
logger: cmp.Or(opts.Logger, slog.Default()), | ||
tags: opts.Tags, | ||
stop: make(chan struct{}), | ||
period: cmp.Or(opts.Period, 10*time.Second), | ||
} | ||
go e.emit() | ||
return e | ||
} | ||
|
||
// Emitter submits runtime/metrics to statsd on a regular interval. | ||
type Emitter struct { | ||
statsd partialStatsdClientInterface | ||
logger *slog.Logger | ||
tags []string | ||
period time.Duration | ||
|
||
stop chan struct{} | ||
} | ||
|
||
// emit emits runtime/metrics to statsd on a regular interval. | ||
func (e *Emitter) emit() { | ||
descs := metrics.All() | ||
rms := newRuntimeMetricStore(descs, statsd, logger) | ||
tags := append(getBaseTags(), e.tags...) | ||
rms := newRuntimeMetricStore(descs, e.statsd, e.logger, tags) | ||
// TODO: Go services experiencing high scheduling latency might see a | ||
// large variance for the period in between rms.report calls. This might | ||
// cause spikes in cumulative metric reporting. Should we try to correct | ||
// for this by measuring the actual reporting time delta and | ||
// extrapolating our numbers? | ||
// for this by measuring the actual reporting time delta to adjust | ||
// the numbers? | ||
// | ||
// Another challenge is that some metrics only update after GC mark | ||
// termination, see [1][2]. This means that it's likely that the rate of | ||
|
@@ -63,20 +78,25 @@ func Start(statsd partialStatsdClientInterface, logger *slog.Logger) error { | |
// | ||
// [1] https://github.com/golang/go/blob/go1.21.3/src/runtime/mstats.go#L939 | ||
// [2] https://github.com/golang/go/issues/59749 | ||
go func() { | ||
for range time.Tick(pollFrequency) { | ||
tick := time.Tick(e.period) | ||
for { | ||
select { | ||
case <-e.stop: | ||
return | ||
case <-tick: | ||
felixge marked this conversation as resolved.
Show resolved
Hide resolved
|
||
rms.report() | ||
} | ||
}() | ||
enabled = true | ||
return nil | ||
} | ||
} | ||
|
||
func SetBaseTags(tags []string) { | ||
muTags.Lock() | ||
defer muTags.Unlock() | ||
|
||
rootBaseTags = tags | ||
// Stop stops the emitter. It is idempotent. | ||
func (e *Emitter) Stop() { | ||
select { | ||
case <-e.stop: | ||
return | ||
default: | ||
close(e.stop) | ||
} | ||
} | ||
|
||
type runtimeMetric struct { | ||
|
@@ -89,10 +109,12 @@ type runtimeMetric struct { | |
|
||
// the map key is the name of the metric in runtime/metrics | ||
type runtimeMetricStore struct { | ||
metrics map[string]*runtimeMetric | ||
statsd partialStatsdClientInterface | ||
logger *slog.Logger | ||
baseTags []string | ||
metrics map[string]*runtimeMetric | ||
statsd partialStatsdClientInterface | ||
logger *slog.Logger | ||
baseTags []string | ||
unknownMetricLogOnce *sync.Once | ||
unsupportedKindLogOnce *sync.Once | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. todo: follow-up PR - refactor this into the Emitter type |
||
|
||
// partialStatsdClientInterface is the subset of statsd.ClientInterface that is | ||
|
@@ -106,12 +128,14 @@ type partialStatsdClientInterface interface { | |
DistributionSamples(name string, values []float64, tags []string, rate float64) error | ||
} | ||
|
||
func newRuntimeMetricStore(descs []metrics.Description, statsdClient partialStatsdClientInterface, logger *slog.Logger) runtimeMetricStore { | ||
func newRuntimeMetricStore(descs []metrics.Description, statsdClient partialStatsdClientInterface, logger *slog.Logger, tags []string) runtimeMetricStore { | ||
rms := runtimeMetricStore{ | ||
metrics: map[string]*runtimeMetric{}, | ||
statsd: statsdClient, | ||
logger: logger, | ||
baseTags: getBaseTags(), | ||
metrics: map[string]*runtimeMetric{}, | ||
statsd: statsdClient, | ||
logger: logger, | ||
baseTags: tags, | ||
unknownMetricLogOnce: &sync.Once{}, | ||
unsupportedKindLogOnce: &sync.Once{}, | ||
} | ||
|
||
for _, d := range descs { | ||
|
@@ -269,15 +293,15 @@ func (rms runtimeMetricStore) report() { | |
case metrics.KindBad: | ||
// This should never happen because all metrics are supported | ||
// by construction. | ||
unknownMetricLogOnce.Do(func() { | ||
rms.unknownMetricLogOnce.Do(func() { | ||
rms.logger.Error("runtimemetrics: encountered an unknown metric, this should never happen and might indicate a bug", slog.Attr{Key: "metric_name", Value: slog.StringValue(name)}) | ||
}) | ||
default: | ||
// This may happen as new metric kinds get added. | ||
// | ||
// The safest thing to do here is to simply log it somewhere once | ||
// as something to look into, but ignore it for now. | ||
unsupportedKindLogOnce.Do(func() { | ||
rms.unsupportedKindLogOnce.Do(func() { | ||
rms.logger.Error("runtimemetrics: unsupported metric kind, support for that kind should be added in pkg/runtimemetrics", | ||
slog.Attr{Key: "metric_name", Value: slog.StringValue(name)}, | ||
slog.Attr{Key: "kind", Value: slog.AnyValue(rm.currentValue.Kind())}, | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.