forked from hoffoo/elasticsearch-dump
-
-
Notifications
You must be signed in to change notification settings - Fork 261
/
main.go
461 lines (376 loc) · 13.1 KB
/
main.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
package main
import (
"bufio"
"github.com/cheggaaa/pb"
log "github.com/cihub/seelog"
goflags "github.com/jessevdk/go-flags"
"github.com/mattn/go-isatty"
"io"
"net/http"
_ "net/http/pprof"
"os"
"runtime"
_ "runtime/pprof"
"strings"
"sync"
"time"
)
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
go func() {
//log.Infof("pprof listen at: http://%s/debug/pprof/", app.httpprof)
mux := http.NewServeMux()
// register pprof handler
mux.HandleFunc("/debug/pprof/", func(w http.ResponseWriter, r *http.Request) {
http.DefaultServeMux.ServeHTTP(w, r)
})
// register metrics handler
//mux.HandleFunc("/debug/vars", app.metricsHandler)
endpoint := http.ListenAndServe("0.0.0.0:6060", mux)
log.Debug("stop pprof server: %v", endpoint)
}()
var err error
c := &Config{}
migrator := Migrator{}
migrator.Config = c
// parse args
_, err = goflags.Parse(c)
if err != nil {
log.Error(err)
return
}
setInitLogging(c.LogLevel)
if len(c.SourceEs) == 0 && len(c.DumpInputFile) == 0 {
log.Error("no input, type --help for more details")
return
}
if len(c.TargetEs) == 0 && len(c.DumpOutFile) == 0 {
log.Error("no output, type --help for more details")
return
}
if c.SourceEs == c.TargetEs && c.SourceIndexNames == c.TargetIndexName {
log.Error("migration output is the same as the output")
return
}
var showBar bool = false
if isatty.IsTerminal(os.Stdout.Fd()) {
showBar = true
} else if isatty.IsCygwinTerminal(os.Stdout.Fd()) {
showBar = true
} else {
showBar = false
}
if c.Sync {
//sync 功能时,只支持一个 index:
if len(c.SourceIndexNames) == 0 || len(c.TargetIndexName) == 0 {
log.Error("migration sync only support source 1 index to 1 target index")
return
}
migrator.SourceESAPI = migrator.ParseEsApi(true, c.SourceEs, c.SourceEsAuthStr, c.SourceProxy, c.Compress)
if migrator.SourceESAPI == nil {
log.Error("can not parse source es api")
return
}
migrator.TargetESAPI = migrator.ParseEsApi(false, c.TargetEs, c.TargetEsAuthStr, c.TargetProxy, false)
if migrator.TargetESAPI == nil {
log.Error("can not parse target es api")
return
}
migrator.SyncBetweenIndex(migrator.SourceESAPI, migrator.TargetESAPI, c)
return
}
//至少输出一次
if c.RepeatOutputTimes < 1 {
c.RepeatOutputTimes = 1
} else {
log.Info("source data will repeat send to target: ", c.RepeatOutputTimes, " times, the document id will be regenerated.")
}
if c.RepeatOutputTimes > 0 {
for i := 0; i < c.RepeatOutputTimes; i++ {
if c.RepeatOutputTimes > 1 {
log.Info("repeat round: ", i+1)
}
// enough of a buffer to hold all the search results across all workers
migrator.DocChan = make(chan map[string]interface{}, c.BufferCount)
//var srcESVersion *ClusterVersion
// create a progressbar and start a docCount
var outputBar *pb.ProgressBar = pb.New(1).Prefix("Output ")
var fetchBar = pb.New(1).Prefix("Scroll")
wg := sync.WaitGroup{}
//dealing with input
if len(c.SourceEs) > 0 {
//dealing with basic auth
migrator.SourceESAPI = migrator.ParseEsApi(true, c.SourceEs, c.SourceEsAuthStr,
migrator.Config.SourceProxy, c.Compress)
if migrator.SourceESAPI == nil {
log.Error("can not parse source es api")
return
}
if c.ScrollSliceSize < 1 {
c.ScrollSliceSize = 1
}
totalSize := 0
finishedSlice := 0
for slice := 0; slice < c.ScrollSliceSize; slice++ {
scroll, err := migrator.SourceESAPI.NewScroll(c.SourceIndexNames, c.ScrollTime, c.DocBufferCount, c.Query,
c.SortField, slice, c.ScrollSliceSize, c.Fields)
if err != nil {
log.Error(err)
return
}
totalSize += scroll.GetHitsTotal()
if scroll.GetDocs() != nil {
if scroll.GetHitsTotal() == 0 {
log.Error("can't find documents from source.")
return
}
go func() {
wg.Add(1)
//process input
// start scroll
scroll.ProcessScrollResult(&migrator, fetchBar)
// loop scrolling until done
for scroll.Next(&migrator, fetchBar) == false {
}
if showBar {
fetchBar.Finish()
}
// finished, close doc chan and wait for goroutines to be done
wg.Done()
finishedSlice++
//clean up final results
if finishedSlice == c.ScrollSliceSize {
log.Debug("closing doc chan")
close(migrator.DocChan)
}
}()
}
}
if totalSize > 0 {
fetchBar.Total = int64(totalSize)
outputBar.Total = int64(totalSize)
}
} else if len(c.DumpInputFile) > 0 {
//read file stream
wg.Add(1)
f, err := os.Open(c.DumpInputFile)
if err != nil {
log.Error(err)
return
}
//get file lines
lineCount := 0
defer f.Close()
r := bufio.NewReader(f)
for {
_, err := r.ReadString('\n')
if io.EOF == err || nil != err {
break
}
lineCount += 1
}
log.Trace("file line,", lineCount)
fetchBar := pb.New(lineCount).Prefix("Read")
outputBar = pb.New(lineCount).Prefix("Output ")
f.Close()
go migrator.NewFileReadWorker(fetchBar, &wg)
}
var pool *pb.Pool
if showBar {
// start pool
pool, err = pb.StartPool(fetchBar, outputBar)
if err != nil {
panic(err)
}
}
//dealing with output
if len(c.TargetEs) > 0 {
if len(c.TargetEsAuthStr) > 0 && strings.Contains(c.TargetEsAuthStr, ":") {
authArray := strings.Split(c.TargetEsAuthStr, ":")
auth := Auth{User: authArray[0], Pass: authArray[1]}
migrator.TargetAuth = &auth
}
//get target es api
migrator.TargetESAPI = migrator.ParseEsApi(false, c.TargetEs, c.TargetEsAuthStr,
migrator.Config.TargetProxy, false)
if migrator.TargetESAPI == nil {
log.Error("can not parse target es api")
return
}
log.Debug("start process with mappings")
if c.CopyIndexMappings &&
migrator.TargetESAPI.ClusterVersion().Version.Number[0] != migrator.SourceESAPI.ClusterVersion().Version.Number[0] {
log.Error(migrator.SourceESAPI.ClusterVersion().Version, "=>",
migrator.TargetESAPI.ClusterVersion().Version,
",cross-big-version mapping migration not available, please update mapping manually :(")
return
}
// wait for cluster state to be okay before moving
idleDuration := 3 * time.Second
timer := time.NewTimer(idleDuration)
defer timer.Stop()
for {
timer.Reset(idleDuration)
if len(c.SourceEs) > 0 {
if status, ready := migrator.ClusterReady(migrator.SourceESAPI); !ready {
log.Infof("%s at %s is %s, delaying migration ", status.Name, c.SourceEs, status.Status)
<-timer.C
continue
}
}
if len(c.TargetEs) > 0 {
if status, ready := migrator.ClusterReady(migrator.TargetESAPI); !ready {
log.Infof("%s at %s is %s, delaying migration ", status.Name, c.TargetEs, status.Status)
<-timer.C
continue
}
}
break
}
if len(c.SourceEs) > 0 {
// get all indexes from source
indexNames, indexCount, sourceIndexMappings, err := migrator.SourceESAPI.GetIndexMappings(c.CopyAllIndexes, c.SourceIndexNames)
if err != nil {
log.Error(err)
return
}
sourceIndexRefreshSettings := map[string]interface{}{}
log.Debugf("indexCount: %d", indexCount)
if indexCount > 0 {
//override indexnames to be copy
c.SourceIndexNames = indexNames
// copy index settings if user asked
if c.CopyIndexSettings || c.ShardsCount > 0 {
log.Info("start settings/mappings migration..")
//get source index settings
var sourceIndexSettings *Indexes
sourceIndexSettings, err := migrator.SourceESAPI.GetIndexSettings(c.SourceIndexNames)
log.Debug("source index settings:", sourceIndexSettings)
if err != nil {
log.Error(err)
return
}
//get target index settings
targetIndexSettings, err := migrator.TargetESAPI.GetIndexSettings(c.TargetIndexName)
if err != nil {
//ignore target es settings error
log.Debug(err)
}
log.Debug("target IndexSettings", targetIndexSettings)
//if there is only one index and we specify the dest indexname
if c.SourceIndexNames != c.TargetIndexName && (len(c.TargetIndexName) > 0) && indexCount == 1 {
log.Debugf("only one index,so we can rewrite indexname, src:%v, dest:%v ,indexCount:%d", c.SourceIndexNames, c.TargetIndexName, indexCount)
(*sourceIndexSettings)[c.TargetIndexName] = (*sourceIndexSettings)[c.SourceIndexNames]
delete(*sourceIndexSettings, c.SourceIndexNames)
log.Debug(sourceIndexSettings)
}
// dealing with indices settings
for name, idx := range *sourceIndexSettings {
log.Debug("dealing with index,name:", name, ",settings:", idx)
tempIndexSettings := getEmptyIndexSettings()
targetIndexExist := false
//if target index settings is exist and we don't copy settings, we use target settings
if targetIndexSettings != nil {
//if target es have this index and we dont copy index settings
if val, ok := (*targetIndexSettings)[name]; ok {
targetIndexExist = true
tempIndexSettings = val.(map[string]interface{})
}
if c.RecreateIndex {
migrator.TargetESAPI.DeleteIndex(name)
targetIndexExist = false
}
}
//copy index settings
if c.CopyIndexSettings {
tempIndexSettings = ((*sourceIndexSettings)[name]).(map[string]interface{})
}
//check map elements
if _, ok := tempIndexSettings["settings"]; !ok {
tempIndexSettings["settings"] = map[string]interface{}{}
}
if _, ok := tempIndexSettings["settings"].(map[string]interface{})["index"]; !ok {
tempIndexSettings["settings"].(map[string]interface{})["index"] = map[string]interface{}{}
}
sourceIndexRefreshSettings[name] = ((*sourceIndexSettings)[name].(map[string]interface{}))["settings"].(map[string]interface{})["index"].(map[string]interface{})["refresh_interval"]
//set refresh_interval
tempIndexSettings["settings"].(map[string]interface{})["index"].(map[string]interface{})["refresh_interval"] = -1
tempIndexSettings["settings"].(map[string]interface{})["index"].(map[string]interface{})["number_of_replicas"] = 0
//clean up settings
delete(tempIndexSettings["settings"].(map[string]interface{})["index"].(map[string]interface{}), "number_of_shards")
//copy indexsettings and mappings
if targetIndexExist {
log.Debug("update index with settings,", name, tempIndexSettings)
//override shard settings
if c.ShardsCount > 0 {
tempIndexSettings["settings"].(map[string]interface{})["index"].(map[string]interface{})["number_of_shards"] = c.ShardsCount
}
err := migrator.TargetESAPI.UpdateIndexSettings(name, tempIndexSettings)
if err != nil {
log.Error(err)
}
} else {
//override shard settings
if c.ShardsCount > 0 {
tempIndexSettings["settings"].(map[string]interface{})["index"].(map[string]interface{})["number_of_shards"] = c.ShardsCount
}
log.Debug("create index with settings,", name, tempIndexSettings)
err := migrator.TargetESAPI.CreateIndex(name, tempIndexSettings)
if err != nil {
log.Error(err)
}
}
}
if c.CopyIndexMappings {
//if there is only one index and we specify the dest indexname
if c.SourceIndexNames != c.TargetIndexName && (len(c.TargetIndexName) > 0) && indexCount == 1 {
log.Debugf("only one index,so we can rewrite indexname, src:%v, dest:%v ,indexCount:%d", c.SourceIndexNames, c.TargetIndexName, indexCount)
(*sourceIndexMappings)[c.TargetIndexName] = (*sourceIndexMappings)[c.SourceIndexNames]
delete(*sourceIndexMappings, c.SourceIndexNames)
log.Debug(sourceIndexMappings)
}
for name, mapping := range *sourceIndexMappings {
err := migrator.TargetESAPI.UpdateIndexMapping(name, mapping.(map[string]interface{})["mappings"].(map[string]interface{}))
if err != nil {
log.Error(err)
}
}
}
log.Info("settings/mappings migration finished.")
}
} else {
log.Error("index not exists,", c.SourceIndexNames)
return
}
defer migrator.recoveryIndexSettings(sourceIndexRefreshSettings)
} else if len(c.DumpInputFile) > 0 {
//check shard settings
//TODO support shard config
}
}
log.Info("start data migration..")
//start es bulk thread
if len(c.TargetEs) > 0 {
log.Debug("start es bulk workers")
outputBar.Prefix("Bulk")
var docCount int
wg.Add(c.Workers)
for i := 0; i < c.Workers; i++ {
go migrator.NewBulkWorker(&docCount, outputBar, &wg)
}
} else if len(c.DumpOutFile) > 0 {
// start file write
outputBar.Prefix("Write")
wg.Add(1)
go migrator.NewFileDumpWorker(outputBar, &wg)
}
wg.Wait()
if showBar {
outputBar.Finish()
// close pool
pool.Stop()
}
}
}
log.Info("data migration finished.")
}