2023-08-11 13:12:13 +00:00
|
|
|
// Copyright (c) HashiCorp, Inc.
|
|
|
|
// SPDX-License-Identifier: BUSL-1.1
|
|
|
|
|
2023-08-01 21:20:18 +00:00
|
|
|
package hcp
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-01-16 16:46:12 +00:00
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
2023-08-01 21:20:18 +00:00
|
|
|
"net/url"
|
2024-01-16 16:46:12 +00:00
|
|
|
"reflect"
|
2023-08-01 21:20:18 +00:00
|
|
|
"regexp"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/armon/go-metrics"
|
2023-08-30 17:25:26 +00:00
|
|
|
"github.com/go-openapi/runtime"
|
2023-08-01 21:20:18 +00:00
|
|
|
"github.com/hashicorp/go-hclog"
|
2024-01-16 16:46:12 +00:00
|
|
|
"github.com/hashicorp/go-retryablehttp"
|
2023-08-01 21:20:18 +00:00
|
|
|
|
|
|
|
"github.com/hashicorp/consul/agent/hcp/client"
|
2024-01-16 16:46:12 +00:00
|
|
|
"github.com/hashicorp/consul/agent/hcp/config"
|
2023-08-01 21:20:18 +00:00
|
|
|
"github.com/hashicorp/consul/agent/hcp/telemetry"
|
2024-01-16 16:46:12 +00:00
|
|
|
"github.com/hashicorp/consul/version"
|
2023-08-01 21:20:18 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
// internalMetricRefreshFailure is a metric to monitor refresh failures.
|
|
|
|
internalMetricRefreshFailure []string = []string{"hcp", "telemetry_config_provider", "refresh", "failure"}
|
|
|
|
// internalMetricRefreshSuccess is a metric to monitor refresh successes.
|
|
|
|
internalMetricRefreshSuccess []string = []string{"hcp", "telemetry_config_provider", "refresh", "success"}
|
2023-08-30 17:25:26 +00:00
|
|
|
// defaultTelemetryConfigRefreshInterval is a default fallback in case the first HCP fetch fails.
|
|
|
|
defaultTelemetryConfigRefreshInterval = 1 * time.Minute
|
2023-08-01 21:20:18 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Ensure hcpProviderImpl implements telemetry provider interfaces.
|
2024-01-30 15:40:36 +00:00
|
|
|
var _ TelemetryProvider = &hcpProviderImpl{}
|
2023-08-01 21:20:18 +00:00
|
|
|
var _ telemetry.ConfigProvider = &hcpProviderImpl{}
|
|
|
|
var _ telemetry.EndpointProvider = &hcpProviderImpl{}
|
2024-01-16 16:46:12 +00:00
|
|
|
var _ client.MetricsClientProvider = &hcpProviderImpl{}
|
2023-08-01 21:20:18 +00:00
|
|
|
|
|
|
|
// hcpProviderImpl holds telemetry configuration and settings for continuous fetch of new config from HCP.
|
|
|
|
// it updates configuration, if changes are detected.
|
|
|
|
type hcpProviderImpl struct {
|
|
|
|
// cfg holds configuration that can be dynamically updated.
|
|
|
|
cfg *dynamicConfig
|
2024-01-16 16:46:12 +00:00
|
|
|
// httpCfg holds configuration for the HTTP client
|
|
|
|
httpCfg *httpCfg
|
2023-08-01 21:20:18 +00:00
|
|
|
|
2024-01-16 16:46:12 +00:00
|
|
|
// Reader-writer mutexes are used as the provider is read heavy.
|
2023-08-01 21:20:18 +00:00
|
|
|
// OTEL components access telemetryConfig during metrics collection and export (read).
|
2024-01-16 16:46:12 +00:00
|
|
|
// Meanwhile, configs are only updated when there are changes (write).
|
|
|
|
rw sync.RWMutex
|
|
|
|
httpCfgRW sync.RWMutex
|
|
|
|
|
|
|
|
// running indicates if the HCP telemetry config provider has been started
|
|
|
|
running bool
|
|
|
|
|
2024-01-30 15:40:36 +00:00
|
|
|
// stopCh is used to signal that the telemetry config provider should stop running.
|
|
|
|
stopCh chan struct{}
|
|
|
|
|
2023-08-01 21:20:18 +00:00
|
|
|
// hcpClient is an authenticated client used to make HTTP requests to HCP.
|
|
|
|
hcpClient client.Client
|
2024-01-16 16:46:12 +00:00
|
|
|
|
|
|
|
// logger is the HCP logger for the provider
|
|
|
|
logger hclog.Logger
|
|
|
|
|
|
|
|
// testUpdateConfigCh is used by unit tests to signal when an update config has occurred
|
|
|
|
testUpdateConfigCh chan struct{}
|
2023-08-01 21:20:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// dynamicConfig is a set of configurable settings for metrics collection, processing and export.
|
|
|
|
// fields MUST be exported to compute hash for equals method.
|
|
|
|
type dynamicConfig struct {
|
2023-08-30 17:25:26 +00:00
|
|
|
disabled bool
|
|
|
|
endpoint *url.URL
|
|
|
|
labels map[string]string
|
|
|
|
filters *regexp.Regexp
|
2023-08-01 21:20:18 +00:00
|
|
|
// refreshInterval controls the interval at which configuration is fetched from HCP to refresh config.
|
2023-08-30 17:25:26 +00:00
|
|
|
refreshInterval time.Duration
|
2023-08-01 21:20:18 +00:00
|
|
|
}
|
|
|
|
|
2023-08-30 17:25:26 +00:00
|
|
|
// defaultDisabledCfg disables metric collection and contains default config values.
|
|
|
|
func defaultDisabledCfg() *dynamicConfig {
|
|
|
|
return &dynamicConfig{
|
|
|
|
labels: map[string]string{},
|
|
|
|
filters: client.DefaultMetricFilters,
|
|
|
|
refreshInterval: defaultTelemetryConfigRefreshInterval,
|
|
|
|
endpoint: nil,
|
|
|
|
disabled: true,
|
2023-08-01 21:20:18 +00:00
|
|
|
}
|
2023-08-30 17:25:26 +00:00
|
|
|
}
|
2023-08-01 21:20:18 +00:00
|
|
|
|
2024-01-16 16:46:12 +00:00
|
|
|
// httpCfg is a set of configurable settings for the HTTP client used to export metrics
|
|
|
|
type httpCfg struct {
|
|
|
|
header *http.Header
|
|
|
|
client *retryablehttp.Client
|
|
|
|
}
|
|
|
|
|
2024-01-30 15:40:36 +00:00
|
|
|
//go:generate mockery --name TelemetryProvider --with-expecter --inpackage
|
|
|
|
type TelemetryProvider interface {
|
|
|
|
Start(ctx context.Context, c *HCPProviderCfg) error
|
|
|
|
Stop()
|
|
|
|
}
|
|
|
|
|
2024-01-16 16:46:12 +00:00
|
|
|
type HCPProviderCfg struct {
|
|
|
|
HCPClient client.Client
|
|
|
|
HCPConfig config.CloudConfigurer
|
|
|
|
}
|
|
|
|
|
2023-08-30 17:25:26 +00:00
|
|
|
// NewHCPProvider initializes and starts a HCP Telemetry provider.
|
2024-01-16 16:46:12 +00:00
|
|
|
func NewHCPProvider(ctx context.Context) *hcpProviderImpl {
|
2023-08-30 17:25:26 +00:00
|
|
|
h := &hcpProviderImpl{
|
|
|
|
// Initialize with default config values.
|
2024-01-16 16:46:12 +00:00
|
|
|
cfg: defaultDisabledCfg(),
|
|
|
|
httpCfg: &httpCfg{},
|
|
|
|
logger: hclog.FromContext(ctx),
|
|
|
|
}
|
|
|
|
|
|
|
|
return h
|
|
|
|
}
|
|
|
|
|
2024-01-30 15:40:36 +00:00
|
|
|
// Start starts a process that continuously checks for updates to the telemetry configuration
|
2024-01-16 16:46:12 +00:00
|
|
|
// by making a request to HCP. It only starts running if it's not already running.
|
2024-01-30 15:40:36 +00:00
|
|
|
func (h *hcpProviderImpl) Start(ctx context.Context, c *HCPProviderCfg) error {
|
2024-01-29 22:31:44 +00:00
|
|
|
changed := h.setRunning(true)
|
|
|
|
if !changed {
|
|
|
|
// Provider is already running.
|
2024-01-16 16:46:12 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Update the provider with the HCP configurations
|
|
|
|
h.hcpClient = c.HCPClient
|
|
|
|
err := h.updateHTTPConfig(c.HCPConfig)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to initialize HCP telemetry provider: %v", err)
|
2023-08-01 21:20:18 +00:00
|
|
|
}
|
|
|
|
|
2023-08-30 17:25:26 +00:00
|
|
|
go h.run(ctx)
|
2023-08-01 21:20:18 +00:00
|
|
|
|
2024-01-16 16:46:12 +00:00
|
|
|
return nil
|
2023-08-01 21:20:18 +00:00
|
|
|
}
|
|
|
|
|
2024-01-16 16:46:12 +00:00
|
|
|
// run continuously checks for updates to the telemetry configuration by making a request to HCP.
|
|
|
|
func (h *hcpProviderImpl) run(ctx context.Context) error {
|
|
|
|
h.logger.Debug("starting telemetry config provider")
|
|
|
|
|
2023-08-30 17:25:26 +00:00
|
|
|
// Try to initialize config once before starting periodic fetch.
|
|
|
|
h.updateConfig(ctx)
|
|
|
|
|
2024-01-30 15:40:36 +00:00
|
|
|
ticker := time.NewTicker(h.getRefreshInterval())
|
2023-08-01 21:20:18 +00:00
|
|
|
defer ticker.Stop()
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ticker.C:
|
2023-08-30 17:25:26 +00:00
|
|
|
if newRefreshInterval := h.updateConfig(ctx); newRefreshInterval > 0 {
|
|
|
|
ticker.Reset(newRefreshInterval)
|
2023-08-01 21:20:18 +00:00
|
|
|
}
|
|
|
|
case <-ctx.Done():
|
2024-01-16 16:46:12 +00:00
|
|
|
return nil
|
2024-01-30 15:40:36 +00:00
|
|
|
case <-h.stopCh:
|
|
|
|
return nil
|
2023-08-01 21:20:18 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-08-30 17:25:26 +00:00
|
|
|
// updateConfig makes a HTTP request to HCP to update metrics configuration held in the provider.
|
|
|
|
func (h *hcpProviderImpl) updateConfig(ctx context.Context) time.Duration {
|
2024-01-16 16:46:12 +00:00
|
|
|
logger := h.logger.Named("telemetry_config_provider")
|
|
|
|
|
|
|
|
if h.testUpdateConfigCh != nil {
|
|
|
|
defer func() {
|
|
|
|
select {
|
|
|
|
case h.testUpdateConfigCh <- struct{}{}:
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
|
|
|
|
if h.hcpClient == nil || reflect.ValueOf(h.hcpClient).IsNil() {
|
|
|
|
// Disable metrics if HCP client is not configured
|
|
|
|
disabledMetricsCfg := defaultDisabledCfg()
|
|
|
|
h.modifyDynamicCfg(disabledMetricsCfg)
|
|
|
|
return disabledMetricsCfg.refreshInterval
|
|
|
|
}
|
2023-08-01 21:20:18 +00:00
|
|
|
|
|
|
|
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
|
2024-01-16 16:46:12 +00:00
|
|
|
logger.Trace("fetching telemetry config")
|
2023-08-01 21:20:18 +00:00
|
|
|
telemetryCfg, err := h.hcpClient.FetchTelemetryConfig(ctx)
|
|
|
|
if err != nil {
|
2023-08-30 17:25:26 +00:00
|
|
|
// Only disable metrics on 404 or 401 to handle the case of an unlinked cluster.
|
|
|
|
// For other errors such as 5XX ones, we continue metrics collection, as these are potentially transient server-side errors.
|
|
|
|
apiErr, ok := err.(*runtime.APIError)
|
|
|
|
if ok && apiErr.IsClientError() {
|
|
|
|
disabledMetricsCfg := defaultDisabledCfg()
|
|
|
|
h.modifyDynamicCfg(disabledMetricsCfg)
|
|
|
|
return disabledMetricsCfg.refreshInterval
|
|
|
|
}
|
|
|
|
|
2023-08-01 21:20:18 +00:00
|
|
|
logger.Error("failed to fetch telemetry config from HCP", "error", err)
|
|
|
|
metrics.IncrCounter(internalMetricRefreshFailure, 1)
|
2023-08-30 17:25:26 +00:00
|
|
|
return 0
|
2023-08-01 21:20:18 +00:00
|
|
|
}
|
2024-01-16 16:46:12 +00:00
|
|
|
logger.Trace("successfully fetched telemetry config")
|
2023-08-01 21:20:18 +00:00
|
|
|
|
|
|
|
// newRefreshInterval of 0 or less can cause ticker Reset() panic.
|
|
|
|
newRefreshInterval := telemetryCfg.RefreshConfig.RefreshInterval
|
|
|
|
if newRefreshInterval <= 0 {
|
|
|
|
logger.Error("invalid refresh interval duration", "refreshInterval", newRefreshInterval)
|
|
|
|
metrics.IncrCounter(internalMetricRefreshFailure, 1)
|
2023-08-30 17:25:26 +00:00
|
|
|
return 0
|
2023-08-01 21:20:18 +00:00
|
|
|
}
|
|
|
|
|
2023-08-30 17:25:26 +00:00
|
|
|
newCfg := &dynamicConfig{
|
|
|
|
filters: telemetryCfg.MetricsConfig.Filters,
|
|
|
|
endpoint: telemetryCfg.MetricsConfig.Endpoint,
|
|
|
|
labels: telemetryCfg.MetricsConfig.Labels,
|
|
|
|
refreshInterval: telemetryCfg.RefreshConfig.RefreshInterval,
|
|
|
|
disabled: telemetryCfg.MetricsConfig.Disabled,
|
2023-08-01 21:20:18 +00:00
|
|
|
}
|
|
|
|
|
2023-08-30 17:25:26 +00:00
|
|
|
h.modifyDynamicCfg(newCfg)
|
|
|
|
|
|
|
|
return newCfg.refreshInterval
|
|
|
|
}
|
|
|
|
|
|
|
|
// modifyDynamicCfg acquires a write lock to update new configuration and emits a success metric.
|
|
|
|
func (h *hcpProviderImpl) modifyDynamicCfg(newCfg *dynamicConfig) {
|
2023-08-01 21:20:18 +00:00
|
|
|
h.rw.Lock()
|
2023-08-30 17:25:26 +00:00
|
|
|
h.cfg = newCfg
|
2023-08-01 21:20:18 +00:00
|
|
|
h.rw.Unlock()
|
|
|
|
|
|
|
|
metrics.IncrCounter(internalMetricRefreshSuccess, 1)
|
|
|
|
}
|
|
|
|
|
2024-01-30 15:40:36 +00:00
|
|
|
func (h *hcpProviderImpl) getRefreshInterval() time.Duration {
|
|
|
|
h.rw.RLock()
|
|
|
|
defer h.rw.RUnlock()
|
|
|
|
|
|
|
|
return h.cfg.refreshInterval
|
|
|
|
}
|
|
|
|
|
2023-08-01 21:20:18 +00:00
|
|
|
// GetEndpoint acquires a read lock to return endpoint configuration for consumers.
|
|
|
|
func (h *hcpProviderImpl) GetEndpoint() *url.URL {
|
|
|
|
h.rw.RLock()
|
|
|
|
defer h.rw.RUnlock()
|
|
|
|
|
2023-08-30 17:25:26 +00:00
|
|
|
return h.cfg.endpoint
|
2023-08-01 21:20:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// GetFilters acquires a read lock to return filters configuration for consumers.
|
|
|
|
func (h *hcpProviderImpl) GetFilters() *regexp.Regexp {
|
|
|
|
h.rw.RLock()
|
|
|
|
defer h.rw.RUnlock()
|
|
|
|
|
2023-08-30 17:25:26 +00:00
|
|
|
return h.cfg.filters
|
2023-08-01 21:20:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// GetLabels acquires a read lock to return labels configuration for consumers.
|
|
|
|
func (h *hcpProviderImpl) GetLabels() map[string]string {
|
|
|
|
h.rw.RLock()
|
|
|
|
defer h.rw.RUnlock()
|
|
|
|
|
2023-08-30 17:25:26 +00:00
|
|
|
return h.cfg.labels
|
|
|
|
}
|
|
|
|
|
|
|
|
// IsDisabled acquires a read lock and return true if metrics are enabled.
|
|
|
|
func (h *hcpProviderImpl) IsDisabled() bool {
|
|
|
|
h.rw.RLock()
|
|
|
|
defer h.rw.RUnlock()
|
|
|
|
|
|
|
|
return h.cfg.disabled
|
2023-08-01 21:20:18 +00:00
|
|
|
}
|
2024-01-16 16:46:12 +00:00
|
|
|
|
|
|
|
// updateHTTPConfig updates the HTTP configuration values that rely on the HCP configuration.
|
|
|
|
func (h *hcpProviderImpl) updateHTTPConfig(cfg config.CloudConfigurer) error {
|
|
|
|
h.httpCfgRW.Lock()
|
|
|
|
defer h.httpCfgRW.Unlock()
|
|
|
|
|
|
|
|
if cfg == nil {
|
|
|
|
return errors.New("must provide valid HCP configuration")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Update headers
|
|
|
|
r, err := cfg.Resource()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed set telemetry client headers: %v", err)
|
|
|
|
}
|
|
|
|
header := make(http.Header)
|
|
|
|
header.Set("content-type", "application/x-protobuf")
|
|
|
|
header.Set("x-hcp-resource-id", r.String())
|
|
|
|
header.Set("x-channel", fmt.Sprintf("consul/%s", version.GetHumanVersion()))
|
|
|
|
h.httpCfg.header = &header
|
|
|
|
|
|
|
|
// Update HTTP client
|
|
|
|
hcpCfg, err := cfg.HCPConfig()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to configure telemetry HTTP client: %v", err)
|
|
|
|
}
|
2024-02-08 16:00:20 +00:00
|
|
|
h.httpCfg.client = client.NewHTTPClient(hcpCfg.APITLSConfig(), hcpCfg)
|
2024-01-16 16:46:12 +00:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetHeader acquires a read lock to return the HTTP request headers needed
|
|
|
|
// to export metrics.
|
|
|
|
func (h *hcpProviderImpl) GetHeader() http.Header {
|
|
|
|
h.httpCfgRW.RLock()
|
|
|
|
defer h.httpCfgRW.RUnlock()
|
|
|
|
|
|
|
|
if h.httpCfg.header == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return h.httpCfg.header.Clone()
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetHTTPClient acquires a read lock to return the retryable HTTP client needed
|
|
|
|
// to export metrics.
|
|
|
|
func (h *hcpProviderImpl) GetHTTPClient() *retryablehttp.Client {
|
|
|
|
h.httpCfgRW.RLock()
|
|
|
|
defer h.httpCfgRW.RUnlock()
|
|
|
|
|
|
|
|
return h.httpCfg.client
|
|
|
|
}
|
|
|
|
|
2024-01-29 22:31:44 +00:00
|
|
|
// setRunning acquires a write lock to set whether the provider is running.
|
|
|
|
// If the given value is the same as the current running status, it returns
|
|
|
|
// false. If current status is updated to the given status, it returns true.
|
|
|
|
func (h *hcpProviderImpl) setRunning(r bool) bool {
|
|
|
|
h.rw.Lock()
|
|
|
|
defer h.rw.Unlock()
|
|
|
|
|
|
|
|
if h.running == r {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2024-01-30 15:40:36 +00:00
|
|
|
// Initialize or close the stop channel depending what running status
|
|
|
|
// we're transitioning to. Channel must be initialized on start since
|
|
|
|
// a provider can be stopped and started multiple times.
|
|
|
|
if r {
|
|
|
|
h.stopCh = make(chan struct{})
|
|
|
|
} else {
|
|
|
|
close(h.stopCh)
|
|
|
|
}
|
|
|
|
|
2024-01-29 22:31:44 +00:00
|
|
|
h.running = r
|
2024-01-16 16:46:12 +00:00
|
|
|
|
2024-01-29 22:31:44 +00:00
|
|
|
return true
|
2024-01-16 16:46:12 +00:00
|
|
|
}
|
2024-01-30 15:40:36 +00:00
|
|
|
|
|
|
|
// Stop acquires a write lock to mark the provider as not running and sends a stop signal to the
|
|
|
|
// main run loop. It also updates the provider with a disabled configuration.
|
|
|
|
func (h *hcpProviderImpl) Stop() {
|
|
|
|
changed := h.setRunning(false)
|
|
|
|
if !changed {
|
|
|
|
h.logger.Trace("telemetry config provider already stopped")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
h.rw.Lock()
|
|
|
|
h.cfg = defaultDisabledCfg()
|
|
|
|
h.rw.Unlock()
|
|
|
|
|
|
|
|
h.logger.Debug("telemetry config provider stopped")
|
|
|
|
}
|