Documentation
¶
Overview ¶
Package types defines event bus abstractions for inter-component communication in the CloudZero Agent.
Package types provides foundational data structures, interfaces, and error definitions for the CloudZero Agent.
This package serves as the Application Core in hexagonal architecture, defining the domain model and contracts that all other layers depend upon. It includes metric data structures, storage interfaces, Kubernetes resource definitions, and comprehensive error classifications for the entire agent system.
Package types defines file abstraction interfaces for CloudZero Agent storage operations.
Package types defines Kubernetes API resource constants and interfaces for the CloudZero Agent webhook system.
Package types defines core metric data structures for the CloudZero Agent's cost allocation pipeline.
Package types provides Prometheus metric naming utilities for the CloudZero Agent. This package contains functions for creating properly prefixed metric names that comply with CloudZero's metric taxonomy and avoid naming conflicts with existing Prometheus metrics or reserved CloudZero prefixes.
The CloudZero Agent distinguishes between two primary metric categories:
- Cost metrics: Prefixed with "cloudzero_" for cost allocation and financial analysis
- Observability metrics: Prefixed with "czo_" for operational monitoring and system health
These functions enforce naming conventions that prevent conflicts with existing CloudZero infrastructure metrics and ensure consistent metric categorization across the entire cost optimization platform.
Package types defines Kubernetes resource metadata structures for cost allocation.
Package types defines common lifecycle management interfaces for CloudZero Agent components.
Package types defines storage interfaces and contracts for the CloudZero Agent persistence layer.
Package types defines storage monitoring types for disk usage tracking and alerting.
Package types defines time abstraction interfaces for testable time-dependent operations.
Index ¶
- Constants
- Variables
- func CostMetric(metricName string) string
- func ObservabilityMetric(metricName string) string
- type AdmissionResponse
- type AdmissionReview
- type AdmissionReviewOp
- type AdmissionReviewVersion
- type Annotations
- type Bus
- type Creator
- type Deleter
- type Event
- type File
- type FileChanged
- type FileCreated
- type FileDeleted
- type FileRenamed
- type InputData
- type K8sObject
- type Label
- type Labels
- type Metric
- type MetricRange
- type MetricTransformer
- type ObjectCreator
- type ParquetMetric
- type ReadableStore
- type Reader
- type RemoteWriteHistory
- type ResourceStore
- type ResourceTags
- type Runnable
- type Sample
- type Set
- func (s *Set[T]) Add(element T)
- func (s *Set[T]) Contains(element T) bool
- func (s *Set[T]) Diff(other *Set[T]) *Set[T]
- func (s *Set[T]) List() []T
- func (s *Set[T]) MarshalJSON() ([]byte, error)
- func (s *Set[T]) Remove(element T)
- func (s *Set[T]) Size() int
- func (s *Set[T]) UnmarshalJSON(data []byte) error
- type Storage
- type StorageCommon
- type Store
- type StoreMonitor
- type StoreUsage
- type StoreWarning
- type Subscription
- type TimeProvider
- type TimeSeries
- type Updater
- type WritableStore
Constants ¶
const ( // GroupApps represents the apps/v1 API group containing workload resources like Deployments and StatefulSets. GroupApps = "apps" // GroupBatch represents the batch/v1 API group containing job-related resources like Jobs and CronJobs. GroupBatch = "batch" // GroupCore represents the core/v1 API group (empty string) containing fundamental resources like Pods and Nodes. GroupCore = "" // GroupExt represents the apiextensions.k8s.io API group containing CustomResourceDefinitions. GroupExt = "apiextensions.k8s.io" // GroupNet represents the networking.k8s.io API group containing Ingress and IngressClass resources. GroupNet = "networking.k8s.io" // GroupGateway represents the gateway.networking.k8s.io API group containing Gateway API resources. GroupGateway = "gateway.networking.k8s.io" // GroupStorage represents the storage.k8s.io API group containing storage-related resources. GroupStorage = "storage.k8s.io" // V1 represents the stable v1 API version used by most core Kubernetes resources. V1 = "v1" // V1Beta2 represents the v1beta2 API version for resources in beta stability. V1Beta2 = "v1beta2" // V1Beta1 represents the v1beta1 API version for resources in beta stability. V1Beta1 = "v1beta1" // KindDeployment represents Deployment workload resources that manage ReplicaSets and Pods. KindDeployment = "deployment" // KindStatefulSet represents StatefulSet workload resources that manage stateful applications. KindStatefulSet = "statefulset" // KindDaemonSet represents DaemonSet workload resources that ensure Pods run on all/selected nodes. KindDaemonSet = "daemonset" // KindReplicaSet represents ReplicaSet resources that maintain a stable set of replica Pods. KindReplicaSet = "replicaset" // KindPod represents Pod resources, the smallest deployable units containing one or more containers. KindPod = "pod" // KindNamespace represents Namespace resources that provide resource isolation and naming scope. KindNamespace = "namespace" // KindNode represents Node resources, the worker machines (physical or virtual) in the cluster. KindNode = "node" // KindService represents Service resources that expose Pods as network services. KindService = "service" // KindStorageClass represents StorageClass resources that define different types of storage. KindStorageClass = "storageclass" // KindPersistentVolume represents PersistentVolume resources that provide cluster-level storage. KindPersistentVolume = "persistentvolume" // KindPersistentVolumeClaim represents PersistentVolumeClaim resources that request storage. KindPersistentVolumeClaim = "persistentvolumeclaim" // KindJob represents Job resources that create one or more Pods to run a task to completion. KindJob = "job" // KindCronJob represents CronJob resources that create Jobs on a schedule. KindCronJob = "cronjob" // KindCRD represents CustomResourceDefinition resources that extend the Kubernetes API. KindCRD = "customresourcedefinition" // KindIngress represents Ingress resources that manage external access to cluster services. KindIngress = "ingress" // KindIngressClass represents IngressClass resources that define different ingress implementations. KindIngressClass = "ingressclass" // KindGateway represents Gateway resources from the Gateway API for advanced traffic management. KindGateway = "gateway" // KindGatewayClass represents GatewayClass resources that define different gateway implementations. KindGatewayClass = "gatewayclass" )
Kubernetes API group constants used for admission webhook resource filtering. These groups represent the primary API categories that the CloudZero Agent monitors for label and annotation collection to support cost allocation.
Variables ¶
var ( // ErrNotFound is returned when a specific item or record is not found. ErrNotFound = errors.New("not found") // ErrDuplicateKey is returned when a duplicate key is detected during an indexing operation. ErrDuplicateKey = errors.New("duplicate key") // ErrForeignKeyViolation is returned when a foreign key constraint is violated. ErrForeignKeyViolation = errors.New("foreign key violation") // ErrMalformedKey is returned when a key is malformed during an indexing operation. ErrMalformedKey = errors.New("malformed key") // ErrMultipleItemsFound is returned when multiple items are found when only one was expected. ErrMultipleItemsFound = errors.New("multiple items found") )
General Errors
var ( // ErrMissingIndices is returned when no indices are provided for an operation. ErrMissingIndices = errors.New("no indices provided") // ErrMissingItem is returned when no item is provided for an operation. ErrMissingItem = errors.New("no item provided") // ErrMissingIndex is returned when no index is provided for an operation. ErrMissingIndex = errors.New("no index provided") // ErrMissingKey is returned when no key is provided for an operation. ErrMissingKey = errors.New("no key provided") // ErrMissingQuery is returned when no query is provided for an operation. ErrMissingQuery = errors.New("no query provided") // ErrMissingValue is returned when no value is provided for an operation. ErrMissingValue = errors.New("no value provided") // ErrPrimaryKeyRequired is returned when a primary key is required but not provided. ErrPrimaryKeyRequired = errors.New("primary key required") // ErrModelValueRequired is returned when a model value is required but not provided. ErrModelValueRequired = errors.New("model value required") // ErrModelAccessibleFieldsRequired is returned when accessible fields are required but not provided. ErrModelAccessibleFieldsRequired = errors.New("model accessible fields required") // ErrSubQueryRequired is returned when a subquery is required but not provided. ErrSubQueryRequired = errors.New("subquery required") // ErrInvalidData is returned when the provided data is invalid. ErrInvalidData = errors.New("invalid data") // ErrInvalidField is returned when a provided field is invalid. ErrInvalidField = errors.New("invalid field") // ErrInvalidValue is returned when a provided value is invalid. ErrInvalidValue = errors.New("invalid value") // ErrInvalidValueLength is returned when a provided value does not meet length requirements. ErrInvalidValueLength = errors.New("invalid value length") // ErrEmptySlice is returned when an operation is performed on an empty slice. ErrEmptySlice = errors.New("empty slice") )
Validation Errors
var ( // ErrNotReady is returned when an operation is attempted on a component that is not ready. ErrNotReady = errors.New("not ready") // ErrInvalidTransaction is returned when a transaction is invalid. ErrInvalidTransaction = errors.New("invalid transaction") // ErrNotImplemented is returned when a feature or function is not implemented. ErrNotImplemented = errors.New("not implemented") // ErrMissingWhereClause is returned when a where clause is missing in a query. ErrMissingWhereClause = errors.New("missing where clause") // ErrUnsupportedRelation is returned when an unsupported relation is encountered. ErrUnsupportedRelation = errors.New("unsupported relation") // ErrUnsupportedDriver is returned when an unsupported database driver is used. ErrUnsupportedDriver = errors.New("unsupported driver") // ErrAlreadyRegistered is returned when attempting to register something that's already registered. ErrAlreadyRegistered = errors.New("already registered") // ErrDryRunModeUnsupported is returned when dry run mode is unsupported. ErrDryRunModeUnsupported = errors.New("dry run mode unsupported") // ErrInvalidDB is returned when an invalid database instance is provided. ErrInvalidDB = errors.New("invalid database") // ErrPreloadNotAllowed is returned when preloading is not permitted in a query. ErrPreloadNotAllowed = errors.New("preload not allowed") // ErrCheckConstraintViolated is returned when a check constraint is violated. ErrCheckConstraintViolated = errors.New("check constraint violated") // ErrTableMissing is returned when a required database table does not exist. ErrTableMissing = errors.New("required database table missing") )
Operational Errors
var Groups = []string{ GroupApps, GroupBatch, GroupCore, GroupExt, GroupNet, GroupGateway, }
Groups contains the complete list of Kubernetes API groups monitored by the CloudZero Agent. Used for webhook admission controller configuration and resource filtering logic.
var Kinds = []string{ KindDeployment, KindStatefulSet, KindDaemonSet, KindReplicaSet, KindPod, KindNamespace, KindNode, KindService, KindPersistentVolume, KindPersistentVolumeClaim, KindJob, KindCronJob, KindCRD, KindIngress, KindGateway, }
Kinds contains all Kubernetes resource kinds that the CloudZero Agent webhook monitors. This list must be kept synchronized with the webhook-validating-config.yaml template to ensure proper admission controller functionality for cost allocation data collection.
var Versions = []string{ V1, V1Beta2, V1Beta1, }
Versions contains the supported Kubernetes API versions for webhook operations. These versions define the API compatibility matrix for admission webhook rules.
Functions ¶
func CostMetric ¶
CostMetric creates a properly prefixed cost metric name for CloudZero financial analysis. This function transforms user-provided metric names into the standardized "cloudzero_" prefix format required by the CloudZero cost allocation platform for billing and cost optimization.
Cost metrics are used for:
- Resource tagging events and cost attribution
- Custom billing dimensions and cost center allocation
- Financial reporting and cost optimization analysis
- Integration with CloudZero's cost intelligence platform
The function enforces strict naming conventions to prevent conflicts with:
- Existing CloudZero infrastructure metrics
- Reserved CloudZero prefixes (czo, cz, cloudzero)
- Empty or malformed metric names
Security and validation:
- Panics on empty input to fail fast during development
- Panics on forbidden prefixes to prevent metric namespace pollution
- Ensures consistent metric categorization across the platform
Example transformations:
- "tag_event" → "cloudzero_tag_event"
- "custom_billing" → "cloudzero_custom_billing"
- "cost_center" → "cloudzero_cost_center"
Usage in metric processing pipeline:
Used during metric classification to distinguish cost-related metrics from observability metrics, enabling proper routing to financial systems.
func ObservabilityMetric ¶
ObservabilityMetric creates a properly prefixed observability metric name for CloudZero operational monitoring. This function transforms user-provided metric names into the standardized "czo_" prefix format used by CloudZero for system health monitoring and operational intelligence.
Observability metrics are used for:
- System performance monitoring and alerting
- Agent health checks and diagnostic information
- Resource utilization tracking and capacity planning
- Operational dashboards and SLA monitoring
The "czo_" prefix distinguishes these metrics from cost metrics ("cloudzero_" prefix), enabling proper routing to monitoring systems versus financial analysis platforms. This separation ensures observability data doesn't interfere with cost calculations while maintaining comprehensive system visibility.
The function enforces the same strict naming conventions as CostMetric to prevent:
- Conflicts with existing CloudZero infrastructure metrics
- Namespace pollution from reserved prefixes
- Inconsistent metric categorization across environments
Security and validation:
- Panics on empty input to ensure robust error handling during development
- Panics on forbidden prefixes to maintain metric namespace integrity
- Enforces consistent observability metric identification
Example transformations:
- "latency" → "czo_latency"
- "cpu_usage" → "czo_cpu_usage"
- "memory_pressure" → "czo_memory_pressure"
Usage in monitoring pipeline:
Used during metric classification to route operational metrics to monitoring systems while keeping cost metrics separate for financial analysis.
Types ¶
type AdmissionResponse ¶
type AdmissionResponse struct {
// ID correlates this response with the original admission request identifier.
// Used for tracking admission decisions through logs and audit trails, enabling
// troubleshooting of cost allocation validation failures and policy enforcement.
// Must match the ID from the corresponding AdmissionReview.
ID string
// Allowed indicates whether the CloudZero Agent permits this resource operation.
// When false, the Kubernetes API server will reject the resource operation and
// return the Message to the user. When true, the operation proceeds normally.
//
// Common reasons for rejection (Allowed=false):
// - Missing required cost allocation tags
// - Invalid cost center or team assignments
// - Policy violations (e.g., unapproved namespaces)
// - Resource quota or billing limit exceeded
Allowed bool
// Message provides detailed explanation for the admission decision.
// When Allowed=false, this message is displayed to users explaining why
// their resource was rejected and how to fix cost allocation issues.
// When Allowed=true, this may contain informational text about cost allocation.
//
// Examples:
// - "Missing required cost allocation tag: cost-center"
// - "Invalid team assignment: 'marketing' not found in organization"
// - "Resource allowed with cost center 'engineering'"
Message string
// Warnings contain non-blocking advice about cost allocation best practices.
// These are displayed to users even when Allowed=true, helping organizations
// improve their cost allocation hygiene without blocking resource creation.
//
// Common warnings:
// - "Consider adding project-specific tags for better cost attribution"
// - "Namespace 'default' has no cost center assignment"
// - "Resource lacks owner information for cost allocation"
Warnings []string
}
AdmissionResponse represents the CloudZero Agent's decision on a Kubernetes admission request. This struct provides a simplified interface for generating admission webhook responses that communicate cost allocation validation results back to the Kubernetes API server.
The CloudZero Agent uses this structure to:
- Indicate whether resources should be allowed into the cluster
- Provide detailed messages explaining cost allocation validation failures
- Generate warnings about cost allocation best practices
- Correlate responses with original admission requests for audit purposes
This abstraction enables consistent response generation across different admission API versions while maintaining compatibility with both v1 and v1beta1 response formats.
type AdmissionReview ¶
type AdmissionReview struct {
// OriginalAdmissionReview holds the raw Kubernetes admission review object (v1 or v1beta1).
// This field preserves the original request for debugging, audit logging, and response
// generation that requires format-specific handling. Essential for troubleshooting
// admission failures and maintaining compatibility with different API versions.
OriginalAdmissionReview runtime.Object
// ID is the unique identifier for this admission request from the Kubernetes API server.
// Used for tracking admission requests through the CloudZero Agent processing pipeline,
// correlating logs, and generating audit trails for cost allocation decisions.
// Corresponds to the UID field in the original admission request.
ID string
// Name is the name of the Kubernetes resource being processed in this admission request.
// Combined with Namespace, this provides the unique resource identifier within the cluster
// for cost allocation tracking and resource metadata storage. May be empty for
// cluster-scoped resources or during resource generation.
Name string
// Namespace is the namespace containing the resource being processed in this admission request.
// Essential for cost allocation as many organizations use namespace-based cost attribution
// and billing strategies. Empty for cluster-scoped resources like nodes, persistent volumes,
// and custom resource definitions that don't belong to specific namespaces.
Namespace string
// Operation identifies the type of Kubernetes operation being performed (CREATE, UPDATE, DELETE, CONNECT).
// The CloudZero Agent uses this field to apply appropriate cost allocation logic:
// CREATE operations validate and inject cost tags, UPDATE operations track cost changes,
// DELETE operations cleanup cost allocation metadata.
Operation AdmissionReviewOp
// Version identifies which admission review API version this request originated from (v1 or v1beta1).
// Used for generating properly formatted responses and handling version-specific field availability.
// Critical for maintaining compatibility across different Kubernetes cluster versions.
Version AdmissionReviewVersion
// RequestGVR identifies the Group/Version/Resource being operated on in this admission request.
// Used by the CloudZero Agent to determine which cost allocation rules and validation
// logic to apply based on resource type. Different resource types may require different
// cost attribution strategies (e.g., pods vs services vs ingresses).
RequestGVR *metav1.GroupVersionResource
// RequestGVK identifies the Group/Version/Kind being operated on in this admission request.
// Complements RequestGVR by providing the Kind information needed for resource-specific
// cost allocation processing. Used for routing requests to appropriate resource handlers.
RequestGVK *metav1.GroupVersionKind
// OldObjectRaw contains the raw JSON of the resource before modification (for UPDATE operations).
// The CloudZero Agent uses this field to detect changes in cost allocation metadata
// and calculate billing impact when resources are modified. Empty for CREATE operations.
// Essential for tracking cost center transfers and ownership changes.
OldObjectRaw []byte
// NewObjectRaw contains the raw JSON of the resource after modification or creation.
// This is the primary field used by the CloudZero Agent to extract cost allocation
// metadata, validate required tags, and inject missing cost attribution information.
// Contains the complete resource specification for cost allocation analysis.
NewObjectRaw []byte
// DryRun indicates whether this is a dry-run request (kubectl apply --dry-run).
// When true, the CloudZero Agent performs all validation and cost allocation analysis
// but doesn't store resource metadata or trigger billing system updates.
// Used for testing cost allocation policies without affecting production data.
DryRun bool
// UserInfo contains authentication information about the user or service account
// making the resource request. The CloudZero Agent may use this information for:
// - Audit logging of cost allocation changes
// - Applying user-specific cost allocation policies
// - Attribution of cost allocation decisions to specific users or teams
UserInfo authenticationv1.UserInfo
}
AdmissionReview represents a normalized admission webhook request for CloudZero cost allocation processing. This struct provides a unified interface for handling admission requests from both v1 and v1beta1 Kubernetes APIs, enabling consistent cost allocation logic regardless of cluster version.
The CloudZero Agent uses this structure to:
- Extract resource metadata for cost allocation validation
- Store admission context for audit and troubleshooting
- Process resource changes for billing impact assessment
- Generate appropriate admission responses with cost allocation guidance
This abstraction simplifies webhook logic by providing a single interface for both admission API versions while preserving all necessary information for cost allocation decisions.
func NewAdmissionReviewV1 ¶
func NewAdmissionReviewV1(ar *admissionv1.AdmissionReview) AdmissionReview
NewAdmissionReviewV1 creates a normalized AdmissionReview from a v1 Kubernetes admission request. This function converts the current stable v1 admission review format into the unified CloudZero Agent internal format, providing the preferred processing path for modern Kubernetes clusters (1.19+) with complete field availability.
This is the primary constructor used for admission request processing as it handles the stable v1 API with full feature support including enhanced warning capabilities and complete authentication information.
Key transformations:
- Maps v1 operation types to internal AdmissionReviewOp constants
- Extracts GroupVersionResource and GroupVersionKind with complete field support
- Handles DryRun field with proper nil pointer checking
- Preserves original admission review for generating properly formatted v1 responses
Returns a fully populated AdmissionReview with access to all v1 API fields.
func NewAdmissionReviewV1Beta1 ¶
func NewAdmissionReviewV1Beta1(ar *admissionv1beta1.AdmissionReview) AdmissionReview
NewAdmissionReviewV1Beta1 creates a normalized AdmissionReview from a v1beta1 Kubernetes admission request. This function converts the deprecated v1beta1 admission review format into the unified CloudZero Agent internal format, enabling consistent cost allocation processing across different Kubernetes API versions.
Used primarily for backward compatibility with older Kubernetes clusters (1.16-1.18) that only support the v1beta1 admission webhook API. The function handles field mapping and provides safe defaults for fields that may not exist in the v1beta1 format.
Key transformations:
- Maps v1beta1 operation types to internal AdmissionReviewOp constants
- Extracts GroupVersionResource and GroupVersionKind with fallback logic
- Handles optional DryRun field with safe default (false)
- Preserves original admission review for format-specific response generation
Returns a fully populated AdmissionReview ready for cost allocation processing.
type AdmissionReviewOp ¶
type AdmissionReviewOp string
AdmissionReviewOp represents the type of Kubernetes operation being performed during admission review. This type enables the CloudZero Agent webhook to apply different cost allocation logic based on whether resources are being created, updated, or deleted within the cluster.
Different operations require different cost allocation strategies:
- CREATE: Initial cost tag validation and metadata injection
- UPDATE: Cost tag change validation and billing impact assessment
- DELETE: Cost allocation cleanup and resource lifecycle tracking
- CONNECT: Proxy request validation (typically not used for cost allocation)
const ( // OperationUnknown represents an unrecognized or unsupported admission operation. // Used as a fallback when the Kubernetes API server sends an operation type // that the CloudZero Agent doesn't recognize, enabling graceful error handling // and preventing admission failures due to unknown operation types. // // Typically results in: // - Admission allowed with warning // - Operational monitoring alert for unknown operation encountered // - No cost allocation metadata processing OperationUnknown AdmissionReviewOp = "unknown" // OperationCreate represents a resource creation operation in Kubernetes. // This is the most common operation processed by the CloudZero Agent webhook // for cost allocation metadata validation and injection. // // Processing includes: // - Validating required cost allocation tags are present // - Injecting missing cost center or team identification labels // - Establishing initial resource cost attribution // - Recording resource creation for billing lifecycle tracking OperationCreate AdmissionReviewOp = "create" // OperationUpdate represents a resource modification operation in Kubernetes. // The CloudZero Agent processes updates to detect cost allocation changes // and ensure billing accuracy when resource metadata changes. // // Processing includes: // - Detecting changes to cost allocation tags and labels // - Validating cost center transfers and ownership changes // - Recording cost attribution modifications for audit purposes // - Updating stored resource metadata for accurate billing OperationUpdate AdmissionReviewOp = "update" // OperationDelete represents a resource deletion operation in Kubernetes. // The CloudZero Agent processes deletions to complete cost allocation // lifecycle tracking and ensure proper resource cleanup. // // Processing includes: // - Recording final cost allocation state before deletion // - Triggering cost allocation cleanup procedures // - Updating resource lifecycle tracking for billing accuracy // - Generally allows deletion with metadata cleanup OperationDelete AdmissionReviewOp = "delete" // OperationConnect represents a proxy connection operation in Kubernetes. // This operation type is rarely used in admission control and typically // doesn't require cost allocation processing by the CloudZero Agent. // // Processing includes: // - Generally allowed without cost allocation validation // - May log connection attempts for security auditing // - Doesn't affect resource cost attribution or billing OperationConnect AdmissionReviewOp = "connect" )
type AdmissionReviewVersion ¶
type AdmissionReviewVersion string
AdmissionReviewVersion represents the API version used for Kubernetes admission webhook communication. This type enables the CloudZero Agent to support multiple admission webhook API versions while maintaining compatibility across different Kubernetes cluster versions.
The CloudZero Agent webhook must handle both v1beta1 (legacy) and v1 (current) admission review protocols to ensure broad compatibility with Kubernetes clusters running different API server versions. Version selection impacts request/response format validation and field availability during cost allocation metadata extraction.
const ( // AdmissionReviewVersionV1beta1 identifies the deprecated v1beta1 admission review API. // Used for compatibility with older Kubernetes clusters (versions 1.16-1.18). // The CloudZero Agent maintains support for this version to ensure cost allocation // functionality works across diverse customer environments with legacy clusters. // // Key limitations: // - Some fields may be missing or have different formats compared to v1 // - Deprecated status requires careful handling for future Kubernetes compatibility // - Warning generation may behave differently than v1 API AdmissionReviewVersionV1beta1 AdmissionReviewVersion = "v1beta1" // AdmissionReviewVersionV1 identifies the current stable v1 admission review API. // This is the preferred version for Kubernetes clusters 1.19+ and provides the most // complete and stable admission review functionality for cost allocation processing. // // Benefits over v1beta1: // - Complete field set for resource metadata extraction // - Stable API contract with guaranteed backward compatibility // - Enhanced warning support for user feedback during validation // - Improved authentication and authorization information access AdmissionReviewVersionV1 AdmissionReviewVersion = "v1" )
type Annotations ¶
Annotations represents Kubernetes resource annotations containing additional metadata for billing analysis.
type Bus ¶
type Bus interface {
// Subscribe creates a new subscription to receive all events published to the bus.
// Returns a subscription that can be used to receive events asynchronously.
Subscribe() *Subscription
// Unsubscribe removes an active subscription from the bus and cleans up resources.
// Should be called when a component no longer needs to receive events.
Unsubscribe(*Subscription) error
// Publish sends an event to all active subscribers on the bus.
// Events are delivered asynchronously to prevent blocking the publisher.
Publish(event Event)
}
Bus defines the event communication interface for asynchronous messaging between CloudZero Agent components. This pattern enables loose coupling between services like file monitoring, metric processing, and storage operations.
type Creator ¶
type Creator[Model any] interface { // Create persists a new record in the underlying storage system. // The method may modify the input Model during the creation process, typically to: // - Set auto-generated primary key IDs for database records // - Populate creation timestamps and audit fields // - Apply default values defined by the storage schema // // Used throughout the agent for persisting new metric data, configuration changes, // and operational state records. The generic type parameter enables type-safe // operations while maintaining a consistent interface across different model types. // // Returns an error if the creation operation fails due to: // - Database connectivity issues or transaction conflicts // - Constraint violations (unique keys, foreign keys, check constraints) // - Storage capacity limits or disk space exhaustion // - Invalid model data that fails validation during persistence Create(ctx context.Context, it *Model) error }
Creator defines the interface for repository implementations that support record creation operations. This interface is part of the CRUD pattern used throughout the CloudZero Agent storage layer, enabling consistent data persistence across different model types and storage backends. Used for creating new metric records, configuration entries, and operational state data.
type Deleter ¶
type Deleter[ID comparable] interface { // Delete removes a record from the underlying storage system by its unique identifier. // The generic ID parameter supports various identifier types (string, int64, UUID) // matching the corresponding Reader interface for consistency. // // Used throughout the agent for: // - Removing processed metric files after successful upload to CloudZero // - Cleaning up expired configuration entries during system maintenance // - Deleting temporary operational state data after processing completion // // The operation should be idempotent - deleting a non-existent record // should not return an error to simplify cleanup logic and retry scenarios. // // Returns an error if the deletion operation fails due to: // - Database connectivity issues preventing the delete operation // - Foreign key constraints that prevent cascade deletion // - Storage system errors (disk full, permissions, corruption) // - Context cancellation interrupting the deletion process // // Implementations should handle referential integrity appropriately, // either through cascade deletion or by returning descriptive errors // when deletion would violate data consistency requirements. // // For systems requiring audit trails, implementations may perform // "soft deletes" (marking records as deleted) rather than physical removal. Delete(ctx context.Context, id ID) error }
Deleter defines the interface for repository implementations that support record removal operations. This interface provides the "D" in CRUD operations, enabling consistent data deletion patterns across different model types and storage backends throughout the CloudZero Agent. Used for removing outdated metrics, cleaning up temporary data, and lifecycle management.
type Event ¶
Event represents a message or notification sent through the event bus. Used throughout the agent for decoupled communication between services.
type File ¶
type File interface {
// io.ReadWriteCloser provides standard I/O operations for reading, writing, and resource cleanup.
// Implementations must handle proper buffering and flushing for performance optimization.
io.ReadWriteCloser
// UniqueID returns a stable identifier for this file across operations.
// Used for tracking files through the collection, compression, and upload pipeline.
// Must remain consistent even if the file is moved or renamed.
UniqueID() string
// Location returns the current full path of the file in the filesystem.
// This path may change if the file is moved during processing operations.
Location() string
// Rename moves the file to a new location in the filesystem.
// Used during the metric processing pipeline to move files between stages
// (e.g., from temporary to processed to uploaded directories).
// Returns error if the rename operation fails due to permissions or filesystem issues.
Rename(new string) error
// Size returns the current size of the file in bytes.
// Used for storage monitoring, upload progress tracking, and batch processing decisions.
// Returns error if the file size cannot be determined (e.g., file deleted, permissions).
Size() (int64, error)
}
File defines a comprehensive interface for file operations in the CloudZero Agent storage system. This abstraction enables testing with mock files and provides a consistent interface for different storage backends while supporting the metric file lifecycle management.
type FileChanged ¶
type FileChanged struct {
// Name is the full path of the modified file.
Name string
}
FileChanged represents a file system event when an existing file is modified. Triggers reprocessing or reloading of configuration and metric files.
type FileCreated ¶
type FileCreated struct {
// Name is the full path of the newly created file.
Name string
}
FileCreated represents a file system event when a new file is created. Used by file monitoring services to notify other components about new metric files or configuration changes that require processing.
type FileDeleted ¶
type FileDeleted struct {
// Name is the full path of the deleted file.
Name string
}
FileDeleted represents a file system event when a file is removed. Used to clean up references and trigger garbage collection of associated resources.
type FileRenamed ¶
type FileRenamed struct {
// Name is the new full path of the renamed file.
Name string
}
FileRenamed represents a file system event when a file is moved or renamed. Important for tracking metric files through the collection and processing pipeline.
type InputData ¶
type InputData struct {
// TimeSeries contains all metric series in the remote_write batch.
TimeSeries []TimeSeries `json:"timeseries"` //nolint:tagliatelle // matches Prometheus remote_write format
}
InputData represents the top-level structure for Prometheus remote_write requests. Received by the collector from Prometheus and other metric sources for processing into CloudZero's cost allocation format.
type K8sObject ¶
K8sObject defines a Kubernetes object that implements both metav1.Object and runtime.Object interfaces. For unknown or unsupported Kubernetes objects, use `unstructured.Unstructured` instead (e.g., objects like `corev1.PodExecOptions` that do not satisfy both interfaces).
type Label ¶
type Label struct {
// Name is the label key, following Prometheus naming conventions (__name__, node, etc.).
Name string `json:"name"`
// Value is the label value, containing the actual metadata for cost allocation analysis.
Value string `json:"value"`
}
Label represents a Prometheus-style label with name-value pair for metric metadata. Used throughout the metric collection and processing pipeline to maintain compatibility with Prometheus remote_write protocol and CloudZero's cost allocation requirements.
type Labels ¶
Labels represents Kubernetes resource labels used for cost allocation and resource identification.
type Metric ¶
type Metric struct {
// ID is a unique identifier for this metric record, generated during collection.
ID uuid.UUID
// ClusterName identifies the Kubernetes cluster this metric originated from.
ClusterName string
// CloudAccountID identifies the cloud provider account for cost allocation.
CloudAccountID string
// MetricName is the Prometheus metric name, typically extracted from the __name__ label.
MetricName string
// NodeName identifies the specific node where this metric was collected, if applicable.
NodeName string
// CreatedAt is when this metric record was created in the CloudZero Agent system.
CreatedAt time.Time
// TimeStamp is the original metric observation time from the Prometheus sample.
TimeStamp time.Time
// Labels contains all metric labels excluding those hoisted to dedicated fields (like __name__, node).
Labels map[string]string
// Value is the metric value as a string to preserve precision during serialization.
Value string
}
Metric represents the internal CloudZero metric format used throughout the processing pipeline. This is the canonical format after conversion from Prometheus TimeSeries, containing all necessary data for cost allocation analysis and upstream transmission.
func (*Metric) FullLabels ¶
FullLabels returns a map of all labels, including ones which have been hoisted out to fields.
func (*Metric) ImportLabels ¶
ImportLabels imports labels from a map. This is similar to setting the Labels field to labels, except for special-case labels are used to set fields on the metric.
Note that the fields will only be set if the label is present in the map, so it will not overwrite existing values unless the relevant label is actually found.
func (*Metric) JSON ¶
JSON converts a Metric to a generic map for flexible JSON serialization. This method is used internally by MarshalJSON to create the CloudZero API format with consistent field naming and timestamp formatting.
func (Metric) MarshalJSON ¶
MarshalJSON implements the json.Marshaler interface for Metric. Uses the JSON() method to ensure consistent serialization format compatible with the CloudZero API specification.
func (*Metric) Parquet ¶
func (m *Metric) Parquet() ParquetMetric
Parquet converts a Metric to ParquetMetric format for efficient columnar storage. This transformation partitions the data by time components (year, month, day, hour) and serializes labels as JSON for flexible querying in data warehouse systems.
func (*Metric) UnmarshalJSON ¶
UnmarshalJSON implements the json.Unmarshaler interface for Metric. Handles conversion from string-based JSON fields back to proper Go types, including UUID parsing and timestamp conversion from Unix milliseconds.
type MetricRange ¶
type MetricRange struct {
// Metrics contains the current page of metric records.
Metrics []Metric `json:"metrics"`
// Next is an optional pagination token for retrieving the next page of results.
Next *string `json:"next,omitempty"`
}
MetricRange represents a paginated collection of metrics for API responses. This structure supports efficient streaming and pagination of large metric datasets from storage systems to the CloudZero platform.
type MetricTransformer ¶ added in v1.2.9
type MetricTransformer interface {
// Transform processes a slice of metrics, converting vendor-specific metrics
// into standardized formats while passing through all other metrics unchanged.
//
// The transformation is idempotent - metrics that are already in standardized
// format or are not recognized pass through without modification.
//
// Parameters:
// - ctx: Request context for cancellation and tracing
// - metrics: Input metrics from Prometheus remote_write decode
//
// Returns:
// - Transformed metrics with GPU metrics in standardized format
// - Error if transformation fails (context cancellation, invalid data, etc.)
//
// The returned slice may have a different length than the input if transformation
// results in metric expansion (e.g., one input metric generating multiple output
// metrics for different resource attribution).
Transform(ctx context.Context, metrics []Metric) ([]Metric, error)
}
MetricTransformer defines the port for metric transformation operations in the Application Core. This interface enables conversion of vendor-specific metrics into standardized formats for cost allocation and resource tracking, following the hexagonal architecture pattern where transformation logic is abstracted through a port interface.
MetricTransformer implementations provide:
- Vendor-specific metric detection and classification
- Transformation of native metrics to standardized formats
- Support for multiple device types (GPUs, network devices, storage, etc.)
- Pass-through of unrecognized metrics without modification
The transformer operates as part of the metric collection pipeline between decode and filter stages:
Prometheus → Decode → Transform → Filter → Store
Example usage:
transformer := transform.NewMetricTransformer() transformed, err := transformer.Transform(ctx, metrics)
type ObjectCreator ¶
type ObjectCreator interface {
// NewObject decodes the provided raw runtime-encoded byte slice into a K8sObject.
// It extracts and captures the necessary metadata from the object.
// Returns the constructed K8sObject or an error if decoding fails.
NewObject(raw []byte) (K8sObject, error)
}
ObjectCreator defines an interface for creating Kubernetes objects from raw encoded data (json, or yaml). It provides a method to decode and transform raw runtime-encoded bytes into a K8sObject while capturing relevant metadata.
type ParquetMetric ¶
type ParquetMetric struct {
// ClusterName identifies the source Kubernetes cluster for cost allocation.
ClusterName string `parquet:"cluster_name"`
// CloudAccountID identifies the cloud provider account for billing analysis.
CloudAccountID string `parquet:"cloud_account_id"`
// Year provides time-based partitioning for efficient data warehouse queries.
Year string `parquet:"year"`
// Month provides monthly partitioning for billing cycle analysis.
Month string `parquet:"month"`
// Day provides daily partitioning for fine-grained cost tracking.
Day string `parquet:"day"`
// Hour provides hourly partitioning for detailed usage analysis.
Hour string `parquet:"hour"`
// MetricName is the Prometheus metric identifier for data classification.
MetricName string `parquet:"metric_name"`
// NodeName identifies the source node for infrastructure cost attribution.
NodeName string `parquet:"node_name"`
// CreatedAt is the metric creation timestamp in Unix milliseconds for efficient storage.
CreatedAt int64 `parquet:"created_at,timestamp"`
// TimeStamp is the original observation timestamp in Unix milliseconds.
TimeStamp int64 `parquet:"timestamp,timestamp"`
// Labels contains all metric metadata serialized as JSON for flexible querying.
Labels string `parquet:"labels"`
// Value is the metric measurement preserved as string for precision.
Value string `parquet:"value"`
}
ParquetMetric represents the optimized format for long-term storage and analytics. This format partitions data by time components (year, month, day, hour) for efficient querying and storage in columnar format, with labels serialized as JSON for flexibility.
func (*ParquetMetric) Metric ¶
func (pm *ParquetMetric) Metric() Metric
Metric converts a ParquetMetric back to the standard internal Metric format. This is used when reading data from long-term storage for processing or transmission. The conversion reconstructs timestamps from Unix milliseconds and deserializes the JSON labels back into a map structure.
type ReadableStore ¶
type ReadableStore interface {
StoreMonitor
// GetFiles returns the list of files in the store. `paths` can be used to add a specific location
GetFiles(paths ...string) ([]string, error)
// ListFiles gives a list of `[]os.DirEntry` for a given store. `paths` can be used to add a specific location
ListFiles(paths ...string) ([]os.DirEntry, error)
// Walk runs a `proccess` on the file loc of the implementation store
Walk(loc string, process filepath.WalkFunc) error
// Find searches for files recursively starting from a given directory with optional filename and extension filters.
Find(ctx context.Context, filterName string, filterExtension string) ([]string, error)
}
ReadableStore is for performing read operations against the store It is understood that this will only read to the store, and not write against it.
In addition, this implements the StoreMonitor interface to monitor the store.
type Reader ¶
type Reader[Model any, ID comparable] interface { // Get retrieves a single record from the storage system by its unique identifier. // The generic ID parameter supports various identifier types (string, int64, UUID) // depending on the specific model and storage backend requirements. // // Used throughout the agent for: // - Loading specific metric records for analysis or reprocessing // - Retrieving configuration entries by key for runtime behavior // - Fetching operational state data for system monitoring // // Returns a pointer to the requested Model instance if found, or an error if: // - The record with the specified ID does not exist (types.ErrNotFound) // - Database connectivity issues prevent the query from executing // - Storage corruption or schema migration issues affect data access // - Context cancellation interrupts the retrieval operation // // The returned Model pointer should not be modified without proper synchronization // if the storage backend uses shared data structures or caching mechanisms. Get(ctx context.Context, id ID) (*Model, error) }
Reader defines the interface for repository implementations that support record retrieval operations. This interface provides the "R" in CRUD operations, enabling type-safe data access patterns across different model types and storage backends throughout the CloudZero Agent. Used for retrieving metric records, configuration data, and operational state information.
type RemoteWriteHistory ¶
type RemoteWriteHistory struct {
// LastRemoteWriteTime is the timestamp of the most recent successful remote_write request.
// Used for monitoring metric collection continuity and detecting collection interruptions.
LastRemoteWriteTime time.Time
}
RemoteWriteHistory tracks the timestamp of the most recent Prometheus remote_write request. This structure is used to monitor metric collection activity and detect collection gaps that might indicate issues with the Prometheus integration or network connectivity.
type ResourceStore ¶
type ResourceStore interface {
// StorageCommon provides transaction support and bulk operations for resource metadata.
// These operations ensure data consistency across multiple resource updates and
// enable efficient batch processing during resource discovery and validation.
StorageCommon
// Storage provides CRUD operations for ResourceTags entities with string-based identifiers.
// The string ID typically represents the unique resource identifier within Kubernetes
// (namespace/name format) enabling efficient resource lookups and updates.
Storage[ResourceTags, string]
// FindFirstBy retrieves the first ResourceTags entity matching the specified query conditions.
// This method supports complex queries for resource discovery and validation operations.
//
// Common usage patterns:
// - Finding resources by specific label combinations for cost attribution
// - Locating resources within specific namespaces for scope validation
// - Discovering resources with specific ownership or team assignments
//
// The conditions parameter accepts ORM-style query conditions (field=value, field IN (values))
// enabling flexible resource lookup without complex SQL construction.
//
// Returns nil if no matching resource is found, enabling safe handling of optional lookups.
// Returns error if the query fails due to database connectivity or malformed conditions.
FindFirstBy(ctx context.Context, conds ...interface{}) (*ResourceTags, error)
// FindAllBy retrieves all ResourceTags entities matching the specified query conditions.
// This method enables bulk resource discovery and batch processing operations essential
// for cost allocation calculations and resource lifecycle management.
//
// Common usage patterns:
// - Finding all resources belonging to a specific team or cost center
// - Discovering resources with missing or incomplete cost allocation tags
// - Retrieving resources for bulk cost calculation and reporting operations
// - Implementing resource cleanup based on lifecycle policies
//
// The conditions parameter supports the same query syntax as FindFirstBy but returns
// multiple results in a slice format for efficient batch processing.
//
// Returns empty slice if no matching resources are found, enabling safe iteration.
// Returns error if the query fails due to database issues or invalid query conditions.
//
// Performance considerations:
// - Large result sets may require pagination in production environments
// - Consider using transaction context for consistency during bulk operations
// - Index key fields used in conditions for optimal query performance
FindAllBy(ctx context.Context, conds ...interface{}) ([]*ResourceTags, error)
}
ResourceStore defines the specialized storage interface for Kubernetes resource metadata persistence. This interface extends the generic Storage pattern with resource-specific query capabilities essential for the CloudZero Agent's cost allocation and resource tracking functionality.
The ResourceStore manages ResourceTags entities which contain cost allocation metadata extracted from Kubernetes resources during admission webhook processing. This data enables CloudZero's cost optimization platform to attribute infrastructure costs to specific applications, teams, and business units.
Key responsibilities:
- Persist resource metadata for cost allocation analysis
- Support efficient lookup of resources by various attributes
- Enable bulk operations for resource processing pipelines
- Maintain referential integrity for cost calculation accuracy
Integration points:
- Webhook handlers store new resource metadata during admission processing
- Cost allocation services query stored metadata for billing attribution
- Monitoring systems track resource metadata volume and processing efficiency
type ResourceTags ¶
type ResourceTags struct {
// ID is a unique database identifier for this resource metadata record.
ID string `gorm:"unique;autoIncrement"`
// Type identifies the Kubernetes resource type (deployment, pod, node, etc.) for cost categorization.
Type config.ResourceType `gorm:"primaryKey"`
// Name is the Kubernetes resource name, forming part of the composite primary key.
Name string `gorm:"primaryKey"`
// Namespace is the Kubernetes namespace containing this resource, nullable for cluster-scoped resources.
Namespace *string `gorm:"primaryKey"`
// MetricLabels contains Prometheus-style labels extracted from the resource for metric correlation.
MetricLabels *config.MetricLabels `gorm:"serializer:json"`
// Labels contains the Kubernetes resource labels used for cost allocation and resource grouping.
Labels *config.MetricLabelTags `gorm:"serializer:json"`
// Annotations contains the Kubernetes resource annotations with additional cost allocation metadata.
Annotations *config.MetricLabelTags `gorm:"serializer:json"`
// RecordCreated is when this metadata record was first created in the local database.
RecordCreated time.Time
// RecordUpdated is when this record was last updated due to resource label/annotation changes.
RecordUpdated time.Time
// SentAt tracks when this record was successfully transmitted to the CloudZero API, null if pending.
SentAt *time.Time
// Size is a computed field showing the total byte size of this record for storage monitoring.
Size int `` /* 174-byte string literal not displayed */
}
ResourceTags represents a database record of Kubernetes resource metadata for cost allocation. This structure stores labels, annotations, and metrics from admission webhook events, enabling the CloudZero platform to perform detailed cost analysis and resource attribution.
type Runnable ¶
type Runnable interface {
// Run starts the runnable component and blocks until completion or error.
// Implementations should handle graceful startup and be prepared for shutdown signals.
Run() error
// IsRunning returns true if the component is currently active and processing.
// This method provides status information for health checks and monitoring.
IsRunning() bool
// Shutdown initiates graceful shutdown of the component.
// Implementations should clean up resources, flush pending data, and return promptly.
Shutdown() error
}
Runnable defines the lifecycle contract for long-running components in the CloudZero Agent. This interface provides standardized start, status check, and shutdown operations for services like collectors, shippers, webhooks, and monitoring components.
type Sample ¶
type Sample struct {
// Value is the metric value as a float64 pointer to support null values in time series data.
Value *float64 `json:"value"`
// Timestamp is the Unix timestamp in milliseconds when the metric was observed, stored as string for JSON compatibility.
Timestamp string `json:"timestamp"`
}
Sample represents a single metric sample with timestamp and value. Follows the Prometheus TimeSeries format for remote_write protocol compatibility.
type Set ¶
type Set[T comparable] struct { // contains filtered or unexported fields }
Set provides a generic set data structure for efficient membership testing and deduplication. Used throughout the CloudZero Agent for managing collections of unique metric names, file paths, and configuration keys where order doesn't matter but uniqueness is required.
func NewSet ¶
func NewSet[T comparable]() *Set[T]
NewSet creates and returns a new empty Set with the specified comparable type. The zero value is ready to use but this constructor ensures proper initialization.
func NewSetFromList ¶
func NewSetFromList[T comparable](list []T) *Set[T]
NewSetFromList creates a set from a slice of elements, automatically deduplicating entries. Useful for converting configuration arrays or metric name lists into sets for efficient processing.
func (*Set[T]) Add ¶
func (s *Set[T]) Add(element T)
Add inserts an element into the set, idempotent operation that has no effect if element already exists. Used for building sets of unique metric names during filtering operations.
func (*Set[T]) Contains ¶
Contains performs O(1) membership testing to check if an element exists in the set. Primary method for metric name filtering and configuration key validation.
func (*Set[T]) Diff ¶
Diff returns a new set containing elements present in this set but absent in the other set. Used for configuration comparison and incremental metric processing to identify new entries.
func (*Set[T]) List ¶
func (s *Set[T]) List() []T
List converts the set to a slice for iteration or serialization purposes. Order is not guaranteed due to the underlying map implementation. Used when converting sets back to arrays for configuration output.
func (*Set[T]) MarshalJSON ¶
MarshalJSON implements the json.Marshaler interface by converting the set to a JSON array. The serialization format matches standard JSON arrays for compatibility with configuration files.
func (*Set[T]) Remove ¶
func (s *Set[T]) Remove(element T)
Remove deletes an element from the set, no effect if element doesn't exist. Used for excluding specific metrics or configuration keys from processing.
func (*Set[T]) Size ¶
Size returns the current number of unique elements in the set. Used for metrics reporting and capacity planning in metric processing pipelines.
func (*Set[T]) UnmarshalJSON ¶
UnmarshalJSON implements the json.Unmarshaler interface by reading a JSON array into the set. Automatically deduplicates any duplicate elements in the input JSON array.
type Storage ¶
type Storage[Model any, ID comparable] interface { // Creator provides record creation capabilities for new data entities. Creator[Model] // Reader provides record retrieval capabilities for existing data lookup. Reader[Model, ID] // Updater provides record modification capabilities for data maintenance. Updater[Model] // Deleter provides record removal capabilities for data lifecycle management. Deleter[ID] }
Storage defines the complete CRUD interface for CloudZero Agent data repositories. This generic interface combines all basic database operations into a unified contract that supports type-safe operations across different model types and ID formats. Used as the foundation for resource metadata, configuration, and operational data storage.
type StorageCommon ¶
type StorageCommon interface {
// Tx executes a block of operations within a database transaction for atomicity.
// The provided context includes transaction state that must be passed to all operations within the block.
// Used for complex operations involving multiple tables or ensuring data consistency across operations.
Tx(ctx context.Context, block func(ctxTx context.Context) error) error
// Count returns the total number of records in the associated table.
// Used for capacity monitoring, pagination calculations, and storage usage reporting.
Count(ctx context.Context) (int, error)
// DeleteAll removes all records from the associated table.
// Used for data cleanup operations, testing teardown, and maintenance procedures.
// Should be used with extreme caution in production environments.
DeleteAll(ctx context.Context) error
}
StorageCommon defines transaction and bulk operation methods shared across all repository implementations. These operations are provided by BaseRepoImpl and enable consistent database operations with proper transaction management for data integrity in the CloudZero Agent.
type Store ¶
type Store interface {
WritableStore
ReadableStore
}
Store represents a storage interface that provides methods to interact with metrics. It allows for writing and reading from the store
type StoreMonitor ¶
type StoreMonitor interface {
// GetUsage returns a complete snapshot of the store usage.
// optional `paths` can be defined which will be used as `filepath.Join(paths...)`
GetUsage(limit uint64, paths ...string) (*StoreUsage, error)
}
StoreMonitor is a generic interface for reporting on the usage of a store
type StoreUsage ¶
type StoreUsage struct {
// Total is the total storage capacity in bytes of the monitored filesystem.
Total uint64 `json:"total"`
// Available is the available storage space in bytes for new data.
Available uint64 `json:"available"`
// Used is the currently utilized storage in bytes, computed as Total - Available.
Used uint64 `json:"used"`
// PercentUsed is the utilization percentage, computed as (Used / Total) * 100.
// This field is used with StoreWarning thresholds to determine alert levels.
PercentUsed float64 `json:"percentUsed"`
// BlockSize is the underlying filesystem block size in bytes for storage efficiency calculations.
BlockSize uint32 `json:"blockSize"`
}
StoreUsage contains comprehensive storage utilization information for monitoring disk usage. This structure provides the data needed to calculate warning levels and make storage management decisions in the CloudZero Agent.
func (*StoreUsage) GetStorageWarning ¶
func (du *StoreUsage) GetStorageWarning() StoreWarning
GetStorageWarning evaluates the current storage usage against warning thresholds. Returns the appropriate StoreWarning level based on percentage utilization, enabling the monitoring system to take appropriate actions for storage management.
type StoreWarning ¶
type StoreWarning int
StoreWarning represents storage usage alert thresholds based on percentage utilization. These thresholds are used to determine when storage systems require attention to prevent data loss or collection failures in the CloudZero Agent.
var ( // StoreWarningNone indicates normal storage usage (below 50% utilization). StoreWarningNone StoreWarning = 49 // StoreWarningLow indicates elevated storage usage (50-64% utilization). // This level suggests monitoring should be increased but no immediate action required. StoreWarningLow StoreWarning = 50 // StoreWarningMed indicates moderate storage pressure (65-79% utilization). // This level may require cleanup of old data or storage expansion planning. StoreWarningMed StoreWarning = 65 // StoreWarningHigh indicates high storage usage (80-89% utilization). // This level requires immediate attention to prevent collection disruption. StoreWarningHigh StoreWarning = 80 // StoreWarningCrit indicates critical storage usage (90%+ utilization). // This level may cause metric collection failures and requires emergency response. StoreWarningCrit StoreWarning = 90 )
Storage usage warning thresholds as percentage values. These constants define the escalation levels for storage monitoring alerts.
type Subscription ¶
type Subscription = partybus.Subscription
Subscription represents an active subscription to event bus notifications. Consumers use subscriptions to receive events from publishers without direct coupling.
type TimeProvider ¶
type TimeProvider interface {
// GetCurrentTime returns the current system time.
// In production, this returns time.Now(). In tests, this can return controlled timestamps
// to validate time-dependent logic such as metric timestamping and data retention.
GetCurrentTime() time.Time
}
TimeProvider abstracts time operations to enable deterministic testing of time-sensitive logic. This interface allows components to use real time in production while enabling controlled time manipulation in tests for accurate validation of time-based behaviors.
type TimeSeries ¶
type TimeSeries struct {
// Labels contains all metric labels including __name__, resource identifiers, and custom tags.
Labels []Label `json:"labels"`
// Samples contains the time series data points with timestamps and values.
Samples []Sample `json:"samples"`
}
TimeSeries represents a complete Prometheus time series with labels and samples. This structure matches the Prometheus remote_write TimeSeries protobuf format for seamless integration with Prometheus collectors and the CloudZero platform.
type Updater ¶
type Updater[Model any] interface { // Update modifies an existing record in the underlying storage system. // The method may modify the input Model during the update process, typically to: // - Set modification timestamps and audit trail information // - Apply version increments for optimistic locking mechanisms // - Normalize or validate field values according to business rules // // Used throughout the agent for: // - Updating metric processing status and classification results // - Modifying configuration settings during runtime reconfiguration // - Updating operational state data for system health monitoring // // The generic type parameter enables type-safe update operations while // maintaining interface consistency across different model types. // // Returns an error if the update operation fails due to: // - Record not found (the target record no longer exists) // - Concurrent modification conflicts (optimistic locking failures) // - Database connectivity issues or transaction rollback conditions // - Constraint violations resulting from the updated field values // - Storage capacity limits preventing the update from completing // // Implementations should ensure atomicity of updates and proper error // reporting to enable appropriate retry and recovery strategies. Update(ctx context.Context, it *Model) error }
Updater defines the interface for repository implementations that support record modification operations. This interface provides the "U" in CRUD operations, enabling consistent data update patterns across different model types and storage backends throughout the CloudZero Agent. Used for modifying metric records, configuration updates, and operational state changes.
type WritableStore ¶
type WritableStore interface {
// All retrieves all metrics. It takes a context and an optional string pointer as parameters.
// Returns a MetricRange and an error.
All(context.Context, string) (MetricRange, error)
// Put appends one or more metrics to the storage, handling buffering internally.
Put(context.Context, ...Metric) error
// Flush writes all buffered data to persistent storage.
// This can be used to force a write without reaching the row limit.
Flush() error
// Pending returns the number of rows currently buffered and not yet written to disk.
// This can be used to monitor when a flush may be needed.
Pending() int
}
WritableStore represents an interface for append-only storage with controlled flushing and monitoring of buffered entries.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package clusterconfig provides protobuf-based cluster configuration management for the CloudZero Agent.
|
Package clusterconfig provides protobuf-based cluster configuration management for the CloudZero Agent. |
|
Package mocks is a generated GoMock package.
|
Package mocks is a generated GoMock package. |
|
Package status provides thread-safe access to CloudZero Agent cluster health reporting.
|
Package status provides thread-safe access to CloudZero Agent cluster health reporting. |