forked from elasticsearch-dump/elasticsearch-dump
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathelasticdump.js
185 lines (156 loc) · 5.27 KB
/
elasticdump.js
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
const http = require('http')
const https = require('https')
const { EventEmitter } = require('events')
const url = require('url')
const vm = require('vm')
const { promisify } = require('util')
const ioHelper = require('./lib/ioHelper')
const getParams = query => {
if (!query) {
return {}
}
return (/^[?#]/.test(query) ? query.slice(1) : query)
.split('&')
.reduce((params, param) => {
let [key, value] = param.split('=')
params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : ''
return params
}, {})
}
class elasticdump extends EventEmitter {
constructor (input, output, options) {
super()
this.input = input
this.output = output
this.options = options
this.modifiers = []
if (output !== '$' && (this.options.toLog === null || this.options.toLog === undefined)) {
this.options.toLog = true
}
this.validationErrors = this.validateOptions()
if (options.maxSockets) {
this.log('globally setting maxSockets=' + options.maxSockets)
http.globalAgent.maxSockets = options.maxSockets
https.globalAgent.maxSockets = options.maxSockets
}
ioHelper(this, 'input')
ioHelper(this, 'output')
if (this.options.type === 'data' && this.options.transform) {
if (!(this.options.transform instanceof Array)) {
this.options.transform = [this.options.transform]
}
this.modifiers = this.options.transform.map(transform => {
if (transform[0] === '@') {
return doc => {
const parsed = url.parse(transform.slice(1))
return require(parsed.pathname)(doc, getParams(parsed.query))
}
} else {
const modificationScriptText = '(function(doc) { ' + transform + ' })'
return new vm.Script(modificationScriptText).runInThisContext()
}
})
}
}
log (message) {
if (typeof this.options.logger === 'function') {
this.options.logger(message)
} else if (this.options.toLog === true) {
this.emit('log', message)
}
}
validateOptions () {
const self = this
const validationErrors = []
const required = ['input']
required.forEach(v => {
if (!self.options[v]) {
validationErrors.push('`' + v + '` is a required input')
}
})
return validationErrors
}
dump (callback, continuing, limit, offset, totalWrites) {
const self = this
if (self.validationErrors.length > 0) {
self.emit('error', { errors: self.validationErrors })
callback(new Error('There was an error starting this dump'))
return
}
if (!limit) { limit = self.options.limit }
if (!offset) { offset = self.options.offset }
if (!totalWrites) { totalWrites = 0 }
if (continuing !== true) {
self.log('starting dump')
if (self.options.offset) {
self.log('Warning: offsetting ' + self.options.offset + ' rows.')
self.log(' * Using an offset doesn\'t guarantee that the offset rows have already been written, please refer to the HELP text.')
}
if (self.modifiers.length) {
self.log('Will modify documents using these scripts: ' + self.options.transform)
}
}
this._loop(limit, offset, totalWrites)
.then((totalWrites) => {
if (typeof callback === 'function') { return callback(null, totalWrites) }
}, (error) => {
if (typeof callback === 'function') { return callback(error/*, totalWrites */) }
})
}
async _loop (limit, offset, totalWrites) {
const self = this
const get = promisify(this.input.get).bind(this.input)
const set = promisify(this.output.set).bind(this.output)
const ignoreErrors = self.options['ignore-errors'] === true || self.options['ignore-errors'] === 'true'
let overlappedIoPromise
let overlappedIoPromiseChain = []
for (;;) {
let data
try {
data = await get(limit, offset)
} catch (err) {
self.emit('error', err)
if (!ignoreErrors) {
self.log('Total Writes: ' + totalWrites)
self.log('dump ended with error (get phase) => ' + String(err))
throw err
}
}
self.log('got ' + data.length + ' objects from source ' + self.inputType + ' (offset: ' + offset + ')')
if (self.modifiers.length) {
for (let i = 0; i < data.length; i++) {
self.modifiers.forEach(modifier => {
modifier(data[i])
})
}
}
overlappedIoPromise = set(data, limit, offset)
.then(writes => {
totalWrites += writes
if (data.length > 0) {
self.log('sent ' + data.length + ' objects to destination ' + self.outputType + ', wrote ' + writes)
}
})
overlappedIoPromiseChain.push(overlappedIoPromise)
if (data.length === 0) {
break
}
offset += data.length
}
return Promise.all(overlappedIoPromiseChain)
.then(() => {
self.log('Total Writes: ' + totalWrites)
self.log('dump complete')
return totalWrites
})
.catch(err => {
self.emit('error', err)
if (!ignoreErrors) {
self.log('Total Writes: ' + totalWrites)
self.log('dump ended with error (set phase) => ' + String(err))
throw err
}
})
}
}
module.exports = elasticdump