Ajouter un nouveau type d'expérience de chaos
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
-
Ajoutez
helloworldchaos_types.goau répertoire d'APIapi/v1alpha1avec 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.
-
Pour intégrer la CRD dans manifests/crd.yaml, ajoutez
config/crd/bases/chaos-mesh.org_helloworldchaos.yamlgé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 -
Exécutez
make generatedans le répertoire racine de Chaos Mesh, ce qui génère un modèle pourHelloWorldChaosque Chaos Mesh compilera :make generateVous pourrez alors voir la définition de
HelloWorldChaosdansmanifests/crd.yaml.
Étape 3 : Enregistrer le gestionnaire d'événements pour les objets helloworldchaos
-
Créez un nouveau fichier
controllers/chaosimpl/helloworldchaos/types.goavec 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,
},
) -
Chaos Mesh utilise la bibliothèque fx pour l'injection de dépendances. Pour enregistrer
HelloWorldChaosdans le gestionnaire de contrôleur, ajoutez une ligne danscontrollers/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
-
Construisez les images de production :
make image -
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.
-
Enregistrez le CRD dans votre cluster :
kubectl create -f manifests/crd.yamlVous verrez que
HelloWorldChaosest créé dans la sortie :customresourcedefinition.apiextensions.k8s.io/helloworldchaos.chaos-mesh.org createdVous pouvez maintenant récupérer le CRD de
HelloWorldChaosavec la commande suivante :kubectl get crd helloworldchaos.chaos-mesh.org -
Déployez Chaos Mesh :
helm install chaos-mesh helm/chaos-mesh -n=chaos-mesh --set controllerManager.leaderElection.enabled=false,dashboard.securityMode=falsePour 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 -
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.0Attendez que le pod soit en cours d'exécution :
kubectl get podsExemple de sortie :
NAME READY STATUS RESTARTS AGE
hello-minikube-77b6f68484-dg4sw 1/1 Running 0 2m -
Créez un fichier
hello.yamlavec 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 -
Exécutez :
kubectl apply -f hello.yaml
# helloworldchaos.chaos-mesh.org/hello-world createdVérifiez si
chaos-controller-managerafficheHello world!dans ses logs :kubectl logs -n chaos-mesh chaos-controller-manager-xxxExemple 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.