havoc

package module
v1.50.7 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2025 License: MIT Imports: 20 Imported by: 2

README

Havoc

The havoc package is a Go library designed to facilitate chaos testing within Kubernetes environments using Chaos Mesh.

Documentation

Documentation

Index

Examples

Constants

This section is empty.

Variables

Default logger

Functions

func ChaosObjectExists

func ChaosObjectExists(object client.Object, c client.Client) (bool, error)

func CreateLogger

func CreateLogger(config LoggerConfig) zerolog.Logger

Create initializes a zerolog.Logger based on the specified configuration.

func NewChaosMeshClient

func NewChaosMeshClient() (client.Client, error)

NewChaosMeshClient initializes and returns a new Kubernetes client configured for Chaos Mesh

func Ptr

func Ptr[T any](value T) *T

func WaitForAllChaosRunning

func WaitForAllChaosRunning(chaosObjects []*Chaos, timeoutDuration time.Duration) error

WaitForAllChaosRunning blocks until chaos experiments are running

Types

type Chaos

type Chaos struct {
	Object      client.Object
	Description string
	DelayCreate time.Duration // Delay before creating the chaos object
	Status      ChaosStatus
	Client      client.Client
	// contains filtered or unexported fields
}

func NewChaos

func NewChaos(opts ChaosOpts) (*Chaos, error)

NewChaos creates a new Chaos instance based on the provided options. It requires a client, a chaos object, and a logger to function properly. This function is essential for initializing chaos experiments in a Kubernetes environment.

Example
testLogger := zerolog.New(zerolog.ConsoleWriter{Out: os.Stderr}).With().Timestamp().Logger()
client := fake.NewFakeClient()
podChaos := &v1alpha1.PodChaos{ /* PodChaos spec */ }
chaos, err := NewChaos(ChaosOpts{
	Object:      podChaos,
	Description: "Pod failure example",
	DelayCreate: 5 * time.Second,
	Client:      client,
	Logger:      &testLogger,
})
if err != nil {
	panic(err)
}
logger := NewChaosLogger(testLogger)
annotator := NewSingleLineGrafanaAnnotator(
	"http://grafana-instance.com",
	"grafana-access-token",
	"dashboard-uid",
	Logger,
)
chaos.AddListener(logger)
chaos.AddListener(annotator)

chaos.Create(context.Background())

func (*Chaos) AddListener

func (c *Chaos) AddListener(listener ChaosListener)

func (*Chaos) Create

func (c *Chaos) Create(ctx context.Context)

Create initiates a delayed creation of a chaos object, respecting context cancellation and deletion requests. It uses a timer based on `DelayCreate` and calls `create` method upon expiration unless preempted by deletion.

func (*Chaos) Delete

func (c *Chaos) Delete(ctx context.Context) error

Delete stops the chaos operation, updates its status, and removes the chaos object if specified. It notifies listeners of the operation's completion and handles any errors encountered during the process.

func (*Chaos) GetChaosDescription

func (c *Chaos) GetChaosDescription() string

func (*Chaos) GetChaosDuration

func (c *Chaos) GetChaosDuration() (time.Duration, error)

func (*Chaos) GetChaosEvents

func (c *Chaos) GetChaosEvents() (*corev1.EventList, error)

func (*Chaos) GetChaosKind

func (c *Chaos) GetChaosKind() string

func (*Chaos) GetChaosName

func (c *Chaos) GetChaosName() string

func (*Chaos) GetChaosSpec

func (c *Chaos) GetChaosSpec() interface{}

func (*Chaos) GetChaosStatus

func (c *Chaos) GetChaosStatus() (*v1alpha1.ChaosStatus, error)

func (*Chaos) GetChaosTypeStr

func (c *Chaos) GetChaosTypeStr() string

func (*Chaos) GetEndTime

func (c *Chaos) GetEndTime() time.Time

GetEndTime returns the time when the chaos experiment ended

func (*Chaos) GetExpectedEndTime

func (c *Chaos) GetExpectedEndTime() (time.Time, error)

GetExpectedEndTime returns the time when the chaos experiment is expected to end

func (*Chaos) GetExperimentStatus

func (c *Chaos) GetExperimentStatus() (v1alpha1.ExperimentStatus, error)

func (*Chaos) GetObject

func (c *Chaos) GetObject() client.Object

func (*Chaos) GetStartTime

func (c *Chaos) GetStartTime() time.Time

GetStartTime returns the time when the chaos experiment started

func (*Chaos) Pause

func (c *Chaos) Pause(ctx context.Context) error

func (*Chaos) Resume

func (c *Chaos) Resume(ctx context.Context) error

func (*Chaos) Update

func (c *Chaos) Update(ctx context.Context) error

type ChaosEntity

type ChaosEntity interface {
	// Create initializes and submits the chaos object to Kubernetes.
	Create(ctx context.Context)
	// Delete removes the chaos object from Kubernetes.
	Delete(ctx context.Context) error
	// Registers a listener to receive updates about the chaos object's lifecycle.
	AddListener(listener ChaosListener)

	GetObject() client.Object
	GetChaosName() string
	GetChaosDescription() string
	GetChaosDuration() (time.Duration, error)
	GetChaosSpec() interface{}
	GetStartTime() time.Time
	GetEndTime() time.Time
	GetExpectedEndTime() (time.Time, error)
}

ChaosEntity is an interface that defines common behaviors for chaos management entities.

type ChaosEventDetails

type ChaosEventDetails struct {
	Event string
	Chaos *Chaos
	Error error
}

type ChaosListener

type ChaosListener interface {
	OnChaosCreated(chaos Chaos)
	OnChaosCreationFailed(chaos Chaos, reason error)
	OnChaosStarted(chaos Chaos)
	OnChaosPaused(chaos Chaos)
	OnChaosEnded(chaos Chaos)         // When the chaos is finished or deleted
	OnChaosStatusUnknown(chaos Chaos) // When the chaos status is unknown
}

ChaosListener is an interface that can be implemented by clients to listen to and react to chaos events.

type ChaosLogger

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

func NewChaosLogger

func NewChaosLogger(logger zerolog.Logger) *ChaosLogger

func (ChaosLogger) OnChaosCreated

func (l ChaosLogger) OnChaosCreated(chaos Chaos)

func (ChaosLogger) OnChaosCreationFailed

func (l ChaosLogger) OnChaosCreationFailed(chaos Chaos, reason error)

func (ChaosLogger) OnChaosDeleted

func (l ChaosLogger) OnChaosDeleted(chaos Chaos)

func (ChaosLogger) OnChaosEnded

func (l ChaosLogger) OnChaosEnded(chaos Chaos)

func (ChaosLogger) OnChaosPaused

func (l ChaosLogger) OnChaosPaused(chaos Chaos)

func (ChaosLogger) OnChaosStarted

func (l ChaosLogger) OnChaosStarted(chaos Chaos)

func (ChaosLogger) OnChaosStatusUnknown

func (l ChaosLogger) OnChaosStatusUnknown(chaos Chaos)

type ChaosOpts

type ChaosOpts struct {
	Object      client.Object
	Description string
	DelayCreate time.Duration
	Client      client.Client
	Listeners   []ChaosListener
	Logger      *zerolog.Logger
	Remove      bool
}

type ChaosStatus

type ChaosStatus string

ChaosStatus represents the status of a chaos experiment.

const (
	StatusCreated        ChaosStatus = "created"
	StatusCreationFailed ChaosStatus = "creation_failed"
	StatusRunning        ChaosStatus = "running"
	StatusPaused         ChaosStatus = "paused"
	StatusFinished       ChaosStatus = "finished"
	StatusDeleted        ChaosStatus = "deleted"
	StatusUnknown        ChaosStatus = "unknown" // For any state that doesn't match the above
)

These constants define possible states of a chaos experiment.

type LoggerConfig

type LoggerConfig struct {
	LogOutput string // "json-console" for JSON output, empty or "console" for human-friendly console output
	LogLevel  string // Log level (e.g., "info", "debug", "error")
	LogType   string // Custom log type identifier
}

type NamespaceScopedChaosRunner added in v1.50.5

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

func NewNamespaceRunner added in v1.50.4

func NewNamespaceRunner(l zerolog.Logger, c client.Client, remove bool) *NamespaceScopedChaosRunner

NewNamespaceRunner creates a new namespace-scoped chaos runner

func (*NamespaceScopedChaosRunner) RunPodCorrupt added in v1.50.7

func (cr *NamespaceScopedChaosRunner) RunPodCorrupt(ctx context.Context, cfg PodCorruptCfg) (*Chaos, error)

RunPodCorrupt initiates packet corruption for some pod in some namespace

func (*NamespaceScopedChaosRunner) RunPodDelay added in v1.50.5

func (cr *NamespaceScopedChaosRunner) RunPodDelay(ctx context.Context, cfg PodDelayCfg) (*Chaos, error)

RunPodDelay initiates a network delay chaos experiment on specified pods. It configures the delay parameters and applies them to the targeted namespace. This function is useful for testing the resilience of applications under network latency conditions.

func (*NamespaceScopedChaosRunner) RunPodFail added in v1.50.5

func (cr *NamespaceScopedChaosRunner) RunPodFail(ctx context.Context, cfg PodFailCfg) (*Chaos, error)

RunPodFail initiates a pod failure experiment based on the provided configuration. It creates a Chaos object that simulates pod failures for a specified duration, allowing users to test the resilience of their applications under failure conditions.

func (*NamespaceScopedChaosRunner) RunPodLoss added in v1.50.7

func (cr *NamespaceScopedChaosRunner) RunPodLoss(ctx context.Context, cfg PodLossCfg) (*Chaos, error)

RunPodLoss initiates packet loss for some pod in some namespace

func (*NamespaceScopedChaosRunner) RunPodPartition added in v1.50.5

func (cr *NamespaceScopedChaosRunner) RunPodPartition(ctx context.Context, cfg PodPartitionCfg) (*Chaos, error)

RunPodPartition initiates a network partition chaos experiment on specified pods. It configures the experiment based on the provided PodPartitionCfg and executes it. This function is useful for testing the resilience of applications under network partition scenarios.

func (*NamespaceScopedChaosRunner) RunPodStressCPU added in v1.50.5

func (cr *NamespaceScopedChaosRunner) RunPodStressCPU(ctx context.Context, cfg NodeCPUStressConfig) (*Chaos, error)

RunPodStressCPU initiates a CPU stress test on specified pods within a namespace. It creates a scheduled chaos experiment that applies CPU load based on the provided configuration. This function is useful for testing the resilience of applications under CPU stress conditions.

type NetworkChaosOpts

type NetworkChaosOpts struct {
	Name        string
	Description string
	DelayCreate time.Duration
	Delay       *v1alpha1.DelaySpec
	Loss        *v1alpha1.LossSpec
	NodeCount   int
	Duration    time.Duration
	Selector    v1alpha1.PodSelectorSpec
	K8sClient   client.Client
}

func (*NetworkChaosOpts) Validate

func (o *NetworkChaosOpts) Validate() error

type NodeCPUStressConfig added in v1.50.4

type NodeCPUStressConfig struct {
	Namespace               string
	Description             string
	Cores                   int
	CoreLoadPercentage      int // 0-100
	LabelKey                string
	LabelValues             []string
	InjectionDuration       time.Duration
	ExperimentTotalDuration time.Duration
	ExperimentCreateDelay   time.Duration
}

type PodChaosOpts

type PodChaosOpts struct {
	Name        string
	Description string
	DelayCreate time.Duration
	NodeCount   int
	Duration    time.Duration
	Spec        v1alpha1.PodChaosSpec
	K8sClient   client.Client
}

type PodCorruptCfg added in v1.50.7

type PodCorruptCfg struct {
	Namespace             string
	Description           string
	Corrupt               string
	Correlation           string
	LabelKey              string
	LabelValues           []string
	InjectionDuration     time.Duration
	ExperimentCreateDelay time.Duration
}

type PodDelayCfg added in v1.50.4

type PodDelayCfg struct {
	Namespace             string
	Description           string
	Latency               time.Duration
	Jitter                time.Duration
	Correlation           string
	LabelKey              string
	LabelValues           []string
	InjectionDuration     time.Duration
	ExperimentCreateDelay time.Duration
}

type PodFailCfg added in v1.50.4

type PodFailCfg struct {
	Namespace             string
	Description           string
	LabelKey              string
	LabelValues           []string
	InjectionDuration     time.Duration
	ExperimentCreateDelay time.Duration
}

type PodLossCfg added in v1.50.7

type PodLossCfg struct {
	Namespace             string
	Description           string
	Loss                  string
	Correlation           string
	LabelKey              string
	LabelValues           []string
	InjectionDuration     time.Duration
	ExperimentCreateDelay time.Duration
}

type PodPartitionCfg added in v1.50.4

type PodPartitionCfg struct {
	Namespace             string
	Description           string
	LabelFromKey          string
	LabelFromValues       []string
	LabelToKey            string
	LabelToValues         []string
	InjectionDuration     time.Duration
	ExperimentCreateDelay time.Duration
}

type RangeGrafanaAnnotator

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

func NewRangeGrafanaAnnotator

func NewRangeGrafanaAnnotator(grafanaURL, grafanaToken, dashboardUID string, logger zerolog.Logger) *RangeGrafanaAnnotator

func (RangeGrafanaAnnotator) OnChaosCreated

func (l RangeGrafanaAnnotator) OnChaosCreated(chaos Chaos)

func (RangeGrafanaAnnotator) OnChaosCreationFailed added in v1.50.3

func (l RangeGrafanaAnnotator) OnChaosCreationFailed(chaos Chaos, reason error)

func (RangeGrafanaAnnotator) OnChaosEnded

func (l RangeGrafanaAnnotator) OnChaosEnded(chaos Chaos)

func (RangeGrafanaAnnotator) OnChaosPaused

func (l RangeGrafanaAnnotator) OnChaosPaused(chaos Chaos)

func (RangeGrafanaAnnotator) OnChaosStarted

func (l RangeGrafanaAnnotator) OnChaosStarted(chaos Chaos)

func (RangeGrafanaAnnotator) OnChaosStatusUnknown

func (l RangeGrafanaAnnotator) OnChaosStatusUnknown(chaos Chaos)

OnChaosStatusUnknown handles the event when the status of a chaos experiment is unknown. It allows listeners to respond appropriately to this specific status change in the chaos lifecycle.

type SimplifiedEvent

type SimplifiedEvent struct {
	LastTimestamp string
	Type          string
	Message       string
}

type SingleLineGrafanaAnnotator

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

SingleLineGrafanaAnnotator annotates Grafana dashboards with chaos experiment events in a single line.

func NewSingleLineGrafanaAnnotator

func NewSingleLineGrafanaAnnotator(grafanaURL, grafanaToken, dashboardUID string, logger zerolog.Logger) *SingleLineGrafanaAnnotator

func (SingleLineGrafanaAnnotator) OnChaosCreated

func (l SingleLineGrafanaAnnotator) OnChaosCreated(chaos Chaos)

func (SingleLineGrafanaAnnotator) OnChaosCreationFailed

func (l SingleLineGrafanaAnnotator) OnChaosCreationFailed(chaos Chaos, reason error)

func (SingleLineGrafanaAnnotator) OnChaosEnded

func (l SingleLineGrafanaAnnotator) OnChaosEnded(chaos Chaos)

func (SingleLineGrafanaAnnotator) OnChaosPaused

func (l SingleLineGrafanaAnnotator) OnChaosPaused(chaos Chaos)

func (SingleLineGrafanaAnnotator) OnChaosStarted

func (l SingleLineGrafanaAnnotator) OnChaosStarted(chaos Chaos)

func (SingleLineGrafanaAnnotator) OnChaosStatusUnknown

func (l SingleLineGrafanaAnnotator) OnChaosStatusUnknown(chaos Chaos)

OnChaosStatusUnknown handles the event when the status of a chaos experiment is unknown. It allows listeners to respond appropriately to this specific status change in the chaos lifecycle.

type StressChaosOpts

type StressChaosOpts struct {
	Name        string
	Description string
	DelayCreate time.Duration
	NodeCount   int
	Stressors   *v1alpha1.Stressors
	Duration    time.Duration
	Selector    v1alpha1.PodSelectorSpec
	K8sClient   client.Client
}

Jump to

Keyboard shortcuts

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