forked from kubernetes/dashboard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
detail.go
358 lines (321 loc) · 12.7 KB
/
detail.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
// Copyright 2017 The Kubernetes 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 pod
import (
"encoding/base64"
"fmt"
"log"
"math"
"strconv"
"github.com/kubernetes/dashboard/src/app/backend/api"
errorHandler "github.com/kubernetes/dashboard/src/app/backend/errors"
metricapi "github.com/kubernetes/dashboard/src/app/backend/integration/metric/api"
"github.com/kubernetes/dashboard/src/app/backend/resource/common"
"github.com/kubernetes/dashboard/src/app/backend/resource/controller"
"github.com/kubernetes/dashboard/src/app/backend/resource/dataselect"
"github.com/kubernetes/dashboard/src/app/backend/resource/persistentvolumeclaim"
"k8s.io/api/core/v1"
res "k8s.io/apimachinery/pkg/api/resource"
metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/kubernetes"
)
// PodDetail is a presentation layer view of Kubernetes Pod resource.
type PodDetail struct {
ObjectMeta api.ObjectMeta `json:"objectMeta"`
TypeMeta api.TypeMeta `json:"typeMeta"`
PodPhase v1.PodPhase `json:"podPhase"`
PodIP string `json:"podIP"`
NodeName string `json:"nodeName"`
RestartCount int32 `json:"restartCount"`
QOSClass string `json:"qosClass"`
Controller controller.ResourceOwner `json:"controller"`
Containers []Container `json:"containers"`
InitContainers []Container `json:"initContainers"`
Metrics []metricapi.Metric `json:"metrics"`
Conditions []common.Condition `json:"conditions"`
EventList common.EventList `json:"eventList"`
PersistentvolumeclaimList persistentvolumeclaim.PersistentVolumeClaimList `json:"persistentVolumeClaimList"`
// List of non-critical errors, that occurred during resource retrieval.
Errors []error `json:"errors"`
}
// Container represents a docker/rkt/etc. container that lives in a pod.
type Container struct {
// Name of the container.
Name string `json:"name"`
// Image URI of the container.
Image string `json:"image"`
// List of environment variables.
Env []EnvVar `json:"env"`
// Commands of the container
Commands []string `json:"commands"`
// Command arguments
Args []string `json:"args"`
}
// EnvVar represents an environment variable of a container.
type EnvVar struct {
// Name of the variable.
Name string `json:"name"`
// Value of the variable. May be empty if value from is defined.
Value string `json:"value"`
// Defined for derived variables. If non-null, the value is get from the reference.
// Note that this is an API struct. This is intentional, as EnvVarSources are plain struct
// references.
ValueFrom *v1.EnvVarSource `json:"valueFrom"`
}
// GetPodDetail returns the details of a named Pod from a particular namespace.
func GetPodDetail(client kubernetes.Interface, metricClient metricapi.MetricClient, namespace, name string) (
*PodDetail, error) {
log.Printf("Getting details of %s pod in %s namespace", name, namespace)
channels := &common.ResourceChannels{
ConfigMapList: common.GetConfigMapListChannel(client, common.NewSameNamespaceQuery(namespace), 1),
SecretList: common.GetSecretListChannel(client, common.NewSameNamespaceQuery(namespace), 1),
}
pod, err := client.CoreV1().Pods(namespace).Get(name, metaV1.GetOptions{})
if err != nil {
return nil, err
}
controller, err := getPodController(client, common.NewSameNamespaceQuery(namespace), pod)
nonCriticalErrors, criticalError := errorHandler.HandleError(err)
if criticalError != nil {
return nil, criticalError
}
_, metricPromises := dataselect.GenericDataSelectWithMetrics(toCells([]v1.Pod{*pod}),
dataselect.StdMetricsDataSelect, metricapi.NoResourceCache, metricClient)
metrics, _ := metricPromises.GetMetrics()
configMapList := <-channels.ConfigMapList.List
err = <-channels.ConfigMapList.Error
nonCriticalErrors, criticalError = errorHandler.AppendError(err, nonCriticalErrors)
if criticalError != nil {
return nil, criticalError
}
secretList := <-channels.SecretList.List
err = <-channels.SecretList.Error
nonCriticalErrors, criticalError = errorHandler.AppendError(err, nonCriticalErrors)
if criticalError != nil {
return nil, criticalError
}
eventList, err := GetEventsForPod(client, dataselect.DefaultDataSelect, pod.Namespace, pod.Name)
nonCriticalErrors, criticalError = errorHandler.AppendError(err, nonCriticalErrors)
if criticalError != nil {
return nil, criticalError
}
persistentVolumeClaimList, err := persistentvolumeclaim.GetPodPersistentVolumeClaims(client,
namespace, name, dataselect.DefaultDataSelect)
nonCriticalErrors, criticalError = errorHandler.AppendError(err, nonCriticalErrors)
if criticalError != nil {
return nil, criticalError
}
podDetail := toPodDetail(pod, metrics, configMapList, secretList, controller,
eventList, persistentVolumeClaimList, nonCriticalErrors)
return &podDetail, nil
}
func getPodController(client kubernetes.Interface, nsQuery *common.NamespaceQuery, pod *v1.Pod) (
ctrl controller.ResourceOwner, err error) {
channels := &common.ResourceChannels{
PodList: common.GetPodListChannel(client, nsQuery, 1),
EventList: common.GetEventListChannel(client, nsQuery, 1),
}
pods := <-channels.PodList.List
err = <-channels.PodList.Error
if err != nil {
return
}
events := <-channels.EventList.List
if err := <-channels.EventList.Error; err != nil {
events = &v1.EventList{}
}
ownerRef := metaV1.GetControllerOf(pod)
if ownerRef != nil {
var rc controller.ResourceController
rc, err = controller.NewResourceController(*ownerRef, pod.Namespace, client)
if err == nil {
ctrl = rc.Get(pods.Items, events.Items)
}
}
return
}
func extractContainerInfo(containerList []v1.Container, pod *v1.Pod, configMaps *v1.ConfigMapList, secrets *v1.SecretList) []Container {
containers := make([]Container, 0)
for _, container := range containerList {
vars := make([]EnvVar, 0)
for _, envVar := range container.Env {
variable := EnvVar{
Name: envVar.Name,
Value: envVar.Value,
ValueFrom: envVar.ValueFrom,
}
if variable.ValueFrom != nil {
variable.Value = evalValueFrom(variable.ValueFrom, &container, pod,
configMaps, secrets)
}
vars = append(vars, variable)
}
vars = append(vars, evalEnvFrom(container, configMaps, secrets)...)
containers = append(containers, Container{
Name: container.Name,
Image: container.Image,
Env: vars,
Commands: container.Command,
Args: container.Args,
})
}
return containers
}
func toPodDetail(pod *v1.Pod, metrics []metricapi.Metric, configMaps *v1.ConfigMapList, secrets *v1.SecretList,
controller controller.ResourceOwner, events *common.EventList,
persistentVolumeClaimList *persistentvolumeclaim.PersistentVolumeClaimList, nonCriticalErrors []error) PodDetail {
return PodDetail{
ObjectMeta: api.NewObjectMeta(pod.ObjectMeta),
TypeMeta: api.NewTypeMeta(api.ResourceKindPod),
PodPhase: pod.Status.Phase,
PodIP: pod.Status.PodIP,
RestartCount: getRestartCount(*pod),
QOSClass: string(pod.Status.QOSClass),
NodeName: pod.Spec.NodeName,
Controller: controller,
Containers: extractContainerInfo(pod.Spec.Containers, pod, configMaps, secrets),
InitContainers: extractContainerInfo(pod.Spec.InitContainers, pod, configMaps, secrets),
Metrics: metrics,
Conditions: getPodConditions(*pod),
EventList: *events,
PersistentvolumeclaimList: *persistentVolumeClaimList,
Errors: nonCriticalErrors,
}
}
func evalEnvFrom(container v1.Container, configMaps *v1.ConfigMapList, secrets *v1.SecretList) []EnvVar {
vars := make([]EnvVar, 0)
for _, envFromVar := range container.EnvFrom {
switch {
case envFromVar.ConfigMapRef != nil:
name := envFromVar.ConfigMapRef.LocalObjectReference.Name
for _, configMap := range configMaps.Items {
if configMap.ObjectMeta.Name == name {
for key, value := range configMap.Data {
valueFrom := &v1.EnvVarSource{
ConfigMapKeyRef: &v1.ConfigMapKeySelector{
LocalObjectReference: v1.LocalObjectReference{
Name: name,
},
Key: key,
},
}
variable := EnvVar{
Name: envFromVar.Prefix + key,
Value: value,
ValueFrom: valueFrom,
}
vars = append(vars, variable)
}
break
}
}
case envFromVar.SecretRef != nil:
name := envFromVar.SecretRef.LocalObjectReference.Name
for _, secret := range secrets.Items {
if secret.ObjectMeta.Name == name {
for key, value := range secret.Data {
valueFrom := &v1.EnvVarSource{
SecretKeyRef: &v1.SecretKeySelector{
LocalObjectReference: v1.LocalObjectReference{
Name: name,
},
Key: key,
},
}
variable := EnvVar{
Name: envFromVar.Prefix + key,
Value: base64.StdEncoding.EncodeToString(value),
ValueFrom: valueFrom,
}
vars = append(vars, variable)
}
break
}
}
}
}
return vars
}
// evalValueFrom evaluates environment value from given source. For more details check:
// https://github.com/kubernetes/kubernetes/blob/d82e51edc5f02bff39661203c9b503d054c3493b/pkg/kubectl/describe.go#L1056
func evalValueFrom(src *v1.EnvVarSource, container *v1.Container, pod *v1.Pod,
configMaps *v1.ConfigMapList, secrets *v1.SecretList) string {
switch {
case src.ConfigMapKeyRef != nil:
name := src.ConfigMapKeyRef.LocalObjectReference.Name
for _, configMap := range configMaps.Items {
if configMap.ObjectMeta.Name == name {
return configMap.Data[src.ConfigMapKeyRef.Key]
}
}
case src.SecretKeyRef != nil:
name := src.SecretKeyRef.LocalObjectReference.Name
for _, secret := range secrets.Items {
if secret.ObjectMeta.Name == name {
return base64.StdEncoding.EncodeToString([]byte(
secret.Data[src.SecretKeyRef.Key]))
}
}
case src.ResourceFieldRef != nil:
valueFrom, err := extractContainerResourceValue(src.ResourceFieldRef, container)
if err != nil {
valueFrom = ""
}
resource := src.ResourceFieldRef.Resource
if valueFrom == "0" && (resource == "limits.cpu" || resource == "limits.memory") {
valueFrom = "node allocatable"
}
return valueFrom
case src.FieldRef != nil:
internalFieldPath, _, err := runtime.NewScheme().ConvertFieldLabel(src.FieldRef.APIVersion,
"Pod", src.FieldRef.FieldPath, "")
if err != nil {
log.Println(err)
return ""
}
valueFrom, err := ExtractFieldPathAsString(pod, internalFieldPath)
if err != nil {
log.Println(err)
return ""
}
return valueFrom
}
return ""
}
// extractContainerResourceValue extracts the value of a resource in an already known container.
func extractContainerResourceValue(fs *v1.ResourceFieldSelector, container *v1.Container) (string,
error) {
divisor := res.Quantity{}
if divisor.Cmp(fs.Divisor) == 0 {
divisor = res.MustParse("1")
} else {
divisor = fs.Divisor
}
switch fs.Resource {
case "limits.cpu":
return strconv.FormatInt(int64(math.Ceil(float64(container.Resources.Limits.
Cpu().MilliValue())/float64(divisor.MilliValue()))), 10), nil
case "limits.memory":
return strconv.FormatInt(int64(math.Ceil(float64(container.Resources.Limits.
Memory().Value())/float64(divisor.Value()))), 10), nil
case "requests.cpu":
return strconv.FormatInt(int64(math.Ceil(float64(container.Resources.Requests.
Cpu().MilliValue())/float64(divisor.MilliValue()))), 10), nil
case "requests.memory":
return strconv.FormatInt(int64(math.Ceil(float64(container.Resources.Requests.
Memory().Value())/float64(divisor.Value()))), 10), nil
}
return "", fmt.Errorf("Unsupported container resource : %v", fs.Resource)
}