/
pod.go
331 lines (310 loc) · 9.63 KB
/
pod.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
package resource
import (
"context"
"encoding/base64"
"fmt"
"github.com/kubespace/kubespace/pkg/core/code"
"github.com/kubespace/kubespace/pkg/kubernetes/config"
"github.com/kubespace/kubespace/pkg/kubernetes/types"
"github.com/kubespace/kubespace/pkg/utils"
"io"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/tools/remotecommand"
"k8s.io/klog/v2"
"sync"
)
var PodGVR = &schema.GroupVersionResource{
Group: "",
Version: "v1",
Resource: "pods",
}
type Pod struct {
*Resource
execSession *sync.Map
}
func NewPod(config *config.KubeConfig) *Pod {
p := &Pod{
execSession: &sync.Map{},
}
p.Resource = NewResource(config, types.PodType, PodGVR, p.listObjectProcess)
p.actions = map[string]ActionHandle{
types.ListAction: p.List,
types.GetAction: p.Get,
types.StdinAction: p.ExecStdIn,
types.DeleteAction: p.Delete,
}
return p
}
type BuildContainer struct {
Name string `json:"name"`
Status string `json:"status"`
Restarts int32 `json:"restarts"`
Ready bool `json:"ready"`
}
type BuildPod struct {
UID string `json:"uid"`
Labels map[string]string `json:"labels"`
Name string `json:"name"`
Namespace string `json:"namespace"`
Containers []*BuildContainer `json:"containers"`
InitContainers []*BuildContainer `json:"init_containers"`
Controlled string `json:"controlled"`
ControlledName string `json:"controlled_name"`
Qos string `json:"qos"`
Created metav1.Time `json:"created"`
Status string `json:"status"`
Ip string `json:"ip"`
NodeName string `json:"node_name"`
ResourceVersion string `json:"resource_version"`
ContainerNum int `json:"containerNum"`
Restarts int32 `json:"restarts"`
}
func (p *Pod) ToBuildContainer(statuses []corev1.ContainerStatus, container *corev1.Container) *BuildContainer {
bc := &BuildContainer{
Name: container.Name,
}
for _, s := range statuses {
if s.Name == container.Name {
bc.Restarts = s.RestartCount
if s.State.Running != nil {
bc.Status = "running"
} else if s.State.Terminated != nil {
bc.Status = "terminated"
} else if s.State.Waiting != nil {
bc.Status = "waiting"
}
bc.Ready = s.Ready
break
}
}
return bc
}
func (p *Pod) ToBuildPod(pod *corev1.Pod) *BuildPod {
if pod == nil {
return nil
}
var restarts = int32(0)
var containers []*BuildContainer
for _, container := range pod.Spec.Containers {
bc := p.ToBuildContainer(pod.Status.ContainerStatuses, &container)
containers = append(containers, bc)
if bc.Restarts > restarts {
restarts = bc.Restarts
}
}
cn := len(containers)
var initContainers []*BuildContainer
for _, container := range pod.Spec.InitContainers {
bc := p.ToBuildContainer(pod.Status.InitContainerStatuses, &container)
initContainers = append(initContainers, bc)
if bc.Restarts > restarts {
restarts = bc.Restarts
}
}
cn += len(initContainers)
var controlled = ""
var controlledName = ""
if len(pod.ObjectMeta.OwnerReferences) > 0 {
controlled = pod.ObjectMeta.OwnerReferences[0].Kind
controlledName = pod.ObjectMeta.OwnerReferences[0].Name
}
return &BuildPod{
UID: string(pod.UID),
Labels: pod.Labels,
Name: pod.Name,
Namespace: pod.Namespace,
Containers: containers,
InitContainers: initContainers,
Controlled: controlled,
ControlledName: controlledName,
Qos: string(pod.Status.QOSClass),
Status: string(pod.Status.Phase),
Ip: pod.Status.PodIP,
Created: pod.GetCreationTimestamp(),
NodeName: pod.Spec.NodeName,
ResourceVersion: pod.ResourceVersion,
ContainerNum: cn,
Restarts: restarts,
}
}
func (p *Pod) listObjectProcess(query *QueryParams, obj *unstructured.Unstructured) (interface{}, error) {
pod := &corev1.Pod{}
if err := runtime.DefaultUnstructuredConverter.FromUnstructured(obj.Object, pod); err != nil {
return nil, err
}
if len(query.Names) > 0 && !utils.Contains(query.Names, pod.Name) {
return nil, nil
}
return p.ToBuildPod(pod), nil
}
type PodExecParams struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
Container string `json:"container"`
SessionId string `json:"session_id"`
Rows string `json:"rows"`
Cols string `json:"cols"`
}
// Exec Todo 添加注释
func (p *Pod) Exec(params interface{}, writer OutWriter) *utils.Response {
var execParams PodExecParams
if err := utils.ConvertTypeByJson(params, &execParams); err != nil {
return &utils.Response{Code: code.ParamsError, Msg: err.Error()}
}
execCmd := []string{"/bin/sh", "-c",
fmt.Sprintf(`export LINES=%s; export COLUMNS=%s;
TERM=xterm-256color; export TERM;
[ -x /bin/bash ] && ([ -x /usr/bin/script ] && /usr/bin/script -q -c \"/bin/bash\" /dev/null || exec /bin/bash) || exec /bin/sh`,
execParams.Rows, execParams.Cols)}
sshReq := p.client.CoreV1().RESTClient().Post().
Resource("pods").
Name(execParams.Name).
Namespace(execParams.Namespace).
SubResource("exec").
VersionedParams(&corev1.PodExecOptions{
Container: execParams.Container,
Command: execCmd,
Stdin: true,
Stdout: true,
Stderr: true,
TTY: true,
}, scheme.ParameterCodec)
executor, err := remotecommand.NewSPDYExecutor(p.client.RestConfig(), "POST", sshReq.URL())
if err != nil {
return &utils.Response{Code: code.RequestError, Msg: err.Error()}
}
handler := &streamHandler{
resizeEvent: make(chan remotecommand.TerminalSize),
stdinCh: make(chan string),
writer: writer,
}
sessionId := execParams.SessionId
p.execSession.Store(sessionId, handler)
go func() {
defer p.execSession.Delete(sessionId)
defer handler.Close()
if err := executor.Stream(remotecommand.StreamOptions{
Stdin: handler,
Stdout: handler,
Stderr: handler,
TerminalSizeQueue: handler,
Tty: true,
}); err != nil {
klog.Errorf("exec pod container error session %s: %v", sessionId, err)
handler.Write([]byte(err.Error()))
}
klog.Info("connection closed")
handler.Write([]byte(fmt.Sprint("\n\rConnection closed")))
}()
return &utils.Response{Code: code.Success}
}
// todo 添加注释
type streamHandler struct {
stdinCh chan string
resizeEvent chan remotecommand.TerminalSize
writer OutWriter
}
func (s *streamHandler) Read(p []byte) (size int, err error) {
select {
case inData, ok := <-s.stdinCh:
if !ok {
return 0, fmt.Errorf("stream closed")
}
d, err := base64.StdEncoding.DecodeString(inData)
if err != nil {
klog.Errorf("decode stream input data error: %s", err.Error())
} else {
size = len(d)
copy(p, d)
}
case <-s.writer.StopCh():
return 0, fmt.Errorf("writer closed")
}
return
}
func (s *streamHandler) Write(p []byte) (size int, err error) {
copyData := make([]byte, len(p))
copy(copyData, p)
size = len(p)
err = s.writer.Write(string(copyData))
return
}
// Next executor回调获取web是否resize
func (s *streamHandler) Next() (size *remotecommand.TerminalSize) {
ret := <-s.resizeEvent
size = &ret
return
}
func (s *streamHandler) Close() {
s.writer.Close()
}
type StdInParams struct {
SessionId string `json:"session_id"`
Input string `json:"input"`
Width uint16 `json:"width"`
Height uint16 `json:"height"`
}
// ExecStdIn todo 添加注释
func (p *Pod) ExecStdIn(params interface{}) *utils.Response {
var inParams StdInParams
if err := utils.ConvertTypeByJson(params, &inParams); err != nil {
return &utils.Response{Code: code.RequestError, Msg: err.Error()}
}
handlerObj, ok := p.execSession.Load(inParams.SessionId)
if !ok {
return &utils.Response{Code: code.RequestError, Msg: fmt.Sprintf("no open terminal")}
}
handler, ok := handlerObj.(*streamHandler)
if !ok {
return &utils.Response{Code: code.RequestError, Msg: fmt.Sprintf("open terminal error")}
}
if inParams.Width > 0 && inParams.Height > 0 {
handler.resizeEvent <- remotecommand.TerminalSize{Width: inParams.Width, Height: inParams.Height}
}
handler.stdinCh <- inParams.Input
return &utils.Response{Code: code.Success, Msg: "Success"}
}
type PodLogParams struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
Container string `json:"container"`
}
func (p *Pod) Log(params interface{}, writer OutWriter) *utils.Response {
var logParams PodLogParams
if err := utils.ConvertTypeByJson(params, &logParams); err != nil {
return &utils.Response{Code: code.ParamsError, Msg: err.Error()}
}
tailLines := int64(100)
podLogOpts := &corev1.PodLogOptions{
Container: logParams.Container,
Follow: true,
TailLines: &tailLines,
}
req := p.client.CoreV1().Pods(logParams.Namespace).GetLogs(logParams.Name, podLogOpts)
logStream, err := req.Stream(context.Background())
if err != nil {
klog.Errorf("open pod %s container %s log stream error: %s", logParams.Name, logParams.Container, err.Error())
return &utils.Response{Code: code.RequestError, Msg: err.Error()}
}
handler := &streamHandler{writer: writer}
go func() {
if _, err = io.Copy(handler, logStream); err != nil {
klog.Errorf("io copy log stream error: %s", err.Error())
handler.Close()
}
klog.V(1).Infof("io copy stopped")
}()
go func() {
select {
case <-handler.writer.StopCh():
klog.V(1).Infof("out stream writer stopped")
logStream.Close()
}
}()
return &utils.Response{Code: code.Success}
}