1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package nodestop
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/gcpchaos/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 gcpchaos, ok := chaos.(*v1alpha1.GCPChaos)
41 if !ok {
42 err := errors.New("chaos is not gcpchaos")
43 impl.Log.Error(err, "chaos is not GCPChaos", "chaos", chaos)
44 return v1alpha1.NotInjected, err
45 }
46 computeService, err := utils.GetComputeService(ctx, impl.Client, gcpchaos)
47 if err != nil {
48 impl.Log.Error(err, "fail to get the compute service")
49 return v1alpha1.NotInjected, err
50 }
51 var selected v1alpha1.GCPSelector
52 json.Unmarshal([]byte(records[index].Id), &selected)
53
54 _, err = computeService.Instances.Stop(selected.Project, selected.Zone, selected.Instance).Do()
55 if err != nil {
56 impl.Log.Error(err, "fail to stop the instance")
57 return v1alpha1.NotInjected, err
58 }
59
60 return v1alpha1.Injected, nil
61 }
62
63 func (impl *Impl) Recover(ctx context.Context, index int, records []*v1alpha1.Record, chaos v1alpha1.InnerObject) (v1alpha1.Phase, error) {
64 gcpchaos, ok := chaos.(*v1alpha1.GCPChaos)
65 if !ok {
66 err := errors.New("chaos is not gcpchaos")
67 impl.Log.Error(err, "chaos is not GCPChaos", "chaos", chaos)
68 return v1alpha1.Injected, err
69 }
70 computeService, err := utils.GetComputeService(ctx, impl.Client, gcpchaos)
71 if err != nil {
72 impl.Log.Error(err, "fail to get the compute service")
73 return v1alpha1.Injected, err
74 }
75 var selected v1alpha1.GCPSelector
76 json.Unmarshal([]byte(records[index].Id), &selected)
77 _, err = computeService.Instances.Start(selected.Project, selected.Zone, selected.Instance).Do()
78 if err != nil {
79 impl.Log.Error(err, "fail to start the instance")
80 return v1alpha1.Injected, err
81 }
82 return v1alpha1.NotInjected, nil
83 }
84
85 func NewImpl(c client.Client, log logr.Logger) *Impl {
86 return &Impl{
87 Client: c,
88 Log: log.WithName("nodestop"),
89 }
90 }
91