gcp

package module
v0.0.0-...-519451a Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2026 License: OSL-3.0 Imports: 30 Imported by: 1 module, 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.

Documentation

Overview

Package gcp provides helpers for classifying GCP API errors.

Package gcp provides Google Cloud Platform provider implementation

Package gcp provides GCP recommendations client

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsPermissionError

func IsPermissionError(err error) bool

IsPermissionError reports whether err represents a GCP permission / authorization failure — typically a missing IAM role on the deploy service account. The GCP collector uses this to downgrade per-account log severity from ERROR to WARN: the operator can fix the gap by granting the missing role, so it is not a genuine collector error and should not drown out other signals in the log stream.

It returns true for:

  • *googleapi.Error with Code == 403 whose reason is "forbidden" or "insufficientPermissions". The Compute API also answers 403 for rateLimitExceeded, quotaExceeded and accessNotConfigured; those are transient or configuration failures, not a missing role.
  • gRPC status with codes.PermissionDenied (gRPC surface, e.g. when a client uses the gRPC transport rather than REST)

Wrapped errors (via fmt.Errorf("...: %w", err)) are unwrapped so the scheduler's wrap-and-rethrow chain still classifies correctly.

Returns false for nil and for any other error.

Types

type PartialResult

type PartialResult interface {
	error
	Partial() bool
	// FailedRegions names the regions whose collection errored.
	FailedRegions() []string
	// SkippedCount and SkipReasons describe recommendations dropped as
	// unconvertible.
	SkippedCount() int
	SkipReasons() []string
}

PartialResult is implemented by the error GetRecommendations returns alongside usable recommendations when the collection was incomplete. A non-empty FailedRegions means those regions' recommendations are unknown, so consumers must not treat them as gone (for example, must hold eviction). Per-region causes are reachable by asserting interface{ Unwrap() []error }.

func AsPartialResult

func AsPartialResult(err error) (PartialResult, bool)

AsPartialResult returns the PartialResult in err's chain, if any.

type PermissionDeniedError

type PermissionDeniedError struct {
	Err       error
	ProjectID string
}

PermissionDeniedError reports that the service account lacks the IAM role needed to collect for ProjectID. It is returned instead of an empty result so callers cannot mistake a lost role for "no savings available". It is constructed only for the region-listing step of GetRecommendations.

func (*PermissionDeniedError) Error

func (e *PermissionDeniedError) Error() string

func (*PermissionDeniedError) Unwrap

func (e *PermissionDeniedError) Unwrap() error

type ProjectsClient

type ProjectsClient interface {
	GetProject(ctx context.Context, req *resourcemanagerpb.GetProjectRequest) (*resourcemanagerpb.Project, error)
	Close() error
}

ProjectsClient interface for project operations (enables mocking).

type Provider

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

Provider implements the provider.Provider interface for Google Cloud Platform.

func NewProvider

func NewProvider(config *provider.Config) (*Provider, error)

NewProvider creates a new GCP provider.

Project resolution order:

  1. config.GCPProjectID (typed field, preferred)
  2. Application Default Credentials' default project

Credential resolution: if config.GCPTokenSource is a non-nil oauth2.TokenSource, it is installed via option.WithTokenSource so all downstream clients use those credentials. Otherwise, clients fall back to Application Default Credentials.

func NewProviderWithCredentials

func NewProviderWithCredentials(ctx context.Context, projectID string, ts oauth2.TokenSource) *Provider

NewProviderWithCredentials creates a GCP provider that uses the supplied token source instead of Application Default Credentials. Use this for service account key or workload identity federation modes.

func NewProviderWithProject

func NewProviderWithProject(ctx context.Context, projectID string, opts ...option.ClientOption) *Provider

NewProviderWithProject creates a new GCP provider with a specific project.

func (*Provider) DisplayName

func (p *Provider) DisplayName() string

DisplayName returns the provider display name.

func (*Provider) GetAccounts

func (p *Provider) GetAccounts(ctx context.Context) ([]common.Account, error)

GetAccounts returns all accessible GCP projects.

func (*Provider) GetCredentials

func (p *Provider) GetCredentials() (provider.Credentials, error)

GetCredentials returns the current GCP credentials information.

This is credential *introspection* (which source is in use), not *validation* (do the credentials work). It deliberately performs NO network call: the source is determined from local inspection only. To verify the credentials actually work, call ValidateCredentials, which issues the GetProject RPC.

func (*Provider) GetDefaultRegion

func (p *Provider) GetDefaultRegion() string

GetDefaultRegion returns the default GCP region.

func (*Provider) GetRecommendationsClient

func (p *Provider) GetRecommendationsClient(ctx context.Context) (provider.RecommendationsClient, error)

GetRecommendationsClient creates a recommendations client.

func (*Provider) GetRegions

func (p *Provider) GetRegions(ctx context.Context) ([]common.Region, error)

GetRegions returns all available GCP regions using Compute Engine API.

func (*Provider) GetServiceClient

func (p *Provider) GetServiceClient(ctx context.Context, service common.ServiceType, region string) (provider.ServiceClient, error)

GetServiceClient creates a service client for the specified service and region.

func (*Provider) GetSupportedServices

func (p *Provider) GetSupportedServices() []common.ServiceType

GetSupportedServices returns the GCP services that have commitment recommendations. Cloud Storage is excluded: it has no commitment product. Cloud SQL and Memorystore are excluded too: their CUDs are spend-based and recommended only at Cloud Billing account scope, which this project-scoped provider does not collect yet (issue #294). GetServiceClient still builds their clients for pricing and validation.

func (*Provider) IsConfigured

func (p *Provider) IsConfigured() bool

IsConfigured checks if GCP credentials are configured.

When a client has been injected via SetProjectsClient (test path), the injector owns its lifecycle and we must NOT Close() it here — otherwise subsequent calls in the same test hit a closed connection. In production the client is constructed internally and we retain Close responsibility.

func (*Provider) Name

func (p *Provider) Name() string

Name returns the provider name.

func (*Provider) SetProjectsClient

func (p *Provider) SetProjectsClient(client ProjectsClient)

SetProjectsClient sets the projects client (for testing).

func (*Provider) SetRegionsClient

func (p *Provider) SetRegionsClient(client RegionsClient)

SetRegionsClient sets the regions client (for testing).

func (*Provider) SetResourceManagerService

func (p *Provider) SetResourceManagerService(svc ResourceManagerService)

SetResourceManagerService sets the resource manager service (for testing).

func (*Provider) ValidateCredentials

func (p *Provider) ValidateCredentials(ctx context.Context) error

ValidateCredentials validates that GCP credentials are valid. Same injected-client ownership rule as IsConfigured — see that godoc.

type RecommendationsClientAdapter

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

RecommendationsClientAdapter aggregates GCP CUD and commitment recommendations across all services.

func (*RecommendationsClientAdapter) GetAllRecommendations

func (r *RecommendationsClientAdapter) GetAllRecommendations(ctx context.Context) ([]common.Recommendation, error)

GetAllRecommendations retrieves all GCP commitment recommendations across all services.

func (*RecommendationsClientAdapter) GetRecommendations

GetRecommendations retrieves all GCP commitment recommendations across all services and regions.

Two-level concurrent fan-out:

  • Outer: errgroup over regions, capped at gcpRegionConcurrency() (CUDLY_GCP_REGION_PARALLELISM, default 10) to stay polite to the project-scoped Recommender API quota.
  • Inner: each region's goroutine calls the Compute Engine commitment recommender, the only GCP service with a project-scoped commitment recommender (issue #294).

Per-region errors are logged at WARN with region identifiers and do NOT cancel siblings: each goroutine returns nil to its errgroup. When some but not all regions fail, the successful recommendations are returned with a partial error naming the failed regions (AsPartialResult); when all fail, an error is returned with no recommendations.

After the outer Wait(), ctx.Err() is checked and propagated so a canceled parent ctx surfaces as context.Canceled / context.DeadlineExceeded rather than being swallowed by the per-region error-isolation goroutines.

Mirrors the Azure parallelisation in providers/azure/recommendations.go (closes #258, commit b10326c5) and the AWS service-loop parallelisation (closes #266).

func (*RecommendationsClientAdapter) GetRecommendationsForService

func (r *RecommendationsClientAdapter) GetRecommendationsForService(ctx context.Context, service common.ServiceType) ([]common.Recommendation, error)

GetRecommendationsForService retrieves GCP commitment recommendations for a specific service.

type RegionsClient

type RegionsClient interface {
	List(ctx context.Context, req *computepb.ListRegionsRequest) RegionsIterator
	Close() error
}

RegionsClient interface for regions operations (enables mocking).

type RegionsIterator

type RegionsIterator interface {
	Next() (*computepb.Region, error)
}

RegionsIterator interface for regions iteration (enables mocking).

type ResourceManagerService

type ResourceManagerService interface {
	ListProjects(ctx context.Context) ([]*cloudresourcemanager.Project, error)
}

ResourceManagerService interface for resource manager operations (enables mocking).

Directories

Path Synopsis
internal
billingcurrency
Package billingcurrency checks the currency of Cloud Billing Catalog prices.
Package billingcurrency checks the currency of Cloud Billing Catalog prices.
billingguard
Package billingguard keeps GCP service tests off the real Cloud Billing Catalog.
Package billingguard keeps GCP service tests off the real Cloud Billing Catalog.
recskip
Package recskip records the recommendations a GCP collection dropped so the provider can report them as a partial result instead of only logging them.
Package recskip records the recommendations a GCP collection dropped so the provider can report them as a partial result instead of only logging them.
skulist
Package skulist reads every page of a Cloud Billing catalog SKU listing.
Package skulist reads every page of a Cloud Billing catalog SKU listing.
skumatch
Package skumatch holds the matching rules the GCP services share when they pick a price out of Cloud Billing catalog SKUs.
Package skumatch holds the matching rules the GCP services share when they pick a price out of Cloud Billing catalog SKUs.
services
catalogprice
Package catalogprice holds the catalog pricing pipeline and offering assembly that the Cloud SQL, Cloud Storage and Memorystore clients have in common.
Package catalogprice holds the catalog pricing pipeline and offering assembly that the Cloud SQL, Cloud Storage and Memorystore clients have in common.
cloudsql
Package cloudsql provides GCP Cloud SQL commitments client
Package cloudsql provides GCP Cloud SQL commitments client
cloudstorage
Package cloudstorage provides GCP Cloud Storage commitments client
Package cloudstorage provides GCP Cloud Storage commitments client
computeengine
Package computeengine provides GCP Compute Engine Committed Use Discounts client
Package computeengine provides GCP Compute Engine Committed Use Discounts client
memorystore
Package memorystore provides GCP Memorystore (Redis) commitments client
Package memorystore provides GCP Memorystore (Redis) commitments client

Jump to

Keyboard shortcuts

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