docs: v2.1.0

Signed-off-by: Yue Yang <g1enyy0ung@gmail.com>
This commit is contained in:
Yue Yang 2021-12-01 11:14:07 +08:00
parent eee68c3da9
commit 0a9d32c6b7
214 changed files with 13880 additions and 2 deletions

View File

@ -28,7 +28,7 @@ yarn build
This command generates static content into the `build` directory and can be served using any static contents hosting service.
## New version
## Rlease new version
```sh
yarn docusaurus docs:version x.x.x

View File

@ -30,7 +30,7 @@ module.exports = {
},
announcementBar: {
content:
'Chaos Mesh 2.0 was released in July, 2021, see <a href="/blog/chaos-mesh-2.0-to-a-chaos-engineering-ecology">what\'s new</a>!',
'Chaos Mesh 2.1.0 was released 🎉, see <a href="https://github.com/chaos-mesh/chaos-mesh/releases/tag/v2.1.0" target="_blank">what\'s new</a>!',
backgroundColor: '#37b5fb',
},
navbar: {

View File

@ -0,0 +1,54 @@
{
"version.label": {
"message": "Next",
"description": "The label for version current"
},
"sidebar.docs.category.About Chaos Mesh": {
"message": "关于 Chaos Mesh",
"description": "The label for category About Chaos Mesh in sidebar docs"
},
"sidebar.docs.category.Getting Started": {
"message": "开始使用",
"description": "The label for category Getting Started in sidebar docs"
},
"sidebar.docs.category.Installation and Deployment": {
"message": "安装部署",
"description": "The label for category Installation and Deployment in sidebar docs"
},
"sidebar.docs.category.Run a Single Chaos Experiment": {
"message": "运行单个混沌实验",
"description": "The label for category Run a Single Chaos Experiment in sidebar docs"
},
"sidebar.docs.category.Orchestrate Multiple Chaos Experiments": {
"message": "编排多个混沌实验",
"description": "The label for category Orchestrate Multiple Chaos Experiments in sidebar docs"
},
"sidebar.docs.category.Types of Chaos Experiments": {
"message": "混沌实验类型",
"description": "The label for category Types of Chaos Experiments in sidebar docs"
},
"sidebar.docs.category.Kubernetes": {
"message": "Kubernetes",
"description": "The label for category Kubernetes in sidebar docs"
},
"sidebar.docs.category.Physical Nodes": {
"message": "物理机",
"description": "The label for category Physical Nodes in sidebar docs"
},
"sidebar.docs.category.Authentication": {
"message": "身份验证",
"description": "The label for category Authentication in sidebar docs"
},
"sidebar.docs.category.Tools Integration": {
"message": "工具整合",
"description": "The label for category Tools Integration in sidebar docs"
},
"sidebar.docs.category.Development Guides": {
"message": "开发指南",
"description": "The label for category Development Guides in sidebar docs"
},
"sidebar.docs.category.FAQs and Troubleshooting": {
"message": "常见问题与故障",
"description": "The label for category FAQs and Troubleshooting in sidebar docs"
}
}

View File

@ -0,0 +1,336 @@
---
title: 新增混沌实验类型
---
本文档介绍如何开发一种新的混沌实验类型。
以开发一种名为 HelloWorldChaos 的混沌实验类型为例,它的功能是向日志中输出一行 "Hello world!"。为了完成这一目标,你需要完成以下步骤:
- 第 1 步:定义混沌实验的结构类型
- 第 2 步:注册 CRD
- 第 3 步:注册混沌实验的处理函数
- 第 4 步:编译 Docker 镜像
- 第 5 步:运行混沌实验
## 第 1 步:定义混沌实验的结构类型
1. 在 API 目录 `api/v1alpha1` 中新建一个名为 `helloworldchaos_types.go` 的文件,写入以下内容:
```go
package v1alpha1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// +kubebuilder:object:root=true
// +chaos-mesh:base
// +chaos-mesh:oneshot=true
// HelloWorldChaos is the Schema for the helloworldchaos API
type HelloWorldChaos struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec HelloWorldChaosSpec `json:"spec"`
Status HelloWorldChaosStatus `json:"status,omitempty"`
}
// HelloWorldChaosSpec is the content of the specification for a HelloWorldChaos
type HelloWorldChaosSpec struct {
// ContainerSelector specifies target
ContainerSelector `json:",inline"`
// Duration represents the duration of the chaos action
// +optional
Duration *string `json:"duration,omitempty"`
}
// HelloWorldChaosStatus represents the status of a HelloWorldChaos
type HelloWorldChaosStatus struct {
ChaosStatus `json:",inline"`
}
// GetSelectorSpecs is a getter for selectors
func (obj *HelloWorldChaos) GetSelectorSpecs() map[string]interface{} {
return map[string]interface{}{
".": &obj.Spec.ContainerSelector,
}
}
```
这个文件定义了 HelloWorldChaos 的结构类型,它可以用一个 YAML 文件描述:
```yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: HelloWorldChaos
metadata:
name: <资源名>
namespace: <命名空间名>
spec:
duration: <持续时间>
status:
experiment: <实验状态>
...
```
2. 在 Chaos Mesh 根目录下运行 `make generate`,为 HelloWorldChaos 生成一些用于编译 Chaos Mesh 的辅助代码。
## 第 2 步:注册 CRD
在 Kubernetes API 中注册 HelloWorldChaos 的 CRD使 HelloWorldChaos 成为一种 Kubernetes 自定义资源。
1. 在根目录下运行 `make yaml`
生成的 YAML 文件位于 `config/crd/bases/chaos-mesh.org_helloworldchaos.yaml`
2. 为将这个 YAML 文件合并入 `manifests/crd.yaml` 中,修改 `config/crd/kustomization.yaml`,在其中加入新的一行:
```yaml
resources:
- bases/chaos-mesh.org_podchaos.yaml
- bases/chaos-mesh.org_networkchaos.yaml
- bases/chaos-mesh.org_iochaos.yaml
- bases/chaos-mesh.org_helloworldchaos.yaml # 新增一行
```
3. 再次运行 `make yaml`HelloWorldChaos 的定义就会出现在 `manifests/crd.yaml` 里。 如需确认,你可以使用 `git diff` 命令。
## 第 3 步:注册混沌实验的处理函数
1. 创建一个新文件 `controllers/chaosimpl/helloworldchaos/types.go` 并写入如下内容:
```go
package helloworldchaos
import (
"context"
"github.com/go-logr/logr"
"go.uber.org/fx"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/chaos-mesh/chaos-mesh/api/v1alpha1"
"github.com/chaos-mesh/chaos-mesh/controllers/chaosimpl/utils"
"github.com/chaos-mesh/chaos-mesh/controllers/common"
"github.com/chaos-mesh/chaos-mesh/controllers/utils/chaosdaemon"
)
type Impl struct {
client.Client
Log logr.Logger
decoder *utils.ContainerRecordDecoder
}
// Apply applies HelloWorldChaos
func (impl *Impl) Apply(ctx context.Context, index int, records []*v1alpha1.Record, obj v1alpha1.InnerObject) (v1alpha1.Phase, error) {
impl.Log.Info("Hello world!")
return v1alpha1.Injected, nil
}
// Recover means the reconciler recovers the chaos action
func (impl *Impl) Recover(ctx context.Context, index int, records []*v1alpha1.Record, obj v1alpha1.InnerObject) (v1alpha1.Phase, error) {
impl.Log.Info("Goodbye world!")
return v1alpha1.NotInjected, nil
}
func NewImpl(c client.Client, log logr.Logger, decoder *utils.ContainerRecordDecoder) *common.ChaosImplPair {
return &common.ChaosImplPair{
Name: "helloworldchaos",
Object: &v1alpha1.HelloWorldChaos{},
Impl: &Impl{
Client: c,
Log: log.WithName("helloworldchaos"),
decoder: decoder,
},
ObjectList: &v1alpha1.HelloWorldChaosList{},
}
}
var Module = fx.Provide(
fx.Annotated{
Group: "impl",
Target: NewImpl,
},
)
```
2. Chaos Mesh 使用 [fx](https://github.com/uber-go/fx) 这个库来进行依赖注入。为了注册进 Controller Manager需要在 `controllers/chaosimpl/fx.go` 中加入一行:
```go
...
gcpchaos.Module,
stresschaos.Module,
jvmchaos.Module,
timechaos.Module,
helloworldchaos.Module // 新增一行,注意处理 import
```
以及在 `controllers/types/types.go` 中加入:
```go
...
fx.Annotated{
Group: "objs",
Target: Object{
Name: "timechaos",
Object: &v1alpha1.TimeChaos{},
},
},
fx.Annotated{
Group: "objs",
Target: Object{
Name: "gcpchaos",
Object: &v1alpha1.GCPChaos{},
},
},
fx.Annotated{
Group: "objs",
Target: Object{
Name: "helloworldchaos",
Object: &v1alpha1.HelloWorldChaos{},
},
},
```
## 第 4 步:编译 Docker 镜像
1. 在完成了前面所有步骤后,你可以尝试编译镜像:
```bash
make
```
2. 将镜像推送到本地的 Docker Registry 中:
```bash
make docker-push
```
3. 如果你的 Kubernetes 集群部署在 kind 上,则还需要将镜像加载进 kind 中:
```bash
kind load docker-image localhost:5000/pingcap/chaos-mesh:latest
kind load docker-image localhost:5000/pingcap/chaos-daemon:latest
kind load docker-image localhost:5000/pingcap/chaos-dashboard:latest
```
## 第 5 步:运行混沌实验
在这一步中,你需要部署修改版的 Chaos Mesh 并测试 HelloWorldChaos。
在你部署 Chaos Mesh 之前(使用 `helm install``helm upgrade`),请修改 helm 模板的 `helm/chaos-mesh/values.yaml`,把镜像更换成你本地 Docker Registry 中的镜像。
Chaos Mesh 的模板使用 `pingcap/chaos-mesh:latest` 作为默认 Registry你需要把它换成 `DOCKER_REGISTRY` 环境变量的值(默认为 `localhost:5000`),示例如下:
```yaml
controllerManager:
image: localhost:5000/pingcap/chaos-mesh:latest
...
chaosDaemon:
image: localhost:5000/pingcap/chaos-daemon:latest
...
dashboard:
image: localhost:5000/pingcap/chaos-dashboard:latest
...
```
完成上述模板修改后,请尝试运行 HelloWorldChaos。
1. 将 CRD 注册进集群:
```bash
kubectl create -f manifests/crd.yaml
```
可以看到 HelloWorldChaos 已经被创建:
```log
customresourcedefinition.apiextensions.k8s.io/helloworldchaos.chaos-mesh.org created
```
现在可以查看 HelloWorldChaos 的 CRD
```bash
kubectl get crd helloworldchaos.chaos-mesh.org
```
2. 安装 Chaos Mesh
```bash
helm install chaos-mesh helm/chaos-mesh --namespace=chaos-testing --set chaosDaemon.runtime=containerd --set chaosDaemon.socketPath=/run/containerd/containerd.sock
```
验证一下安装是否成功,查询 `chaos-testing` 命名空间的 Pod:
```bash
kubectl get pods --namespace chaos-testing -l app.kubernetes.io/instance=chaos-mesh
```
:::note 注意
`--set chaosDaemon.runtime=containerd --set chaosDaemon.socketPath=/run/containerd/containerd.sock` 是用来在 kind 上运行 NetworkChaos 的。
:::
3. 部署用于测试的目标 Pod
```bash
kubectl apply -f https://raw.githubusercontent.com/chaos-mesh/apps/master/ping/busybox-statefulset.yaml
```
请确保用于测试的目标 Pod 可以正常运行。
4. 创建一个名为 `chaos.yaml` 的文件,写入以下内容:
```yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: HelloWorldChaos
metadata:
name: hello-world
namespace: chaos-testing
spec:
selector:
namespaces:
- busybox
mode: one
duration: 1h
```
5. 运行混沌实验:
```bash
kubectl apply -f /path/to/chaos.yaml
```
```bash
kubectl get HelloWorldChaos -n chaos-testing
```
现在查看 `chaos-controller-manager` 的日志,就会看到 `Hello World!`
```bash
kubectl logs chaos-controller-manager-{pod-post-fix} -n chaos-testing
```
显示日志如下:
```log
2021-06-24T06:42:26.858Z INFO records apply chaos {"id": "chaos-testing/chaos-daemon-vsmc5"}
2021-06-24T06:42:26.858Z INFO helloworldchaos Hello World!
```
:::note 注意
`{pod-post-fix}` 是一个随机串。你可以运行 `kubectl get pod -n chaos-testing` 来查看它。
:::
## 探索更多
如果你在新增混沌实验类型的过程中遇到了问题,请在 GitHub 创建一个 [issue](https://github.com/pingcap/chaos-mesh/issues) 向 Chaos Mesh 团队反馈。
如果你想进一步尝试开发工作,请参阅 [拓展 Chaos Daemon 接口](extend-chaos-daemon-interface.md)。

View File

@ -0,0 +1,5 @@
---
title: Chaos Mesh 架构
---
## TODO

View File

@ -0,0 +1,55 @@
---
title: 基本功能
---
本文档介绍 Chaos Mesh 的基本功能,包括[故障注入](#故障注入)、[混沌实验场景](#混沌实验场景)、[可视化操作](#可视化操作)、[安全保障](#安全保障)。
## 故障注入
故障注入是混沌实验的核心。Chaos Mesh 充分考虑分布式系统可能出现的故障,提供全面、细粒度的故障类型,分为基础资源类型故障、平台类型故障和应用层故障三大类。
- 基础资源类型故障:
- [PodChaos](simulate-pod-chaos-on-kubernetes.md):模拟 Pod 故障,例如 Pod 节点重启、Pod 持续不可用,以及特定 Pod 中的某些容器故障。
- [NetworkChaos](simulate-network-chaos-on-kubernetes.md):模拟网络故障,例如网络延迟、网络丢包、包乱序、各类网络分区。
- [DNSChaos](simulate-dns-chaos-on-kubernetes.md):模拟 DNS 故障,例如 DNS 域名解析失败、返回错误 IP 地址。
- [HTTPChaos](simulate-http-chaos-on-kubernetes.md):模拟 HTTP 通信故障,例如 HTTP 通信延迟。
- [StressChaos](simulate-heavy-stress-on-kubernetes.md):模拟 CPU 抢占或内存抢占场景。
- [IOChaos](simulate-io-chaos-on-kubernetes.md):模拟具体某个应用的文件 I/O 故障,例如 I/O 延迟、读写失败。
- [TimeChaos](simulate-time-chaos-on-kubernetes.md):模拟时间跳动异常。
- [KernelChaos](simulate-kernel-chaos-on-kubernetes.md):模拟内核故障,例如应用内存分配异常。
- 平台类型故障:
- [AWSChaos](simulate-aws-chaos.md):模拟 AWS 平台故障,例如 AWS 节点重启。
- [GCPChaos](simulate-gcp-chaos.md):模拟 GCP 平台故障,例如 GCP 节点重启。
- 应用层故障:
- [JVMChaos](simulate-jvm-application-chaos.md):模拟 JVM 应用故障,例如函数调用延迟。
## 混沌实验场景
混沌实验场景由一组混沌实验和应用状态检查组成,旨在帮助用户在平台上实现混沌工程闭环。
用户运行混沌场景,可以通过一系列的混沌实验,不断地扩大爆炸半径(包括攻击范围)和增加故障类型。运行混沌实验后,用户可以方便地检查当前的应用状态,判断是否需要进行后续混沌实验。同时用户可以不断地迭代混沌实验场景,积累混沌实验场景,以及方便地将已有的混沌实验场景复用到其他应用混沌实验中,大大降低了混沌实验的成本。
目前混沌实验场景提供的功能有:
- 编排串行混沌实验
- 编排并行混沌实验
- 支持状态检查步骤
- 支持中途暂停混沌实验
- 支持使用 YAML 文件定义和管理混沌实验场景
- 支持通过 Web UI 定义和管理混沌实验场景
具体的实验场景配置,参考具体[创建 Chaos Mesh Workflow](create-chaos-mesh-workflow.md)。
## 可视化操作
Chaos Mesh 为用户提供了单独的 Chaos Dashboard 组件即可视化支持。Chaos Dashboard 极大地简化了混沌实验,用户可以直接通过可视化界面来管理和监控混沌实验,仅需点一点鼠标就能够定义混沌实验的范围、指定混沌注入的类型、定义调度规则,以及在界面上获取到混沌实验的结果等。
![混沌实验场景](img/dashboard-overview.png)
## 安全保障
Chaos Mesh 通过 Kubernetes 原生的 [RBAC](https://kubernetes.io/docs/reference/access-authn-authz/rbac/)(基于角色的权限控制)功能对权限进行管理。
用户可以根据实际的权限需求自由地创建多种 Role然后绑定到用户名 Service Account 上,最后生成 Service Account 对应的 Token。用户使用该 Token 登陆 Dashboard只能在该 Service Account 允许的权限范围内进行 Chaos 实验。
此外 Chaos Mesh 还支持通过设置 Namespace Annotation 的方式开启特定 Namespace 下混沌实验的权限,进一步保障混沌实验的可控性。

View File

@ -0,0 +1,5 @@
---
title: 混沌工程理论
---
## TODO

View File

@ -0,0 +1,61 @@
---
title: chaosctl
---
chaosctl 是一个用于辅助调试 Chaos Mesh 的工具。我们希望利用 chaosctl 简化开发调试新 chaos 类型,以及提交 issue 相关日志的流程。
## 获取 chaosctl
我们为 Linux 提供了可执行文件。你可以直接下载 chaosctl
```bash
curl -sSL https://mirrors.chaos-mesh.org/latest/chaosctl
```
如果你使用 Windows 或 macOS可以自行从源代码编译。推荐使用 Go 1.15 以上版本进行编译。具体步骤如下:
1. 将 Chaos Mesh 克隆至本地
```bash
git clone https://github.com/chaos-mesh/chaos-mesh.git
```
2. 切换至 Chaos Mesh 目录下
3. 执行
```bash
make chaosctl
```
编译得到的可执行文件位于 `bin/chaosctl`
## 功能介绍
chaosctl 有两类功能,分别是查看日志及调试 Chaos。
### 日志查看
使用 `chaosctl logs` 可以查看所有 Chaos Mesh 组件的日志。`chaosctl logs -h` 会提供关于此功能的帮助和例子。命令示例如下:
```bash
chaosctl logs -t 100 # 输出所有组件的最后100行日志
```
### 调试 Chaos
使用 `chaosctl debug` 可以查看 Chaos 的调试信息。`chaosctl debug -h` 会提供关于此功能的帮助和例子。使用这一功能时chaosctl 需要与相应的 chaos-daemon 建立连接,如果你在部署 Chaos Mesh 时关闭了 TLS (默认打开),需要使用 `-i` 选项来告知 chaosctl 不使用 TLS。命令示例如下
```bash
./chaosctl debug -i networkchaos web-show-network-delay
```
目前chaosctl 只支持 iochaos, networkchaos, stresschaos 三类 Chaos 的调试。
## 使用场景
如果你希望提交关于 Chaos Mesh 的问题,在问题中附上相关的日志与 chaos 信息很有帮助。你可以将 `chaosctl logs` 的输出附在 issue 尾部以供开发人员参考。如果你希望提交的问题与 iochaos, networkchaos, stresschaos 有关,那么 `chaosctl debug` 的相关信息也会很有用。
## 开发与改进
chaosctl 的代码目前托管于 Chaos Mesh 项目中,你可以在 [chaos-mesh/pkg/chaosctl](https://github.com/chaos-mesh/chaos-mesh/tree/master/pkg/chaosctl) 找到相关实现。如果你有兴趣帮助我们改进这一工具,可以通过 [Slack](https://cloud-native.slack.com/archives/C0193VAV272) 联系我们,或是在 Chaos Mesh 项目中提出相关 issue 。

View File

@ -0,0 +1,70 @@
---
title: Chaosd 组件简介
---
## Chaosd 组件简介
[Chaosd](https://github.com/chaos-mesh/chaosd) 是 Chaos Mesh 提供的一款混沌工程测试工具(需要单独[下载和部署](#下载和部署)),用于在物理机环境上注入故障,并提供故障恢复功能。
Chaosd 具有以下核心优势:
- 易用性强:输入简单的 Chaosd 命令即可创建混沌实验,并对实验进行管理。
- 故障类型丰富:在物理机的不同层次、不同类型上都提供了故障注入的功能,包括进程、网络、压力、磁盘、主机等,且更多的功能在不断扩展中。
- 支持多种模式Chaosd 既可作为命令行工具使用,也可以作为服务使用,满足不同场景的使用需求。
### 支持故障类型
你可以使用 Chaosd 模拟以下故障类型:
- 进程:对进程进行故障注入,支持进程的 kill、stop 等操作。
- 网络:对物理机的网络进行故障注入,支持增加网络延迟、丢包、损坏包等操作。
- 压力:对物理机的 CPU 或内存注入压力。
- 磁盘:对物理机的磁盘进行故障注入,支持增加读写磁盘负载、填充磁盘等操作。
- 主机:对物理机本身进行故障注入,支持关机等操作。
对于每种故障类型的详细介绍和使用方式,请参考对应的说明文档。
### 运行环境
Linux 系统内核必须为 2.17 及以上版本。
### 下载和部署
1. 将要下载的 Chaosd 版本设置为环境变量,例如 v1.0.0
```bash
export CHAOSD_VERSION=v1.0.0
```
如果要查看所有已发布的 Chaosd 版本,请参阅 [releases](https://github.com/chaos-mesh/chaosd/releases) 。
如果要下载最新的非稳定版本,则使用 `latest`
```bash
export CHAOSD_VERSION=latest
```
2. 下载 Chaosd
```bash
curl -fsSL -o chaosd-$CHAOSD_VERSION-linux-amd64.tar.gz https://mirrors.chaos-mesh.org/chaosd-$CHAOSD_VERSION-linux-amd64.tar.gz
```
3. 解压 Chaosd 文件并转移到 /usr/local 目录下:
```bash
tar zxvf chaosd-$CHAOSD_VERSION-linux-amd64.tar.gz && sudo mv chaosd-$CHAOSD_VERSION-linux-amd64 /usr/local/
```
4. 将 Chaosd 目录加到环境变量 `PATH` 中:
```bash
export PATH=/usr/local/chaosd-$CHAOSD_VERSION-linux-amd64:$PATH
```
### 运行模式
你可以通过以下模式使用 Chaosd
- 命令行模式:将 Chaosd 作为命令行工具,直接运行即可注入故障、恢复故障。
- 服务模式:将 Chaosd 作为服务运行在后台,通过发送 HTTP 请求来注入故障、恢复故障。

View File

@ -0,0 +1,125 @@
---
title: 查找和恢复 Chaosd 实验
summary: 本文档介绍了查找和恢复 Chaosd 实验的操作方法,并提供了示例。
---
Chaosd 支持按照条件搜索实验,以及恢复指定的 uid 对应的实验。本文档介绍了查找和恢复 Chaosd 实验的操作方法,并提供了示例。
## 查找 Chaosd 实验
本章节介绍了如何使用命令行模式和服务模式查找 Chaosd 实验。
### 使用命令行模式查找实验
运行以下命令可查看搜索实验支持的配置:
```bash
chaosd search --help
Search chaos attack, you can search attacks through the uid or the state of the attack
Usage:
chaosd search UID [flags]
Flags:
-A, --all list all chaos attacks
--asc order by CreateTime, default value is false that means order by CreateTime desc
-h, --help help for search
-k, --kind string attack kind, supported value: network, process, stress, disk, host, jvm
-l, --limit uint32 limit the count of attacks
-o, --offset uint32 starting to search attacks from offset
-s, --status string attack status, supported value: created, success, error, destroyed, revoked
Global Flags:
--log-level string the log level of chaosd, the value can be 'debug', 'info', 'warn' and 'error'
```
#### 参数说明
| 配置项 | 配置缩写 | 说明 | 值 |
| :-- | :-- | :-- | :-- |
| all | A | 列出所有的实验 | bool 类型 |
| asc | 无 | 按照创建时间的升序对实验进行排列,默认为 false | bool 类型 |
| kind | k | 列出指定类型的实验 | string 类型支持的类型包括network、process、stress、 disk、host、jvm |
| limit | l | 列出实验的数量 | int 类型 |
| offset | o | 从指定的偏移量开始搜索 | int 类型 |
| status s | 列出指定状态的实验 | string 类型支持的状态包括created、success、error、destroyed、revoked |
#### 示例
```bash
./chaosd search --kind network --status destroyed --limit 1
```
该命令查找 `network` 类型且状态为 `destroyed`(表示实验已恢复)的实验,只输出一行数据,输出如下所示:
```bash
UID KIND ACTION STATUS CREATE TIME CONFIGURATION
--------------------------------------- --------- -------- ----------- --------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1f6c1253-522a-43d9-83f8-42607102b3b9 network delay destroyed 2021-11-02T15:14:07+08:00 {"schedule":"","duration":"","action":"delay","kind":"network","uid":"1f6c1253-522a-43d9-83f8-42607102b3b9","latency":"2s","jitter":"0ms","correlation":"0","device":"eth0","ip-address":"220.181.38.251","ip-protocol":"all"}
```
### 使用服务模式查找实验
服务模式目前只支持查找出所有的实验,访问 Chaosd 服务的 /api/experiments/ 路径获取数据。
#### 示例
```bash
curl -X GET 127.0.0.1:31767/api/experiments/
```
输出如下所示:
```bash
[{"id":1,"uid":"ddc5ca81-b677-4595-b691-0ce57bedb156","created_at":"2021-10-18T16:01:18.563542491+08:00","updated_at":"2021-10-18T16:07:27.87111393+08:00","status":"success","kind":"stress","action":"mem","recover_command":"{\"schedule\":\"\",\"duration\":\"\",\"action\":\"mem\",\"kind\":\"stress\",\"uid\":\"ddc5ca81-b677-4595-b691-0ce57bedb156\",\"Load\":0,\"Workers\":0,\"Size\":\"100MB\",\"Options\":null,\"StressngPid\":0}","launch_mode":"svr"}]
```
## 恢复 Chaosd 实验
在创建完实验后,如果想撤销实验造成的影响,可以使用实验的恢复功能。
### 使用命令行模式恢复实验
使用 Chaosd recover UID 的方式恢复实验。
以下为通过命令行模式恢复实验示例。使用 Chaosd 创建一个 CPU 压力的实验:
```bash
chaosd attack stress cpu --workers 2 --load 10
```
输出如下所示:
```bash
[2021/05/12 03:38:33.698 +00:00] [INFO] [stress.go:66] ["stressors normalize"] [arguments=" --cpu 2 --cpu-load 10"]
[2021/05/12 03:38:33.702 +00:00] [INFO] [stress.go:82] ["Start stress-ng process successfully"] [command="/usr/bin/stress-ng --cpu 2 --cpu-load 10"] [Pid=27483]
Attack stress cpu successfully, uid: 4f33b2d4-aee6-43ca-9c43-0f12867e5c9c
```
可以在输出中看到实验的 UID 信息,请注意保存。在不需要模拟 CPU 压力场景时,使用 `recover` 命令来恢复 uid 对应的实验:
```bash
chaosd recover 4f33b2d4-aee6-43ca-9c43-0f12867e5c9c
```
### 使用服务模式恢复实验
你可以通过向 Chaosd 服务的 /api/attack/{uid} 路径发送 DELETE HTTP 请求来恢复实验。
以下为通过服务模式恢复实验示例。向 Chaosd 服务发送 HTTP POST 请求创建一个 CPU 压力实验:
```bash
curl -X POST 172.16.112.130:31767/api/attack/stress -H "Content-Type:application/json" -d '{"load":10, "action":"cpu","workers":1}'
```
输出如下所示:
```bash
{"status":200,"message":"attack successfully","uid":"c3c519bf-819a-4a7b-97fb-e3d0814481fa"}
```
可以在输出中看到实验的 UID 信息,请注意保存。在不需要模拟 CPU 压力场景时,运行以下命令来结束 UID 对应的实验:
```bash
curl -X DELETE 172.16.112.130:31767/api/attack/c3c519bf-819a-4a7b-97fb-e3d0814481fa
```

View File

@ -0,0 +1,31 @@
---
title: 检查 Workflow 状态
---
<!-- ## 通过 Chaos Dashboard 检查 Workflow 状态 -->
<!-- TODO: 待 Chaos Dashboard 完善后补充这一部分 -->
## 通过 `kubectl` 检查 Workflow 状态
1. 执行以下命令来获取指定命名空间中已经创建的 Workflow
```shell
kubectl -n <namespace> get workflow
```
2. 根据上一步输出的 Workflow 列表,选择想查看的 Workflow 并在以下命令中指定其名称。执行命令以获取该 Workflow 下的所有 WorkflowNode
```shell
kubectl -n <namespace> get workflownode --selector="chaos-mesh.org/workflow=<workflow-name>"
```
Workflow 在执行过程中的步骤会以 WorkflowNode 这一 CustomResource 来表示。
3. 执行以下命令来获取指定 WorkflowNode 的详细状态:
```shell
kubectl -n <namespace> describe workflownode <workflow-node-name>
```
输出内容包括当前节点是否执行完成、并行/串行节点的执行状态、对应的 Chaos 实验对象等。

View File

@ -0,0 +1,3 @@
验证安装完成后,你可以运行一个 Chaos 实验来体验 Chaos Mesh 的功能。
请参考[运行试验](run-a-chaos-experiment.md)进行创建。成功创建实验后,你可以通过 Chaos Dashboard 观察实验的运行状态。

View File

@ -0,0 +1,40 @@
要查看 Chaos Mesh 的运行情况,请执行以下命令:
```bash
kubectl get po -n chaos-testing
```
以下是预期输出:
```bash
NAME READY STATUS RESTARTS AGE
chaos-controller-manager-69fd5c46c8-xlqpc 3/3 Running 0 2d5h
chaos-daemon-jb8xh 1/1 Running 0 2d5h
chaos-dashboard-98c4c5f97-tx5ds 1/1 Running 0 2d5h
```
如果你的实际输出与预期输出相符,表示 Chaos Mesh 已经成功安装。
:::note 注意
如果实际输出的 `STATUS` 状态不是 `Running`,则需要运行以下命令查看 Pod 的详细信息,然后依据错误提示排查并解决问题。
```bash
# 以 chaos-controller 为例
kubectl describe po -n chaos-testing chaos-controller-manager-69fd5c46c8-xlqpc
```
:::
:::note 注意
如果手动关闭了 `leader-election``chaos-controller-manager` 应该只有 1 个实例。
```sh
NAME READY STATUS RESTARTS AGE
chaos-controller-manager-69fd5c46c8-xlqpc 1/1 Running 0 2d5h
chaos-daemon-jb8xh 1/1 Running 0 2d5h
chaos-dashboard-98c4c5f97-tx5ds 1/1 Running 0 2d5h
```
:::

View File

@ -0,0 +1,87 @@
---
title: 配置开发环境
---
本文档介绍如何搭建 Chaos Mesh 的开发环境。
## 环境要求
安装 Chaos Mesh 所需的开发工具。
- [golang](https://golang.org/dl/) 版本不低于 v1.15
- [docker](https://www.docker.com/)
- [gcc](https://gcc.gnu.org/)
- [helm](https://helm.sh/) 版本不低于 v2.8.2
- [kind](https://github.com/kubernetes-sigs/kind)
- [nodejs](https://nodejs.org/en/) 和 [yarn](https://yarnpkg.com/lang/en/) (以开发 Chaos Dashboard)
## 准备工具链
准备好上述环境后,请按照以下步骤配置用于编译 Chaos Mesh 的工具链。
1. 将 Chaos Mesh 项目克隆至本地。
```bash
git clone https://github.com/chaos-mesh/chaos-mesh.git
cd chaos-mesh
```
2. 确保你的环境中已经安装 [Docker](https://docs.docker.com/install/) 并且正在运行 Docker。
3. 确保 [Docker Registry](https://docs.docker.com/registry/) 正在运行。将环境变量 `DOCKER_REGISTRY` 设置为其地址:
```bash
echo 'export DOCKER_REGISTRY=localhost:5000' >> ~/.bash_profile
source ~/.bash_profile
```
4. 确保 `${GOPATH}/bin` 在你的 `PATH` 环境变量中。
```bash
echo 'export PATH=$(go env GOPATH)/bin:${PATH}' >> ~/.bash_profile
```
```bash
source ~/.bash_profile
```
5. 检查 Nodejs 相关环境。
```bash
node -v
yarn -v
```
6. 尝试编译 Chaos Mesh
```bash
make
```
如果没有报错,那么工具链已经配置完毕。
## 准备部署环境
在工具链准备完之后,你还需要启动一个本地的 Kubernetes 集群用于部署 Chaos Mesh。由于 kind 已经安装好了,你可以直接使用以下脚本启动一个 Kubernetes 集群:
```bash
hack/kind-cluster-build.sh
```
当你不再需要此集群,希望删除它时,可以使用:
```bash
kind delete cluster --name=kind
```
如需启动 Chaos Dashboard请运行以下命令
```bash
cd ui && yarn
# 启动
yarn start:default # cross-env REACT_APP_API_URL=http://localhost:2333 BROWSER=none react-scripts start
```
## 下一步
在完成上述 Chaos Mesh 开发的准备工作后,请尝试[新增混沌实验类型](add-new-chaos-experiment-type.md)。

View File

@ -0,0 +1,78 @@
---
title: 配置允许混沌实验的命名空间
---
本篇文章描述如何配置混沌实验只在指定的命名空间内生效,其他未配置的命令空间则会受到保护不会被故障注入。
## 控制混沌实验生效的范围
Chaos Mesh 提供了以下两种方式用于控制混沌实验生效的范围:
- 要配置混沌实验只在指定的命名空间内生效,你需要开启 FilterNamespace 功能(默认关闭),此功能将在全局范围内生效。开启此功能后,你可以为允许混沌实验的命名空间添加注解,其他未添加注解的命名空间则会受到保护不会被注入故障。
- 要为单个混沌实验指定实验生效的范围,请参考[定义实验范围](define-chaos-experiment-scope.md)。
## 开启 FilterNamespace 功能
如果你尚未安装 Chaos Mesh在使用 Helm 进行安装时,可以在安装命令中添加 `--set controllerManager.enableFilterNamespace=true` 来开启这项功能。Docker 容器的命令示例如下:
```bash
helm install chaos-mesh chaos-mesh/chaos-mesh -n chaos-testing --set controllerManager.enableFilterNamespace=true
```
:::note 注意
当使用 Helm 进行安装时,不同容器运行时的命令和参数有所区别,详情请参阅[使用 Helm 安装](production-installation-using-helm.md)。
:::
如果已经通过 Helm 安装了 Chaos Mesh ,可以通过 `helm upgrade` 命令来更新配置。示例如下:
```bash
helm upgrade chaos-mesh chaos-mesh/chaos-mesh -n chaos-testing --set controllerManager.enableFilterNamespace=true
```
`helm upgrade` 中可以通过设置多个 `--set` 参数来设置多个参数,覆盖规则是后设置的覆盖前设置的。比如 `--set controllerManager.enableFilterNamespace=false --set controllerManager.enableFilterNamespace=true` 仍将开启这项功能。
也可以通过 `-f` 参数来指定一个 YAML 文件用于描述配置,详细请参考 [Helm 升级文档](https://helm.sh/zh/docs/helm/helm_upgrade/#%E7%AE%80%E4%BB%8B)。
## 为允许混沌实验的命名空间添加注解
在开启 FilterNamespace 功能后Chaos Mesh 将只会向包含有 `chaos-mesh.org/inject=enabled` 注解的命名空间注入故障。因此,在进行混沌实验之前,你需要为允许混沌实验的命名空间添加该注解,其他命名空间则受到保护不会被注入故障。
可以通过如下 `kubectl` 命令为一个 `namespace` 添加注解:
```bash
kubectl annotate ns $NAMESPACE chaos-mesh.org/inject=enabled
```
其中 `$NAMESPACE` 为命名空间的名字,比如 `default`。如果成功,得到输出如下:
```bash
namespace/$NAMESPACE annotated
```
如果希望删除这一注解,则可以通过以下命令:
```bash
kubectl annotate ns $NAMESPACE chaos-mesh.org/inject-
```
如果成功,得到输出如下:
```bash
namespace/$NAMESPACE annotated
```
## 查看所有允许混沌实验的命名空间
你可以使用以下命令列出所有允许混沌实验的命名空间:
```bash
kubectl get ns -o jsonpath='{.items[?(@.metadata.annotations.chaos-mesh\.org/inject=="enabled")].metadata.name}'
```
此命令将会输出所有包含 `chaos-mesh.org/inject=enabled` 注解的命名空间。示例输出如下:
```bash
default
```

View File

@ -0,0 +1,201 @@
---
title: 创建 Chaos Mesh Workflow
---
## Chaos Mesh Workflow 简介
在 Chaos Mesh 中模拟真实的系统故障时,通常伴随着持续验证。你可能希望在 Chaos Mesh 平台上构建一系列故障,而不是执行单个独立的混沌故障注入操作。
为满足该需求Chaos Mesh 提供了 Chaos Mesh Workflow一个内置的工作流引擎。使用该引擎你可以串行或并行地执行多种不同的 Chaos 实验, 用于模拟生产级别的错误。
目前, Chaos Mesh Workflow 支持以下功能:
- 串行编排
- 并行编排
- 自定义任务
- 条件分支
使用场景举例:
- 使用并行编排同时注入多个 NetworkChaos 模拟复杂的网络环境
- 在串行编排中进行健康检查,使用条件分支决定是否执行剩下的步骤
Chaos Mesh Workflow 在设计时一定程度上参考了 Argo Workflow。如果您熟悉 Argo Workflow 您也能很快地上手 Chaos Mesh Workflow。
Github 仓库中含有其他 Workflow 的[示例](https://github.com/chaos-mesh/chaos-mesh/tree/master/examples/workflow).
## 使用 YAML 文件与 `kubectl` 创建 Workflow
Workflow 类似于各种类型的 Chaos 对象,同样作为 CRD 存在于 kubernetes 集群中。你可以使用 `kubectl create -f <workflow.yaml>` 创建 Chaos Mesh Workflow。以下为创建的具体示例。使用本地 YAML 文件创建 Workflow
```shell
kubectl create -f <workflow.yaml>
```
使用网络上的 YAML 文件创建 Workflow
```shell
kubectl create -f https://raw.githubusercontent.com/chaos-mesh/chaos-mesh/master/examples/workflow/serial.yaml
```
一个简单的 Workflow YAML 文件定义如下所示,这个 Workflow 将会同时注入 `StressChaos`、`NetworkChaos` 与 `PodChaos`
```yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: Workflow
metadata:
name: try-workflow-parallel
spec:
entry: the-entry
templates:
- name: the-entry
templateType: Parallel
deadline: 240s
children:
- workflow-stress-chaos
- workflow-network-chaos
- workflow-pod-chaos
- name: workflow-network-chaos
templateType: NetworkChaos
deadline: 20s
networkChaos:
direction: to
action: delay
mode: all
selector:
labelSelectors:
"app": "hello-kubernetes"
delay:
latency: "90ms"
correlation: "25"
jitter: "90ms"
- name: workflow-pod-chaos-schedule
templateType: Schedule
deadline: 40s
schedule:
schedule: "@every 2s"
podChaos:
action: pod-kill
mode: one
selector:
labelSelectors:
"app": "hello-kubernetes"
- name: workflow-stress-chaos
templateType: StressChaos
deadline: 20s
stressChaos:
mode: one
selector:
labelSelectors:
"app": "hello-kubernetes"
stressors:
cpu:
workers: 1
load: 20
options: ["--cpu 1" "--timeout 600"]
```
其中 `templates` 定义了实验中的各个步骤,`entry` 定义了 Workflow 执行时的入口。
`templates` 中的每个元素都代表了一个 Workflow 的步骤,例如:
```yaml
name: the-entry
templateType: Parallel
deadline: 240s
children:
- workflow-stress-chaos
- workflow-network-chaos
- workflow-pod-chaos
```
`templateType: Parallel` 代表节点的类型为并行;`deadline: 240s` 代表这个节点下的所有并行实验预期在 240 秒内执行完成,否则将超时;`children` 代表将要并行执行的其他 template 名称。
再例如:
```yaml
name: workflow-pod-chaos
templateType: PodChaos
deadline: 40s
podChaos:
action: pod-kill
mode: one
selector:
labelSelectors:
'app': 'hello-kubernetes'
```
`templateType: PodChaos` 代表节点的类型为 PodChaos 实验;`deadline: 40s` 代表当前 Chaos 实验将持续 40 秒;`podChaos` 字段是 PodChaos 实验的定义。
通过 YAML 文件与 `kubectl` 创建 Workflow 较为灵活,你可以对串行活并行编排进行嵌套,声明复杂的编排,甚至可以与条件分支组合达到循环的效果。
## 字段说明
### Workflow 字段说明
| 参数 | 类型 | 说明 | 默认值 | 是否必填 | 示例 |
| --- | --- | --- | --- | --- | --- |
| entry | string | 声明 Workflow 的入口,值为 templates 中某一 template 的名称。 | 无 | 是 | |
| templates | []Template | 声明 Workflow 中可执行的各个步骤的行为,详见 [Template 字段说明](#template-字段说明) | 无 | 是 | |
### Template 字段说明
| 参数 | 类型 | 说明 | 默认值 | 是否必填 | 示例 |
| --- | --- | --- | --- | --- | --- |
| name | string | template 的名称,需要符合 DNS-1123 命名规范。 | 无 | 是 | any-name |
| type | string | template 的类型。可选值有: Task、Serial、Parallel、Suspend、Schedule、AWSChaos、DNSChaos、GCPChaos、HTTPChaos、IOChaos、JVMChaos、KernelChaos、NetworkChaos、PodChaos、StressChaos、TimeChaos | 无 | 是 | PodChaos |
| deadline | string | template 持续的时间。 | 无 | 否 | '5m30s' |
| children | []string | 声明该 template 下的子任务,当 type 为 Serial 或 Parallel 时需要配置该字段。 | 无 | 否 | ["any-chaos-1", "another-serial-2", "any-shcedule"] |
| task | Task | 配置自定义任务,当 type 为 Task 时需要配置该字段。详见 [Task 字段说明](#task-字段说明) | 无 | 否 | |
| conditionalBranches | []ConditionalBranch | 配置自定任务后的条件分支,当 type 为 Task 时可选配置该字段。详见 [ConditionalBranch 字段说明](#conditionalBranch-字段说明) | 无 | 否 | |
| awsChaos | object | 配置 AWSChaos当 type 为 AWSChaos 时需要配置该字段。详见 [模拟 AWS 故障](simulate-aws-chaos.md) | 无 | 否 | |
| dnsChaos | object | 配置 DNSChaos当 type 为 DNSChaos 时需要配置该字段。详见 [模拟 DNS 故障](simulate-dns-chaos-on-kubernetes.md) | 无 | 否 | |
| gcpChaos | object | 配置 GCPChaos当 type 为 GCPChaos当 时需要配置该字段。详见 [模拟 GCP 故障](simulate-gcp-chaos.md) | 无 | 否 | |
| httpChaos | object | 配置 HTTPChaos当 type 为 HTTPChaos 时需要配置该字段。详见 [模拟 HTTP 故障](simulate-http-chaos-on-kubernetes.md) | 无 | 否 | |
| ioChaos | object | 配置 IOChaos当 type 为 IOChaos 时需要配置该字段。详见 [模拟文件 I/O 故障](simulate-io-chaos-on-kubernetes.md) | 无 | 否 | |
| jvmChaos | object | 配置 JVMChaos当 type 为 JVMChaos 时需要配置该字段。详见 [模拟 JVM 应用故障](simulate-jvm-application-chaos.md) | 无 | 否 | |
| kernelChaos | object | 配置 KernelChaos当 type 为 KernelChaos 时需要配置该字段。详见 [模拟内核故障](simulate-kernel-chaos-on-kubernetes.md) | 无 | 否 | |
| networkChaos | object | 配置 NetworkChaos当 type 为 NetworkChaos 时需要配置该字段。详见 [模拟 AWS 故障](simulate-aws-chaos.md) | 无 | 否 | |
| podChaos | object | 配置 PodChaosd ,当 type 为 PodChaosd 时需要配置该字段。详见 [模拟网络故障](simulate-network-chaos-on-kubernetes.md) | 无 | 否 | |
| stressChao | object | 配置 StressChaos当 type 为 StressChaos 时需要配置该字段。详见 [模拟压力场景](simulate-heavy-stress-on-kubernetes.md) | 无 | 否 | |
| timeChaos | object | 配置 TimeChaos当 type 为 TimeChaos 时需要配置该字段。详见 [模拟时间故障](simulate-time-chaos-on-kubernetes.md) | 无 | 否 | |
| schedule | object | 配置 Schedule ,当 type 为 Schedule 时需要配置该字段。详见 [定义调度规则](define-scheduling-rules.md) | 无 | 否 | |
:::note 注意
当在 Workflow 中建立有持续时间的 Chaos 时,需要将持续时间填写到外层的 `deadline` 字段中,而不是使用 Chaos 中的 `duration` 字段。
:::
### Task 字段说明
| 参数 | 类型 | 说明 | 默认值 | 是否必填 | 示例 |
| --- | --- | --- | --- | --- | --- |
| container | object | 定义自定义任务容器,可参考 [Container 字段说明](#container-字段说明) | 无 | 否 | |
| volumes | array | 若需要在自定义任务容器中挂载卷,则需要在该字段声明卷。关于完整定义可参考 [corev1.Volume](https://v1-17.docs.kubernetes.io/docs/reference/generated/kubernetes-api/v1.17/#volume-v1-core) | 无 | 否 | |
### ConditionalBranch 字段说明
| 参数 | 类型 | 说明 | 默认值 | 是否必填 | 示例 |
| --- | --- | --- | --- | --- | --- |
| target | string | 当前条件分支想要执行的 template 名称 | 无 | 是 | another-chaos |
| expression | string | 类型为布尔的表达式,在自定义任务完成后,当表达式值为真时,当前条件分支将会被执行。未设置该值时,条件分支将会在自定义任务完成后直接执行。 | 无 | 否 | exitCode == 0 |
目前在 `expression` 中提供了两个上下文变量:
- `exitCode` 表示自定义任务的退出码。
- `stdout` 表示自定义任务的标准输出。
> 更多的上下文变量将在后续补充。
可参考[该文档](https://github.com/antonmedv/expr/blob/master/docs/Language-Definition.md)编写 `expression` 表达式。
### Container 字段说明
这里只列举了常用字段,关于完整定义可参考 [corev1.Container](https://v1-17.docs.kubernetes.io/docs/reference/generated/kubernetes-api/v1.17/#container-v1-core)
| 参数 | 类型 | 说明 | 默认值 | 是否必填 | 示例 |
| ------- | -------- | -------------- | ------ | -------- | ------------------------------------------------- |
| name | string | 容器名称 | 无 | 是 | task |
| image | string | 镜像名称 | 无 | 是 | busybox:latest |
| command | []string | 容器执行的命令 | 无 | 否 | `["wget", "-q", "http://httpbin.org/status/201"]` |

View File

@ -0,0 +1,176 @@
---
title: 定义实验范围
---
本篇文档描述如何为单个混沌实验定义实验范围,帮助你准确地控制故障爆炸半径。
## 简介
在 Chaos Mesh 中,你可以通过指定选择器 (Selectors) 的方式定义单个混沌实验的作用范围。
不同类型的 Selector 对应着不同的过滤规则。你可以在一个混沌实验中指定一个或多个 Selector 来定义你的实验范围。如果同时指定多个 Selector代表当前实验目标需要同时满足所有指定的 Selectors 的规则。
在创建混沌实验时Chaos Mesh 支持以下两种定义混沌实验范围的方式。你可以按需选择以下任一方式:
- 在 YAML 配置文件中定义实验范围
- 在 Dashboard 上定义实验范围
## 在 YAML 配置文件中定义实验范围
本小节提供了不同类型的 Selectors 的含义、用法、在 YAML 文件中的配置示例。在 YAML 配置文件中定义实验范围时,你可以按照实验范围的过滤需求指定一个或多个 Selectors。
### Namespace Selectors
- 指定实验目标 Pod 所属的命名空间。
- 数据类型:字符串数组类型。
- 如果此 Selector 为空或者不指定此 SelectorChaos Mesh 会将其设置为当前混沌实验所属的命名空间。
当使用 YAML 文件创建实验时,示例配置如下:
```yaml
spec:
selector:
namespaces:
- 'app-ns'
```
### Label Selector
- 指定实验目标 Pod 需要带有的 [Labels](https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/)。
- 数据类型:键值对类型。
- 如果指定了多个 Labels代表实验目标需要带有此 Selector 指定的所有 Labels。
当使用 YAML 文件创建实验时,示例配置如下:
```yaml
spec:
selector:
labelSelectors:
'app.kubernetes.io/component': 'tikv'
```
### Expression Selector
- 指定一组定义 Label 规则的[表达式](https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#resources-that-support-set-based-requirements)用来限定实验目标 Pod。
- 你可以通过此 Selector 设置不满足某些 Labels 的实验目标 Pod。
当使用 YAML 文件创建实验时,示例配置如下:
```yaml
spec:
selector:
expressionSelectors:
- { key: tier, operator: In, values: [cache] }
- { key: environment, operator: NotIn, values: [dev] }
```
### Annotation Selector
- 指定实验目标 Pod 需要带有的 [Annotations](https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/)。
- 数据类型:键值对类型。
- 如果指定了多个 Annotations代表实验目标需要带有此 Selector 指定的所有 Annotations。
当使用 YAML 文件创建实验时,示例配置如下:
```yaml
spec:
selector:
annotationSelectors:
'example-annotation': 'group-a'
```
### Field Selector
- 指定实验目标 Pod 的 [Fields](https://kubernetes.io/docs/concepts/overview/working-with-objects/field-selectors/)。
- 数据类型:键值对类型。
- 如果指定了多个 Fields 字段,代表实验目标需要带有此 Selector 设置的所有 Fields。
当使用 YAML 文件创建实验时,示例配置如下:
```yaml
spec:
selector:
fieldSelectors:
'metadata.name': 'my-pod'
```
### PodPhase Selector
- 指定实验目标 Pod 的 Phase。
- 数据类型:字符串数组类型。
- 支持的 Phase 有Pending、Running、Succeeded、Failed、Unknown。
- 此选项默认为空,意味不限制目标 Pod 的 Phase。
当使用 YAML 文件创建实验时,示例配置如下:
```yaml
spec:
selector:
podPhaseSelectors:
- 'Running'
```
### Node Selector
- 指定实验目标 Pod 所属的 [Node 的 Labels](https://kubernetes.io/docs/tasks/configure-pod-container/assign-pods-nodes/)。
- 数据类型:键值对类型。
- 如果指定了多个 Node Labels代表实验目标 Pod 所属的 Node 需要带有此 Selector 指定的所有 Labels。
当用户通过 YAML 文件创建实验,配置如下:
```yaml
spec:
selector:
nodeSelectors:
'node-label': 'label-one'
```
### Node List
- 指定实验目标 Pod 所属的 Node。
- 数据类型: 字符串数组。
- 目标 Pod 只需属于配置的 Node 列表中的其中一个 Node 即可。
当使用 YAML 文件创建实验时,示例配置如下:
```yaml
spec:
selector:
nodes:
- node1
- node2
```
### Pod List
- 指定实验目标 Pod 命名空间和 Pod 列表。
- 数据类型:键值对类型。"键"为目标 Pod 所属的 Namespace, "值"为目标 Pod 列表。
- 只要指定了此 SelectorChaos Mesh 就会**忽略其他配置的 Selectors**。
当使用 YAML 文件创建实验时,示例配置如下:
```yaml
spec:
selector:
pods:
tidb-cluster: # namespace of the target pods
- basic-tidb-0
- basic-pd-0
- basic-tikv-0
- basic-tikv-1
```
## 在 Dashboard 上定义实验范围
如果使用 Chaos Dashboard 创建混沌实验,你可以在填写实验信息时配置混沌实验范围。
目前 Chaos Dashboard 上提供了以下 Selectors。可以按照实验范围的过滤需求指定一个或多个 Selectors
- 命名空间选择器 (`Namespace Selectors`)
- 标签选择器 (`Label Selectors`)
- 注解选择器 (`Annotation Selectors`)
- 阶段选择器 (`Phase Selectors`)。
在设置 Selectors 的同时,你也可以在 Dashboard 中实时预览实验目标的实际范围,并且可以直接修改 Selectors 过滤出的目标 Pod 范围。
![Dashboard Selectors](img/dashboard_selectors_zh.png)

View File

@ -0,0 +1,223 @@
---
title: 定义调度规则
---
## Schedule 简介
本文档主要介绍如何在 Chaos Mesh 中创建定时任务,从而在固定的时间(或根据固定的时间间隔)自动新建混沌实验。
在 Kubernetes 中Chaos Mesh 使用 `Schedule` 对象来描述定时任务。
:::note 注意
一个 `Schedule` 对象名不应超过 57 字符,因为它创建的混沌实验将在名字后额外添加 6 位随机字符。一个包含有 `Workflow``Schedule` 对象名不应超过 51 字符,因为 Workflow 也将在创建的名字后额外添加 6 位随机字符。
:::
## 使用 YAML 文件与 `kubectl` 创建 Schedule 调度规则
以在每个小时的第 5 分钟持续 12 秒施加 100 毫秒延迟为例:
```yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: Schedule
metadata:
name: schedule-delay-example
spec:
schedule: '5 * * * *'
historyLimit: 2
concurrencyPolicy: 'Allow'
type: 'NetworkChaos'
networkChaos:
action: delay
mode: one
selector:
namespaces:
- default
labelSelectors:
'app': 'web-show'
delay:
latency: '10ms'
correlation: '100'
jitter: '0ms'
duration: '12s'
```
将此 YAML 文件保存至 `schedule-networkchaos.yaml`,运行 `kubectl apply -f ./schedule-networkchaos.yaml` 即可。
依据此配置Chaos Mesh 将会在每个小时的第五分钟(比如 0:05, 1:05...)创建以下 `NetworkChaos` 对象:
```yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: NetworkChaos
metadata:
name: schedule-delay-example-xxxxx
spec:
action: delay
mode: one
selector:
namespaces:
- default
labelSelectors:
'app': 'web-show'
delay:
latency: '10ms'
correlation: '100'
jitter: '0ms'
duration: '12s'
```
在后文中会对 `Schedule` 中的字段进行描述,大多与 Kubernetes `CronJob` 的字段等价。可以参考 Kubernetes CronJob 的[文档](https://kubernetes.io/zh/docs/concepts/workloads/controllers/cron-jobs/)。
:::note 注意
`Schedule``schedule` 字段对应的时区以 `chaos-controller-manager` 的时区为准。
:::
### `schedule` 字段
`schedule` 字段用于指定实验发生的时间。
```
# ┌───────────── 分钟 (0 - 59)
# │ ┌───────────── 小时 (0 - 23)
# │ │ ┌───────────── 月的某天 (1 - 31)
# │ │ │ ┌───────────── 月份 (1 - 12)
# │ │ │ │ ┌───────────── 周的某天 (0 - 6) 周日到周一在某些系统上7 也是星期日)
# │ │ │ │ │
# │ │ │ │ │
# │ │ │ │ │
# * * * * *
```
| 输入 | 描述 | 等效替代 |
| ---------------------- | ---------------------------- | ------------- |
| @yearly (or @annually) | 每年 1 月 1 日的午夜运行一次 | 0 0 1 1 \* |
| @monthly | 每月第一天的午夜运行一次 | 0 0 1 \* \* |
| @weekly | 每周的周日午夜运行一次 | 0 0 \* \* 0 |
| @daily (or @midnight) | 每天午夜运行一次 | 0 0 \* \* \* |
| @hourly | 每小时的开始一次 | 0 \* \* \* \* |
如果想要生成时间表达式,你还可以使用 [crontab.guru](https://crontab.guru) 等 Web 工具。
### `historyLimit` 字段
一项实验在结束之后并不会被删除,这是为了方便用户检索和观察实验结果,在出错时能够排查。在 `historyLimit` 中设定的数值为保留的任务数这一数量包括了正在运行中的任务。当然Chaos Mesh 并不会删除正在运行中的任务。
当存在超过 `historyLimit` 数量的任务时Chaos Mesh 将会按照顺序依次删除最早创建的任务。如果那些任务还在继续,则会跳过。
### `concurrencyPolicy` 字段
该字段所有可用的值为 `"Forbid"`、`"Allow"`、`""`。
该字段用于指定是否允许该 `Schedule` 对象创建多个同时运行的实验。比如 `schedule: * * * * *` 配置下,每分钟创建一个实验对象,而如果实验对象的 `duration` 配置为 70 秒,则会出现多个实验同时发生的情况。
`concurrencyPolicy` 字段默认为 `Forbid`,即不允许多个实验同时发生。当 `concurrencyPolicy` 字段为 `Allow` 时,将允许多个实验同时发生。
在以下配置的基础上,仍以延迟为例:
```yaml
spec:
schedule: '* * * * *'
type: 'NetworkChaos'
networkChaos:
action: delay
mode: one
selector:
namespaces:
- default
labelSelectors:
'app': 'web-show'
delay:
latency: '10ms'
duration: '70s'
```
如果设置 `concurrencyPolicy: "Allow"`,则表现为在每分钟中存在 10 秒有 20 毫秒的延迟,而其他 50 秒将存在 10 毫秒的延迟;如果设置 `concurrencyPolicy: "Forbid"`,则表现为一直有 10 毫秒的延迟。
:::note 注意
并非所有实验类型均支持多个实验对同一 Pod 生效。详见各实验类型的文档。
:::
### `startingDeadlineSeconds` 字段
`startingDeadlineSeconds` 默认值为 0。
`startingDeadlineSeconds` 为 0 时Chaos Mesh 将检查从上一次调度发生到当前时间为止,期间是否有错过的实验(这种情况在用户关闭 Chaos Mesh、长期暂停 Schedule、设置 `concurrencyPolicy``Forbid` 时可能发生)。
`startingDeadlineSeconds` 的值大于 0 时Chaos Mesh 将检查从当前时间开始,过去的 `startingDeadlineSeconds` 秒内是否有错过的实验。如果 `startingDeadlineSeconds` 的值过小可能会错过一些实验,以下给出一个例子:
```yaml
spec:
schedule: '* * * * *'
type: 'NetworkChaos'
networkChaos:
action: delay
mode: one
selector:
namespaces:
- default
labelSelectors:
'app': 'web-show'
startingDeadlineSeconds: 5
delay:
latency: '10ms'
duration: '70s'
```
由于 `concurrencyPolicy``Forbid`,在分钟的开始会因为这一限制而禁止创建新任务。而在该分钟的第十秒,上一次创建的 Chaos 运行结束,但由于 `startingDeadlineSeconds` 的限制不会检索到因 `concurrencyPolicy` 而错过的事件,所以不会创建 Chaos。在下一分钟开始时才会创建新的 Chaos。
而如果不设置 `startingDeadlineSeconds` (或设置为 0则表现为一直有 10 毫秒的延迟。这是因为在运行着的任务结束之后Chaos Mesh 发现一段时间前错过了一个任务(因为 `concurrencyPolicy` 的阻止),于是立即创建了新的任务。
这一字段在 Kubernetes CronJob 的[文档](https://kubernetes.io/zh/docs/concepts/workloads/controllers/cron-jobs/#cron-job-limitations)中拥有其他例子与类似解释。
### 定义实验
`Schedule` 中需要使用两个字段来定义实验的具体内容。`type` 字段和 `*Chaos` 字段。其中 `type` 字段用于指定实验类型,`*Chaos` 字段用于描述实验内容。通常来说,`type` 字段的内容为大驼峰,例如 `NetworkChaos`、`PodChaos`、`IOChaos`;而 `*Chaos` 的键为与之对应的小驼峰,如 `networkChaos`, `podChaos`, `ioChaos`。`*Chaos` 的键为对应实验类型的 `spec`,详见个实验类型的文档。
## 使用 Dashboard 创建 Schedule 调度规则
1. 单击计划页面中的“新的计划”按钮创建计划:
![创建计划](./img/create-new-schedule.png)
2. 选择并填写实验的具体内容
![选择并填写内容](./img/define-schedule-inner-resource.png)
3. 填写计划周期、并发策略等信息
![填写计划规则](./img/define-schedule-spec.png)
4. 提交实验
### 暂停定时任务
`CronJob` 不同,暂停一个 `Schedule` 不仅仅会阻止它创建新的实验,也会暂停已创建的实验。
如果你暂时不想再通过定时任务来创建混沌实验,需要为该 `Schedule` 对象添加 `experiment.chaos-mesh.org/pause=true` 注解。可以使用 `kubectl` 命令行工具添加注解:
```bash
kubectl annotate -n $NAMESPACE schedule $NAME experiment.chaos-mesh.org/pause=true
```
其中 `$NAMESPACE` 为命名空间,`$NAME` 为 `Schedule` 的名字。返回成功的结果如下:
```bash
schedule/$NAME annotated
```
如果要解除暂停,可以使用如下命令去除该注解:
```bash
kubectl annotate -n $NAMESPACE schedule $NAME experiment.chaos-mesh.org/pause-
```
其中 `$NAMESPACE` 为命名空间,`$NAME` 为 `Schedule` 的名字。成功返回如下:
```bash
schedule/$NAME annotated
```

View File

@ -0,0 +1,13 @@
---
title: 开发指南概览
---
本文档介绍如何开发 Chaos Mesh。在开始之前推荐阅读以下材料以熟悉整个项目
- [Chaos Mesh README](https://github.com/chaos-mesh/chaos-mesh/blob/master/README.md)
- [Chaos Mesh Dashboard README](https://github.com/chaos-mesh/chaos-mesh/blob/master/ui/README.md)
先从 [配置开发环境](configure-development-environment.md) 开始,之后你可以依次尝试:
- [新增混沌实验类型](add-new-chaos-experiment-type.md)
- [拓展 Chaos Daemon 接口](extend-chaos-daemon-interface.md)

View File

@ -0,0 +1,275 @@
---
title: 拓展 Chaos Daemon 接口
---
在[新增混沌实验类型](add-new-chaos-experiment-type.md)中,你实现了一种名为 HelloWorldChaos 的混沌实验,它的功能是在 Chaos Controller Manager 的日志中输出一行 "Hello world!"。为了让 HelloWorldChaos 真正有用,你还需要向 Chaos Daemon 添加接口,从而在目标 Pod 上注入一些故障。比方说,获取目标 Pod 中正在运行的进程信息。
:::note 注意一些关于 Chaos Mesh 架构的知识对于帮助你理解这一文档非常有用,例如 [Chaos Mesh  架构](architecture.md)。 :::
本文档分为以下几部分:
- [选择器](#选择器)
- [实现 gRPC 接口](#实现-grpc-接口)
- [验证实验效果](#验证实验效果)
- [探索更多](#探索更多)
## 选择器
回顾一下你在 `api/v1alpha1/helloworldchaos_type.go` 中定义的 `HelloWorldSpec` 这一结构,其中包括了一项 `ContainerSelector`
```go
// HelloWorldChaosSpec is the content of the specification for a HelloWorldChaos
type HelloWorldChaosSpec struct {
// ContainerSelector specifies target
ContainerSelector `json:",inline"`
// Duration represents the duration of the chaos action
// +optional
Duration *string `json:"duration,omitempty"`
}
...
// GetSelectorSpecs is a getter for selectors
func (obj *HelloWorldChaos) GetSelectorSpecs() map[string]interface{} {
return map[string]interface{}{
".": &obj.Spec.ContainerSelector,
}
}
```
在 Chaos Mesh 中,混沌实验通过选择器来定义试验范围。选择器可以限定目标的命名空间、注解、标签等。选择器也可以是一些更特殊的值(如 AWSChaos 中的 AWSSelector。通常来说每个混沌实验只需要一个选择器但也有例外比如 NetworkChaos 有时需要两个选择器作为网络分区的两个对象。
## 实现 gRPC 接口
为了让 Chaos Daemon 能接受 Chaos Controller Manager 的请求,需要给它们加上新的 gRPC 接口。
1. 在 `pkg/chaosdaemon/pb/chaosdaemon.proto` 中加上新的 RPC。
```proto
service chaosDaemon {
...
rpc ExecHelloWorldChaos(ExecHelloWorldRequest) returns (google.protobuf.Empty) {}
}
message ExecHelloWorldRequest {
string container_id = 1;
}
```
更新了 proto 文件后,需要重新生成 Golang 代码。
```bash
make proto
```
2. 在 Chaos Daemon 中实现 gRPC 服务。
`pkg/chaosdaemon` 目录下新建一个名为 `helloworld_server.go` 的文件,写入以下内容:
```go
package chaosdaemon
import (
"context"
"fmt"
"github.com/golang/protobuf/ptypes/empty"
"github.com/chaos-mesh/chaos-mesh/pkg/bpm"
pb "github.com/chaos-mesh/chaos-mesh/pkg/chaosdaemon/pb"
)
func (s *DaemonServer) ExecHelloWorldChaos(ctx context.Context, req *pb.ExecHelloWorldRequest) (*empty.Empty, error) {
log.Info("ExecHelloWorldChaos", "request", req)
pid, err := s.crClient.GetPidFromContainerID(ctx, req.ContainerId)
if err != nil {
return nil, err
}
cmd := bpm.DefaultProcessBuilder("sh", "-c", fmt.Sprintf("ps aux")).
SetNS(pid, bpm.MountNS).
SetContext(ctx).
Build()
out, err := cmd.Output()
if err != nil {
return nil, err
}
if len(out) != 0 {
log.Info("cmd output", "output", string(out))
}
return &empty.Empty{}, nil
}
```
`chaos-daemon` 收到 `ExecHelloWorldChaos` 请求后, 它会输出当前容器的进程列表.
3. 在应用混沌实验中发送 gRPC 请求。
每个混沌实验都有其生命周期,首先被应用,然后被恢复。有一些混沌实验无法被恢复(如 PodChaos 中的 PodKill以及 HelloWorldChaos我们称之为 OneShot 实验,你可以在 HelloWorldChaos 结构的定义上方找到一行 `+chaos-mesh:oneshot=true`
Chaos Controller Manager 需要在应用 HelloWorldChaos 时给 Chaos Daemon 发送请求。为此,你需要对 `controllers/chaosimpl/helloworldchaos/types.go` 稍作修改。
```go
package helloworldchaos
import (
"context"
"github.com/chaos-mesh/chaos-mesh/api/v1alpha1"
"github.com/chaos-mesh/chaos-mesh/controllers/chaosimpl/utils"
"github.com/chaos-mesh/chaos-mesh/controllers/common"
"github.com/chaos-mesh/chaos-mesh/pkg/chaosdaemon/pb"
"github.com/go-logr/logr"
"go.uber.org/fx"
"sigs.k8s.io/controller-runtime/pkg/client"
)
type Impl struct {
client.Client
Log logr.Logger
decoder *utils.ContainerRecordDecoder
}
// Apply applies KernelChaos
func (impl *Impl) Apply(ctx context.Context, index int, records []*v1alpha1.Record, obj v1alpha1.InnerObject) (v1alpha1.Phase, error) {
impl.Log.Info("Apply helloworld chaos")
decodedContainer, err := impl.decoder.DecodeContainerRecord(ctx, records[index])
if err != nil {
return v1alpha1.NotInjected, err
}
pbClient := decodedContainer.PbClient
containerId := decodedContainer.ContainerId
_, err = pbClient.ExecHelloWorldChaos(ctx, &pb.ExecHelloWorldRequest{
ContainerId: containerId,
})
if err != nil {
return v1alpha1.NotInjected, err
}
return v1alpha1.Injected, nil
}
// Recover means the reconciler recovers the chaos action
func (impl *Impl) Recover(ctx context.Context, index int, records []*v1alpha1.Record, obj v1alpha1.InnerObject) (v1alpha1.Phase, error) {
impl.Log.Info("Recover helloworld chaos")
return v1alpha1.NotInjected, nil
}
func NewImpl(c client.Client, log logr.Logger, decoder *utils.ContainerRecordDecoder) *common.ChaosImplPair {
return &common.ChaosImplPair{
Name: "helloworldchaos",
Object: &v1alpha1.HelloWorldChaos{},
Impl: &Impl{
Client: c,
Log: log.WithName("helloworldchaos"),
decoder: decoder,
},
ObjectList: &v1alpha1.HelloWorldChaosList{},
}
}
var Module = fx.Provide(
fx.Annotated{
Group: "impl",
Target: NewImpl,
},
)
```
:::note 注意在 HelloWorldChaos 中,恢复过程什么都没有做。这是因为 HelloWorldChaos 是一个 OneShot 实验。如果你的新实验需要恢复,你应该在其中实现相关逻辑。 :::
## 验证实验效果
要验证实验效果,请进行以下操作:
1. 重新编译 Docker 镜像,并推送到本地 Registry 上,然后加载进 kind如果你使用 kind
```bash
make image
make docker-push
kind load docker-image localhost:5000/pingcap/chaos-mesh:latest
kind load docker-image localhost:5000/pingcap/chaos-daemon:latest
kind load docker-image localhost:5000/pingcap/chaos-dashboard:latest
```
2. 更新 Chaos Mesh
```bash
helm upgrade chaos-mesh helm/chaos-mesh --namespace=chaos-testing
```
3. 部署用于测试的目标 Pod如果你已经在之前部署了这个 Pod请跳过这一步
```bash
kubectl apply -f https://raw.githubusercontent.com/chaos-mesh/apps/master/ping/busybox-statefulset.yaml
```
4. 新建一个 YAML 文件,写入:
```yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: HelloWorldChaos
metadata:
name: busybox-helloworld-chaos
spec:
selector:
namespaces:
- busybox
mode: all
duration: 1h
```
5. 应用混沌实验:
```bash
kubectl apply -f /path/to/helloworld.yaml
```
6. 验证实验结果。有几份日志需要确认:
- 查看 Chaos Controller Manager 的日志:
```bash
kubectl logs chaos-controller-manager-{pod-post-fix} -n chaos-testing
```
查找以下内容:
```log
2021-06-25T06:02:12.754Z INFO records apply chaos {"id": "busybox/busybox-1/busybox"}
2021-06-25T06:02:12.754Z INFO helloworldchaos Apply helloworld chaos
```
- 查看 Chaos Daemon 的日志:
```bash
kubectl logs chaos-daemon-{pod-post-fix} -n chaos-testing
```
查找以下内容:
```log
2021-06-25T06:25:13.048Z INFO chaos-daemon-server ExecHelloWorldChaos {"request": "container_id:\"containerd://af1b99df3513c49c4cab4f12e468ed1d7a274fe53722bd883256d8f65bc9f681\""}
2021-06-25T06:25:13.050Z INFO background-process-manager build command {"command": "/usr/local/bin/nsexec -m /proc/243383/ns/mnt -- sh -c ps aux"}
2021-06-25T06:25:13.056Z INFO chaos-daemon-server cmd output {"output": "PID USER TIME COMMAND\n 1 root 0:00 sleep 3600\n"}
2021-06-25T06:25:13.070Z INFO chaos-daemon-server ExecHelloWorldChaos {"request": "container_id:\"containerd://88f6a469e5da82b48dc1190de07a2641b793df1f4e543a5958e448119d1bec11\""}
2021-06-25T06:25:13.072Z INFO background-process-manager build command {"command": "/usr/local/bin/nsexec -m /proc/243479/ns/mnt -- sh -c ps aux"}
2021-06-25T06:25:13.076Z INFO chaos-daemon-server cmd output {"output": "PID USER TIME COMMAND\n 1 root 0:00 sleep 3600\n"}
```
可以看到两条 `ps aux`,对应两个不同的 Pod。
:::note 注意如果你的集群有多个节点,你会发现有不止一个 Chaos Daemon Pod。试着查看每一个 Chaos Daemon Pod 的日志,寻找真正被调用的那一个。 :::
## 探索更多
在完成上述步骤后HelloWorldChaos 已经成为一种有实际作用的混沌实验。如果你在这一过程中遇到了问题,请在 GitHub 创建一个 [issue](https://github.com/pingcap/chaos-mesh/issues) 向 Chaos Mesh 团队反馈。
你可能很好奇这一切是如何生效的。可以试着看看 `controllers` 目录下的各类 `controller`,它们有自己的 README如 [controllers/common/README.md](https://github.com/chaos-mesh/chaos-mesh/blob/master/controllers/common/README.md))。你可以通过这些 README 了解每个 controller 的功能,也可以阅读 [Chaos Mesh  架构](architecture.md)了解 Chaos Mesh 背后的原理。
你已经准备好成为一名真正的 Chaos Mesh 开发者了!到 [Chaos Mesh](https://github.com/chaos-mesh/chaos-mesh) 里找一找练手的任务吧!推荐你先从简单的入手,例如这些 [good first issues](https://github.com/chaos-mesh/chaos-mesh/labels/good%20first%20issue)。

View File

@ -0,0 +1,5 @@
---
title: 拓展 Chaosd 组件
---
## TODO

View File

@ -0,0 +1,108 @@
---
title: 常见问题解答 (FAQ)
---
import PickHelmVersion from '@site/src/components/PickHelmVersion'
## 问题
### Q: If I do not have deployed Kubernetes clusters, can I use Chaos Mesh to create chaos experiments?
No. Instead, you could use [`chaosd`](https://github.com/chaos-mesh/chaosd/) to inject failures without kubernetes.
### Q: I have deployed Chaos Mesh and created PodChaos experiments successfully, but I still failed in creating NetworkChaos/TimeChaos Experiment. The log is shown as below:
```console
2020-06-18T02:49:15.160Z ERROR controllers.TimeChaos failed to apply chaos on all pods {"reconciler": "timechaos", "error": "rpc error: code = Unavailable desc = connection error: desc = \"transport: Error while dialing dial tcp xx.xx.xx.xx:xxxx: connect: connection refused\""}
```
The reason is that `chaos-controller-manager` failed to connect to `chaos-daemon`. You need to first check the Pod network and its [policies](https://kubernetes.io/docs/concepts/services-networking/network-policies/).
If everything is in order, maybe you can use the `hostNetwork` parameter to fix this problem as follows:
<PickHelmVersion>{`helm upgrade chaos-mesh chaos-mesh/chaos-mesh -n chaos-testing --version latest --set chaosDaemon.hostNetwork=true`}</PickHelmVersion>
Reference: <https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/troubleshooting-kubeadm/#hostport-services-do-not-work>
### Q: The default administrator Google Cloud user account is forbidden to create chaos experiments. How to fix it?
The default administrator Google Cloud user cannot be checked by `AdmissionReview`. You need to create an administrator role and assign the role to your account to grant the privilege of creating chaos experiments to it. For example:
```yaml
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: role-cluster-manager-pdmas
rules:
- apiGroups: ['']
resources: ['pods', 'namespaces']
verbs: ['get', 'watch', 'list']
- apiGroups:
- chaos-mesh.org
resources: ['*']
verbs: ['get', 'list', 'watch', 'create', 'delete', 'patch', 'update']
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: cluster-manager-binding
namespace: chaos-testing
subjects:
# Google Cloud user account
- kind: User
name: USER_ACCOUNT
roleRef:
kind: ClusterRole
name: role-cluster-manager-pdmas
apiGroup: rbac.authorization.k8s.io
```
The `USER_ACCOUNT` above should be your Google Cloud user email.
### Q: Daemon throws an error similar to `version 1.41 is too new. The maximum supported API version is 1.39`
This indicates that the maximum API version that the Docker daemon can accept is `1.39`, but the client in `chaos-daemon` uses `1.41` by default. You can choose the following options to solve this problem:
1. Upgrade your Docker to a newer version.
2. Helm install/upgrade with `--set chaosDaemon.env.DOCKER_API_VERSION=1.39`.
## DNSChaos
### Q: While trying to run DNSChaos in OpenShift, the problems regarding authorization blocked the process
If the error message is similar to the following:
```bash
Error creating: pods "chaos-dns-server-123aa56123-" is forbidden: unable to validate against any security context constraint: [spec.containers[0].securityContext.capabilities.add: Invalid value: "NET_BIND_SERVICE": capability may not be added]
```
You need to add the privileged Security Context Constraints (SCC) to the `chaos-dns-server`.
```bash
oc adm policy add-scc-to-user privileged -n chaos-testing -z chaos-dns-server
```
## 安装
### Q: While trying to install Chaos Mesh in OpenShift, the problems regarding authorization blocked the installation process
If the error message is similar to the following:
```bash
Error creating: pods "chaos-daemon-" is forbidden: unable
to validate against any security context constraint: [spec.securityContext.hostNetwork:
Invalid value: true: Host network is not allowed to be used spec.securityContext.hostPID:
Invalid value: true: Host PID is not allowed to be used spec.securityContext.hostIPC:
Invalid value: true: Host IPC is not allowed to be used securityContext.runAsUser:
Invalid value: "hostPath": hostPath volumes are not allowed to be used spec.containers[0].securityContext.volumes[1]:
Invalid value: true: Host network is not allowed to be used spec.containers[0].securityContext.containers[0].hostPort:
Invalid value: 31767: Host ports are not allowed to be used spec.containers[0].securityContext.hostPID:
Invalid value: true: Host PID is not allowed to be used spec.containers[0].securityContext.hostIPC:
......]
```
You need to add privileged scc to default.
```bash
oc adm policy add-scc-to-user privileged -n chaos-testing -z chaos-daemon
```

View File

@ -0,0 +1,65 @@
---
title: GCP 身份验证接入
---
如果 Chaos Mesh 集群部署于 Google Cloud Platform用户将能够通过 Google OAuth 验证登入 Chaos Dashboard。本文档将介绍如何配置和启用这项功能。
## 创建用于登陆验证的 OAuth Client
根据 [Setting up OAuth 2.0](https://support.google.com/cloud/answer/6158849?hl=en) 创建用于接入 GCP 的 OAuth 2.0 客户端,并获得 Client ID 与 Client Secret。
1. 进入 [Google Cloud Platform 控制台](https://console.cloud.google.com/)。
2. 选择一个项目。
3. 如果没有自动打开 APIs & services 页面,请在控制台的左侧菜单中手动选择 APIs & services。
4. 点击位于左侧的 Credentials。
5. 点击 Create Credentials并选择 OAuth client ID。
6. 应用类型选择 Web Application填入合适的名称以及 Chaos Dashboard 对应的 redirect urls。Chaos Dashboard 的 redirect urls 将位于 `ROOT_URL/api/auth/gcp/callback`,其中 `ROOT_URL` 是 dashboard 的根地址,例如 `http://localhost:2333`,可以通过 `helm``dashboard.rootUrl` 配置项进行配置。
7. 点击创建。
完成创建后,即可获得该客户端的 Client ID 与 Client Secret请保存这两项内容供在后续步骤中使用。
## 填写配置并启动 Chaos Mesh
要启动这项功能,需要打开 Chaos Mesh 的 helm charts ,设置以下配置项:
1. `dashboard.gcpSecurityMode` 需要设置为 `true`
2. `dashboard.gcpClientId` 需要设置为上一步骤中获得的 Client ID
3. `dashboard.gcpClientSecret` 需要设置为上一步骤中获得的 Client Secret
4. `dashboard.rootUrl` 需要设置为 Chaos Dashboard 的根地址
如果已经安装并运行了 Chaos Mesh可以通过 `helm upgrade` 命令来更新配置;如果还未安装 Chaos Mesh则可以通过 `helm install` 进行安装。
## 使用
打开 Chaos Dashboard点击验证窗口下方的 Google Icon。
![img](./img/google-auth.png)
登入 Google 账号并授予 OAuth Client 权限后,页面会自动跳转至 Chaos Dashboard并提示用户已登录。此时用户的权限与该 Google 账户在集群中的权限一致。如需设置额外的用户权限,可以使用 RBAC 的方式来赋予其对应权限,例如:
```yaml
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: chaos-mesh-cluster-manager
rules:
- apiGroups:
- chaos-mesh.org
resources: ['*']
verbs: ['get', 'list', 'watch', 'create', 'delete', 'patch', 'update']
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: cluster-manager-binding
namespace: chaos-testing
subjects:
- kind: User
name: example@gmail.com
roleRef:
kind: ClusterRole
name: chaos-mesh-cluster-manager
apiGroup: rbac.authorization.k8s.io
```
这一配置为用户 `example@gmail.com` 赋予了浏览或创建所有类型混沌实验的权限。

View File

@ -0,0 +1,5 @@
---
title: 术语表
---
## TODO

View File

@ -0,0 +1,5 @@
---
title: Go
---
## TODO

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 197 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 166 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 250 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 158 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 171 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 152 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 130 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 149 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 129 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 146 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

View File

@ -0,0 +1,105 @@
---
title: 检查实验结果
---
本文档介绍如何使用 Chaos Mesh 检查混沌实验的运行状态和结果。
## 实验阶段介绍
在 Chaos Mesh 中,根据实验的执行流程,一个混沌实验的生命周期主要分为以下四个阶段:
- 注入阶段:混沌实验正在进行注入故障操作。通常情况下,此阶段持续的时间很短。如果此阶段持续的时间很长,可能是由于混沌实验出现了异常,此时可以查看事件信息确定异常原因。
- 运行阶段:当所有测试目标都已经被成功注入故障后,混沌实验进入运行阶段。
- 暂停阶段:当对混沌实验进行[暂停](run-a-chaos-experiment.md#暂停混沌实验)操作时Chaos Mesh 会恢复所有测试目标,此时实验进入暂停阶段。
- 结束阶段如果配置了实验持续时间当实验运行时间达到了持续时间后Chaos Mesh 会恢复所有测试目标,表示实验已经结束。
## 通过 Chaos Dashboard 检查实验结果
在 Chaos Dashboard 中,你可以在以下任一页面查看实验的运行阶段:
- 混沌实验列表页面:
![实验状态](img/list_chaos_status_zh.png)
- 混沌实验详情页面:
![实验状态](img/chaos_detail_status_zh.png)
:::note 注意
- 如果一个混沌实验长时间处于**注入**阶段,可能是由于此实验出现了异常(例如,配置的 Selectors 未选出待测目标)。此时,你可以通过查看**事件信息**确定异常原因,并检查混沌实验的配置信息。
- Chaos Dashboard 中仅展示了[主要实验阶段](#实验的阶段介绍),如需查看更详细的实验状态,请通过 `kubectl` 检查实验结果。
:::
## 通过 `kubectl` 检查实验结果
可以使用 `kubectl describe` 命令查看此混沌实验对象的 `Status``Events`,从而确定实验结果。
```shell
kubectl describe podchaos pod-failure-tikv -n tidb-cluster
```
执行上述命令后,预期输出如下:
```shell
...
Status:
Conditions:
Reason:
Status: False
Type: Paused
Reason:
Status: True
Type: Selected
Reason:
Status: True
Type: AllInjected
Reason:
Status: False
Type: AllRecovered
Experiment:
Container Records:
Id: tidb-cluster/basic-tikv-0
Phase: Injected
Selector Key: .
Desired Phase: Run
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal FinalizerInited 39s finalizer Finalizer has been inited
Normal Paused 39s desiredphase Experiment has been paused
Normal Updated 39s finalizer Successfully update finalizer of resource
Normal Updated 39s records Successfully update records of resource
Normal Updated 39s desiredphase Successfully update desiredPhase of resource
Normal Started 17s desiredphase Experiment has started
Normal Updated 17s desiredphase Successfully update desiredPhase of resource
Normal Applied 17s records Successfully apply chaos for tidb-cluster/basic-tikv-0
Normal Updated 17s records Successfully update records of resource
```
上述输出中,主要包含两部分:
- `Status`
依据混沌实验的执行流程,`Status` 提供了以下四类状态记录:
- `Paused` 代表混沌实验正处于暂停阶段。
- `Selected` 代表混沌实验已经正确选择出待测试目标。
- `AllInjected`:代表所有测试目标都已经被成功注入故障。
- `AllRecoverd`:代表所有测试目标的故障都已经被成功恢复。
可以通过这四类状态记录推断出当前混沌实验的真实运行情况。例如:
- 当 `Paused`、`Selected`、`AllRecoverd` 的状态是 `True``AllInjected` 的状态是 `False`时,说明当前实验处在暂停状态。
- 当 `Paused``True` 的时,说明当前实验处在暂停状态,但是如果此时的 `Selected` 值为 `False`,那么可以进一步得出此混沌实验无法选出待测试目标。
:::note 注意
你可以从上述的四类实验记录组合中可以推导出更多的信息,例如当 `Paused``True` 的时候,说明混沌实验处在暂停状态,但是如果此时的 `Selected` 值为 `False`,那么可以进一步得出此混沌实验无法选出待测试目标。
:::
- `Events`
事件列表中包含混沌实验整个生命周期中的操作记录,可以帮助确定混沌实验状态并排除问题。

View File

@ -0,0 +1,185 @@
---
title: 集成 Chaos Mesh 到 GitHub Actions
---
本文介绍如何使用 chaos-mesh-action 将 Chaos Mesh 集成到 CI 中,帮助你在产品发布前发现在系统开发过程中引入的问题。
chaos-mesh-action 是一个 GitHub action已经在 [GitHub 市场](https://github.com/marketplace/actions/chaos-mesh)上发布,源代码也在 [GitHub](https://github.com/chaos-mesh/chaos-mesh-action) 上。
## chaos-mesh-action 的设计
[GitHub Action](https://docs.github.com/en/actions) 是 GitHub 原生支持的 CI/CD 功能,通过它你可以轻松地在 GitHub 仓库中构建自动化和自定义的软件开发工作流 (workflow)。
结合 GitHub ActionChaos Mesh 可以更容易地融入到系统的日常开发和测试中,从而保证每次在 GitHub 上提交的代码没有 bug至少可以通过测试不会破坏现有的逻辑。 下图显示了集成到 CI workflow 中的 chaos-mesh-action
![chaos-mesh-action-integrate-in-the-ci-workflow](./img/chaos-mesh-action-integrate-in-the-ci-workflow.png)
## 在 GitHub workflow 中使用 chaos-mesh-action
chaos-mesh-action 用于 Github workflow。 GitHub workflow 是一个可配置的自动化流程,你可以在你的仓库中设置它,以构建、测试、打包、发布或部署任何 GitHub 项目。 要将 Chaos Mesh 集成到你的 CI 中,请执行以下操作:
- 第 1 步:设计 workflow
- 第 2 步:创建 workflow
- 第 3 步:运行 workflow
### 第 1 步:设计 workflow
在设计 workflow 之前,你必须考虑以下问题:
- 要在此 workflow 中测试哪些功能?
- 要注入哪些类型的故障?
- 如何验证系统的正确性?
例如,让我们设计一个简单的测试 workflow包括以下步骤
1. 在 Kubernetes 集群中创建两个 Pod。
2. 从一个 Pod ping 另一个 Pod。
3. 使用 Chaos Mesh 注入网络延迟故障,测试 ping 命令是否收到影响。
### 第 2 步:创建 workflow
在设计好 workflow 之后,请按照以下步骤创建 workflow。
1. 导航到要测试软件的 GitHub 仓库。
2. 开始创建 workflow点击 `Actions`,然后点击 `New workflow`
![creating-a-workflow](./img/creating-a-workflow.png)
workflow 本质上是按顺序自动进行的作业配置。 请注意以下的作业job是在单个文件中配置的。 为了更好地说明,本文将脚本拆分为不同的作业组,如下所示:
- 设置 workflow 名称和触发规则
将 workflow 命名为 “Chaos”。 当代码推送到 master 分支或向 master 分支提交 pull request 时,会触发此 workflow。
```yaml
name: Chaos
on:
push:
branches:
- master
pull_request:
branches:
- master
```
- 安装 CI 相关的环境
此配置指定操作系统 (Ubuntu),并使用 helm/kind-action 创建 Kind 集群。 然后,它输出集群的相关信息。最后,它会检出该 workflow 要访问的 GitHub 仓库。
```yaml
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Creating kind cluster
uses: helm/kind-action@v1.0.0-rc.1
- name: Print cluster information
run: |
kubectl config view
kubectl cluster-info
kubectl get nodes
kubectl get pods -n kube-system
helm version
kubectl version
- uses: actions/checkout@v2
```
- 部署应用程序
在以下示例中,此 job 部署了一个应用程序,它会创建两个 Kubernetes Pod。
```yaml
- name: Deploy an application
run: |
kubectl apply -f https://raw.githubusercontent.com/chaos-mesh/apps/master/ping/busybox-statefulset.yaml
```
- 用 Chaos Mesh 注入故障
```yaml
- name: Run chaos mesh action
uses: chaos-mesh/chaos-mesh-action@v0.5
env:
CHAOS_MESH_VERSION: v1.0.0
CFG_BASE64: YXBpVmVyc2lvbjogY2hhb3MtbWVzaC5vcmcvdjFhbHBoYTEKa2luZDogTmV0d29ya0NoYW9zCm1ldGFkYXRhOgogIG5hbWU6IG5ldHdvcmstZGVsYXkKICBuYW1lc3BhY2U6IGJ1c3lib3gKc3BlYzoKICBhY3Rpb246IGRlbGF5ICMgdGhlIHNwZWNpZmljIGNoYW9zIGFjdGlvbiB0byBpbmplY3QKICBtb2RlOiBhbGwKICBzZWxlY3RvcjoKICAgIHBvZHM6CiAgICAgIGJ1c3lib3g6CiAgICAgICAgLSBidXN5Ym94LTAKICBkZWxheToKICAgIGxhdGVuY3k6ICIxMG1zIgogIGR1cmF0aW9uOiAiNXMiCiAgc2NoZWR1bGVyOgogICAgY3JvbjogIkBldmVyeSAxMHMiCiAgZGlyZWN0aW9uOiB0bwogIHRhcmdldDoKICAgIHNlbGVjdG9yOgogICAgICBwb2RzOgogICAgICAgIGJ1c3lib3g6CiAgICAgICAgICAtIGJ1c3lib3gtMQogICAgbW9kZTogYWxsCg==
```
通过 chaos-mesh-actionChaos Mesh 的安装和故障的注入会自动完成。你只需要准备好混沌实验的配置,并获取它的 Base64 值。如果想给 Pod 注入网络延迟,可以使用以下示例配置:
```yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: NetworkChaos
metadata:
name: network-delay
namespace: busybox
spec:
action: delay # the specific chaos action to inject
mode: all
selector:
pods:
busybox:
- busybox-0
delay:
latency: '10ms'
duration: '5s'
scheduler:
cron: '@every 10s'
direction: to
target:
selector:
pods:
busybox:
- busybox-1
mode: all
```
使用以下命令获取上述混沌实验配置文件的 Base64 值:
```bash
base64 chaos.yaml
```
- 验证系统正确性
在此 job 中workflow 从一个 Pod 中 ping 另一个 Pod。请观察网络延迟的变化。
```yaml
- name: Verify
run: |
echo "do some verification"
kubectl exec busybox-0 -it -n busybox -- ping -c 30 busybox-1.busybox.busybox.svc
```
### 第 3 步:运行 workflow
创建好 workflow 后,可以通过向 master 分支提交 pull request 来触发它。workflow 运行完成后,验证 job 中输出的结果类似于以下内容:
```log
do some verification
Unable to use a TTY - input is not a terminal or the right kind of file
PING busybox-1.busybox.busybox.svc (10.244.0.6): 56 data bytes
64 bytes from 10.244.0.6: seq=0 ttl=63 time=0.069 ms
64 bytes from 10.244.0.6: seq=1 ttl=63 time=10.136 ms
64 bytes from 10.244.0.6: seq=2 ttl=63 time=10.192 ms
64 bytes from 10.244.0.6: seq=3 ttl=63 time=10.129 ms
64 bytes from 10.244.0.6: seq=4 ttl=63 time=10.120 ms
64 bytes from 10.244.0.6: seq=5 ttl=63 time=0.070 ms
64 bytes from 10.244.0.6: seq=6 ttl=63 time=0.073 ms
64 bytes from 10.244.0.6: seq=7 ttl=63 time=0.111 ms
64 bytes from 10.244.0.6: seq=8 ttl=63 time=0.070 ms
64 bytes from 10.244.0.6: seq=9 ttl=63 time=0.077 ms
……
```
输出显示了一连串的 10 毫秒延迟,每次延迟大约 5 秒(也就是 5 次)。 这与我们使用 chaos-mesh-action 注入的的混沌实验配置一致。
## 探索更多
目前 chaos-mesh-action 已经应用于 [TiDB Operator](https://github.com/pingcap/tidb-operator) 项目,可以在 workflow 中注入 Pod 故障用于验证 Operator 实例的重启功能。 目的是为了保证在注入的故障随机删除 Operator 的 Pod 时TiDB Operator 能够正常工作。 更多详情可以查看 [TiDB Operator 页面](https://github.com/pingcap/tidb-operator/actions?query=workflow%3Achaos)。
未来chaos-mesh-action 将被应用到 TiDB 更多的测试中,以保证 TiDB 及相关组件的稳定性。 欢迎使用 chaos-mesh-action 创建自己的 workflow。
如果你发现错误,或者认为缺少某些内容,请随时提交 [issue](https://github.com/pingcap/chaos-mesh/issues)、[pull request(PR)](https://github.com/chaos-mesh/chaos-mesh/pulls),或加入我们的 [CNCF](https://www.cncf.io/) slack 工作区中的 [#project-chaos-mesh](https://slack.cncf.io/) 频道。

View File

@ -0,0 +1,5 @@
---
title: JAVA
---
## TODO

View File

@ -0,0 +1,148 @@
---
title: 管理用户权限
---
本文档介绍如何在 Chaos Mesh 中进行用户权限管理,包括创建用户并绑定权限、管理令牌以及开启/关闭权限验证功能。
Chaos Mesh 使用 Kubernetes 原生的 [RBAC](https://kubernetes.io/zh/docs/reference/access-authn-authz/rbac/) 功能来管理用户角色和权限。用户在创建、查看、管理混沌实验时,需要拥有 `chaos-mesh.org` 这个 `apiGroups` 下混沌实验自定义资源的相应权限。
:::note 注意
使用 Helm 安装 Chaos Mesh 时,默认开启权限验证功能。对于生产环境及其他安全要求较高的场景,建议保持权限验证功能开启。如果只是想体验 Chaos Mesh 的功能,希望关闭权限验证从而快速创建混沌实验,可以直接参阅[权限验证功能的开启及关闭](#开启或关闭权限验证功能)部分了解如何关闭权限验证。
:::
### 创建用户并绑定权限
你可以直接通过 Chaos Mesh Dashboard 界面创建用户并绑定权限。在访问 Dashboard 时会有登录窗口弹出,点击**“点击这里生成”**
![Dashboard 令牌登录](img/dashboard_login1.png)
点击后,弹出的窗口如下所示:
![Dashboard 令牌辅助生成器](img/token_helper.png)
需在弹出的窗口上执行下面的操作至第 3 步:
1. 选择权限范围
如要获取整个 Kubernetes 混沌实验的相应权限,勾选**集群范围**方框。如果在**命名空间**下拉选项中指定了 namespace则只获取该 namespace 下的权限。
2. 选择角色
目前 Chaos Mesh 提供了以下角色:
- Manager拥有混沌实验的创建、查看、更新、删除等所有权限。
- Viewer只拥有混沌实验的查看权限。
3. 生成 RBAC 配置
在确定了所创建权限的范围和角色后Dashboard 页面上会显示对应的 RBAC 配置。例如, `busybox` namespace 下 Manager 角色的 RBAC 配置如下所示:
```yaml
kind: ServiceAccount
apiVersion: v1
metadata:
namespace: busybox
name: account-busybox-manager-zcbaf
---
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
namespace: busybox
name: role-busybox-manager-zcbaf
rules:
- apiGroups: [""]
resources: ["pods", "namespaces"]
verbs: ["get", "watch", "list"]
- apiGroups:
- chaos-mesh.org
resources: [ "*" ]
verbs: ["get", "list", "watch", "create", "delete", "patch", "update"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: bind-busybox-manager-zcbaf
namespace: busybox
subjects:
- kind: ServiceAccount
name: account-busybox-manager-zcbaf
namespace: busybox
roleRef:
kind: Role
name: role-busybox-manager-zcbaf
apiGroup: rbac.authorization.k8s.io
```
点击 Dashboard 窗口中 RBAC 配置右上角的**复制**将 RBAC 配置内容复制到剪切板,然后写入到本地文件 `rbac.yaml`
4. 创建用户并绑定权限
在终端中运行以下命令:
```bash
kubectl apply -f rbac.yaml
```
5. 生成令牌
复制 Dashboard 中第 3 步“最后获取令牌”下的命令,并在终端中运行:
```bash
kubectl describe -n busybox secrets account-busybox-manager-zcbaf
```
输出如下所示:
```log
Name: account-busybox-manager-zcbaf-token-x572r
Namespace: busybox
Labels: <none>
Annotations: kubernetes.io/service-account.name: account-busybox-manager-zcbaf
kubernetes.io/service-account.uid: 19757b8d-195f-4231-b193-be18280b65d3
Type: kubernetes.io/service-account-token
Data
====
ca.crt: 1025 bytes
namespace: 7 bytes
token: eyJhbGciOi...z-PWMK8iQ
```
复制以上输出中的 token 的数据,用于下一步的登录。
6. 使用创建的用户登录 Chaos Mesh
点击 Dashboard 令牌辅助生成器窗口上的**关闭**,返回到登录窗口。在**令牌**输入框中输入上一步复制的 token 数据,并在**名称**输入框中给该令牌输入一个有意义的名称,建议使用权限的范围和角色,例如 `busybox-manager`。输入完成后,点击**提交**进行登录:
![Dashboard 令牌登录](img/dashboard_login2.png)
:::note 注意
- 需要保证执行 kubectl 的本地用户具有集群的管理权限,从而可以创建用户、绑定不同的权限、并获取 token。
- 如果没有部署 Chaos Mesh Dashboard也可以自行生成相应的 RBAC 配置,通过 kubectl 创建用户并绑定权限。
:::
### 管理令牌
如要管理令牌,在 Dashboard Web 页面中点击**设置**,如下所示:
![Dashboard 令牌管理](img/token_manager.png)
可以在**添加令牌**窗口中继续添加新的令牌,也可以点击**使用**以切换不同权限的令牌,或者删除令牌。
### 开启或关闭权限验证功能
使用 Helm 安装 Chaos Mesh 时,默认开启权限验证功能。对于生产环境及其他安全要求较高的场景,建议都保持权限验证功能开启。如果只是想体验 Chaos Mesh 的功能,希望关闭权限验证从而快速创建混沌实验,可以在 Helm 命令中设置 `--set dashboard.securityMode=false`,命令如下所示:
```bash
helm upgrade chaos-mesh chaos-mesh/chaos-mesh --namespace=chaos-testing --set dashboard.securityMode=false
```
如果想重新开启权限验证功能,再重新设置 `--set dashboard.securityMode=true` 即可。

View File

@ -0,0 +1,5 @@
---
title: 多数据中心场景
---
## TODO

View File

@ -0,0 +1,150 @@
---
title: 离线安装
---
import PickVersion from '@site/src/components/PickVersion'
import VerifyInstallation from './common/verify-installation.md'
import QuickRun from './common/quick-run.md'
本篇文档描述如何离线安装 Chaos Mesh。
## 环境准备
在安装前,请先确保离线环境中已经安装 Docker 并部署了 Kubernetes 集群。如果环境尚未准备好,请参考以下链接安装 Docker 并部署 Kubernetes 集群:
- [Docker](https://www.docker.com/get-started)
- [Kubernetes](https://kubernetes.io/docs/setup/)
## 准备安装文件
在离线安装 Chaos Mesh 前,你需要从有外网连接的机器上下载所有 Chaos Mesh 镜像和仓库压缩包,然后将下载的文件拷贝到离线环境中。
### 指定版本号
在有外网连接的机器上,设置 Chaos Mesh 的版本号为环境变量:
<PickVersion>
export CHAOS_MESH_VERSION=latest
</PickVersion>
### 下载 Chaos Mesh 镜像
在有外网连接的机器上,通过已经设置的版本号拉取镜像:
```bash
docker pull ghcr.io/chaos-mesh/chaos-mesh:${CHAOS_MESH_VERSION}
docker pull ghcr.io/chaos-mesh/chaos-daemon:${CHAOS_MESH_VERSION}
docker pull ghcr.io/chaos-mesh/chaos-dashboard:${CHAOS_MESH_VERSION}
```
保存镜像为 tar 包:
```bash
docker save ghcr.io/chaos-mesh/chaos-mesh:${CHAOS_MESH_VERSION} > image-chaos-mesh.tar
docker save ghcr.io/chaos-mesh/chaos-daemon:${CHAOS_MESH_VERSION} > image-chaos-daemon.tar
docker save ghcr.io/chaos-mesh/chaos-dashboard:${CHAOS_MESH_VERSION} > image-chaos-dashboard.tar
```
:::note 注意
如需模拟 DNS 故障(例如,使 DNS 响应返回随机的错误 IP 地址),请额外拉取 [`pingcap/coredns`](https://hub.docker.com/r/pingcap/coredns) 镜像。
:::
### 下载 Chaos Mesh 仓库压缩包
在有外网连接的机器上,下载 Chaos Mesh 的 zip 包:
```bash
curl -fsSL -o chaos-mesh.zip https://github.com/chaos-mesh/chaos-mesh/archive/refs/heads/master.zip
```
### 拷贝文件
所有安装所需的文件下载完成后,请将这些文件拷贝到离线环境中:
- `image-chaos-mesh.tar`
- `image-chaos-daemon.tar`
- `image-chaos-dashboard.tar`
- `chaos-mesh.zip`
## 安装
将 Chaos Mesh 镜像的 tar 包和仓库的 zip 包拷贝到你的离线环境后,就可以按照以下步骤进行安装。
### 第 1 步:加载 Chaos Mesh 镜像
从 tar 包中加载镜像:
```bash
docker load < image-chaos-mesh.tar
docker load < image-chaos-daemon.tar
docker load < image-chaos-dashboard.tar
```
### 第 2 步:推送镜像至 Registry
:::note 注意
在推送镜像前,请确保离线环境中已经部署 Registry。如果尚未部署请参考 [Docker Registry](https://docs.docker.com/registry/) 进行部署。
:::
设置 Chaos Mesh 版本和 Registry 地址为环境变量:
<PickVersion className="language-bash">
export CHAOS_MESH_VERSION=latest;
export DOCKER_REGISTRY=localhost:5000
</PickVersion>
标记镜像使其指向 Registry
```bash
export CHAOS_MESH_IMAGE=$DOCKER_REGISTRY/chaos-mesh/chaos-mesh:${CHAOS_MESH_VERSION}
export CHAOS_DAEMON_IMAGE=$DOCKER_REGISTRY/chaos-mesh/chaos-daemon:${CHAOS_MESH_VERSION}
export CHAOS_DASHBOARD_IMAGE=$DOCKER_REGISTRY/chaos-mesh/chaos-dashboard:${CHAOS_MESH_VERSION}
docker image tag ghcr.io/chaos-mesh/chaos-mesh:${CHAOS_MESH_VERSION} $CHAOS_MESH_IMAGE
docker image tag ghcr.io/chaos-mesh/chaos-daemon:${CHAOS_MESH_VERSION} $CHAOS_DAEMON_IMAGE
docker image tag ghcr.io/chaos-mesh/chaos-dashboard:${CHAOS_MESH_VERSION} $CHAOS_DASHBOARD_IMAGE
```
推送镜像至 Registry
```bash
docker push $CHAOS_MESH_IMAGE
docker push $CHAOS_DAEMON_IMAGE
docker push $CHAOS_DASHBOARD_IMAGE
```
### 第 3 步:使用 Helm 安装
解压 Chaos Mesh 的 zip 包:
```bash
unzip chaos-mesh.zip -d chaos-mesh && cd chaos-mesh
```
创建命名空间:
```bash
kubectl create ns chaos-testing
```
执行 Chaos Mesh 安装命令。在安装命令中,你需要指定 Chaos Mesh 的命名空间和各组件的镜像值:
```bash
helm install chaos-mesh helm/chaos-mesh -n=chaos-testing \
--set chaosDaemon.image=$CHAOS_DAEMON_IMAGE \
--set controllerManager.image=$CHAOS_MESH_IMAGE \
--set dashboard.image=$CHAOS_DASHBOARD_IMAGE
```
## 验证安装
<VerifyInstallation />
## 运行 Chaos 实验
<QuickRun />

View File

@ -0,0 +1,40 @@
---
slug: /
title: Chaos Mesh 简介
---
本篇文档描述 Chaos Mesh 的概念、使用场景、核心优势、以及架构概览。
## 简介
Chaos Mesh 是一个开源的云原生混沌工程平台提供丰富的故障模拟类型具有强大的故障场景编排能力方便用户在开发测试中以及生产环境中模拟现实世界中可能出现的各类异常帮助用户发现系统潜在的问题。Chaos Mesh 提供完善的可视化操作,旨在降低用户进行混沌工程的门槛。用户可以方便地在 Web UI 界面上设计自己的混沌场景,以及监控混沌实验的运行状态。
## Chaos Mesh 的核心优势
Chaos Mesh 作为业内领先的混沌测试平台,具备以下核心优势:
- 核心能力稳固Chaos Mesh 起源于 [TiDB](https://github.com/pingcap/tidb) 的核心测试平台,发布初期即继承了大量 TiDB 已有的测试经验。
- 被充分验证Chaos Mesh 被众多公司以及组织所使用,例如腾讯和美团等;同时被用于众多知名分布式系统的测试体系中,例如 Apache APISIX 和 RabbitMQ 等。
- 系统易用性强:图形化操作和基于 Kubernetes 的使用方式,充分利用了自动化能力。
- 云原生Chaos Mesh 原生支持 Kubernetes 环境,提供了强悍的自动化能力。
- 丰富的故障模拟场景Chaos Mesh 几乎涵盖了分布式测试体系中基础故障模拟的绝大多数场景。
- 灵活的实验编排能力:用户可以通过平台设计自己的混沌实验场景,场景可包含多个混沌实验编排,以及应用状态检查等。
- 安全性高Chaos Mesh 具有多层次安全控制设计,提供高安全性。
- 活跃的社区Chaos Mesh 为全球知名开源混沌测试平台CNCF 开源基金会孵化项目。
- 强大的扩展能力Chaos Mesh 为故障测试类型扩展和功能扩展提供了充分的扩展能力。
## 架构概览
Chaos Mesh 基于 Kubernetes CRD (Custom Resource Definition) 构建,根据不同的故障类型定义多个 CRD 类型,并为不同的 CRD 对象实现单独的 Controller 以管理不同的混沌实验。Chaos Mesh 主要包含以下三个组件:
- **Chaos Dashboard**Chaos Mesh 的可视化组件,提供了一套用户友好的 Web 界面用户可通过该界面对混沌实验进行操作和观测。同时Chaos Dashboard 还提供了 RBAC 权限管理机制。
- **Chaos Controller Manager**Chaos Mesh 的核心逻辑组件,主要负责混沌实验的调度与管理。该组件包含多个 CRD Controller例如 Workflow Controller、Scheduler Controller 以及各类故障类型的 Controller。
- **Chaos Daemon**Chaos Mesh 的主要执行组件。Chaos Daemon 以 [DaemonSet](https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/) 的方式运行,默认拥有 Privileged 权限(可以关闭)。该组件主要通过侵入目标 Pod Namespace 的方式干扰具体的网络设备、文件系统、内核等。
![Architecture](img/architecture.png)
Chaos Mesh 的整体架构如上图所展示,可以自上而下分为三个部分:
- 用户输入和观测的部分。用户输入以用户操作 (User) 为起点到达 Kubernetes API Server。用户不直接和 Chaos Mesh 的 Controller 交互,一切用户操作最终都将反映为某个 Chaos 资源的变更(比如 NetworkChaos 资源的变更)。
- 监听资源变化、调度 Workflow 和开展混沌实验的部分。Chaos Mesh 的 Controller 只接受来自 Kubernetes API Server 的事件,这种事件描述某个 Chaos 资源的变更,例如新的 Workflow 对象或者 Chaos 对象被创建。
- 具体节点故障的注入部分。该部分主要由 Chaos Daemon 组件负责,接受来自 Chaos Controller Manager 组件的指令,侵入到目标 Pod 的 Namespace 下,执行具体的故障注入。例如设置 TC 网络规则,启动 stress-ng 进程抢占 CPU 或内存资源等。

View File

@ -0,0 +1,186 @@
---
title: 使用 Helm 安装(生产推荐)
---
import PickVersion from '@site/src/components/PickVersion' import PickHelmVersion from '@site/src/components/PickHelmVersion'
import VerifyInstallation from './common/verify-installation.md' import QuickRun from './common/quick-run.md'
本篇文档描述如何在生产环境安装 Chaos Mesh。
## 环境准备
在安装之前,请先确保环境中已经安装 [Helm](https://helm.sh/docs/intro/install/)。
如要查看 Helm 是否已经安装,请执行如下命令:
```bash
helm version
```
以下是预期输出:
```bash
version.BuildInfo{Version:"v3.5.4", GitCommit:"1b5edb69df3d3a08df77c9902dc17af864ff05d1", GitTreeState:"dirty", GoVersion:"go1.16.3"}
```
如果你的实际输出与预期输出一致,表示 Helm 已经成功安装。
:::note 注意
本文中的命令将会使用 Helm v3 来操作 Chaos Mesh。如果你的环境中 Helm 的版本为 v2请参考[将 Helm v2 迁移到 v3](https://helm.sh/docs/topics/v2_v3_migration/)或按照 v2 的格式进行修改。
:::
## 使用 Helm 安装
### 第 1 步:添加 Chaos Mesh 仓库
在 Helm 仓库中添加 Chaos Mesh 仓库:
```bash
helm repo add chaos-mesh https://charts.chaos-mesh.org
```
### 第 2 步:查看可以安装的 Chaos Mesh 版本
执行如下命令显示可以安装的 charts
```bash
helm search repo chaos-mesh
```
:::note 注意
上述命令会输出最新发布的 chart如需安装历史版本请执行如下命令查看所有的版本
```bash
helm search repo chaos-mesh -l
```
:::
在上述命令完成后,接下来开始安装 Chaos Mesh。
### 第 3 步:创建安装 Chaos Mesh 的命名空间
推荐将 Chaos Mesh 安装在 `chaos-testing` 命名空间下,也可以指定任意命名空间安装 Chaos Mesh
```bash
kubectl create ns chaos-testing
```
### 第 4 步:在不同环境下安装
由于不同容器运行时的守护进程所监听的 socket path 不同,在安装时需要设置不同的值,可以根据不同的环境来运行如下的安装命令。
#### Docker
```bash
# 默认为 /var/run/docker.sock
helm install chaos-mesh chaos-mesh/chaos-mesh -n=chaos-testing
```
#### containerd
```bash
helm install chaos-mesh chaos-mesh/chaos-mesh -n=chaos-testing --set chaosDaemon.runtime=containerd --set chaosDaemon.socketPath=/run/containerd/containerd.sock
```
#### K3s
```bash
helm install chaos-mesh chaos-mesh/chaos-mesh -n=chaos-testing --set chaosDaemon.runtime=containerd --set chaosDaemon.socketPath=/run/k3s/containerd/containerd.sock
```
:::note 注意
如要安装特定版本的 Chaos Mesh请在 `helm install` 后添加 `--version xxx` 参数,如 `--version v2.0.0`
:::
:::note 注意
为了保证高可用性Chaos Mesh 默认开启了 `leader-election` 特性。如果不需要这个特性,请通过 `--set controllerManager.leaderElection.enabled=false` 手动关闭该特性。
:::
## 验证安装
<VerifyInstallation />
## 运行 Chaos 实验
<QuickRun />
## 升级 Chaos Mesh
如要升级 Chaos Mesh请执行如下命令
```bash
helm upgrade chaos-mesh chaos-mesh/chaos-mesh
```
:::note 注意
如要升级至特定版本的 Chaos Mesh请在 `helm upgrade` 后添加 `--version xxx` 参数,如 `--version v2.0.0`
:::
:::note 注意
如在非 Docker 环境下进行升级,需如[在不同环境下安装](#在不同环境下安装)所述添加相应的参数。
:::
如要修改配置,请根据需要设置不同的值。例如,如下命令会升级并卸载 `chaos-dashboard`
```bash
helm upgrade chaos-mesh chaos-mesh/chaos-mesh -n=chaos-testing --set dashboard.create=false
```
:::note 注意
如果想了解更多的值及其相关的用法,请参考[所有的值](https://github.com/chaos-mesh/chaos-mesh/blob/master/helm/chaos-mesh/values.yaml)。
:::
:::caution 警告
目前Helm 在升级时不会应用最新的 CustomResourceDefinition (CRD),这可能会导致一些错误的发生。为了避免这种情况,请手动应用最新的 CRD
<PickVersion>
curl -sSL https://mirrors.chaos-mesh.org/latest/crd.yaml | kubectl create -f -
</PickVersion>
:::
## 卸载 Chaos Mesh
如要卸载 Chaos Mesh请执行以下命令
```bash
helm uninstall chaos-mesh -n chaos-testing
```
## 常见问题解答
### 如何安装最新版本的 Chaos Mesh
Chaos Mesh 仓库中的 `helm/chaos-mesh/values.yaml` 定义了最新版本master 分支)的镜像。若想安装最新版本的 Chaos Mesh请执行以下命令
```bash
# 克隆仓库
git clone https://github.com/chaos-mesh/chaos-mesh.git
cd chaos-mesh
helm install chaos-mesh helm/chaos-mesh -n=chaos-testing
```
### 如何关闭安全模式
安全模式是默认启用的。如需关闭,请在安装或升级时指定 `dashboard.securityMode``false`
<PickHelmVersion>
helm install chaos-mesh chaos-mesh/chaos-mesh -n=chaos-testing --set dashboard.securityMode=false --version latest
</PickHelmVersion>

View File

@ -0,0 +1,5 @@
---
title: Python
---
## TODO

View File

@ -0,0 +1,101 @@
---
title: 快速试用(测试推荐)
---
import PickVersion from '@site/src/components/PickVersion'
import VerifyInstallation from './common/verify-installation.md' import QuickRun from './common/quick-run.md'
本篇文档描述如何在测试环境或本机环境快速试用 Chaos Mesh。
:::note 注意
**本文档提供的 Chaos Mesh 安装方式为脚本安装,仅供快速试用。**
如果需要在生产环境或者是其他严格的非测试场景下安装,推荐使用 [Helm](https://helm.sh/),详情请参考[使用 Helm 安装(生产推荐)](production-installation-using-helm.md)。
:::
## 环境准备
在试用之前,请先确保环境中已经部署 Kubernetes 集群。如果尚未部署 Kubernetes 集群,可以参考以下链接完成部署:
- [Kubernetes](https://kubernetes.io/docs/setup/)
- [minikube](https://minikube.sigs.k8s.io/docs/start/)
- [kind](https://kind.sigs.k8s.io/docs/user/quick-start/)
- [K3s](https://rancher.com/docs/k3s/latest/en/quick-start/)
- [Microk8s](https://microk8s.io/)
## 快速安装
要在试用环境中安装 Chaos Mesh请运行以下脚本
<PickVersion className="language-bash">
curl -sSL https://mirrors.chaos-mesh.org/latest/install.sh | bash
</PickVersion>
:::note 注意
- 如果当前环境为 [kind](https://kind.sigs.k8s.io/),请在脚本后添加 `--local kind` 参数。
<PickVersion className="language-bash">
curl -sSL https://mirrors.chaos-mesh.org/latest/install.sh | bash -s -- --local kind
</PickVersion>
若需要指定 kind 版本,请在脚本后添加 `--kind-version xxx` 参数,如:
<PickVersion className="language-bash">
curl -sSL https://mirrors.chaos-mesh.org/latest/install.sh | bash -s -- --local kind --kind-version v0.10.0
</PickVersion>
- 如果当前环境为 [K3s](https://k3s.io/),请在脚本后添加 `--k3s` 参数。
<PickVersion className="language-bash">
curl -sSL https://mirrors.chaos-mesh.org/latest/install.sh | bash -s -- --k3s
</PickVersion>
- 如果当前环境为 [Microk8s](https://microk8s.io/),请在脚本后添加 `--microk8s` 参数。
<PickVersion className="language-bash">
curl -sSL https://mirrors.chaos-mesh.org/latest/install.sh | bash -s -- --microk8s
</PickVersion>
:::
:::tip 建议
中国大陆地区的用户可在脚本后添加 `--docker-mirror` 参数来加快拉取镜像的速度。添加该参数后,`install.sh` 安装脚本将从 `dockerhub.azk8s.cn``gcr.azk8s.cn` 拉取镜像。
:::
运行此安装脚本后Chaos Mesh 将会自动安装与版本相符的 CustomResourceDefinition (CRD)、所有需要的组件、及相关的 Service Account 配置。
如果想了解更多的安装细节,请参考 [`install.sh` 的源代码](https://github.com/chaos-mesh/chaos-mesh/blob/master/install.sh)。
## 验证安装
<VerifyInstallation />
## 运行 Chaos 实验
<QuickRun />
## 卸载 Chaos Mesh
如要卸载 Chaos Mesh请执行以下命令
<PickVersion className="language-bash">
curl -sSL https://mirrors.chaos-mesh.org/latest/install.sh | bash -s -- --template | kubectl delete -f -
</PickVersion>
也可以通过删除 `chaos-testing` 命名空间直接卸载 Chaos Mesh
```sh
kubectl delete ns chaos-testing
```
## 常见问题解答
### 为什么安装后根目录会出现 `local` 目录
如果当前环境并没有安装 kind 但你在安装命令中使用了 `--local kind` 参数,`install.sh` 安装脚本将会自动安装 kind 到根目录下的 `local` 目录中。

View File

@ -0,0 +1,5 @@
---
title: 0.0.8 release notes
---
## TODO

View File

@ -0,0 +1,5 @@
---
title: 0.0.9 release notes
---
## TODO

View File

@ -0,0 +1,5 @@
---
title: 1.0.0 release notes
---
## TODO

View File

@ -0,0 +1,5 @@
---
title: 2.0.0 release notes
---
## TODO

View File

@ -0,0 +1,170 @@
---
title: 运行实验
---
本文档介绍如何使用 Chaos Mesh 创建并运行混沌实验、查看混沌实验运行情况、暂停混沌实验、更新混沌实验以及清理混沌实验。
## 创建混沌实验
使用 Chaos Mesh你可以创建以下两类混沌实验
- 一次性混沌实验:是最小粒度的混沌实验。创建后,实验会立刻向测试目标注入已配置的故障。如果配置了 `duration` 参数,故障在 `duration` 指定的时间结束后会自动恢复。当暂停或者删除混沌实验时,故障会立刻被恢复。
- 定时或循环混沌实验: 是可以定时运行或循环进行的混沌实验。创建时需要定义实验的时间调度规则。
### 一次性混沌实验
要创建一次性混沌实验,你可以采用以下两种方式之一:
- 使用 Dashboard 新建混沌实验,然后点击**提交**按钮运行实验。更多详细步骤,请参阅具体的混沌实验类型文档。
- 使用 YAML 文件定义混沌实验,然后使用 `kubectl` 命令创建并运行实验。要使用 YAML 文件方式定义混沌实验并运行实验,请完成以下操作:
1. 新建一个 YAML 文件用于定义混沌实验。在此 YAML 文件中,依据混沌实验类型,添加相应的配置参数。
以模拟网络故障为例,新建一个包含如下配置示例的 `network-delay.yaml` 文件。
```yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: NetworkChaos
metadata:
name: network-delay
spec:
action: delay # the specific chaos action to inject
mode: one # the mode to run chaos action; supported modes are one/all/fixed/fixed-percent/random-max-percent
selector: # pods where to inject chaos actions
namespaces:
- default
labelSelectors:
'app': 'web-show' # the label of the pod for chaos injection
delay:
latency: '10ms'
duration: '12s'
```
示例 YAML 文件中定义了一个持续 `12s` 的网络延迟故障,实验目标是 `default namespace` 下带有 `"app": "web-show"` 标签的应用。关于网络故障的更多配置信息,请参考[模拟网络故障](simulate-network-chaos-on-kubernetes.md)。
2. 使用 `kubectl apply -f` 命令创建并运行此混沌实验:
```yaml
kubectl apply -f network-delay.yaml
```
3. 混沌实验开始后,如需检查混沌实验的运行情况,请使用 `kubectl describe` 命令查看此混沌实验对象的 `status` 或者 `event`
```yaml
kubectl describe networkchaos network-delay
```
要了解详细的运行结果检查步骤,请参考[检查实验结果](inspect-chaos-experiments.md)。
### 定时或循环混沌实验
Chaos Mesh 提供 `Schedule` 对象,帮助创建定时混沌实验和循环混沌实验。
要创建定时或循环混沌实验,请进行以下操作:
1. 新建一个 YAML 文件用于定义混沌实验。在此 YAML 文件中,需要配置 `Schedule` 相关参数用于定义具体的时间调度规则,然后依据混沌实验类型配置故障相关参数。
以模拟一个定时的网络故障为例,新建一个包含如下配置示例的 `schedule-delay-example.yaml` 文件。
```yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: Schedule
metadata:
name: schedule-delay-example
spec:
schedule: '5 * * * *'
historyLimit: 2
concurrencyPolicy: 'Allow'
type: 'NetworkChaos'
networkChaos:
action: delay
mode: one
selector:
namespaces:
- default
labelSelectors:
'app': 'web-show'
delay:
latency: '10ms'
duration: '12s'
```
示例 YAML 文件中定义了一个可以在每个小时的第 5 分钟自动运行的网络延迟故障。更详细的调度规则定义,请参考[定义调度规则](define-scheduling-rules.md)。
:::note 注意如果不设置 `duration` 参数,表示故障行为会一直持续下去,直到暂停或者删除混沌实验。 :::
2. 使用 `kubectl apply -f` 命令创建并运行混沌实验。
```yaml
kubectl apply -f schedule-delay-example.yaml
```
3. 混沌实验开始后,如需检查混沌实验的运行情况,请使用 kubectl describe 命令查看此混沌实验对象的 status 或者 event。
```yaml
kubectl describe networkchaos schedule-delay-example
```
要了解详细的运行结果检查步骤,请参考[检查实验结果](inspect-chaos-experiments.md)。
## 暂停混沌实验
### 使用命令暂停或者恢复混沌实验
在混沌实验运行过程中,如需暂停混沌实验,可以使用命令设置暂停注解。
例如,要暂停默认命名空间中一个名为 `network-delay` 的混沌实验,你可以使用以下命令:
```yaml
kubectl annotate networkchaos network-delay experiment.chaos-mesh.org/pause=true
```
执行此命令后,注入的故障会被立刻恢复。如果想将此混沌实验从暂停状态中恢复到正常执行状态,可以通过如下命令:
```yaml
kubectl annotate networkchaos network-delay experiment.chaos-mesh.org/pause-
```
### 使用 Dashboard 暂停或者恢复混沌实验
如果你想通过 Dashboard 暂停或者恢复混沌实验,找到对应的混沌实验点击**暂停**或者**启动**按钮即可。
![Pause experiment](img/pause_zh.png)
![Restart experiment](img/restart_zh.png)
## 更新混沌实验
### 使用命令更新混沌实验
目前混沌实验的 `Spec` 字段不允许被更新。
更多细节,请参见对应的 [GitHub issue](https://github.com/chaos-mesh/chaos-mesh/issues/2227)。
### 使用 Dashboard 更新混沌实验
由于目前混沌实验的 `Spec` 字段不允许被更新,所以 Dashboard 暂不支持更新混沌实验。
## 清理混沌实验
### 使用命令删除混沌实验
结束混沌实验后,可以通过 `kubectl delete` 命令删除混沌实验。混沌实验删除后,注入的故障会被立刻恢复:
```yaml
kubectl delete -f network-delay.yaml
# or delete the chaos object directly
kubectl delete networkchaos network-delay
```
如果删除操作被阻塞,这意味着有一些目标对象的故障行为无法恢复。你可以查看 Chaos Mesh 的日志进行故障排查,或者直接在 GitHub 创建一个 [issue](https://github.com/pingcap/chaos-mesh/issues) 向 Chaos Mesh 团队反馈问题。此外,你也可以通过以下命令强制删除混沌实验:
```yaml
kubectl annotate networkchaos web-show-network-delay chaos-mesh.chaos-mesh.org/cleanFinalizer=forced
```
### 使用 Dashboard 删除混沌实验
如果你想要在 Dashboard 上删除混沌实验并归档到历史记录汇总,可以点击对应混沌实验的**归档**按钮。
![Archive experiment](img/archive_zh.png)

View File

@ -0,0 +1,124 @@
---
title: 串行或并行运行实验
---
Chaos Mesh Workflow 提供了串行与并行两种实验编排方式。你可以依据实验需求,编排调度多个实验的运行方式。
- 如果你想要按照顺序进行多个混沌实验,可以使用串行节点。
- 如果你想要同时进行多个混沌实验,可以使用并行节点。
在设计串行节点与并行节点时使用了[组合模式](https://en.wikipedia.org/wiki/Composite_pattern),可以包含多个任意类型的节点,并以特定的模式执行这些被组合的节点。这也意味着你可以嵌套组合串行与并行节点来实现复杂的调度。
## 串行运行实验
在 Workflow 中创建 `templates` 时,使用 `templateType: Serial` 便可以声明一个串行节点。
串行节点中另一个必需的字段为 `children`,类型为 `[]string` ,值为串行执行的其他 `template` 名称。例如:
```yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: Workflow
metadata:
name: try-workflow-serial
spec:
entry: serial-of-3-node
templates:
- name: serial-of-3-node
templateType: Serial
deadline: 240s
children:
- workflow-stress-chaos
- suspending
- workflow-network-chaos
- name: suspending
templateType: Suspend
deadline: 10s
- name: workflow-network-chaos
templateType: NetworkChaos
deadline: 20s
networkChaos:
direction: to
action: delay
mode: all
selector:
labelSelectors:
'app': 'hello-kubernetes'
delay:
latency: '90ms'
correlation: '25'
jitter: '90ms'
- name: workflow-stress-chaos
templateType: StressChaos
deadline: 20s
stressChaos:
mode: one
selector:
labelSelectors:
'app': 'hello-kubernetes'
stressors:
cpu:
workers: 1
load: 20
options: ['--cpu 1', '--timeout 600']
```
声明了一个串行节点,名为 `serial-of-3-node`,将按照顺序执行 `workflow-stress-chaos``suspending` 与 `workflow-network-chaos`。待所有任务完成后,串行节点被标记为完成。
串行节点执行时,会依次执行 `children` 中声明的任务,保持同一时间点只有一个任务在执行。
串行节点中的 `deadline` 为可选字段,目的是限制整个串行流程的最长执行时间。若达到了这个时间,其下属的子节点将会被停止,未执行的节点也不会再执行。若所有子节点先于 `deadline` 完成了行为,串行节点会立刻被标记为完成,`deadline` 没有任何影响。
## 并行运行实验
在 Workflow 中创建 `templates` 时,使用 `templateType: Parallel` 便可以声明一个并行节点。
并行节点中另一个必需的字段为 `children`,类型为 `[]string`,值为并行执行的其他 `template` 名称。例如:
```yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: Workflow
metadata:
name: try-workflow-parallel
spec:
entry: parallel-of-2-chaos
templates:
- name: parallel-of-2-chaos
templateType: Parallel
deadline: 240s
children:
- workflow-stress-chaos
- workflow-network-chaos
- name: workflow-network-chaos
templateType: NetworkChaos
deadline: 20s
networkChaos:
direction: to
action: delay
mode: all
selector:
labelSelectors:
'app': 'hello-kubernetes'
delay:
latency: '90ms'
correlation: '25'
jitter: '90ms'
- name: workflow-stress-chaos
templateType: StressChaos
deadline: 20s
stressChaos:
mode: one
selector:
labelSelectors:
'app': 'hello-kubernetes'
stressors:
cpu:
workers: 1
load: 20
options: ['--cpu 1', '--timeout 600']
```
声明了一个并行节点,名为 `parallel-of-2-chaos`,将同时执行 `workflow-stress-chaos``workflow-network-chaos`。待所有任务完成后,并行节点被标记为完成。
并行节点执行时,会同时执行 `children` 中所有声明的任务。
并行节点同样存在 `deadline` 可选字段,类似于串行节点,目的是限制整个并行流程的最长执行时间。若达到了这个时间,其下属的子节点将会被停止。若所有子节点先于 `deadline` 完成了行为,并行节点会立刻被标记为完成,`deadline` 没有任何影响。

View File

@ -0,0 +1,5 @@
---
title: Rust
---
## TODO

View File

@ -0,0 +1,57 @@
---
title: 在工作流中发送 HTTP 请求
---
Chaos Mesh Workflow 提供了 `Task` 节点以支持任意工作负载,其功能类似于 Kubernetes 中的 `Job`。 为了提供更好的产品体验Chaos Dashboard 提供了一个基于 `Task` 的模板。通过此模板,你可以方便地在 WebUI 中创建 HTTP 请求。本文介绍如何通过 Chaos Dashboard 创建 HTTP 请求。
:::note 注意
Chaos Mesh 中不存在属于 `HTTPRequest` 类型的工作流节点。本特性基于 `Task` 节点,用于更方便地发送 HTTP 请求。
:::
:::note 注意
当前该功能为实验特性,不建议在生产环境中使用,其配置与行为可能会在未来的版本中发生变化。
:::
## 通过 Chaos Dashboard 创建 HTTP 请求
你可以通过以下步骤在 Chaos Dashboard 中创建 HTTP 请求,具体操作以通过 Slack Webhook 发送消息为例。
### 第 1 步:创建类型为 HTTP 请求的工作流节点
任务类型选为"HTTP 请求" :
![create-http-request-workflow-node](img/create-http-request-workflow-node_zh.png)
### 第 2 步:配置 HTTP 请求
完成对以下配置的设置:
- 节点名称:`send-slack-message`
- 请求地址:`https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX`
- 请求方法:`POST`
- 请求体: `{"text": "Hello, world."}`,并勾选 "为 JSON 内容"
![configure-http-request-workflow-node](img/configure-http-request-workflow-node_zh.png)
### 第 3 步:提交工作流节点
点击“提交”按钮,即可在预览窗口查看创建的任务。
![http-request-task-node-preview](img/http-request-task-node-preview.png)
## 表单字段
| 参数 | 类型 | 说明 | 默认值 | 是否必填 | 示例 |
| --- | --- | --- | --- | --- | --- |
| 名称 | string | 节点名称 | | 是 | `send-slack-message` |
| URL | string | 请求地址 | | 是 | `https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX` |
| 方法 | string | 请求方法 | | 是 | `POST` |
| 请求体 | string | 请求体 | | 否 | `{"text": "Hello, world."}` |
| 跟随 301/302 跳转 | boolean | 该参数的值对应 `curl``-L` 参数 | `false` | 否 | `false` |
| 为 JSON 内容 | boolean | 该参数会将`Content-Type: application/json` 添加至 HTTP 请求头 | `false` | 否 | `false` |
生成的任务节点的 `name` 字段的值会把 `http-request` 后缀加到"名称"的后面。

View File

@ -0,0 +1,166 @@
---
title: 模拟 AWS 故障
---
本文档介绍如何使用 Chaos Mesh 来模拟 AWS 故障。
## AWSChaos 介绍
AWSChaos 能够帮助你模拟指定的 AWS 实例发生故障的情景。目前AWSChaos 支持以下类型的故障:
- **EC2 Stop**: 使指定的 EC2 实例进入停止状态。
- **EC2 Restart**: 重启指定的 EC2 实例。
- **Detach Volume**: 从指定的 EC2 实例中卸载存储卷。
## Secret 文件
为了方便地连接 AWS 集群,你可以提前创建一个 Kubernetes Secret 文件存储认证相关信息。
以下是一个 `secret` 文件示例:
```yaml
apiVersion: v1
kind: Secret
metadata:
name: cloud-key-secret
namespace: chaos-testing
type: Opaque
stringData:
aws_access_key_id: your-aws-access-key-id
aws_secret_access_key: your-aws-secret-access-key
```
- **name** 表示 Kubernetes Secret 对象的名字。
- **namespace** 表示 Kubernetes Secret 对象的命名空间。
- **aws_access_key_id** 存储 AWS 集群的访问密钥 ID。
- **aws_secret_access_key** 存储 AWS 集群的秘密访问密钥。
## 使用 Dashboard 方式创建实验
:::note 注意
在使用 Dashboard 方式创建实验之前,请确保:
1. 已经安装了 Dashboard。
2. 可以通过 **kubectl port-forward** 方式访问 Dashboard
```bash
kubectl port-forward -n chaos-testing svc/chaos-dashboard 2333:2333
```
接着你可以在浏览器通过 [`http://localhost:2333`](http://localhost:2333)访问 Dashboard 。
:::
1. 单击实验页面中的**新的实验**按钮进行创建实验。
![img](./img/create-pod-chaos-on-dashborad-1_zh.jpg)
2. 在**选择目标**处选择 **Aws 故障**,并选择具体行为,例如 **Ec2 Stop**
3. 填写实验信息,指定实验范围以及实验计划运行时间。
4. 提交实验。
## 使用 YAML 方式创建实验
### ec2-stop 配置文件示例
1. 将实验配置写入到文件 `awschaos-ec2-stop.yaml` 中,内容如下所示:
```yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: AWSChaos
metadata:
name: ec2-stop-example
namespace: chaos-testing
spec:
action: ec2-stop
secretName: 'cloud-key-secret'
awsRegion: 'us-east-2'
ec2Instance: 'your-ec2-instance-id'
duration: '5m'
```
依据此配置示例Chaos Mesh 将向指定的 EC2 实例中注入 ec2-stop 故障,使该 EC2 实例将在 5 分钟时间内处于不可用的状态。
如需查看更多关于停止 EC2 实例的信息,可以参考 [停止和启动 EC2 实例](https://docs.aws.amazon.com/zh_cn/AWSEC2/latest/UserGuide/Stop_Start.html)。
2. 使用 kubectl 创建实验,命令如下:
```bash
kubectl apply -f awschaos-ec2-stop.yaml
```
### ec2-restart 配置文件示例
1. 将实验配置写入到文件 `awschaos-ec2-restart.yaml` 中,内容如下所示:
```yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: AWSChaos
metadata:
name: ec2-restart-example
namespace: chaos-testing
spec:
action: ec2-restart
secretName: 'cloud-key-secret'
awsRegion: 'us-east-2'
ec2Instance: 'your-ec2-instance-id'
```
依据此配置示例Chaos Mesh 将向指定的 EC2 实例中注入 ec2-restart 故障,使该 EC2 实例将重启一次。
如需查看更多关于重启 EC2 实例的信息,可以参考[重启实例](https://docs.aws.amazon.com/zh_cn/AWSEC2/latest/UserGuide/ec2-instance-reboot.html)。
2. 使用 kubectl 创建实验,命令如下:
```bash
kubectl apply -f awschaos-ec2-restart.yaml
```
### detach-volume 配置文件示例
1. 将实验配置写入到文件 `awschaos-detach-volume.yaml` 中,内容如下所示:
```yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: AWSChaos
metadata:
name: ec2-detach-volume-example
namespace: chaos-testing
spec:
action: ec2-stop
secretName: 'cloud-key-secret'
awsRegion: 'us-east-2'
ec2Instance: 'your-ec2-instance-id'
volumeID: 'your-volume-id'
deviceName: '/dev/sdf'
duration: '5m'
```
依据此配置示例Chaos Mesh 将向指定的 EC2 实例中注入 detach-volume 故障,使该 EC2 实例在 5 分钟内与指定存储卷分离。
查看更多关于分离 Amazon EBS 卷的消息, 可以参考[分离 Amazon EBS 卷](https://docs.aws.amazon.com/zh_cn/AWSEC2/latest/UserGuide/ebs-detaching-volume.html)。
2. 使用 kubectl 创建实验,命令如下:
```bash
kubectl apply -f awschaos-detach-volume.yaml
```
### 字段说明
下表介绍以上 YAML 配置文件中的字段。
| 参数 | 类型 | 说明 | 默认值 | 是否必填 | 示例 |
| --- | --- | --- | --- | --- | --- |
| action | string | 表示具体的故障类型,仅支持 ec2-stop、ec2-restart、detach-volume | ec2-stop | 是 | ec2-stop |
| mode | string | 指定实验的运行方式,可选择的方式包括:`one`(表示随机选出一个符合条件的 Pod、`all`(表示选出所有符合条件的 Pod、`fixed`(表示选出指定数量且符合条件的 Pod、`fixed-percent`(表示选出占符合条件的 Pod 中指定百分比的 Pod、`random-max-percent`(表示选出占符合条件的 Pod 中不超过指定百分比的 Pod | 无 | 是 | `one` |
| value | string | 取决与 `mode` 的配置,为 `mode` 提供对应的参数。例如,当你将 `mode` 配置为 `fixed-percent` 时,`value` 用于指定 Pod 的百分比。 | 无 | 否 | 1 |
| secretName | string | 指定存储 AWS 认证信息的 Kubernetes Secret 名字 | 无 | 否 | cloud-key-secret |
| awsRegion | string | 指定 AWS 区域 | 无 | 是 | us-east-2 |
| ec2Instance | string | 指定 EC2 实例的 ID | 无 | 是 | your-ec2-instance-id |
| volumeID | string | 当 action 为 detach-volume 必填,指定 EBS 卷的 ID | 无 | 否 | your-volume-id |
| deviceName | string | 当 action 为 detach-volume 必填,指定设备名 | 无 | 否 | /dev/sdf |
| duration | string | 指定实验的持续时间 | 无 | 是 | 30s |

View File

@ -0,0 +1,292 @@
---
title: 模拟磁盘故障
---
本文主要介绍如何使用 Chaosd 模拟磁盘故障场景。使用该功能,你可以在物理机器上模拟磁盘读写负载(通过 [dd](https://man7.org/linux/man-pages/man1/dd.1.html)),或磁盘填充(通过 [dd](https://man7.org/linux/man-pages/man1/dd.1.html),或 [fallocate](https://man7.org/linux/man-pages/man1/fallocate.1.html))。
## 使用命令行模式创建实验
本节介绍如何在命令行模式中创建磁盘故障实验。
在创建磁盘故障实验前,可运行以下命令行查看 Chaosd 支持的磁盘故障类型:
```bash
chaosd attack disk -h
```
输出结果如下所示:
```bash
disk attack related command
Usage:
chaosd attack disk [command]
Available Commands:
add-payload add disk payload
fill fill disk
Flags:
-h, --help help for disk
Global Flags:
--log-level string the log level of chaosd, the value can be 'debug', 'info', 'warn' and 'error'
Use "chaosd attack disk [command] --help" for more information about a command.
```
目前 Chaosd 支持创建磁盘读负载实验、磁盘写负载实验、磁盘填充实验。
### 使用命令行模式模拟磁盘读负载
本模块介绍如何通过命令行创建磁盘读负载实验,提供模拟磁盘读负载相关配置说明与具体示例。
#### 模拟磁盘读负载命令
具体命令如下所示:
```bash
chaosd attack disk add-payload read -h
```
输出结果如下所示:
```bash
read payload
Usage:
chaosd attack disk add-payload read [flags]
Flags:
-h, --help help for read
-p, --path string 'path' specifies the location to read data.If path not provided, payload will read from disk mount on "/"
-n, --process-num uint8 'process-num' specifies the number of process work on reading , default 1, only 1-255 is valid value (default 1)
-s, --size string 'size' specifies how many units of data will read from the file path.'unit' specifies the unit of data, support c=1, w=2, b=512, kB=1000, K=1024, MB=1000*1000,M=1024*1024, , GB=1000*1000*1000, G=1024*1024*1024 BYTESexample : 1M | 512kB
Global Flags:
--log-level string the log level of chaosd, the value can be 'debug', 'info', 'warn' and 'error'
```
#### 模拟磁盘读负载相关配置说明
| 配置项 | 配置缩写 | 说明 | 值 |
| :-- | :-- | :-- | :-- |
| path | p | 指定所读数据的文件路径。如果没有设置此参数,或者设置参数值为空字符串,则从目录“/”所挂载的虚拟磁盘文件读取。根据读取文件的权限不同,会需要你使用一定的权限运行本程序。 | string 类型,默认为"" |
| process-num | n | 指定使用多少个并发运行的 [dd](https://man7.org/linux/man-pages/man1/dd.1.html) 进程执行程序。 | uint8 类型,默认值为 1范围为 1-255 |
| size | s | 指定读取多少数据。size 为 多个 dd 读数据的总量。 | |
#### 模拟磁盘读负载示例
```bash
chaosd attack disk add-payload read -s 1000G -n 7 -p /dev/zero
```
输出结果如下所示:
```bash
andrew@LAPTOP-NUS30NQD:~/chaosd/bin$ ./chaosd attack disk add-payload read -s 1000G -n 7 -p /dev/zero
[2021/05/20 13:54:31.323 +08:00] [INFO] [disk.go:128] ["5242880+0 records in\n5242880+0 records out\n5242880 bytes (5.2 MB, 5.0 MiB) copied, 4.13252 s, 1.3 MB/s\n"]
[2021/05/20 13:54:46.977 +08:00] [INFO] [disk.go:147] ["146285+0 records in\n146285+0 records out\n153390940160 bytes (153 GB, 143 GiB) copied, 15.6513 s, 9.8 GB/s\n"]
[2021/05/20 13:54:47.002 +08:00] [INFO] [disk.go:147] ["146285+0 records in\n146285+0 records out\n153390940160 bytes (153 GB, 143 GiB) copied, 15.6762 s, 9.8 GB/s\n"]
[2021/05/20 13:54:47.004 +08:00] [INFO] [disk.go:147] ["146285+0 records in\n146285+0 records out\n153390940160 bytes (153 GB, 143 GiB) copied, 15.6777 s, 9.8 GB/s\n"]
[2021/05/20 13:54:47.015 +08:00] [INFO] [disk.go:147] ["146285+0 records in\n146285+0 records out\n153390940160 bytes (153 GB, 143 GiB) copied, 15.6899 s, 9.8 GB/s\n"]
[2021/05/20 13:54:47.018 +08:00] [INFO] [disk.go:147] ["146285+0 records in\n146285+0 records out\n153390940160 bytes (153 GB, 143 GiB) copied, 15.6914 s, 9.8 GB/s\n"]
[2021/05/20 13:54:47.051 +08:00] [INFO] [disk.go:147] ["146285+0 records in\n146285+0 records out\n153390940160 bytes (153 GB, 143 GiB) copied, 15.7254 s, 9.8 GB/s\n"]
[2021/05/20 13:54:47.074 +08:00] [INFO] [disk.go:147] ["146285+0 records in\n146285+0 records out\n153390940160 bytes (153 GB, 143 GiB) copied, 15.7487 s, 9.7 GB/s\n"]
Read file /dev/zero successfully, uid: 4bc9b74a-5fe2-4038-b4f2-09ae95b57694
```
### 使用命令行模式模拟磁盘写负载
本模块介绍如何通过命令行创建磁盘写负载实验,提供模拟磁盘写负载相关配置说明与具体示例。
#### 模拟磁盘写负载命令
具体命令如下所示:
```bash
chaosd attack disk add-payload write -h
```
输出结果如下所示:
```bash
write payload
Usage:
chaosd attack disk add-payload write [flags]
Flags:
-h, --help help for write
-p, --path string 'path' specifies the location to fill data in.If path not provided, payload will write into a temp file, temp file will be deleted after writing
-n, --process-num uint8 'process-num' specifies the number of process work on writing , default 1, only 1-255 is valid value (default 1)
-s, --size string 'size' specifies how many units of data will write into the file path.'unit' specifies the unit of data, support c=1, w=2, b=512, kB=1000, K=1024, MB=1000*1000,M=1024*1024, , GB=1000*1000*1000, G=1024*1024*1024 BYTESexample : 1M | 512kB
Global Flags:
--log-level string the log level of chaosd, the value can be 'debug', 'info', 'warn' and 'error'
```
#### 模拟磁盘写负载相关配置说明
| 配置项 | 配置缩写 | 说明 | 值 |
| :-- | :-- | :-- | :-- |
| path | p | 指定所写数据的文件路径。如果没有设置此参数,或者设置参数值为空字符串,则会在程序执行目录下创建一个临时文件。根据写入文件的权限不同,会需要你使用一定的权限运行本程序。 | string 类型,默认为 "" |
| process-num | n | 指定使用多少个并发运行的 [dd](https://man7.org/linux/man-pages/man1/dd.1.html) 进程执行程序。 | uint8 类型。默认值为 1范围为 1-255 |
| size | s | 指定写入多少数据size 为 多个 dd 写数据的总量。 | string 类型,默认为""合法形式为一个整数加一个单位。例如1M、512kB。支持的单位有 c=1、w=2、b=512、kB=1000、K=1024、MB=1000\*1000,M=1024\*1024、GB=1000\*1000\*1000、G=1024\*1024\*1024 BYTE 等。size 不能为 "" 。 |
#### 模拟磁盘写负载示例
```bash
chaosd attack disk add-payload write -s 2G -n 8
```
输出结果如下所示:
```bash
[2021/05/20 14:28:14.452 +08:00] [INFO] [disk.go:128] ["0+0 records in\n0+0 records out\n0 bytes copied, 4.3e-05 s, 0.0 kB/s\n"]
[2021/05/20 14:28:16.793 +08:00] [INFO] [disk.go:147] ["256+0 records in\n256+0 records out\n268435456 bytes (268 MB, 256 MiB) copied, 2.32841 s, 115 MB/s\n"]
[2021/05/20 14:28:16.793 +08:00] [INFO] [disk.go:147] ["256+0 records in\n256+0 records out\n268435456 bytes (268 MB, 256 MiB) copied, 2.3344 s, 115 MB/s\n"]
[2021/05/20 14:28:16.793 +08:00] [INFO] [disk.go:147] ["256+0 records in\n256+0 records out\n268435456 bytes (268 MB, 256 MiB) copied, 2.33312 s, 115 MB/s\n"]
[2021/05/20 14:28:16.793 +08:00] [INFO] [disk.go:147] ["256+0 records in\n256+0 records out\n268435456 bytes (268 MB, 256 MiB) copied, 2.33466 s, 115 MB/s\n"]
[2021/05/20 14:28:16.793 +08:00] [INFO] [disk.go:147] ["256+0 records in\n256+0 records out\n268435456 bytes (268 MB, 256 MiB) copied, 2.33189 s, 115 MB/s\n"]
[2021/05/20 14:28:16.793 +08:00] [INFO] [disk.go:147] ["256+0 records in\n256+0 records out\n268435456 bytes (268 MB, 256 MiB) copied, 2.33752 s, 115 MB/s\n"]
[2021/05/20 14:28:16.793 +08:00] [INFO] [disk.go:147] ["256+0 records in\n256+0 records out\n268435456 bytes (268 MB, 256 MiB) copied, 2.33295 s, 115 MB/s\n"]
[2021/05/20 14:28:16.794 +08:00] [INFO] [disk.go:147] ["256+0 records in\n256+0 records out\n268435456 bytes (268 MB, 256 MiB) copied, 2.3359 s, 115 MB/s\n"]
Write file /home/andrew/chaosd/bin/example255569279 successfully, uid: e66afd86-6f3e-43a0-b161-09447ed84856
```
### 使用命令行模式模拟磁盘填充
本模块介绍如何通过命令行创建磁盘填充实验,提供模拟磁盘填充相关配置说明与具体示例。
#### 模拟磁盘填充命令
```bash
chaosd attack disk fill -h
```
输出结果如下所示:
```bash
fill disk
Usage:
chaosd attack disk fill [flags]
Flags:
-d, --destroy destroy file after filled in or allocated
-f, --fallocate fill disk by fallocate instead of dd (default true)
-h, --help help for fill
-p, --path string 'path' specifies the location to fill data in.If path not provided, a temp file will be generated and deleted immediately after data filled in or allocated
-c, --percent string 'percent' how many percent data of disk will fill in the file path
-s, --size string 'size' specifies how many units of data will fill in the file path.'unit' specifies the unit of data, support c=1, w=2, b=512, kB=1000, K=1024, MB=1000*1000,M=1024*1024, , GB=1000*1000*1000, G=1024*1024*1024 BYTESexample : 1M | 512kB
Global Flags:
--log-level string the log level of chaosd, the value can be 'debug', 'info', 'warn' and 'error'
```
#### 模拟磁盘填充相关配置说明
| 配置项 | 配置缩写 | 说明 | 值 |
| :-- | :-- | :-- | :-- |
| destroy | d | 如果此参数为 true ,则在填充文件后立即删除填充文件 | bool 类型,默认为 false。 |
| fallocate | f | 如果此参数为 true ,则使用 linux 调用 fallocate 来快速申请磁盘空间,此时 size 必须大于 0。如果此参数为 false则使用 linux 调用 dd 以相对较慢速度填充磁盘。 | bool 类型,默认为 true。 |
| path | p | 指定所写数据的文件路径。如果没有设置此参数,或者设置参数值为空字符串,则会在程序执行目录下创建一个临时文件。根据写入文件的权限不同,会需要你使用一定的权限运行本程序。 | string 类型,默认为 "" |
| percent | c | 指定填充多少百分比磁盘。 | string 类型,默认为 "",可以填入 uint 类型的正整数, size 和 percent 不能同时为 "" |
| size | s | 指定写入多少数据。 | string 类型,默认为""合法形式为一个整数加一个单位。例如1M、512kB。支持的单位有 c=1、w=2、b=512、kB=1000、K=1024、MB=1000\*1000,M=1024\*1024、GB=1000\*1000\*1000、G=1024\*1024\*1024 BYTE 等。size 和 percent 不能同时为 ""。 |
#### 模拟磁盘填充示例
```bash
chaosd attack disk fill -c 50 -d
```
输出结果如下所示:
```bash
[2021/05/20 14:30:02.943 +08:00] [INFO] [disk.go:215]
Fill file /home/andrew/chaosd/bin/example623832242 successfully, uid: 097b4214-8d8e-46ad-8768-c3e0d8cbb326
```
## 使用服务模式创建实验
本节介绍如何使用服务模式创建磁盘故障实验。
### 使用服务模式模拟磁盘读负载
本模块介绍使用服务模式创建磁盘读负载实验时所涉及到的相关配置说明与实验创建示例。
#### 模拟磁盘读负载相关参数说明
| 参数 | 说明 | 值 |
| :-- | :-- | :-- |
| action | 实验的行为 | 设置为 "read-payload" |
| path | 指定所读数据的文件路径。如果没有设置此参数,或者设置参数值为空字符串,则从目录“/”所挂载的虚拟磁盘文件读取。根据读取文件的权限不同,会需要你使用一定的权限运行本程序。 | string 类型,默认为"" |
| process-num | 指定使用多少个并发运行的 [dd](https://man7.org/linux/man-pages/man1/dd.1.html) 进程执行程序。 | uint8 类型,默认值为 1范围为 1-255 |
| size | 指定读取多少数据。size 为 多个 dd 读数据的总量。 | string 类型,默认为""必须要设置。合法形式为一个整数加一个单位。例如1M、512kB。支持的单位有 c=1、w=2、b=512、kB=1000、K=1024、MB=1000\*1000,M=1024\*1024、GB=1000\*1000\*1000、G=1024\*1024\*1024 BYTE 等。 |
#### 模拟磁盘读负载示例
```bash
curl -X POST 172.16.112.130:31767/api/attack/disk -H "Content-Type:application/json" -d '{"action":"read-payload","path":"/dev/zero", "payload-process-num":7,"size":"1000G"}'
```
输出结果如下所示:
```bash
{"status":200,"message":"attack successfully","uid":"a551206c-960d-4ac5-9056-518e512d4d0d"}
```
读负载为一次性操作,实验不需要恢复。
### 服务模式模拟磁盘写负载
本模块介绍使用服务模式创建磁盘写负载实验时所涉及到的相关配置说明与实验创建示例。
#### 模拟磁盘写负载相关参数说明
| 参数 | 说明 | 值 |
| :-- | :-- | :-- |
| action | 实验的行为 | 设置为 "write-payload" |
| path | 指定所写数据的文件路径。如果没有设置此参数,或者设置参数值为空字符串,则会在程序执行目录下创建一个临时文件。根据写入文件的权限不同,会需要你使用一定的权限运行本程序。 | string 类型,默认为 "" |
| process-num | 指定使用多少个并发运行的 [dd](https://man7.org/linux/man-pages/man1/dd.1.html) 进程执行程序。 | uint8 类型。默认值为 1范围为 1-255 |
| size | 指定写入多少数据size 为 多个 dd 写数据的总量。 | string 类型,默认为""合法形式为一个整数加一个单位。例如1M、512kB。支持的单位有 c=1、w=2、b=512、kB=1000、K=1024、MB=1000\*1000,M=1024\*1024、GB=1000\*1000\*1000、G=1024\*1024\*1024 BYTE 等。size 不能为 "" 。 |
#### 模拟磁盘写负载示例
```bash
curl -X POST 172.16.112.130:31767/api/attack/disk -H "Content-Type:application/json" -d '{"action":"write-payload","path":"/tmp/test", "payload-process-num":7,"size":"1000G"}'
```
输出如下所示:
```bash
{"status":200,"message":"attack successfully","uid":"a551206c-960d-4ac5-9056-518e512d4d0d"}
```
### 使用服务模式模拟磁盘填充
本模块介绍使用服务模式创建磁盘填充实验时所涉及到的相关配置说明与实验创建示例。
#### 模拟磁盘填充相关参数说明
| 参数 | 说明 | 值 |
| :-- | :-- | :-- |
| action | 实验的行为 | 设置为 "fill" |
| destroy | 如果此参数为 true ,则在填充文件后立即删除填充文件 | bool 类型,默认为 false。 |
| fill_by_fallocate | 如果此参数为 true ,则使用 linux 调用 fallocate 来快速申请磁盘空间,此时 size 必须大于 0。如果此参数为 false则使用 linux 调用 dd 以相对较慢速度填充磁盘。 | bool 类型,默认为 true。 |
| path | 指定所写数据的文件路径。如果没有设置此参数,或者设置参数值为空字符串,则会在程序执行目录下创建一个临时文件。根据写入文件的权限不同,会需要你使用一定的权限运行本程序。 | string 类型,默认为 "" |
| percent | 指定填充多少百分比磁盘。 | string 类型,默认为 "",可以填入 uint 类型的正整数size 和 percent 不能同时为 "" |
| size | 指定写入多少数据。 | string 类型,默认为""合法形式为一个整数加一个单位。例如1M、512kB。支持的单位有 c=1、w=2、b=512、kB=1000、K=1024、MB=1000\*1000,M=1024\*1024、GB=1000\*1000\*1000、G=1024\*1024\*1024 BYTE 等。size 和 percent 不能同时为 ""。 |
#### 模拟磁盘填充示例
```bash
curl -X POST 172.16.112.130:31767/api/attack/disk -H "Content-Type:application/json" -d '{"action":"fill","path":"/tmp/test", "fill-by-fallocate":true,"percent":"50"}'
```
输出如下所示:
```bash
{"status":200,"message":"attack successfully","uid":"a551206c-960d-4ac5-9056-518e512d4d0d"}
```

View File

@ -0,0 +1,101 @@
---
title: 模拟 DNS 故障
---
本文档主要介绍如何在 Chaos Mesh 中创建 DNSChaos 混沌实验,以模拟 DNS 故障。
## DNSChaos 介绍
DNSChaos 可以用于模拟错误的 DNS 响应,例如在收到 DNS 请求时返回错误,或者返回随机的 IP 地址。
## 部署 Chaos DNS Service
在使用 Chaos Mesh 创建 DNSChaos 混沌实验前,你需要部署一个专门的 DNS 服务用于注入故障,命令如下:
```bash
helm upgrade chaos-mesh chaos-mesh/chaos-mesh --namespace=chaos-testing --set dnsServer.create=true
```
执行后,可以通过如下命令检查 DNS 服务的状态是否正常:
```bash
kubectl get pods -n chaos-testing -l app.kubernetes.io/component=chaos-dns-server
```
确认 Pod 的状态为 `Running` 即可。
## 注意事项
1. 目前 DNSChaos 只支持 DNS 记录类型 `A``AAAA`
2. Chaos DNS 服务运行的带有 [k8s_dns_chaos](https://github.com/chaos-mesh/k8s_dns_chaos) 插件的 CoreDNS。如果 Kubernetes 集群本身的 CoreDNS 服务包含一些特殊配置,你可以通过编辑 configMap `dns-server-config`,使 Chaos DNS 服务的配置与 K8s CoreDNS 服务的配置一致,编辑命令如下:
```bash
kubectl edit configmap dns-server-config -n chaos-testing
```
## 使用 Dashboard 方式创建实验
1. 单击实验页面中的**新的实验**按钮创建实验:
![创建实验](./img/create-new-exp.png)
2. 在“选择目标”处选择 “DNS 故障”,然后选择具体行为,例如 `ERROR`,最后填写匹配规则:
![DNSChaos 实验](./img/dnschaos-exp.png)
图中配置的匹配规则可以对域名 `google.com`、`chaos-mesh.org` 和 `github.com` 生效,即对这三个域名发送 DNS 请求将返回错误。具体的匹配规则填写方式,参考[配置说明](#配置说明)中 `patterns` 字段的介绍。
3. 填写实验信息,指定实验范围以及实验计划运行时间:
![实验信息](./img/exp-info.png)
4. 提交实验。
## 使用 YAML 方式创建实验
1. 将实验配置写入到文件 `dnschaos.yaml` 中,内容如下所示:
```yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: DNSChaos
metadata:
name: dns-chaos-example
namespace: chaos-testing
spec:
action: random
mode: all
patterns:
- google.com
- chaos-mesh.*
- github.?om
selector:
namespaces:
- busybox
```
该实验配置可以对域名 `google.com`、`chaos-mesh.org` 和 `github.com` 生效,对这三个域名发送 DNS 请求将返回随机 IP 地址。具体的匹配规则填写方式,参考[配置说明](#配置说明)中 `patterns` 字段的介绍。
2. 使用 kubectl 创建实验,命令如下:
```bash
kubectl apply -f dnschaos.yaml
```
### 配置说明
| 参数 | 类型 | 说明 | 默认值 | 是否必填 | 示例 |
| :-- | :-- | :-- | :-- | :-- | :-- |
| action | string | 定义 DNS 故障的行为,值可以为 `random``error`。当值为 `random` 时, DNS 服务返回随机的 IP 地址;当值为 `error` 时 DNS 服务返回错误 | 无 | 是 | `random``error` |
| patterns | string 数组 | 选择匹配故障行为的域名模版, 支持占位符 `?` 以及通配符 `*` | [] | 否 | `google.com``chaos-mesh.org``github.com` |
| mode | string | 指定实验的运行方式,可选择的方式包括:`one`(表示随机选出一个符合条件的 Pod、`all`(表示选出所有符合条件的 Pod、`fixed`(表示选出指定数量且符合条件的 Pod、`fixed-percent`(表示选出占符合条件的 Pod 中指定百分比的 Pod、`random-max-percent`(表示选出占符合条件的 Pod 中不超过指定百分比的 Pod | 无 | 是 | `one` |
| value | string | 取决与 `mode` 的配置,为 `mode` 提供对应的参数。例如,当你将 `mode` 配置为 `fixed-percent` 时,`value` 用于指定 Pod 的百分比 | 无 | 否 | 1 |
| selector | struct | 指定注入故障的目标 Pod详情请参考[定义实验范围](./define-chaos-experiment-scope.md) | 无 | 是 | |
:::note 注意
- `patterns` 配置中的通配符必须位于字符串的尾部,例如 `chaos-mes*.org` 是不合法的配置。
- 当 `patterns` 没有配置时,默认对所有域名注入故障。
:::

View File

@ -0,0 +1,173 @@
---
title: 模拟 GCP 故障
---
本文档介绍如何使用 Chaos Mesh 为 GCP 节点注入故障,并提供 Dashboard 和 YAML 文件两种方式用于创建 GCPChaos 实验。
## GCPChaos 介绍
GCPChaos 是 Chaos Mesh 中的一种故障类型。通过创建 GCPChaos 类型的混沌实验,你可以模拟指定的 GCP 实例发生故障的情景。目前GCPChaos 支持模拟以下故障类型:
- **Node Stop**:使指定的 GCP 实例进入停止状态。
- **Node Reset**:重置指定的 GCP 实例。
- **Disk Loss**:从指定的 GCP 实例中卸载存储卷。
## 创建 Secret 文件
为了方便地连接 GCP 集群,你可以提前创建一个 Kubernetes Secret 文件用于存储认证相关信息。
以下是一个 `secret` 文件示例:
```yaml
apiVersion: v1
kind: Secret
metadata:
name: cloud-key-secret
namespace: chaos-testing
type: Opaque
stringData:
service_account: your-gcp-service-account-base64-encode
```
- **name** 表示 Kubernetes Secret 对象的名字。
- **namespace** 表示 Kubernetes Secret 对象的命名空间。
- **service_account** 存储 GCP 集群的服务账号。请注意,你需要对 GCP 集群的服务账号进行 [Base64](https://zh.wikipedia.org/wiki/Base64) 编码。
## 使用 Dashboard 方式创建实验
:::note 注意
在使用 Dashboard 方式创建实验前,请确保满足以下条件:
1. 已安装 Dashboard。
2. 可以通过 **kubectl port-forward** 方式访问 Dashboard
```bash
kubectl port-forward -n chaos-testing svc/chaos-dashboard 2333:2333
```
接着你可以在浏览器通过[`http://localhost:2333`](http://localhost:2333)访问 Dashboard 。
:::
1. 单击实验页面中的**新的实验**按钮创建实验。
![img](./img/create-pod-chaos-on-dashborad-1_zh.jpg)
2. 在**选择目标**处选择 **GCP 故障**,并选择具体行为,例如 **STOP NODE**
![img](./img/create-gcp-chaos-on-dashborad-2_zh.jpg)
3. 填写实验信息,指定实验范围以及实验计划运行时间。
![img](./img/create-gcp-chaos-on-dashborad-3_zh.jpg)
![img](./img/create-gcp-chaos-on-dashborad-4_zh.jpg)
4. 提交实验。
## 使用 YAML 方式创建实验
### node-stop 示例
1. 将实验配置写入到文件 `gcpchaos-node-stop.yaml` 中,内容如下所示:
```yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: GCPChaos
metadata:
name: node-stop-example
namespace: chaos-testing
spec:
action: node-stop
secretName: 'cloud-key-secret'
project: 'your-project'
zone: 'your-zone'
instance: 'your-instance'
duration: '5m'
```
依据此配置示例Chaos Mesh 将向指定的 GCP 实例中注入 node-stop 故障,使该 GCP 实例在 5 分钟时间内处于不可用的状态。
更多关于停止 GCP 实例的信息,请参考[停止 GCP 实例](https://cloud.google.com/compute/docs/instances/stop-start-instance)。
2. 使用 kubectl 创建实验,命令如下:
```bash
kubectl apply -f gcpchaos-node-stop.yaml
```
### node-reset 示例
1. 将实验配置写入到文件 `gcpchaos-node-reset.yaml` 中,内容如下所示:
```yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: GCPChaos
metadata:
name: node-reset-example
namespace: chaos-testing
spec:
action: node-reset
secretName: 'cloud-key-secret'
project: 'your-project'
zone: 'your-zone'
instance: 'your-instance'
duration: '5m'
```
依据此配置示例Chaos Mesh 将向指定的 GCP 实例中注入 node-reset 故障,使该 GCP 实例重置一次。
更多关于重置 GCP 实例的信息,请参考[重置 GCP 实例](https://cloud.google.com/compute/docs/instances/stop-start-instance#resetting_an_instance)。
2. 使用 kubectl 创建实验,命令如下:
```bash
kubectl apply -f gcpchaos-node-reset.yaml
```
### disk-loss 示例
1. 将实验配置写入到文件 `gcpchaos-disk-loss.yaml` 中,内容如下所示:
```yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: GCPChaos
metadata:
name: disk-loss-example
namespace: chaos-testing
spec:
action: disk-loss
secretName: 'cloud-key-secret'
project: 'your-project'
zone: 'your-zone'
instance: 'your-instance'
deviceNames: ['disk-name']
duration: '5m'
```
依据此配置示例Chaos Mesh 将向指定的 GCP 实例中注入 disk-loss 故障,使该 GCP 实例在 5 分钟内与指定存储设备分离。
更多关于分离 GCP 存储设备的信息,请参考 [分离 GCP 存储](https://cloud.google.com/compute/docs/reference/rest/v1/instances/detachDisk)。
2. 使用 kubectl 创建实验,命令如下:
```bash
kubectl apply -f gcpchaos-disk-loss.yaml
```
### 字段说明
下表介绍以上 YAML 配置文件中的字段。
| 参数 | 类型 | 说明 | 默认值 | 是否必填 | 示例 |
| --- | --- | --- | --- | --- | --- |
| action | string | 指定故障类型可选择的类型包括node-stop、node-reset、disk-loss | node-stop | 是 | node-stop |
| mode | string | 指定实验的运行方式,可选择的方式包括:`one`(表示随机选出一个符合条件的 Pod、`all`(表示选出所有符合条件的 Pod、`fixed`(表示选出指定数量且符合条件的 Pod、`fixed-percent`(表示选出占符合条件的 Pod 中指定百分比的 Pod、`random-max-percent`(表示选出占符合条件的 Pod 中不超过指定百分比的 Pod | 无 | 是 | `one` |
| value | string | 取决与 `mode` 的配置,为 `mode` 提供对应的参数。例如,当你将 `mode` 配置为 `fixed-percent` 时,`value` 用于指定 Pod 的百分比。 | 无 | 否 | 1 |
| secretName | string | 指定存储 GCP 认证信息的 Kubernetes Secret 名字 | 无 | 否 | cloud-key-secret |
| project | string | 指定 GCP 项目名 | 无 | 是 | your-project |
| zone | string | 指定 GCP 实例区域 | 无 | 是 | us-central1-a |
| instance | string | 指定 GCP 实例的 ID | 无 | 是 | your-gcp-instance-id |
| deviceNames | []string | 当 action 为 disk-loss 必填,指定设备磁盘 ID | 无 | 否 | ["your-disk-id"] |
| duration | string | 指定实验的持续时间 | 无 | 是 | 30s |

View File

@ -0,0 +1,191 @@
---
title: 模拟压力场景
---
本文主要介绍如何使用 Chaosd 模拟压力场景。该功能通过使用 [stress-ng](https://wiki.ubuntu.com/Kernel/Reference/stress-ng) 在主机上生成 CPU 或者内存压力,支持通过命令行模式或服务模式创建压力实验。
## 使用命令行模式创建压力实验
本节介绍如何在命令行模式中创建压力实验。
在创建压力实验前,可运行以下命令查看 Chaosd 支持的压力实验类型:
```bash
chaosd attack stress --help
```
输出如下所示:
```bash
Stress attack related commands
Usage:
chaosd attack stress [command]
Available Commands:
cpu continuously stress CPU out
mem continuously stress virtual memory out
Flags:
-h, --help help for stress
Global Flags:
--log-level string the log level of chaosd, the value can be 'debug', 'info', 'warn' and 'error'
Use "chaosd attack stress [command] --help" for more information about a command.
```
目前 Chaosd 支持创建 CPU 压力实验和内存压力实验。
### 模拟 CPU 压力场景
#### 模拟 CPU 压力命令
运行以下命令可查看模拟 CPU 压力场景支持的配置:
```bash
chaosd attack stress cpu --help
```
输出如下所示:
```bash
continuously stress CPU out
Usage:
chaosd attack stress cpu [options] [flags]
Flags:
-h, --help help for cpu
-l, --load int Load specifies P percent loading per CPU worker. 0 is effectively a sleep (no load) and 100 is full loading. (default 10)
-o, --options strings extend stress-ng options.
-w, --workers int Workers specifies N workers to apply the stressor. (default 1)
Global Flags:
--log-level string the log level of chaosd, the value can be 'debug', 'info', 'warn' and 'error'
```
#### 模拟 CPU 压力相关配置说明
| 配置项 | 配置缩写 | 说明 | 值 |
| :-- | :-- | :-- | :-- |
| load | l | 指定使用每个 worker 占用 CPU 负载的百分比。如果为 0则表示为一个空负载为 100 则表示满负载 | int 类型,取值范围为 0 到 100 默认值为 10 |
| workers | w | 指定用于生成 CPU 压力的 worker 数量 | int 类型,默认值为 1 |
| options | o | stress-ng 的其他参数设置,一般情况下不需要配置 | string 类型,默认值为 "" |
#### 模拟 CPU 压力示例
```bash
chaosd attack stress cpu --workers 2 --load 10
```
输出如下所示:
```bash
[2021/05/12 03:38:33.698 +00:00] [INFO] [stress.go:66] ["stressors normalize"] [arguments=" --cpu 2 --cpu-load 10"]
[2021/05/12 03:38:33.702 +00:00] [INFO] [stress.go:82] ["Start stress-ng process successfully"] [command="/usr/bin/stress-ng --cpu 2 --cpu-load 10"] [Pid=27483]
Attack stress cpu successfully, uid: 4f33b2d4-aee6-43ca-9c43-0f12867e5c9c
```
### 模拟内存压力场景
#### 模拟内存压力命令
运行以下命令可查看模拟内存压力场景支持的配置:
```bash
chaosd attack stress mem --help
```
输出如下所示:
```bash
continuously stress virtual memory out
Usage:
chaosd attack stress mem [options] [flags]
Flags:
-h, --help help for mem
-o, --options strings extend stress-ng options.
-s, --size string Size specifies N bytes consumed per vm worker, default is the total available memory. One can specify the size as % of total available memory or in units of B, KB/KiB, MB/MiB, GB/GiB, TB/TiB..
Global Flags:
--log-level string the log level of chaosd, the value can be 'debug', 'info', 'warn' and 'error'
```
#### 模拟内存压力相关配置说明
| 配置项 | 配置缩写 | 说明 | 值 |
| :-- | :-- | :-- | :-- |
| size | s | 指定每个 vm worker 占用内存的大小 | string 类型,支持使用单位 BKB/KiBMB/MiBGB/GiBTB/TiB 来设置占用的内存大小。如果不设置,则默认占用所有可用的内存。 |
| options | o | stress-ng 的其他参数设置,一般情况下不需要配置 | string 类型,默认值为 "" |
#### 模拟内存压力示例
```bash
chaosd attack stress mem --workers 2 --size 100M
```
输出如下所示:
```bash
[2021/05/12 03:37:19.643 +00:00] [INFO] [stress.go:66] ["stressors normalize"] [arguments=" --vm 2 --vm-keep --vm-bytes 100000000"]
[2021/05/12 03:37:19.654 +00:00] [INFO] [stress.go:82] ["Start stress-ng process successfully"] [command="/usr/bin/stress-ng --vm 2 --vm-keep --vm-bytes 100000000"] [Pid=26799]
Attack stress mem successfully, uid: c2bff2f5-3aac-4ace-b7a6-322946ae6f13
```
## 使用服务模式创建压力实验
要使用服务模式创建实验,请进行以下操作:
1. 以服务模式运行 chaosd。
```bash
chaosd server --port 31767
```
2. 向 chaosd 服务的路径 /api/attack/stress 发送 HTTP POTST 请求。 `bash curl -X POST 172.16.112.130:31767/api/attack/stress -H "Content-Type:application/json" -d '{fault-configuration}' ` 其中 `fault-configuration` 需要按照故障类型进行配置,对应的配置参数请参考下文中各个类型故障的相关参数说明和命令示例。 在运行实验时,请注意保存实验的 uid 信息,当要结束 uid 对应的实验时,需要向 chaosd 服务的路径 /api/attack/{uid} 发送 HTTP DELETE 请求。
### 服务模式模拟 CPU 压力场景
#### 模拟 CPU 压力相关参数说明
| 参数 | 说明 | 值 |
| :-- | :-- | :-- |
| action | 实验的行为 | 设置为 "cpu" |
| load | 指定使用每个 worker 占用 CPU 负载的百分比。如果为 0则表示为一个空负载为 100 则表示满负载 | int 类型,取值范围为 0 到 100 默认值为 10 |
| workers | 指定用于生成 CPU 压力的 worker 数量 | int 类型,默认值为 1 |
| options | stress-ng 的其他参数设置,一般情况下不需要配置 | string 类型,默认值为 "" |
#### 服务模式模拟 CPU 压力示例
```bash
curl -X POST 172.16.112.130:31767/api/attack/stress -H "Content-Type:application/json" -d '{"load":10, "action":"cpu","workers":1}'
```
输出如下所示:
```bash
{"status":200,"message":"attack successfully","uid":"c3c519bf-819a-4a7b-97fb-e3d0814481fa"}
```
### 服务模式模拟内存压力场景
#### 模拟内存压力相关参数说明
| 参数 | 说明 | 值 |
| :-- | :-- | :-- |
| action | 实验的行为 | 设置为 "mem" |
| size | 指定每个 vm worker 占用内存的大小 | string 类型,支持使用单位 BKB/KiBMB/MiBGB/GiBTB/TiB 来设置占用的内存大小。如果不设置,则默认占用所有可用的内存。 |
| options | stress-ng 的其他参数设置,一般情况下不需要配置 | string 类型,默认值为 "" |
#### 服务模式模拟内存压力示例
```bash
curl -X POST 172.16.112.130:31767/api/attack/stress -H "Content-Type:application/json" -d '{"size":"100M", "action":"mem"}'
```
输出如下所示:
```bash
{"status":200,"message":"attack successfully","uid":"a551206c-960d-4ac5-9056-518e512d4d0d"}
```

View File

@ -0,0 +1,89 @@
---
title: 模拟压力场景
---
## StressChaos 介绍
Chaos Mesh 提供的 StressChaos 实验类型可用于模拟容器内压力的场景。本文档介绍如何创建 StressChaos 实验以及相关的配置文件说明。
你可以在 Chaos Dashboard 中创建实验,也可以使用 YAML 配置文件的方式创建实验。
## 使用 Chaos Dashboard 创建实验
1. 打开 Chaos Dashboard 面板,单击实验页面中“**新的实验**”按钮创建实验:
![创建实验](./img/create-new-exp.png)
2. 在“**选择目标**”区域选择“**压力测试**”,然后填写实验内容,配置字段详见[配置说明](#字段说明)中的介绍。
![StressChaos 实验](./img/stresschaos-exp.png)
3. 填写实验信息,指定实验范围以及计划的实验运行时间:
![实验信息](./img/exp-info.png)
4. 提交实验。
## 使用 YAML 方式创建实验
1. 将实验配置写入到 YAML 配置文件中。本文档以 `memory-stress.yaml` 文件为例,内容如下所示:
```yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: StressChaos
metadata:
name: memory-stress-example
namespace: chaos-testing
spec:
mode: one
selector:
labelSelectors:
'app': 'app1'
stressors:
memory:
workers: 4
size: '256MB'
```
该实验配置会在选中容器中创建进程,不断分配和在内存中进行读写,最多占用 256MB 内存。
2. 准备好配置文件后,使用 `kubectl` 创建实验,命令如下:
```bash
kubectl apply -f memory-stress.yaml
```
### 字段说明
以上 YAML 配置文件中的字段说明如下:
| 参数 | 类型 | 说明 | 默认值 | 是否必填 | 示例 |
| --- | --- | --- | --- | --- | --- |
| duration | string | 指定具体实验的持续时间 | 无 | 是 | `30s` |
| stressors | [Stressors](#stressors) | 指定 CPU 或内存压力的参数 | 无 | 否 | |
| stressngStressors | string | 指定 stress-ng 的参数来达到更丰富的压力注入 | 无 | 否 | `--clone 2` |
| mode | string | 指定实验的运行方式,可选择的方式包括:`one`(表示随机选出一个符合条件的 Pod、`all`(表示选出所有符合条件的 Pod、`fixed`(表示选出指定数量且符合条件的 Pod、`fixed-percent`(表示选出占符合条件的 Pod 中指定百分比的 Pod、`random-max-percent`(表示选出占符合条件的 Pod 中不超过指定百分比的 Pod | 无 | 是 | `one` |
| value | string | 取决于 `mode` 的配置,为 `mode` 提供对应的参数。例如,当你将 `mode` 配置为 `fixed-percent` 时,`value` 用于指定 Pod 的百分比 | 无 | 否 | 1 |
| containerNames | []string | 指定注入的容器名称 | 无 | 否 | `["nginx"]` |
| selector | struct | 指定注入故障的目标 Pod详情请参考[定义实验范围](./define-chaos-experiment-scope.md) | 无 | 是 | |
#### Stressors
| 参数 | 类型 | 说明 | 默认值 | 是否必填 | 示例 |
| ------ | --------------------------------- | ------------------- | ------ | -------- | ---- |
| memory | [MemoryStressor](#memorystressor) | 指定内存压力的参数 | 无 | 否 | |
| cpu | [CPUStressor](#cpustressor) | 指定 CPU 压力的参数 | 无 | 否 | |
##### MemoryStressor
| 参数 | 类型 | 说明 | 默认值 | 是否必填 | 示例 |
| ------- | ------ | ---------------------------- | ------ | -------- | ------- |
| workers | int | 指定施加内存压力的线程个数 | | 是 | `1` |
| size | string | 指定总共最多可使用的内存大小 | | 否 | `256MB` |
##### CPUStressor
| 参数 | 类型 | 说明 | 默认值 | 是否必填 | 示例 |
| ------- | ---- | --------------------------------------------------------------- | ------ | -------- | ---- |
| workers | int | 指定施加内存压力的线程个数 | | 是 | `1` |
| load | int | 指定占据 CPU 的百分比。0 意味着睡眠毫无负载100 意味着满负载 | | 否 | `50` |

View File

@ -0,0 +1,45 @@
---
title: 模拟主机故障
---
## 模拟主机故障
Chaosd 支持模拟主机关机故障。本文档介绍如何使用命令行模拟主机关机故障。
### 创建实验
要创建实验模拟主机关机故障,执行以下命令:
```bash
chaosd attack host shutdown
```
输出示例如下:
```bash
chaosd attack host shutdown
Shutdown successfully, uid: 4bc9b74a-5fe2-4038-b4f3-09ae95b57694
```
执行该命令后,你的主机会在所有进程关闭后关机。
要查看 Chaosd 支持哪些类型的主机关机实验,执行以下命令:
```bash
chaosd attack host shutdown -h
```
输出如下所示:
```bash
shutdowns system, this action will trigger shutdown of the host machine
Usage:
chaosd attack host shutdown [flags]
Flags:
-h, --help help for shutdown
Global Flags:
--log-level string the log level of chaosd, the value can be 'debug', 'info', 'warn' and 'error'
```

View File

@ -0,0 +1,165 @@
---
title: 模拟 HTTP 故障
---
本文档介绍如何在 Chaos Mesh 中通过创建 HTTPChaos 实验模拟 HTTP 故障。
## HTTPChaos 简介
HTTPChaos 是 Chaos Mesh 中的一种故障类型。通过创建 HTTPChaos 实验,你可以模拟 **HTTP 服务端**在请求或响应过程中发生故障的场景。目前HTTPChaos 支持模拟以下故障类型:
- `abort`:中断服务端的连接
- `delay`:为目标过程注入延迟
- `replace`:替换请求报文或者响应报文的部分内容
- `patch`:给请求报文或响应报文添加额外内容
HTTPChaos 支持多种类型故障的组合。在创建 HTTPChaos 实验时,如果同时配置了多种 HTTP 故障类型,实验运行时注入故障的优先级(顺序)固定为 `abort` -> `delay` -> `replace` -> `patch`。其中 `abort` 故障会导致短路,直接中断此次连接。
关于 HTTPChaos 详细的配置介绍,请参见[字段说明](#字段说明)部分。
## 注意事项
在注入 HTTPChaos 相关故障之前,请注意以下事项:
- 确保目标 Pod 上没有运行 Chaos Mesh 的 Control Manager。
- 确保目标服务禁用了 HTTPS 访问,因为 HTTPChaos 暂不支持注入 HTTPS 连接。
- 为使 HTTPChaos 注入生效,尽量避免复用客户端的 TCP socket。因为在注入故障前建立的 TCP socket 上进行 HTTP 请求不受 HTTPChaos 影响。
- 在生产环境下谨慎使用非幂等语义请求(例如大多数 POST 请求)。若使用了这类请求,注入故障后可能无法通过重复请求使目标服务恢复正常状态。
## 使用 Dashboard 创建实验
1. 单击实验页面中的“新的实验”按钮创建实验:
![创建实验](./img/create-new-exp.png)
2. 在“选择目标”处选择“HTTP 故障”,然后选择具体行为(如 `RESPONSE ABORT`),并填写具体配置:
![创建实验](./img/create-new-httpchaos.png)
如上图实例,点击提交即完成了对 80 端口所有请求的响应中断配置。
## 使用 YAML 文件创建实验
Chaos Mesh 也支持使用 YAML 配置文件创建 HTTPChaos 实验。在 YAML 配置文件中,你可以模拟一种 HTTP 故障类型,也可以模拟多种 HTTP 故障的组合。
### `abort` 示例
1. 将实验配置写入到 `http-abort-failure.yaml` 文件中,内容示例如下:
```yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: HTTPChaos
metadata:
name: test-http-chaos
spec:
mode: all
selector:
labelSelectors:
app: nginx
target: Request
port: 80
method: GET
path: /api
abort: true
duration: 5m
```
依据此配置示例Chaos Mesh 将向指定的 Pod 中注入 `abort` 故障 5 分钟,故障注入期间该 Pod 的 80 端口 `/api` 路径的 GET 请求会被中断。
2. 使用 `kubectl` 创建实验,命令如下:
```bash
kubectl apply -f ./http-abort-failure.yaml
```
### 其它故障组合示例
1. 将实验配置写入到 `http-failure.yaml` 文件中,内容示例如下:
```yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: HTTPChaos
metadata:
name: test-http-chaos
spec:
mode: all
selector:
labelSelectors:
app: nginx
target: Request
port: 80
method: GET
path: /api/*
delay: 10s
replace:
path: /api/v2/
method: DELETE
patch:
headers:
- ['Token', '<one token>']
- ['Token', '<another token>']
body:
type: JSON
value: '{"foo": "bar"}'
duration: 5m
```
依据此配置示例Chaos Mesh 将向指定的 Pod 中分别注入 `delay` 故障、`replace` 故障、`patch` 故障。
2. 使用 `kubectl` 创建实验,命令如下:
```bash
kubectl apply -f ./http-failure.yaml
```
## 字段说明
### 通用字段说明
通用字段指故障注入的目标过程为 Request 或 Response 时均有意义的字段。
| 参数 | 类型 | 说明 | 默认值 | 是否必填 | 示例 |
| --- | --- | --- | --- | --- | --- |
| mode | string | 指定实验的运行方式,可选择的方式包括:`one`(表示随机选出一个符合条件的 Pod、`all`(表示选出所有符合条件的 Pod、`fixed`(表示选出指定数量且符合条件的 Pod、`fixed-percent`(表示选出占符合条件的 Pod 中指定百分比的 Pod、`random-max-percent`(表示选出占符合条件的 Pod 中不超过指定百分比的 Pod | 无 | 是 | `one` |
| value | string | 取决于 `mode` 的取值,为 `mode` 提供参数 | 无 | 否 | 1 |
| target | string | 指定故障注入的目标过程为 `Request``Response`,需要同时配置[与 `target` 相关的字段](#与-target-相关的字段说明) | | 是 | Request |
| port | int32 | 目标服务监听的 TCP 端口 | | 是 | 80 |
| path | string | 目标请求的 URI 路径,支持[通配符](https://www.wikiwand.com/en/Matching_wildcards) | 默认对所有路径生效 | 是 | /api/\* |
| method | string | 目标请求的 HTTP method | 默认对所有方法生效 | 否 | GET |
| request_headers | map[string]string | 目标请求的请求头匹配 | 默认对所有请求生效 | 否 | Content-Type: application/json |
| abort | bool | 是否注入连接中断故障 | false | 否 | true |
| delay | string | 指定延迟故障的时间 | 0 | 否 | 10s |
| replace.headers | map[string]string | 指定请求头或响应头替换故障中用于替换的键值对 | | 否 | Content-Type: application/xml |
| replace.body | []byte | 指定请求体或响应体替换故障的内容base64 编码) | | 否 | eyJmb28iOiAiYmFyIn0K |
| patch.headers | [][]string | 指定请求头或响应头附加故障中附加的键值对 | | 否 | - [Set-Cookie, one cookie] |
| patch.body.type | string | 指定请求体或响应体附加故障的类型,目前只支持 [`JSON`](https://tools.ietf.org/html/rfc7396) | | 否 | JSON |
| patch.body.value | string | 指定请求体或响应体附加故障的故障内容 | | 否 | "{"foo": "bar"}" |
| duration | string | 指定具体实验的持续时间 | | 是 | 30s |
| scheduler | string | 指定具体实验的运行时间调度规则 | | 否 | 5 \* \* \* \* |
### 与 `target` 相关的字段说明
### Request 专用字段说明
Request 专用字段是指故障注入的目标过程为 Request (即 `target` 设置为 `Request` 时有意义的字段。
| 参数 | 类型 | 说明 | 默认值 | 是否必填 | 示例 |
| ---------------- | ----------------- | ------------------------------------- | ------ | -------- | ------------ |
| replace.path | string | 指定 URI 路径替换内容 | | 否 | /api/v2/ |
| replace.method` | string | 指定请求 HTTP 方法的替换内容 | | 否 | DELETE |
| replace.queries` | map[string]string | 指定 URI query 的替换键值对 | | 否 | foo: bar |
| patch.queries` | [][]string | 指定 URI query 附加故障中附加的键值对 | | 否 | - [foo, bar] |
### Response 专用字段说明
Response 专用字段是指故障注入的目标过程为 Response (即 `target` 设置为 `Response` 时有意义的字段。
| 参数 | 类型 | 说明 | 默认值 | 是否必填 | 示例 |
| --- | --- | --- | --- | --- | --- |
| code | int32 | 目标响应的状态码 | 默认对所有状态码生效 | 否 | 200 |
| response_headers | map[string]string | 目标响应的响应头匹配 | 默认对所有响应生效 | 否 | Content-Type: application/json |
| replace.code | int32 | 指定响应状态码的替换内容 | | 否 | 404 |
## 本地调试
如果你不确定某种故障的效果,也可以使用 [rs-tproxy](https://github.com/chaos-mesh/rs-tproxy) 在本地测试相应功能。Chaos Mesh 同样使用 rs-tproxy 实现 HTTPChaos。

View File

@ -0,0 +1,315 @@
---
title: 模拟文件 I/O 故障
---
本文档主要介绍如何在 Chaos Mesh 中创建 IOChaos 混沌实验。
## IOChaos 介绍
IOChaos 是 Chaos Mesh 中的一种故障类型。通过创建 IOChaos 类型的混沌实验你可以模拟文件系统发生故障的情景。目前IOChaos 支持模拟以下故障类型:
- latency为文件系统调用加入延迟
- fault使文件系统调用返回错误
- attrOverride修改文件属性
- mistake使文件读到或写入错误的值
详细的功能介绍参见[使用 YAML 文件创建实验](#使用-yaml-文件创建实验)。
## 注意事项
1. 创建 IOChaos 实验前,请确保目标 Pod 上没有运行 Chaos Mesh 的 Controller Manager。
2. IOChaos 可能会损坏你的数据,在生产环境中请**谨慎**使用。
## 使用 Dashboard 创建实验
1. 单击实验页面中的**新的实验**按钮创建实验。
![新建实验](img/create-io-chaos-on-dashborad-1.jpg)
2. 在**选择目标**处选择**文件系统注入**,并选择具体行为,如**LATENCY**。
![设置实验类型](img/create-io-chaos-on-dashborad-2.jpg)
3. 填写实验信息,指定实验范围以及实验计划运行时间。
![设置实验内容](img/create-io-chaos-on-dashborad-3.jpg)
![设置目标和运行时间](img/create-io-chaos-on-dashborad-4.jpg)
4. 提交实验。
![提交实验](img/create-io-chaos-on-dashborad-5.jpg)
## 使用 YAML 文件创建实验
### latency 示例
1. 将实验配置写入到文件中 `io-latency.yaml`,内容示例如下:
```yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: IOChaos
metadata:
name: io-latency-example
namespace: chaos-testing
spec:
action: latency
mode: one
selector:
labelSelectors:
app: etcd
volumePath: /var/run/etcd
path: '/var/run/etcd/**/*'
delay: '100ms'
percent: 50
duration: '400s'
```
依据此配置示例Chaos Mesh 将向 `/var/run/etcd` 目录注入延迟故障,使该目录下的所有文件系统操作(包括读,写,列出目录内容等)产生 100 毫秒延迟。
2. 使用 `kubectl` 创建实验,命令如下:
```bash
kubectl apply -f ./io-latency.yaml
```
### fault 示例
1. 将实验配置写入到文件中 `io-fault.yaml`,内容示例如下:
```yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: IOChaos
metadata:
name: io-fault-example
namespace: chaos-testing
spec:
action: fault
mode: one
selector:
labelSelectors:
app: etcd
volumePath: /var/run/etcd
path: /var/run/etcd/**/*
errno: 5
percent: 50
duration: '400s'
```
依据此配置示例Chaos Mesh 将向 `/var/run/etcd` 目录注入文件错误故障,使该目录下的所有文件系统操作有 50% 的概率发生错误,并返回错误码 5 (Input/output error)。
2. 使用 `kubectl` 创建实验,命令如下:
```bash
kubectl apply -f ./io-fault.yaml
```
### attrOverride 示例
1. 将实验配置写入到文件中 `io-attr.yaml`,内容示例如下:
```yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: IOChaos
metadata:
name: io-attr-example
namespace: chaos-testing
spec:
action: attrOverride
mode: one
selector:
labelSelectors:
app: etcd
volumePath: /var/run/etcd
path: /var/run/etcd/**/*
attr:
perm: 72
percent: 10
duration: '400s'
```
依据此配置示例Chaos Mesh 将向 `/var/run/etcd` 目录注入 `attrOverride` 故障,使该目录下的所有文件系统操作将有 10% 的概率使目标文件的权限变为 72即八进制下的 110这将使得文件只能由拥有者与其所在的组执行无权进行其他操作。
2. 使用 `kubectl` 创建实验,命令如下:
```bash
kubectl apply -f ./io-attr.yaml
```
### mistake 示例
1. 将实验配置写入到文件中 `io-mistake.yaml`,内容示例如下:
```yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: IOChaos
metadata:
name: io-mistake-example
namespace: chaos-testing
spec:
action: mistake
mode: one
selector:
labelSelectors:
app: etcd
volumePath: /var/run/etcd
path: /var/run/etcd/**/*
mistake:
filling: zero
maxOccurrences: 1
maxLength: 10
methods:
- READ
- WRITE
percent: 10
duration: '400s'
```
依据此配置示例Chaos Mesh 将向 `/var/run/etcd` 目录注入读写错误故障,使该目录下的读写操作将有 10% 的概率将发生错误。其中以字节为单位,最大长度为 10 的 1 处随机位置将被替换为 0。
2. 使用 `kubectl` 创建实验,命令如下:
```bash
kubectl apply -f ./io-mistake.yaml
```
### 字段说明
#### 通用字段
| 参数 | 类型 | 说明 | 默认值 | 是否必填 | 示例 |
| --- | --- | --- | --- | --- | --- |
| action | string | 表示具体的故障类型,仅支持 latency、fault、attrOverride、mistake | | 是 | latency |
| mode | string | 指定实验的运行方式,可选择的方式包括:`one`(表示随机选出一个符合条件的 Pod、`all`(表示选出所有符合条件的 Pod、`fixed`(表示选出指定数量且符合条件的 Pod、`fixed-percent`(表示选出占符合条件的 Pod 中指定百分比的 Pod、`random-max-percent`(表示选出占符合条件的 Pod 中不超过指定百分比的 Pod | 无 | 是 | `one` |
| selector | struct | 指定注入故障的目标 Pod详情请参考[定义实验范围](./define-chaos-experiment-scope.md) | 无 | 是 | |
| value | string | 取决与 `mode` 的配置,为 `mode` 提供对应的参数。例如,当你将 `mode` 配置为 `fixed-percent` 时,`value` 用于指定 Pod 的百分比 | 无 | 否 | 1 |
| volumePath | string | volume 在目标容器内的挂载点,必须为挂载的根目录 | | 是 | /var/run/etcd |
| path | string | 注入错误的生效范围,可以是通配符,也可以是单个文件 | 默认对所有文件生效 | 否 | /var/run/etcd/\*_/_ |
| methods | string[] | 需要注入故障的文件系统调用类型,具体支持的类型见[附录 A](#附录-amethods-类型) | 所有类型 | 否 | READ |
| percent | int | 每次操作发生故障的概率,单位为% | 100 | 否 | 100 |
| containerName | string | 指定注入的容器名 | | 否 | |
| duration | string | 指定具体实验的持续时间 | | 是 | 30s |
#### 与 action 相关的字段
这些字段仅在 action 为对应值时才有意义:
- latency
| 参数 | 类型 | 说明 | 默认值 | 是否必填 | 示例 |
| ----- | ------ | -------------- | ------ | -------- | ------ |
| delay | string | 具体的延迟时长 | | 是 | 100 ms |
- fault
| 参数 | 类型 | 说明 | 默认值 | 是否必填 | 示例 |
| ----- | ---- | ------------ | ------ | -------- | ---- |
| errno | int | 返回的错误号 | | 是 | 22 |
常见的错误号见[附录 B](#附录-b常见错误号)
- attrOverride
| 参数 | 类型 | 说明 | 默认值 | 是否必填 | 示例 |
| ---- | ---------------- | ------------------ | ------ | -------- | ---- |
| attr | AttrOverrideSpec | 具体的属性覆写规则 | | 是 | 见下 |
AttrOverrideSpec 定义如下
| 参数 | 类型 | 说明 | 默认值 | 是否必填 | 示例 |
| --- | --- | --- | --- | --- | --- |
| ino | int | ino 的号 | | 否 | |
| size | int | 文件大小 | | 否 | |
| blocks | int | 文件占用块数 | | 否 | |
| atime | TimeSpec | 最后访问时间 | | 否 | |
| mtime | TimeSpec | 最后修改时间 | | 否 | |
| ctime | TimeSpec | 最后状态变更时间 | | 否 | |
| kind | string | 文件类型,详见 [fuser::FileType](https://docs.rs/fuser/0.7.0/fuser/enum.FileType.html) | | 否 | |
| perm | int | 文件权限的十进制表示 | | 否 | 72八进制下为 110 |
| nlink | int | 硬链接数量 | | 否 | |
| uid | int | 所有者的用户 ID | | 否 | |
| gid | int | 所有者的组 ID | | 否 | |
| rdev | int | 设备 ID | | 否 | |
TimeSpec 定义如下
| 参数 | 类型 | 说明 | 默认值 | 是否必填 | 示例 |
| ---- | ---- | -------------------- | ------ | -------- | ---- |
| sec | int | 以秒为单位的时间戳 | | 否 | |
| nsec | int | 以纳秒为单位的时间戳 | | 否 | |
关于参数的具体含义,你可以参考 [man stat](https://man7.org/linux/man-pages/man2/lstat.2.html) 。
- mistake
| 参数 | 类型 | 说明 | 默认值 | 是否必填 | 示例 |
| ------- | ----------- | ------------ | ------ | -------- | ---- |
| mistake | MistakeSpec | 具体错误规则 | | 是 | |
MistakeSpec 定义如下
| 参数 | 类型 | 说明 | 默认值 | 是否必填 | 示例 |
| --- | --- | --- | --- | --- | --- |
| filling | string | 错误数据的填充内容,只能为 zero填充 0或 random填充随机字节 | | 是 | |
| maxOccurrences | int | 错误在每一次操作中最多出现次数 | | 是 | 1 |
| maxLength | int | 每次错误的最大长度(单位为字节) | | 是 | 1 |
:::warning 警告不推荐在除了 READ 和 WRITE 之外的文件系统调用上使用 mistake 错误。这可能会导致预期之外的结果,包括但不限于文件系统损坏、程序崩溃等。 :::
## 本地调试
如果你不确定某个 Chaos 的效果,也可以使用 [toda](https://github.com/chaos-mesh/toda) 在本地测试相应功能。Chaos Mesh 同样使用 toda 实现 IOChaos。
## 附录 Amethods 类型
- lookup
- forget
- getattr
- setattr
- readlink
- mknod
- mkdir
- unlink
- rmdir
- symlink
- rename
- link
- open
- read
- write
- flush
- release
- fsync
- opendir
- readdir
- releasedir
- fsyncdir
- statfs
- setxattr
- getxattr
- listxattr
- removexattr
- access
- create
- getlk
- setlk
- bmap
详见 [fuser::Filesystem](https://docs.rs/fuser/0.7.0/fuser/trait.Filesystem.html)
## 附录 B常见错误号
- 1: Operation not permitted
- 2: No such file or directory
- 5: I/O error
- 6: No such device or address
- 12: Out of memory
- 16: Device or resource busy
- 17: File exists
- 20: Not a directory
- 22: Invalid argument
- 24: Too many open files
- 28: No space left on device
详见 [Linux 源码](https://raw.githubusercontent.com/torvalds/linux/master/include/uapi/asm-generic/errno-base.h)

View File

@ -0,0 +1,562 @@
---
title: 模拟 JVM 应用故障
---
Chaosd 通过 [Byteman](https://github.com/chaos-mesh/byteman) 模拟 JVM 应用故障,主要支持以下几种故障类型:
- 抛出自定义异常
- 触发垃圾回收
- 增加方法延迟
- 修改方法返回值
- 设置 Byteman 配置文件触发故障
- 增加 JVM 压力
本文主要介绍如何创建以上故障类型的 JVM 实验。
## 使用命令行模式创建实验
本节介绍如何在命令行模式中创建 JVM 应用故障实验。
在创建磁盘故障实验前,可运行以下命令行查看 Chaosd 支持的 JVM 应用故障类型:
```bash
chaosd attack jvm -h
```
输出结果如下所示:
```bash
JVM attack related commands
Usage:
chaosd attack jvm [command]
Available Commands:
exception throw specified exception for specified method
gc trigger GC for JVM
latency inject latency to specified method
return return specified value for specified method
rule-file inject fault with configured byteman rule file
stress inject stress to JVM
Flags:
-h, --help help for jvm
--pid int the pid of Java process which needs to attach
--port int the port of agent server (default 9288)
Global Flags:
--log-level string the log level of chaosd. The value can be 'debug', 'info', 'warn' and 'error'
--uid string the experiment ID
Use "chaosd attack jvm [command] --help" for more information about a command.
```
### 抛出自定义异常
#### 抛出自定义异常命令
运行以下命令查看抛出自定义异常场景支持的配置:
```bash
chaosd attack jvm exception --help
```
输出如下所示:
```bash
throw specified exception for specified method
Usage:
chaosd attack jvm exception [options] [flags]
Flags:
-c, --class string Java class name
--exception string the exception which needs to throw for action 'exception'
-h, --help help for exception
-m, --method string the method name in Java class
Global Flags:
--log-level string the log level of chaosd. The value can be 'debug', 'info', 'warn' and 'error'
--pid int the pid of Java process which needs to attach
--port int the port of agent server (default 9288)
--uid string the experiment ID
```
#### 抛出自定义异常相关配置说明
| 配置项 | 配置缩写 | 说明 | 值 |
| :-- | :-- | :-- | :-- |
| class | c | Java 类的名称 | string 类型,必须配置 |
| exception | 无 | 抛出的自定义异常 | string 类型,必须配置 |
| method | m | 方法名称 | string 类型,必须配置 |
| pid | 无 | 需要注入故障的 Java 进程号 | int 类型,必须配置 |
| port | 无 | 附加到 Java 进程 agent 的端口号,通过该端口号将故障注入到 Java 进程 | int 类型,默认为 9288 |
| uid | 无 | 实验的编号 | string 类型可以不配置Chaosd 会随机生成一个 |
#### 抛出自定义异常示例
```bash
chaosd attack jvm exception -c Main -m sayhello --exception 'java.io.IOException("BOOM")' --pid 30045
```
输出如下所示:
```bash
[2021/08/05 02:39:39.106 +00:00] [INFO] [jvm.go:208] ["byteman rule"] [rule="\nRULE Main-sayhello-exception-q6nd0\nCLASS Main\nMETHOD sayhello\nAT ENTRY\nIF true\nDO \n\tthrow new java.io.IOException(\"BOOM\");\nENDRULE\n"] [file=/tmp/rule.btm296930759]
Attack jvm successfully, uid: 26a45ae2-d395-46f5-a126-2b2c6c85ae9d
```
### 触发垃圾回收
#### 触发垃圾回收命令
运行以下命令查看抛出自定义异常场景支持的配置:
```bash
chaosd attack jvm gc --help
```
```bash
trigger GC for JVM
Usage:
chaosd attack jvm gc [flags]
Flags:
-h, --help help for gc
Global Flags:
--log-level string the log level of chaosd. The value can be 'debug', 'info', 'warn' and 'error'
--pid int the pid of Java process which needs to attach
--port int the port of agent server (default 9288)
--uid string the experiment ID
```
#### 触发垃圾回收相关配置说明
| 配置项 | 配置缩写 | 说明 | 值 |
| :-- | :-- | :-- | :-- |
| pid | 无 | 需要注入故障的 Java 进程号 | int 类型,必须配置 |
| port | 无 | 附加到 Java 进程 agent 的端口号,通过该端口号将故障注入到 Java 进程 | int 类型,默认为 9288 |
| uid | 无 | 实验的编号 | string 类型可以不配置Chaosd 会随机生成一个 |
#### 触发垃圾回收示例
```bash
chaosd attack jvm gc --pid 89345
```
输出如下所示:
```bash
[2021/08/05 02:49:47.850 +00:00] [INFO] [jvm.go:208] ["byteman rule"] [rule="\nRULE --gc-u0mlf\nGC\nENDRULE\n"] [file=/tmp/rule.btm012481052]
Attack jvm successfully, uid: f360e70a-5359-49b6-8526-d7e0a3c6f696
```
触发垃圾回收为一次性操作,实验不需要恢复。
### 增加方法延迟
#### 增加方法延迟命令
```bash
chaosd attack jvm latency --help
```
输出如下所示:
```bash
inject latency to specified method
Usage:
chaosd attack jvm latency [options] [flags]
Flags:
-c, --class string Java class name
-h, --help help for latency
--latency int the latency duration, unit ms
-m, --method string the method name in Java class
Global Flags:
--log-level string the log level of chaosd. The value can be 'debug', 'info', 'warn' and 'error'
--pid int the pid of Java process which needs to attach
--port int the port of agent server (default 9288)
--uid string the experiment ID
```
#### 增加方法延迟相关配置说明
| 配置项 | 配置缩写 | 说明 | 值 |
| :-- | :-- | :-- | :-- |
| class | c | Java 类的名称 | string 类型,必须配置 |
| latency | 无 | 增加方法的延迟时间 | int 类型,必须配置,单位为 ms |
| method | m | 方法名称 | string 类型,必须配置 |
| pid | 无 | 需要注入故障的 Java 进程号 | int 类型,必须配置 |
| port | 无 | 附加到 Java 进程 agent 的端口号,通过该端口号将故障注入到 Java 进程 | int 类型,默认为 9288 |
| uid | 无 | 实验的编号 | string 类型可以不配置Chaosd 会随机生成一个 |
#### 增加方法延迟示例
```bash
chaosd attack jvm latency --class Main --method sayhello --latency 5000 --pid 100840
```
输出如下所示:
```bash
[2021/08/05 03:08:50.716 +00:00] [INFO] [jvm.go:208] ["byteman rule"] [rule="\nRULE Main-sayhello-latency-hlib2\nCLASS Main\nMETHOD sayhello\nAT ENTRY\nIF true\nDO \n\tThread.sleep(5000);\nENDRULE\n"] [file=/tmp/rule.btm359997255]
[2021/08/05 03:08:51.155 +00:00] [INFO] [jvm.go:94] ["submit rules"] [output="install rule Main-sayhello-latency-hlib2\n\n"]
Attack jvm successfully, uid: bbe00c57-ac9d-4113-bf0c-2a6f184be261
```
### 修改方法返回值
#### 修改方法返回值命令
```bash
chaosd attack jvm return --help
```
```bash
return specified value for specified method
Usage:
chaosd attack jvm return [options] [flags]
Flags:
-c, --class string Java class name
-h, --help help for return
-m, --method string the method name in Java class
--value string the return value for action 'return'. Only supports number and string types.
Global Flags:
--log-level string the log level of chaosd. The value can be 'debug', 'info', 'warn' and 'error'
--pid int the pid of Java process which needs to attach
--port int the port of agent server (default 9288)
--uid string the experiment ID
```
#### 修改方法返回值相关配置说明
| 配置项 | 配置缩写 | 说明 | 值 |
| :-- | :-- | :-- | :-- |
| class | c | Java 类的名称 | string 类型,必须配置 |
| method | m | 方法名称 | string 类型,必须配置 |
| value | 无 | 指定方法的返回值 | string 类型,必须配置。目前支持数字和字符串类型的返回值,如果为字符串,则需要使用双引号,例如:"chaos"。 |
| pid | 无 | 需要注入故障的 Java 进程号 | int 类型,必须配置 |
| port | 无 | 附加到 Java 进程 agent 的端口号,通过该端口号将故障注入到 Java 进程 | int 类型,默认为 9288 |
| uid | 无 | 实验的编号 | string 类型可以不配置Chaosd 会随机生成一个 |
#### 修改方法返回值示例
```bash
chaosd attack jvm return --class Main --method getnum --value 999 --pid 112694
```
输出如下所示:
```bash
[2021/08/05 03:35:10.603 +00:00] [INFO] [jvm.go:208] ["byteman rule"] [rule="\nRULE Main-getnum-return-i6gb7\nCLASS Main\nMETHOD getnum\nAT ENTRY\nIF true\nDO \n\treturn 999;\nENDRULE\n"] [file=/tmp/rule.btm051982059]
[2021/08/05 03:35:10.820 +00:00] [INFO] [jvm.go:94] ["submit rules"] [output="install rule Main-getnum-return-i6gb7\n\n"]
Attack jvm successfully, uid: e2f204f6-4bed-4d92-aade-2b4a47b02e5d
```
### 设置 Byteman 配置文件触发故障
通过 Byteman 规则配置文件来设置故障规则,然后使用 Chaosd 指定该文件路径来注入故障。关于 Byteman 的规则配置,请参考 [byteman-rule-language](https://downloads.jboss.org/byteman/4.0.16/byteman-programmers-guide.html#the-byteman-rule-language)。
#### 设置 Byteman 配置文件触发故障命令
```bash
chaosd attack jvm rule-file --help
```
输出如下所示:
```bash
inject fault with configured byteman rule file
Usage:
chaosd attack jvm rule-file [options] [flags]
Flags:
-h, --help help for rule-file
-p, --path string the path of configured byteman rule file
Global Flags:
--log-level string the log level of chaosd, the value can be 'debug', 'info', 'warn' and 'error'
--pid int the pid of Java process which needs to attach
--port int the port of agent server (default 9288)
--uid string the experiment ID
```
#### 设置 Byteman 配置文件触发故障相关配置说明
| 配置项 | 配置缩写 | 说明 | 值 |
| :-- | :-- | :-- | :-- |
| path | 无 | 指定 Byteman 配置文件的路径 | string 类型,必须配置 |
| pid | 无 | 需要注入故障的 Java 进程号 | int 类型,必须配置 |
| port | 无 | 附加到 Java 进程 agent 的端口号,通过该端口号将故障注入到 Java 进程 | int 类型,默认为 9288 |
| uid | 无 | 实验的编号 | string 类型可以不配置Chaosd 会随机生成一个 |
#### 设置 Byteman 配置文件触发故障示例
首先根据具体的 Java 程序,并参考 [byteman-rule-language](https://downloads.jboss.org/byteman/4.0.16/byteman-programmers-guide.html#the-byteman-rule-language) 编写一个规则配置文件,例如:
```txt
RULE modify return value
CLASS Main
METHOD getnum
AT ENTRY
IF true
DO
return 9999
ENDRULE
```
将该文件保存到文件 `return.btm`,然后运行以下命令注入故障:
```bash
chaosd attack jvm rule-file -p ./return.btm --pid 112694
```
输出如下所示:
```bash
[2021/08/05 03:45:40.757 +00:00] [INFO] [jvm.go:152] ["rule file data:RULE modify return value\nCLASS Main\nMETHOD getnum\nAT ENTRY\nIF true\nDO\n return 9999\nENDRULE\n"]
[2021/08/05 03:45:41.011 +00:00] [INFO] [jvm.go:94] ["submit rules"] [output="install rule modify return value\n\n"]
Attack jvm successfully, uid: 5ca2e06d-a7c6-421d-bb67-0c9908bac17a
```
### 增加 JVM 压力
#### 增加 JVM 压力命令
```bash
chaosd attack jvm stress --help
```
输出如下所示:
```bash
inject stress to JVM
Usage:
chaosd attack jvm stress [options] [flags]
Flags:
--cpu-count int the CPU core number
-h, --help help for stress
--mem-type int the memory type to be allocated. The value can be 'stack' or 'heap'.
Global Flags:
--log-level string the log level of chaosd. The value can be 'debug', 'info', 'warn' and 'error'
--pid int the pid of Java process which needs to attach
--port int the port of agent server (default 9288)
--uid string the experiment ID
```
#### 增加 JVM 压力相关配置说明
| 配置项 | 配置缩写 | 说明 | 值 |
| :-- | :-- | :-- | :-- |
| cpu-count | 无 | 增加 CPU 压力所使用的 CPU 核的数量 | int 类型,`cpu-count` 和 `mem-type` 只能配置一个 |
| mem-type | 无 | OOM 的类型 | string 类型,目前支持 'stack' 和 'heap' 两种 OOM 类型。cpu-count 和 mem-type 只能配置一个 |
| pid | 无 | 需要注入故障的 Java 进程号 | int 类型,必须配置 |
| port | 无 | 附加到 Java 进程 agent 的端口号,通过该端口号将故障注入到 Java 进程 | int 类型,默认为 9288 |
| uid | 无 | 实验的编号 | string 类型可以不配置Chaosd 会随机生成一个 |
#### 增加 JVM 压力示例
```bash
chaosd attack jvm stress --cpu-count 2 --pid 123546
```
输出如下所示:
```bash
[2021/08/05 03:59:51.256 +00:00] [INFO] [jvm.go:208] ["byteman rule"] [rule="\nRULE --stress-jfeiu\nSTRESS CPU\nCPUCOUNT 2\nENDRULE\n"] [file=/tmp/rule.btm773062009]
[2021/08/05 03:59:51.613 +00:00] [INFO] [jvm.go:94] ["submit rules"] [output="install rule --stress-jfeiu\n\n"]
Attack jvm successfully, uid: b9b997b5-0a0d-4f1f-9081-d52a32318b84
```
## 使用服务模式创建实验
要使用服务模式创建实验,请进行以下操作:
1. 以服务模式运行 chaosd。
```bash
chaosd server --port 31767
```
2. 向 chaosd 服务的路径 /api/attack/jvm 发送 HTTP POTST 请求。其中,`bash curl -X POST 172.16.112.130:31767/api/attack/jvm -H "Content-Type:application/json" -d '{fault-configuration}'` 的 `fault-configuration` 需要按照故障类型进行配置,其对应的配置参数请参考下文中各个类型故障的相关参数说明和命令示例。在运行实验时,请注意保存实验的 UID 信息,当要结束 UID 对应的实验时,需要向 Chaosd 服务的路径 /api/attack/{uid} 发送 HTTP DELETE 请求。
### 服务模式抛出自定义异常
#### 抛出自定义异常相关参数说明
| 参数 | 说明 | 值 |
| :-- | :-- | :-- |
| action | 实验的行为 | 设置为 "exception" |
| class | Java 类的名称 | string 类型,必须配置 |
| exception | 抛出的自定义异常 | string 类型,必须配置 |
| method | 方法名称 | string 类型,必须配置 |
| pid | 需要注入故障的 Java 进程号 | int 类型,必须配置 |
| port | 附加到 Java 进程 agent 的端口号,通过该端口号将故障注入到 Java 进程 | int 类型,默认为 9288 |
| uid | 实验的编号 | string 类型可以不配置Chaosd 会随机生成一个 |
#### 服务模式抛出自定义异常示例
```bash
curl -X POST 172.16.112.130:31767/api/attack/jvm -H "Content-Type:application/json" -d '{"action":"exception","class":"Main","method":"sayhello","exception":"java.io.IOException(\"BOOM\")","pid":1828622}'
```
输出如下所示:
```bash
{"status":200,"message":"attack successfully","uid":"c3c519bf-819a-4a7b-97fb-e3d0814481fa"}
```
### 服务模式触发垃圾回收
#### 触发垃圾回收相关参数说明
| 参数 | 说明 | 值 |
| :-- | :-- | :-- |
| action | 实验的行为 | 设置为 "gc" |
| pid | 需要注入故障的 Java 进程号 | int 类型,必须配置 |
| port | 附加到 Java 进程 agent 的端口号,通过该端口号将故障注入到 Java 进程 | int 类型,默认为 9288 |
| uid | 实验的编号 | string 类型可以不配置Chaosd 会随机生成一个 |
#### 服务模式触发垃圾回收示例
```bash
curl -X POST 172.16.112.130:31767/api/attack/jvm -H "Content-Type:application/json" -d '{"action":"gc","pid":1828622}'
```
输出如下所示:
```bash
{"status":200,"message":"attack successfully","uid":"c3c519bf-819a-4a7b-97fb-e3d0814481fa"}
```
触发垃圾回收为一次性操作,实验不需要恢复。
### 服务模式增加方法延迟
#### 增加方法延迟相关参数说明
| 参数 | 说明 | 值 |
| :-- | :-- | :-- |
| action | 实验的行为 | 设置为 "latency" |
| class | Java 类的名称 | string 类型,必须配置 |
| latency | 增加方法的延迟时间 | int 类型,必须配置,单位为 ms |
| method | 方法名称 | string 类型,必须配置 |
| pid | 需要注入故障的 Java 进程号 | int 类型,必须配置 |
| port | 附加到 Java 进程 agent 的端口号,通过该端口号将故障注入到 Java 进程 | int 类型,默认为 9288 |
| uid | 实验的编号 | string 类型可以不配置Chaosd 会随机生成一个 |
#### 服务增加方法延迟示例
```bash
curl -X POST 172.16.112.130:31767/api/attack/jvm -H "Content-Type:application/json" -d '{"action":"latency","class":"Main","method":"sayhello","latency":5000,"pid":1828622}'
```
输出如下所示:
```bash
{"status":200,"message":"attack successfully","uid":"a551206c-960d-4ac5-9056-518e512d4d0d"}
```
### 服务模式修改方法返回值
#### 修改方法返回值相关参数说明
| 参数 | 说明 | 值 |
| :-- | :-- | :-- |
| action | 实验的行为 | 设置为 "return" |
| class | Java 类的名称 | string 类型,必须配置 |
| method | 方法名称 | string 类型,必须配置 |
| value | 指定方法的返回值 | string 类型,必须配置。目前支持数字和字符串类型的返回值,如果为字符串,则需要使用双引号,例如:"chaos"。 |
| pid | 需要注入故障的 Java 进程号 | int 类型,必须配置 |
| port | 附加到 Java 进程 agent 的端口号,通过该端口号将故障注入到 Java 进程 | int 类型,默认为 9288 |
| uid | 实验的编号 | string 类型可以不配置Chaosd 会随机生成一个 |
#### 服务模式修改方法返回值示例
```bash
curl -X POST 172.16.112.130:31767/api/attack/jvm -H "Content-Type:application/json" -d '{"action":"return","class":"Main","method":"getnum","value":"999","pid":1828622}'
```
输出如下所示:
```bash
{"status":200,"message":"attack successfully","uid":"a551206c-960d-4ac5-9056-518e512d4d0d"}
```
### 服务模式设置 Byteman 配置触发故障
通过 Byteman 规则配置来设置故障规则。关于 Byteman 的规则配置,请参考 [byteman-rule-language](https://downloads.jboss.org/byteman/4.0.16/byteman-programmers-guide.html#the-byteman-rule-language)。
#### 设置 Byteman 配置触发故障相关参数说明
| 参数 | 说明 | 值 |
| :-- | :-- | :-- |
| action | 实验的行为 | 设置为 "rule-data" |
| rule-data | 指定 Byteman 配置数据 | string 类型,必须配置 |
| pid | 需要注入故障的 Java 进程号 | int 类型,必须配置 |
| port | 附加到 Java 进程 agent 的端口号,通过该端口号将故障注入到 Java 进程 | int 类型,默认为 9288 |
| uid | 实验的编号 | string 类型可以不配置Chaosd 会随机生成一个 |
#### 服务模式设置 Byteman 配置触发故障示例
首先根据具体的 Java 程序,并参考 [byteman-rule-language](https://downloads.jboss.org/byteman/4.0.16/byteman-programmers-guide.html#the-byteman-rule-language) 编写一个规则配置文件,例如:
```txt
RULE modify return value
CLASS Main
METHOD getnum
AT ENTRY
IF true
DO
return 9999
ENDRULE
```
将配置中的换行转换为换行符 "\n",将转换后的数据设置为参数 "rule-data" 的值,运行如下命令:
```bash
curl -X POST 127.0.0.1:31767/api/attack/jvm -H "Content-Type:application/json" -d '{"action":"rule-data","pid":30045,"rule-data":"\nRULE modify return value\nCLASS Main\nMETHOD getnum\nAT ENTRY\nIF true\nDO return 9999\nENDRULE\n"}'
```
输出如下所示:
```bash
{"status":200,"message":"attack successfully","uid":"a551206c-960d-4ac5-9056-518e512d4d0d"}
```
### 服务模式增加 JVM 压力
#### 增加 JVM 压力相关参数说明
| 参数 | 说明 | 值 |
| :-- | :-- | :-- |
| action | 实验的行为 | 设置为 "stress" |
| cpu-count | 增加 CPU 压力所使用的 CPU 核的数量 | int 类型,`cpu-count` 和 `mem-type` 中必须配置一个 |
| mem-type | OOM 的类型 | string 类型,目前支持 'stack' 和 'heap' 两种 OOM 类型。cpu-count 和 mem-type 只能配置一个 |
| pid | 需要注入故障的 Java 进程号 | int 类型,必须配置 |
| port | 附加到 Java 进程 agent 的端口号,通过该端口号将故障注入到 Java 进程 | int 类型,默认为 9288 |
| uid | 实验的编号 | string 类型可以不配置Chaosd 会随机生成一个 |
#### 服务模式增加 JVM 压力示例
```bash
curl -X POST 172.16.112.130:31767/api/attack/jvm -H "Content-Type:application/json" -d '{"action":"stress","cpu-count":1,"pid":1828622}'
```
输出如下所示:
```bash
{"status":200,"message":"attack successfully","uid":"a551206c-960d-4ac5-9056-518e512d4d0d"}
```

View File

@ -0,0 +1,236 @@
---
title: 模拟 JVM 应用故障
---
Chaos Mesh 通过 [Byteman](https://github.com/chaos-mesh/byteman) 模拟 JVM 应用故障,主要支持以下类型的故障::
- 抛出自定义异常
- 触发垃圾回收
- 增加方法延迟
- 指定方法返回值
- 设置 Byteman 配置文件触发故障
- 增加 JVM 压力
本文主要介绍如何创建以上故障类型的 JVM 实验。
## 使用 Dashboard 方式创建实验
1. 单击实验页面中的“新的实验”按钮创建实验:
![创建实验](./img/create-new-exp.png)
2. 在“选择目标”处选择 “JVM 故障”,然后选择具体行为(如 `RETURN`),最后填写具体配置:
![JVMChaos 实验](./img/jvmchaos-exp.png)
具体配置的填写方式,参考[字段说明](#字段说明)。
3. 填写实验信息,指定实验范围以及实验计划运行时间:
![实验信息](./img/exp-info.png)
4. 提交实验。
## 使用 YAML 方式创建实验
下面将以指定返回值为例,展示 JVMChaos 的使用方法与效果。以下内容中涉及的 YAML 文件均可在 [examples/jvm](https://github.com/chaos-mesh/chaos-mesh/tree/master/examples/jvm) 中找到,以下步骤默认的工作路径也是在 `examples/jvm` 中。 默认 Chaos Mesh 安装的命名空间为 `chaos-testing`
### 第 1 步:创建被测应用
[helloworld](https://github.com/WangXiangUSTC/byteman-example/tree/main/example.helloworld) 是一个简单的 Java 应用,此处作为被测应用。被测应用定义在 `example/jvm/app.yaml` 中,内容如下:
```yaml
apiVersion: v1
kind: Pod
metadata:
name: helloworld
namespace: helloworld
spec:
containers:
- name: helloworld
# source code: https://github.com/WangXiangUSTC/byteman-example/tree/main/example.helloworld
# this application will print log like this below:
# 0. Hello World
# 1. Hello World
# ...
image: xiang13225080/helloworld:v1.0
imagePullPolicy: IfNotPresent
```
1. 创建应用所属的 namespace
```shell
kubectl create namespace helloworld
```
2. 建立该应用 Pod
```shell
kubectl apply -f app.yaml
```
3. 执行 `kubectl -n helloworld get pods`,预期能够观察到命名空间 `helloworld` 中名为 `helloworld` 的 Pod等待其 `READY``1/1` 后进行下一步。
```shell
kubectl -n helloworld get pods
```
预期结果如下:
```text
kubectl get pods -n helloworld
NAME READY STATUS RESTARTS AGE
helloworld 1/1 Running 0 2m
```
### 第 2 步:观测未被注入时的行为
在注入前你可以先观测应用 `helloworld` 未被注入时的行为,例如:
```shell
kubectl -n helloworld logs -f helloworld
```
输出如下所示:
```shell
0. Hello World
1. Hello World
2. Hello World
3. Hello World
4. Hello World
5. Hello World
```
可以看到 `helloworld` 每隔一秒输出一行 `Hello World`,每行的编号依次递增。
### 第 3 步:注入 JVMChaos 并验证
1. 指定返回值的 JVMChaos 内容如下:
```yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: JVMChaos
metadata:
name: return
namespace: helloworld
spec:
action: return
class: Main
method: getnum
value: '9999'
mode: all
selector:
namespaces:
- helloworld
```
JVMChaos 将 `getnum` 方法的返回值修改为数字 `9999`,也就是让 `helloworld` 的每行输出的编号都设置为 `9999`
2. 注入指定返回值的 JVMChaos
```shell
kubectl apply -f ./jvm-return-example.yaml
```
3. 查看 helloworld 的最新日志:
```shell
kubectl -n helloworld logs -f helloworld
```
日志如下所示:
```shell
Rule.execute called for return_0:0
return execute
caught ReturnException
9999. Hello World
```
## 字段说明
| 参数 | 类型 | 说明 | 默认值 | 是否必填 | 示例 |
| --- | --- | --- | --- | --- | --- |
| action | string | 表示具体的故障类型,支持 latency、return、exception、stress、gc、ruleData。 | 无 | 是 | return |
| mode | string | 表示选择 Pod 的方式,支持 one、all、fixed、fixed-percent、random-max-percent。 | 无 | 是 | `one` |
关于 action 的取值的含义,可参考:
| 名称 | 含义 |
| --------- | -------------------------------------------------------------- |
| latency | 增加方法调用延迟 |
| return | 修改方法返回值 |
| exception | 抛出自定义异常 |
| stress | 提高 java 进程 CPU 使用率,或者造成 内存溢出(支持堆、栈溢出) |
| gc | 触发垃圾回收 |
| ruleData | 设置 Byteman 配置触发故障 |
针对不同的 `action`,有不同的配置项可以填写。
### latency 相关参数
| 参数 | 类型 | 说明 | 是否必填 |
| ------- | ----------- | ------------------------------------------------------------------- | -------- |
| class | string 类型 | Java 类的名称 | 是 |
| method | string 类型 | 方法名称 | 是 |
| latency | int 类型 | 增加方法的延迟时间,单位为 ms | 是 |
| port | int 类型 | 附加到 Java 进程 agent 的端口号,通过该端口号将故障注入到 Java 进程 | 否 |
### return 相关参数
| 参数 | 类型 | 说明 | 是否必填 |
| --- | --- | --- | --- |
| class | string 类型 | Java 类的名称 | 是 |
| method | string 类型 | 方法名称 | 是 |
| value | string 类型 | 指定方法的返回值,目前支持数字和字符串类型的返回值,如果为字符串,则需要使用双引号,例如:"chaos"。 | 是 |
| port | int 类型 | 附加到 Java 进程 agent 的端口号,通过该端口号将故障注入到 Java 进程 | 否 |
### exception 相关参数
| 参数 | 类型 | 说明 | 是否必填 |
| --------- | ----------- | ------------------------------------------------------------------- | -------- |
| class | string 类型 | Java 类的名称 | 是 |
| method | string 类型 | 方法名称 | 是 |
| exception | string 类型 | 抛出的自定义异常,例如:'java.io.IOException("BOOM")' | 是 |
| port | int 类型 | 附加到 Java 进程 agent 的端口号,通过该端口号将故障注入到 Java 进程 | 否 |
### stress 相关参数
| 参数 | 类型 | 说明 | 是否必填 |
| -------- | ----------- | -------------------------------------------------------------------------- | -------- |
| cpuCount | int 类型 | 增加 CPU 压力所使用的 CPU 核的数量,`cpuCount` 和 `memType` 中必须配置一个 | 否 |
| memType | string 类型 | 内存 OOM 的类型,目前支持 "stack" 和 "heap" 两种类型 | 无 |
| port | int 类型 | 附加到 Java 进程 agent 的端口号,通过该端口号将故障注入到 Java 进程 | 否 |
### gc 相关参数
| 参数 | 类型 | 说明 | 是否必填 |
| ---- | -------- | ------------------------------------------------------------------- | -------- |
| port | int 类型 | 附加到 Java 进程 agent 的端口号,通过该端口号将故障注入到 Java 进程 | 否 |
### ruleData 相关参数
| 参数 | 类型 | 说明 | 是否必填 |
| -------- | ----------- | ------------------------------------------------------------------- | -------- |
| ruleData | srting 类型 | 指定 Byteman 配置数据 | 是 |
| port | int 类型 | 附加到 Java 进程 agent 的端口号,通过该端口号将故障注入到 Java 进程 | 否 |
需要根据具体的 Java 程序,并参考 [byteman-rule-language](https://downloads.jboss.org/byteman/4.0.16/byteman-programmers-guide.html#the-byteman-rule-language) 编写规则配置文件,例如:
```txt
RULE modify return value
CLASS Main
METHOD getnum
AT ENTRY
IF true
DO
return 9999
ENDRULE
```
将配置中的换行转换为换行符 "\n",将转换后的数据设置为参数 "ruleData" 的值,如上的配置转换为:
```txt
\nRULE modify return value\nCLASS Main\nMETHOD getnum\nAT ENTRY\nIF true\nDO return 9999\nENDRULE\n"
```

View File

@ -0,0 +1,139 @@
---
title: 模拟 Linux 内核故障
---
本文介绍如何使用 KernelChaos 模拟 Linux 内核故障。该功能通过使用 [BPF](https://lore.kernel.org/lkml/20171213180356.hsuhzoa7s4ngro2r@destiny/T/) 在指定内核路径上注入基于 I/O 或内存的故障。
尽管 KernelChaos 的注入对象可以设置成一个或几个 Pod但所属主机的其他 Pod 的性能也会受到一些影响,因为所有的 Pod 共享同一个内核。
::: warning 警告
模拟 Linux 内核故障的功能默认关闭,请不要用于生产环境。
:::
## 准备条件
- Linux 内核: 版本 >= 4.18
- 已启动 Linux 内核配置项 [CONFIG_BPF_KPROBE_OVERRIDE](https://cateee.net/lkddb/web-lkddb/BPF_KPROBE_OVERRIDE.html)
- 已设置 [values.yaml](https://github.com/chaos-mesh/chaos-mesh/blob/master/helm/chaos-mesh/values.yaml) 中 `bpfki.create` 配置项的值为 `true`
## 配置文件
下面是一个简单的 KernelChaos 配置文件:
```yaml
apiVersion: chaos-mesh.org/v1alpha1
kind: KernelChaos
metadata:
name: kernel-chaos-example
namespace: chaos-testing
spec:
mode: one
selector:
namespaces:
- chaos-mount
failKernRequest:
callchain:
- funcname: '__x64_sys_mount'
failtype: 0
```
更多的配置示例,请参考 [examples](https://github.com/chaos-mesh/chaos-mesh/tree/master/examples)。你可按需修改这些配置示例。
配置说明:
- **mode** 指定实验的运行方式,可选择的方式包括:
- `one`:表示随机选出一个符合条件的 Pod
- `all`:表示选出所有符合条件的 Pod
- `fixed`:表示选出指定数量且符合条件的 Pod
- `fixed-percent`:表示选出符合条件的 Pod 中指定百分比的 Pod
- `random-max-percent`:表示选出占符合条件的 Pod 中不超过指定百分比的 Pod
- **selector** 指定需要注入故障的目标 Pods。
- **failedkernRequest** 指定故障模式 (kmalloc, bio 等),可以指定一个具体的调用链路径和可选的过滤条件。配置项包括:
- **failtype** 指定故障类型,可设置的值包括:
- '0':表明注入 slab 分配错误 should_failslab。
- '1':表明注入 内存页分配错误 should_fail_alloc_page。
- '2':表明注入 bio 错误 should_fail_bio。
对于这三种故障的更多信息,请参考 [fault-injection](https://www.kernel.org/doc/html/latest/fault-injection/fault-injection.html) 和 [inject_example](http://github.com/iovisor/bcc/blob/master/tools/inject_example.txt)。
- **callchain** 指定一个具体的调用链,例如:
```c
ext4_mount
-> mount_subtree
-> ...
-> should_failslab
```
也可以使用函数参数作为过滤条件,进一步细粒度的故障注入。请参考 [call chain and predicate examples](https://github.com/chaos-mesh/bpfki/tree/develop/examples) 来获得更多信息。如果没有指定调用链,请保持 `callchain` 为空,表明它将在任意调用 slab alloc 的路径(比如 kmalloc上注入故障。
调用链的类型是 frame 数组,由以下三个部分组成:
- **funcname**:可以从内核源码或 `/proc/kallsyms` 中找到 `funcname`,比如 `ext4_mount`
- **parameters**:用于过滤。如果你想在 `d_alloc_parallel(struct dentry *parent, const struct qstr *name)`(其中 `name``bananas`)路径上注入 slab 错误,你需要将 parameters 设置为 `struct dentry *parent, const struct qstr *name` 否则省略此配置。
- **predicate**:用于访问 frame 数组的参数,以 **parameters** 为例,你可以把它设置为 `STRNCMP(name->name, "bananas", 8)` 来控制故障注入路径,也可以不设置,使得所有执行 `d_alloc_parallel` 的调用路径都注入 slab 故障。
- **headers** 指定你需要的内核头文件,比如:"linux/mmzone.h""linux/blkdev.h" 等。
- **probability** 指定故障发生概率,如果你想要 1% 的概率,请将其设置为 '1'.
- **times** 指定触发故障的最大次数。
## 使用 kubectl 创建实验
使用 kubectl 创建实验,命令如下:
```bash
kubectl apply -f KernelChaos
```
KernelChaos 功能和 [inject.py](https://github.com/iovisor/bcc/blob/master/tools/inject.py) 类似,你可以阅读 [inject_example.txt](https://github.com/iovisor/bcc/blob/master/tools/inject_example.txt) 来获得更多的信息。
下面是一个简单的例子:
```c
#include <sys/mount.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
int main(void) {
int ret;
while (1) {
ret = mount("/dev/sdc", "/mnt", "ext4",
MS_MGC_VAL | MS_RDONLY | MS_NOSUID, "");
if (ret < 0)
fprintf(stderr, "%s\n", strerror(errno));
sleep(1);
ret = umount("/mnt");
if (ret < 0)
fprintf(stderr, "%s\n", strerror(errno));
}
}
```
在故障注入期间,输出如下:
```console
> Cannot allocate memory
> Invalid argument
> Cannot allocate memory
> Invalid argument
> Cannot allocate memory
> Invalid argument
> Cannot allocate memory
> Invalid argument
> Cannot allocate memory
> Invalid argument
```
## 使用限制
通过 container_id 可以限制故障注入范围,但有些路径会触发系统级别的行为。比如:
`failtype``1` 时,它意味着物理页面分配失败。如果这个事件在很短的时间内频繁触发(例如,`while (1) {memset(malloc(1M), '1', 1M)}`),会触发系统调用 oom-killer 来回收内存。

View File

@ -0,0 +1,565 @@
---
title: 模拟网络故障
---
本文主要介绍如何使用 Chaosd 模拟网络故障场景。该功能通过使用 iptables、ipsets、tc 等工具修改网络路由、流量控制来模拟网络故障。
::: note 注意
请确保 Linux 内核拥有 请确保 Linux 内核拥有 NET_SCH_NETEM 模块。对于 CentOS可以通过 kernel-modules-extra 包安装该模块,大部分其他发行版已默认安装相应模块。
:::
## 使用命令行模式创建网络故障实验
本节介绍如何在命令行模式创建网络故障实验。
在创建网络故障实验前,可以运行以下命令查看 Chaosd 支持的网络故障类型:
```bash
chaosd attack network --help
```
输出结果如下所示:
```bash
Network attack related commands
Usage:
chaosd attack network [command]
Available Commands:
corrupt corrupt network packet
delay delay network
duplicate duplicate network packet
loss loss network packet
Flags:
-h, --help help for network
Global Flags:
--log-level string the log level of chaosd, the value can be 'debug', 'info', 'warn' and 'error'
Use "chaosd attack network [command] --help" for more information about a command.
```
目前 Chaosd 支持模拟网络包错误corrupt、延迟delay、重复duplicate、丢失loss四种实验场景。
### 网络包错误
通过运行网络包错误命令,可以查看模拟网络包错误场景支持的配置。
#### 网络包错误命令
具体命令如下所示:
```bash
chaosd attack network corrupt --help
```
输出结果如下所示:
```bash
corrupt network packet
Usage:
chaosd attack network corrupt [flags]
Flags:
-c, --correlation string correlation is percentage (10 is 10%) (default "0")
-d, --device string the network interface to impact
-e, --egress-port string only impact egress traffic to these destination ports, use a ',' to separate or to indicate the range, such as 80, 8001:8010. It can only be used in conjunction with -p tcp or -p udp
-h, --help help for corrupt
-H, --hostname string only impact traffic to these hostnames
-i, --ip string only impact egress traffic to these IP addresses
--percent string percentage of packets to corrupt (10 is 10%) (default "1")
-p, --protocol string only impact traffic using this IP protocol, supported: tcp, udp, icmp, all
-s, --source-port string only impact egress traffic from these source ports, use a ',' to separate or to indicate the range, such as 80, 8001:8010. It can only be used in conjunction with -p tcp or -p udp
Global Flags:
--log-level string the log level of chaosd, the value can be 'debug', 'info', 'warn' and 'error'
```
#### 网络包错误相关配置说明
相关配置说明如下所示:
| 配置项 | 配置缩写 | 说明 | 值 |
| :-- | :-- | :-- | :-- |
| correlation | c | 表示包错误发生的概率与前一次是否发生的相关性 | int 类型,取值范围为 0 到 100表示百分比10 表示 10%),默认值为 0 |
| device | d | 影响的网卡设备名称 | string 类型,例如 "eth0",必须要设置 |
| egress-port | e | 仅影响到指定目的端口的出口流量,仅当 protocol 为 tcp 或 udp 时配置 | string 类型,使用 "," 分隔指定的端口或者端口范围,如 "80,8001:8010" |
| hostname | H | 只影响到指定的主机名 | string 类型,如 "chaos-mesh.org" |
| ip | i | 只影响到指定的 IP 地址 | string 类型,如 "123.123.123.123" |
| protocol | p | 只影响指定的 IP 协议 | string 类型支持协议类型包括tcp、 udp、icmp、all表示影响所有网络协议 |
| source-port | s | 仅影响到指定目的端口的入口流量,仅当 protocol 为 tcp 或 udp 时配置 | string 类型,使用 "," 分隔指定的端口或者端口范围,如 "80,8001:8010" |
| percent | 无 | 网络包错误的比例 | string 类型,取值范围为 0 到 100表示百分比10 表示 10%),默认值为 1 |
#### 网络包错误示例
运行以下命令,模拟网络包错误:
```bash
chaosd attack network corrupt -d eth0 -i 172.16.4.4 --percent 50
```
运行成功时,会输出以下结果:
```bash
Attack network successfully, uid: 4eab1e62-8d60-45cb-ac85-3c17b8ac4825
```
### 网络包延迟
通过运行网络包延迟命令,查看模拟网络延迟场景支持的配置。
#### 网络包延迟命令
具体命令如下所示:
```bash
chaosd attack network delay --help
```
输出结果如下所示:
```bash
delay network
Usage:
chaosd attack network delay [flags]
Flags:
-c, --correlation string correlation is percentage (10 is 10%) (default "0")
-d, --device string the network interface to impact
-e, --egress-port string only impact egress traffic to these destination ports, use a ',' to separate or to indicate the range, such as 80, 8001:8010. It can only be used in conjunction with -p tcp or -p udp
-h, --help help for delay
-H, --hostname string only impact traffic to these hostnames
-i, --ip string only impact egress traffic to these IP addresses
-j, --jitter string jitter time, time units: ns, us (or µs), ms, s, m, h.
-l, --latency string delay egress time, time units: ns, us (or µs), ms, s, m, h.
-p, --protocol string only impact traffic using this IP protocol, supported: tcp, udp, icmp, all
-s, --source-port string only impact egress traffic from these source ports, use a ',' to separate or to indicate the range, such as 80, 8001:8010. It can only be used in conjunction with -p tcp or -p udp
Global Flags:
--log-level string the log level of chaosd, the value can be 'debug', 'info', 'warn' and 'error'
```
#### 网络包延迟相关配置说明
相关配置说明如下所示:
| 配置项 | 配置缩写 | 说明 | 值 |
| :-- | :-- | :-- | :-- |
| correlation | c | 表示延迟时间的时间长度与前一次延迟时长的相关性 | int 类型,取值范围为 0 到 100表示百分比10 表示 10%),默认值为 0 |
| device | d | 影响的网卡设备名称 | string 类型,例如 "eth0",必须要设置 |
| egress-port | e | 仅影响到指定目的端口的出口流量,仅当 protocol 为 tcp 或 udp 时配置 | string 类型,使用 "," 分隔指定的端口或者端口范围,如 "80,8001:8010" |
| hostname | H | 只影响到指定的主机名 | string 类型,如 "chaos-mesh.org" |
| ip | i | 只影响到指定的 IP 地址 | string 类型,如 "123.123.123.123" |
| jitter | j | 延迟时间的变化范围 | string 类型可使用的时间单位包括ns、us (µs)、ms、s、m、h如 "1ms" |
| latency | l | 表示延迟的时间长度 | string 类型可使用的时间单位包括ns、us (µs)、ms、s、m、h如 "1ms" |
| protocol | p | 只影响指定的 IP 协议 | string 类型支持协议类型包括tcp、 udp、icmp、all表示影响所有网络协议 |
| source-port | s | 仅影响到指定目的端口的入口流量,仅当 protocol 为 tcp 或 udp 时配置 | string 类型,使用 "," 分隔指定的端口或者端口范围,如 "80,8001:8010" |
#### 网络包延迟示例
运行以下命令,模拟网络包延迟:
```bash
chaosd attack network delay -d eth0 -i 172.16.4.4 -l 10ms
```
运行成功时,会输出以下结果:
```bash
Attack network successfully, uid: 4b23a0b5-e193-4b27-90a7-3e04235f32ab
```
### 网络包重复
可以运行网络包重复命令,查看模拟网络包重复场景支持的配置:
#### 网络包重复命令
具体命令如下所示:
```bash
chaosd attack network duplicate --help
```
输出结果如下所示:
```bash
duplicate network packet
Usage:
chaosd attack network duplicate [flags]
Flags:
-c, --correlation string correlation is percentage (10 is 10%) (default "0")
-d, --device string the network interface to impact
-e, --egress-port string only impact egress traffic to these destination ports, use a ',' to separate or to indicate the range, such as 80, 8001:8010. It can only be used in conjunction with -p tcp or -p udp
-h, --help help for duplicate
-H, --hostname string only impact traffic to these hostnames
-i, --ip string only impact egress traffic to these IP addresses
--percent string percentage of packets to duplicate (10 is 10%) (default "1")
-p, --protocol string only impact traffic using this IP protocol, supported: tcp, udp, icmp, all
-s, --source-port string only impact egress traffic from these source ports, use a ',' to separate or to indicate the range, such as 80, 8001:8010. It can only be used in conjunction with -p tcp or -p udp
Global Flags:
--log-level string the log level of chaosd, the value can be 'debug', 'info', 'warn' and 'error'
```
#### 网络包重复相关配置说明
相关配置说明如下所示:
| 配置项 | 配置缩写 | 说明 | 值 |
| :-- | :-- | :-- | :-- |
| correlation | c | 表示包重复发生的概率与前一次是否发生的相关性性 | int 类型,取值范围为 0 到 100表示百分比10 表示 10%),默认值为 0 |
| device | d | 影响的网卡设备名称 | string 类型,例如 "eth0",必须要设置 |
| egress-port | e | 仅影响到指定目的端口的出口流量,仅当 protocol 为 tcp 或 udp 时配置 | string 类型,使用 "," 分隔指定的端口或者端口范围,如 "80,8001:8010" |
| hostname | H | 只影响到指定的主机名 | string 类型,如 "chaos-mesh.org" |
| ip | i | 只影响到指定的 IP 地址 | string 类型,如 "123.123.123.123" |
| percent | 无 | 网络包重复的比例 | int 类型,取值范围为 0 到 100表示百分比10 表示 10%),默认值为 1 |
| protocol | p | 只影响指定的 IP 协议 | string 类型支持协议类型包括tcp、 udp、icmp、all表示影响所有网络协议 |
| source-port | s | 仅影响到指定目的端口的入口流量,仅当 protocol 为 tcp 或 udp 时配置 | string 类型,使用 "," 分隔指定的端口或者端口范围,如 "80,8001:8010" |
#### 网络包重复示例
运行以下命令,模拟网络包重复:
```bash
chaosd attack network duplicate -d eth0 -i 172.16.4.4 --percent 50
```
运行成功时,会输出以下结果:
```bash
Attack network successfully, uid: 7bcb74ee-9101-4ae4-82f0-e44c8a7f113c
```
### 网络包丢失
可以运行网络包丢失命令,查看模拟网络包丢失场景支持的配置:
#### 网络包丢失命令
具体命令如下所示:
```bash
chaosd attack network loss --help
```
输出结果如下所示:
```bash
loss network packet
Usage:
chaosd attack network loss [flags]
Flags:
-c, --correlation string correlation is percentage (10 is 10%) (default "0")
-d, --device string the network interface to impact
-e, --egress-port string only impact egress traffic to these destination ports, use a ',' to separate or to indicate the range, such as 80, 8001:8010. It can only be used in conjunction with -p tcp or -p udp
-h, --help help for loss
-H, --hostname string only impact traffic to these hostnames
-i, --ip string only impact egress traffic to these IP addresses
--percent string percentage of packets to drop (10 is 10%) (default "1")
-p, --protocol string only impact traffic using this IP protocol, supported: tcp, udp, icmp, all
-s, --source-port string only impact egress traffic from these source ports, use a ',' to separate or to indicate the range, such as 80, 8001:8010. It can only be used in conjunction with -p tcp or -p udp
Global Flags:
--log-level string the log level of chaosd, the value can be 'debug', 'info', 'warn' and 'error'
```
#### 网络包丢失相关配置说明
相关配置说明如下所示:
| 配置项 | 配置缩写 | 说明 | 值 |
| :-- | :-- | :-- | :-- |
| correlation | c | 表示丢包发生的概率与前一次是否发生的相关性 | int 类型,取值范围为 0 到 100表示百分比10 表示 10%),默认值为 0 |
| device | d | 影响的网卡设备名称 | string 类型,例如 "eth0",必须要设置 |
| egress-port | e | 仅影响到指定目的端口的出口流量,仅当 protocol 为 tcp 或 udp 时配置 | string 类型,使用 "," 分隔指定的端口或者端口范围,如 "80,8001:8010" |
| hostname | H | 只影响到指定的主机名 | string 类型,如 "chaos-mesh.org" |
| ip | i | 只影响到指定的 IP 地址 | string 类型,如 "123.123.123.123" |
| percent | 无 | 网络丢包的比例 | int 类型,取值范围为 0 到 100表示百分比10 表示 10%),默认值为 1 |
| protocol | p | 只影响指定的 IP 协议 | string 类型支持协议类型包括tcp、 udp、icmp、all表示影响所有网络协议 |
| source-port | s | 仅影响到指定目的端口的入口流量,仅当 protocol 为 tcp 或 udp 时配置 | string 类型,使用 "," 分隔指定的端口或者端口范围,如 "80,8001:8010" |
#### 网络包丢失示例
运行以下命令,模拟网络包丢失:
```bash
chaosd attack network loss -d eth0 -i 172.16.4.4 --percent 50
```
运行成功时,会输出以下结果:
```bash
Attack network successfully, uid: 1e818adf-3942-4de4-949b-c8499f120265
```
### 网络分区
可以运行网络分区命令,查看模拟网络分区场景支持的配置。
#### 网络分区命令
具体命令如下所示:
```bash
chaosd attack network partition --help
```
输出结果如下所示:
```bash
partition
Usage:
chaosd attack network partition [flags]
Flags:
--accept-tcp-flags string only the packet which match the tcp flag can be accepted, others will be dropped. only set when the protocol is tcp.
-d, --device string the network interface to impact
--direction string specifies the partition direction, values can be 'from', 'to'. 'from' means packets coming from the 'IPAddress' or 'Hostname' and going to your server, 'to' means packets originating from your server and going to the 'IPAddress' or 'Hostname'.
-h, --help help for partition
-H, --hostname string only impact traffic to these hostnames
-i, --ip string only impact egress traffic to these IP addresses
-p, --protocol string only impact traffic using this IP protocol, supported: tcp, udp, icmp, all
Global Flags:
--log-level string the log level of chaosd, the value can be 'debug', 'info', 'warn' and 'error'
--uid string the experiment ID
```
#### 网络分区相关配置说明
相关配置说明如下所示:
| 配置项 | 配置缩写 | 说明 | 值 |
| :-- | :-- | :-- | :-- |
| accept-tcp-flags | 无 | 表示接收包含指定标志的的 tcp 数据包,其他的则丢弃。具体配置规则参考 iptables 的 tcp-flags。仅当 protocol 为 tcp 时可以配置。 | string 类型,例如:"SYN,ACK SYN,ACK" |
| device | d | 影响的网卡设备名称 | string 类型,例如 "eth0",必须要设置 |
| direction | 无 | 指定分区的方向,对来自/发送到 hostname 指定的主机或者 ip 指定的地址的数据包进行分区 | string 类型,可选值为 "from" 或者 "to" |
| hostname | H | 只影响到指定的主机名 | string 类型,如 "chaos-mesh.org" |
| ip | i | 只影响到指定的 IP 地址 | string 类型,如 "123.123.123.123" |
| protocol | p | 只影响指定的 IP 协议 | string 类型支持协议类型包括tcp、udp、icmp、all表示影响所有网络协议 |
#### 网络分区命令示例
```bash
./chaosd attack network partition -i 172.16.4.4 -d eth0 --direction from
```
### DNS 故障
可以运行 DNS 故障命令,查看模拟 DNS 故障场景支持的配置。
#### DNS 故障命令
具体命令如下所示:
```bash
chaosd attack network dns --help
```
输出结果如下所示:
```bash
attack DNS server or map specified host to specified IP
Usage:
chaosd attack network dns [flags]
Flags:
-d, --dns-domain-name string map this host to specified IP
-i, --dns-ip string map specified host to this IP address
--dns-server string update the DNS server in /etc/resolv.conf with this value (default "123.123.123.123")
-h, --help help for dns
Global Flags:
--log-level string the log level of chaosd, the value can be 'debug', 'info', 'warn' and 'error'
--uid string the experiment ID
```
#### DNS 故障相关配置说明
相关配置说明如下所示:
| 配置项 | 配置缩写 | 说明 | 值 |
| :-------------- | :------- | :----------------------------- | :-------------------------------------- |
| dns-domain-name | H | 表示影响的域名。 | string 类型,例如:"chaos-mesh.org" |
| dns-ip | i | 表示将影响的域名映射到该地址。 | string 类型,例如 "123.123.123.123" |
| dns-server | 无 | 指定 DNS 服务地址。 | string 类型,默认值为 "123.123.123.123" |
#### DNS 故障示例
```bash
./chaosd attack network dns --dns-ip 123.123.123.123 --dns-domain-name chaos-mesh.org
```
## 使用服务模式创建网络故障实验
要使用服务模式创建实验,请进行以下操作:
1. 以服务模式运行 chaosd。
```bash
chaosd server --port 31767
```
2. 向 chaosd 服务的路径 /api/attack/network 发送 HTTP POTST 请求。 `bash curl -X POST 172.16.112.130:31767/api/attack/network -H "Content-Type:application/json" -d '{fault-configuration}' ` 其中 `fault-configuration` 需要按照故障类型进行配置,对应的配置参数请参考下文中各个类型故障的相关参数说明和命令示例。 在运行实验时,请注意保存实验的 uid 信息,当要结束 uid 对应的实验时,需要向 chaosd 服务的路径 /api/attack/{uid} 发送 HTTP DELETE 请求。
### 服务模式模拟网络包错误
在使用服务模拟网络包错误时,请参考如下内容。
#### 网络包错误相关参数说明
相关参数说明如下所示:
| 参数 | 说明 | 值 |
| :-- | :-- | :-- |
| action | 实验的行为 | 设置为 "corrupt" |
| correlation | 表示包错误发生的概率与前一次是否发生的相关性 | int 类型,取值范围为 0 到 100表示百分比10 表示 10%),默认值为 0 |
| device | 影响的网卡设备名称 | string 类型,例如 "eth0",必须要设置 |
| egress-port | 仅影响到指定目的端口的出口流量,仅当 protocol 为 tcp 或 udp 时配置 | string 类型,使用 "," 分隔指定的端口或者端口范围,如 "80,8001:8010" |
| hostname | 只影响到指定的主机名 | string 类型,如 "chaos-mesh.org" |
| ip-address | 只影响到指定的 IP 地址 | string 类型,如 "123.123.123.123" |
| ip-protocol | 只影响指定的 IP 协议 | string 类型支持协议类型包括tcp、 udp、icmp、all表示影响所有网络协议 |
| source-port | 仅影响到指定目的端口的入口流量,仅当 protocol 为 tcp 或 udp 时配置 | string 类型,使用 "," 分隔指定的端口或者端口范围,如 "80,8001:8010" |
| percent | 网络包错误的比例 | string 类型,取值范围为 0 到 100表示百分比10 表示 10%),默认值为 1 |
#### 服务模式模拟网络包错误示例
```bash
curl -X POST 172.16.112.130:31767/api/attack/network -H "Content-Type:application/json" -d '{"action":"corrupt","device":"eth0","ip-address":"172.16.4.4","percent":"50"}'
```
### 服务模式模拟网络包延迟
在使用服务模拟网络包延迟时,请参考如下内容。
#### 网络包延迟相关参数说明
相关参数说明如下所示:
| 参数 | 说明 | 值 |
| :-- | :-- | :-- |
| action | 实验的行为 | 设置为 "delay" |
| correlation | 表示延迟时间的时间长度与前一次延迟时长的相关性 | int 类型,取值范围为 0 到 100表示百分比10 表示 10%),默认值为 0 |
| device | 影响的网卡设备名称 | string 类型,例如 "eth0",必须要设置 |
| egress-port | 仅影响到指定目的端口的出口流量,仅当 protocol 为 tcp 或 udp 时配置 | string 类型,使用 "," 分隔指定的端口或者端口范围,如 "80,8001:8010" |
| hostname | 只影响到指定的主机名 | string 类型,如 "chaos-mesh.org" |
| ip-address | 只影响到指定的 IP 地址 | string 类型,如 "123.123.123.123" |
| jitter | 延迟时间的变化范围 | string 类型可使用的时间单位包括ns、us (µs)、ms、s、m、h如 "1ms" |
| latency | 表示延迟的时间长度 | string 类型可使用的时间单位包括ns、us (µs)、ms、s、m、h如 "1ms" |
| ip-protocol | 只影响指定的 IP 协议 | string 类型支持协议类型包括tcp、 udp、icmp、all表示影响所有网络协议 |
| source-port | 仅影响到指定目的端口的入口流量,仅当 protocol 为 tcp 或 udp 时配置 | string 类型,使用 "," 分隔指定的端口或者端口范围,如 "80,8001:8010" |
#### 服务模式模拟网络包延迟示例
```bash
curl -X POST 172.16.112.130:31767/api/attack/network -H "Content-Type:application/json" -d '{"action":"delay","device":"eth0","ip-address":"172.16.4.4","latency":"10ms"}'
```
### 服务模式模拟网络包重复
在使用服务模拟网络包重复时,请参考如下内容。
#### 网络包重复相关参数说明
相关参数说明如下所示:
| 参数 | 说明 | 值 |
| :-- | :-- | :-- |
| action | 实验的行为 | 设置为 "duplicate" |
| correlation | 表示包重复发生的概率与前一次是否发生的相关性性 | int 类型,取值范围为 0 到 100表示百分比10 表示 10%),默认值为 0 |
| device | 影响的网卡设备名称 | string 类型,例如 "eth0",必须要设置 |
| egress-port | 仅影响到指定目的端口的出口流量,仅当 protocol 为 tcp 或 udp 时配置 | string 类型,使用 "," 分隔指定的端口或者端口范围,如 "80,8001:8010" |
| hostname | 只影响到指定的主机名 | string 类型,如 "chaos-mesh.org" |
| ip-address | 只影响到指定的 IP 地址 | string 类型,如 "123.123.123.123" |
| percent | 网络包重复的比例 | int 类型,取值范围为 0 到 100表示百分比10 表示 10%),默认值为 1 |
| ip-protocol | 只影响指定的 IP 协议 | string 类型支持协议类型包括tcp、 udp、icmp、all表示影响所有网络协议 |
| source-port | 仅影响到指定目的端口的入口流量,仅当 protocol 为 tcp 或 udp 时配置 | string 类型,使用 "," 分隔指定的端口或者端口范围,如 "80,8001:8010" |
#### 服务模式模拟网络包重复示例
```bash
curl -X POST 172.16.112.130:31767/api/attack/network -H "Content-Type:application/json" -d '{"action":"duplicate","ip-protocol":"172.16.4.4","device":"eth0","percent":"50"}'
```
### 服务模式模拟网络包丢失
在使用服务模拟网络包丢失时,请参考如下内容。
#### 网络包丢失相关参数说明
相关参数说明如下所示:
| 参数 | 说明 | 值 |
| :-- | :-- | :-- |
| action | 实验的行为 | 设置为 "loss" |
| correlation | 表示丢包发生的概率与前一次是否发生的相关性 | int 类型,取值范围为 0 到 100表示百分比10 表示 10%),默认值为 0 |
| device | 影响的网卡设备名称 | string 类型,例如 "eth0",必须要设置 |
| egress-port | 仅影响到指定目的端口的出口流量,仅当 protocol 为 tcp 或 udp 时配置 | string 类型,使用 "," 分隔指定的端口或者端口范围,如 "80,8001:8010" |
| hostname | 只影响到指定的主机名 | string 类型,如 "chaos-mesh.org" |
| ip-address | 只影响到指定的 IP 地址 | string 类型,如 "123.123.123.123" |
| percent | 网络丢包的比例 | int 类型,取值范围为 0 到 100表示百分比10 表示 10%),默认值为 1 |
| ip-protocol | 只影响指定的 IP 协议 | string 类型支持协议类型包括tcp、 udp、icmp、all表示影响所有网络协议 |
| source-port | 仅影响到指定目的端口的入口流量,仅当 protocol 为 tcp 或 udp 时配置 | string 类型,使用 "," 分隔指定的端口或者端口范围,如 "80,8001:8010" |
#### 服务模式模拟网络包丢失示例
````bash
```bash
curl -X POST 172.16.112.130:31767/api/attack/network -H "Content-Type:application/json" -d '{"action":"loss","ip-protocol":"172.16.4.4","device":"eth0","percent":"50"}'
````
### 服务模式模拟网络分区
在使用服务模拟网络分区时,请参考如下内容。
#### 网络分区相关参数说明
相关参数说明如下所示:
| 参数 | 说明 | 值 |
| :-- | :-- | :-- |
| action | 实验的行为 | 设置为 "partition" |
| accept-tcp-flags | 表示接收包含指定标志的的 tcp 数据包,其他的则丢弃。具体配置规则参考 iptables 的 tcp-flags。仅当 protocol 为 tcp 时可以配置。 | string 类型,例如:"SYN,ACK SYN,ACK" |
| device | 影响的网卡设备名称 | string 类型,例如 "eth0",必须要设置 |
| direction | 指定分区的方向,对来自/发送到 hostname 指定的主机或者 ip 指定的地址的数据包进行分区 | string 类型,可选值为 "from" 或者 "to" |
| hostname | 只影响到指定的主机名 | string 类型,如 "chaos-mesh.org" |
| ip | 只影响到指定的 IP 地址 | string 类型,如 "123.123.123.123" |
| protocol | 只影响指定的 IP 协议 | string 类型支持协议类型包括tcp、udp、icmp、all表示影响所有网络协议 |
#### 服务模式网络分区命令示例
```bash
curl -X POST 172.16.112.130:31767/api/attack/network -H "Content-Type:application/json" -d '{"action":"partition","ip-protocol":"172.16.4.4","device":"eth0","direction":"from"}'
```
### 服务模式模拟 DNS 故障
在使用服务模拟 DNS 故障时,请参考如下内容。
#### DNS 故障相关参数说明
相关参数说明如下所示:
| 参数 | 说明 | 值 |
| :-------------- | :----------------------------- | :-------------------------------------- |
| action | 实验的行为 | 设置为 "dns" |
| dns-domain-name | 表示影响的域名。 | string 类型,例如:"chaos-mesh.org" |
| dns-ip | 表示将影响的域名映射到该地址。 | string 类型,例如 "123.123.123.123" |
| dns-server | 指定 DNS 服务地址。 | string 类型,默认值为 "123.123.123.123" |
#### 服务模式模拟 DNS 故障示例
```bash
curl -X POST 172.16.112.130:31767/api/attack/network -H "Content-Type:application/json" -d '{"action":"dns","dns-ip":"123.123.123.123","dns-domain-name":"chaos-mesh.org"}'
```

Some files were not shown because too many files have changed in this diff Show More