-
Notifications
You must be signed in to change notification settings - Fork 29
/
push_dbev_consumer.go
329 lines (286 loc) · 9.35 KB
/
push_dbev_consumer.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
// Copyright 2017 Vector Creations 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.
//
//
// Modifications copyright (C) 2020 Finogeeks Co., Ltd
package consumers
import (
"bufio"
"context"
"fmt"
"io"
"os"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/finogeeks/ligase/common"
"github.com/finogeeks/ligase/common/config"
"github.com/finogeeks/ligase/model/dbtypes"
log "github.com/finogeeks/ligase/skunkworks/log"
"github.com/finogeeks/ligase/skunkworks/monitor/go-client/monitor"
"github.com/finogeeks/ligase/storage/model"
)
func init() {
Register(dbtypes.CATEGORY_PUSH_DB_EVENT, NewPushDBEVConsumer)
}
type PushDBEVConsumer struct {
db model.PushAPIDatabase
//msgChan []chan *dbtypes.DBEvent
msgChan []chan common.ContextMsg
monState []*DBMonItem
path string
fileName string
recoverName string
mutex *sync.Mutex
recvMutex *sync.Mutex
ticker *time.Timer
cfg *config.Dendrite
}
func (s *PushDBEVConsumer) startWorker(msgChan chan common.ContextMsg) error {
var res error
for msg := range msgChan {
ctx := msg.Ctx
output := msg.Msg.(*dbtypes.DBEvent)
start := time.Now().UnixNano() / 1000000
key := output.Key
data := output.PushDBEvents
switch key {
case dbtypes.PusherDeleteKey:
res = s.onPusherDelete(ctx, data.PusherDelete)
case dbtypes.PusherDeleteByKeyKey:
res = s.onPusherDeleteByKey(ctx, data.PusherDeleteByKey)
case dbtypes.PusherDeleteByKeyOnlyKey:
res = s.onPusherDeleteByKeyOnly(ctx, data.PusherDeleteByKeyOnly)
case dbtypes.PusherInsertKey:
res = s.onPusherInsert(ctx, data.PusherInsert)
case dbtypes.PushRuleUpsertKey:
res = s.onPushRuleInsert(ctx, data.PushRuleInert)
case dbtypes.PushRuleDeleteKey:
res = s.onPushRuleDelete(ctx, data.PushRuleDelete)
case dbtypes.PushRuleEnableUpsetKey:
res = s.onPushRuleEnableInsert(ctx, data.PushRuleEnableInsert)
default:
res = nil
log.Infow("push db event: ignoring unknown output type", log.KeysAndValues{"key", key})
}
item := s.monState[key]
if res == nil {
atomic.AddInt32(&item.process, 1)
} else {
atomic.AddInt32(&item.fail, 1)
if s.IsDump(res.Error()) {
bytes, _ := json.Marshal(output)
log.Warnf("write push db event to db warn %v key: %s event:%s", res, dbtypes.PushDBEventKeyToStr(key), string(bytes))
} else {
log.Error("write push db event to db error %v key: %s", res, dbtypes.PushDBEventKeyToStr(key))
}
}
if res != nil {
if s.cfg.RetryFlushDB && !s.IsDump(res.Error()) {
s.processError(output)
}
}
now := time.Now().UnixNano() / 1000000
log.Infof("PushDBEVConsumer process %s takes %d", dbtypes.PushDBEventKeyToStr(key), now-start)
}
return res
}
func (s *PushDBEVConsumer) IsDump(errMsg string) bool {
return strings.Contains(errMsg, "duplicate key value")
}
func NewPushDBEVConsumer() ConsumerInterface {
s := new(PushDBEVConsumer)
//init mon
s.monState = make([]*DBMonItem, dbtypes.PushMaxKey)
for i := int64(0); i < dbtypes.PushMaxKey; i++ {
if dbtypes.DBEventKeyToTableStr(dbtypes.CATEGORY_PUSH_DB_EVENT, i) != "unknown" {
item := new(DBMonItem)
item.tablenamse = dbtypes.DBEventKeyToTableStr(dbtypes.CATEGORY_PUSH_DB_EVENT, i)
item.method = dbtypes.DBEventKeyToStr(dbtypes.CATEGORY_PUSH_DB_EVENT, i)
s.monState[i] = item
}
}
//init worker
s.msgChan = make([]chan common.ContextMsg, 3)
for i := uint64(0); i < 3; i++ {
s.msgChan[i] = make(chan common.ContextMsg, 4096)
}
s.mutex = new(sync.Mutex)
s.recvMutex = new(sync.Mutex)
s.fileName = "pushDbEvErrs.txt"
s.recoverName = "pushDbEvRecover.txt"
s.ticker = time.NewTimer(600)
return s
}
func (s *PushDBEVConsumer) Prepare(cfg *config.Dendrite) {
db, err := common.GetDBInstance("pushapi", cfg)
if err != nil {
log.Panicf("failed to connect to push db %v", err)
}
s.db = db.(model.PushAPIDatabase)
s.path = cfg.RecoverPath
s.cfg = cfg
}
func (s *PushDBEVConsumer) Start() {
for i := uint64(0); i < 3; i++ {
go s.startWorker(s.msgChan[i])
}
go s.startRecover()
}
func (s *PushDBEVConsumer) startRecover() {
for {
select {
case <-s.ticker.C:
s.ticker.Reset(time.Second * 600) //10分钟一次
func() {
span, ctx := common.StartSobSomSpan(context.Background(), "PushDBEVConsumer.startRecover")
defer span.Finish()
s.recover(ctx)
}()
}
}
}
func (s *PushDBEVConsumer) OnMessage(ctx context.Context, dbEv *dbtypes.DBEvent) error {
chanID := 0
switch dbEv.Key {
case dbtypes.PusherDeleteKey, dbtypes.PusherDeleteByKeyKey, dbtypes.PusherDeleteByKeyOnlyKey, dbtypes.PusherInsertKey:
chanID = 0
case dbtypes.PushRuleUpsertKey, dbtypes.PushRuleDeleteKey:
chanID = 1
case dbtypes.PushRuleEnableUpsetKey:
chanID = 2
default:
log.Infow("push db event: ignoring unknown output type", log.KeysAndValues{"key", dbEv.Key})
return nil
}
s.msgChan[chanID] <- common.ContextMsg{Ctx: ctx, Msg: dbEv}
return nil
}
func (s *PushDBEVConsumer) onPusherDelete(
ctx context.Context, msg *dbtypes.PusherDelete,
) error {
return s.db.OnDeleteUserPushers(ctx, msg.UserID, msg.AppID, msg.PushKey)
}
func (s *PushDBEVConsumer) onPusherDeleteByKey(
ctx context.Context, msg *dbtypes.PusherDeleteByKey,
) error {
return s.db.OnDeletePushersByKey(ctx, msg.AppID, msg.PushKey)
}
func (s *PushDBEVConsumer) onPusherDeleteByKeyOnly(
ctx context.Context, msg *dbtypes.PusherDeleteByKeyOnly,
) error {
return s.db.OnDeletePushersByKeyOnly(ctx, msg.PushKey)
}
func (s *PushDBEVConsumer) onPusherInsert(
ctx context.Context, msg *dbtypes.PusherInsert,
) error {
return s.db.OnAddPusher(ctx, msg.UserID, msg.ProfileTag, msg.Kind, msg.AppID, msg.AppDisplayName, msg.DeviceDisplayName, msg.PushKey, msg.Lang, msg.Data, msg.DeviceID)
}
func (s *PushDBEVConsumer) onPushRuleInsert(
ctx context.Context, msg *dbtypes.PushRuleInert,
) error {
return s.db.OnAddPushRule(ctx, msg.UserID, msg.RuleID, msg.PriorityClass, msg.Priority, msg.Conditions, msg.Actions)
}
func (s *PushDBEVConsumer) onPushRuleDelete(
ctx context.Context, msg *dbtypes.PushRuleDelete,
) error {
return s.db.OnDeletePushRule(ctx, msg.UserID, msg.RuleID)
}
func (s *PushDBEVConsumer) onPushRuleEnableInsert(
ctx context.Context, msg *dbtypes.PushRuleEnableInsert,
) error {
return s.db.OnAddPushRuleEnable(ctx, msg.UserID, msg.RuleID, msg.Enabled)
}
func (s *PushDBEVConsumer) Report(mon monitor.LabeledGauge) {
for i := int64(0); i < dbtypes.PushMaxKey; i++ {
item := s.monState[i]
if item != nil {
mon.WithLabelValues("monolith", item.tablenamse, item.method, "process").Set(float64(atomic.LoadInt32(&item.process)))
mon.WithLabelValues("monolith", item.tablenamse, item.method, "fail").Set(float64(atomic.LoadInt32(&item.fail)))
}
}
}
func (s *PushDBEVConsumer) processError(dbEv *dbtypes.DBEvent) {
s.mutex.Lock()
defer s.mutex.Unlock()
filePath := fmt.Sprintf("%s/%s", s.path, s.fileName)
if fileObj, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644); err == nil {
defer fileObj.Close()
writeObj := bufio.NewWriterSize(fileObj, 4096)
bytes, err := json.Marshal(dbEv)
if err != nil {
log.Errorf("PushDBEVConsumer.processError marshal error %v", err)
return
}
log.Infof("PushDBEVConsumer.processError process data %s", string(bytes))
if _, err := writeObj.WriteString(string(bytes) + "\n"); err == nil {
if err := writeObj.Flush(); err != nil {
log.Errorf("PushDBEVConsumer.processError Flush err %v", err)
}
} else {
log.Errorf("PushDBEVConsumer.processError WriteString err %v", err)
}
} else {
log.Errorf("PushDBEVConsumer.processError open file %s err %v", filePath, err)
}
}
func (s *PushDBEVConsumer) renameRecoverFile() bool {
s.mutex.Lock()
defer s.mutex.Unlock()
filePath := fmt.Sprintf("%s/%s", s.path, s.fileName)
newPath := fmt.Sprintf("%s/%s", s.path, s.recoverName)
if exists, _ := common.PathExists(filePath); exists {
err := os.Rename(filePath, newPath)
if err == nil {
return true
}
log.Errorf("PushDBEVConsumer.renameRecoverFile err %v", err)
}
return false
}
func (s *PushDBEVConsumer) recover(ctx context.Context) {
log.Infof("PushDBEVConsumer start recover")
s.recvMutex.Lock()
defer s.recvMutex.Unlock()
if s.renameRecoverFile() {
newPath := fmt.Sprintf("%s/%s", s.path, s.recoverName)
f, err := os.Open(newPath)
if err != nil {
log.Errorf("PushDBEVConsumer.recover open file %s err %v", newPath, err)
return
}
rd := bufio.NewReader(f)
for {
line, err := rd.ReadString('\n') //以'\n'为结束符读入一行
if err != nil || io.EOF == err {
break
}
log.Infof("PushDBEVConsumer.processError recover data %s", line)
var dbEv dbtypes.DBEvent
err = json.Unmarshal([]byte(line), &dbEv)
if err != nil {
log.Errorf("PushDBEVConsumer.recover unmarshal err %v", err)
continue
}
s.OnMessage(ctx, &dbEv)
}
f.Close()
err = os.Remove(newPath)
if err != nil {
log.Errorf("PushDBEVConsumer.recover remove file %s err %v", newPath, err)
}
}
log.Infof("PushDBEVConsumer finished recover")
}