types

package
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Jun 17, 2025 License: Apache-2.0 Imports: 20 Imported by: 0

Documentation

Overview

Package types contains types and errors used throughout the application.

Index

Constants

View Source
const (
	GroupApps    = "apps"
	GroupBatch   = "batch"
	GroupCore    = ""
	GroupExt     = "apiextensions.k8s.io"
	GroupNet     = "networking.k8s.io"
	GroupGateway = "gateway.networking.k8s.io"
	GroupStorage = "storage.k8s.io"

	V1      = "v1"
	V1Beta2 = "v1beta2"
	V1Beta1 = "v1beta1"

	KindDeployment            = "deployment"
	KindStatefulSet           = "statefulset"
	KindDaemonSet             = "daemonset"
	KindReplicaSet            = "replicaset"
	KindPod                   = "pod"
	KindNamespace             = "namespace"
	KindNode                  = "node"
	KindService               = "service"
	KindStorageClass          = "storageclass"
	KindPersistentVolume      = "persistentvolume"
	KindPersistentVolumeClaim = "persistentvolumeclaim"
	KindJob                   = "job"
	KindCronJob               = "cronjob"
	KindCRD                   = "customresourcedefinition"
	KindIngress               = "ingress"
	KindIngressClass          = "ingressclass"
	KindGateway               = "gateway"
	KindGatewayClass          = "gatewayclass"
)

Variables

View Source
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

View Source
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

View Source
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")
)

Operational Errors

View Source
var Versions = []string{
	V1,
	V1Beta2,
	V1Beta1,
}

Functions

func CostMetric

func CostMetric(metricName string) string

CostMetric takes a metric name as input and returns a new metric name prefixed with "cloudzero_". This function is used when creating new cost metrics for customers, such as tags (e.g., "cloudzero_tag_event").

The input metric name must not be empty and must not start with any of the forbidden prefixes: "", "czo", "cz", or "cloudzero". If these conditions are violated, the function will panic.

Example usage:

metric := CostMetric("tag_event") // Returns "cloudzero_tag_event"

func ObservabilityMetric

func ObservabilityMetric(metricName string) string

ObservabilityMetric takes a metric name as input and returns a new metric name prefixed with "czo_". This function is used when creating new observability metrics for customers.

The input metric name must not be empty and must not start with any of the forbidden prefixes: "", "czo", "cz", or "cloudzero". If these conditions are violated, the function will panic.

Example usage:

metric := ObservabilityMetric("latency") // Returns "cloudzero_obs_latency"

Types

type AdmissionResponse

type AdmissionResponse struct {
	ID       string
	Allowed  bool
	Message  string
	Warnings []string
}

AdmissionResponse is the response for validating webhooks.

type AdmissionReview

type AdmissionReview struct {
	OriginalAdmissionReview runtime.Object

	ID           string
	Name         string
	Namespace    string
	Operation    AdmissionReviewOp
	Version      AdmissionReviewVersion
	RequestGVR   *metav1.GroupVersionResource
	RequestGVK   *metav1.GroupVersionKind
	OldObjectRaw []byte
	NewObjectRaw []byte
	DryRun       bool
	UserInfo     authenticationv1.UserInfo
}

AdmissionReview represents a request admission review.

func NewAdmissionReviewV1

func NewAdmissionReviewV1(ar *admissionv1.AdmissionReview) AdmissionReview

NewAdmissionReviewV1 returns a new AdmissionReview from a admission/v1/admissionReview.

func NewAdmissionReviewV1Beta1

func NewAdmissionReviewV1Beta1(ar *admissionv1beta1.AdmissionReview) AdmissionReview

NewAdmissionReviewV1Beta1 returns a new AdmissionReview from a admission/v1beta/admissionReview.

type AdmissionReviewOp

type AdmissionReviewOp string

AdmissionReviewOp represents an admission review operation.

const (
	// OperationUnknown is an unknown operation.
	OperationUnknown AdmissionReviewOp = "unknown"
	// OperationCreate is a create operation.
	OperationCreate AdmissionReviewOp = "create"
	// OperationUpdate is a update operation.
	OperationUpdate AdmissionReviewOp = "update"
	// OperationDelete is a delete operation.
	OperationDelete AdmissionReviewOp = "delete"
	// OperationConnect is a connect operation.
	OperationConnect AdmissionReviewOp = "connect"
)

type AdmissionReviewVersion

type AdmissionReviewVersion string

AdmissionReviewVersion reprensents the version of the admission review.

const (
	// AdmissionReviewVersionV1beta1 is the version of the v1beta1 webhooks admission review.
	AdmissionReviewVersionV1beta1 AdmissionReviewVersion = "v1beta1"

	// AdmissionReviewVersionV1 is the version of the v1 webhooks admission review.
	AdmissionReviewVersionV1 AdmissionReviewVersion = "v1"
)

type Annotations

type Annotations = map[string]string

type Bus

type Bus interface {
	// Subscribe returns a new subscription to the bus.
	Subscribe() *Subscription
	// Unsubscribe removes a subscription from the bus.
	Unsubscribe(*Subscription) error
	// Publish sends an event to the bus.
	Publish(event Event)
}

type Creator

type Creator[Model any] interface {
	// Create creates a new record in the database. It may modify the input Model
	// along the way (e.g. to set the ID). It returns an error if there was a
	// problem creating the record.
	Create(ctx context.Context, it *Model) error
}

Creator is an interface that defines the method that must be implemented by a repository that provides access to records that can be created.

type Deleter

type Deleter[ID comparable] interface {
	// Delete deletes a record from the database by ID. It returns an error if
	// there was a problem deleting the record.
	Delete(ctx context.Context, id ID) error
}

Deleter is an interface that defines the method that must be implemented by a repository that provides access to records that can be deleted.

type Event

type Event = partybus.Event

type File

type File interface {
	io.ReadWriteCloser

	// a unique identifier for the file
	UniqueID() string

	// location of the file
	Location() string

	// change the name / location of the file in the environment
	Rename(new string) error

	// get the size of the file in bytes
	Size() (int64, error)
}

type FileChanged

type FileChanged struct {
	Name string
}

type FileCreated

type FileCreated struct {
	Name string
}

type FileDeleted

type FileDeleted struct {
	Name string
}

type FileRenamed

type FileRenamed struct {
	Name string
}

type InputData

type InputData struct {
	TimeSeries []TimeSeries `json:"timeseries"` //nolint:tagliatelle // "time_series" might be right; does this need to match something else?
}

type K8sObject

type K8sObject interface {
	metav1.Object
	runtime.Object
}

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  string `json:"name"`
	Value string `json:"value"`
}

type Labels

type Labels = map[string]string

type Metric

type Metric struct {
	ID             uuid.UUID
	ClusterName    string
	CloudAccountID string
	MetricName     string
	NodeName       string
	CreatedAt      time.Time
	TimeStamp      time.Time
	Labels         map[string]string
	Value          string
}

func (*Metric) FullLabels

func (m *Metric) FullLabels() map[string]string

FullLabels returns a map of all labels, including ones which have been hoisted out to fields.

func (*Metric) ImportLabels

func (m *Metric) ImportLabels(labels map[string]string)

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

func (m *Metric) JSON() map[string]interface{}

func (Metric) MarshalJSON

func (m Metric) MarshalJSON() ([]byte, error)

func (*Metric) Parquet

func (m *Metric) Parquet() ParquetMetric

func (*Metric) UnmarshalJSON

func (m *Metric) UnmarshalJSON(data []byte) error

type MetricRange

type MetricRange struct {
	Metrics []Metric `json:"metrics"`
	Next    *string  `json:"next,omitempty"`
}

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    string `parquet:"cluster_name"`
	CloudAccountID string `parquet:"cloud_account_id"`
	Year           string `parquet:"year"`
	Month          string `parquet:"month"`
	Day            string `parquet:"day"`
	Hour           string `parquet:"hour"`
	MetricName     string `parquet:"metric_name"`
	NodeName       string `parquet:"node_name"`
	CreatedAt      int64  `parquet:"created_at,timestamp"`
	TimeStamp      int64  `parquet:"timestamp,timestamp"`
	Labels         string `parquet:"labels"`
	Value          string `parquet:"value"`
}

func (*ParquetMetric) Metric

func (pm *ParquetMetric) Metric() Metric

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 record from the database by ID. It returns an error if there
	// was a problem retrieving the record.
	Get(ctx context.Context, id ID) (*Model, error)
}

Reader is an interface that defines the method that must be implemented by a repository that provides access to records that can be read.

type RemoteWriteHistory

type RemoteWriteHistory struct {
	LastRemoteWriteTime time.Time
}

type ResourceStore

type ResourceStore interface {
	StorageCommon
	Storage[ResourceTags, string]

	// FindFirstBy returns the first resource tag that matches the given conditions.
	FindFirstBy(ctx context.Context, conds ...interface{}) (*ResourceTags, error)
	// FindAllBy returns all resource tags that match the given conditions.
	FindAllBy(ctx context.Context, conds ...interface{}) ([]*ResourceTags, error)
}

type ResourceTags

type ResourceTags struct {
	ID            string                  `gorm:"unique;autoIncrement"`
	Type          config.ResourceType     `gorm:"primaryKey"`      // Type of k8s resource; deployment, statefulset, pod, node, namespace
	Name          string                  `gorm:"primaryKey"`      // Name of the resource
	Namespace     *string                 `gorm:"primaryKey"`      // Namspace of the resource, if applicable
	MetricLabels  *config.MetricLabels    `gorm:"serializer:json"` // Metric labels of the resource; nullable
	Labels        *config.MetricLabelTags `gorm:"serializer:json"` // Labels of the resource; nullable
	Annotations   *config.MetricLabelTags `gorm:"serializer:json"` // Annotations of the resource; nullable
	RecordCreated time.Time               // Creation time of the record
	RecordUpdated time.Time               // Time that the record was updated, if the k8s object was updated with different labels
	SentAt        *time.Time              // Time that the record was sent to the cloudzero API, or null if not sent yet
	Size          int                     `` // Size of the record in bytes
	/* 174-byte string literal not displayed */
}

type Runnable

type Runnable interface {
	// Run starts the runnable.
	Run() error
	// IsRunning returns true if the runnable is running.
	IsRunning() bool
	// Shutdown shuts down the runnable.
	Shutdown() error
}

type Sample

type Sample struct {
	Value     *float64 `json:"value"`
	Timestamp string   `json:"timestamp"`
}

type Set

type Set[T comparable] struct {
	// contains filtered or unexported fields
}

Set is a convenience type around a `map[string]struct{}`

func NewSet

func NewSet[T comparable]() *Set[T]

NewSet creates and returns a new Set

func NewSetFromList

func NewSetFromList[T comparable](list []T) *Set[T]

NewSetFromList creates a set from a list of elements

func (*Set[T]) Add

func (s *Set[T]) Add(element T)

Add adds an element to the set

func (*Set[T]) Contains

func (s *Set[T]) Contains(element T) bool

Contains checks if an element is in the set

func (*Set[T]) Diff

func (s *Set[T]) Diff(other *Set[T]) *Set[T]

Diff returns a new set containing elements that exist in the source set but not in `b`

func (*Set[T]) List

func (s *Set[T]) List() []T

List returns all elements in the set as a slice

func (*Set[T]) MarshalJSON

func (s *Set[T]) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface

func (*Set[T]) Remove

func (s *Set[T]) Remove(element T)

Remove removes an element from the set

func (*Set[T]) Size

func (s *Set[T]) Size() int

Size returns the number of elements in the set

func (*Set[T]) UnmarshalJSON

func (s *Set[T]) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface

type Storage

type Storage[Model any, ID comparable] interface {
	Creator[Model]
	Reader[Model, ID]
	Updater[Model]
	Deleter[ID]
}

Storage is a CRUD interface that defines the minimal methods that must be implemented by a storage that provides access to records. It is a combination of the Creator, Reader, Updater, and Deleter interfaces.

type StorageCommon

type StorageCommon interface {
	// Tx runs block in a transaction.
	Tx(ctx context.Context, block func(ctxTx context.Context) error) error
	// Count returns the number of records.
	Count(ctx context.Context) (int, error)
	// DeleteAll deletes all records.
	DeleteAll(ctx context.Context) error
}

StorageCommon defines common methods all repos implement by virtue of using BaseRepoImpl.

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       uint64  `json:"total"`       // Total storage in bytes
	Available   uint64  `json:"available"`   // Available storage in bytes
	Used        uint64  `json:"used"`        // Computed as Total - Available
	PercentUsed float64 `json:"percentUsed"` // Computed as (Used / Total) * 100
	BlockSize   uint32  `json:"blockSize"`   // Underlying block size
}

StoreUsage stores information about the current state of a store

func (*StoreUsage) GetStorageWarning

func (du *StoreUsage) GetStorageWarning() StoreWarning

GetStorageWarning uses the `PercentUsed` field to calculate the current warning state of a store

type StoreWarning

type StoreWarning int
var (
	StoreWarningNone StoreWarning = 49
	StoreWarningLow  StoreWarning = 50
	StoreWarningMed  StoreWarning = 65
	StoreWarningHigh StoreWarning = 80
	StoreWarningCrit StoreWarning = 90
)

type Subscription

type Subscription = partybus.Subscription

type TimeProvider

type TimeProvider interface {
	// GetCurrentTime returns the current time.
	GetCurrentTime() time.Time
}

type TimeSeries

type TimeSeries struct {
	Labels  []Label  `json:"labels"`
	Samples []Sample `json:"samples"`
}

type Updater

type Updater[Model any] interface {
	// Update updates an existing record in the database. It may modify the input
	// Model along the way (e.g. to set the updated_at timestamp). It returns an
	// error if there was a problem updating the record.
	Update(ctx context.Context, it *Model) error
}

Updater is an interface that defines the method that must be implemented by a repository that provides access to records that can be updated.

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.

Directories

Path Synopsis
Package clusterconfig provides clusterconfig
Package clusterconfig provides clusterconfig
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
Package status contains generated code for reading and writing the ClusterStatus protobuf.
Package status contains generated code for reading and writing the ClusterStatus protobuf.

Jump to

Keyboard shortcuts

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