/
client.go
289 lines (261 loc) · 8.13 KB
/
client.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
// Copyright © 2023 Alibaba Group Holding Ltd.
//
// 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 k8s
import (
"bytes"
"context"
"fmt"
"io"
"net"
"path/filepath"
"regexp"
"github.com/sealerio/sealer/test/testhelper"
"github.com/pkg/errors"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
const (
ReadyStatus = "Ready"
TRUE = "True"
FALSE = "False"
)
type Client struct {
client *kubernetes.Clientset
}
type NamespacePod struct {
Namespace v1.Namespace
PodList *v1.PodList
}
type EventPod struct {
Reason string
Message string
Count int32
Type string
Action string
Namespace string
}
func NewK8sClient(sshClient *testhelper.SSHClient) (*Client, error) {
kubeconfigPath := filepath.Join("/root", ".kube", "config")
data := testhelper.GetRemoteFileData(sshClient, kubeconfigPath)
reg := regexp.MustCompile(`server: https://(.*):6443`)
data = reg.ReplaceAll(data, []byte(fmt.Sprintf("server: https://%s:6443", sshClient.RemoteHostIP.String())))
config, err := clientcmd.RESTConfigFromKubeConfig(data)
if err != nil {
return nil, errors.Wrap(err, "failed to build kube config")
}
clientSet, err := kubernetes.NewForConfig(config)
if err != nil {
return nil, err
}
return &Client{
client: clientSet,
}, nil
}
func (c *Client) ListNodes() (*v1.NodeList, error) {
nodes, err := c.client.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{})
if err != nil {
return nil, errors.Wrapf(err, "failed to get cluster nodes")
}
return nodes, nil
}
func (c *Client) listNamespaces() (*v1.NamespaceList, error) {
namespaceList, err := c.client.CoreV1().Namespaces().List(context.TODO(), metav1.ListOptions{})
if err != nil {
return nil, errors.Wrapf(err, "failed to get namespaces")
}
return namespaceList, nil
}
func (c *Client) ListNodesByLabel(label string) (*v1.NodeList, error) {
nodes, err := c.client.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{LabelSelector: label})
if err != nil {
return nil, errors.Wrapf(err, "failed to get cluster nodes")
}
return nodes, nil
}
func (c *Client) ListNodeIPByLabel(label string) ([]net.IP, error) {
var ips []net.IP
nodes, err := c.ListNodesByLabel(label)
if err != nil {
return nil, err
}
for _, node := range nodes.Items {
for _, v := range node.Status.Addresses {
if v.Type == v1.NodeInternalIP {
ips = append(ips, net.ParseIP(v.Address))
}
}
}
return ips, nil
}
func (c *Client) ListAllNamespacesPods() ([]*NamespacePod, error) {
namespaceList, err := c.listNamespaces()
if err != nil {
return nil, err
}
var namespacePodList []*NamespacePod
for _, ns := range namespaceList.Items {
pods, err := c.client.CoreV1().Pods(ns.Name).List(context.TODO(), metav1.ListOptions{})
if err != nil {
return nil, errors.Wrapf(err, "failed to get all namespace pods")
}
namespacePod := NamespacePod{
Namespace: ns,
PodList: pods,
}
namespacePodList = append(namespacePodList, &namespacePod)
}
return namespacePodList, nil
}
// Check if all pods of kube-system are ready
func (c *Client) CheckAllKubeSystemPodsReady() (bool, error) {
pods, err := c.client.CoreV1().Pods("kube-system").List(context.TODO(), metav1.ListOptions{})
if err != nil {
return false, errors.Wrapf(err, "failed to get kube-system namespace pods")
}
// pods.Items maybe nil
if len(pods.Items) == 0 {
return false, nil
}
for _, pod := range pods.Items {
// pod.Status.ContainerStatus == nil because of pod contain initcontainer
if len(pod.Status.ContainerStatuses) == 0 {
continue
}
if !pod.Status.ContainerStatuses[0].Ready {
return false, nil
}
}
return true, nil
}
func (c *Client) GetPodLog(namespace, podName string) (string, error) {
req := c.client.CoreV1().Pods(namespace).GetLogs(podName, &v1.PodLogOptions{})
podLogs, err := req.Stream(context.TODO())
if err != nil {
return "", err
}
defer func() {
_ = podLogs.Close()
}()
buf := new(bytes.Buffer)
_, err = io.Copy(buf, podLogs)
if err != nil {
return "", err
}
return buf.String(), nil
}
func (c *Client) GetPodEvents(namespace, podName string) ([]v1.Event, error) {
events, err := c.client.CoreV1().
Events(namespace).
List(context.TODO(), metav1.ListOptions{FieldSelector: "involvedObject.name=" + podName, TypeMeta: metav1.TypeMeta{Kind: "Pod"}})
if err != nil {
return nil, err
}
return events.Items, nil
}
func (c *Client) getPodReadyStatus(pod v1.Pod) bool {
for _, condition := range pod.Status.Conditions {
if condition.Type != ReadyStatus {
continue
}
if condition.Status == TRUE {
return true
}
}
return false
}
func (c *Client) GetNotReadyPodEvent() (map[string][]EventPod, error) {
namespacePodList, err := c.ListAllNamespacesPods()
if err != nil {
return nil, err
}
result := make(map[string][]EventPod)
for _, podNamespace := range namespacePodList {
for _, pod := range podNamespace.PodList.Items {
if c.getPodReadyStatus(pod) {
continue
}
events, err := c.GetPodEvents(podNamespace.Namespace.Name, pod.Name)
if err != nil {
return nil, err
}
var eventpods []EventPod
for _, event := range events {
eventpods = append(eventpods, EventPod{
Reason: event.Reason,
Message: event.Message,
Count: event.Count,
Type: event.Type,
Action: event.Action,
Namespace: event.Namespace,
})
}
result[pod.Name] = append(result[pod.Name], eventpods...)
}
}
return result, nil
}
// If exist pod not ready, show pod events and logs
func (c *Client) OutputNotReadyPodInfo() error {
podEvents, err := c.GetNotReadyPodEvent()
if err != nil {
return err
}
for podName, events := range podEvents {
fmt.Println("=========================================================================================================================================")
fmt.Println("PodName: " + podName)
fmt.Println("******************************************************Events*****************************************************************************")
var namespace string
for _, event := range events {
namespace = event.Namespace
fmt.Printf("Reason: %s\n", event.Reason)
fmt.Printf("Message: %s\n", event.Message)
fmt.Printf("Count: %v\n", event.Count)
fmt.Printf("Type: %s\n", event.Type)
fmt.Printf("Action: %s\n", event.Action)
fmt.Println("------------------------------------------------------------------------------------------------------------------------------------")
}
log, err := c.GetPodLog(namespace, podName)
if err != nil {
return err
}
fmt.Println("********************************************************Log*****************************************************************************")
fmt.Println(log)
fmt.Println("=========================================================================================================================================")
}
return nil
}
// Check if all nodes are ready
func (c *Client) CheckAllNodeReady() (bool, error) {
nodes, err := c.ListNodes()
if err != nil {
return false, err
}
for _, node := range nodes.Items {
for _, condition := range node.Status.Conditions {
if condition.Type != ReadyStatus {
continue
}
if condition.Status == FALSE {
fmt.Println("********************************************************Node*****************************************************************************")
fmt.Println(condition.Reason)
fmt.Println(condition.Message)
fmt.Println("=========================================================================================================================================")
return false, nil
}
}
}
return true, nil
}