Implement review suggestions

This commit is contained in:
Daniel 2021-01-29 16:55:01 +01:00
parent 813a5f0f0d
commit 3e7e5e0096
5 changed files with 44 additions and 29 deletions

View file

@ -69,7 +69,7 @@ func WriteMetrics(w io.Writer, permission api.Permission, expertiseLevel config.
registryLock.RLock() registryLock.RLock()
defer registryLock.RUnlock() defer registryLock.RUnlock()
// Check if metric ID is already registered. // Write all matching metrics.
for _, metric := range registry { for _, metric := range registry {
if permission >= metric.Opts().Permission && if permission >= metric.Opts().Permission &&
expertiseLevel >= metric.Opts().ExpertiseLevel { expertiseLevel >= metric.Opts().ExpertiseLevel {
@ -96,20 +96,18 @@ func writeMetricsTo(ctx context.Context, url string) error {
} }
// Send. // Send.
client := &http.Client{} resp, err := http.DefaultClient.Do(req)
resp, err := client.Do(req)
if err != nil { if err != nil {
return err return err
} }
defer resp.Body.Close() defer resp.Body.Close()
// Check return status. // Check return status.
switch resp.StatusCode { if resp.StatusCode >= 200 && resp.StatusCode <= 299 {
case http.StatusOK,
http.StatusAccepted,
http.StatusNoContent:
return nil return nil
default: }
// Get and return error.
body, _ := ioutil.ReadAll(resp.Body) body, _ := ioutil.ReadAll(resp.Body)
return fmt.Errorf( return fmt.Errorf(
"got %s while writing metrics to %s: %s", "got %s while writing metrics to %s: %s",
@ -117,7 +115,6 @@ func writeMetricsTo(ctx context.Context, url string) error {
url, url,
body, body,
) )
}
} }
func metricsWriter(ctx context.Context) error { func metricsWriter(ctx context.Context) error {

View file

@ -126,11 +126,12 @@ func (m *metricBase) buildLabeledID() string {
return metricID return metricID
} }
// Add global labels to the custom ones. // Add global labels to the custom ones, if they don't exist yet.
// This overrides conflicts.
for labelName, labelValue := range globalLabels { for labelName, labelValue := range globalLabels {
if _, ok := m.Labels[labelName]; !ok {
m.Labels[labelName] = labelValue m.Labels[labelName] = labelValue
} }
}
// Render labels into a slice and sort them in order to make the labeled ID // Render labels into a slice and sort them in order to make the labeled ID
// reproducible. // reproducible.

View file

@ -9,6 +9,9 @@ import (
) )
func init() { func init() {
registryLock.Lock()
defer registryLock.Unlock()
registry = append(registry, &runtimeMetrics{}) registry = append(registry, &runtimeMetrics{})
} }

View file

@ -21,6 +21,7 @@ var (
globalLabels = make(map[string]string) globalLabels = make(map[string]string)
pushURL string pushURL string
metricInstance string
// ErrAlreadyStarted is returned when an operation is only valid before the // ErrAlreadyStarted is returned when an operation is only valid before the
// first metric is registered, and is called after. // first metric is registered, and is called after.
@ -36,11 +37,19 @@ var (
func init() { func init() {
flag.StringVar(&pushURL, "push-metrics", "", "URL to push prometheus metrics to") flag.StringVar(&pushURL, "push-metrics", "", "URL to push prometheus metrics to")
flag.StringVar(&metricInstance, "metrics-instance", "", "Set the global instance label")
module = modules.Register("metrics", prep, start, stop, "database", "api") module = modules.Register("metrics", prep, start, stop, "database", "api")
} }
func prep() error { func prep() error {
// Add metric instance name as global variable if set.
if metricInstance != "" {
if err := AddGlobalLabel("instance", metricInstance); err != nil {
return err
}
}
return registerInfoMetric() return registerInfoMetric()
} }
@ -75,7 +84,7 @@ func register(m Metric) error {
// Add new metric to registry and sort it. // Add new metric to registry and sort it.
registry = append(registry, m) registry = append(registry, m)
sort.Sort(metricRegistry(registry)) sort.Sort(byLabeledID(registry))
// Set flag that first metric is now registered. // Set flag that first metric is now registered.
firstMetricRegistered = true firstMetricRegistered = true
@ -124,8 +133,8 @@ func AddGlobalLabel(name, value string) error {
return nil return nil
} }
type metricRegistry []Metric type byLabeledID []Metric
func (r metricRegistry) Len() int { return len(r) } func (r byLabeledID) Len() int { return len(r) }
func (r metricRegistry) Less(i, j int) bool { return r[i].LabeledID() < r[j].LabeledID() } func (r byLabeledID) Less(i, j int) bool { return r[i].LabeledID() < r[j].LabeledID() }
func (r metricRegistry) Swap(i, j int) { r[i], r[j] = r[j], r[i] } func (r byLabeledID) Swap(i, j int) { r[i], r[j] = r[j], r[i] }

View file

@ -14,13 +14,18 @@ import (
var ( var (
storage *metricsStorage storage *metricsStorage
storageLoaded = abool.New()
storageKey string storageKey string
storageInit = abool.New()
storageLoaded = abool.New()
db = database.NewInterface(&database.Options{ db = database.NewInterface(&database.Options{
Local: true, Local: true,
Internal: true, Internal: true,
}) })
// ErrAlreadyInitialized is returned when trying to initialize an option
// more than once.
ErrAlreadyInitialized = errors.New("already initialized")
) )
type metricsStorage struct { type metricsStorage struct {
@ -39,9 +44,9 @@ type metricsStorage struct {
// persistence. // persistence.
// May only be called once. // May only be called once.
func EnableMetricPersistence(key string) error { func EnableMetricPersistence(key string) error {
// Check if already loaded. // Check if already initialized.
if storageLoaded.IsSet() { if !storageInit.SetToIf(false, true) {
return nil return ErrAlreadyInitialized
} }
// Set storage key. // Set storage key.
@ -85,7 +90,7 @@ func (c *Counter) loadState() {
func storePersistentMetrics() { func storePersistentMetrics() {
// Check if persistence is enabled. // Check if persistence is enabled.
if storageKey == "" { if !storageInit.IsSet() || storageKey == "" {
return return
} }