-
Notifications
You must be signed in to change notification settings - Fork 800
/
Copy pathriver.go
339 lines (268 loc) · 7.44 KB
/
river.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
package river
import (
"context"
"fmt"
"regexp"
"strings"
"sync"
"github.com/juju/errors"
"github.com/siddontang/go-log/log"
"github.com/siddontang/go-mysql-elasticsearch/elastic"
"github.com/siddontang/go-mysql/canal"
)
// ErrRuleNotExist is the error if rule is not defined.
var ErrRuleNotExist = errors.New("rule is not exist")
// River is a pluggable service within Elasticsearch pulling data then indexing it into Elasticsearch.
// We use this definition here too, although it may not run within Elasticsearch.
// Maybe later I can implement an actual river in Elasticsearch, but I must learn java. :-)
type River struct {
c *Config
canal *canal.Canal
rules map[string]*Rule
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
es *elastic.Client
master *masterInfo
syncCh chan interface{}
}
// NewRiver creates the River from config
func NewRiver(c *Config) (*River, error) {
r := new(River)
r.c = c
r.rules = make(map[string]*Rule)
r.syncCh = make(chan interface{}, 4096)
r.ctx, r.cancel = context.WithCancel(context.Background())
var err error
if r.master, err = loadMasterInfo(c.DataDir); err != nil {
return nil, errors.Trace(err)
}
if err = r.newCanal(); err != nil {
return nil, errors.Trace(err)
}
if err = r.prepareRule(); err != nil {
return nil, errors.Trace(err)
}
if err = r.prepareCanal(); err != nil {
return nil, errors.Trace(err)
}
// We must use binlog full row image
if err = r.canal.CheckBinlogRowImage("FULL"); err != nil {
return nil, errors.Trace(err)
}
cfg := new(elastic.ClientConfig)
cfg.Addr = r.c.ESAddr
cfg.User = r.c.ESUser
cfg.Password = r.c.ESPassword
cfg.HTTPS = r.c.ESHttps
r.es = elastic.NewClient(cfg)
go InitStatus(r.c.StatAddr, r.c.StatPath)
return r, nil
}
func (r *River) newCanal() error {
cfg := canal.NewDefaultConfig()
cfg.Addr = r.c.MyAddr
cfg.User = r.c.MyUser
cfg.Password = r.c.MyPassword
cfg.Charset = r.c.MyCharset
cfg.Flavor = r.c.Flavor
cfg.ServerID = r.c.ServerID
cfg.Dump.ExecutionPath = r.c.DumpExec
cfg.Dump.DiscardErr = false
cfg.Dump.SkipMasterData = r.c.SkipMasterData
for _, s := range r.c.Sources {
for _, t := range s.Tables {
cfg.IncludeTableRegex = append(cfg.IncludeTableRegex, s.Schema+"\\."+t)
}
}
var err error
r.canal, err = canal.NewCanal(cfg)
return errors.Trace(err)
}
func (r *River) prepareCanal() error {
var db string
dbs := map[string]struct{}{}
tables := make([]string, 0, len(r.rules))
for _, rule := range r.rules {
db = rule.Schema
dbs[rule.Schema] = struct{}{}
tables = append(tables, rule.Table)
}
if len(dbs) == 1 {
// one db, we can shrink using table
r.canal.AddDumpTables(db, tables...)
} else {
// many dbs, can only assign databases to dump
keys := make([]string, 0, len(dbs))
for key := range dbs {
keys = append(keys, key)
}
r.canal.AddDumpDatabases(keys...)
}
r.canal.SetEventHandler(&eventHandler{r})
return nil
}
func (r *River) newRule(schema, table string) error {
key := ruleKey(schema, table)
if _, ok := r.rules[key]; ok {
return errors.Errorf("duplicate source %s, %s defined in config", schema, table)
}
r.rules[key] = newDefaultRule(schema, table)
return nil
}
func (r *River) updateRule(schema, table string) error {
rule, ok := r.rules[ruleKey(schema, table)]
if !ok {
return ErrRuleNotExist
}
tableInfo, err := r.canal.GetTable(schema, table)
if err != nil {
return errors.Trace(err)
}
rule.TableInfo = tableInfo
return nil
}
func (r *River) parseSource() (map[string][]string, error) {
wildTables := make(map[string][]string, len(r.c.Sources))
// first, check sources
for _, s := range r.c.Sources {
if !isValidTables(s.Tables) {
return nil, errors.Errorf("wildcard * is not allowed for multiple tables")
}
for _, table := range s.Tables {
if len(s.Schema) == 0 {
return nil, errors.Errorf("empty schema not allowed for source")
}
if regexp.QuoteMeta(table) != table {
if _, ok := wildTables[ruleKey(s.Schema, table)]; ok {
return nil, errors.Errorf("duplicate wildcard table defined for %s.%s", s.Schema, table)
}
tables := []string{}
sql := fmt.Sprintf(`SELECT table_name FROM information_schema.tables WHERE
table_name RLIKE "%s" AND table_schema = "%s";`, buildTable(table), s.Schema)
res, err := r.canal.Execute(sql)
if err != nil {
return nil, errors.Trace(err)
}
for i := 0; i < res.Resultset.RowNumber(); i++ {
f, _ := res.GetString(i, 0)
err := r.newRule(s.Schema, f)
if err != nil {
return nil, errors.Trace(err)
}
tables = append(tables, f)
}
wildTables[ruleKey(s.Schema, table)] = tables
} else {
err := r.newRule(s.Schema, table)
if err != nil {
return nil, errors.Trace(err)
}
}
}
}
if len(r.rules) == 0 {
return nil, errors.Errorf("no source data defined")
}
return wildTables, nil
}
func (r *River) prepareRule() error {
wildtables, err := r.parseSource()
if err != nil {
return errors.Trace(err)
}
if r.c.Rules != nil {
// then, set custom mapping rule
for _, rule := range r.c.Rules {
if len(rule.Schema) == 0 {
return errors.Errorf("empty schema not allowed for rule")
}
if regexp.QuoteMeta(rule.Table) != rule.Table {
//wildcard table
tables, ok := wildtables[ruleKey(rule.Schema, rule.Table)]
if !ok {
return errors.Errorf("wildcard table for %s.%s is not defined in source", rule.Schema, rule.Table)
}
if len(rule.Index) == 0 {
return errors.Errorf("wildcard table rule %s.%s must have a index, can not empty", rule.Schema, rule.Table)
}
rule.prepare()
for _, table := range tables {
rr := r.rules[ruleKey(rule.Schema, table)]
rr.Index = rule.Index
rr.Type = rule.Type
rr.Parent = rule.Parent
rr.ID = rule.ID
rr.FieldMapping = rule.FieldMapping
}
} else {
key := ruleKey(rule.Schema, rule.Table)
if _, ok := r.rules[key]; !ok {
return errors.Errorf("rule %s, %s not defined in source", rule.Schema, rule.Table)
}
rule.prepare()
r.rules[key] = rule
}
}
}
rules := make(map[string]*Rule)
for key, rule := range r.rules {
if rule.TableInfo, err = r.canal.GetTable(rule.Schema, rule.Table); err != nil {
return errors.Trace(err)
}
if len(rule.TableInfo.PKColumns) == 0 {
if !r.c.SkipNoPkTable {
return errors.Errorf("%s.%s must have a PK for a column", rule.Schema, rule.Table)
}
log.Errorf("ignored table without a primary key: %s\n", rule.TableInfo.Name)
} else {
rules[key] = rule
}
}
r.rules = rules
return nil
}
func ruleKey(schema string, table string) string {
return strings.ToLower(fmt.Sprintf("%s:%s", schema, table))
}
// Run syncs the data from MySQL and inserts to ES.
func (r *River) Run() error {
r.wg.Add(1)
canalSyncState.Set(float64(1))
go r.syncLoop()
pos := r.master.Position()
if err := r.canal.RunFrom(pos); err != nil {
log.Errorf("start canal err %v", err)
canalSyncState.Set(0)
return errors.Trace(err)
}
return nil
}
// Ctx returns the internal context for outside use.
func (r *River) Ctx() context.Context {
return r.ctx
}
// Close closes the River
func (r *River) Close() {
log.Infof("closing river")
r.cancel()
r.canal.Close()
r.master.Close()
r.wg.Wait()
}
func isValidTables(tables []string) bool {
if len(tables) > 1 {
for _, table := range tables {
if table == "*" {
return false
}
}
}
return true
}
func buildTable(table string) string {
if table == "*" {
return "." + table
}
return table
}