Aller au contenu principal
Version : 2.6.7

Ajouter un nouveau type d'expérience de chaos

Traduction Bêta Non Officielle

Cette page a été traduite par PageTurner AI (bêta). Non approuvée officiellement par le projet. Vous avez trouvé une erreur ? Signaler un problème →

Ce document explique comment ajouter un nouveau type d'expérience de chaos.

La procédure suivante vous guide à travers un exemple de HelloWorldChaos, un nouveau type d'expérience de chaos qui affiche Hello world! dans les journaux. Les étapes incluent :

Étape 1 : Définir le schéma de HelloWorldChaos

  1. Ajoutez helloworldchaos_types.go au répertoire d'API api/v1alpha1 avec le contenu suivant :

    package v1alpha1

    import (
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    )

    // +kubebuilder:object:root=true
    // +chaos-mesh:experiment
    // +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 defines the desired state of HelloWorldChaos
    type HelloWorldChaosSpec struct {
    // ContainerSelector specifies the target for injection
    ContainerSelector `json:",inline"`

    // Duration represents the duration of the chaos
    // +optional
    Duration *string `json:"duration,omitempty"`

    // RemoteCluster represents the remote cluster where the chaos will be deployed
    // +optional
    RemoteCluster string `json:"remoteCluster,omitempty"`
    }

    // HelloWorldChaosStatus defines the observed state of 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,
    }
    }

    Ce fichier définit le type de schéma de HelloWorldChaos, qui peut être décrit dans un fichier YAML :

    apiVersion: chaos-mesh.org/v1alpha1
    kind: HelloWorldChaos
    metadata:
    name: <resource name>
    namespace: <namespace>
    spec:
    duration: <duration>
    #...

Étape 2 : Enregistrer la CRD

Vous devez enregistrer la CRD (Custom Resource Definition) de HelloWorldChaos pour interagir avec l'API Kubernetes.

  1. Pour intégrer la CRD dans manifests/crd.yaml, ajoutez config/crd/bases/chaos-mesh.org_helloworldchaos.yaml généré à l'étape précédente à config/crd/kustomization.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 # This is the new line
  2. Exécutez make generate dans le répertoire racine de Chaos Mesh, ce qui génère un modèle pour HelloWorldChaos que Chaos Mesh compilera :

    make generate

    Vous pourrez alors voir la définition de HelloWorldChaos dans manifests/crd.yaml.

Étape 3 : Enregistrer le gestionnaire d'événements pour les objets helloworldchaos

  1. Créez un nouveau fichier controllers/chaosimpl/helloworldchaos/types.go avec le contenu suivant :

    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"
    impltypes "github.com/chaos-mesh/chaos-mesh/controllers/chaosimpl/types"
    "github.com/chaos-mesh/chaos-mesh/controllers/chaosimpl/utils"
    )

    var _ impltypes.ChaosImpl = (*Impl)(nil)

    type Impl struct {
    client.Client
    Log logr.Logger

    decoder *utils.ContainerRecordDecoder
    }

    // This corresponds to the Apply phase of HelloWorldChaos. The execution of HelloWorldChaos will be triggered.
    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
    }

    // This corresponds to the Recover phase of HelloWorldChaos. The reconciler will be triggered to recover 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
    }

    // NewImpl returns a new HelloWorldChaos implementation instance.
    func NewImpl(c client.Client, log logr.Logger, decoder *utils.ContainerRecordDecoder) *impltypes.ChaosImplPair {
    return &impltypes.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 utilise la bibliothèque fx pour l'injection de dépendances. Pour enregistrer HelloWorldChaos dans le gestionnaire de contrôleur, ajoutez une ligne dans controllers/chaosimpl/fx.go :

    var AllImpl = fx.Options(
    gcpchaos.Module,
    stresschaos.Module,
    jvmchaos.Module,
    timechaos.Module,
    helloworldchaos.Module // Add a new line. Make sure you have imported helloworldchaos first.
    //...
    )

    Puis dans controllers/types/types.go, ajoutez le contenu suivant à ChaosObjects :

    var ChaosObjects = fx.Supply(
    //...
    fx.Annotated{
    Group: "objs",
    Target: Object{
    Name: "helloworldchaos",
    Object: &v1alpha1.HelloWorldChaos{},
    },
    },
    )

Étape 4 : Construire les images Docker

  1. Construisez les images de production :

    make image
  2. Si vous déployez le cluster Kubernetes avec minikube, vous devez charger les images dans le cluster :

    minikube image load ghcr.io/chaos-mesh/chaos-dashboard:latest
    minikube image load ghcr.io/chaos-mesh/chaos-mesh:latest
    minikube image load ghcr.io/chaos-mesh/chaos-daemon:latest

Étape 5 : Exécuter HelloWorldChaos

Dans cette étape, vous devez déployer Chaos Mesh avec vos dernières modifications pour tester HelloWorldChaos.

  1. Enregistrez le CRD dans votre cluster :

    kubectl create -f manifests/crd.yaml

    Vous verrez que HelloWorldChaos est créé dans la sortie :

    customresourcedefinition.apiextensions.k8s.io/helloworldchaos.chaos-mesh.org created

    Vous pouvez maintenant récupérer le CRD de HelloWorldChaos avec la commande suivante :

    kubectl get crd helloworldchaos.chaos-mesh.org
  2. Déployez Chaos Mesh :

    helm install chaos-mesh helm/chaos-mesh -n=chaos-mesh --set controllerManager.leaderElection.enabled=false,dashboard.securityMode=false

    Pour vérifier que le déploiement a réussi, consultez tous les Pods dans l'espace de noms chaos-mesh :

    kubectl get pods --namespace chaos-mesh -l app.kubernetes.io/instance=chaos-mesh
  3. Déployez un déploiement de test, par exemple le serveur echo des documentations minikube :

    kubectl create deployment hello-minikube --image=kicbase/echo-server:1.0

    Attendez que le pod soit en cours d'exécution :

    kubectl get pods

    Exemple de sortie :

    NAME                              READY   STATUS    RESTARTS   AGE
    hello-minikube-77b6f68484-dg4sw 1/1 Running 0 2m
  4. Créez un fichier hello.yaml avec le contenu suivant :

    apiVersion: chaos-mesh.org/v1alpha1
    kind: HelloWorldChaos
    metadata:
    name: hello-world
    namespace: chaos-mesh
    spec:
    selector:
    labelSelectors:
    app: hello-minikube
    mode: one
    duration: 1h
  5. Exécutez :

    kubectl apply -f hello.yaml
    # helloworldchaos.chaos-mesh.org/hello-world created

    Vérifiez si chaos-controller-manager affiche Hello world! dans ses logs :

    kubectl logs -n chaos-mesh chaos-controller-manager-xxx

    Exemple de sortie :

    2023-07-16T06:19:40.068Z INFO records records/controller.go:149 apply chaos {"id": "default/hello-minikube-77b6f68484-dg4sw/echo-server"}
    2023-07-16T06:19:40.068Z INFO helloworldchaos helloworldchaos/types.go:26 Hello world!

Étapes suivantes

Si vous rencontrez des problèmes lors de ce processus, créez une issue dans le dépôt Chaos Mesh.

Dans la section suivante, nous approfondirons l'extension du comportement de HelloWorldChaos.