Help us shape the future of Go! Take the 2026 Go Developer Survey

gcpmonitoring

package
v1.9.0 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2026 License: MIT Imports: 49 Imported by: 0

README

Cloud Monitoring

Parity grade: B · SDK cloud.google.com/go/monitoring@v1.31.0 · last audited 2026-10-21 (c7e82dfd3)

Coverage

Metric Value
PARITY entries audited 53 (43 ok, 9 partial, 1 gap)
Feature families 8 (2 ok, 6 partial)
Known gaps 11
Deferred items 0
Resource leaks clean
Known gaps
  • QueryService.QueryTimeSeries (MQL, deprecated by Google) returns UNIMPLEMENTED. The PromQL HTTP API has no rules, alerts, targets, exemplars or buildinfo endpoints, and ignores the timeout parameter.
  • ServiceLevelObjective view=EXPLICIT does not expand a BasicSli into a RequestBasedSli, and SLO attainment is never evaluated (no error-budget burn, no SLO-based alerting).
  • Alert conditions condition_matched_log, condition_monitoring_query_language, condition_prometheus_query_language and condition_sql are stored but never evaluated; ratio conditions (denominator_filter) are rejected; forecast_options, evaluation_missing_data, notification_rate_limit, notification_channel_strategy and auto_close are stored but have no effect.
  • Incidents are not exposed through a Cloud Monitoring API; they are readable only from Go through InMemoryBackend.Incidents.
  • email, sms, slack and pagerduty notification channels are never delivered.
  • Uptime checks do not support resource_group, internal checkers or JSON path content matchers; all checker locations share one probe, and ListUptimeCheckIps reports 127.0.0.1.
  • ALIGN_INTERPOLATE, ALIGN_PERCENT_CHANGE, REDUCE_PERCENTILE_* and aligners on distributions other than PERCENTILE and MEAN are rejected; order_by is ignored; page_size counts series rather than points.
  • Log-based metric series are a single accumulated total per label set rather than per-minute deltas, and always use the global resource.
  • Built-in metric descriptors (12) and monitored resource descriptors (22) are a subset of the live catalogs, and no built-in metric receives data from the other emulators.
  • Custom metric descriptors gain labels automatically as new label keys are written; the live service rejects unknown labels for descriptors created explicitly.
  • Error messages and edge cases of the live service (timestamp bounds, quota errors, label limits) were not verified against it.

More

Documentation

Index

Constants

View Source
const (
	// DefaultEvalInterval is how often alert policies and uptime checks are evaluated.
	DefaultEvalInterval = 5 * time.Second
)
View Source
const DefaultPort = 8132

DefaultPort is the dedicated gRPC listener's default TCP port.

Variables

View Source
var ErrNilAppContext = errors.New("gcpmonitoring: nil app context")

ErrNilAppContext is returned when Init is called with a nil AppContext.

Functions

func IsPrometheusPath

func IsPrometheusPath(path string) bool

IsPrometheusPath reports whether the URL path addresses the Prometheus-compatible query API.

Types

type API

API groups the Monitoring services for in-process callers (dashboard proxy).

type ConfigProvider

type ConfigProvider interface {
	GetGCPMonitoringSettings() Settings
}

ConfigProvider extracts Cloud Monitoring configuration from the AppContext Config.

type Delivery

type Delivery struct {
	At         time.Time `json:"at"`
	IncidentID string    `json:"incidentId"`
	Channel    string    `json:"channel"`
	Type       string    `json:"type"`
	State      string    `json:"state"`
	Result     string    `json:"result"`
	Error      string    `json:"error,omitempty"`
}

Delivery records the outcome of one notification attempt.

type Handler

type Handler struct {
	Backend *InMemoryBackend

	// EvalInterval is the alert and uptime tick; zero disables the background loop.
	EvalInterval time.Duration
	Port         int
	// contains filtered or unexported fields
}

Handler serves the Cloud Monitoring gRPC API (and its REST transcoding) on a dedicated listener.

func NewHandler

func NewHandler(backend *InMemoryBackend) *Handler

NewHandler creates a Handler; callers override Port from Settings.

func (*Handler) API

func (h *Handler) API() *API

API exposes the metric, alert policy, uptime check, snooze and notification channel services.

func (*Handler) Addr

func (h *Handler) Addr() string

Addr returns the bound listener address, or "" before StartWorker.

func (*Handler) ExtractOperation

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

ExtractOperation is unused: requests never reach the shared router.

func (*Handler) ExtractResource

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

ExtractResource is unused: requests never reach the shared router.

func (*Handler) GetSupportedOperations

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

GetSupportedOperations lists the supported gRPC methods.

func (*Handler) Handler

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

Handler returns a 404 handler; the real API is on the dedicated port.

func (*Handler) MatchPriority

func (h *Handler) MatchPriority() int

MatchPriority is irrelevant because RouteMatcher never matches.

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.

func (*Handler) Restore

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

Restore implements persistence.Persistable by delegating to the backend.

func (*Handler) RouteMatcher

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

RouteMatcher never matches: Cloud Monitoring runs on its own listener.

func (*Handler) Shutdown

func (h *Handler) Shutdown(ctx context.Context)

Shutdown stops the gRPC server, forcing a close after a short grace period.

func (*Handler) Snapshot

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

Snapshot implements persistence.Persistable by delegating to the backend.

func (*Handler) StartWorker

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

StartWorker binds the dedicated listener synchronously so a port conflict is returned to the caller.

type InMemoryBackend

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

InMemoryBackend holds all Cloud Monitoring state under one lock.

func NewInMemoryBackend

func NewInMemoryBackend() *InMemoryBackend

NewInMemoryBackend creates an empty backend.

func (*InMemoryBackend) CreateAlertPolicy

CreateAlertPolicy stores a policy and names its conditions.

func (*InMemoryBackend) CreateGroup

CreateGroup stores a group.

func (*InMemoryBackend) CreateMetricDescriptor

CreateMetricDescriptor stores a custom metric descriptor; an identical re-create returns the existing one.

func (*InMemoryBackend) CreateNotificationChannel

CreateNotificationChannel stores a channel; email and SMS channels start unverified.

func (*InMemoryBackend) CreateService

CreateService stores a service under the given or a generated id.

func (*InMemoryBackend) CreateServiceLevelObjective

CreateServiceLevelObjective stores an objective under an existing service.

func (*InMemoryBackend) CreateServiceTimeSeries

func (b *InMemoryBackend) CreateServiceTimeSeries(req *monitoringpb.CreateTimeSeriesRequest) error

CreateServiceTimeSeries writes to built-in service metrics as well as custom ones.

func (*InMemoryBackend) CreateSnooze

CreateSnooze stores a snooze with a generated id.

func (*InMemoryBackend) CreateTimeSeries

func (b *InMemoryBackend) CreateTimeSeries(req *monitoringpb.CreateTimeSeriesRequest) error

CreateTimeSeries writes one point per series as a user; valid series are stored even when others fail.

func (*InMemoryBackend) CreateUptimeCheckConfig

CreateUptimeCheckConfig stores a check; it is probed on the next Tick.

func (*InMemoryBackend) DeleteAlertPolicy

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

DeleteAlertPolicy removes a policy; its open incidents close on the next evaluation.

func (*InMemoryBackend) DeleteGroup

DeleteGroup removes a group, and with recursive its descendants.

func (*InMemoryBackend) DeleteMetricDescriptor

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

DeleteMetricDescriptor removes a custom descriptor and the series written with it.

func (*InMemoryBackend) DeleteNotificationChannel

func (b *InMemoryBackend) DeleteNotificationChannel(req *monitoringpb.DeleteNotificationChannelRequest) error

DeleteNotificationChannel removes a channel; policies that use it block deletion unless forced.

func (*InMemoryBackend) DeleteService

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

DeleteService removes a service and its service level objectives.

func (*InMemoryBackend) DeleteServiceLevelObjective

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

DeleteServiceLevelObjective removes an objective.

func (*InMemoryBackend) DeleteUptimeCheckConfig

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

DeleteUptimeCheckConfig removes a check.

func (*InMemoryBackend) Deliveries

func (b *InMemoryBackend) Deliveries() []Delivery

Deliveries returns the most recent notification attempts, oldest first.

func (*InMemoryBackend) GetAlertPolicy

func (b *InMemoryBackend) GetAlertPolicy(name string) (*monitoringpb.AlertPolicy, error)

GetAlertPolicy returns one policy.

func (*InMemoryBackend) GetGroup

func (b *InMemoryBackend) GetGroup(name string) (*monitoringpb.Group, error)

GetGroup returns one group.

func (*InMemoryBackend) GetMetricDescriptor

func (b *InMemoryBackend) GetMetricDescriptor(name string) (*metricpb.MetricDescriptor, error)

GetMetricDescriptor returns a custom, built-in or log-based descriptor.

func (*InMemoryBackend) GetMonitoredResourceDescriptor

func (b *InMemoryBackend) GetMonitoredResourceDescriptor(
	name string,
) (*monitoredres.MonitoredResourceDescriptor, error)

GetMonitoredResourceDescriptor returns one catalog entry.

func (*InMemoryBackend) GetNotificationChannel

func (b *InMemoryBackend) GetNotificationChannel(name string) (*monitoringpb.NotificationChannel, error)

GetNotificationChannel returns one channel without its sensitive labels.

func (*InMemoryBackend) GetNotificationChannelDescriptor

func (b *InMemoryBackend) GetNotificationChannelDescriptor(
	name string,
) (*monitoringpb.NotificationChannelDescriptor, error)

GetNotificationChannelDescriptor returns one channel type.

func (*InMemoryBackend) GetNotificationChannelVerificationCode

GetNotificationChannelVerificationCode returns a fresh code for a channel and when it expires.

func (*InMemoryBackend) GetService

func (b *InMemoryBackend) GetService(name string) (*monitoringpb.Service, error)

GetService returns one service.

func (*InMemoryBackend) GetServiceLevelObjective

func (b *InMemoryBackend) GetServiceLevelObjective(name string) (*monitoringpb.ServiceLevelObjective, error)

GetServiceLevelObjective returns one objective.

func (*InMemoryBackend) GetSnooze

func (b *InMemoryBackend) GetSnooze(name string) (*monitoringpb.Snooze, error)

GetSnooze returns one snooze.

func (*InMemoryBackend) GetUptimeCheckConfig

func (b *InMemoryBackend) GetUptimeCheckConfig(name string) (*monitoringpb.UptimeCheckConfig, error)

GetUptimeCheckConfig returns one check.

func (*InMemoryBackend) Incidents

func (b *InMemoryBackend) Incidents(project string) []Incident

Incidents returns the project's incidents, oldest first; open ones have a zero EndedAt.

func (*InMemoryBackend) ListAlertPolicies

ListAlertPolicies pages the project's policies ordered by name, or by display_name when requested.

func (*InMemoryBackend) ListGroupMembers

ListGroupMembers returns the distinct monitored resources that match the group's filter.

func (*InMemoryBackend) ListGroups

ListGroups pages the project's groups, optionally restricted to a group's children, ancestors or descendants.

func (*InMemoryBackend) ListMetricDescriptors

ListMetricDescriptors pages every descriptor of the project, narrowed by a metric.type filter.

func (*InMemoryBackend) ListMonitoredResourceDescriptors

ListMonitoredResourceDescriptors pages the static catalog, narrowed by a resource.type filter.

func (*InMemoryBackend) ListNotificationChannelDescriptors

ListNotificationChannelDescriptors pages the supported channel types.

func (*InMemoryBackend) ListNotificationChannels

ListNotificationChannels pages the project's channels ordered by name.

func (*InMemoryBackend) ListServiceLevelObjectives

ListServiceLevelObjectives pages the objectives of a service, or of every service of the project for "-".

func (*InMemoryBackend) ListServices

ListServices pages the project's services ordered by name.

func (*InMemoryBackend) ListSnoozes

ListSnoozes pages the project's snoozes ordered by name.

func (*InMemoryBackend) ListTimeSeries

ListTimeSeries returns the series matching the filter with aggregation applied, newest point first.

func (*InMemoryBackend) ListUptimeCheckConfigs

ListUptimeCheckConfigs pages the project's checks ordered by name.

func (*InMemoryBackend) ListUptimeCheckIps

func (b *InMemoryBackend) ListUptimeCheckIps() []*monitoringpb.UptimeCheckIp

ListUptimeCheckIps lists the checker locations; probes originate from the emulator itself.

func (*InMemoryBackend) PrometheusHandler

func (b *InMemoryBackend) PrometheusHandler() http.Handler

PrometheusHandler serves the Managed Service for Prometheus query API over the stored metrics: /v1/projects/P/location/global/prometheus/api/v1/{query,query_range,series,labels,label/NAME/values,metadata}.

func (*InMemoryBackend) Reset

func (b *InMemoryBackend) Reset()

Reset clears all state; seam wiring is kept.

func (*InMemoryBackend) Restore

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

Restore loads backend state from a snapshot.

func (*InMemoryBackend) RunLoop

func (b *InMemoryBackend) RunLoop(ctx context.Context, interval time.Duration)

RunLoop calls Tick every interval until ctx is cancelled.

func (*InMemoryBackend) SendNotificationChannelVerificationCode

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

SendNotificationChannelVerificationCode issues a code for an email or SMS channel.

func (*InMemoryBackend) SetClock

func (b *InMemoryBackend) SetClock(now func() time.Time)

SetClock replaces the backend clock; alert evaluation, uptime checks and timestamp validation use it.

func (*InMemoryBackend) SetLogMetricSource

func (b *InMemoryBackend) SetLogMetricSource(s LogMetricSource)

SetLogMetricSource wires log-based metrics from Cloud Logging.

func (*InMemoryBackend) SetPublisher

func (b *InMemoryBackend) SetPublisher(p Publisher)

SetPublisher wires Pub/Sub notification channels.

func (*InMemoryBackend) Snapshot

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

Snapshot serialises descriptors, series, policies, channels, uptime checks, groups and incidents.

func (*InMemoryBackend) Tick

func (b *InMemoryBackend) Tick(ctx context.Context)

Tick runs one round of uptime checks and alert evaluation at the backend clock's current time.

func (*InMemoryBackend) UpdateAlertPolicy

UpdateAlertPolicy replaces the fields named in the mask (every mutable field when empty).

func (*InMemoryBackend) UpdateGroup

UpdateGroup replaces a group's mutable fields.

func (*InMemoryBackend) UpdateNotificationChannel

UpdateNotificationChannel replaces the fields named in the mask (all mutable fields when empty).

func (*InMemoryBackend) UpdateService

UpdateService replaces the mutable fields in the mask: display_name, user_labels and telemetry.

func (*InMemoryBackend) UpdateServiceLevelObjective

UpdateServiceLevelObjective replaces the fields in the mask (every mutable field when empty).

func (*InMemoryBackend) UpdateSnooze

UpdateSnooze changes the display name or interval; an ended snooze is immutable and a started one keeps its start.

func (*InMemoryBackend) UpdateUptimeCheckConfig

UpdateUptimeCheckConfig replaces the fields in the mask (the whole config when empty).

func (*InMemoryBackend) VerifyNotificationChannel

VerifyNotificationChannel marks a channel verified when the code matches one issued for it or an equivalent channel.

type Incident

type Incident struct {
	StartedAt            time.Time         `json:"startedAt"`
	EndedAt              time.Time         `json:"endedAt"`
	MetricLabels         map[string]string `json:"metricLabels,omitempty"`
	ResourceLabels       map[string]string `json:"resourceLabels,omitempty"`
	ID                   string            `json:"id"`
	Key                  string            `json:"key"`
	Project              string            `json:"project"`
	Policy               string            `json:"policy"`
	PolicyDisplayName    string            `json:"policyDisplayName"`
	Condition            string            `json:"condition"`
	ConditionDisplayName string            `json:"conditionDisplayName"`
	State                string            `json:"state"`
	MetricType           string            `json:"metricType"`
	ResourceType         string            `json:"resourceType"`
	Observed             float64           `json:"observed"`
	Threshold            float64           `json:"threshold"`
}

Incident is one alert firing: it opens when a condition is met and closes when it recovers.

type LogMetric

type LogMetric struct {
	CreateTime time.Time
	Descriptor *metricpb.MetricDescriptor
	Name       string
	Series     []LogMetricSeries
}

LogMetric is a Cloud Logging log-based metric with its accumulated series.

type LogMetricSeries

type LogMetricSeries struct {
	Labels        map[string]string
	BucketOptions *distribution.Distribution_BucketOptions
	BucketCounts  []int64
	Count         int64
	Sum           float64
	SumSqDev      float64
}

LogMetricSeries is the accumulated value of one label combination of a log-based metric.

type LogMetricSource

type LogMetricSource interface {
	LogMetrics(project string) []LogMetric
}

LogMetricSource lists the log-based metrics of a project; it is the seam to Cloud Logging.

type Provider

type Provider struct{}

Provider implements service.Provider for Google Cloud Monitoring. It serves gRPC and REST on its own listener (see Handler.StartWorker) and never matches on the shared AWS router.

func (*Provider) Init

Init creates the backend and handler; the port is bound in StartWorker.

func (*Provider) Name

func (p *Provider) Name() string

Name returns the service provider name.

type Publisher

type Publisher interface {
	Publish(topic string, data []byte, attrs map[string]string) error
}

Publisher publishes an alert notification to a Pub/Sub topic (projects/P/topics/T).

type Settings

type Settings struct {
	Port int `` //nolint:lll // config struct tags are intentionally verbose
	/* 188-byte string literal not displayed */
}

Settings holds service-level configuration, embedded in the root CLI command as CLI.GCPMonitoring.

func DefaultSettings

func DefaultSettings() Settings

DefaultSettings returns the settings used when no ConfigProvider is available.

Jump to

Keyboard shortcuts

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