cloudwatch

package
v1.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 20, 2026 License: MIT Imports: 39 Imported by: 0

README

CloudWatch

Parity grade: A · SDK aws-sdk-go-v2/service/cloudwatch@v1.55.1 · last audited 2026-07-11 (95dfa093)

Coverage

Metric Value
Operations audited 50 (48 ok, 1 partial, 1 deferred)
Feature families 1 (1 ok)
Known gaps 1
Deferred items 3
Resource leaks clean
Known gaps
  • PutDashboard never validates DashboardBody JSON/widget schema, so DashboardValidationMessages is always empty even for malformed input (bd: gopherstack-3ro) # PutMetricData timestamp acceptance window (bd: gopherstack-pyv) — FIXED this # pass, see PutMetricData row and Notes below. bd issue should be closed.
Deferred
  • widget.go / widget_draw.go / widget_font.go (GetMetricWidgetImage PNG rendering internals — not a wire-shape or state-correctness concern, only visual fidelity)
  • metric-stream Firehose delivery payload format (OutputFormat json/opentelemetry0.7 byte-level shape)
  • insight-rule Definition/Schema JSON-body validation depth (accepted verbatim, like PutDashboard)

More

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrAlarmMuteRuleNotFound = errors.New(errResourceNotFoundException)

ErrAlarmMuteRuleNotFound is returned when a requested alarm mute rule does not exist.

View Source
var ErrAlarmNameRequired = errors.New("AlarmName is required")

ErrAlarmNameRequired is returned when an alarm name is missing.

View Source
var ErrAlarmNotFound = errors.New(errResourceNotFoundException)

ErrAlarmNotFound is returned when a requested alarm does not exist.

View Source
var ErrAlarmRuleRequired = errors.New("AlarmRule is required")

ErrAlarmRuleRequired is returned when a composite alarm rule is missing.

View Source
var ErrAnomalyDetectorNotFound = errors.New(errResourceNotFoundException)

ErrAnomalyDetectorNotFound is returned when a requested anomaly detector does not exist.

View Source
var ErrDashboardNameRequired = errors.New("DashboardName is required")

ErrDashboardNameRequired is returned when a dashboard name is missing.

View Source
var ErrDashboardNotFound = errors.New(errResourceNotFoundException)

ErrDashboardNotFound is returned when a requested dashboard does not exist.

View Source
var ErrInsightRuleNotFound = errors.New(errResourceNotFoundException)

ErrInsightRuleNotFound is returned when a requested insight rule does not exist.

View Source
var ErrInvalidMetricValue = errors.New(
	"InvalidParameterValue: metric values must be finite and within -2^360 to 2^360",
)

ErrInvalidMetricValue is returned when a metric value (Value, Sum, Min, Max, or an entry of the Values array) is NaN, +/-Infinity, or outside the documented -2^360..2^360 range that CloudWatch accepts.

View Source
var ErrInvalidNextToken = errors.New("InvalidParameterValue: NextToken is invalid or expired")

ErrInvalidNextToken is returned when a pagination NextToken is invalid or expired.

View Source
var ErrMetricFilterNotFound = errors.New(errResourceNotFoundException)

ErrMetricFilterNotFound is returned when a requested metric filter does not exist.

View Source
var ErrMetricSeriesLimitExceeded = errors.New("LimitExceeded: metric series limit reached")

ErrMetricSeriesLimitExceeded is returned when storing a batch of MetricDatum entries would push the namespace or account past its distinct-time-series cap.

View Source
var ErrMetricStreamNotFound = errors.New(errResourceNotFoundException)

ErrMetricStreamNotFound is returned when a requested metric stream does not exist.

View Source
var ErrMetricTimestampOutOfRange = errors.New(
	"InvalidParameterValue: Timestamp must not be more than two weeks before or " +
		"two hours after the current time",
)

ErrMetricTimestampOutOfRange is returned when a MetricDatum's Timestamp falls outside CloudWatch's documented PutMetricData acceptance window: no more than cwMetricTimestampPastWindow in the past, and no more than cwMetricTimestampFutureWindow in the future, relative to now.

View Source
var ErrTooManyValues = errors.New(
	"InvalidParameterValue: the maximum values array size is 150",
)

ErrTooManyValues is returned when a MetricDatum's Values array exceeds the 150-unique-value limit documented for PutMetricData.

View Source
var ErrValidation = errors.New("InvalidParameterValue")

ErrValidation is returned when a caller provides an invalid or missing parameter.

View Source
var ErrValueAndStatisticSet = errors.New(
	"InvalidParameterCombination: Value, StatisticValues, and Values/Counts are mutually exclusive",
)

ErrValueAndStatisticSet is returned when more than one of Value, StatisticSet, and the Values/Counts array are set on a MetricDatum. AWS treats all three input shapes as mutually exclusive.

View Source
var ErrValuesCountsLengthMismatch = errors.New(
	"InvalidParameterValue: Values and Counts arrays must be the same length",
)

ErrValuesCountsLengthMismatch is returned when a MetricDatum's Counts array is present but does not have the same number of elements as its Values array.

Functions

This section is empty.

Types

type AlarmContributor

type AlarmContributor struct {
	Keys []string `json:"Keys"`
	Sum  float64  `json:"Sum"`
}

AlarmContributor represents a single contributor returned by DescribeAlarmContributors.

type AlarmHistoryItem

type AlarmHistoryItem struct {
	Timestamp       time.Time `json:"Timestamp"`
	AlarmName       string    `json:"AlarmName"`
	AlarmType       string    `json:"AlarmType,omitempty"`
	HistoryItemType string    `json:"HistoryItemType"`
	HistorySummary  string    `json:"HistorySummary"`
	HistoryData     string    `json:"HistoryData,omitempty"`
}

AlarmHistoryItem represents a single history entry for an alarm.

type AlarmMuteRule

type AlarmMuteRule struct {
	CreationTime  time.Time `json:"CreationTime"`
	MuteStartTime time.Time `json:"MuteStartTime"`
	MuteName      string    `json:"MuteName"`
	Description   string    `json:"Description,omitempty"`
	AlarmNames    []string  `json:"AlarmNames,omitempty"`
	MuteDuration  int32     `json:"MuteDuration"`
}

AlarmMuteRule represents a CloudWatch alarm mute rule.

type AnomalyDetector

type AnomalyDetector struct {
	Namespace  string      `json:"Namespace"`
	MetricName string      `json:"MetricName"`
	Stat       string      `json:"Stat"`
	StateValue string      `json:"StateValue"`
	Dimensions []Dimension `json:"Dimensions,omitempty"`
	BandWidth  float64     `json:"BandWidth,omitempty"`
}

AnomalyDetector represents a CloudWatch anomaly detector.

type AutoScalingPolicyExecutor

type AutoScalingPolicyExecutor interface {
	ExecuteScalingPolicy(autoScalingGroupName, policyName string) error
}

AutoScalingPolicyExecutor executes an Auto Scaling scaling-policy alarm action (arn:aws:autoscaling:...:scalingPolicy:...).

type CompositeAlarm

type CompositeAlarm struct {
	CreatedAt                  time.Time `json:"AlarmCreatedAt"`
	StateTransitionedTimestamp time.Time `json:"StateTransitionedTimestamp"`
	StateValue                 string    `json:"StateValue"`
	AlarmName                  string    `json:"AlarmName"`
	AlarmRule                  string    `json:"AlarmRule"`
	AlarmDescription           string    `json:"AlarmDescription,omitempty"`
	AlarmArn                   string    `json:"AlarmArn"`
	StateReason                string    `json:"StateReason,omitempty"`
	AlarmActions               []string  `json:"AlarmActions,omitempty"`
	OKActions                  []string  `json:"OKActions,omitempty"`
	InsufficientDataActions    []string  `json:"InsufficientDataActions,omitempty"`
	ActionsEnabled             bool      `json:"ActionsEnabled"`
}

CompositeAlarm represents a CloudWatch composite alarm that combines child alarms.

type DashboardEntry

type DashboardEntry struct {
	LastModified  time.Time `json:"LastModified"`
	DashboardArn  string    `json:"DashboardArn"`
	DashboardName string    `json:"DashboardName"`
	Size          int64     `json:"Size"`
}

DashboardEntry represents a single CloudWatch dashboard summary entry returned by ListDashboards.

type Datapoint

type Datapoint struct {
	Average            *float64           `json:"Average,omitempty"`
	Sum                *float64           `json:"Sum,omitempty"`
	Minimum            *float64           `json:"Minimum,omitempty"`
	Maximum            *float64           `json:"Maximum,omitempty"`
	SampleCount        *float64           `json:"SampleCount,omitempty"`
	ExtendedStatistics map[string]float64 `json:"ExtendedStatistics,omitempty"`
	// BandLower and BandUpper are the anomaly detection band boundaries for this point.
	// Only populated when a matching AnomalyDetector exists for the metric.
	BandLower *float64  `json:"BandLower,omitempty"`
	BandUpper *float64  `json:"BandUpper,omitempty"`
	Timestamp time.Time `json:"Timestamp"`
	Unit      string    `json:"Unit,omitempty"`
}

Datapoint holds aggregated stats for GetMetricStatistics.

type Dimension

type Dimension struct {
	Name  string `json:"Name"`
	Value string `json:"Value"`
}

Dimension is a key-value pair for a metric.

type EC2InstanceActioner

type EC2InstanceActioner interface {
	StopInstances(instanceIDs []string) error
	TerminateInstances(instanceIDs []string) error
	RebootInstances(instanceIDs []string) error
}

EC2InstanceActioner executes EC2 alarm actions (arn:aws:automate:<region>:ec2:*) against the instances named by the alarm's InstanceId dimension.

type GetMetricDataPage

type GetMetricDataPage struct {
	NextToken string
	Results   []MetricDataResult
	Messages  []MetricDataMessage
}

GetMetricDataPage is the paginated result of a GetMetricData request. NextToken is non-empty when the response was truncated to honour MaxDatapoints. Messages carries top-level diagnostics (e.g. a truncation notice).

type Handler

type Handler struct {
	Backend StorageBackend
	// contains filtered or unexported fields
}

Handler is the Echo HTTP service handler for CloudWatch operations.

func NewHandler

func NewHandler(backend StorageBackend) *Handler

NewHandler creates a new CloudWatch handler.

func (*Handler) ChaosOperations

func (h *Handler) ChaosOperations() []string

ChaosOperations returns all operations that can be fault-injected.

func (*Handler) ChaosRegions

func (h *Handler) ChaosRegions() []string

ChaosRegions returns all regions this CloudWatch instance handles.

func (*Handler) ChaosServiceName

func (h *Handler) ChaosServiceName() string

ChaosServiceName returns the lowercase AWS service name for fault rule matching.

func (*Handler) ExtractOperation

func (h *Handler) ExtractOperation(c *echo.Context) string

ExtractOperation extracts the operation name from the Action form field or CBOR path.

func (*Handler) ExtractResource

func (h *Handler) ExtractResource(c *echo.Context) string

ExtractResource extracts the resource name (Namespace) from the form.

func (*Handler) GetSupportedOperations

func (h *Handler) GetSupportedOperations() []string

GetSupportedOperations returns all mocked CloudWatch operations.

func (*Handler) Handler

func (h *Handler) Handler() echo.HandlerFunc

Handler returns the Echo handler function for CloudWatch requests.

func (*Handler) MatchPriority

func (h *Handler) MatchPriority() int

MatchPriority returns the routing priority for the CloudWatch handler.

func (*Handler) Name

func (h *Handler) Name() string

Name returns the service name.

func (*Handler) Reset

func (h *Handler) Reset()

Reset clears all in-memory state from the backend. It is used by the POST /_gopherstack/reset endpoint for CI pipelines and rapid local development.

func (*Handler) Restore

func (h *Handler) Restore(ctx context.Context, data []byte) error

Restore implements persistence.Persistable by delegating to the backend and restoring the handler-level resource tags.

func (*Handler) RouteMatcher

func (h *Handler) RouteMatcher() service.Matcher

RouteMatcher returns a matcher for CloudWatch query-protocol requests.

func (*Handler) Snapshot

func (h *Handler) Snapshot(ctx context.Context) []byte

Snapshot implements persistence.Persistable by delegating to the backend and also persisting the handler-level resource tags.

func (*Handler) StartWorker

func (h *Handler) StartWorker(ctx context.Context) error

StartWorker starts the background janitor for metric sweeping. It implements service.BackgroundWorker.

type InMemoryBackend

type InMemoryBackend struct {
	// contains filtered or unexported fields
}

InMemoryBackend implements StorageBackend using in-memory maps. metrics is a two-level map: namespace -> composite-key -> *metricRecord. The composite key is produced by metricStorageKey(metricName, dims) so that different dimension sets for the same metric name are stored separately. metrics and alarmHistory are deliberately left as plain maps rather than store.Table -- see the comment block at the top of store_setup.go for why. Every other resource field is registered on registry -- see registerAllTables in store_setup.go.

func NewInMemoryBackend

func NewInMemoryBackend() *InMemoryBackend

NewInMemoryBackend creates a new InMemoryBackend with default configuration.

func NewInMemoryBackendWithConfig

func NewInMemoryBackendWithConfig(accountID, region string) *InMemoryBackend

NewInMemoryBackendWithConfig creates a new InMemoryBackend with given account and region.

func (*InMemoryBackend) DeleteAlarmMuteRule

func (b *InMemoryBackend) DeleteAlarmMuteRule(muteName string) error

DeleteAlarmMuteRule removes an alarm mute rule by name. Returns ErrAlarmMuteRuleNotFound if the rule does not exist.

func (*InMemoryBackend) DeleteAlarms

func (b *InMemoryBackend) DeleteAlarms(alarmNames []string) error

DeleteAlarms removes alarms by name (metric and composite).

func (*InMemoryBackend) DeleteAnomalyDetector

func (b *InMemoryBackend) DeleteAnomalyDetector(namespace, metricName, stat string, dims []Dimension) error

DeleteAnomalyDetector removes an anomaly detector. Returns ErrAnomalyDetectorNotFound if the detector does not exist.

func (*InMemoryBackend) DeleteDashboards

func (b *InMemoryBackend) DeleteDashboards(names []string) error

DeleteDashboards removes the named dashboards. Names that do not exist are silently ignored.

func (*InMemoryBackend) DeleteInsightRules

func (b *InMemoryBackend) DeleteInsightRules(ruleNames []string) ([]InsightRuleFailure, error)

DeleteInsightRules removes insight rules by name. Non-existent rules are reported as failures.

func (*InMemoryBackend) DeleteMetricFilter

func (b *InMemoryBackend) DeleteMetricFilter(filterName, logGroupName string) error

DeleteMetricFilter removes a metric filter by name and log group. Returns ErrMetricFilterNotFound if the filter does not exist.

func (*InMemoryBackend) DeleteMetricStream

func (b *InMemoryBackend) DeleteMetricStream(name string) error

DeleteMetricStream removes a metric stream by name. Returns ErrMetricStreamNotFound if the stream does not exist.

func (*InMemoryBackend) DescribeAlarmContributors

func (b *InMemoryBackend) DescribeAlarmContributors(
	alarmName, nextToken string,
) (page.Page[AlarmContributor], error)

DescribeAlarmContributors returns a page of contributors for the specified alarm.

For a composite alarm, the contributors are the referenced child alarms whose state currently satisfies their state-function condition (e.g. a child named in ALARM(...) that is itself in ALARM) — i.e. the alarms actually driving the composite alarm's state. Each contributor is keyed by [childAlarmName, state] with Sum=1. For a metric alarm, AWS returns no contributors, so the result is an empty (but successful) page.

func (*InMemoryBackend) DescribeAlarmHistory

func (b *InMemoryBackend) DescribeAlarmHistory(
	alarmName, alarmType, historyItemType, nextToken string,
	startDate, endDate time.Time,
	maxRecords int,
) (page.Page[AlarmHistoryItem], error)

DescribeAlarmHistory returns history items for one or all alarms, filtered by type and date range. alarmType filters by "MetricAlarm" or "CompositeAlarm" (stored on history items); empty means all.

func (*InMemoryBackend) DescribeAlarms

func (b *InMemoryBackend) DescribeAlarms(
	alarmNames []string,
	alarmTypes []string,
	alarmNamePrefix, stateValue, nextToken string,
	maxRecords int,
) (page.Page[MetricAlarm], page.Page[CompositeAlarm], error)

DescribeAlarms lists a page of alarms, optionally filtered by name, type, prefix, and/or state. alarmTypes can contain "MetricAlarm", "CompositeAlarm", or both (empty means both). MaxRecords applies to the total combined result set (metric + composite).

func (*InMemoryBackend) DescribeAlarmsForMetric

func (b *InMemoryBackend) DescribeAlarmsForMetric(
	namespace, metricName string,
	dimensions []Dimension,
	alarmNames []string,
	nextToken string,
	maxRecords int,
) (page.Page[MetricAlarm], error)

DescribeAlarmsForMetric returns metric alarms associated with a specific metric.

func (*InMemoryBackend) DescribeAnomalyDetectors

func (b *InMemoryBackend) DescribeAnomalyDetectors(
	namespace, metricName, nextToken string,
	maxResults int,
) (page.Page[AnomalyDetector], error)

DescribeAnomalyDetectors returns a filtered, paginated list of anomaly detectors.

func (*InMemoryBackend) DescribeInsightRules

func (b *InMemoryBackend) DescribeInsightRules(
	nextToken string,
	maxResults int,
) (page.Page[InsightRule], error)

DescribeInsightRules returns a paginated list of insight rules.

func (*InMemoryBackend) DescribeMetricFilters

func (b *InMemoryBackend) DescribeMetricFilters(
	filterNamePrefix, logGroupName, nextToken string,
	maxResults int,
) (page.Page[MetricFilter], error)

DescribeMetricFilters returns a paginated list of metric filters with optional filters.

func (*InMemoryBackend) DisableAlarmActions

func (b *InMemoryBackend) DisableAlarmActions(alarmNames []string) error

DisableAlarmActions disables action execution for the given alarms.

func (*InMemoryBackend) DisableInsightRules

func (b *InMemoryBackend) DisableInsightRules(ruleNames []string) ([]InsightRuleFailure, error)

DisableInsightRules disables the specified insight rules. Non-existent rules are reported as failures.

func (*InMemoryBackend) EnableAlarmActions

func (b *InMemoryBackend) EnableAlarmActions(alarmNames []string) error

EnableAlarmActions enables action execution for the given alarms.

func (*InMemoryBackend) EnableInsightRules

func (b *InMemoryBackend) EnableInsightRules(ruleNames []string) ([]InsightRuleFailure, error)

EnableInsightRules enables the specified insight rules. Non-existent rules are reported as failures.

func (*InMemoryBackend) EvaluateAlarms

func (b *InMemoryBackend) EvaluateAlarms(ctx context.Context, now time.Time)

EvaluateAlarms evaluates all metric alarms against recent metric data and transitions state (OK ↔ ALARM ↔ INSUFFICIENT_DATA) as appropriate. SNS and Lambda alarm actions are fired on state change. Intended to be called periodically by the Janitor.

func (*InMemoryBackend) GetAlarmARNs

func (b *InMemoryBackend) GetAlarmARNs(names []string) []string

GetAlarmARNs returns the ARNs for the given alarm names (metric + composite). Used by the HTTP handler to clean up tag entries on delete.

func (*InMemoryBackend) GetAlarmMuteRule

func (b *InMemoryBackend) GetAlarmMuteRule(muteName string) (*AlarmMuteRule, error)

GetAlarmMuteRule returns an alarm mute rule by name. Returns ErrAlarmMuteRuleNotFound if the rule does not exist.

func (*InMemoryBackend) GetDashboard

func (b *InMemoryBackend) GetDashboard(name string) (DashboardEntry, string, error)

GetDashboard returns the dashboard entry and body for the given name.

func (*InMemoryBackend) GetDashboardARNs

func (b *InMemoryBackend) GetDashboardARNs(names []string) []string

GetDashboardARNs returns the ARNs for the given dashboard names. Used by the HTTP handler to clean up tag entries on delete.

func (*InMemoryBackend) GetInsightRule

func (b *InMemoryBackend) GetInsightRule(name string) (*InsightRule, error)

GetInsightRule returns an insight rule by name.

func (*InMemoryBackend) GetInsightRuleContributors

func (b *InMemoryBackend) GetInsightRuleContributors(
	ruleName string,
	startTime, endTime time.Time,
	maxContributorCount int,
	orderBy string,
) ([]AlarmContributor, error)

GetInsightRuleContributors returns top-N contributors for an insight rule by aggregating stored metric data along dimension values. This is a best-effort local approximation. Caller must hold b.mu (at least read lock).

func (*InMemoryBackend) GetMetricData

func (b *InMemoryBackend) GetMetricData(
	queries []MetricDataQuery,
	startTime, endTime time.Time,
) ([]MetricDataResult, error)

GetMetricData executes multiple metric queries and returns results. Queries with a MetricStat are resolved first; expression queries are evaluated after all metric-stat results are available so expressions can reference them. scanBy controls sort order: "TimestampDescending" reverses each result; default ascending.

func (*InMemoryBackend) GetMetricDataPaged

func (b *InMemoryBackend) GetMetricDataPaged(
	queries []MetricDataQuery,
	startTime, endTime time.Time,
	scanBy, nextToken string,
	maxDatapoints int,
) (GetMetricDataPage, error)

GetMetricDataPaged resolves the queries and applies MaxDatapoints pagination. maxDatapoints <= 0 uses the AWS default. The returned page carries a NextToken when the response was truncated, plus a top-level informational message so callers know more data is available.

func (*InMemoryBackend) GetMetricDataWithOptions

func (b *InMemoryBackend) GetMetricDataWithOptions(
	queries []MetricDataQuery,
	startTime, endTime time.Time,
	scanBy string,
) ([]MetricDataResult, error)

GetMetricDataWithOptions is GetMetricData extended with scan order control. scanBy may be "TimestampDescending" or "" / "TimestampAscending" (default).

func (*InMemoryBackend) GetMetricStatistics

func (b *InMemoryBackend) GetMetricStatistics(
	namespace, metricName string,
	dimensions []Dimension,
	startTime, endTime time.Time,
	period int32,
	statistics []string,
	extendedStatistics []string,
) ([]Datapoint, error)

GetMetricStatistics aggregates data for a metric over a time range into period-sized buckets. extendedStatistics supports percentile expressions such as "p99", "p95", "p50". dimensions filters to the specific metric series; an empty slice matches the dimensionless series.

func (*InMemoryBackend) GetMetricStream

func (b *InMemoryBackend) GetMetricStream(name string) (*MetricStream, error)

GetMetricStream returns a metric stream by name.

func (*InMemoryBackend) ListAlarmMuteRules

func (b *InMemoryBackend) ListAlarmMuteRules(
	nextToken string,
	maxResults int,
) (page.Page[AlarmMuteRule], error)

ListAlarmMuteRules returns a paginated list of all alarm mute rules.

func (*InMemoryBackend) ListDashboards

func (b *InMemoryBackend) ListDashboards(
	prefix, nextToken string,
) (page.Page[DashboardEntry], error)

ListDashboards returns a page of dashboard entries optionally filtered by name prefix.

func (*InMemoryBackend) ListManagedInsightRules

func (b *InMemoryBackend) ListManagedInsightRules(
	resourceARN, nextToken string,
	maxResults int,
) (page.Page[InsightRule], error)

ListManagedInsightRules returns a paginated list of managed (service-linked) insight rules. If resourceARN is non-empty only rules whose Arn matches are included; in the emulator the ManagedRule flag is used as the primary discriminator.

func (*InMemoryBackend) ListMetricStreams

func (b *InMemoryBackend) ListMetricStreams(
	nextToken string,
	maxResults int,
) (page.Page[MetricStream], error)

ListMetricStreams returns a paginated list of all metric streams.

func (*InMemoryBackend) ListMetrics

func (b *InMemoryBackend) ListMetrics(
	namespace, metricName string,
	dimensions []Dimension,
	recentlyActive, nextToken string,
	maxResults int,
) (page.Page[Metric], error)

ListMetrics returns a page of unique metrics matching optional namespace, metricName, and dimension filters. dimensions specifies an exact set that must match (all filter dims present with matching values and no extra dims in the stored record). recentlyActive, when set, must be "PT3H" (the only value CloudWatch documents) and restricts results to metrics that received a data point in the last 3 hours.

func (*InMemoryBackend) PutAlarmMuteRule

func (b *InMemoryBackend) PutAlarmMuteRule(rule *AlarmMuteRule) error

PutAlarmMuteRule creates or updates an alarm mute rule by name.

func (*InMemoryBackend) PutAlarmMuteRuleInternal

func (b *InMemoryBackend) PutAlarmMuteRuleInternal(rule *AlarmMuteRule)

PutAlarmMuteRuleInternal creates or updates an alarm mute rule (used for test seeding).

func (*InMemoryBackend) PutAnomalyDetector

func (b *InMemoryBackend) PutAnomalyDetector(detector *AnomalyDetector) error

func (*InMemoryBackend) PutAnomalyDetectorInternal

func (b *InMemoryBackend) PutAnomalyDetectorInternal(detector *AnomalyDetector)

PutAnomalyDetectorInternal creates or updates an anomaly detector (used for test seeding).

func (*InMemoryBackend) PutCompositeAlarm

func (b *InMemoryBackend) PutCompositeAlarm(alarm *CompositeAlarm) error

PutCompositeAlarm creates or updates a composite alarm and evaluates its state.

func (*InMemoryBackend) PutDashboard

func (b *InMemoryBackend) PutDashboard(name, body string) error

PutDashboard creates or updates a CloudWatch dashboard by name.

func (*InMemoryBackend) PutInsightRule

func (b *InMemoryBackend) PutInsightRule(rule *InsightRule) error

PutInsightRule creates or updates an insight rule.

func (*InMemoryBackend) PutInsightRuleInternal

func (b *InMemoryBackend) PutInsightRuleInternal(rule *InsightRule)

PutInsightRuleInternal creates or updates an insight rule (used for test seeding).

func (*InMemoryBackend) PutMetricAlarm

func (b *InMemoryBackend) PutMetricAlarm(alarm *MetricAlarm) error

PutMetricAlarm creates or updates an alarm.

func (*InMemoryBackend) PutMetricData

func (b *InMemoryBackend) PutMetricData(
	namespace string,
	data []MetricDatum,
) error

PutMetricData stores metric data points for the given namespace.

Real CloudWatch has no partial-failure response for this operation: the request either succeeds in full or fails in full with a single API error (PutMetricDataOutput has no members other than the request ID). This validates the entire batch before storing any of it, matching that all-or-nothing contract.

func (*InMemoryBackend) PutMetricFilter

func (b *InMemoryBackend) PutMetricFilter(filter *MetricFilter) error

PutMetricFilter creates or updates a metric filter.

func (*InMemoryBackend) PutMetricStream

func (b *InMemoryBackend) PutMetricStream(stream *MetricStream) error

PutMetricStream creates or updates a metric stream by name.

func (*InMemoryBackend) PutMetricStreamInternal

func (b *InMemoryBackend) PutMetricStreamInternal(stream *MetricStream)

PutMetricStreamInternal creates or updates a metric stream (used for test seeding).

func (*InMemoryBackend) Reset

func (b *InMemoryBackend) Reset()

Reset clears all in-memory state from the backend. It is used by the POST /_gopherstack/reset endpoint for CI pipelines and rapid local development.

func (*InMemoryBackend) Restore

func (b *InMemoryBackend) Restore(ctx context.Context, data []byte) error

Restore loads backend state from a JSON snapshot. It implements persistence.Persistable.

func (*InMemoryBackend) SetAlarmState

func (b *InMemoryBackend) SetAlarmState(
	ctx context.Context,
	alarmName, stateValue, stateReason, stateReasonData string,
) error

SetAlarmState manually sets the state of an alarm and fires the corresponding actions.

func (*InMemoryBackend) SetAutoScalingExecutor

func (b *InMemoryBackend) SetAutoScalingExecutor(e AutoScalingPolicyExecutor)

SetAutoScalingExecutor registers an Auto Scaling executor used to run scaling-policy alarm actions.

func (*InMemoryBackend) SetEC2Actioner

func (b *InMemoryBackend) SetEC2Actioner(a EC2InstanceActioner)

SetEC2Actioner registers an EC2 actioner used to execute arn:aws:automate EC2 alarm actions (stop/terminate/reboot/recover).

func (*InMemoryBackend) SetLambdaInvoker

func (b *InMemoryBackend) SetLambdaInvoker(inv LambdaInvoker)

SetLambdaInvoker registers a Lambda invoker used to fire alarm action Lambda invocations.

func (*InMemoryBackend) SetSNSPublisher

func (b *InMemoryBackend) SetSNSPublisher(pub SNSPublisher)

SetSNSPublisher registers an SNS publisher used to fire alarm action notifications.

func (*InMemoryBackend) Snapshot

func (b *InMemoryBackend) Snapshot(ctx context.Context) []byte

Snapshot serialises the backend state to JSON. It implements persistence.Persistable.

func (*InMemoryBackend) StartMetricStreams

func (b *InMemoryBackend) StartMetricStreams(names []string) error

StartMetricStreams sets the State of the named streams to RUNNING. Names that do not exist are silently ignored (AWS behaviour).

func (*InMemoryBackend) StopMetricStreams

func (b *InMemoryBackend) StopMetricStreams(names []string) error

StopMetricStreams sets the State of the named streams to STOPPED. Names that do not exist are silently ignored (AWS behaviour).

func (*InMemoryBackend) SweepExpiredMetrics

func (b *InMemoryBackend) SweepExpiredMetrics()

SweepExpiredMetrics removes metric data points older than cwMetricRetentionDays. It is intended to be called periodically (e.g., by a janitor goroutine).

Uses a two-phase approach: snapshot candidate series under a read lock, then apply deletions under a write lock. This avoids holding the write lock during the full O(series × points) filter scan.

type InsightRule

type InsightRule struct {
	CreatedAt   time.Time `json:"CreatedAt"`
	Name        string    `json:"Name"`
	State       string    `json:"State"`
	Schema      string    `json:"Schema"`
	Definition  string    `json:"Definition"`
	Arn         string    `json:"RuleArn"`
	ManagedRule bool      `json:"ManagedRule"`
}

InsightRule represents a CloudWatch Contributor Insights rule.

type InsightRuleFailure

type InsightRuleFailure struct {
	RuleName           string `json:"RuleName"`
	FailureCode        string `json:"FailureCode"`
	FailureDescription string `json:"FailureDescription,omitempty"`
}

InsightRuleFailure represents a failed rule in batch insight rule operations.

type Janitor

type Janitor struct {
	Backend           *InMemoryBackend
	Interval          time.Duration
	AlarmEvalInterval time.Duration
}

Janitor is the CloudWatch background worker that manages metric retention and evaluates metric alarm states.

func NewJanitor

func NewJanitor(backend *InMemoryBackend) *Janitor

NewJanitor creates a new CloudWatch Janitor.

func (*Janitor) Run

func (j *Janitor) Run(ctx context.Context)

Run runs the janitor loop until ctx is cancelled. It runs two independent tickers: one that sweeps expired metrics at Interval, and one that evaluates metric alarm states at AlarmEvalInterval.

type LambdaInvoker

type LambdaInvoker interface {
	InvokeFunction(
		ctx context.Context,
		name string,
		invocationType string,
		payload []byte,
	) ([]byte, int, error)
}

LambdaInvoker can invoke a Lambda function by ARN or name.

type Metric

type Metric struct {
	Namespace  string      `json:"Namespace"`
	MetricName string      `json:"MetricName"`
	Dimensions []Dimension `json:"Dimensions,omitempty"`
}

Metric represents a named metric (name+namespace+dimensions).

type MetricAlarm

type MetricAlarm struct {
	CreatedAt                          time.Time `json:"AlarmCreatedAt"`
	StateTransitionedTimestamp         time.Time `json:"StateTransitionedTimestamp"`
	AlarmConfigurationUpdatedTimestamp time.Time `json:"AlarmConfigurationUpdatedTimestamp"`
	StateValue                         string    `json:"StateValue"`
	Namespace                          string    `json:"Namespace"`
	MetricName                         string    `json:"MetricName"`
	ComparisonOperator                 string    `json:"ComparisonOperator"`
	Statistic                          string    `json:"Statistic"`
	ExtendedStatistic                  string    `json:"ExtendedStatistic,omitempty"`
	TreatMissingData                   string    `json:"TreatMissingData,omitempty"`
	AlarmName                          string    `json:"AlarmName"`
	StateReason                        string    `json:"StateReason,omitempty"`
	StateReasonData                    string    `json:"StateReasonData,omitempty"`
	AlarmDescription                   string    `json:"AlarmDescription,omitempty"`
	AlarmArn                           string    `json:"AlarmArn"`
	// ThresholdMetricID references the MetricDataQuery ID whose result is used as the
	// dynamic threshold (anomaly band) for GreaterThanUpperThreshold and
	// LessThanLowerOrGreaterThanUpperThreshold comparison operators.
	ThresholdMetricID       string      `json:"ThresholdMetricId,omitempty"`
	AlarmActions            []string    `json:"AlarmActions,omitempty"`
	OKActions               []string    `json:"OKActions,omitempty"`
	InsufficientDataActions []string    `json:"InsufficientDataActions,omitempty"`
	Dimensions              []Dimension `json:"Dimensions,omitempty"`
	// Metrics holds the MetricDataQuery list for multi-metric / metric-math alarms.
	// When set, MetricName/Namespace/Statistic/Period/Dimensions are ignored for evaluation.
	Metrics           []MetricDataQuery `json:"Metrics,omitempty"`
	Threshold         float64           `json:"Threshold"`
	EvaluationPeriods int32             `json:"EvaluationPeriods"`
	DatapointsToAlarm int32             `json:"DatapointsToAlarm,omitempty"`
	Period            int32             `json:"Period"`
	ActionsEnabled    bool              `json:"ActionsEnabled"`
}

MetricAlarm represents a CloudWatch metric alarm.

type MetricDataMessage

type MetricDataMessage struct {
	Code  string `json:"Code"`
	Value string `json:"Value"`
}

MetricDataMessage is a diagnostic message returned by GetMetricData, either at the top level of the response or attached to an individual MetricDataResult. Code is a short machine-readable identifier (e.g. "ArithmeticError", "Forbidden", "MaxDatapointsExceeded"); Value is the human-readable text.

type MetricDataQuery

type MetricDataQuery struct {
	ID         string     `json:"Id"`
	Label      string     `json:"Label,omitempty"`
	Expression string     `json:"Expression,omitempty"`
	AccountID  string     `json:"AccountId,omitempty"`
	MetricStat MetricStat `json:"MetricStat"`
	Period     int32      `json:"Period,omitempty"`
	ReturnData bool       `json:"ReturnData"`
}

MetricDataQuery is a single query in a GetMetricData request. Expression supports metric math (e.g. "m1+m2"). When non-empty, MetricStat is ignored. AccountId, when set to an account other than the local account, causes the query to return empty data (cross-account metrics are not supported locally but must not error). ReturnData controls whether the query result is included in the response.

type MetricDataResult

type MetricDataResult struct {
	Timestamps []time.Time         `json:"Timestamps"`
	ID         string              `json:"Id"`
	Label      string              `json:"Label,omitempty"`
	StatusCode string              `json:"StatusCode"`
	Values     []float64           `json:"Values"`
	Messages   []MetricDataMessage `json:"Messages,omitempty"`
}

MetricDataResult is a single result entry in a GetMetricData response. StatusCode is "Complete", "PartialData", "InternalError", or "Forbidden". Messages carries per-result diagnostics (e.g. arithmetic errors in metric math).

type MetricDatum

type MetricDatum struct {
	Timestamp  time.Time   `json:"Timestamp"`
	MetricName string      `json:"MetricName"`
	Namespace  string      `json:"Namespace"`
	Unit       string      `json:"Unit,omitempty"`
	Dimensions []Dimension `json:"Dimensions,omitempty"`
	// Values and Counts implement the PutMetricData "array of values" input: each
	// Values[i] occurred Counts[i] times during the period. Populated only when
	// HasValuesArray is true; Counts is defaulted to all-1s by the parser when the
	// caller omits it.
	Values []float64 `json:"Values,omitempty"`
	Counts []float64 `json:"Counts,omitempty"`
	Count  float64   `json:"SampleCount"`
	Value  float64   `json:"Value"`
	Sum    float64   `json:"Sum"`
	Min    float64   `json:"Min"`
	Max    float64   `json:"Max"`
	// StorageResolution is 1 (high-resolution) or 60 (standard); 0 means "use default".
	StorageResolution int32 `json:"StorageResolution,omitempty"`
	// HasStatisticSet is true when the datum was built from a StatisticValues input.
	HasStatisticSet bool `json:"-"`
	// HasValuesArray is true when the datum was built from a Values/Counts input.
	HasValuesArray bool `json:"-"`
	// HasValue is true when the caller explicitly supplied the Value field
	// (independent of whether that value is the float zero value).
	HasValue bool `json:"-"`
}

MetricDatum holds a single metric data point.

A datum is built from exactly one of three mutually-exclusive input shapes: a single Value, a pre-aggregated StatisticValues set, or a Values/Counts array pair (up to 150 unique values, each with an occurrence count). The Has* flags record which shape was supplied on the wire so validation can enforce mutual exclusion by presence rather than by zero-value guessing.

type MetricFilter

type MetricFilter struct {
	CreationTime          time.Time              `json:"CreationTime"`
	FilterName            string                 `json:"FilterName"`
	LogGroupName          string                 `json:"LogGroupName"`
	FilterPattern         string                 `json:"FilterPattern"`
	MetricTransformations []MetricTransformation `json:"MetricTransformations,omitempty"`
}

MetricFilter represents a CloudWatch Logs metric filter.

type MetricStat

type MetricStat struct {
	Namespace  string      `json:"Namespace"`
	MetricName string      `json:"MetricName"`
	Stat       string      `json:"Stat"`
	Dimensions []Dimension `json:"Dimensions,omitempty"`
	Period     int32       `json:"Period"`
}

MetricStat specifies a metric and statistic for a MetricDataQuery.

type MetricStream

type MetricStream struct {
	CreationDate   time.Time            `json:"CreationDate"`
	LastUpdateDate time.Time            `json:"LastUpdateDate"`
	Name           string               `json:"Name"`
	FirehoseArn    string               `json:"FirehoseArn"`
	RoleArn        string               `json:"RoleArn"`
	OutputFormat   string               `json:"OutputFormat"`
	State          string               `json:"State"`
	Arn            string               `json:"Arn"`
	IncludeFilters []MetricStreamFilter `json:"IncludeFilters,omitempty"`
	ExcludeFilters []MetricStreamFilter `json:"ExcludeFilters,omitempty"`
}

MetricStream represents a CloudWatch metric stream.

type MetricStreamFilter

type MetricStreamFilter struct {
	Namespace   string   `json:"Namespace"`
	MetricNames []string `json:"MetricNames,omitempty"`
}

MetricStreamFilter specifies a namespace-level include/exclude filter for a metric stream.

type MetricTransformation

type MetricTransformation struct {
	MetricName      string  `json:"MetricName"`
	MetricNamespace string  `json:"MetricNamespace"`
	MetricValue     string  `json:"MetricValue"`
	Unit            string  `json:"Unit,omitempty"`
	DefaultValue    float64 `json:"DefaultValue,omitempty"`
}

MetricTransformation describes how to map matched log events to a metric.

type Provider

type Provider struct{}

Provider implements service.Provider for the CloudWatch service.

func (*Provider) Init

Init initializes the CloudWatch service backend and handler.

func (*Provider) Name

func (p *Provider) Name() string

Name returns the logical name of the provider.

type SNSPublisher

type SNSPublisher interface {
	PublishToTopic(topicARN, message string) error
}

SNSPublisher can publish a message to an SNS topic by ARN.

type StorageBackend

type StorageBackend interface {
	PutMetricData(namespace string, data []MetricDatum) error
	GetMetricStatistics(
		namespace, metricName string,
		dimensions []Dimension,
		startTime, endTime time.Time,
		period int32,
		statistics []string,
		extendedStatistics []string,
	) ([]Datapoint, error)
	GetMetricData(
		queries []MetricDataQuery,
		startTime, endTime time.Time,
	) ([]MetricDataResult, error)
	ListMetrics(
		namespace, metricName string,
		dimensions []Dimension,
		recentlyActive, nextToken string,
		maxResults int,
	) (page.Page[Metric], error)
	PutMetricAlarm(alarm *MetricAlarm) error
	PutCompositeAlarm(alarm *CompositeAlarm) error
	DescribeAlarms(
		alarmNames []string,
		alarmTypes []string,
		alarmNamePrefix, stateValue, nextToken string,
		maxRecords int,
	) (page.Page[MetricAlarm], page.Page[CompositeAlarm], error)
	DescribeAlarmsForMetric(
		namespace, metricName string,
		dimensions []Dimension,
		alarmNames []string,
		nextToken string,
		maxRecords int,
	) (page.Page[MetricAlarm], error)
	DescribeAlarmHistory(
		alarmName, alarmType, historyItemType, nextToken string,
		startDate, endDate time.Time,
		maxRecords int,
	) (page.Page[AlarmHistoryItem], error)
	DeleteAlarms(alarmNames []string) error
	SetAlarmState(
		ctx context.Context,
		alarmName, stateValue, stateReason, stateReasonData string,
	) error
	EnableAlarmActions(alarmNames []string) error
	DisableAlarmActions(alarmNames []string) error
	PutDashboard(name, body string) error
	GetDashboard(name string) (DashboardEntry, string, error)
	ListDashboards(prefix, nextToken string) (page.Page[DashboardEntry], error)
	DeleteDashboards(names []string) error
	PutAlarmMuteRule(rule *AlarmMuteRule) error
	DeleteAlarmMuteRule(muteName string) error
	GetAlarmMuteRule(muteName string) (*AlarmMuteRule, error)
	PutAnomalyDetector(detector *AnomalyDetector) error
	DeleteAnomalyDetector(namespace, metricName, stat string, dims []Dimension) error
	DescribeAnomalyDetectors(
		namespace, metricName, nextToken string,
		maxResults int,
	) (page.Page[AnomalyDetector], error)
	DeleteInsightRules(ruleNames []string) ([]InsightRuleFailure, error)
	PutInsightRule(rule *InsightRule) error
	GetInsightRule(name string) (*InsightRule, error)
	DescribeInsightRules(nextToken string, maxResults int) (page.Page[InsightRule], error)
	DisableInsightRules(ruleNames []string) ([]InsightRuleFailure, error)
	EnableInsightRules(ruleNames []string) ([]InsightRuleFailure, error)
	PutMetricStream(stream *MetricStream) error
	GetMetricStream(name string) (*MetricStream, error)
	ListMetricStreams(nextToken string, maxResults int) (page.Page[MetricStream], error)
	DeleteMetricStream(name string) error
	DescribeAlarmContributors(alarmName, nextToken string) (page.Page[AlarmContributor], error)
	PutMetricFilter(filter *MetricFilter) error
	DescribeMetricFilters(
		filterNamePrefix, logGroupName, nextToken string,
		maxResults int,
	) (page.Page[MetricFilter], error)
	DeleteMetricFilter(filterName, logGroupName string) error
	StartMetricStreams(names []string) error
	StopMetricStreams(names []string) error
	ListAlarmMuteRules(nextToken string, maxResults int) (page.Page[AlarmMuteRule], error)
	ListManagedInsightRules(
		resourceARN, nextToken string,
		maxResults int,
	) (page.Page[InsightRule], error)
}

StorageBackend is the interface for the CloudWatch in-memory store.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL