# Chaosblade-Spec-Go Architecture: Understanding the ChaosBlade Specification Module

> Explore the chaosblade-spec-go architecture, a pure Go contract layer defining experiment models and execution channels for ChaosBlade fault injection. Understand its role in separating core engine and backends.

- Repository: [ChaosBlade/chaosblade](https://github.com/chaosblade-io/chaosblade)
- Tags: architecture
- Published: 2026-02-27

---

**TLDR:** chaosblade-spec-go is a pure-Go contract layer that defines experiment models, execution channels, and standardized response formats for the ChaosBlade fault-injection platform, enabling clean separation between the core engine and executor backends.

The chaosblade-spec-go repository serves as the foundational specification module for the ChaosBlade chaos engineering platform. Located under `github.com/chaosblade-io/chaosblade-spec-go`, this library (version 1.8.0) establishes canonical data structures and interfaces that enable consistent communication between the CLI, server-side executors, and language-specific bindings.

## High-Level Directory Structure

The chaosblade-spec-go module follows a focused layout centered on the `spec/` directory. All public types reside under the `github.com/chaosblade-io/chaosblade-spec-go/spec` import path.

```

chaosblade-spec-go/
├── spec/
│   ├── spec.go          # Core types: ExpModel, command specs

│   ├── response.go      # Standardized response handling

│   ├── channel.go       # Execution channel interface

│   ├── log.go           # Context-aware logging

│   ├── error_code.go    # System-wide status codes

│   └── util/
│       └── util.go      # Helper functions

├── go.mod
└── go.sum

```

This organization keeps the API surface minimal while providing comprehensive support for experiment definition and execution control.

## Core Data Structures

The specification module centers on four primary concerns: experiment modeling, command declarations, transport abstraction, and result handling.

### Experiment Model Definition

In [`spec/spec.go`](https://github.com/chaosblade-io/chaosblade/blob/main/spec/spec.go), the **ExpModel** struct serves as the canonical representation of a ChaosBlade experiment. This type captures the unique experiment ID, target system, action name, and flag configuration:

```go
type ExpModel struct {
    Uid        string
    ActionName string
    Target     string
    Flags      []ExpFlag
}

```

The `ExpFlag` type stores individual parameter values as key-value pairs, allowing executors to parse configurations like CPU load percentage or network latency duration.

### Command Specification Types

Executor plugins declare their capabilities through **BaseExpModelCommandSpec**, defined in [`spec/spec.go`](https://github.com/chaosblade-io/chaosblade/blob/main/spec/spec.go):

```go
type BaseExpModelCommandSpec struct {
    ExpActions []ExpActionCommandSpec
    ExpFlags   []ExpFlagSpec
}

```

Each action specification includes metadata for CLI generation and validation:

```go
type ExpActionCommandSpec struct {
    ActionName string
    Desc       string
    Flags      []ExpFlagSpec
}

type ExpFlagSpec struct {
    Name     string
    Desc     string
    Required bool
    Default  string
}

```

### Standardized Response Handling

The **Response** type in [`spec/response.go`](https://github.com/chaosblade-io/chaosblade/blob/main/spec/response.go) provides a uniform envelope for success and failure results:

```go
type Response struct {
    Code    int
    Message string
    Result  interface{}
}

```

Helper constructors simplify response creation:

```go
func ReturnSuccess(result interface{}) *Response
func ReturnFail(code int, errMsg string) *Response

```

This standardization ensures that CLI and API consumers receive predictable JSON structures regardless of whether the executor runs locally or remotely.

### Channel Interface for Execution Transport

The **Channel** interface in [`spec/channel.go`](https://github.com/chaosblade-io/chaosblade/blob/main/spec/channel.go) decouples the client from execution backends:

```go
type Channel interface {
    Call(ctx context.Context, model *ExpModel) *Response
}

```

Implementations such as `GrpcChannel` handle transport specifics, allowing the core `chaosblade` repository to remain agnostic of whether experiments execute via local OS calls, remote gRPC, or Kubernetes CRDs.

## Execution Flow Architecture

The chaosblade-spec-go architecture orchestrates experiment lifecycle through a consistent five-phase flow:

1. **Model Construction**: The CLI or SDK populates an `ExpModel` using helpers like `GenerateUid()` from [`spec/util/util.go`](https://github.com/chaosblade-io/chaosblade/blob/main/spec/util/util.go).
2. **Channel Selection**: The system selects a `Channel` implementation—local for direct execution or gRPC for distributed scenarios.
3. **Spec Validation**: The executor validates the model against its `BaseExpModelCommandSpec`, ensuring supported actions and required flags.
4. **Execution**: The channel invokes the appropriate backend (OS, Docker, Kubernetes, JVM) and awaits completion.
5. **Response Wrapping**: Results are encapsulated using `ReturnSuccess` or `ReturnFail`, with the UID serving as the correlation key for subsequent operations.

This flow applies identically to both **Create** (fault injection) and **Destroy** (recovery) operations.

## Utility and Logging Infrastructure

The [`spec/util/util.go`](https://github.com/chaosblade-io/chaosblade/blob/main/spec/util/util.go) file provides essential helpers for experiment management:

```go
func GenerateUid() string
func GetFlagValue(flags []ExpFlag, name string) (string, bool)

```

For observability, [`spec/log.go`](https://github.com/chaosblade-io/chaosblade/blob/main/spec/log.go) exports context-aware logging functions that automatically prefix messages with experiment UIDs:

```go
func Info(ctx context.Context, format string, a ...interface{})
func Error(ctx context.Context, format string, a ...interface{})

```

This approach maintains audit trails without requiring manual UID injection in every log statement.

## Error Code Standardization

The [`spec/error_code.go`](https://github.com/chaosblade-io/chaosblade/blob/main/spec/error_code.go) file establishes a centralized registry of numeric status codes:

```go
const (
    ParameterInvalid = 1001
    K8sExecFailed    = 2002
)

```

This enumeration prevents code collisions and enables programmatic error handling across the ecosystem.

## Summary

- **chaosblade-spec-go** defines the contract layer between ChaosBlade's orchestration engine and execution backends through the `github.com/chaosblade-io/chaosblade-spec-go/spec` package.
- The **ExpModel** struct in [`spec/spec.go`](https://github.com/chaosblade-io/chaosblade/blob/main/spec/spec.go) serves as the canonical experiment representation, while **BaseExpModelCommandSpec** declares executor capabilities.
- The **Channel** interface abstracts transport mechanisms, supporting local execution, gRPC, and Kubernetes CRDs without modifying core logic.
- **Response** standardization and centralized **error codes** ensure consistent behavior across CLI, API, and embedded SDK consumers.
- Minimal dependencies and stable type definitions maintain binary compatibility across versions.

## Frequently Asked Questions

### What is the primary purpose of the chaosblade-spec-go module?

The chaosblade-spec-go module establishes the data contracts and interfaces required for ChaosBlade experiment execution. It defines how experiments are structured (`ExpModel`), how they are transmitted (`Channel` interface), and how results are reported (`Response`), enabling the core engine to remain decoupled from specific executor implementations like OS commands, Docker, or Kubernetes.

### How does the Channel interface enable multi-platform support?

The `Channel` interface in [`spec/channel.go`](https://github.com/chaosblade-io/chaosblade/blob/main/spec/channel.go) abstracts the transport layer through a single method signature: `Call(ctx context.Context, model *ExpModel) *Response`. Different implementations—such as `LocalChannel` for direct system calls or `GrpcChannel` for remote agents—handle platform-specific details while presenting a uniform API. This design allows ChaosBlade to support new execution environments by adding Channel implementations without modifying the specification module.

### Where are experiment UIDs generated in the codebase?

Experiment UIDs are generated in [`spec/util/util.go`](https://github.com/chaosblade-io/chaosblade/blob/main/spec/util/util.go) via the `GenerateUid()` function. This utility ensures unique identifiers across distributed executions, with the UID stored in the `ExpModel.Uid` field. The logging utilities in [`spec/log.go`](https://github.com/chaosblade-io/chaosblade/blob/main/spec/log.go) automatically extract this UID from the context to prefix all operation logs, maintaining correlation across create, query, and destroy lifecycle events.

### How does chaosblade-spec-go maintain backward compatibility?

The module maintains compatibility by treating the `spec/` package as a stable API surface. Core types like `ExpModel`, `Response`, and `Channel` remain structurally consistent, with new fields added only as optional extensions. Centralized error codes in [`spec/error_code.go`](https://github.com/chaosblade-io/chaosblade/blob/main/spec/error_code.go) use numeric ranges (e.g., 1000s for parameter issues, 2000s for Kubernetes) to prevent collisions as the ecosystem expands.