-
Notifications
You must be signed in to change notification settings - Fork 175
Expand file tree
/
Copy pathmetrics_client.go
More file actions
95 lines (80 loc) · 2.38 KB
/
metrics_client.go
File metadata and controls
95 lines (80 loc) · 2.38 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
package perconaservermongodb
import (
"bytes"
"context"
"strconv"
"strings"
"time"
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/util/retry"
"github.com/percona/percona-server-mongodb-operator/pkg/naming"
"github.com/percona/percona-server-mongodb-operator/pkg/psmdb/config"
)
// PVCUsage contains information about PVC disk usage
type PVCUsage struct {
PVCName string
UsedBytes int64
TotalBytes int64
UsagePercent int
}
func (r *ReconcilePerconaServerMongoDB) getPVCUsageFromMetrics(
ctx context.Context,
pod *corev1.Pod,
pvcName string,
) (*PVCUsage, error) {
if pod == nil {
return nil, errors.New("pod is nil")
}
backoff := wait.Backoff{
Steps: 5,
Duration: 5 * time.Second,
Factor: 2.0,
}
// Execute df command in the mongod container to get disk usage
// df -B1 /data/db outputs in bytes
// Example output:
// Filesystem 1B-blocks Used Available Use% Mounted on
// /dev/sdb 3094126592 221798400 2855550976 8% /data/db
var stdout, stderr bytes.Buffer
command := []string{"df", "-B1", config.MongodContainerDataDir}
err := retry.OnError(backoff, func(err error) bool { return true }, func() error {
stdout.Reset()
stderr.Reset()
err := r.clientcmd.Exec(ctx, pod, naming.ComponentMongod, command, nil, &stdout, &stderr, false)
if err != nil {
return errors.Wrapf(err, "failed to execute df in pod %s: %s", pod.Name, stderr.String())
}
return nil
})
if err != nil {
return nil, errors.Wrap(err, "wait for df execution")
}
lines := strings.Split(strings.TrimSpace(stdout.String()), "\n")
if len(lines) < 2 {
return nil, errors.Errorf("unexpected df output format: %s", stdout.String())
}
fields := strings.Fields(lines[1])
if len(fields) < 6 {
return nil, errors.Errorf("unexpected df output fields: %s", lines[1])
}
totalBytes, err := strconv.ParseInt(fields[1], 10, 64)
if err != nil {
return nil, errors.Wrapf(err, "failed to parse total bytes: %s", fields[1])
}
usedBytes, err := strconv.ParseInt(fields[2], 10, 64)
if err != nil {
return nil, errors.Wrapf(err, "failed to parse used bytes: %s", fields[2])
}
usagePercent := 0
if totalBytes > 0 {
usagePercent = int((usedBytes * 100) / totalBytes)
}
return &PVCUsage{
PVCName: pvcName,
UsedBytes: usedBytes,
TotalBytes: totalBytes,
UsagePercent: usagePercent,
}, nil
}