-
Notifications
You must be signed in to change notification settings - Fork 82
/
status.go
412 lines (343 loc) · 11.5 KB
/
status.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
/*
* status.go
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2023 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 fixtures
import (
"encoding/json"
"fmt"
"log"
"strings"
"time"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega"
fdbv1beta2 "github.com/FoundationDB/fdb-kubernetes-operator/api/v1beta2"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/util/wait"
)
// getStatusFromOperatorPod returns fdb status queried through the operator Pod.
func (fdbCluster *FdbCluster) getStatusFromOperatorPod() *fdbv1beta2.FoundationDBStatus {
status := &fdbv1beta2.FoundationDBStatus{}
if fdbCluster.factory.shutdownInProgress {
return status
}
gomega.Eventually(func() error {
out, _, err := fdbCluster.RunFdbCliCommandInOperatorWithoutRetry("status json", false, 30)
if err != nil {
return err
}
status, err = parseStatusOutput(out)
return err
}).WithTimeout(2 * time.Minute).WithPolling(1 * time.Second).ShouldNot(gomega.HaveOccurred())
return status
}
// RunFdbCliCommandInOperator allows to run a command with fdbcli in the operator Pod.
func (fdbCluster *FdbCluster) RunFdbCliCommandInOperator(
command string,
printOutput bool,
timeout int,
) (string, string) {
var stdout, stderr string
var err error
gomega.Eventually(func() error {
// Ensure we fetch everything if we have to retry it e.g. because the connection string has changed or
// because the operator Pod was killed.
stdout, stderr, err = fdbCluster.RunFdbCliCommandInOperatorWithoutRetry(
command,
printOutput,
timeout,
)
return err
}).WithTimeout(2 * time.Minute).WithPolling(1 * time.Second).ShouldNot(gomega.HaveOccurred())
return stdout, stderr
}
// RunFdbCliCommandInOperatorWithoutRetry allows to run a command with fdbcli in the operator Pod without doing any retries.
func (fdbCluster *FdbCluster) RunFdbCliCommandInOperatorWithoutRetry(
command string,
printOutput bool,
timeout int,
) (string, string, error) {
pod := ChooseRandomPod(fdbCluster.factory.GetOperatorPods(fdbCluster.Namespace()))
cluster, err := fdbCluster.factory.getClusterStatus(
fdbCluster.Name(),
fdbCluster.Namespace(),
)
if err != nil {
return "", "", err
}
runningVersion, err := fdbv1beta2.ParseFdbVersion(cluster.GetRunningVersion())
gomega.Expect(err).NotTo(gomega.HaveOccurred())
fdbCliPaths := []string{
fmt.Sprintf("/usr/bin/fdb/%s/fdbcli", runningVersion.Compact()),
}
if cluster.IsBeingUpgraded() {
desiredVersion, err := fdbv1beta2.ParseFdbVersion(cluster.Spec.Version)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
fdbCliPaths = append(
fdbCliPaths,
fmt.Sprintf("/usr/bin/fdb/%s/fdbcli", desiredVersion.Compact()),
)
}
clusterFile := fmt.Sprintf("/tmp/%s", cluster.Name)
var timeoutArgs string
if timeout > 0 {
timeoutArgs = fmt.Sprintf("--timeout %d", timeout)
}
var stdout, stderr string
// If a cluster is currently updated the update of the FoundationDBCluster status is done aysnc. That means there is
// a timespan where the cluster is already upgraded but the status.RunningVersion is still pointing to the old version.
// In order to catch those cases we try first the fdbcli for the running version and if that doesn't work (an error
// is returned) we will try the version for the spec. This should reduce some test flakiness.
for _, fdbCliPath := range fdbCliPaths {
stdout, stderr, err = fdbCluster.factory.ExecuteCmd(
pod.Namespace,
pod.Name,
"manager",
fmt.Sprintf(
"export TIMEFORMAT='%%R' && echo '%s' > %s && time %s --log-dir \"/var/log/fdb\" --log --trace_format \"json\" %s -C %s --exec '%s'",
cluster.Status.ConnectionString,
clusterFile,
fdbCliPath,
timeoutArgs,
clusterFile,
command,
),
printOutput,
)
if err != nil {
return stdout, stderr, err
}
// Only if we do an upgrade we have to check if we actually use the correct fdbcli version
if !cluster.IsBeingUpgraded() {
break
}
var parsedStatus *fdbv1beta2.FoundationDBStatus
parsedStatus, err = parseStatusOutput(stdout)
// If we cannot parse the status we probably have an error or timeout
if err != nil {
continue
}
// Quorum of coordinators are available, so we probably use the correct version
if parsedStatus.Client.Coordinators.QuorumReachable {
break
}
}
return stdout, stderr, err
}
// getStatusFromOperatorPod returns fdb status queried through this Pod.
func parseStatusOutput(rawStatus string) (*fdbv1beta2.FoundationDBStatus, error) {
if strings.HasPrefix(rawStatus, "\r\nWARNING") {
rawStatus = strings.TrimPrefix(
rawStatus,
"\r\nWARNING: Long delay (Ctrl-C to interrupt)\r\n",
)
}
status := &fdbv1beta2.FoundationDBStatus{}
err := json.Unmarshal([]byte(rawStatus), status)
if err != nil {
return nil, fmt.Errorf(
"could not parse result of status json %w (unparseable JSON: %s) ",
err,
rawStatus,
)
}
return status, nil
}
// IsAvailable returns true if the database is available.
func (fdbCluster *FdbCluster) IsAvailable() bool {
return fdbCluster.GetStatus().Client.DatabaseStatus.Available
}
// WaitUntilAvailable waits until the cluster is available.
func (fdbCluster *FdbCluster) WaitUntilAvailable() error {
return wait.PollImmediate(100*time.Millisecond, 60*time.Second, func() (bool, error) {
return fdbCluster.IsAvailable(), nil
})
}
// StatusInvariantChecker provides a way to check an invariant for the cluster status.
// nolint:nilerr
func (fdbCluster FdbCluster) StatusInvariantChecker(
name string,
threshold time.Duration,
f func(status *fdbv1beta2.FoundationDBStatus) error,
) error {
first := true
return CheckInvariant(
name,
&fdbCluster.factory.invariantShutdownHooks,
threshold,
func() error {
// Once we are in the shutdown mode ignore all checks
if fdbCluster.factory.shutdownInProgress {
return nil
}
cluster, err := fdbCluster.factory.getClusterStatus(
fdbCluster.Name(),
fdbCluster.Namespace(),
)
if err != nil {
return nil
}
if !cluster.DeletionTimestamp.IsZero() {
return nil
}
out, _, err := fdbCluster.RunFdbCliCommandInOperatorWithoutRetry(
"status json",
false,
30,
)
if err != nil {
log.Println("error in StatusInvariantChecker fetching status json:", err.Error())
return nil
}
status, err := parseStatusOutput(out)
if err != nil {
return nil
}
err = f(status)
if err != nil && first {
log.Printf("invariant %s failed for the first time", name)
first = false
}
return err
},
)
}
// checkAvailability returns nil if the cluster is reachable. If the cluster is unreachable an error will be returned.
func checkAvailability(status *fdbv1beta2.FoundationDBStatus) error {
if !status.Client.DatabaseStatus.Available {
return fmt.Errorf("cluster is not available")
}
return nil
}
// InvariantClusterStatusAvailableWithThreshold checks if the database is at a maximum unavailable for the provided threshold.
func (fdbCluster FdbCluster) InvariantClusterStatusAvailableWithThreshold(
availabilityThreshold time.Duration,
) error {
return fdbCluster.StatusInvariantChecker(
"InvariantClusterStatusAvailableWithThreshold",
availabilityThreshold,
checkAvailability,
)
}
// InvariantClusterStatusAvailable checks if the cluster is available the whole test.
func (fdbCluster FdbCluster) InvariantClusterStatusAvailable() error {
return fdbCluster.StatusInvariantChecker(
"InvariantClusterStatusAvailable",
// Per default we allow 5 seconds unavailability. Otherwise we could get a few test failures when we do operations
// like a replacement on a transaction system Pod and the recovery takes longer.
5*time.Second,
checkAvailability,
)
}
// GetProcessCount returns the number of processes having the specified role
func (fdbCluster *FdbCluster) GetProcessCount(targetRole fdbv1beta2.ProcessRole) int {
pCounter := 0
status := fdbCluster.GetStatus()
for _, process := range status.Cluster.Processes {
for _, role := range process.Roles {
if role.Role == string(targetRole) {
pCounter++
}
}
}
return pCounter
}
// HasTLSEnabled returns true if the cluster is running with TLS enabled.
func (fdbCluster *FdbCluster) HasTLSEnabled() bool {
status := fdbCluster.GetStatus()
if len(status.Cluster.Processes) == 0 {
return false
}
tlsCnt := 0
noTLSCnt := 0
for _, process := range status.Cluster.Processes {
if _, ok := process.Address.Flags["tls"]; ok {
tlsCnt++
continue
}
noTLSCnt++
}
// We assume that the cluster either listens on TLS or not but not both.
// A process would only listen during the transition on both addresses but we wait
// until the cluster is reconciled.
if tlsCnt == len(status.Cluster.Processes) {
return true
}
if noTLSCnt == len(status.Cluster.Processes) {
return false
}
ginkgo.Fail(fmt.Sprintf(
"expected that all processes either have tls enabled or disabled but got %d with TLS and %d without tls",
tlsCnt,
noTLSCnt,
))
return false
}
// GetCoordinators returns the Pods of the FoundationDBCluster that are having the coordinator role.
func (fdbCluster *FdbCluster) GetCoordinators() []corev1.Pod {
return fdbCluster.GetPodsWithRole(fdbv1beta2.ProcessRoleCoordinator)
}
// GetStatus returns fdb status queried from a random operator Pod in this clusters namespace.
func (fdbCluster FdbCluster) GetStatus() *fdbv1beta2.FoundationDBStatus {
return fdbCluster.getStatusFromOperatorPod()
}
// RoleInfo stores information for one particular worker role.
type RoleInfo struct {
Role string
ID string
}
// GetPodRoleMap returns a map with the process group ID as key and all associated roles.
func (fdbCluster *FdbCluster) GetPodRoleMap() map[fdbv1beta2.ProcessGroupID][]RoleInfo {
ret := make(map[fdbv1beta2.ProcessGroupID][]RoleInfo)
status := fdbCluster.GetStatus()
for _, process := range status.Cluster.Processes {
podName := fdbv1beta2.ProcessGroupID(process.Locality[fdbv1beta2.FDBLocalityInstanceIDKey])
for _, role := range process.Roles {
ret[podName] = append(ret[podName], RoleInfo{role.Role, role.ID})
}
}
return ret
}
// GetPodsWithRole returns all Pods that have the provided role.
func (fdbCluster *FdbCluster) GetPodsWithRole(role fdbv1beta2.ProcessRole) []corev1.Pod {
roleMap := fdbCluster.GetPodRoleMap()
pods := fdbCluster.GetPods()
var matches []corev1.Pod
for _, p := range pods.Items {
roles := roleMap[GetProcessGroupID(p)]
for _, r := range roles {
if r.Role == string(role) {
matches = append(matches, p)
}
}
}
return matches
}
// GetCommandlineForProcessesPerClass fetches the commandline args for all processes except of the specified class.
func (fdbCluster FdbCluster) GetCommandlineForProcessesPerClass() map[fdbv1beta2.ProcessClass][]string {
status := fdbCluster.GetStatus()
knobs := map[fdbv1beta2.ProcessClass][]string{}
for _, process := range status.Cluster.Processes {
if _, ok := knobs[process.ProcessClass]; !ok {
knobs[process.ProcessClass] = []string{process.CommandLine}
continue
}
knobs[process.ProcessClass] = append(knobs[process.ProcessClass], process.CommandLine)
}
return knobs
}