This repository is currently being migrated. It's locked while the migration is in progress.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
mock_client.go
602 lines (541 loc) · 15 KB
/
mock_client.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
package storageos
import (
"context"
"fmt"
"math/rand"
"sync"
"time"
"github.com/google/uuid"
"github.com/hashicorp/go-multierror"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
stosv1 "github.com/storageos/api-manager/api/v1"
stosapi "github.com/storageos/go-api/autogenerated"
"k8s.io/apimachinery/pkg/api/resource"
)
func init() {
rand.Seed(int64(time.Now().Nanosecond()))
}
// MockObject can be be used to replace an api object.
type MockObject struct {
ID string
Name string
Namespace string
Labels map[string]string
Healthy bool
Inner interface{}
}
func (m MockObject) GetInner() interface{} {
return m.Inner
}
// GetID returns the object ID.
func (m MockObject) GetID() string {
return m.ID
}
// GetName returns the object name.
func (m MockObject) GetName() string {
return m.Name
}
// GetNamespace returns the object namespace.
func (m MockObject) GetNamespace() string {
return m.Namespace
}
// GetLabels returns the object labels.
func (m MockObject) GetLabels() map[string]string {
return m.Labels
}
// IsHealthy returns true if the object is healthy.
func (m MockObject) IsHealthy() bool {
return m.Healthy
}
// MockLicence is used to replace a licence.
type MockLicence struct {
ClusterID string
ExpiresAt time.Time
ClusterCapacityBytes uint64
UsedBytes uint64
Kind string
CustomerName string
Features *[]string
Version string
}
func (l MockLicence) GetClusterID() string {
return l.ClusterID
}
func (l MockLicence) GetExpiresAt() time.Time {
return l.ExpiresAt
}
func (l MockLicence) GetClusterCapacityBytes() uint64 {
return l.ClusterCapacityBytes
}
func (l MockLicence) GetUsedBytes() uint64 {
return l.UsedBytes
}
func (l MockLicence) GetKind() string {
return l.Kind
}
func (l MockLicence) GetCustomerName() string {
return l.CustomerName
}
func (l MockLicence) GetFeatures() *[]string {
return l.Features
}
func (l MockLicence) GetVersion() string {
return l.Version
}
// MockClient provides a test interface to the StorageOS api.
type MockClient struct {
setExternalEndpoint func(string, string) error
namespaces map[client.ObjectKey]Object
nodes map[client.ObjectKey]Object
volumes map[client.ObjectKey]Object
nodeLabels map[string]string
licence LicenceObject
mu sync.RWMutex
DeleteNamespaceCallCount map[client.ObjectKey]int
DeleteNodeCallCount map[client.ObjectKey]int
ListNamespacesErr error
DeleteNamespaceErr error
GetNodeErr error
NodeObjectsErr error
ListNodesErr error
DeleteNodeErr error
EnsureNodeLabelsErr error
GetNodeLabelsErr error
ListVolumeErr error
GetVolumeErr error
VolumeObjectsErr error
EnsureVolumeLabelsErr error
SharedVolsErr error
SharedVolErr error
SetEndpointErr error
GetLicenceErr error
}
// NewMockClient returns an initialized MockClient.
func NewMockClient() *MockClient {
var licenceObject LicenceObject
return &MockClient{
namespaces: make(map[client.ObjectKey]Object),
nodes: make(map[client.ObjectKey]Object),
volumes: make(map[client.ObjectKey]Object),
nodeLabels: make(map[string]string),
licence: licenceObject,
DeleteNamespaceCallCount: make(map[client.ObjectKey]int),
DeleteNodeCallCount: make(map[client.ObjectKey]int),
mu: sync.RWMutex{},
}
}
// ListNamespaces returns a list of StorageOS namespace objects.
func (c *MockClient) ListNamespaces(ctx context.Context) ([]Object, error) {
if c.ListNamespacesErr != nil {
return nil, c.ListNamespacesErr
}
ret := []Object{}
c.mu.RLock()
defer c.mu.RUnlock()
for _, ns := range c.namespaces {
ret = append(ret, ns)
}
return ret, nil
}
// AddNamespace adds a namespace to the StorageOS cluster.
func (c *MockClient) AddNamespace(key client.ObjectKey) error {
c.mu.Lock()
c.namespaces[key] = MockObject{Name: key.Name}
c.mu.Unlock()
return nil
}
// NamespaceExists returns true if the namespace exists.
func (c *MockClient) NamespaceExists(key client.ObjectKey) bool {
c.mu.RLock()
defer c.mu.RUnlock()
if _, ok := c.namespaces[key]; ok {
return true
}
return false
}
// DeleteNamespace removes a namespace from the StorageOS cluster.
func (c *MockClient) DeleteNamespace(ctx context.Context, key client.ObjectKey) error {
c.DeleteNamespaceCallCount[key]++
if c.DeleteNamespaceErr != nil {
return c.DeleteNamespaceErr
}
if !c.NamespaceExists(key) {
return ErrNamespaceNotFound
}
c.mu.Lock()
delete(c.namespaces, key)
c.mu.Unlock()
return nil
}
// NodeObjects returns a map of nodes objects, indexed on object key.
func (c *MockClient) NodeObjects(ctx context.Context) (map[client.ObjectKey]Object, error) {
if c.NodeObjectsErr != nil {
return nil, c.NodeObjectsErr
}
c.mu.RLock()
defer c.mu.RUnlock()
return c.nodes, nil
}
// ListNodes returns a list of StorageOS node objects.
func (c *MockClient) ListNodes(ctx context.Context) ([]client.Object, error) {
if c.ListNodesErr != nil {
return nil, c.ListNodesErr
}
c.mu.RLock()
defer c.mu.RUnlock()
ret := []client.Object{}
for _, node := range c.nodes {
health := stosv1.NodeHealthOnline
if !node.IsHealthy() {
health = stosv1.NodeHealthOffline
}
ret = append(ret, &stosv1.Node{
ObjectMeta: metav1.ObjectMeta{Name: node.GetName()},
Status: stosv1.NodeStatus{
Health: health,
},
})
}
return ret, nil
}
// AddNode adds a node to the StorageOS cluster.
func (c *MockClient) AddNode(obj Object) error {
c.mu.Lock()
c.nodes[ObjectKeyFromObject(obj)] = obj
c.mu.Unlock()
return nil
}
// NodeExists returns true if the node exists.
func (c *MockClient) NodeExists(key client.ObjectKey) bool {
c.mu.RLock()
defer c.mu.RUnlock()
if _, ok := c.nodes[key]; ok {
return true
}
return false
}
// DeleteNode removes a node from the StorageOS cluster.
func (c *MockClient) DeleteNode(ctx context.Context, key client.ObjectKey) error {
c.DeleteNodeCallCount[key]++
if c.DeleteNodeErr != nil {
return c.DeleteNodeErr
}
if !c.NodeExists(key) {
return ErrNodeNotFound
}
c.mu.Lock()
delete(c.nodes, key)
c.mu.Unlock()
return nil
}
// EnsureNodeLabels applies a set of labels to the StorageOS node.
func (c *MockClient) EnsureNodeLabels(ctx context.Context, key client.ObjectKey, labels map[string]string) error {
if c.EnsureNodeLabelsErr != nil {
return c.EnsureNodeLabelsErr
}
var errors *multierror.Error
var newLabels = make(map[string]string)
for k, v := range labels {
switch {
case !IsReservedLabel(k):
newLabels[k] = v
case k == ReservedLabelComputeOnly:
newLabels[k] = v
default:
errors = multierror.Append(errors, ErrReservedLabelUnknown)
}
}
c.mu.Lock()
c.nodeLabels = newLabels
c.mu.Unlock()
return errors.ErrorOrNil()
}
// GetNodeLabels retrieves the set of labels.
func (c *MockClient) GetNodeLabels(key client.ObjectKey) (map[string]string, error) {
if c.GetNodeLabelsErr != nil {
return nil, c.GetNodeLabelsErr
}
c.mu.RLock()
defer c.mu.RUnlock()
return c.nodeLabels, nil
}
// AddCommunityLicence adds a community licence to the StorageOS cluster.
func (c *MockClient) AddCommunityLicence() error {
c.mu.Lock()
c.licence = MockLicence{ClusterCapacityBytes: 1099511627776, Kind: "personal"}
c.mu.Unlock()
return nil
}
// AddEnterproseLicence adds an enterprise licence to the StorageOS cluster.
func (c *MockClient) AddEnterpriseLicence(capacity string) error {
q := resource.MustParse(capacity)
var int64Cap int64
var ok bool
if int64Cap, ok = q.AsInt64(); !ok {
return fmt.Errorf("failed to parse capacity %s", capacity)
}
c.mu.Lock()
c.licence = MockLicence{ClusterCapacityBytes: uint64(int64Cap), Kind: "premium"}
c.mu.Unlock()
return nil
}
// GetLicence retrieves the licence of the StorageOS cluster.
func (c *MockClient) GetLicence(ctx context.Context) (LicenceObject, error) {
if c.GetLicenceErr != nil {
return nil, c.GetLicenceErr
}
c.mu.RLock()
defer c.mu.RUnlock()
return c.licence, nil
}
// AddVolume adds a volume to the StorageOS cluster.
func (c *MockClient) AddVolume(obj Object) error {
c.mu.Lock()
defer c.mu.Unlock()
c.volumes[ObjectKeyFromObject(obj)] = obj
return nil
}
// DelVolume deletes a volume from the StorageOS cluster.
func (c *MockClient) DelVolume(obj Object) error {
c.mu.Lock()
defer c.mu.Unlock()
delete(c.volumes, ObjectKeyFromObject(obj))
return nil
}
// UpdateNodeHealth sets the node health.
func (c *MockClient) UpdateNodeHealth(key client.ObjectKey, healthy bool) bool {
c.mu.Lock()
defer c.mu.Unlock()
n, ok := c.nodes[key]
if !ok {
return false
}
c.nodes[key] = MockObject{
ID: n.GetID(),
Name: n.GetName(),
Namespace: n.GetNamespace(),
Labels: n.GetLabels(),
Healthy: healthy,
}
return true
}
// UpdateVolumeHealth sets the volume health.
func (c *MockClient) UpdateVolumeHealth(key client.ObjectKey, healthy bool) bool {
c.mu.Lock()
defer c.mu.Unlock()
n, ok := c.volumes[key]
if !ok {
return false
}
c.volumes[key] = MockObject{
ID: n.GetID(),
Name: n.GetName(),
Namespace: n.GetNamespace(),
Labels: n.GetLabels(),
Healthy: healthy,
}
return true
}
func (c *MockClient) ListVolumes(ctx context.Context) ([]Object, error) {
if c.ListVolumeErr != nil {
return nil, c.ListVolumeErr
}
c.mu.RLock()
defer c.mu.RUnlock()
volumes := []Object{}
for _, vol := range c.volumes {
volumes = append(volumes, vol)
}
return volumes, nil
}
// GetVolume retrieves a volume object.
func (c *MockClient) GetVolume(ctx context.Context, key client.ObjectKey) (Object, error) {
if c.GetVolumeErr != nil {
return nil, c.GetVolumeErr
}
c.mu.RLock()
defer c.mu.RUnlock()
obj, ok := c.volumes[key]
if !ok {
return nil, ErrVolumeNotFound
}
return obj, nil
}
// VolumeObjects returns a map of volume objects, indexed on object key.
func (c *MockClient) VolumeObjects(ctx context.Context) (map[client.ObjectKey]Object, error) {
if c.ListNodesErr != nil {
return nil, c.ListNodesErr
}
c.mu.RLock()
defer c.mu.RUnlock()
return c.volumes, nil
}
// EnsureVolumeLabels applies a set of labels to the StorageOS volume.
func (c *MockClient) EnsureVolumeLabels(ctx context.Context, key client.ObjectKey, labels map[string]string) error {
if c.EnsureVolumeLabelsErr != nil {
return c.EnsureVolumeLabelsErr
}
var errors *multierror.Error
var newLabels = make(map[string]string)
for k, v := range labels {
switch {
case !IsReservedLabel(k):
newLabels[k] = v
case k == ReservedLabelReplicas || k == ReservedLabelFailureMode:
newLabels[k] = v
default:
errors = multierror.Append(errors, ErrReservedLabelUnknown)
}
}
c.mu.Lock()
defer c.mu.Unlock()
n, ok := c.volumes[key]
if !ok {
return ErrVolumeNotFound
}
c.volumes[key] = &MockObject{
ID: n.GetID(),
Name: n.GetName(),
Namespace: n.GetNamespace(),
Labels: newLabels,
}
return errors.ErrorOrNil()
}
// SetExternalEndpoint sets the external endpoint on a SharedVolume. The
// endpoint should be <host|ip>:<port>.
func (c *MockClient) SetExternalEndpoint(ctx context.Context, id string, namespace string, endpoint string) error {
if c.SetEndpointErr != nil {
return c.SetEndpointErr
}
c.mu.Lock()
defer c.mu.Unlock()
if c.setExternalEndpoint != nil {
return c.setExternalEndpoint(id, endpoint)
}
return nil
}
// WithSetExternalEndpoint configures setExternalEndpoint callback.
func (c *MockClient) WithSetExternalEndpoint(callback func(string, string) error) {
c.setExternalEndpoint = callback
}
// Reset the shared volume list.
func (c *MockClient) Reset() {
c.mu.Lock()
c.setExternalEndpoint = nil
c.namespaces = make(map[client.ObjectKey]Object)
c.nodes = make(map[client.ObjectKey]Object)
c.nodeLabels = make(map[string]string)
c.licence = nil
c.DeleteNamespaceCallCount = make(map[client.ObjectKey]int)
c.DeleteNodeCallCount = make(map[client.ObjectKey]int)
c.ListNamespacesErr = nil
c.DeleteNamespaceErr = nil
c.ListNodesErr = nil
c.DeleteNodeErr = nil
c.EnsureNodeLabelsErr = nil
c.GetNodeLabelsErr = nil
c.SharedVolErr = nil
c.SharedVolsErr = nil
c.SetEndpointErr = nil
c.licence = nil
c.GetLicenceErr = nil
c.mu.Unlock()
}
// RandomSharedVolume returns a randomly generated shared volume. Always uses default
// namespace since it will always exist.
func (c *MockClient) RandomSharedVolume() *SharedVolume {
se := fmt.Sprintf("%d.%d.%d.%d:%d", rand.Intn(100)+1, rand.Intn(253)+1, rand.Intn(253)+1, rand.Intn(253)+1, rand.Intn(65534)+1)
vol := stosv1.Volume{
TypeMeta: metav1.TypeMeta{
Kind: "Volume",
APIVersion: stosv1.GroupVersion.Version,
},
ObjectMeta: metav1.ObjectMeta{
Name: randomString(8),
},
Spec: stosv1.VolumeSpec{
ConfigLabels: map[string]string{
ReservedLabelK8sPVName: "pvc-" + uuid.New().String(),
ReservedLabelK8sPVCName: randomString(8),
ReservedLabelK8sPVCNamespace: "default",
},
NFS: stosv1.NFSConfig{
ServiceEndpoint: &se,
},
},
Status: stosv1.VolumeStatus{
VolumeID: randomString(32),
},
}
return &SharedVolume{
Volume: &vol,
}
}
// RandomStorageOSVolume returns a randomly generated StorageOS volume. Always uses default
// namespace since it will always exist.
func (c *MockClient) RandomStorageOSVolume() *stosapi.Volume {
return &stosapi.Volume{
Id: randomString(4),
Name: randomString(8),
Description: randomString(255),
AttachedOn: randomString(8),
Nfs: stosapi.NfsConfig{
Exports: &[]stosapi.NfsExportConfig{
{
ExportID: 0,
Path: randomString(16),
PseudoPath: randomString(16),
Acls: []stosapi.NfsAcl{
{
Identity: stosapi.NfsAclIdentity{
IdentityType: randomString(4),
Matcher: randomString(4),
},
SquashConfig: stosapi.NfsAclSquashConfig{
Uid: rand.Int63(),
Gid: rand.Int63(),
Squash: randomString(4),
},
AccessLevel: randomString(4),
},
},
},
},
},
NamespaceID: randomString(8),
Labels: map[string]string{
ReservedLabelK8sPVName: "pvc-" + uuid.New().String(),
ReservedLabelK8sPVCName: randomString(8),
ReservedLabelK8sPVCNamespace: "default",
},
FsType: stosapi.FSTYPE_EXT2,
AttachmentType: stosapi.ATTACHTYPE_HOST,
Master: stosapi.MasterDeploymentInfo{
Id: randomString(4),
NodeID: randomString(8),
Promotable: true,
Health: stosapi.MASTERHEALTH_ONLINE,
},
Replicas: &[]stosapi.ReplicaDeploymentInfo{
{
Id: randomString(4),
NodeID: randomString(8),
Promotable: true,
Health: stosapi.REPLICAHEALTH_PROVISIONED,
},
},
SizeBytes: 1,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
Version: randomString(2),
}
}
func randomString(n int) string {
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyz")
b := make([]rune, n)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
}
return string(b)
}