/
admin_client_mock.go
672 lines (565 loc) · 20.5 KB
/
admin_client_mock.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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
/*
* admin_client_mock.go
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2020-2021 Apple Inc. and the FoundationDB project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package controllers
import (
"context"
"fmt"
"net"
"strings"
"sync"
fdbtypes "github.com/FoundationDB/fdb-kubernetes-operator/api/v1beta1"
"github.com/FoundationDB/fdb-kubernetes-operator/internal"
"github.com/FoundationDB/fdb-kubernetes-operator/pkg/fdbadminclient"
"github.com/FoundationDB/fdb-kubernetes-operator/pkg/podmanager"
corev1 "k8s.io/api/core/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// mockAdminClient provides a mock implementation of the cluster admin interface
type mockAdminClient struct {
Cluster *fdbtypes.FoundationDBCluster
KubeClient client.Client
DatabaseConfiguration *fdbtypes.DatabaseConfiguration
ExcludedAddresses []string
ReincludedAddresses map[string]bool
KilledAddresses []string
frozenStatus *fdbtypes.FoundationDBStatus
Backups map[string]fdbtypes.FoundationDBBackupStatusBackupDetails
restoreURL string
clientVersions map[string][]string
missingProcessGroups map[string]bool
additionalProcesses []fdbtypes.ProcessGroupStatus
localityInfo map[string]map[string]string
incorrectCommandLines map[string]bool
maxZoneFailuresWithoutLosingData *int
maxZoneFailuresWithoutLosingAvailability *int
}
// adminClientCache provides a cache of mock admin clients.
var adminClientCache = make(map[string]*mockAdminClient)
var adminClientMutex sync.Mutex
// newMockAdminClient creates an admin client for a cluster.
func newMockAdminClient(cluster *fdbtypes.FoundationDBCluster, kubeClient client.Client) (fdbadminclient.AdminClient, error) {
return newMockAdminClientUncast(cluster, kubeClient)
}
// newMockAdminClientUncast creates a mock admin client for a cluster.
// nolint:unparam
// is required because we always return a nil error
func newMockAdminClientUncast(cluster *fdbtypes.FoundationDBCluster, kubeClient client.Client) (*mockAdminClient, error) {
adminClientMutex.Lock()
defer adminClientMutex.Unlock()
client := adminClientCache[cluster.Name]
if client == nil {
client = &mockAdminClient{
Cluster: cluster.DeepCopy(),
KubeClient: kubeClient,
ReincludedAddresses: make(map[string]bool),
missingProcessGroups: make(map[string]bool),
localityInfo: make(map[string]map[string]string),
}
adminClientCache[cluster.Name] = client
client.Backups = make(map[string]fdbtypes.FoundationDBBackupStatusBackupDetails)
} else {
client.Cluster = cluster.DeepCopy()
}
return client, nil
}
// clearMockAdminClients clears the cache of mock Admin clients
func clearMockAdminClients() {
adminClientCache = map[string]*mockAdminClient{}
}
// GetStatus gets the database's status
func (client *mockAdminClient) GetStatus() (*fdbtypes.FoundationDBStatus, error) {
adminClientMutex.Lock()
defer adminClientMutex.Unlock()
if client.frozenStatus != nil {
return client.frozenStatus, nil
}
pods := &corev1.PodList{}
err := client.KubeClient.List(context.TODO(), pods)
if err != nil {
return nil, err
}
status := &fdbtypes.FoundationDBStatus{
Cluster: fdbtypes.FoundationDBStatusClusterInfo{
Processes: make(map[string]fdbtypes.FoundationDBStatusProcessInfo, len(pods.Items)),
},
}
coordinators := make(map[string]bool)
var coordinatorAddresses []string
if strings.Contains(client.Cluster.Status.ConnectionString, "@") {
coordinatorAddresses = strings.Split(strings.Split(client.Cluster.Status.ConnectionString, "@")[1], ",")
} else {
coordinatorAddresses = []string{}
}
for _, address := range coordinatorAddresses {
coordinators[address] = false
}
exclusionMap := make(map[string]bool, len(client.ExcludedAddresses))
for _, address := range client.ExcludedAddresses {
exclusionMap[address] = true
}
for _, pod := range pods.Items {
podClient, _ := internal.NewMockFdbPodClient(client.Cluster, &pod)
processCount, err := internal.GetStorageServersPerPodForPod(&pod)
if err != nil {
return nil, err
}
processGroupID := podmanager.GetProcessGroupID(client.Cluster, &pod)
if client.missingProcessGroups[processGroupID] {
continue
}
subs, err := podClient.GetVariableSubstitutions()
if err != nil {
return nil, err
}
processIP, ok := subs["FDB_PUBLIC_IP"]
if !ok {
processIP = pod.Status.PodIP
}
for processIndex := 1; processIndex <= processCount; processIndex++ {
var fdbRoles []fdbtypes.FoundationDBStatusProcessRoleInfo
fullAddress := client.Cluster.GetFullAddress(processIP, processIndex)
_, ipExcluded := exclusionMap[processIP]
_, addressExcluded := exclusionMap[fullAddress.String()]
excluded := ipExcluded || addressExcluded
_, isCoordinator := coordinators[fullAddress.String()]
if isCoordinator && !excluded {
coordinators[fullAddress.String()] = true
fdbRoles = append(fdbRoles, fdbtypes.FoundationDBStatusProcessRoleInfo{Role: string(fdbtypes.ProcessRoleCoordinator)})
}
pClass, err := podmanager.GetProcessClass(client.Cluster, &pod)
if err != nil {
return nil, err
}
command, err := internal.GetStartCommand(client.Cluster, pClass, podClient, processIndex, processCount)
if err != nil {
return nil, err
}
if client.incorrectCommandLines != nil && client.incorrectCommandLines[processGroupID] {
command += " --locality_incorrect=1"
}
locality := map[string]string{
fdbtypes.FDBLocalityInstanceIDKey: processGroupID,
fdbtypes.FDBLocalityZoneIDKey: pod.Name,
fdbtypes.FDBLocalityDCIDKey: client.Cluster.Spec.DataCenter,
}
for key, value := range client.localityInfo[processGroupID] {
locality[key] = value
}
if processCount > 1 {
locality["process_id"] = fmt.Sprintf("%s-%d", processGroupID, processIndex)
}
status.Cluster.Processes[fmt.Sprintf("%s-%d", pod.Name, processIndex)] = fdbtypes.FoundationDBStatusProcessInfo{
Address: fullAddress,
ProcessClass: internal.GetProcessClassFromMeta(client.Cluster, pod.ObjectMeta),
CommandLine: command,
Excluded: excluded,
Locality: locality,
Version: client.Cluster.Status.RunningVersion,
UptimeSeconds: 60000,
Roles: fdbRoles,
}
}
for _, processGroup := range client.additionalProcesses {
locality := map[string]string{
fdbtypes.FDBLocalityInstanceIDKey: processGroup.ProcessGroupID,
fdbtypes.FDBLocalityZoneIDKey: processGroup.ProcessGroupID,
}
for key, value := range client.localityInfo[processGroupID] {
locality[key] = value
}
fullAddress := client.Cluster.GetFullAddress(processGroup.Addresses[0], 1)
status.Cluster.Processes[processGroup.ProcessGroupID] = fdbtypes.FoundationDBStatusProcessInfo{
Address: fullAddress,
ProcessClass: processGroup.ProcessClass,
Locality: locality,
Version: client.Cluster.Status.RunningVersion,
UptimeSeconds: 60000,
}
}
}
if client.clientVersions != nil {
supportedVersions := make([]fdbtypes.FoundationDBStatusSupportedVersion, 0, len(client.clientVersions))
for version, addresses := range client.clientVersions {
protocolVersion, err := client.GetProtocolVersion(version)
if err != nil {
return nil, err
}
protocolClients := make([]fdbtypes.FoundationDBStatusConnectedClient, 0, len(addresses))
for _, address := range addresses {
protocolClients = append(protocolClients, fdbtypes.FoundationDBStatusConnectedClient{
Address: address,
})
}
supportedVersions = append(supportedVersions, fdbtypes.FoundationDBStatusSupportedVersion{
ClientVersion: version,
ProtocolVersion: protocolVersion,
MaxProtocolClients: protocolClients,
})
}
status.Cluster.Clients.SupportedVersions = supportedVersions
}
for address, reachable := range coordinators {
pAddr, err := fdbtypes.ParseProcessAddress(address)
if err != nil {
return nil, err
}
status.Client.Coordinators.Coordinators = append(status.Client.Coordinators.Coordinators, fdbtypes.FoundationDBStatusCoordinator{
Address: pAddr,
Reachable: reachable,
})
}
status.Client.DatabaseStatus.Available = true
status.Client.DatabaseStatus.Healthy = true
if client.DatabaseConfiguration == nil {
status.Cluster.Layers.Error = "configurationMissing"
} else {
status.Cluster.DatabaseConfiguration = *client.DatabaseConfiguration
}
if status.Cluster.DatabaseConfiguration.LogSpill == 0 {
status.Cluster.DatabaseConfiguration.VersionFlags.LogSpill = 2
}
status.Cluster.FullReplication = true
status.Cluster.Data.State.Healthy = true
status.Cluster.Data.State.Name = "healthy"
if len(client.Backups) > 0 {
status.Cluster.Layers.Backup.Tags = make(map[string]fdbtypes.FoundationDBStatusBackupTag, len(client.Backups))
for tag, tagStatus := range client.Backups {
status.Cluster.Layers.Backup.Tags[tag] = fdbtypes.FoundationDBStatusBackupTag{
CurrentContainer: tagStatus.URL,
RunningBackup: tagStatus.Running,
Restorable: true,
}
status.Cluster.Layers.Backup.Paused = tagStatus.Paused
}
}
if client.maxZoneFailuresWithoutLosingData == nil {
status.Cluster.FaultTolerance.MaxZoneFailuresWithoutLosingData = client.Cluster.DesiredFaultTolerance()
}
if client.maxZoneFailuresWithoutLosingAvailability == nil {
status.Cluster.FaultTolerance.MaxZoneFailuresWithoutLosingAvailability = client.Cluster.DesiredFaultTolerance()
}
return status, nil
}
// ConfigureDatabase changes the database configuration
func (client *mockAdminClient) ConfigureDatabase(configuration fdbtypes.DatabaseConfiguration, newDatabase bool) error {
adminClientMutex.Lock()
defer adminClientMutex.Unlock()
client.DatabaseConfiguration = configuration.DeepCopy()
return nil
}
// ExcludeProcesses starts evacuating processes so that they can be removed
// from the database.
func (client *mockAdminClient) ExcludeProcesses(addresses []fdbtypes.ProcessAddress) error {
adminClientMutex.Lock()
defer adminClientMutex.Unlock()
count := len(addresses) + len(client.ExcludedAddresses)
exclusionMap := make(map[string]bool, count)
newExclusions := make([]string, 0, count)
for _, pAddr := range addresses {
address := pAddr.String()
if !exclusionMap[address] {
exclusionMap[address] = true
newExclusions = append(newExclusions, address)
}
}
for _, address := range client.ExcludedAddresses {
if !exclusionMap[address] {
exclusionMap[address] = true
newExclusions = append(newExclusions, address)
}
}
if len(newExclusions) == 0 {
newExclusions = nil
}
client.ExcludedAddresses = newExclusions
return nil
}
// IncludeProcesses removes processes from the exclusion list and allows
// them to take on roles again.
func (client *mockAdminClient) IncludeProcesses(addresses []fdbtypes.ProcessAddress) error {
adminClientMutex.Lock()
defer adminClientMutex.Unlock()
newExclusions := make([]string, 0, len(client.ExcludedAddresses))
for _, excludedAddress := range client.ExcludedAddresses {
included := false
for _, address := range addresses {
if address.String() == excludedAddress {
included = true
client.ReincludedAddresses[address.String()] = true
break
}
}
if !included {
newExclusions = append(newExclusions, excludedAddress)
}
}
if len(newExclusions) == 0 {
newExclusions = nil
}
client.ExcludedAddresses = newExclusions
return nil
}
// CanSafelyRemove checks whether it is safe to remove the process group from the
// cluster
//
// The list returned by this method will be the addresses that are *not*
// safe to remove.
func (client *mockAdminClient) CanSafelyRemove(addresses []fdbtypes.ProcessAddress) ([]fdbtypes.ProcessAddress, error) {
skipExclude := map[string]internal.None{}
// Check which process groups have the skip exclusion flag or are already
// excluded
for _, pg := range client.Cluster.Status.ProcessGroups {
if !(pg.ExclusionSkipped || pg.Excluded) {
continue
}
for _, addr := range pg.Addresses {
skipExclude[addr] = internal.None{}
}
}
// Add all process groups that are excluded in the client
for _, addr := range client.ExcludedAddresses {
skipExclude[addr] = internal.None{}
}
// Filter out all excluded process groups and also all process groups
// that skip exclusion
remaining := make([]fdbtypes.ProcessAddress, 0, len(addresses))
for _, addr := range addresses {
// Is already excluded or skipped
if _, ok := skipExclude[addr.String()]; ok {
continue
}
remaining = append(remaining, addr)
}
return remaining, nil
}
// GetExclusions gets a list of the addresses currently excluded from the
// database.
func (client *mockAdminClient) GetExclusions() ([]fdbtypes.ProcessAddress, error) {
adminClientMutex.Lock()
defer adminClientMutex.Unlock()
pAddrs := make([]fdbtypes.ProcessAddress, len(client.ExcludedAddresses))
for _, addr := range client.ExcludedAddresses {
pAddrs = append(pAddrs, fdbtypes.ProcessAddress{
IPAddress: net.ParseIP(addr),
Placeholder: "",
Port: 0,
Flags: nil,
})
}
return pAddrs, nil
}
// KillProcesses restarts processes
func (client *mockAdminClient) KillProcesses(addresses []fdbtypes.ProcessAddress) error {
adminClientMutex.Lock()
for _, addr := range addresses {
client.KilledAddresses = append(client.KilledAddresses, addr.String())
}
adminClientMutex.Unlock()
client.UnfreezeStatus()
return nil
}
// ChangeCoordinators changes the coordinator set
func (client *mockAdminClient) ChangeCoordinators(addresses []fdbtypes.ProcessAddress) (string, error) {
adminClientMutex.Lock()
defer adminClientMutex.Unlock()
connectionString, err := fdbtypes.ParseConnectionString(client.Cluster.Status.ConnectionString)
if err != nil {
return "", err
}
err = connectionString.GenerateNewGenerationID()
if err != nil {
return "", err
}
newCoord := make([]string, len(addresses))
for idx, coord := range addresses {
newCoord[idx] = coord.String()
}
connectionString.Coordinators = newCoord
return connectionString.String(), err
}
// GetConnectionString fetches the latest connection string.
func (client *mockAdminClient) GetConnectionString() (string, error) {
adminClientMutex.Lock()
defer adminClientMutex.Unlock()
return client.Cluster.Status.ConnectionString, nil
}
// VersionSupported reports whether we can support a cluster with a given
// version.
func (client *mockAdminClient) VersionSupported(versionString string) (bool, error) {
version, err := fdbtypes.ParseFdbVersion(versionString)
if err != nil {
return false, err
}
if !version.IsSupported() {
return false, nil
}
return true, nil
}
// GetProtocolVersion determines the protocol version that is used by a
// version of FDB.
func (client *mockAdminClient) GetProtocolVersion(version string) (string, error) {
return version, nil
}
// StartBackup starts a new backup.
func (client *mockAdminClient) StartBackup(url string, snapshotPeriodSeconds int) error {
adminClientMutex.Lock()
defer adminClientMutex.Unlock()
client.Backups["default"] = fdbtypes.FoundationDBBackupStatusBackupDetails{
URL: url,
Running: true,
SnapshotPeriodSeconds: snapshotPeriodSeconds,
}
return nil
}
// PauseBackups pauses backups.
func (client *mockAdminClient) PauseBackups() error {
adminClientMutex.Lock()
defer adminClientMutex.Unlock()
for tag, backup := range client.Backups {
backup.Paused = true
client.Backups[tag] = backup
}
return nil
}
// ResumeBackups resumes backups.
func (client *mockAdminClient) ResumeBackups() error {
adminClientMutex.Lock()
defer adminClientMutex.Unlock()
for tag, backup := range client.Backups {
backup.Paused = false
client.Backups[tag] = backup
}
return nil
}
// ModifyBackup reconfigures the backup.
func (client *mockAdminClient) ModifyBackup(snapshotPeriodSeconds int) error {
adminClientMutex.Lock()
defer adminClientMutex.Unlock()
backup := client.Backups["default"]
backup.SnapshotPeriodSeconds = snapshotPeriodSeconds
client.Backups["default"] = backup
return nil
}
// StopBackup stops a backup.
func (client *mockAdminClient) StopBackup(url string) error {
adminClientMutex.Lock()
defer adminClientMutex.Unlock()
for tag, backup := range client.Backups {
if backup.URL == url {
backup.Running = false
client.Backups[tag] = backup
return nil
}
}
return fmt.Errorf("No backup found for URL %s", url)
}
// GetBackupStatus gets the status of the current backup.
func (client *mockAdminClient) GetBackupStatus() (*fdbtypes.FoundationDBLiveBackupStatus, error) {
adminClientMutex.Lock()
defer adminClientMutex.Unlock()
status := &fdbtypes.FoundationDBLiveBackupStatus{}
tag := "default"
backup, present := client.Backups[tag]
if present {
status.DestinationURL = backup.URL
status.Status.Running = backup.Running
status.BackupAgentsPaused = backup.Paused
status.SnapshotIntervalSeconds = backup.SnapshotPeriodSeconds
}
return status, nil
}
// StartRestore starts a new restore.
func (client *mockAdminClient) StartRestore(url string, keyRanges []fdbtypes.FoundationDBKeyRange) error {
adminClientMutex.Lock()
defer adminClientMutex.Unlock()
client.restoreURL = url
return nil
}
// GetRestoreStatus gets the status of the current restore.
func (client *mockAdminClient) GetRestoreStatus() (string, error) {
adminClientMutex.Lock()
defer adminClientMutex.Unlock()
return fmt.Sprintf("%s\n", client.restoreURL), nil
}
// MockClientVersion returns a mocked client version
func (client *mockAdminClient) MockClientVersion(version string, clients []string) {
adminClientMutex.Lock()
defer adminClientMutex.Unlock()
if client.clientVersions == nil {
client.clientVersions = make(map[string][]string)
}
client.clientVersions[version] = clients
}
// MockAdditionalProcesses adds additional processes to the cluster status.
func (client *mockAdminClient) MockAdditionalProcesses(processes []fdbtypes.ProcessGroupStatus) {
adminClientMutex.Lock()
defer adminClientMutex.Unlock()
client.additionalProcesses = append(client.additionalProcesses, processes...)
}
// MockMissingProcessGroup updates the mock for whether a process group should
// be missing from the cluster status.
func (client *mockAdminClient) MockMissingProcessGroup(processGroupID string, missing bool) {
client.missingProcessGroups[processGroupID] = missing
}
// MockLocalityInfo sets mock locality information for a process.
func (client *mockAdminClient) MockLocalityInfo(processGroupID string, locality map[string]string) {
client.localityInfo[processGroupID] = locality
}
// MockIncorrectCommandLine updates the mock for whether a process group should
// be have an incorrect command-line.
func (client *mockAdminClient) MockIncorrectCommandLine(processGroupID string, incorrect bool) {
if client.incorrectCommandLines == nil {
client.incorrectCommandLines = make(map[string]bool)
}
client.incorrectCommandLines[processGroupID] = incorrect
}
// Close shuts down any resources for the client once it is no longer
// needed.
func (client *mockAdminClient) Close() error {
return nil
}
// FreezeStatus causes the GetStatus method to return its current value until
// UnfreezeStatus is called, or another method is called which would invalidate
// the status.
func (client *mockAdminClient) FreezeStatus() error {
status, err := client.GetStatus()
if err != nil {
return err
}
adminClientMutex.Lock()
defer adminClientMutex.Unlock()
client.frozenStatus = status
return nil
}
// UnfreezeStatus causes the admin client to start recalculating the status
// on every call to GetStatus
func (client *mockAdminClient) UnfreezeStatus() {
adminClientMutex.Lock()
defer adminClientMutex.Unlock()
client.frozenStatus = nil
}
// GetCoordinatorSet gets the current coordinators from the status
func (client *mockAdminClient) GetCoordinatorSet() (map[string]struct{}, error) {
status, err := client.GetStatus()
if err != nil {
return nil, err
}
return internal.GetCoordinatorsFromStatus(status), nil
}