forked from kubesphere/kubesphere
/
pods.go
261 lines (223 loc) · 7.86 KB
/
pods.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
/*
Copyright 2019 The KubeSphere 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 (
"fmt"
"strings"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/informers"
"kubesphere.io/kubesphere/pkg/api"
"kubesphere.io/kubesphere/pkg/apiserver/query"
"kubesphere.io/kubesphere/pkg/models/resources/v1alpha3"
)
const (
fieldNodeName = "nodeName"
fieldPVCName = "pvcName"
fieldServiceName = "serviceName"
fieldPhase = "phase"
fieldStatus = "status"
statusTypeWaitting = "Waiting"
statusTypeRunning = "Running"
statusTypeError = "Error"
statusTypeCompleted = "Completed"
)
type podsGetter struct {
informer informers.SharedInformerFactory
}
func New(sharedInformers informers.SharedInformerFactory) v1alpha3.Interface {
return &podsGetter{informer: sharedInformers}
}
func (p *podsGetter) Get(namespace, name string) (runtime.Object, error) {
return p.informer.Core().V1().Pods().Lister().Pods(namespace).Get(name)
}
func (p *podsGetter) List(namespace string, query *query.Query) (*api.ListResult, error) {
pods, err := p.informer.Core().V1().Pods().Lister().Pods(namespace).List(query.Selector())
if err != nil {
return nil, err
}
var result []runtime.Object
for _, pod := range pods {
result = append(result, pod)
}
return v1alpha3.DefaultList(result, query, p.compare, p.filter), nil
}
func (p *podsGetter) compare(left runtime.Object, right runtime.Object, field query.Field) bool {
leftPod, ok := left.(*corev1.Pod)
if !ok {
return false
}
rightPod, ok := right.(*corev1.Pod)
if !ok {
return false
}
return v1alpha3.DefaultObjectMetaCompare(leftPod.ObjectMeta, rightPod.ObjectMeta, field)
}
func (p *podsGetter) filter(object runtime.Object, filter query.Filter) bool {
pod, ok := object.(*corev1.Pod)
if !ok {
return false
}
switch filter.Field {
case fieldNodeName:
return pod.Spec.NodeName == string(filter.Value)
case fieldPVCName:
return p.podBindPVC(pod, string(filter.Value))
case fieldServiceName:
return p.podBelongToService(pod, string(filter.Value))
case fieldStatus:
_, statusType := p.getPodStatus(pod)
return statusType == string(filter.Value)
case fieldPhase:
return string(pod.Status.Phase) == string(filter.Value)
default:
return v1alpha3.DefaultObjectMetaFilter(pod.ObjectMeta, filter)
}
}
func (p *podsGetter) podBindPVC(item *corev1.Pod, pvcName string) bool {
for _, v := range item.Spec.Volumes {
if v.VolumeSource.PersistentVolumeClaim != nil &&
v.VolumeSource.PersistentVolumeClaim.ClaimName == pvcName {
return true
}
}
return false
}
func (p *podsGetter) podBelongToService(item *corev1.Pod, serviceName string) bool {
service, err := p.informer.Core().V1().Services().Lister().Services(item.Namespace).Get(serviceName)
if err != nil {
return false
}
selector := labels.Set(service.Spec.Selector).AsSelectorPreValidated()
if selector.Empty() || !selector.Matches(labels.Set(item.Labels)) {
return false
}
return true
}
// getPodStatus refer to `kubectl get po` result.
// https://github.com/kubernetes/kubernetes/blob/45279654db87f4908911569c07afc42804f0e246/pkg/printers/internalversion/printers.go#L820-920
// podStatusPhase = []string("Pending", "Running","Succeeded","Failed","Unknown")
// podStatusReasons = []string{"Evicted", "NodeAffinity", "NodeLost", "Shutdown", "UnexpectedAdmissionError"}
// containerWaitingReasons = []string{"ContainerCreating", "CrashLoopBackOff", "CreateContainerConfigError", "ErrImagePull", "ImagePullBackOff", "CreateContainerError", "InvalidImageName"}
// containerTerminatedReasons = []string{"OOMKilled", "Completed", "Error", "ContainerCannotRun", "DeadlineExceeded", "Evicted"}
func (p *podsGetter) getPodStatus(pod *corev1.Pod) (string, string) {
reason := string(pod.Status.Phase)
if pod.Status.Reason != "" {
reason = pod.Status.Reason
}
/*
todo: upgrade k8s.io/api version
// If the Pod carries {type:PodScheduled, reason:WaitingForGates}, set reason to 'SchedulingGated'.
for _, condition := range pod.Status.Conditions {
if condition.Type == corev1.PodScheduled && condition.Reason == corev1.PodReasonSchedulingGated {
reason = corev1.PodReasonSchedulingGated
}
}
*/
initializing := false
for i := range pod.Status.InitContainerStatuses {
container := pod.Status.InitContainerStatuses[i]
switch {
case container.State.Terminated != nil && container.State.Terminated.ExitCode == 0:
continue
case container.State.Terminated != nil:
// initialization is failed
if len(container.State.Terminated.Reason) == 0 {
if container.State.Terminated.Signal != 0 {
reason = fmt.Sprintf("Init:Signal:%d", container.State.Terminated.Signal)
} else {
reason = fmt.Sprintf("Init:ExitCode:%d", container.State.Terminated.ExitCode)
}
} else {
reason = "Init:" + container.State.Terminated.Reason
}
initializing = true
case container.State.Waiting != nil && len(container.State.Waiting.Reason) > 0 && container.State.Waiting.Reason != "PodInitializing":
reason = "Init:" + container.State.Waiting.Reason
initializing = true
default:
reason = fmt.Sprintf("Init:%d/%d", i, len(pod.Spec.InitContainers))
initializing = true
}
break
}
if !initializing {
hasRunning := false
for i := len(pod.Status.ContainerStatuses) - 1; i >= 0; i-- {
container := pod.Status.ContainerStatuses[i]
if container.State.Waiting != nil && container.State.Waiting.Reason != "" {
reason = container.State.Waiting.Reason
} else if container.State.Terminated != nil && container.State.Terminated.Reason != "" {
reason = container.State.Terminated.Reason
} else if container.State.Terminated != nil && container.State.Terminated.Reason == "" {
if container.State.Terminated.Signal != 0 {
reason = fmt.Sprintf("Signal:%d", container.State.Terminated.Signal)
} else {
reason = fmt.Sprintf("ExitCode:%d", container.State.Terminated.ExitCode)
}
} else if container.Ready && container.State.Running != nil {
hasRunning = true
}
}
// change pod status back to "Running" if there is at least one container still reporting as "Running" status
if reason == "Completed" && hasRunning {
if hasPodReadyCondition(pod.Status.Conditions) {
reason = "Running"
} else {
reason = "NotReady"
}
}
}
if pod.DeletionTimestamp != nil && pod.Status.Reason == "NodeLost" {
reason = "Unknown"
} else if pod.DeletionTimestamp != nil {
reason = "Terminating"
}
statusType := statusTypeWaitting
switch reason {
case "Running":
statusType = statusTypeRunning
case "Failed":
statusType = statusTypeError
case "Error":
statusType = statusTypeError
case "Completed":
statusType = statusTypeCompleted
case "Succeeded":
if isPodReadyConditionReason(pod.Status.Conditions, "PodCompleted") {
statusType = statusTypeCompleted
}
default:
if strings.HasPrefix(reason, "OutOf") {
statusType = statusTypeError
}
}
return reason, statusType
}
func hasPodReadyCondition(conditions []corev1.PodCondition) bool {
for _, condition := range conditions {
if condition.Type == corev1.PodReady && condition.Status == corev1.ConditionTrue {
return true
}
}
return false
}
func isPodReadyConditionReason(conditions []corev1.PodCondition, reason string) bool {
for _, condition := range conditions {
if condition.Type == corev1.PodReady && condition.Reason != reason {
return false
}
}
return true
}