Extend Chaos Daemon Interface

In Add new chaos experiment type, you have added HelloWorldChaos, which can print Hello World! in the logs of Chaos Controller Manager. To enable the HelloWorldChaos to inject some faults into the target Pod, you need to extend interface for Chaos Daemon.

Extend Chaos Daemon Interface - 图1note

It’s recommended to read Chaos Mesh architecture before you go forward.

This document covers:

Selector

In api/v1alpha1/helloworldchaos_type.go, you have defined HelloWorldSpec, which includes ContainerSelector:

  1. // HelloWorldChaosSpec is the content of the specification for a HelloWorldChaos
  2. type HelloWorldChaosSpec struct {
  3. // ContainerSelector specifies target
  4. ContainerSelector `json:",inline"`
  5. // Duration represents the duration of the chaos action
  6. // +optional
  7. Duration *string `json:"duration,omitempty"`
  8. }
  9. ...
  10. // GetSelectorSpecs is a getter for selectors
  11. func (obj *HelloWorldChaos) GetSelectorSpecs() map[string]interface{} {
  12. return map[string]interface{}{
  13. ".": &obj.Spec.ContainerSelector,
  14. }
  15. }

In Chaos Mesh, Selector is used to define the scope of a chaos experiment, the target namespace, annotation, label, etc. Selector can also be some more specific values (for example, AWSSelector in AWSChaos). Usually, each chaos experiment requires only one Selector, with exceptions such as NetworkChaos because it sometimes needs two Selectors as two objects for network partition.

Implement the gRPC interface

To allow Chaos Daemon to accept the requests from Chaos Controller Manager, you need to implement a new gRPC interface.

  1. Add the RPC in pkg/chaosdaemon/pb/chaosdaemon.proto:

    1. service chaosDaemon {
    2. ...
    3. rpc ExecHelloWorldChaos(ExecHelloWorldRequest) returns (google.protobuf.Empty) {}
    4. }
    5. message ExecHelloWorldRequest {
    6. string container_id = 1;
    7. }

    You need to update the Golang code generated by this proto file:

    1. make proto
  2. Implement gRPC services in Chaos Daemon.

    In the pkg/chaosdaemon directory, create a file named helloworld_server.go with the following contents:

    1. package chaosdaemon
    2. import (
    3. "context"
    4. "fmt"
    5. "github.com/golang/protobuf/ptypes/empty"
    6. "github.com/chaos-mesh/chaos-mesh/pkg/bpm"
    7. "github.com/chaos-mesh/chaos-mesh/pkg/chaosdaemon/pb"
    8. )
    9. func (s *DaemonServer) ExecHelloWorldChaos(ctx context.Context, req *pb.ExecHelloWorldRequest) (*empty.Empty, error) {
    10. log := s.getLoggerFromContext(ctx)
    11. log.Info("ExecHelloWorldChaos", "request", req)
    12. pid, err := s.crClient.GetPidFromContainerID(ctx, req.ContainerId)
    13. if err != nil {
    14. return nil, err
    15. }
    16. cmd := bpm.DefaultProcessBuilder("sh", "-c", fmt.Sprintf("ps aux")).
    17. SetNS(pid, bpm.MountNS).
    18. SetContext(ctx).
    19. Build(ctx)
    20. out, err := cmd.Output()
    21. if err != nil {
    22. return nil, err
    23. }
    24. if len(out) != 0 {
    25. log.Info("cmd output", "output", string(out))
    26. }
    27. return &empty.Empty{}, nil
    28. }

    After chaos-daemon receives the ExecHelloWorldChaos request, you can see a list of processes in the current container.

  3. Send a gRPC request when applying the chaos experiment.

    Each chaos experiment has its life cycle: apply and then recover. However, there are some chaos experiments that cannot be recovered by default (for example, PodKill in PodChaos, and HelloWorldChaos). These are called OneShot experiments. You can find +chaos-mesh:oneshot=true in the file that defines the schema type of chaos experiment type.

    Chaos Controller Manager needs to send a request to Chaos Daemon when HelloWorldChaos is in recover. To do this, you need to modify controllers/chaosimpl/helloordchaos/types.go:

    1. package helloworldchaos
    2. import (
    3. "context"
    4. "github.com/chaos-mesh/chaos-mesh/api/v1alpha1"
    5. impltypes "github.com/chaos-mesh/chaos-mesh/controllers/chaosimpl/types"
    6. "github.com/chaos-mesh/chaos-mesh/controllers/chaosimpl/utils"
    7. "github.com/chaos-mesh/chaos-mesh/pkg/chaosdaemon/pb"
    8. "github.com/go-logr/logr"
    9. "go.uber.org/fx"
    10. "sigs.k8s.io/controller-runtime/pkg/client"
    11. )
    12. type Impl struct {
    13. client.Client
    14. Log logr.Logger
    15. decoder *utils.ContainerRecordDecoder
    16. }
    17. // Apply applies KernelChaos
    18. func (impl *Impl) Apply(ctx context.Context, index int, records []*v1alpha1.Record, obj v1alpha1.InnerObject) (v1alpha1.Phase, error) {
    19. impl.Log.Info("Apply helloworld chaos")
    20. decodedContainer, err := impl.decoder.DecodeContainerRecord(ctx, records[index], obj)
    21. if err != nil {
    22. return v1alpha1.NotInjected, err
    23. }
    24. pbClient := decodedContainer.PbClient
    25. containerId := decodedContainer.ContainerId
    26. _, err = pbClient.ExecHelloWorldChaos(ctx, &pb.ExecHelloWorldRequest{
    27. ContainerId: containerId,
    28. })
    29. if err != nil {
    30. return v1alpha1.NotInjected, err
    31. }
    32. return v1alpha1.Injected, nil
    33. }
    34. // Recover means the reconciler recovers the chaos action
    35. func (impl *Impl) Recover(ctx context.Context, index int, records []*v1alpha1.Record, obj v1alpha1.InnerObject) (v1alpha1.Phase, error) {
    36. mpl.Log.Info("Recover helloworld chaos")
    37. return v1alpha1.NotInjected, nil
    38. }
    39. func NewImpl(c client.Client, log logr.Logger, decoder *utils.ContainerRecordDecoder) *impltypes.ChaosImplPair {
    40. return &impltypes.ChaosImplPair{
    41. Name: "helloworldchaos",
    42. Object: &v1alpha1.HelloWorldChaos{},
    43. Impl: &Impl{
    44. Client: c,
    45. Log: log.WithName("helloworldchaos"),
    46. decoder: decoder,
    47. },
    48. ObjectList: &v1alpha1.HelloWorldChaosList{},
    49. }
    50. }
    51. var Module = fx.Provide(
    52. fx.Annotated{
    53. Group: "impl",
    54. Target: NewImpl,
    55. },
    56. )

    Extend Chaos Daemon Interface - 图2note

    In this chaos experiment, there is no need to recover the chaos action. This is because HelloWorldChaos is a OneShot experiment. For the chaos experiment type you developed, you can implement the logic of the recovery function as needed.

Verify the experiment

To verify the experiment, perform the following steps.

  1. Build the Docker image and push it to your local Registry. If the Kubernetes cluster is deployed using kind, you need to load the image to kind:

    1. make image
    2. make docker-push
    3. kind load docker-image localhost:5000/pingcap/chaos-mesh:latest
    4. kind load docker-image localhost:5000/pingcap/chaos-daemon:latest
    5. kind load docker-image localhost:5000/pingcap/chaos-dashboard:latest
  2. Update Chaos Mesh:

  3. Deploy the target Pod for testing. Skip this step if you have already deployed this Pod:

    1. kubectl apply -f https://raw.githubusercontent.com/chaos-mesh/apps/master/ping/busybox-statefulset.yaml
  4. Create a new YAML file with the following content:

    1. apiVersion: chaos-mesh.org/v1alpha1
    2. kind: HelloWorldChaos
    3. metadata:
    4. name: busybox-helloworld-chaos
    5. spec:
    6. selector:
    7. namespaces:
    8. - busybox
    9. mode: all
    10. duration: 1h
  5. Apply the chaos experiment:

    1. kubectl apply -f /path/to/helloworld.yaml
  6. Verify the results. You can check several logs:

    • Check the logs of Chaos Controller Manager:
    1. kubectl logs chaos-controller-manager-{pod-post-fix} -n chaos-testing

    Example output:

    1. 2021-06-25T06:02:12.754Z INFO records apply chaos {"id": "busybox/busybox-1/busybox"}
    2. 2021-06-25T06:02:12.754Z INFO helloworldchaos Apply helloworld chaos
    • Check the logs of Chaos Daemon:
    1. kubectl logs chaos-daemon-{pod-post-fix} -n chaos-testing

    Example output:

    1. 2021-06-25T06:25:13.048Z INFO chaos-daemon-server ExecHelloWorldChaos {"request": "container_id:\"containerd://af1b99df3513c49c4cab4f12e468ed1d7a274fe53722bd883256d8f65bc9f681\""}
    2. 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"}
    3. 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"}
    4. 2021-06-25T06:25:13.070Z INFO chaos-daemon-server ExecHelloWorldChaos {"request": "container_id:\"containerd://88f6a469e5da82b48dc1190de07a2641b793df1f4e543a5958e448119d1bec11\""}
    5. 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"}
    6. 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"}

    You can see ps aux in two separate lines, which are corresponding to two different Pods.

    Extend Chaos Daemon Interface - 图3note

    If your cluster has multiple nodes, you will find more than one Chaos Daemon Pod. Try to check logs of every Chaos Daemon Pods and find which Pod is being called.

Next steps

If you encounter any problems in this process, create an issue in the Chaos Mesh repository.

If you are curious about how all of these come into effect, you can read the README files of different controllers in the controller directory to learn their functionalities. For example, controllers/common/README.md.

Now you are ready to become a Chaos Mesh developer! You are welcome to visit the Chaos Mesh repository to find a good first issue and get started!