forked from datastax/pulsar-heartbeat
/
clientset.go
482 lines (419 loc) · 13.6 KB
/
clientset.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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//
// Copyright (c) 2020-2021 Datastax, Inc.
//
//
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 (
"context"
"fmt"
"os"
"path/filepath"
log "github.com/apex/log"
apps_v1 "k8s.io/api/apps/v1"
v1 "k8s.io/api/apps/v1"
batch_v1 "k8s.io/api/batch/v1"
core_v1 "k8s.io/api/core/v1"
ext_v1beta1 "k8s.io/api/extensions/v1beta1"
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/homedir"
metrics "k8s.io/metrics/pkg/client/clientset/versioned"
)
const (
// DefaultPulsarNamespace is the default pulsar namespace in the cluster
DefaultPulsarNamespace = "pulsar"
// ZookeeperSts is zookeeper sts name
ZookeeperSts = "zookeeper"
// BookkeeperSts is bookkeeper sts name
BookkeeperSts = "bookkeeper"
// BrokerDeployment is the broker deployment name
BrokerDeployment = "broker"
// BrokerSts is the broker deployment name
BrokerSts = "brokersts"
// ProxyDeployment is the proxy deployment name
ProxyDeployment = "proxy"
// FunctionWorkerDeployment is the function worker deployment name
FunctionWorkerDeployment = "functionWorker"
)
// ClusterStatusCode is the high level health of cluster status
type ClusterStatusCode int
const (
// TotalDown is the initial status
TotalDown ClusterStatusCode = iota
// OK is the healthy status
OK
// PartialReady is some parts of system are ok
PartialReady
)
// Client is the k8s client object
type Client struct {
Clientset *kubernetes.Clientset
Metrics *metrics.Clientset
ClusterName string
DefaultNamespace string
Status ClusterStatusCode
Zookeeper StatefulSet
Bookkeeper StatefulSet
BrokerSts StatefulSet
Broker Deployment
Proxy Deployment
FunctionWorker StatefulSet
}
// ClusterStatus is the health status of the cluster and its components
type ClusterStatus struct {
ZookeeperOfflineInstances int
BookkeeperOfflineInstances int
BrokerOfflineInstances int
BrokerStsOfflineInstances int
ProxyOfflineInstances int
Status ClusterStatusCode
}
// Deployment is the k8s deployment
type Deployment struct {
Name string
Replicas int32
Instances int32
}
// StatefulSet is the k8s sts
type StatefulSet struct {
Name string
Replicas int32
Instances int32
}
// GetK8sClient gets k8s clientset
func GetK8sClient(pulsarNamespace string) (*Client, error) {
var config *rest.Config
if home := homedir.HomeDir(); home != "" {
// TODO: add configuration to allow customized config file
kubeconfig := filepath.Join(home, ".kube", "config")
if _, err := os.Stat(kubeconfig); os.IsNotExist(err) {
log.Infof("this is an in-cluster k8s monitor, pulsar namespace %s", pulsarNamespace)
if config, err = rest.InClusterConfig(); err != nil {
return nil, err
}
} else {
log.Infof("this is outside of k8s cluster monitor, kubeconfig dir %s, pulsar namespace %s", kubeconfig, pulsarNamespace)
if config, err = clientcmd.BuildConfigFromFlags("", kubeconfig); err != nil {
return nil, err
}
}
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
return nil, err
}
metrics, err := metrics.NewForConfig(config)
if err != nil {
return nil, err
}
client := Client{
Clientset: clientset,
Metrics: metrics,
}
err = client.UpdateReplicas(pulsarNamespace)
if err != nil {
return nil, err
}
return &client, nil
}
func buildInClusterConfig() kubernetes.Interface {
config, err := rest.InClusterConfig()
if err != nil {
log.Fatalf("Can not get kubernetes config: %v", err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatalf("Can not create kubernetes client: %v", err)
}
return clientset
}
// UpdateReplicas updates the replicas for deployments and sts
func (c *Client) UpdateReplicas(namespace string) error {
brokersts, err := c.getStatefulSets(namespace, BrokerSts)
if err != nil {
return err
}
if len(brokersts.Items) == 0 {
c.BrokerSts.Replicas = 0
} else {
c.BrokerSts.Replicas = *(brokersts.Items[0]).Spec.Replicas
}
broker, err := c.getDeployments(namespace, BrokerDeployment)
if err != nil {
return err
}
if len(broker.Items) == 0 {
c.Broker.Replicas = 0
} else {
c.Broker.Replicas = *(broker.Items[0]).Spec.Replicas
}
if c.Broker.Replicas+c.BrokerSts.Replicas == 0 {
// broker can be deployed as sts with component=broker
brokersts, err = c.getStatefulSets(namespace, BrokerDeployment)
if err != nil {
return err
}
if len(brokersts.Items) == 0 {
c.BrokerSts.Replicas = 0
} else {
c.BrokerSts.Replicas = *(brokersts.Items[0]).Spec.Replicas
}
}
proxy, err := c.getDeployments(namespace, ProxyDeployment)
if err != nil {
return err
}
if len(proxy.Items) == 0 {
c.Proxy.Replicas = 0
} else {
c.Proxy.Replicas = *(proxy.Items[0]).Spec.Replicas
}
zk, err := c.getStatefulSets(namespace, ZookeeperSts)
if err != nil {
return err
}
c.Zookeeper.Replicas = *(zk.Items[0]).Spec.Replicas
bk, err := c.getStatefulSets(namespace, BookkeeperSts)
if err != nil {
return err
}
c.Bookkeeper.Replicas = *(bk.Items[0]).Spec.Replicas
return nil
}
// WatchPods watches the running pods vs intended replicas
func (c *Client) WatchPods(namespace string) error {
if counts, err := c.runningPodCounts(namespace, ZookeeperSts); err == nil {
c.Zookeeper.Instances = int32(counts)
} else {
return err
}
if counts, err := c.runningPodCounts(namespace, BookkeeperSts); err == nil {
c.Bookkeeper.Instances = int32(counts)
} else {
return err
}
if c.Broker.Replicas > 0 {
if counts, err := c.runningPodCounts(namespace, BrokerDeployment); err == nil {
c.Broker.Instances = int32(counts)
} else {
return err
}
}
if c.BrokerSts.Replicas > 0 {
var brokerStsCount, brokerCount int32
if counts, err := c.runningPodCounts(namespace, BrokerSts); err == nil {
brokerCount = int32(counts)
} else {
return err
}
if counts, err := c.runningPodCounts(namespace, BrokerDeployment); err == nil {
brokerStsCount = int32(counts)
} else {
return err
}
c.BrokerSts.Instances = brokerCount + brokerStsCount
}
if c.Proxy.Replicas > 0 {
if counts, err := c.runningPodCounts(namespace, ProxyDeployment); err == nil {
c.Proxy.Instances = int32(counts)
} else {
return err
}
}
return nil
}
// EvalHealth evaluate the health of cluster status
func (c *Client) EvalHealth() (string, ClusterStatus) {
health := ""
status := ClusterStatus{
ZookeeperOfflineInstances: int(c.Zookeeper.Replicas - c.Zookeeper.Instances),
BookkeeperOfflineInstances: int(c.Bookkeeper.Replicas - c.Bookkeeper.Instances),
BrokerOfflineInstances: int(c.Broker.Replicas - c.Broker.Instances),
BrokerStsOfflineInstances: int(c.BrokerSts.Replicas - c.BrokerSts.Instances),
ProxyOfflineInstances: int(c.Proxy.Replicas - c.Proxy.Instances),
Status: OK,
}
if c.Zookeeper.Instances < 2 {
health = fmt.Sprintf("\nCluster error - zookeeper is running %d instances out of %d replicas", c.Zookeeper.Instances, c.Zookeeper.Replicas)
status.Status = TotalDown
} else if c.Zookeeper.Instances == 2 {
health = fmt.Sprintf("\nCluster warning - zookeeper is running only 2 instances")
status.Status = PartialReady
}
if c.Bookkeeper.Instances < 2 {
health = health + fmt.Sprintf("\nCluster error - bookkeeper is running %d instances out of %d replicas", c.Bookkeeper.Instances, c.Bookkeeper.Replicas)
status.Status = TotalDown
} else if c.Bookkeeper.Instances != c.Bookkeeper.Replicas {
health = health + fmt.Sprintf("\nCluster warning - bookkeeper is running %d instances out of %d", c.Bookkeeper.Instances, c.Bookkeeper.Replicas)
status.Status = updateStatus(status.Status, PartialReady)
}
if (c.Broker.Instances + c.BrokerSts.Instances) == 0 {
health = health + fmt.Sprintf("\nCluster error - no broker instances is running")
status.Status = TotalDown
} else if c.Broker.Instances < c.Broker.Replicas {
health = fmt.Sprintf("\nCluster warning - broker is running %d instances out of %d", c.Broker.Instances, c.Broker.Replicas)
status.Status = updateStatus(status.Status, PartialReady)
}
if c.BrokerSts.Replicas > 0 && c.BrokerSts.Instances == 0 {
health = health + fmt.Sprintf("\nCluster error - broker stateful has no running instances out of %d replicas", c.Broker.Replicas)
status.Status = TotalDown
} else if status.BrokerStsOfflineInstances > 0 {
health = health + fmt.Sprintf("\nCluster error - broker statefulset only has %d running instances out of %d replicas", c.BrokerSts.Instances, c.BrokerSts.Replicas)
status.Status = TotalDown
}
if c.Proxy.Replicas > 0 && c.Proxy.Instances == 0 {
health = health + fmt.Sprintf("\nCluster error - proxy has no running instances out of %d replicas", c.Proxy.Replicas)
status.Status = TotalDown
} else if c.Proxy.Replicas > 0 && c.Proxy.Instances < c.Proxy.Replicas {
health = health + fmt.Sprintf("\nCluster warning - proxy is running %d instances out of %d", c.Proxy.Instances, c.Proxy.Replicas)
status.Status = updateStatus(status.Status, PartialReady)
}
c.Status = status.Status
return health, status
}
func updateStatus(original, current ClusterStatusCode) ClusterStatusCode {
if current == TotalDown || original == TotalDown {
return TotalDown
} else if current == PartialReady || original == PartialReady {
return PartialReady
}
return current
}
// WatchPodResource watches pod's resource
func (c *Client) WatchPodResource(namespace, component string) error {
podMetrics, err := c.Metrics.MetricsV1beta1().PodMetricses(namespace).List(context.TODO(), meta_v1.ListOptions{
LabelSelector: fmt.Sprintf("component=%s", component),
})
if err != nil {
return err
}
for _, podMetric := range podMetrics.Items {
podContainers := podMetric.Containers
for _, container := range podContainers {
cpuQuantity := container.Usage.Cpu().AsDec()
memQuantity, _ := container.Usage.Memory().AsInt64()
msg := fmt.Sprintf("Container Name: %s \n CPU usage: %v \n Memory usage: %d", container.Name, cpuQuantity, memQuantity)
fmt.Println(msg)
}
}
return nil
}
func (c *Client) runningPodCounts(namespace, component string) (int, error) {
pods, err := c.Clientset.CoreV1().Pods(namespace).List(context.TODO(), meta_v1.ListOptions{
LabelSelector: fmt.Sprintf("component=%s", component),
})
if err != nil {
return -1, err
}
counts := 0
for _, item := range pods.Items {
containers := 0
readyContainers := 0
for _, status := range item.Status.ContainerStatuses {
// status.Name is container name
if status.Ready {
readyContainers++
}
containers++
}
if containers == readyContainers {
counts++
}
}
return counts, nil
}
// GetNodeResource gets the node total available memory
func (c *Client) GetNodeResource() {
nodeList, err := c.Clientset.CoreV1().Nodes().List(context.TODO(), meta_v1.ListOptions{})
if err == nil {
if len(nodeList.Items) > 0 {
node := &nodeList.Items[0]
memQuantity := node.Status.Allocatable[core_v1.ResourceMemory] // "memory"
totalMemAvail := int(memQuantity.Value() >> 20)
fmt.Printf("total memory %d", totalMemAvail)
} else {
log.Fatal("Unable to read node list")
return
}
} else {
log.Fatalf("Error while reading node list data: %v", err)
}
}
func (c *Client) getDeployments(namespace, component string) (*v1.DeploymentList, error) {
deploymentsClient := c.Clientset.AppsV1().Deployments(namespace)
return deploymentsClient.List(context.TODO(), meta_v1.ListOptions{
LabelSelector: fmt.Sprintf("component=%s", component),
})
}
func (c *Client) getStatefulSets(namespace, component string) (*v1.StatefulSetList, error) {
stsClient := c.Clientset.AppsV1().StatefulSets(namespace)
return stsClient.List(context.TODO(), meta_v1.ListOptions{
LabelSelector: fmt.Sprintf("component=%s", component),
})
}
// ClusterStatusCodeString is the cluster status code in Kubernetes
func ClusterStatusCodeString(status ClusterStatusCode) string {
switch status {
case TotalDown:
return "Down"
case OK:
return "OK"
case PartialReady:
return "PartialReady"
default:
return "invalid"
}
}
// GetObjectMetaData returns metadata of a given k8s object
func GetObjectMetaData(obj interface{}) meta_v1.ObjectMeta {
var objectMeta meta_v1.ObjectMeta
switch object := obj.(type) {
case *apps_v1.Deployment:
objectMeta = object.ObjectMeta
case *core_v1.ReplicationController:
objectMeta = object.ObjectMeta
case *apps_v1.ReplicaSet:
objectMeta = object.ObjectMeta
case *apps_v1.DaemonSet:
objectMeta = object.ObjectMeta
case *core_v1.Service:
objectMeta = object.ObjectMeta
case *core_v1.Pod:
objectMeta = object.ObjectMeta
case *batch_v1.Job:
objectMeta = object.ObjectMeta
case *core_v1.PersistentVolume:
objectMeta = object.ObjectMeta
case *core_v1.Namespace:
objectMeta = object.ObjectMeta
case *core_v1.Secret:
objectMeta = object.ObjectMeta
case *ext_v1beta1.Ingress:
objectMeta = object.ObjectMeta
}
return objectMeta
}