forked from TencentBlueKing/bk-cmdb
/
subscription.go
379 lines (330 loc) · 13.9 KB
/
subscription.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
/*
* Tencent is pleased to support the open source community by making 蓝鲸 available.
* Copyright (C) 2017-2018 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 service
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"sort"
"strconv"
"strings"
"github.com/emicklei/go-restful"
"configcenter/src/common"
"configcenter/src/common/blog"
"configcenter/src/common/metadata"
commontypes "configcenter/src/common/types"
"configcenter/src/common/util"
"configcenter/src/scene_server/event_server/types"
)
// Subscribe Subscribe events
func (s *Service) Subscribe(req *restful.Request, resp *restful.Response) {
var err error
pheader := req.Request.Header
defErr := s.CCErr.CreateDefaultCCErrorIf(util.GetLanguage(pheader))
ownerID := util.GetOwnerID(pheader)
sub := &metadata.Subscription{}
if err := json.NewDecoder(req.Request.Body).Decode(&sub); err != nil {
blog.Errorf("add subscription, but decode body failed, err: %v", err)
resp.WriteError(http.StatusBadRequest, &metadata.RespError{Msg: defErr.Error(common.CCErrCommJSONUnmarshalFailed)})
return
}
now := commontypes.Now()
sub.Operator = util.GetUser(req.Request.Header)
if sub.TimeOut <= 0 {
sub.TimeOut = 10
}
if sub.ConfirmMode == metadata.ConfirmmodeHttpstatus && sub.ConfirmPattern == "" {
sub.ConfirmPattern = "200"
}
sub.LastTime = &now
sub.OwnerID = ownerID
sub.SubscriptionForm = strings.Replace(sub.SubscriptionForm, " ", "", 0)
events := strings.Split(sub.SubscriptionForm, ",")
sort.Strings(events)
sub.SubscriptionForm = strings.Join(events, ",")
exists := []metadata.Subscription{}
err = s.db.GetMutilByCondition(common.BKTableNameSubscription, nil, map[string]interface{}{common.BKSubscriptionNameField: sub.SubscriptionName, common.BKOwnerIDField: ownerID}, &exists, "", 0, 0)
if err != nil {
resp.WriteError(http.StatusInternalServerError, &metadata.RespError{Msg: defErr.Error(common.CCErrCommDuplicateItem)})
return
}
if len(exists) > 0 {
if err = s.rebook(exists[0].SubscriptionID, ownerID, sub); err != nil {
resp.WriteError(http.StatusBadRequest, &metadata.RespError{Msg: defErr.Error(common.CCErrEventSubscribeUpdateFailed)})
return
}
} else {
sub.SubscriptionID, err = s.db.GetIncID(common.BKTableNameSubscription)
if nil != err {
resp.WriteError(http.StatusInternalServerError, &metadata.RespError{Msg: defErr.Error(common.CCErrEventSubscribeInsertFailed)})
return
}
// save to the storage
if _, err := s.db.Insert(common.BKTableNameSubscription, sub); err != nil {
blog.Errorf("create subscription failed, error:%s", err.Error())
resp.WriteError(http.StatusInternalServerError, &metadata.RespError{Msg: defErr.Error(common.CCErrEventSubscribeInsertFailed)})
return
}
// save to subscribeform in cache
for _, event := range events {
if err := s.cache.SAdd(types.EventSubscriberCacheKey(ownerID, event), sub.SubscriptionID).Err(); err != nil {
blog.Errorf("create subscription failed, error:%s", err.Error())
resp.WriteError(http.StatusInternalServerError, &metadata.RespError{Msg: defErr.Error(common.CCErrEventSubscribeInsertFailed)})
return
}
}
mesg, _ := json.Marshal(&sub)
s.cache.Publish(types.EventCacheProcessChannel, "create"+string(mesg))
s.cache.Del(types.EventCacheDistCallBackCountPrefix + fmt.Sprint(sub.SubscriptionID))
}
resp.WriteEntity(metadata.RspSubscriptionCreate{
BaseResp: metadata.SuccessBaseResp,
Data: struct {
SubscriptionID int64 `json:"subscription_id"`
}{
SubscriptionID: sub.SubscriptionID,
},
})
}
func (s *Service) UnSubscribe(req *restful.Request, resp *restful.Response) {
pheader := req.Request.Header
defErr := s.CCErr.CreateDefaultCCErrorIf(util.GetLanguage(pheader))
ownerID := util.GetOwnerID(pheader)
id, err := strconv.ParseInt(req.PathParameter("subscribeID"), 10, 64)
if nil != err {
resp.WriteError(http.StatusBadRequest, &metadata.RespError{Msg: defErr.Error(common.CCErrCommJSONUnmarshalFailed)})
return
}
// query old Subscription
sub := metadata.Subscription{}
condiction := util.NewMapBuilder(common.BKSubscriptionIDField, id, common.BKOwnerIDField, ownerID).Build()
if err := s.db.GetOneByCondition(common.BKTableNameSubscription, nil, condiction, &sub); err != nil {
blog.Errorf("fail to get subscription by id %v, error information is %v", id, err)
resp.WriteError(http.StatusInternalServerError, &metadata.RespError{Msg: defErr.Error(common.CCErrEventSubscribeDeleteFailed)})
return
}
// execute delete command
if delerr := s.db.DelByCondition(common.BKTableNameSubscription, condiction); nil != delerr {
blog.Errorf("fail to delete subscription by id %v, error information is %v", id, delerr)
resp.WriteError(http.StatusInternalServerError, &metadata.RespError{Msg: defErr.Error(common.CCErrEventSubscribeDeleteFailed)})
}
subID := fmt.Sprint(id)
eventTypes := strings.Split(sub.SubscriptionForm, ",")
for _, eventType := range eventTypes {
eventType = strings.TrimSpace(eventType)
if err := s.cache.SRem(types.EventSubscriberCacheKey(ownerID, eventType), subID).Err(); err != nil {
blog.Errorf("delete subscription failed, error:%s", err.Error())
resp.WriteError(http.StatusInternalServerError, &metadata.RespError{Msg: defErr.Error(common.CCErrEventSubscribeDeleteFailed)})
}
}
s.cache.Del(types.EventCacheDistIDPrefix+subID,
types.EventCacheDistQueuePrefix+subID,
types.EventCacheDistDonePrefix+subID)
mesg, _ := json.Marshal(&sub)
s.cache.Publish(types.EventCacheProcessChannel, "delete"+string(mesg))
resp.WriteEntity(metadata.NewSuccessResp(nil))
}
func (s *Service) Rebook(req *restful.Request, resp *restful.Response) {
pheader := req.Request.Header
defErr := s.CCErr.CreateDefaultCCErrorIf(util.GetLanguage(pheader))
ownerID := util.GetOwnerID(pheader)
id, err := strconv.ParseInt(req.PathParameter("subscribeID"), 10, 64)
if nil != err {
resp.WriteError(http.StatusBadRequest, &metadata.RespError{Msg: defErr.Error(common.CCErrCommJSONUnmarshalFailed)})
return
}
blog.Info("update subscription %v", id)
sub := &metadata.Subscription{}
if err := json.NewDecoder(req.Request.Body).Decode(&sub); err != nil {
blog.Errorf("update subscription, but decode body failed, err: %v", err)
resp.WriteError(http.StatusBadRequest, &metadata.RespError{Msg: defErr.Error(common.CCErrCommJSONUnmarshalFailed)})
return
}
sub.Operator = util.GetUser(req.Request.Header)
if err = s.rebook(id, ownerID, sub); err != nil {
resp.WriteError(http.StatusBadRequest, &metadata.RespError{Msg: defErr.Error(common.CCErrEventSubscribeUpdateFailed)})
return
}
resp.WriteEntity(metadata.NewSuccessResp(nil))
}
func (s *Service) rebook(id int64, ownerID string, sub *metadata.Subscription) error {
// query old Subscription
oldsub := metadata.Subscription{}
condiction := util.NewMapBuilder(common.BKSubscriptionIDField, id, common.BKOwnerIDField, ownerID).Build()
if err := s.db.GetOneByCondition(common.BKTableNameSubscription, nil, condiction, &oldsub); err != nil {
blog.Errorf("fail to get subscription by id %v, error information is %v", id, err)
return err
}
if oldsub.SubscriptionName != sub.SubscriptionName {
count, err := s.db.GetCntByCondition(common.BKTableNameSubscription, map[string]interface{}{common.BKSubscriptionNameField: sub.SubscriptionName, common.BKOwnerIDField: ownerID})
if err != nil {
blog.Errorf("get subscription count error: %v", err)
return err
}
if count > 0 {
blog.Error("duplicate subscription name")
return err
}
}
sub.SubscriptionID = oldsub.SubscriptionID
if sub.TimeOut <= 0 {
sub.TimeOut = 10
}
now := commontypes.Now()
sub.LastTime = &now
sub.OwnerID = ownerID
sub.SubscriptionForm = strings.Replace(sub.SubscriptionForm, " ", "", 0)
events := strings.Split(sub.SubscriptionForm, ",")
sort.Strings(events)
sub.SubscriptionForm = strings.Join(events, ",")
if updateerr := s.db.UpdateByCondition(common.BKTableNameSubscription, sub, util.NewMapBuilder(common.BKSubscriptionIDField, id, common.BKOwnerIDField, ownerID).Build()); nil != updateerr {
blog.Errorf("fail update subscription by condition, error information is %s", updateerr.Error())
return updateerr
}
eventTypes := strings.Split(sub.SubscriptionForm, ",")
oldeventTypes := strings.Split(oldsub.SubscriptionForm, ",")
subs, plugs := util.CalSliceDiff(oldeventTypes, eventTypes)
for _, eventType := range subs {
eventType = strings.TrimSpace(eventType)
if err := s.cache.SRem(types.EventSubscriberCacheKey(ownerID, eventType), id).Err(); err != nil {
blog.Errorf("delete subscription failed, error:%s", err.Error())
return err
}
}
for _, event := range plugs {
if err := s.cache.SAdd(types.EventSubscriberCacheKey(ownerID, event), sub.SubscriptionID).Err(); err != nil {
blog.Errorf("create subscription failed, error:%s", err.Error())
return err
}
}
mesg, err := json.Marshal(&sub)
if err != nil {
return err
}
return s.cache.Publish(types.EventCacheProcessChannel, "update"+string(mesg)).Err()
}
func (s *Service) Query(req *restful.Request, resp *restful.Response) {
pheader := req.Request.Header
defErr := s.CCErr.CreateDefaultCCErrorIf(util.GetLanguage(pheader))
ownerID := util.GetOwnerID(pheader)
blog.Info("select subscription")
var dat metadata.ParamSubscriptionSearch
if err := json.NewDecoder(req.Request.Body).Decode(&dat); err != nil {
blog.Errorf("search subscription, but decode body failed, err: %v", err)
resp.WriteError(http.StatusBadRequest, &metadata.RespError{Msg: defErr.Error(common.CCErrCommJSONUnmarshalFailed)})
return
}
fields := dat.Fields
condition := dat.Condition
condition = util.SetModOwner(condition, ownerID)
skip := dat.Page.Start
limit := dat.Page.Limit
if limit <= 0 {
limit = common.BKNoLimit
}
sort := dat.Page.Sort
count, err := s.db.GetCntByCondition(common.BKTableNameSubscription, condition)
if err != nil {
blog.Errorf("get host count error, input:%+v error:%v", dat, err)
resp.WriteError(http.StatusBadRequest, &metadata.RespError{Msg: defErr.Error(common.CCErrEventSubscribeSelectFailed)})
return
}
results := []metadata.Subscription{}
blog.Debug("selector:%+v", condition)
if selerr := s.db.GetMutilByCondition(common.BKTableNameSubscription, fields, condition, &results, sort, skip, limit); nil != selerr {
blog.Errorf("select data failed, error information is %s, input:%v", selerr, dat)
resp.WriteError(http.StatusBadRequest, &metadata.RespError{Msg: defErr.Error(common.CCErrEventSubscribeSelectFailed)})
return
}
for index := range results {
val := s.cache.HGetAll(types.EventCacheDistCallBackCountPrefix + fmt.Sprint(results[index].SubscriptionID)).Val()
failue, err := strconv.ParseInt(val["failue"], 10, 64)
if nil != err {
blog.Errorf("get failue value error %s", err.Error())
}
total, err := strconv.ParseInt(val["total"], 10, 64)
if nil != err {
blog.Errorf("get total value error %s", err.Error())
}
results[index].Statistics = &metadata.Statistics{
Total: total,
Failure: failue,
}
}
info := make(map[string]interface{})
info["count"] = count
info["info"] = results
resp.WriteEntity(
metadata.NewSuccessResp(
metadata.RspSubscriptionSearch{
Count: count,
Info: results,
}))
}
func (s *Service) Ping(req *restful.Request, resp *restful.Response) {
pheader := req.Request.Header
defErr := s.CCErr.CreateDefaultCCErrorIf(util.GetLanguage(pheader))
var dat metadata.ParamSubscriptionTestCallback
if err := json.NewDecoder(req.Request.Body).Decode(&dat); err != nil {
blog.Errorf("ping subscription, but decode body failed, err: %v", err)
resp.WriteError(http.StatusBadRequest, &metadata.RespError{Msg: defErr.Error(common.CCErrCommJSONUnmarshalFailed)})
return
}
callbackurl := dat.CallbackUrl
callbackBody := dat.Data
blog.Infof("requesting callback: %v,%s", callbackurl, callbackBody)
callbackreq, _ := http.NewRequest("POST", callbackurl, bytes.NewBufferString(callbackBody))
callbackResp, err := http.DefaultClient.Do(callbackreq)
if err != nil {
blog.Errorf("test distribute error:%v", err)
resp.WriteError(http.StatusBadRequest, &metadata.RespError{Msg: defErr.Error(common.CCErrEventSubscribePingFailed)})
return
}
defer callbackResp.Body.Close()
callbackRespBody, err := ioutil.ReadAll(callbackResp.Body)
if err != nil {
blog.Errorf("test distribute error:%v", err)
}
result := metadata.RspSubscriptionTestCallback{}
result.HttpStatus = callbackResp.StatusCode
result.ResponseBody = string(callbackRespBody)
resp.WriteEntity(metadata.NewSuccessResp(result))
}
func (s *Service) Telnet(req *restful.Request, resp *restful.Response) {
pheader := req.Request.Header
defErr := s.CCErr.CreateDefaultCCErrorIf(util.GetLanguage(pheader))
var dat metadata.ParamSubscriptionTelnet
if err := json.NewDecoder(req.Request.Body).Decode(&dat); err != nil {
blog.Errorf("telnet subscription, but decode body failed, err: %v", err)
resp.WriteError(http.StatusBadRequest, &metadata.RespError{Msg: defErr.Error(common.CCErrCommJSONUnmarshalFailed)})
return
}
callbackurl := dat.CallbackUrl
uri, err := util.GetDailAddress(callbackurl)
if err != nil {
blog.Errorf("telent callback error:%v", err)
resp.WriteError(http.StatusBadRequest, &metadata.RespError{Msg: defErr.Errorf(common.CCErrCommParamsInvalid, "bk_callback_url")})
return
}
blog.Infof("telnet %", uri)
conn, err := net.Dial("tcp", uri)
if err != nil {
blog.Errorf("telent callback error:%v", err)
resp.WriteError(http.StatusBadRequest, &metadata.RespError{Msg: defErr.Error(common.CCErrEventSubscribeTelnetFailed)})
return
}
conn.Close()
resp.WriteEntity(metadata.NewSuccessResp(nil))
}