-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathadmin_client.go
More file actions
1393 lines (1180 loc) · 42.4 KB
/
admin_client.go
File metadata and controls
1393 lines (1180 loc) · 42.4 KB
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
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* fdbadminclient.go
*
* This source file is part of the FoundationDB open source project
*
* Copyright 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 fdbclient
import (
"bytes"
"context"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"path"
"regexp"
"strconv"
"strings"
"time"
"github.com/FoundationDB/fdb-kubernetes-operator/v2/internal/metrics"
fdbv1beta2 "github.com/FoundationDB/fdb-kubernetes-operator/v2/api/v1beta2"
"github.com/FoundationDB/fdb-kubernetes-operator/v2/internal"
"github.com/FoundationDB/fdb-kubernetes-operator/v2/pkg/fdbadminclient"
"github.com/FoundationDB/fdb-kubernetes-operator/v2/pkg/fdbstatus"
"github.com/apple/foundationdb/bindings/go/src/fdb"
"github.com/go-logr/logr"
"sigs.k8s.io/controller-runtime/pkg/client"
)
const (
fdbcliStr = "fdbcli"
fdbbackupStr = "fdbbackup"
fdbrestoreStr = "fdbrestore"
)
var maxCommandOutput = parseMaxCommandOutput()
func parseMaxCommandOutput() int {
flag := os.Getenv("MAX_FDB_CLI_OUTPUT_LENGTH")
if flag == "" {
return 20
}
result, err := strconv.Atoi(flag)
if err != nil {
panic(err)
}
return result
}
var protocolVersionRegex = regexp.MustCompile(`(?m)^protocol (\w+)$`)
// cliAdminClient provides an implementation of the admin interface using the FDB CLI.
type cliAdminClient struct {
// Cluster is the reference to the cluster model.
Cluster *fdbv1beta2.FoundationDBCluster
// custom parameters that should be set.
knobs []string
// log implementation for logging output
log logr.Logger
// cmdRunner is an interface to run commands. In the real runner we use the exec package to execute binaries. In
// the mock runner we can define mocked output for better integration tests.
cmdRunner commandRunner
// fdbLibClient is an interface to interact with a FDB cluster over the FDB client libraries. In the real fdb lib client
// we will issue the actual requests against FDB. In the mock runner we will return predefined output.
fdbLibClient fdbLibClient
// timeout defines the timeout that should be used for interacting with FDB.
timeout time.Duration
}
// NewCliAdminClient generates an Admin client for a cluster
func NewCliAdminClient(
cluster *fdbv1beta2.FoundationDBCluster,
_ client.Client,
logger logr.Logger,
) (fdbadminclient.AdminClient, error) {
return &cliAdminClient{
Cluster: cluster,
log: logger,
cmdRunner: &realCommandRunner{log: logger},
fdbLibClient: &realFdbLibClient{
cluster: cluster,
logger: logger,
},
}, nil
}
// cliCommand describes a command that we are running against FDB.
type cliCommand struct {
// binary is the binary to run.
binary string
// command is the command to execute.
command string
// version is the version of FoundationDB we should run.
version string
// args provides alternative arguments in place of the exec command.
args []string
// timeout provides a way to overwrite the default cli timeout.
timeout time.Duration
// ignoreClusterFile if set to true, the cluster file will not be added to the arguments.
ignoreClusterFile bool
}
// hasTimeoutArg determines whether a command accepts a timeout argument.
func (command cliCommand) hasTimeoutArg() bool {
return command.isFdbCli()
}
// getLogDirParameter returns the log dir parameter for a command, depending on the binary the log dir parameter
// has a dash or not.
func (command cliCommand) getLogDirParameter() string {
if command.isFdbCli() {
return "--log-dir"
}
return "--logdir"
}
// getClusterFileFlag gets the flag this command uses for its cluster file
// argument.
func (command cliCommand) getClusterFileFlag() string {
if command.binary == fdbrestoreStr {
return "--dest_cluster_file"
}
return "-C"
}
// getTimeout returns the timeout for the command
func (command cliCommand) getTimeout() time.Duration {
if command.timeout != 0 {
return command.timeout
}
return DefaultCLITimeout
}
// getVersion returns the versions defined in the command or if not present returns the running version of the
// cluster.
func (command cliCommand) getVersion(cluster *fdbv1beta2.FoundationDBCluster) string {
if command.version != "" {
return command.version
}
return cluster.GetRunningVersion()
}
// getBinary returns the binary of the command, if unset this will default to fdbcli.
func (command cliCommand) getBinary() string {
if command.binary != "" {
return command.binary
}
return fdbcliStr
}
// isFdbCli returns true if the used binary is fdbcli.
func (command cliCommand) isFdbCli() bool {
return command.getBinary() == fdbcliStr
}
// getBinaryPath generates the path to an FDB binary.
func getBinaryPath(binaryName string, version string) string {
parsed, _ := fdbv1beta2.ParseFdbVersion(version)
return path.Join(os.Getenv("FDB_BINARY_DIR"), parsed.GetBinaryVersion(), binaryName)
}
func (client *cliAdminClient) getArgsAndTimeout(
command cliCommand,
clusterFile string,
) ([]string, time.Duration) {
args := make([]string, len(command.args))
copy(args, command.args)
if len(args) == 0 {
args = append(args, "--exec", command.command)
}
// If we want to print out the version we don't have to pass the cluster file path
if !command.ignoreClusterFile {
args = append(args, command.getClusterFileFlag(), clusterFile)
}
// We only want to pass the knobs to fdbbackup and fdbrestore
if !command.isFdbCli() {
args = append(args, client.knobs...)
}
traceDir := os.Getenv(fdbv1beta2.EnvNameFDBTraceLogDirPath)
if traceDir != "" {
args = append(args, "--log")
if command.isFdbCli() {
format := os.Getenv("FDB_NETWORK_OPTION_TRACE_FORMAT")
if format == "" {
format = "xml"
}
args = append(args, "--trace_format", format)
}
args = append(args, command.getLogDirParameter(), traceDir)
}
hardTimeout := command.getTimeout()
if command.hasTimeoutArg() {
args = append(args, "--timeout", strconv.Itoa(int(command.getTimeout().Seconds())))
hardTimeout += command.getTimeout()
}
return args, hardTimeout
}
// runCommand executes a command in the CLI.
func (client *cliAdminClient) runCommand(command cliCommand) (string, error) {
clusterFile, err := createClusterFileForCommandLine(client.Cluster)
if err != nil {
return "", err
}
defer func() {
_ = clusterFile.Close()
_ = os.Remove(clusterFile.Name())
}()
args, hardTimeout := client.getArgsAndTimeout(command, clusterFile.Name())
timeoutContext, cancelFunction := context.WithTimeout(context.Background(), hardTimeout)
defer cancelFunction()
output, err := client.cmdRunner.runCommand(
timeoutContext,
getBinaryPath(command.getBinary(), command.getVersion(client.Cluster)),
args...)
if err != nil {
// If we hit a timeout report it as a timeout error and don't log it, but let the caller take care of logging.
if strings.Contains(string(output), "Specified timeout reached") {
// See: https://apple.github.io/foundationdb/api-error-codes.html
// 1031: Operation aborted because the transaction timed out
return "", fdbv1beta2.TimeoutError{Err: err}
}
if strings.Contains(string(output), "Backup does not exist") {
return "", fdbv1beta2.BackupDoesNotExist{Err: err}
}
if strings.Contains(string(output), "A backup was not running on tag") {
return "", fdbv1beta2.BackupNotRunning{Err: err}
}
var exitError *exec.ExitError
if errors.As(err, &exitError) {
client.log.Error(
exitError,
"Error from FDB command",
"code",
exitError.ExitCode(),
"stdout",
string(output),
"stderr",
string(exitError.Stderr),
)
}
return "", err
}
outputString := string(output)
var debugOutput string
if len(outputString) > maxCommandOutput && maxCommandOutput > 0 {
debugOutput = outputString[0:maxCommandOutput] + "..."
} else {
debugOutput = outputString
}
client.log.Info("Command completed", "output", debugOutput)
return outputString, nil
}
// getStatusFromCli uses the fdbcli to connect to the FDB cluster
func (client *cliAdminClient) getStatusFromCli(
checkForProcesses bool,
) (*fdbv1beta2.FoundationDBStatus, error) {
// Always use the max timeout here. Otherwise we will retry multiple times with an increasing timeout. As the
// timeout is only the upper bound using directly the max timeout reduces the calls to a single call.
output, err := client.runCommand(
cliCommand{command: "status json", timeout: client.getTimeout()},
)
if err != nil {
return nil, err
}
contents, err := fdbstatus.RemoveWarningsInJSON(output)
if err != nil {
return nil, err
}
return parseMachineReadableStatus(client.log, contents, checkForProcesses)
}
// getStatus uses fdbcli to connect to the FDB cluster, if the cluster is upgraded and the initial version returns no processes
// the new version for fdbcli will be tried.
func (client *cliAdminClient) getStatus() (*fdbv1beta2.FoundationDBStatus, error) {
status, err := client.getStatusFromCli(true)
// If the cluster is under an upgrade and the getStatus call returns an error, we have to retry it with the new version,
// as it could be that the wrong version was selected.
if client.Cluster.IsBeingUpgradedWithVersionIncompatibleVersion() &&
internal.IsTimeoutError(err) {
client.log.V(1).
Info("retry fetching status with version specified in spec.Version", "error", err, "status", status)
// Create a copy of the cluster and make use of the desired version instead of the last observed running version.
clusterCopy := client.Cluster.DeepCopy()
clusterCopy.Status.RunningVersion = clusterCopy.Spec.Version
client.Cluster = clusterCopy
return client.getStatusFromCli(true)
}
return status, err
}
// GetStatus gets the database's status
func (client *cliAdminClient) GetStatus() (*fdbv1beta2.FoundationDBStatus, error) {
startTime := time.Now()
// This will call directly the database and fetch the status information from the system key space.
status, err := getStatusFromDB(client.fdbLibClient, client.log, client.getTimeout())
// There is a limitation in the multi version client if the cluster is only partially upgraded e.g. because not
// all fdbserver processes are restarted, then the multi version client sometimes picks the wrong version
// to connect to the cluster. This will result in an empty status only reporting the unreachable coordinators.
// In this case we want to fall back to use fdbcli which is version specific and will (hopefully) work.
// If we hit a timeout we will also use fdbcli to retry the get status command.
client.log.V(1).
Info("Result from multi version client (bindings)", "error", err, "status", status)
if client.Cluster.Status.Configured && internal.IsTimeoutError(err) &&
client.Cluster.IsBeingUpgradedWithVersionIncompatibleVersion() {
client.log.Info("retry fetching status with fdbcli instead of using the client library")
status, err = client.getStatus()
}
client.log.V(1).
Info("Completed GetStatus() call", "error", err, "status", status, "duration", time.Since(startTime).String())
return status, err
}
// ConfigureDatabase sets the database configuration
func (client *cliAdminClient) ConfigureDatabase(
configuration fdbv1beta2.DatabaseConfiguration,
newDatabase bool,
) error {
configurationString, err := configuration.GetConfigurationString()
if err != nil {
return err
}
if newDatabase {
configurationString = "new " + configurationString
}
_, err = client.runCommand(
cliCommand{command: fmt.Sprintf("configure %s", configurationString)},
)
return err
}
// SetMaintenanceZone places zone into maintenance mode
func (client *cliAdminClient) SetMaintenanceZone(zone string, timeoutSeconds int) error {
if client.Cluster.GetDatabaseInteractionMode() == fdbv1beta2.DatabaseInteractionModeMgmtAPI {
client.log.Info(
"setting maintenance zone with management API",
"zone",
zone,
"timeoutSeconds",
timeoutSeconds,
)
return client.executeTransactionForManagementAPI(func(tr fdb.Transaction) error {
// The value is a literal text of a non-negative double which represents the remaining time for the zone to be in maintenance.
tr.Set(
fdb.Key(path.Join("\xff\xff/management/maintenance/", zone)),
[]byte(fmt.Sprintf("%d.0", timeoutSeconds)),
)
return nil
})
}
_, err := client.runCommand(cliCommand{
command: fmt.Sprintf(
"maintenance on %s %s",
zone,
strconv.Itoa(timeoutSeconds)),
})
return err
}
// ResetMaintenanceMode switches of maintenance mode
func (client *cliAdminClient) ResetMaintenanceMode() error {
if client.Cluster.GetDatabaseInteractionMode() == fdbv1beta2.DatabaseInteractionModeMgmtAPI {
client.log.Info("reset maintenance zone with management API")
return client.executeTransactionForManagementAPI(func(tr fdb.Transaction) error {
keyRange, err := fdb.PrefixRange([]byte("\xff\xff/management/maintenance/"))
if err != nil {
return err
}
tr.ClearRange(keyRange)
return nil
})
}
_, err := client.runCommand(cliCommand{
command: "maintenance off",
})
return err
}
// ExcludeProcesses starts evacuating processes so that they can be removed from the database.
func (client *cliAdminClient) ExcludeProcesses(addresses []fdbv1beta2.ProcessAddress) error {
return client.ExcludeProcessesWithNoWait(addresses, client.Cluster.GetUseNonBlockingExcludes())
}
// getAddressStringsWithoutPorts will return a string with addresses or localities that can be used for exclusion
// or inclusion. If any of the addresses defines a port, it will be reset by this method to ensure the whole pod gets
// excluded or included.
func getAddressStringsWithoutPorts(addresses []fdbv1beta2.ProcessAddress) string {
// Ensure that the ports are set to 0, as the operator will always exclude whole pods.
for idx, address := range addresses {
if address.Port != 0 {
addresses[idx].Port = 0
}
}
return fdbv1beta2.ProcessAddressesStringWithoutFlags(addresses, " ")
}
// ExcludeProcessesWithNoWait starts evacuating processes so that they can be removed from the database. If noWait is
// set to true, the exclude command will not block until all data is moved away from the processes.
func (client *cliAdminClient) ExcludeProcessesWithNoWait(
addresses []fdbv1beta2.ProcessAddress,
noWait bool,
) error {
if len(addresses) == 0 {
return nil
}
if client.Cluster.GetDatabaseInteractionMode() == fdbv1beta2.DatabaseInteractionModeMgmtAPI {
localitiesToExclude, addressesToExclude := getAddressesAndLocalities(addresses)
client.log.Info(
"exclude processes with management API",
"addressesToExclude",
addressesToExclude,
"localitiesToExclude",
localitiesToExclude,
)
err := client.executeTransactionForManagementAPI(func(tr fdb.Transaction) error {
for _, addr := range addressesToExclude {
tr.Set(fdb.Key(path.Join("\xff\xff/management/excluded/", addr)), []byte{})
}
for _, locality := range localitiesToExclude {
tr.Set(
fdb.Key(path.Join("\xff\xff/management/excluded_locality/", locality)),
[]byte{},
)
}
return nil
})
if err != nil {
return err
}
if noWait {
return nil
}
// Ensure we are stopping the check after the timeout time.
timeout := time.Now().Add(client.timeout)
for {
err = client.executeTransactionForManagementAPI(func(tr fdb.Transaction) error {
inProgressKeyRange, err := fdb.PrefixRange(
[]byte("\xff\xff/management/in_progress_exclusion/"),
)
if err != nil {
return err
}
inProgressResults := tr.GetRange(inProgressKeyRange, fdb.RangeOptions{}).
GetSliceOrPanic()
inProgressExclusions := map[string]fdbv1beta2.None{}
for _, result := range inProgressResults {
inProgressExclusions[path.Base(result.Key.String())] = fdbv1beta2.None{}
}
client.log.V(1).
Info("found results for in progress exclusions", "inProgressResults", len(inProgressResults), "inProgressExclusions", inProgressExclusions)
var inProgress []string
if len(inProgressExclusions) > 0 {
for _, addr := range addressesToExclude {
if _, ok := inProgressExclusions[addr]; ok {
inProgress = append(inProgress, addr)
}
}
for _, locality := range localitiesToExclude {
if _, ok := inProgressExclusions[locality]; ok {
inProgress = append(inProgress, locality)
}
}
}
if len(inProgress) > 0 {
return fmt.Errorf(
"exclusion still in progress: %s",
strings.Join(inProgress, ","),
)
}
return nil
})
if err == nil {
return nil
}
client.log.V(1).Info("checking exclusion state", "err", err.Error())
if time.Now().After(timeout) {
return err
}
time.Sleep(1 * time.Second)
}
}
var excludeCommand strings.Builder
excludeCommand.WriteString("exclude ")
if noWait {
excludeCommand.WriteString("no_wait ")
}
excludeCommand.WriteString(getAddressStringsWithoutPorts(addresses))
_, err := client.runCommand(
cliCommand{command: excludeCommand.String(), timeout: client.getTimeout()},
)
return err
}
func getAddressesAndLocalities(processAddresses []fdbv1beta2.ProcessAddress) ([]string, []string) {
localities := make([]string, 0, len(processAddresses))
addresses := make([]string, 0, len(processAddresses))
for _, address := range processAddresses {
address.Port = 0
addr := address.String()
if strings.HasPrefix(addr, fdbv1beta2.FDBLocalityExclusionPrefix) {
localities = append(localities, addr)
continue
}
addresses = append(addresses, addr)
}
return localities, addresses
}
// IncludeProcesses removes processes from the exclusion list and allows them to take on roles again.
func (client *cliAdminClient) IncludeProcesses(addresses []fdbv1beta2.ProcessAddress) error {
if len(addresses) == 0 {
return nil
}
if client.Cluster.GetDatabaseInteractionMode() == fdbv1beta2.DatabaseInteractionModeMgmtAPI {
localitiesToInclude, addressesToInclude := getAddressesAndLocalities(addresses)
client.log.V(1).
Info("include processes with management API", "addressesToInclude", addressesToInclude, "localitiesToInclude", localitiesToInclude)
return client.executeTransactionForManagementAPI(func(tr fdb.Transaction) error {
for _, addr := range addressesToInclude {
tr.Clear(fdb.Key(path.Join("\xff\xff/management/excluded/", addr)))
}
for _, locality := range localitiesToInclude {
tr.Clear(fdb.Key(path.Join("\xff\xff/management/excluded_locality/", locality)))
}
return nil
})
}
_, err := client.runCommand(cliCommand{command: fmt.Sprintf(
"include %s",
getAddressStringsWithoutPorts(addresses),
)})
return err
}
// GetExclusions gets a list of the addresses currently excluded from the
// database.
func (client *cliAdminClient) GetExclusions() ([]fdbv1beta2.ProcessAddress, error) {
if client.Cluster.GetDatabaseInteractionMode() == fdbv1beta2.DatabaseInteractionModeFdbcli {
status, err := client.GetStatus()
if err != nil {
return nil, err
}
return fdbstatus.GetExclusions(status)
}
var currentExclusions []fdbv1beta2.ProcessAddress
client.log.V(1).Info("getting current exclusions with management API")
err := client.executeTransactionForManagementAPI(func(tr fdb.Transaction) error {
exclusions, err := tr.GetRange(fdb.KeyRange{
Begin: fdb.Key("\xff\xff/management/excluded/"),
End: fdb.Key("\xff\xff/management/excluded0"),
}, fdb.RangeOptions{}).GetSliceWithError()
if err != nil {
return err
}
for _, exclusion := range exclusions {
addr := path.Base(exclusion.Key.String())
client.log.V(1).Info("found excluded addr", "addr", addr)
parsed, err := fdbv1beta2.ParseProcessAddress(addr)
if err != nil {
return err
}
currentExclusions = append(currentExclusions, parsed)
}
exclusions, err = tr.GetRange(fdb.KeyRange{
Begin: fdb.Key("\xff\xff/management/excluded_locality/"),
End: fdb.Key("\xff\xff/management/excluded_locality0"),
}, fdb.RangeOptions{}).GetSliceWithError()
if err != nil {
return err
}
for _, exclusion := range exclusions {
locality := path.Base(exclusion.Key.String())
client.log.V(1).Info("found excluded locality", "locality", locality)
currentExclusions = append(currentExclusions, fdbv1beta2.ProcessAddress{
StringAddress: locality,
})
}
return nil
})
client.log.V(1).
Info("done getting current exclusions with management API", "currentExclusions", currentExclusions, "err", err)
if err != nil {
return nil, err
}
return currentExclusions, nil
}
func getKillCommand(addresses []fdbv1beta2.ProcessAddress, isUpgrade bool) string {
var killCmd strings.Builder
addrString := fdbv1beta2.ProcessAddressesStringWithoutFlags(addresses, " ")
killCmd.WriteString("kill; kill ")
killCmd.WriteString(addrString)
if isUpgrade {
killCmd.WriteString("; sleep 1; kill ")
killCmd.WriteString(addrString)
}
killCmd.WriteString("; sleep 5")
return killCmd.String()
}
func (client *cliAdminClient) killWithManagementAPI(addresses []fdbv1beta2.ProcessAddress) error {
db, err := getFDBDatabase(client.Cluster)
if err != nil {
return err
}
return db.RebootWorker(fdbv1beta2.ProcessAddressesStringWithoutFlags(addresses, ","), false, 0)
}
// KillProcesses restarts processes
func (client *cliAdminClient) KillProcesses(addresses []fdbv1beta2.ProcessAddress) error {
if len(addresses) == 0 {
return nil
}
if client.Cluster.GetDatabaseInteractionMode() == fdbv1beta2.DatabaseInteractionModeMgmtAPI {
return client.killWithManagementAPI(addresses)
}
// Run the kill command once with the max timeout to reduce the risk of multiple recoveries happening.
_, err := client.runCommand(
cliCommand{command: getKillCommand(addresses, false), timeout: client.getTimeout()},
)
return err
}
// KillProcessesForUpgrade restarts processes for upgrades, this will issue 2 kill commands to make sure all
// processes are restarted.
func (client *cliAdminClient) KillProcessesForUpgrade(addresses []fdbv1beta2.ProcessAddress) error {
if len(addresses) == 0 {
return nil
}
if client.Cluster.GetDatabaseInteractionMode() == fdbv1beta2.DatabaseInteractionModeMgmtAPI {
return client.killWithManagementAPI(addresses)
}
// Run the kill command once with the max timeout to reduce the risk of multiple recoveries happening.
_, err := client.runCommand(
cliCommand{command: getKillCommand(addresses, true), timeout: client.getTimeout()},
)
return err
}
// ChangeCoordinators changes the coordinator set
func (client *cliAdminClient) ChangeCoordinators(
addresses []fdbv1beta2.ProcessAddress,
) (string, error) {
if client.Cluster.GetDatabaseInteractionMode() == fdbv1beta2.DatabaseInteractionModeMgmtAPI {
coordinatorString := fdbv1beta2.ProcessAddressesString(addresses, ",")
client.log.Info(
"change coordinators with management API",
"coordinatorString",
coordinatorString,
)
err := client.executeTransactionForManagementAPI(func(tr fdb.Transaction) error {
tr.Set(
fdb.Key("\xff\xff/configuration/coordinators/processes"),
[]byte(coordinatorString),
)
return nil
})
if err != nil {
return "", err
}
} else {
_, err := client.runCommand(cliCommand{command: fmt.Sprintf(
"coordinators %s",
fdbv1beta2.ProcessAddressesString(addresses, " "),
)})
if err != nil {
return "", err
}
}
// Increment the coordinator changes counter for this cluster
metrics.CoordinatorChangesCounter.WithLabelValues(client.Cluster.Namespace, client.Cluster.Name).
Inc()
return getConnectionStringFromDB(client.fdbLibClient, client.getTimeout())
}
// VersionSupported reports whether we can support a cluster with a given
// version.
func (client *cliAdminClient) VersionSupported(versionString string) (bool, error) {
// TODO(johscheuer): In the future make use of GetClientStatus(). Available from 7.4:
// https://github.com/apple/foundationdb/blob/release-7.4/bindings/go/src/fdb/database.go#L140-L161
// Should we backport this feature to the 7.1 bindings?
_, err := os.Stat(getBinaryPath(fdbcliStr, versionString))
if err != nil {
return false, err
}
return true, nil
}
// GetProtocolVersion determines the protocol version that is used by a
// version of FDB.
func (client *cliAdminClient) GetProtocolVersion(version string) (string, error) {
// TODO(johscheuer): In the future make use of GetClientStatus(). Available from 7.4:
// https://github.com/apple/foundationdb/blob/release-7.4/bindings/go/src/fdb/database.go#L140-L161
// Should we backport this feature to the 7.1 bindings?
output, err := client.runCommand(
cliCommand{args: []string{"--version"}, version: version, ignoreClusterFile: true},
)
if err != nil {
return "", err
}
protocolVersionMatch := protocolVersionRegex.FindStringSubmatch(output)
if len(protocolVersionMatch) < 2 {
return "", fmt.Errorf(
"failed to parse protocol version for %s. Version output:\n%s",
version,
output,
)
}
return protocolVersionMatch[1], nil
}
func (client *cliAdminClient) StartBackup(backup *fdbv1beta2.FoundationDBBackup) error {
backupURL, err := backup.BackupURL()
if err != nil {
return err
}
args := []string{
"start",
"-d",
backupURL,
}
// Add continuous backup flags only if backup mode is continuous.
if backup.GetBackupMode() == fdbv1beta2.BackupModeContinuous {
args = append(args, "-s", strconv.Itoa(backup.SnapshotPeriodSeconds()), "-z")
}
encryptionKeyPath, err := backup.GetEncryptionKey()
if err != nil {
return err
}
if encryptionKeyPath != "" {
args = append(args, "--encryption-key-file", encryptionKeyPath)
}
if backup.GetBackupType() == fdbv1beta2.BackupTypePartitionedLog {
args = append(args, "--partitioned-log-experimental")
}
_, err = client.runCommand(cliCommand{
binary: fdbbackupStr,
args: args,
})
return err
}
// StopBackup stops a backup.
func (client *cliAdminClient) StopBackup(_ *fdbv1beta2.FoundationDBBackup) error {
_, err := client.runCommand(cliCommand{
binary: fdbbackupStr,
args: []string{
"discontinue",
},
})
return err
}
// AbortBackup will abort a running backup.
func (client *cliAdminClient) AbortBackup(_ *fdbv1beta2.FoundationDBBackup) error {
_, err := client.runCommand(cliCommand{
binary: fdbbackupStr,
args: []string{
"abort",
},
})
return err
}
// DeleteBackup deletes all data related to a backup.
func (client *cliAdminClient) DeleteBackup(backup *fdbv1beta2.FoundationDBBackup) error {
backupURL, err := backup.BackupURL()
if err != nil {
return err
}
_, err = client.runCommand(cliCommand{
binary: fdbbackupStr,
args: []string{
"delete",
"-d",
backupURL,
},
// Increase the default timeout here, deleting large backups will probably take even more time.
timeout: 10 * time.Minute,
// The delete command doesn't use the cluster file.
ignoreClusterFile: true,
})
return err
}
// PauseBackups pauses the backups.
func (client *cliAdminClient) PauseBackups() error {
_, err := client.runCommand(cliCommand{
binary: fdbbackupStr,
args: []string{
"pause",
},
})
return err
}
// ResumeBackups resumes the backups.
func (client *cliAdminClient) ResumeBackups() error {
_, err := client.runCommand(cliCommand{
binary: fdbbackupStr,
args: []string{
"resume",
},
})
return err
}
// ModifyBackup updates the backup parameters.
func (client *cliAdminClient) ModifyBackup(backup *fdbv1beta2.FoundationDBBackup) error {
backupURL, err := backup.BackupURL()
if err != nil {
return err
}
_, err = client.runCommand(cliCommand{
binary: fdbbackupStr,
args: []string{
"modify",
"-s",
strconv.Itoa(backup.SnapshotPeriodSeconds()),
"-d",
backupURL,
},
})
return err
}
// GetBackupStatus gets the status of the current backup.
func (client *cliAdminClient) GetBackupStatus() (*fdbv1beta2.FoundationDBLiveBackupStatus, error) {
statusString, err := client.runCommand(cliCommand{
binary: fdbbackupStr,
args: []string{
"status",
"--json",
},
})
if err != nil {
return nil, err
}
statusBytes, err := fdbstatus.RemoveWarningsInJSON(statusString)
if err != nil {
return nil, err
}
status := &fdbv1beta2.FoundationDBLiveBackupStatus{}
err = json.Unmarshal(statusBytes, &status)
client.log.V(1).Info("backup status", "status", string(statusBytes), "error", err)
if err != nil {
return nil, err
}
return status, nil
}
// StartRestore starts a new restore.
func (client *cliAdminClient) StartRestore(
url string,
restore fdbv1beta2.FoundationDBRestore,
) error {
args := []string{
"start",
"-r",
url,
}
fdbVersion, verErr := fdbv1beta2.ParseFdbVersion(client.Cluster.GetRunningVersion())
if verErr != nil {
return verErr