gcpmonitoring

package
v1.10.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 53 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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 54 (46 ok, 7 partial, 1 gap)
Feature families 8 (2 ok, 6 partial)
Known gaps 4
Deferred items 0
Resource leaks unknown
Known gaps
  • QueryService.QueryTimeSeries (MQL, deprecated by Google) returns UNIMPLEMENTED. The PromQL HTTP API has no targets or buildinfo endpoints and ignores the timeout parameter: the compatibility list at docs.cloud.google.com/stackdriver/docs/managed-prometheus/query names neither endpoint and documents no timeout.
  • Alert conditions condition_monitoring_query_language and condition_sql are stored but never evaluated; metric existence validation for PromQL conditions (disable_metric_validation) has no effect; PromQL label templating supports only {{ $labels.X }} and {{ $value }} and the percentile method of REDUCE_PERCENTILE on numeric series (linear interpolation) is unverified; the forecast model is unverified; the renotify_interval range, the exact auto_close and evaluation_missing_data NO_OP edge behaviour (a series that stops reporting keeps its incident until auto_close) are inferred from the monitoringpb field comments.
  • Uptime checks do not support resource_group (no in-process mapping from monitoring group members to Compute Engine instance addresses) or internal checkers; every location probes from the emulator process and ListUptimeCheckIps reports 127.0.0.1.
  • Log-based metric series always use the global resource, and minutes without entries produce no point.

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"`
	Recipient  string    `json:"recipient,omitempty"`
	Payload    string    `json:"payload,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

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) Outbox

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

Outbox returns the notifications of channels that have no egress in the emulator (email, sms, slack, pagerduty), oldest first, each with the incident JSON it would have carried.

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,query_exemplars,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) SLOStatus

func (b *InMemoryBackend) SLOStatus(name string) (SLOStatus, error)

SLOStatus evaluates the objective against the stored series at the backend clock's time.

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) SetLogEntrySource

func (b *InMemoryBackend) SetLogEntrySource(s LogEntrySource)

SetLogEntrySource wires log entries from Cloud Logging for log-match alert conditions.

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"`
	LastSeen             time.Time            `json:"lastSeen"`
	Notified             map[string]time.Time `json:"notified,omitempty"`
	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 LogEntry

type LogEntry struct {
	Timestamp time.Time
	Fields    map[string]any
	InsertID  string
}

LogEntry is one Cloud Logging entry as the field tree of its JSON form (camelCase names).

type LogEntrySource

type LogEntrySource interface {
	LogEntries(project, filter string, notBefore time.Time) []LogEntry
}

LogEntrySource reads log entries matching a Cloud Logging filter from a project, oldest first. It is the read-only seam to Cloud Logging for condition_matched_log.

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
	Windows       []LogMetricWindow
	Count         int64
	Sum           float64
	SumSqDev      float64
}

LogMetricSeries is the accumulated value of one label combination of a log-based metric; Windows, when the source keeps them, are its per-minute parts.

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 LogMetricWindow

type LogMetricWindow struct {
	Start        time.Time
	BucketCounts []int64
	Count        int64
	Sum          float64
	SumSqDev     float64
}

LogMetricWindow is what a series accumulated during the minute starting at Start.

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 SLOStatus

type SLOStatus struct {
	PeriodStart    time.Time
	PeriodEnd      time.Time
	Good           float64
	Total          float64
	Compliance     float64
	BudgetFraction float64
	BurnRate       float64
}

SLOStatus is the standing of an objective over its current compliance period.

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