Documentation
¶
Overview ¶
Package webhook provides Kubernetes admission webhook business logic for CloudZero Agent cost allocation. This package implements the core admission control system that validates and enhances Kubernetes resources with cost allocation metadata during their lifecycle (CREATE, UPDATE, DELETE operations).
The webhook system operates as a Primary Adapter in the hexagonal architecture, receiving admission requests from the Kubernetes API server and applying CloudZero's cost allocation policies before resources are persisted to etcd.
Key responsibilities:
- Admission validation: Ensure resources have required cost allocation tags
- Metadata injection: Add missing cost center, team, and project labels
- Policy enforcement: Validate cost allocation rules and organizational policies
- Resource tracking: Store resource metadata for billing and cost optimization
- Multi-version support: Handle different Kubernetes API versions (v1, v1beta1, v1beta2)
Architecture:
- WebhookController: Main orchestration and routing logic
- Resource Handlers: Specialized logic for each Kubernetes resource type
- Configuration Management: Dynamic policy updates and feature toggles
- Metrics Integration: Prometheus monitoring for webhook performance and errors
The webhook supports 20+ Kubernetes resource types across multiple API groups: Apps (Deployment, StatefulSet, DaemonSet), Core (Pod, Service, PVC), Batch (Job, CronJob), Networking (Ingress, IngressClass), Gateway API, Storage, and Custom Resource Definitions.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type WebhookController ¶
type WebhookController interface {
// GetSupported returns the complete registry of supported Kubernetes resource types for cost allocation.
// This method provides a comprehensive map of Group/Version/Kind combinations that the CloudZero Agent
// webhook can process, enabling dynamic discovery of supported resources and API version compatibility.
//
// The nested map structure enables efficient lookup and iteration:
// - First key (string): API group (apps, core, batch, networking, gateway-api, storage, extensions)
// - Second key (string): API version (v1, v1beta1, v1beta2) for backward compatibility
// - Third key (string): Resource kind (deployment, pod, service, ingress, job, etc.)
// - Value (metav1.Object): Prototype object for the resource type, used for deserialization
//
// Used by:
// - HTTP handlers to validate incoming admission requests against supported resources
// - Configuration systems to generate webhook configuration YAML with proper GVK declarations
// - Monitoring dashboards to display webhook coverage and supported resource inventory
// - Testing frameworks to verify handler registration for all supported resource combinations
//
// The returned map reflects the current handler registry and updates dynamically as handlers
// are registered during webhook controller initialization or runtime reconfiguration.
GetSupported() map[string]map[string]map[string]metav1.Object
// IsSupported checks whether a specific Group-Version-Kind (GVK)
// combination is supported for GET operations by the webhook controller.
//
// Parameters:
// - g: The API group of the resource.
// - v: The API version of the resource.
// - k: The kind of the resource.
//
// Returns:
// - bool: True if the specified GVK combination is supported for GET operations,
// otherwise false.
IsSupported(g, v, k string) bool
// GetConfigurationAccessor retrieves the configuration accessor for a specific
// Group-Version-Kind (GVK) combination, if it is registered.
//
// Parameters:
// - g: The API group of the resource.
// - v: The API version of the resource.
// - k: The kind of the resource.
//
// Returns:
// - config.ConfigAccessor: The configuration accessor for the specified GVK,
// or nil if the GVK is not registered.
GetConfigurationAccessor(g, v, k string) config.ConfigAccessor
// Review executes the core admission control logic for CloudZero cost allocation validation.
// This method is the primary entry point for processing Kubernetes admission requests,
// orchestrating the complete cost allocation pipeline from resource validation to metadata storage.
//
// Processing pipeline:
// 1. Extract Group/Version/Kind from admission request for handler selection
// 2. Record webhook event metrics for operational monitoring and analysis
// 3. Route to resource-specific handler or default allow-all handler
// 4. Execute cost allocation validation, policy enforcement, and metadata injection
// 5. Store resource metadata for billing attribution and cost optimization
// 6. Return admission decision with detailed explanations and warnings
//
// Resource-specific handlers implement specialized logic for different Kubernetes resource types:
// - Pods: Validate required cost tags, inject missing labels, track resource requests
// - Deployments: Enforce team assignments, validate cost center policies
// - Services: Apply network cost allocation rules, validate ingress configurations
// - PVCs: Implement storage cost attribution, validate retention policies
// - Jobs: Apply batch workload cost tracking, validate resource quotas
//
// Default handler behavior (unknown resources):
// - Allow admission without modification to prevent blocking legitimate workloads
// - Log unknown resource types for potential handler development
// - Record metrics for monitoring webhook coverage gaps
//
// Error handling and resilience:
// - Admission failures are logged with detailed context for troubleshooting
// - Network timeouts and context cancellation are handled gracefully
// - Configuration errors result in admission denial with clear user guidance
// - Handler panics are recovered to prevent webhook service disruption
//
// Performance considerations:
// - Request processing latency is tracked via Prometheus metrics
// - Handler selection uses efficient map lookup (O(1) complexity)
// - Resource deserialization is optimized for common resource types
// - Database operations are batched where possible for efficiency
//
// Returns admission response with:
// - Allowed: Boolean decision whether to permit the resource operation
// - Message: Detailed explanation for denials or informational guidance
// - Warnings: Non-blocking advice about cost allocation best practices
// - ID: Request correlation ID for audit trails and troubleshooting
Review(ctx context.Context, ar *types.AdmissionReview) (*types.AdmissionResponse, error)
// Settings returns the configuration settings for the webhook controller.
//
// Returns:
// - *config.Settings: The settings instance containing webhook configuration.
Settings() *config.Settings
}
WebhookController defines the core interface for CloudZero Agent admission webhook processing. This interface orchestrates the entire admission control pipeline, routing incoming Kubernetes admission requests to appropriate resource-specific handlers based on Group/Version/Kind (GVK) mapping.
The controller implements a dispatch pattern where each supported Kubernetes resource type (Pod, Deployment, Service, etc.) has a dedicated handler with specialized cost allocation logic. When no specific handler exists, a default handler allows requests to proceed without modification.
Key architectural responsibilities:
- Request routing: Map GVK combinations to specialized resource handlers
- Handler registry: Maintain supported resource types and API version compatibility
- Configuration access: Provide resource-specific configuration for cost allocation policies
- Default behavior: Ensure unknown resources are handled gracefully without blocking
The interface enables testing through mock implementations and supports runtime reconfiguration of cost allocation policies without requiring webhook service restarts.
Integration points:
- HTTP handlers receive admission requests and delegate to this controller
- Resource stores persist cost allocation metadata extracted during processing
- Configuration services provide dynamic policy updates and feature toggles
- Monitoring systems track processing metrics and error rates
func NewWebhookFactory ¶
func NewWebhookFactory(store types.ResourceStore, settings *config.Settings, clock types.TimeProvider) (WebhookController, error)
NewWebhookFactory constructs a fully configured WebhookController for CloudZero admission control. This factory function initializes the complete webhook processing pipeline, including handler registration for all supported Kubernetes resource types, metrics setup, and operational configuration.
The factory performs comprehensive initialization:
- Creates default "allow-all" handler for unknown resource types
- Registers 20+ resource-specific handlers across 5 API groups
- Establishes Prometheus metrics for operational monitoring
- Configures multi-version API support (v1, v1beta1, v1beta2)
- Sets up dependency injection for storage, configuration, and time services
Supported resource types and API groups:
- Apps API: Deployment, StatefulSet, DaemonSet, ReplicaSet
- Core API: Pod, Service, PVC, PV, Namespace, Node
- Batch API: Job, CronJob
- Networking API: Ingress, IngressClass
- Gateway API: Gateway, GatewayClass
- Storage API: StorageClass
- Extensions API: CustomResourceDefinition
Multi-version compatibility:
Each resource type is registered for multiple API versions to ensure compatibility across different Kubernetes cluster versions. This prevents admission failures when clusters use deprecated API versions during upgrades or legacy installations.
Dependencies and integration:
- store: ResourceStore for persisting cost allocation metadata
- settings: Dynamic configuration for cost allocation policies and feature toggles
- clock: TimeProvider for consistent timestamps and testing determinism
Error conditions:
Currently always returns success, but the error return enables future validation of configuration consistency, handler registration conflicts, or dependency issues.
Performance optimizations:
- Handler registration uses efficient map initialization
- Prometheus metrics are registered once using sync.Once
- Dispatch map structure enables O(1) handler lookup during request processing
Directories
¶
| Path | Synopsis |
|---|---|
|
Package backfiller provides functionality to backfill Kubernetes Resource objects, and if enabled invokes the webhook domain logic
|
Package backfiller provides functionality to backfill Kubernetes Resource objects, and if enabled invokes the webhook domain logic |
|
Package handler admission webhook handlers (hook.Handler) for various resource types.
|
Package handler admission webhook handlers (hook.Handler) for various resource types. |
|
Package helper contains decode helper methods for transforming kubernetes metav1.Objects into K8sObjects
|
Package helper contains decode helper methods for transforming kubernetes metav1.Objects into K8sObjects |
|
Package hook contains structures and interfaces for implementing admission webhooks handlers.
|
Package hook contains structures and interfaces for implementing admission webhooks handlers. |