Skip to content

Commit 1b53cc4

Browse files
committed
Modernize go code
1 parent b431f35 commit 1b53cc4

32 files changed

+86
-114
lines changed

api/v1beta2/foundationdb_database_configuration.go

+4-4
Original file line numberDiff line numberDiff line change
@@ -925,10 +925,10 @@ var versionFlagIndices = make(map[string]int)
925925
var roleNames = fieldNames(RoleCounts{})
926926

927927
// fieldNames provides the names of fields on a structure.
928-
func fieldNames(value interface{}) []ProcessClass {
928+
func fieldNames(value any) []ProcessClass {
929929
countType := reflect.TypeOf(value)
930930
names := make([]ProcessClass, 0, countType.NumField())
931-
for index := 0; index < countType.NumField(); index++ {
931+
for index := range countType.NumField() {
932932
tag := strings.Split(countType.Field(index).Tag.Get("json"), ",")
933933
names = append(names, ProcessClass(tag[0]))
934934
}
@@ -951,10 +951,10 @@ func init() {
951951

952952
// fieldIndices provides a map from the names of fields in a structure to the
953953
// index of each field in the list of fields.
954-
func fieldIndices(value interface{}, result interface{}, keyType reflect.Type) {
954+
func fieldIndices(value any, result any, keyType reflect.Type) {
955955
countType := reflect.TypeOf(value)
956956
resultValue := reflect.ValueOf(result)
957-
for index := 0; index < countType.NumField(); index++ {
957+
for index := range countType.NumField() {
958958
tag := strings.Split(countType.Field(index).Tag.Get("json"), ",")
959959
resultValue.SetMapIndex(reflect.ValueOf(tag[0]).Convert(keyType), reflect.ValueOf(index))
960960
}

api/v1beta2/foundationdb_process_address.go

+3-5
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ import (
2424
"fmt"
2525
"net"
2626
"regexp"
27-
"sort"
27+
"slices"
2828
"strconv"
2929
"strings"
3030
)
@@ -96,9 +96,7 @@ func (address ProcessAddress) SortedFlags() []string {
9696
}
9797
}
9898

99-
sort.Slice(flags, func(i int, j int) bool {
100-
return flags[i] < flags[j]
101-
})
99+
slices.Sort(flags)
102100

103101
return flags
104102
}
@@ -149,7 +147,7 @@ func (address *ProcessAddress) UnmarshalJSON(data []byte) error {
149147

150148
// MarshalJSON defines the parsing method for the ProcessAddress field from struct to JSON
151149
func (address ProcessAddress) MarshalJSON() ([]byte, error) {
152-
return []byte(fmt.Sprintf("\"%s\"", address.String())), nil
150+
return fmt.Appendf(nil, "\"%s\"", address.String()), nil
153151
}
154152

155153
// ParseProcessAddress parses a structured address from its string

api/v1beta2/foundationdbcluster_types.go

+9-20
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ import (
3333
"k8s.io/apimachinery/pkg/api/equality"
3434
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
3535
"k8s.io/utils/pointer"
36+
"slices"
3637
)
3738

3839
// +kubebuilder:object:root=true
@@ -1799,7 +1800,7 @@ func (str *ConnectionString) String() string {
17991800
// GenerateNewGenerationID builds a new generation ID
18001801
func (str *ConnectionString) GenerateNewGenerationID() error {
18011802
id := strings.Builder{}
1802-
for i := 0; i < 32; i++ {
1803+
for range 32 {
18031804
err := id.WriteByte(alphanum[rand.Intn(len(alphanum))])
18041805
if err != nil {
18051806
return err
@@ -2022,19 +2023,11 @@ func (cluster *FoundationDBCluster) ProcessGroupIsBeingRemoved(processGroupID Pr
20222023
}
20232024
}
20242025

2025-
for _, id := range cluster.Spec.ProcessGroupsToRemove {
2026-
if id == processGroupID {
2027-
return true
2028-
}
2029-
}
2030-
2031-
for _, id := range cluster.Spec.ProcessGroupsToRemoveWithoutExclusion {
2032-
if id == processGroupID {
2033-
return true
2034-
}
2026+
if slices.Contains(cluster.Spec.ProcessGroupsToRemove, processGroupID) {
2027+
return true
20352028
}
20362029

2037-
return false
2030+
return slices.Contains(cluster.Spec.ProcessGroupsToRemoveWithoutExclusion, processGroupID)
20382031
}
20392032

20402033
// ShouldUseLocks determine whether we should use locks to coordinator global
@@ -2262,20 +2255,16 @@ const (
22622255
// AddServersPerDisk adds serverPerDisk to the status field to keep track which ConfigMaps should be kept
22632256
func (clusterStatus *FoundationDBClusterStatus) AddServersPerDisk(serversPerDisk int, pClass ProcessClass) {
22642257
if pClass == ProcessClassStorage {
2265-
for _, curServersPerDisk := range clusterStatus.StorageServersPerDisk {
2266-
if curServersPerDisk == serversPerDisk {
2267-
return
2268-
}
2258+
if slices.Contains(clusterStatus.StorageServersPerDisk, serversPerDisk) {
2259+
return
22692260
}
22702261
clusterStatus.StorageServersPerDisk = append(clusterStatus.StorageServersPerDisk, serversPerDisk)
22712262
return
22722263
}
22732264

22742265
if pClass.SupportsMultipleLogServers() {
2275-
for _, curServersPerDisk := range clusterStatus.LogServersPerDisk {
2276-
if curServersPerDisk == serversPerDisk {
2277-
return
2278-
}
2266+
if slices.Contains(clusterStatus.LogServersPerDisk, serversPerDisk) {
2267+
return
22792268
}
22802269
clusterStatus.LogServersPerDisk = append(clusterStatus.LogServersPerDisk, serversPerDisk)
22812270
}

controllers/add_process_groups.go

+2-5
Original file line numberDiff line numberDiff line change
@@ -56,10 +56,7 @@ func (a addProcessGroups) reconcile(ctx context.Context, r *FoundationDBClusterR
5656

5757
hasNewProcessGroups := false
5858
for _, processClass := range fdbv1beta2.ProcessClasses {
59-
desiredCount := desiredCounts[processClass]
60-
if desiredCount < 0 {
61-
desiredCount = 0
62-
}
59+
desiredCount := max(desiredCounts[processClass], 0)
6360
newCount := desiredCount - processCounts[processClass]
6461
if newCount <= 0 {
6562
continue
@@ -73,7 +70,7 @@ func (a addProcessGroups) reconcile(ctx context.Context, r *FoundationDBClusterR
7370
hasNewProcessGroups = true
7471
logger.Info("Adding new Process Groups", "processClass", processClass, "newCount", newCount, "desiredCount", desiredCount, "currentCount", processCounts[processClass])
7572
r.Recorder.Event(cluster, corev1.EventTypeNormal, "AddingProcesses", fmt.Sprintf("Adding %d %s processes", newCount, processClass))
76-
for i := 0; i < newCount; i++ {
73+
for range newCount {
7774
processGroupID := cluster.GetNextRandomProcessGroupIDWithExclusions(processClass, processGroupIDs[processClass], exclusions)
7875
logger.Info("Adding new Process Group to cluster", "processClass", processClass, "processGroupID", processGroupID, "exclusions", exclusions)
7976
cluster.Status.ProcessGroups = append(cluster.Status.ProcessGroups, fdbv1beta2.NewProcessGroupStatus(processGroupID, processClass, nil))

controllers/add_process_groups_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,7 @@ var _ = Describe("add_process_groups", func() {
234234
excludedCnt := 100
235235
exclusions := make([]fdbv1beta2.ProcessAddress, 0, excludedCnt)
236236
excludedProcessGroupIDs = map[fdbv1beta2.ProcessGroupID]fdbv1beta2.None{}
237-
for i := 0; i < excludedCnt; i++ {
237+
for i := range excludedCnt {
238238
processGroupID := fdbv1beta2.ProcessGroupID(fmt.Sprintf("storage-%d", i))
239239
if _, ok := currentProcessGroupIDs[processGroupID]; ok {
240240
continue

controllers/bounce_processes.go

+1-4
Original file line numberDiff line numberDiff line change
@@ -99,10 +99,7 @@ func (c bounceProcesses) reconcile(_ context.Context, r *FoundationDBClusterReco
9999
if err != nil {
100100
r.Recorder.Event(cluster, corev1.EventTypeNormal, "NeedsBounce", err.Error())
101101
// Retry after we waited the minimum uptime or at least 15 seconds.
102-
delayTime := cluster.GetMinimumUptimeSecondsForBounce() - int(currentMinimumUptime)
103-
if delayTime < 15 {
104-
delayTime = 15
105-
}
102+
delayTime := max(cluster.GetMinimumUptimeSecondsForBounce()-int(currentMinimumUptime), 15)
106103

107104
return &requeue{
108105
message: err.Error(),

controllers/cluster_controller_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -694,7 +694,7 @@ var _ = Describe("cluster_controller", func() {
694694

695695
sortPodsByName(pods)
696696

697-
for i := 0; i < 17; i++ {
697+
for i := range 17 {
698698
Expect(pods.Items[i].Name).To(Equal(originalPods.Items[i].Name))
699699
}
700700
})

controllers/controllers.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ type requeue struct {
103103
}
104104

105105
// processRequeue interprets a requeue result from a subreconciler.
106-
func processRequeue(requeue *requeue, subReconciler interface{}, object runtime.Object, recorder record.EventRecorder, logger logr.Logger) (ctrl.Result, error) {
106+
func processRequeue(requeue *requeue, subReconciler any, object runtime.Object, recorder record.EventRecorder, logger logr.Logger) (ctrl.Result, error) {
107107
curLog := logger.WithValues("reconciler", fmt.Sprintf("%T", subReconciler), "requeueAfter", requeue.delay)
108108
if requeue.message == "" && requeue.curError != nil {
109109
requeue.message = requeue.curError.Error()

controllers/replace_failed_process_groups_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ var _ = Describe("replace_failed_process_groups", func() {
129129

130130
BeforeEach(func() {
131131
targetProcessGroups = make([]fdbv1beta2.ProcessGroupID, 2)
132-
for i := 0; i < 2; i++ {
132+
for i := range 2 {
133133
targetProcessGroup := cluster.Status.ProcessGroups[i]
134134
timestamp := time.Now().Add(-10 * time.Minute).Unix()
135135
targetProcessGroup.UpdateCondition(fdbv1beta2.NodeTaintDetected, true)

controllers/update_backup_status.go

+1-4
Original file line numberDiff line numberDiff line change
@@ -56,10 +56,7 @@ func (s updateBackupStatus) reconcile(ctx context.Context, r *FoundationDBBackup
5656
}
5757

5858
if currentBackupDeployment != nil && desiredBackupDeployment != nil {
59-
status.AgentCount = int(currentBackupDeployment.Status.ReadyReplicas)
60-
if status.AgentCount > int(currentBackupDeployment.Status.UpdatedReplicas) {
61-
status.AgentCount = int(currentBackupDeployment.Status.UpdatedReplicas)
62-
}
59+
status.AgentCount = min(int(currentBackupDeployment.Status.ReadyReplicas), int(currentBackupDeployment.Status.UpdatedReplicas))
6360
generationsMatch := currentBackupDeployment.Status.ObservedGeneration == currentBackupDeployment.ObjectMeta.Generation
6461

6562
annotationChange := mergeAnnotations(&currentBackupDeployment.ObjectMeta, desiredBackupDeployment.ObjectMeta)

controllers/update_status.go

+2-7
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ import (
4343
k8serrors "k8s.io/apimachinery/pkg/api/errors"
4444
"k8s.io/apimachinery/pkg/types"
4545
"k8s.io/utils/pointer"
46+
"slices"
4647
)
4748

4849
// updateStatus provides a reconciliation step for updating the status in the
@@ -561,13 +562,7 @@ func validateProcessGroups(ctx context.Context, r *FoundationDBClusterReconciler
561562
status.AddServersPerDisk(processCount, processGroup.ProcessClass)
562563

563564
imageType := internal.GetImageType(pod)
564-
imageTypeFound := false
565-
for _, currentImageType := range status.ImageTypes {
566-
if imageType == currentImageType {
567-
imageTypeFound = true
568-
break
569-
}
570-
}
565+
imageTypeFound := slices.Contains(status.ImageTypes, imageType)
571566
if !imageTypeFound {
572567
status.ImageTypes = append(status.ImageTypes, imageType)
573568
}

e2e/fixtures/chaos_network.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ func (factory *Factory) InjectNetworkLoss(lossPercentage string, source chaosmes
7878
// InjectNetworkLossBetweenPods Injects network loss b/w each combination of podGroups.
7979
func (factory *Factory) InjectNetworkLossBetweenPods(pods []chaosmesh.PodSelectorSpec, loss string) {
8080
count := len(pods)
81-
for i := 0; i < count; i++ {
81+
for i := range count {
8282
for j := i + 1; j < count; j++ {
8383
factory.InjectNetworkLoss(loss, pods[i], pods[j], chaosmesh.Both)
8484
}

e2e/fixtures/fdb_backup.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -216,14 +216,14 @@ func (fdbBackup *FdbBackup) WaitForRestorableVersion(version uint64) {
216216
false,
217217
)
218218
g.Expect(err).NotTo(gomega.HaveOccurred())
219-
var result map[string]interface{}
219+
var result map[string]any
220220
g.Expect(json.Unmarshal([]byte(out), &result)).NotTo(gomega.HaveOccurred())
221221

222222
restorable, ok := result["Restorable"].(bool)
223223
g.Expect(ok).To(gomega.BeTrue())
224224
g.Expect(restorable).To(gomega.BeTrue())
225225

226-
restorablePoint, ok := result["LatestRestorablePoint"].(map[string]interface{})
226+
restorablePoint, ok := result["LatestRestorablePoint"].(map[string]any)
227227
g.Expect(ok).To(gomega.BeTrue())
228228

229229
restorableVersion, ok := restorablePoint["Version"].(float64)

e2e/fixtures/fdb_cluster.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -1825,7 +1825,7 @@ func (fdbCluster *FdbCluster) GenerateRandomValues(
18251825
res := make([]KeyValue, 0, n)
18261826
index := []byte{'a'}
18271827
var err error
1828-
for i := 0; i < n; i++ {
1828+
for range n {
18291829
res = append(res, KeyValue{
18301830
Key: append([]byte{prefix}, index...),
18311831
Value: []byte(fdbCluster.factory.RandStringRunes(4)),

e2e/fixtures/fdb_cluster_creation_tracker.go

+6-6
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,9 @@ import (
3535
// CreationTrackerLogger is an interface that can be used to log the time between different creation steps.
3636
type CreationTrackerLogger interface {
3737
// NewEntry adds an entry to the internal map.
38-
NewEntry() map[string]interface{}
38+
NewEntry() map[string]any
3939
// Log will write the values in the map directly to the logger.
40-
Log(values map[string]interface{}) error
40+
Log(values map[string]any) error
4141
// Flush will write all values from the entry map to the logger.
4242
Flush() error
4343
}
@@ -51,12 +51,12 @@ func NewDefaultCreationTrackerLogger() CreationTrackerLogger {
5151
type DefaultCreationTrackerLogger struct{}
5252

5353
// NewEntry adds an entry to the internal map.
54-
func (logger *DefaultCreationTrackerLogger) NewEntry() map[string]interface{} {
55-
return map[string]interface{}{}
54+
func (logger *DefaultCreationTrackerLogger) NewEntry() map[string]any {
55+
return map[string]any{}
5656
}
5757

5858
// Log will write the values in the map directly to the logger.
59-
func (logger *DefaultCreationTrackerLogger) Log(_ map[string]interface{}) error {
59+
func (logger *DefaultCreationTrackerLogger) Log(_ map[string]any) error {
6060
return nil
6161
}
6262

@@ -132,7 +132,7 @@ func (tracker *fdbClusterCreationTracker) nextStep() {
132132
log.Println("Finished step", tracker.currentStep.String(), "in", duration)
133133

134134
// Log the duration in milliseconds
135-
gomega.Expect(tracker.logger.Log(map[string]interface{}{
135+
gomega.Expect(tracker.logger.Log(map[string]any{
136136
tracker.currentStep.String(): duration.Milliseconds(),
137137
})).NotTo(gomega.HaveOccurred())
138138
}

e2e/fixtures/fixtures.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ func (shutdown *ShutdownHooks) Defer(f func() error) {
4343
}
4444

4545
// ToJSON tries to convert any object to a string representing the struct as JSON.
46-
func ToJSON(v interface{}) string {
46+
func ToJSON(v any) string {
4747
s, err := json.Marshal(v)
4848
gomega.Expect(err).NotTo(gomega.HaveOccurred())
4949
return string(s)

e2e/fixtures/pods.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ func (factory *Factory) RandomPickPod(input []corev1.Pod, count int) []corev1.Po
6060
maxPods = len(input)
6161
}
6262

63-
for i := 0; i < maxPods; i++ {
63+
for i := range maxPods {
6464
ret[i] = input[perm[i]]
6565
}
6666

@@ -84,7 +84,7 @@ func (factory *Factory) RandomPickCluster(input []*FdbCluster, count int) []*Fdb
8484
maxPods = len(input)
8585
}
8686

87-
for i := 0; i < maxPods; i++ {
87+
for i := range maxPods {
8888
ret[i] = input[perm[i]]
8989
}
9090

e2e/test_operator_stress/operator_stress_test.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ var _ = Describe("Operator Stress", Label("e2e"), func() {
5353
It("should create a healthy and available cluster", func() {
5454
// Since Ginkgo doesn't support what we want, we run this multiple times.
5555
// We create and delete a cluster 10 times to ensure we don't have any flaky behaviour in the operator.
56-
for i := 0; i < 10; i++ {
56+
for range 10 {
5757
fdbCluster := factory.CreateFdbCluster(
5858
fixtures.DefaultClusterConfig(false),
5959
factory.GetClusterOptions()...,
@@ -81,7 +81,7 @@ var _ = Describe("Operator Stress", Label("e2e"), func() {
8181

8282
It("should replace the targeted Pod", func() {
8383
// Since Ginkgo doesn't support what we want, we run this multiple times.
84-
for i := 0; i < 10; i++ {
84+
for range 10 {
8585
Expect(fdbCluster.ClearProcessGroupsToRemove()).ShouldNot(HaveOccurred())
8686
pod := factory.ChooseRandomPod(fdbCluster.GetPods())
8787
fdbCluster.ReplacePod(*pod, true)

fdbclient/admin_client.go

+4-4
Original file line numberDiff line numberDiff line change
@@ -703,7 +703,7 @@ func (client *cliAdminClient) SetKnobs(knobs []string) {
703703

704704
// WithValues will update the logger used by the current AdminClient to contain the provided key value pairs. The provided
705705
// arguments must be even.
706-
func (client *cliAdminClient) WithValues(keysAndValues ...interface{}) {
706+
func (client *cliAdminClient) WithValues(keysAndValues ...any) {
707707
newLogger := client.log.WithValues(keysAndValues...)
708708
client.log = newLogger
709709

@@ -745,7 +745,7 @@ func (client *cliAdminClient) GetProcessesUnderMaintenance() (map[fdbv1beta2.Pro
745745

746746
maintenancePrefix := client.Cluster.GetMaintenancePrefix() + "/"
747747

748-
maintenanceProcesses, err := db.Transact(func(tr fdb.Transaction) (interface{}, error) {
748+
maintenanceProcesses, err := db.Transact(func(tr fdb.Transaction) (any, error) {
749749
err := tr.Options().SetReadSystemKeys()
750750
if err != nil {
751751
return nil, err
@@ -799,7 +799,7 @@ func (client *cliAdminClient) RemoveProcessesUnderMaintenance(processGroupIDs []
799799
return err
800800
}
801801

802-
_, err = db.Transact(func(tr fdb.Transaction) (interface{}, error) {
802+
_, err = db.Transact(func(tr fdb.Transaction) (any, error) {
803803
err := tr.Options().SetAccessSystemKeys()
804804
if err != nil {
805805
return nil, err
@@ -831,7 +831,7 @@ func (client *cliAdminClient) SetProcessesUnderMaintenance(processGroupIDs []fdb
831831
return err
832832
}
833833

834-
_, err = db.Transact(func(tr fdb.Transaction) (interface{}, error) {
834+
_, err = db.Transact(func(tr fdb.Transaction) (any, error) {
835835
err := tr.Options().SetAccessSystemKeys()
836836
if err != nil {
837837
return nil, err

fdbclient/fdb_client.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ func (fdbClient *realFdbLibClient) getValueFromDBUsingKey(fdbKey string, timeout
5252
return nil, err
5353
}
5454

55-
result, err := database.Transact(func(transaction fdb.Transaction) (interface{}, error) {
55+
result, err := database.Transact(func(transaction fdb.Transaction) (any, error) {
5656
err := transaction.Options().SetAccessSystemKeys()
5757
if err != nil {
5858
return nil, err

0 commit comments

Comments
 (0)