-
Notifications
You must be signed in to change notification settings - Fork 248
/
service-monitor.go
448 lines (413 loc) · 15.6 KB
/
service-monitor.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
/*
* Tencent is pleased to support the open source community by making Blueking Container Service available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* 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 discovery
import (
"context"
"encoding/json"
"fmt"
"path"
"reflect"
"regexp"
"strings"
"sync"
"github.com/Tencent/bk-bcs/bcs-common/common/blog"
commtypes "github.com/Tencent/bk-bcs/bcs-common/common/types"
apisbkbcsv2 "github.com/Tencent/bk-bcs/bcs-mesos/kubebkbcsv2/apis/bkbcs/v2"
apismonitorv1 "github.com/Tencent/bk-bcs/bcs-mesos/kubebkbcsv2/apis/monitor/v1"
internalclientset "github.com/Tencent/bk-bcs/bcs-mesos/kubebkbcsv2/client/clientset/versioned"
informers "github.com/Tencent/bk-bcs/bcs-mesos/kubebkbcsv2/client/informers/externalversions"
bkbcsv2 "github.com/Tencent/bk-bcs/bcs-mesos/kubebkbcsv2/client/listers/bkbcs/v2"
"github.com/Tencent/bk-bcs/bcs-services/bcs-service-prometheus/types"
apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
apiextensionsclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/clientcmd"
)
type serviceMonitor struct {
sync.RWMutex
kubeconfig string
sdFilePath string
module string
promFilePrefix string
eventHandler EventHandleFunc
// endpoints
endpointLister bkbcsv2.BcsEndpointLister
endpointInformer cache.SharedIndexInformer
// service monitor
// serviceMonitorLister monitorv1.ServiceMonitorLister
serviceMonitorInformer cache.SharedIndexInformer
// apiextensions clientset
extensionClientset *apiextensionsclient.Clientset
// local cache for combination of servicemonitor & bcsendpoint
svrMonitors map[string]*serviceEndpoint
}
type serviceEndpoint struct {
serviceM *apismonitorv1.ServiceMonitor
endpoints map[string]*apisbkbcsv2.BcsEndpoint
cPorts map[string]apismonitorv1.Endpoint
}
func (s *serviceEndpoint) getPrometheusConfigs() []*types.PrometheusSdConfig {
promConfigs := make([]*types.PrometheusSdConfig, 0)
// traverse BcsEndpoints, corresponding to a separate BcsService
for _, bcsEndpoint := range s.endpoints {
conf := &types.PrometheusSdConfig{
Targets: make([]string, 0),
Labels: make(map[string]string),
}
for k, v := range bcsEndpoint.Labels {
r, _ := regexp.Compile("[a-zA-Z_][a-zA-Z0-9_]*")
rk := r.FindAllString(k, 1)
if len(rk) != 1 || rk[0] != k {
blog.Warnf("BcsEndpoint(%s) Label(%s: %s) is invalid, skip", bcsEndpoint.GetUuid(), k, v)
continue
}
conf.Labels[k] = v
}
// append ServiceMonitor Identity
conf.Labels["ServiceMonitor"] = s.serviceM.GetUuid()
// append BcsEndpoint Identity
conf.Labels["BcsEndpoint"] = bcsEndpoint.GetUuid()
// append namespace
conf.Labels["namespace"] = bcsEndpoint.Namespace
conf.Labels["job"] = fmt.Sprintf("%s/%s/0", bcsEndpoint.Namespace, s.serviceM.Name)
// conf.Labels["name"] = s.serviceM.Name
for _, endpoint := range bcsEndpoint.Spec.Endpoints {
for _, cPort := range endpoint.Ports {
_, ok := s.cPorts[cPort.Name]
if !ok {
blog.V(5).Infof("BcsEndpoint(%s) endpoint(%s) port(%s) don't matched, and continue",
bcsEndpoint.GetUuid(), endpoint.ContainerIP, cPort.Name)
continue
}
// if container network=Host
if endpoint.NetworkMode == "HOST" {
conf.Targets = append(conf.Targets, fmt.Sprintf("%s:%d", endpoint.NodeIP, cPort.ContainerPort))
} else {
conf.Targets = append(conf.Targets, fmt.Sprintf("%s:%d", endpoint.ContainerIP, cPort.ContainerPort))
}
}
}
promConfigs = append(promConfigs, conf)
}
return promConfigs
}
// NewServiceMonitor new serviceMonitor for discovery node cadvisor targets
func NewServiceMonitor(kubeconfig string, promFilePrefix, module string) (Discovery, error) {
disc := &serviceMonitor{
kubeconfig: kubeconfig,
module: module,
promFilePrefix: promFilePrefix,
svrMonitors: make(map[string]*serviceEndpoint),
}
return disc, nil
}
// Start start up service monitor feature
func (disc *serviceMonitor) Start() error {
cfg, err := clientcmd.BuildConfigFromFlags("", disc.kubeconfig)
if err != nil {
blog.Errorf("build kubeconfig %s error %s", disc.kubeconfig, err.Error())
return err
}
// apiextensions clientset for creating BcsLogConfig Crd
disc.extensionClientset, err = apiextensionsclient.NewForConfig(cfg)
if err != nil {
blog.Errorf("build apiextension client by kubeconfig %s error %s", disc.kubeconfig, err.Error())
return err
}
// create BcsLogConfig Crd
err = disc.createserviceMonitor()
if err != nil {
return err
}
stopCh := make(chan struct{})
// internal clientset for informer serviceMonitor Crd
internalClientset, err := internalclientset.NewForConfig(cfg)
if err != nil {
blog.Errorf("build internal clientset by kubeconfig %s error %s", disc.kubeconfig, err.Error())
return err
}
internalFactory := informers.NewSharedInformerFactory(internalClientset, 0)
disc.endpointInformer = internalFactory.Bkbcs().V2().BcsEndpoints().Informer()
disc.endpointLister = internalFactory.Bkbcs().V2().BcsEndpoints().Lister()
blog.Infof("build bkbcsClientset for config %s success", disc.kubeconfig)
// init monitor clientset
disc.serviceMonitorInformer = internalFactory.Monitor().V1().ServiceMonitors().Informer()
internalFactory.Start(stopCh)
// Wait for all caches to sync.
internalFactory.WaitForCacheSync(stopCh)
blog.Infof("build monitorClientset for config %s success", disc.kubeconfig)
// add k8s resources event handler functions
disc.serviceMonitorInformer.AddEventHandler(
cache.ResourceEventHandlerFuncs{
AddFunc: disc.OnServiceMonitorAdd,
UpdateFunc: disc.OnServiceMonitorUpdate,
DeleteFunc: disc.OnServiceMonitorDelete,
},
)
disc.endpointInformer.AddEventHandler(
cache.ResourceEventHandlerFuncs{
AddFunc: disc.OnEndpointsAdd,
UpdateFunc: disc.OnEndpointsUpdate,
DeleteFunc: disc.OnEndpointsDelete,
},
)
return nil
}
// createserviceMonitor xxx
// create crd of ServiceMonitor
func (disc *serviceMonitor) createserviceMonitor() error {
blog.Infof("start create ServiceMonitor")
serviceMonitorPlural := "servicemonitors"
serviceMonitorFullName := "servicemonitors" + "." + apismonitorv1.SchemeGroupVersion.Group
crd := &apiextensionsv1beta1.CustomResourceDefinition{
ObjectMeta: metav1.ObjectMeta{
Name: serviceMonitorFullName,
},
Spec: apiextensionsv1beta1.CustomResourceDefinitionSpec{
Group: apismonitorv1.SchemeGroupVersion.Group, // serviceMonitorsGroup,
Version: apismonitorv1.SchemeGroupVersion.Version, // serviceMonitorsVersion,
Scope: apiextensionsv1beta1.NamespaceScoped,
Names: apiextensionsv1beta1.CustomResourceDefinitionNames{
Plural: serviceMonitorPlural,
Kind: reflect.TypeOf(apismonitorv1.ServiceMonitor{}).Name(),
ListKind: reflect.TypeOf(apismonitorv1.ServiceMonitorList{}).Name(),
},
},
}
_, err := disc.extensionClientset.ApiextensionsV1beta1().CustomResourceDefinitions().Create(
context.Background(), crd, metav1.CreateOptions{})
if err != nil {
if apierrors.IsAlreadyExists(err) {
blog.Infof("serviceMonitor Crd is already exists")
return nil
}
blog.Errorf("create serviceMonitor Crd error %s", err.Error())
return err
}
blog.Infof("create serviceMonitor Crd success")
return nil
}
// GetPrometheusSdConfig xxx
func (disc *serviceMonitor) GetPrometheusSdConfig(key string) ([]*types.PrometheusSdConfig, error) {
disc.Lock()
defer disc.Unlock()
svrMonitor, ok := disc.svrMonitors[key]
if !ok {
return nil, fmt.Errorf("ServiceMonitor(%s) Not Found", key)
}
return svrMonitor.getPrometheusConfigs(), nil
}
// GetPromSdConfigFile xxx
func (disc *serviceMonitor) GetPromSdConfigFile(key string) string {
return strings.ToLower(path.Join(disc.promFilePrefix, fmt.Sprintf("%s_%s%s", key, disc.module, DiscoveryFileName)))
}
// RegisterEventFunc xxx
func (disc *serviceMonitor) RegisterEventFunc(handleFunc EventHandleFunc) {
disc.eventHandler = handleFunc
}
// OnServiceMonitorAdd xxx
func (disc *serviceMonitor) OnServiceMonitorAdd(obj interface{}) {
serviceM, ok := obj.(*apismonitorv1.ServiceMonitor)
if !ok {
blog.Errorf("cannot convert to *apismonitorv1.ServiceMonitor: %v", obj)
return
}
by, _ := json.Marshal(serviceM)
blog.Infof("receive ServiceMonitor(%s) Data(%s) Add event", serviceM.GetUuid(), string(by))
disc.handlerServiceMonitorChanged(serviceM)
}
func (disc *serviceMonitor) validateServiceMonitor(serviceM *apismonitorv1.ServiceMonitor) bool {
if len(serviceM.Spec.Endpoints) == 0 {
blog.Errorf("ServiceMonitor(%s) len(Endpoints)==0, then ignore it", serviceM.GetUuid())
return false
}
if len(serviceM.Spec.Selector.MatchLabels) == 0 {
blog.Errorf("ServiceMonitor(%s) len(Selector.MatchLabels)==0, then ignore it", serviceM.GetUuid())
return false
}
return true
}
// OnServiceMonitorUpdate xxx
// if on update event, then don't need to update sd config
func (disc *serviceMonitor) OnServiceMonitorUpdate(old, cur interface{}) {
serviceM, ok := cur.(*apismonitorv1.ServiceMonitor)
if !ok {
blog.Errorf("cannot convert to *apismonitorv1.ServiceMonitor: %v", cur)
return
}
by, _ := json.Marshal(serviceM)
blog.Infof("receive ServiceMonitor(%s) Data(%s) Update event", serviceM.GetUuid(), string(by))
disc.handlerServiceMonitorChanged(serviceM)
}
// handlerServiceMonitorChanged recreate relationship between ServiceMonitor & BcsEndpoint
// no matter AddEvent or UpdateEvent
func (disc *serviceMonitor) handlerServiceMonitorChanged(serviceM *apismonitorv1.ServiceMonitor) {
if !disc.validateServiceMonitor(serviceM) {
return
}
o := &serviceEndpoint{
serviceM: serviceM,
endpoints: make(map[string]*apisbkbcsv2.BcsEndpoint),
cPorts: make(map[string]apismonitorv1.Endpoint),
}
for _, endpoint := range serviceM.Spec.Endpoints {
o.cPorts[endpoint.Port] = endpoint
blog.Infof("ServiceMonitor(%s) have endpoint(%s:%s)", serviceM.GetUuid(), endpoint.Port, endpoint.Path)
}
rms := labels.NewSelector()
reqs, err := serviceM.GetSelector()
if err != nil {
blog.Errorf("ServiceMonitor(%s) selector definition err, %s. skip handling", serviceM.GetUuid(), err.Error())
return
}
for _, o := range reqs {
rms.Add(o)
}
endpoints, err := disc.endpointLister.BcsEndpoints(serviceM.Namespace).List(rms)
if err != nil {
blog.Errorf("ServiceMonitor(%s) get Endpoints failed: %s", serviceM.GetUuid(), err.Error())
return
}
for _, v := range endpoints {
if !serviceM.Match(v.Labels) {
blog.V(5).Infof("ServiceMonitor(%s) don't match BcsEndpoint(%s), and continue", serviceM.GetUuid(), v.GetUuid())
continue
}
o.endpoints[v.GetUuid()] = v
blog.Infof("ServiceMonitor(%s) add selected BcsEndpoint(%s) success", serviceM.GetUuid(), v.GetUuid())
}
disc.Lock()
disc.svrMonitors[serviceM.GetUuid()] = o
disc.Unlock()
blog.Infof("handle recreate ServiceMonitor(%s) success", serviceM.GetUuid())
go disc.eventHandler(Info{Module: disc.module, Key: serviceM.GetUuid()})
}
// OnServiceMonitorDelete xxx
func (disc *serviceMonitor) OnServiceMonitorDelete(obj interface{}) {
serviceM, ok := obj.(*apismonitorv1.ServiceMonitor)
if !ok {
blog.Errorf("cannot convert to *apismonitorv1.ServiceMonitor: %v", obj)
return
}
blog.Infof("receive ServiceMonitor(%s) Delete event", serviceM.GetUuid())
disc.Lock()
delete(disc.svrMonitors, serviceM.GetUuid())
disc.Unlock()
blog.Infof("handle Delete event ServiceMonitor(%s) success", serviceM.GetUuid())
// call event handler
go disc.eventHandler(Info{Module: disc.module, Key: serviceM.GetUuid()})
}
// OnEndpointsAdd xxx
func (disc *serviceMonitor) OnEndpointsAdd(obj interface{}) {
endpoint, ok := obj.(*apisbkbcsv2.BcsEndpoint)
if !ok {
blog.Errorf("cannot convert to *apisbkbcsv2.BcsEndpoint: %v", obj)
return
}
by, _ := json.Marshal(endpoint)
blog.Infof("receive BcsEndpoint(%s) Data(%s) Add event", endpoint.GetUuid(), string(by))
disc.Lock()
defer disc.Unlock()
for _, sm := range disc.svrMonitors {
serviceM := sm.serviceM
if serviceM.Namespace != endpoint.Namespace || !serviceM.Match(endpoint.Labels) {
blog.V(5).Infof("ServiceMonitor(%s) don't match BcsEndpoint(%s), and continue", serviceM.GetUuid(),
endpoint.GetUuid())
continue
}
sm.endpoints[endpoint.GetUuid()] = endpoint
blog.Infof("ServiceMonitor(%s) add selected BcsEndpoint(%s) success", serviceM.GetUuid(), endpoint.GetUuid())
// call event handler
go disc.eventHandler(Info{Module: disc.module, Key: serviceM.GetUuid()})
}
}
// OnEndpointsUpdate xxx
// if on update event, then don't need to update sd config
func (disc *serviceMonitor) OnEndpointsUpdate(old, cur interface{}) {
oldEndpoint, ok := old.(*apisbkbcsv2.BcsEndpoint)
if !ok {
blog.Errorf("cannot convert to *apisbkbcsv2.BcsEndpoint: %v", old)
return
}
curEndpoint, ok := cur.(*apisbkbcsv2.BcsEndpoint)
if !ok {
blog.Errorf("cannot convert to *apisbkbcsv2.BcsEndpoint: %v", cur)
return
}
changed := checkEndpointsChanged(oldEndpoint.Spec.BcsEndpoint, curEndpoint.Spec.BcsEndpoint)
if !changed {
blog.Infof("OnEndpointsUpdate BcsEndpoint(%s) don't change", oldEndpoint.GetUuid())
return
}
by, _ := json.Marshal(curEndpoint)
blog.Infof("receive BcsEndpoint(%s) Data(%s) Update event", curEndpoint.GetUuid(), string(by))
disc.Lock()
defer disc.Unlock()
for _, sm := range disc.svrMonitors {
serviceM := sm.serviceM
if serviceM.Namespace != curEndpoint.Namespace || !serviceM.Match(curEndpoint.Labels) {
blog.V(5).Infof("ServiceMonitor(%s) don't match BcsEndpoint(%s), and continue", serviceM.GetUuid(),
curEndpoint.GetUuid())
continue
}
sm.endpoints[curEndpoint.GetUuid()] = curEndpoint
blog.Infof("ServiceMonitor(%s) update selected BcsEndpoint(%s) success", serviceM.GetUuid(), curEndpoint.GetUuid())
// call event handler
go disc.eventHandler(Info{Module: disc.module, Key: serviceM.GetUuid()})
}
}
func checkEndpointsChanged(old, cur commtypes.BcsEndpoint) bool {
if len(old.Endpoints) != len(cur.Endpoints) {
return true
}
endpoints := make(map[string]bool)
for _, in := range old.Endpoints {
endpoints[in.ContainerIP] = false
}
for _, in := range cur.Endpoints {
endpoints[in.ContainerIP] = true
}
for k, v := range endpoints {
if !v {
blog.Infof("BcsEndpoint(%s) ContainerIP(%s) changed", k)
return true
}
}
return false
}
// OnEndpointsDelete xxx
func (disc *serviceMonitor) OnEndpointsDelete(obj interface{}) {
endpoint, ok := obj.(*apisbkbcsv2.BcsEndpoint)
if !ok {
blog.Errorf("cannot convert to *apisbkbcsv2.BcsEndpoint: %v", obj)
return
}
blog.Infof("receive BcsEndpoint(%s) Delete event", endpoint.GetUuid())
disc.Lock()
defer disc.Unlock()
for _, sm := range disc.svrMonitors {
serviceM := sm.serviceM
if serviceM.Namespace != endpoint.Namespace || !serviceM.Match(endpoint.Labels) {
blog.V(5).Infof("ServiceMonitor(%s) don't match BcsEndpoint(%s), and continue", serviceM.GetUuid(),
endpoint.GetUuid())
continue
}
delete(sm.endpoints, endpoint.GetUuid())
blog.Infof("ServiceMonitor(%s) delete selected BcsEndpoint(%s) success", serviceM.GetUuid(), endpoint.GetUuid())
// call event handler
go disc.eventHandler(Info{Module: disc.module, Key: serviceM.GetUuid()})
}
}