-
Notifications
You must be signed in to change notification settings - Fork 33
/
mockclient.go
317 lines (276 loc) · 10.3 KB
/
mockclient.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
// SPDX-FileCopyrightText: 2024 SAP SE or an SAP affiliate company and Gardener contributors
//
// SPDX-License-Identifier: Apache-2.0
package mockclient
import (
"fmt"
awserror "github.com/gardener/machine-controller-manager-provider-aws/pkg/aws/errors"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
awssession "github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/ec2/ec2iface"
corev1 "k8s.io/api/core/v1"
)
const (
// FailAtRegion string to fail call due to invalid region
FailAtRegion string = "fail-at-region"
// FailQueryAtDescribeImages string to fail call at Describeimages call
FailQueryAtDescribeImages string = "fail-query-at-DescribeImages"
// FailQueryAtRunInstances string to fail call at RunInstances call
FailQueryAtRunInstances string = "aws:///eu-west-1/i-fail-query-at-RunInstances"
// FailQueryAtTerminateInstances string to fail call at TerminateInstances call
FailQueryAtTerminateInstances string = "fail-query-at-TerminateInstances"
// InstanceDoesntExistError string returns instance doesn't exist error
InstanceDoesntExistError string = "i-instance-doesnt-exist"
// InstanceStopError string returns error mentioning instance has been stopped
InstanceStopError string = "i-instance-stop-error"
// ReturnEmptyListAtDescribeInstances string returns empty list at DescribeInstances call
ReturnEmptyListAtDescribeInstances string = "return-empty-list-at-DescribeInstances"
// ReturnErrorAtDescribeInstances string returns error at DescribeInstances call
ReturnErrorAtDescribeInstances string = "return-error-at-DescribeInstances"
// SetInstanceID string sets the instance ID provided at keyname
SetInstanceID string = "set-instance-id"
// InconsistencyInAPIs string makes RunInstances and DescribeInstances APIs out of sync
InconsistencyInAPIs string = "apis-are-inconsistent"
// InsufficientCapacity string makes RunInstances return an InsufficientCapacity error code
InsufficientCapacity = "insufficient-capacity"
)
var (
// AWSInvalidRegionError denotes an error with an InvalidRegion error code.
AWSInvalidRegionError = awserr.New("InvalidRegion", "region doesn't exist while trying to create session", fmt.Errorf("region doesn't exist while trying to create session"))
// AWSImageNotFoundError denotes an error with an ImageNotFound error code.
AWSImageNotFoundError = awserr.New("ImageNotFound", "couldn't find image with given ID", fmt.Errorf("couldn't find image with given ID"))
// AWSInternalErrorForRunInstances denotes an error returned by RunInstances call with Internal error code
AWSInternalErrorForRunInstances = awserr.New("Internal", "couldn't run instance with given ID", fmt.Errorf("couldn't run instance with given ID"))
// AWSInsufficientCapacityError denotes an error with an InsufficientCapacity error code.
AWSInsufficientCapacityError = awserr.New(awserror.InsufficientCapacity, "insufficient capacity on cloud provider side", fmt.Errorf("insufficient capacity on cloud provider side"))
// AWSInternalErrorForDescribeInstances denotes an error returned by DescribeInstances call with an Internal error code
AWSInternalErrorForDescribeInstances = awserr.New("Internal", "cloud provider returned error", fmt.Errorf("cloud provider returned error"))
// AWSInstanceNotFoundError returns denotes an error with InvalidInstanceID.NotFound error code
AWSInstanceNotFoundError = awserr.New(awserror.InstanceIDNotFound, "InvalidInstanceID.NotFound: The instance IDs do not exist", fmt.Errorf("InvalidInstanceID.NotFound: The instance IDs do not exist"))
)
// MockPluginSPIImpl is the mock implementation of PluginSPI interface that makes dummy calls
type MockPluginSPIImpl struct {
FakeInstances []ec2.Instance
}
// NewSession starts a new AWS session
func (ms *MockPluginSPIImpl) NewSession(secret *corev1.Secret, region string) (*awssession.Session, error) {
if region == FailAtRegion {
return nil, AWSInvalidRegionError
}
return &awssession.Session{}, nil
}
// NewEC2API Returns a EC2API object
func (ms *MockPluginSPIImpl) NewEC2API(session *session.Session) ec2iface.EC2API {
return &MockEC2Client{
FakeInstances: &ms.FakeInstances,
}
}
// MockEC2Client is the mock implementation of an EC2Client
type MockEC2Client struct {
ec2iface.EC2API
FakeInstances *[]ec2.Instance
}
// DescribeImages implements a mock describe image method
func (ms *MockEC2Client) DescribeImages(input *ec2.DescribeImagesInput) (*ec2.DescribeImagesOutput, error) {
if *input.ImageIds[0] == FailQueryAtDescribeImages {
return nil, AWSImageNotFoundError
}
rootDeviceName := "test-root-disk"
return &ec2.DescribeImagesOutput{
Images: []*ec2.Image{
{
RootDeviceName: &rootDeviceName,
},
},
}, nil
}
// RunInstances implements a mock run instance method
// The name of the newly created instances depends on the number of instances in cache starts from 0
func (ms *MockEC2Client) RunInstances(input *ec2.RunInstancesInput) (*ec2.Reservation, error) {
if *input.ImageId == FailQueryAtRunInstances {
if *input.KeyName == InsufficientCapacity {
return nil, AWSInsufficientCapacityError
}
return nil, AWSInternalErrorForRunInstances
}
instanceID := fmt.Sprintf("i-0123456789-%d", len(*ms.FakeInstances))
privateDNSName := fmt.Sprintf("ip-%d", len(*ms.FakeInstances))
placement := input.Placement
if placement != nil {
instanceID = fmt.Sprintf("i-0123456789-%d/placement={affinity:%s,availabilityZone:%s,tenancy:%s}", len(*ms.FakeInstances), *placement.Affinity, *placement.AvailabilityZone, *placement.Tenancy)
}
if strings.Contains(*input.ImageId, SetInstanceID) {
if *input.KeyName == InconsistencyInAPIs {
instanceID = InstanceDoesntExistError
} else {
instanceID = *input.KeyName
}
}
newInstance := ec2.Instance{
InstanceId: &instanceID,
PrivateDnsName: &privateDNSName,
State: &ec2.InstanceState{
Code: aws.Int64(16),
Name: aws.String("running"),
},
Tags: deepCopyTagList(input.TagSpecifications[0].Tags),
}
*ms.FakeInstances = append(*ms.FakeInstances, newInstance)
return &ec2.Reservation{
Instances: []*ec2.Instance{
&newInstance,
},
}, nil
}
// DescribeInstances implements a mock run instance method
func (ms *MockEC2Client) DescribeInstances(input *ec2.DescribeInstancesInput) (*ec2.DescribeInstancesOutput, error) {
found := false
instanceList := make([]*ec2.Instance, 0)
for _, filter := range input.Filters {
if *filter.Values[0] == "kubernetes.io/cluster/"+ReturnErrorAtDescribeInstances {
return nil, AWSInternalErrorForDescribeInstances
}
}
if len(input.InstanceIds) > 0 {
if *input.InstanceIds[0] == ReturnEmptyListAtDescribeInstances {
return &ec2.DescribeInstancesOutput{
Reservations: []*ec2.Reservation{
{
Instances: instanceList,
},
},
}, nil
} else if *input.InstanceIds[0] == InstanceDoesntExistError {
return nil, awserr.New(
ec2.UnsuccessfulInstanceCreditSpecificationErrorCodeInvalidInstanceIdNotFound, "",
fmt.Errorf("Instance with instance-ID doesn't exist"),
)
}
// Target Specific instances
for _, instanceID := range input.InstanceIds {
for _, instance := range *ms.FakeInstances {
if *instance.InstanceId == *instanceID {
found = true
instanceToCopy := instance
instanceList = append(instanceList, &instanceToCopy)
}
}
}
if !found {
return nil, AWSInstanceNotFoundError
}
} else {
// Target all instances
for _, instance := range *ms.FakeInstances {
instanceToCopy := instance
instanceList = append(instanceList, &instanceToCopy)
}
}
return &ec2.DescribeInstancesOutput{
Reservations: []*ec2.Reservation{
{
Instances: instanceList,
},
},
}, nil
}
// TerminateInstances implements a mock terminate instance method
func (ms *MockEC2Client) TerminateInstances(input *ec2.TerminateInstancesInput) (*ec2.TerminateInstancesOutput, error) {
if *input.InstanceIds[0] == FailQueryAtTerminateInstances {
return nil, awserr.New(
ec2.UnsuccessfulInstanceCreditSpecificationErrorCodeInvalidInstanceIdMalformed, "",
fmt.Errorf("Termination of instance errorred out"),
)
}
var desiredInstance ec2.Instance
found := false
newInstanceList := make([]ec2.Instance, 0)
for _, instanceID := range input.InstanceIds {
for _, instance := range *ms.FakeInstances {
if *instance.InstanceId == *instanceID {
// Do not append InstanceID, there by removing it
found = true
desiredInstance = instance
} else {
newInstanceList = append(newInstanceList, instance)
}
}
}
ms.FakeInstances = &newInstanceList
if !found {
return nil, AWSInstanceNotFoundError
}
return &ec2.TerminateInstancesOutput{
TerminatingInstances: []*ec2.InstanceStateChange{
{
PreviousState: desiredInstance.State,
InstanceId: input.InstanceIds[0],
CurrentState: &ec2.InstanceState{
Code: aws.Int64(32),
Name: aws.String("shutting-down"),
},
},
},
}, nil
}
// StopInstances implements a mock stop instance method
func (ms *MockEC2Client) StopInstances(input *ec2.StopInstancesInput) (*ec2.StopInstancesOutput, error) {
if *input.InstanceIds[0] == InstanceStopError {
return nil, fmt.Errorf("Stopping of instance errored out")
} else if *input.DryRun {
// If it is a dry run
return nil, awserr.New(
"DryRunOperation",
"This is a dryRun call",
fmt.Errorf("This is a dry run call"),
)
}
var desiredInstance ec2.Instance
found := false
for _, instanceID := range input.InstanceIds {
for _, instance := range *ms.FakeInstances {
if *instance.InstanceId == *instanceID {
// Do not append InstanceID, there by removing it
found = true
desiredInstance = instance
} else {
}
}
}
if !found {
return nil, AWSInstanceNotFoundError
}
return &ec2.StopInstancesOutput{
StoppingInstances: []*ec2.InstanceStateChange{
{
PreviousState: desiredInstance.State,
InstanceId: input.InstanceIds[0],
CurrentState: &ec2.InstanceState{
Code: aws.Int64(64),
Name: aws.String("stopping"),
},
},
},
}, nil
}
// deepCopyTagList copies inTags list to outTags
func deepCopyTagList(inTags []*ec2.Tag) []*ec2.Tag {
var outTags []*ec2.Tag
for _, tagPtr := range inTags {
tag := &ec2.Tag{}
if tagPtr.Key != nil {
key := *tagPtr.Key
tag.Key = &key
}
if tagPtr.Value != nil {
value := *tagPtr.Value
tag.Value = &value
}
outTags = append(outTags, tag)
}
return outTags
}