...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package vmrestart
17
18 import (
19 "context"
20 "encoding/json"
21 "errors"
22
23 "github.com/go-logr/logr"
24 "sigs.k8s.io/controller-runtime/pkg/client"
25
26 "github.com/chaos-mesh/chaos-mesh/api/v1alpha1"
27 "github.com/chaos-mesh/chaos-mesh/controllers/chaosimpl/azurechaos/utils"
28 impltypes "github.com/chaos-mesh/chaos-mesh/controllers/chaosimpl/types"
29 )
30
31 var _ impltypes.ChaosImpl = (*Impl)(nil)
32
33 type Impl struct {
34 client.Client
35
36 Log logr.Logger
37 }
38
39 func (impl *Impl) Apply(ctx context.Context, index int, records []*v1alpha1.Record, chaos v1alpha1.InnerObject) (v1alpha1.Phase, error) {
40 azurechaos, ok := chaos.(*v1alpha1.AzureChaos)
41 if !ok {
42 err := errors.New("chaos is not azurechaos")
43 impl.Log.Error(err, "chaos is not azureChaos", "chaos", chaos)
44 return v1alpha1.NotInjected, err
45 }
46
47 vmClient, err := utils.GetVMClient(ctx, impl.Client, azurechaos)
48 if err != nil {
49 impl.Log.Error(err, "fail to get the vm client")
50 return v1alpha1.NotInjected, err
51 }
52
53 var selected v1alpha1.AzureSelector
54 err = json.Unmarshal([]byte(records[index].Id), &selected)
55 if err != nil {
56 impl.Log.Error(err, "fail to unmarshal the selector")
57 return v1alpha1.NotInjected, err
58 }
59
60 _, err = vmClient.Restart(ctx, selected.ResourceGroupName, selected.VMName)
61 if err != nil {
62 impl.Log.Error(err, "fail to power off the vm")
63 return v1alpha1.NotInjected, err
64 }
65
66 return v1alpha1.Injected, nil
67 }
68 func (impl *Impl) Recover(ctx context.Context, index int, records []*v1alpha1.Record, chaos v1alpha1.InnerObject) (v1alpha1.Phase, error) {
69 return v1alpha1.NotInjected, nil
70 }
71
72 func NewImpl(c client.Client, log logr.Logger) *Impl {
73 return &Impl{
74 Client: c,
75 Log: log.WithName("vmrestart"),
76 }
77 }
78