...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package ec2restart
17
18 import (
19 "context"
20 "encoding/json"
21
22 awscfg "github.com/aws/aws-sdk-go-v2/config"
23 "github.com/aws/aws-sdk-go-v2/credentials"
24 "github.com/aws/aws-sdk-go-v2/service/ec2"
25 "github.com/go-logr/logr"
26 v1 "k8s.io/api/core/v1"
27 "k8s.io/apimachinery/pkg/types"
28 "sigs.k8s.io/controller-runtime/pkg/client"
29
30 "github.com/chaos-mesh/chaos-mesh/api/v1alpha1"
31 impltypes "github.com/chaos-mesh/chaos-mesh/controllers/chaosimpl/types"
32 )
33
34 var _ impltypes.ChaosImpl = (*Impl)(nil)
35
36 type Impl struct {
37 client.Client
38
39 Log logr.Logger
40 }
41
42 func (impl *Impl) Apply(ctx context.Context, index int, records []*v1alpha1.Record, obj v1alpha1.InnerObject) (v1alpha1.Phase, error) {
43 awschaos := obj.(*v1alpha1.AWSChaos)
44
45 var selected v1alpha1.AWSSelector
46 err := json.Unmarshal([]byte(records[index].Id), &selected)
47 if err != nil {
48 impl.Log.Error(err, "fail to unmarshal the selector")
49 return v1alpha1.NotInjected, err
50 }
51
52 opts := []func(*awscfg.LoadOptions) error{
53 awscfg.WithRegion(selected.AWSRegion),
54 }
55
56 if awschaos.Spec.SecretName != nil {
57 secret := &v1.Secret{}
58 err := impl.Client.Get(ctx, types.NamespacedName{
59 Name: *awschaos.Spec.SecretName,
60 Namespace: awschaos.Namespace,
61 }, secret)
62 if err != nil {
63 impl.Log.Error(err, "fail to get cloud secret")
64 return v1alpha1.NotInjected, err
65 }
66 opts = append(opts, awscfg.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(
67 string(secret.Data["aws_access_key_id"]),
68 string(secret.Data["aws_secret_access_key"]),
69 string(secret.Data["aws_session_token"]),
70 )))
71 }
72 cfg, err := awscfg.LoadDefaultConfig(ctx, opts...)
73 if err != nil {
74 impl.Log.Error(err, "unable to load aws SDK config")
75 return v1alpha1.NotInjected, err
76 }
77 ec2client := ec2.NewFromConfig(cfg)
78
79 _, err = ec2client.RebootInstances(context.TODO(), &ec2.RebootInstancesInput{
80 InstanceIds: []string{selected.Ec2Instance},
81 })
82
83 if err != nil {
84 impl.Log.Error(err, "fail to restart the instance")
85 return v1alpha1.NotInjected, err
86 }
87
88 return v1alpha1.Injected, nil
89 }
90
91 func (impl *Impl) Recover(_ context.Context, _ int, _ []*v1alpha1.Record, _ v1alpha1.InnerObject) (v1alpha1.Phase, error) {
92 return v1alpha1.NotInjected, nil
93 }
94
95 func NewImpl(c client.Client, log logr.Logger) *Impl {
96 return &Impl{
97 Client: c,
98 Log: log.WithName("ec2restart"),
99 }
100 }
101