-
Notifications
You must be signed in to change notification settings - Fork 874
/
metrics.go
310 lines (278 loc) · 8.69 KB
/
metrics.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
/*
Copyright 2022 The KubeVela 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 common
import (
"context"
"math"
"strconv"
pkgmulticluster "github.com/kubevela/pkg/multicluster"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/rest"
"k8s.io/metrics/pkg/apis/metrics/v1beta1"
metricsclientset "k8s.io/metrics/pkg/client/clientset/versioned"
"sigs.k8s.io/controller-runtime/pkg/client"
appv1beta1 "github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
"github.com/oam-dev/kubevela/pkg/multicluster"
"github.com/oam-dev/kubevela/pkg/velaql/providers/query"
)
const (
// MetricsNA is the value of metrics when it is not available
MetricsNA = "N/A"
)
// PodMetricStatus is the status of pod metrics
type PodMetricStatus struct {
Spec MetricsLR
Usage MetricsUsage
}
// ApplicationMetrics is the metrics of application
type ApplicationMetrics struct {
Metrics *ApplicationMetricsStatus
ResourceNum *ApplicationResourceNum
}
// ApplicationMetricsStatus is the status of application metrics
type ApplicationMetricsStatus struct {
CPUUsage int64
CPURequest int64
CPULimit int64
MemoryUsage int64
MemoryRequest int64
MemoryLimit int64
Storage int64
}
// ApplicationResourceNum is the resource number of application
type ApplicationResourceNum struct {
Node int
Cluster int
Subresource int
Pod int
Container int
}
// MetricsLR is the metric of resource requests and limits
type MetricsLR struct {
Rcpu, Rmem int64
Lcpu, Lmem int64
}
// MetricsUsage is the metric of resource usage
type MetricsUsage struct {
CPU, Mem, Storage int64
}
func podUsage(metrics *v1beta1.PodMetrics) (*resource.Quantity, *resource.Quantity) {
cpu, mem := new(resource.Quantity), new(resource.Quantity)
for _, co := range metrics.Containers {
usage := co.Usage
if len(usage) == 0 {
continue
}
if usage.Cpu() != nil {
cpu.Add(*usage.Cpu())
}
if co.Usage.Memory() != nil {
mem.Add(*usage.Memory())
}
}
return cpu, mem
}
func podLimits(spec v1.PodSpec) (*resource.Quantity, *resource.Quantity) {
cpu, mem := new(resource.Quantity), new(resource.Quantity)
for _, co := range spec.Containers {
limits := co.Resources.Limits
if len(limits) == 0 {
continue
}
if limits.Cpu() != nil {
cpu.Add(*limits.Cpu())
}
if limits.Memory() != nil {
mem.Add(*limits.Memory())
}
}
return cpu, mem
}
func podRequests(spec v1.PodSpec) (*resource.Quantity, *resource.Quantity) {
cpu, mem := new(resource.Quantity), new(resource.Quantity)
for _, co := range spec.Containers {
req := co.Resources.Requests
if len(req) == 0 {
continue
}
if req.Cpu() != nil {
cpu.Add(*req.Cpu())
}
if req.Memory() != nil {
mem.Add(*req.Memory())
}
}
return cpu, mem
}
// ToPercentage computes percentage as string otherwise n/aa.
func ToPercentage(v1, v2 int64) int {
if v2 == 0 {
return 0
}
return int(math.Floor((float64(v1) / float64(v2)) * 100))
}
// ToPercentageStr computes percentage, but if v2 is 0, it will return NAValue instead of 0.
func ToPercentageStr(v1, v2 int64) string {
if v2 == 0 {
return MetricsNA
}
return strconv.Itoa(ToPercentage(v1, v2)) + "%"
}
// GetPodMetrics get pod metrics object
func GetPodMetrics(conf *rest.Config, podName, namespace, cluster string) (*v1beta1.PodMetrics, error) {
ctx := multicluster.ContextWithClusterName(context.Background(), cluster)
conf.Wrap(pkgmulticluster.NewTransportWrapper())
metricsClient := metricsclientset.NewForConfigOrDie(conf)
m, err := metricsClient.MetricsV1beta1().PodMetricses(namespace).Get(ctx, podName, metav1.GetOptions{})
if err != nil {
return nil, err
}
return m, nil
}
// GetPodResourceSpecAndUsage return the usage metrics of a pod and specified metric including requests and limits metrics
func GetPodResourceSpecAndUsage(c client.Client, pod *v1.Pod, metrics *v1beta1.PodMetrics) (MetricsLR, MetricsUsage) {
var metricsSpec MetricsLR
var metricsUsage MetricsUsage
rcpu, rmem := podRequests(pod.Spec)
lcpu, lmem := podLimits(pod.Spec)
metricsSpec.Rcpu, metricsSpec.Lcpu, metricsSpec.Rmem, metricsSpec.Lmem = rcpu.MilliValue(), lcpu.MilliValue(), rmem.Value(), lmem.Value()
if metrics != nil {
ccpu, cmem := podUsage(metrics)
metricsUsage.CPU, metricsUsage.Mem = ccpu.MilliValue(), cmem.Value()
}
storage := int64(0)
storages := GetPodStorage(c, pod)
for _, s := range storages {
storage += s.Status.Capacity.Storage().Value()
}
metricsUsage.Storage = storage
return metricsSpec, metricsUsage
}
// GetPodStorage get pod storage
func GetPodStorage(client client.Client, pod *v1.Pod) (storages []v1.PersistentVolumeClaim) {
for _, v := range pod.Spec.Volumes {
if v.PersistentVolumeClaim != nil {
storage := v1.PersistentVolumeClaim{}
err := client.Get(context.Background(), types.NamespacedName{Name: v.PersistentVolumeClaim.ClaimName, Namespace: pod.Namespace}, &storage)
if err != nil {
continue
}
storages = append(storages, storage)
}
}
return
}
// ListApplicationResource list application resource
func ListApplicationResource(c client.Client, name, namespace string) ([]query.Resource, error) {
opt := query.Option{
Name: name,
Namespace: namespace,
Filter: query.FilterOption{},
}
collector := query.NewAppCollector(c, opt)
appResList, err := collector.CollectResourceFromApp(context.Background())
if err != nil {
return []query.Resource{}, err
}
return appResList, err
}
// GetPodOfManagedResource get pod of managed resource
func GetPodOfManagedResource(c client.Client, app *appv1beta1.Application, components string) []*v1.Pod {
pods := make([]*v1.Pod, 0)
opt := query.Option{
Name: app.Name,
Namespace: app.Namespace,
Filter: query.FilterOption{
Components: []string{components},
APIVersion: "v1",
Kind: "Pod",
},
WithTree: true,
}
objects, err := CollectApplicationResource(context.Background(), c, opt)
if err != nil {
return pods
}
for _, object := range objects {
pod := &v1.Pod{}
err = runtime.DefaultUnstructuredConverter.FromUnstructured(object.UnstructuredContent(), pod)
if err != nil {
continue
}
pods = append(pods, pod)
}
return pods
}
// GetPodMetricsStatus get pod metrics
func GetPodMetricsStatus(c client.Client, conf *rest.Config, pod *v1.Pod, cluster string) (*PodMetricStatus, error) {
metricsStatus := &PodMetricStatus{}
podMetrics, err := GetPodMetrics(conf, pod.Name, pod.Namespace, cluster)
if err != nil {
return nil, err
}
spec, usage := GetPodResourceSpecAndUsage(c, pod, podMetrics)
metricsStatus.Spec = spec
metricsStatus.Usage = usage
return metricsStatus, nil
}
// GetApplicationMetrics get application metrics
func GetApplicationMetrics(c client.Client, conf *rest.Config, app *appv1beta1.Application) (*ApplicationMetrics, error) {
appResList, err := ListApplicationResource(c, app.Name, app.Namespace)
if err != nil {
return nil, err
}
clusters := make(map[string]struct{})
nodes := make(map[string]struct{})
podNum := 0
containerNum := 0
podMetricsArray := make([]*PodMetricStatus, 0)
for _, managedResource := range appResList {
clusters[managedResource.Cluster] = struct{}{}
pods := GetPodOfManagedResource(c, app, managedResource.Object.GetName())
podNum += len(pods)
for _, pod := range pods {
nodes[pod.Spec.NodeName] = struct{}{}
containerNum += len(pod.Spec.Containers)
status, err := GetPodMetricsStatus(c, conf, pod, managedResource.Cluster)
if err != nil {
continue
}
podMetricsArray = append(podMetricsArray, status)
}
}
appResource := &ApplicationResourceNum{
Cluster: len(clusters),
Node: len(nodes),
Subresource: len(appResList),
Pod: podNum,
Container: containerNum,
}
appMetrics := &ApplicationMetricsStatus{}
for _, metrics := range podMetricsArray {
appMetrics.CPUUsage += metrics.Usage.CPU
appMetrics.CPULimit += metrics.Spec.Lcpu
appMetrics.CPURequest += metrics.Spec.Rcpu
appMetrics.MemoryUsage += metrics.Usage.Mem
appMetrics.MemoryLimit += metrics.Spec.Lmem
appMetrics.MemoryRequest += metrics.Spec.Rmem
appMetrics.Storage += metrics.Usage.Storage
}
return &ApplicationMetrics{
Metrics: appMetrics,
ResourceNum: appResource,
}, nil
}