forked from vanthome/winston-elasticsearch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bulk_writer.js
179 lines (167 loc) · 4.87 KB
/
bulk_writer.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
const fs = require('fs');
const path = require('path');
const Promise = require('promise');
const debug = require('debug')('winston:elasticsearch');
const retry = require('retry');
const BulkWriter = function BulkWriter(client, options) {
this.client = client;
this.options = options;
this.interval = options.interval || 5000;
this.waitForActiveShards = options.waitForActiveShards;
this.pipeline = options.pipeline;
this.bulk = []; // bulk to be flushed
this.running = false;
this.timer = false;
debug('created', this);
};
BulkWriter.prototype.start = function start() {
this.checkEsConnection();
this.running = true;
this.tick();
debug('started');
};
BulkWriter.prototype.stop = function stop() {
this.running = false;
if (!this.timer) { return; }
clearTimeout(this.timer);
this.timer = null;
debug('stopped');
};
BulkWriter.prototype.schedule = function schedule() {
const thiz = this;
this.timer = setTimeout(() => {
thiz.tick();
}, this.interval);
};
BulkWriter.prototype.tick = function tick() {
debug('tick');
const thiz = this;
if (!this.running) { return; }
this.flush()
.then(() => {
// Emulate finally with last .then()
})
.then(() => { // finally()
thiz.schedule();
});
};
BulkWriter.prototype.flush = function flush() {
// write bulk to elasticsearch
const thiz = this;
if (this.bulk.length === 0) {
debug('nothing to flush');
return new Promise((resolve) => {
return resolve();
});
}
const bulk = this.bulk.concat();
this.bulk = [];
const body = [];
bulk.forEach(({ index, type, doc }) => {
body.push({ index: { _index: index, _type: type, pipeline: this.pipeline } }, doc);
});
debug('going to write', body);
return this.client.bulk({
body,
waitForActiveShards: this.waitForActiveShards,
timeout: this.interval + 'ms',
type: this.type
}).then((res) => {
if (res.errors && res.items) {
res.items.forEach((item) => {
if (item.index && item.index.error) {
// eslint-disable-next-line no-console
console.error('Elasticsearch index error', item.index);
}
});
}
bulk.forEach(({ callback }) => callback());
}).catch((e) => { // prevent [DEP0018] DeprecationWarning
// rollback this.bulk array
thiz.bulk = bulk.concat(thiz.bulk);
// eslint-disable-next-line no-console
console.error(e);
debug('error occurred', e);
this.stop();
this.checkEsConnection();
});
};
BulkWriter.prototype.append = function append(index, type, doc, callback) {
this.bulk.push({
index, type, doc, callback
});
};
BulkWriter.prototype.checkEsConnection = function checkEsConnection() {
const thiz = this;
thiz.esConnection = false;
const operation = retry.operation({
forever: true,
retries: 1,
factor: 1,
minTimeout: 1 * 1000,
maxTimeout: 60 * 1000,
randomize: false
});
return new Promise((fulfill, reject) => {
operation.attempt((currentAttempt) => {
debug('checking for connection');
thiz.client.ping().then(
(res) => {
thiz.esConnection = true;
// Ensure mapping template is existing if desired
if (thiz.options.ensureMappingTemplate) {
thiz.ensureMappingTemplate(fulfill, reject);
} else {
fulfill(true);
}
debug('starting bulk writer');
thiz.running = true;
thiz.tick();
},
(err) => {
debug('checking for connection');
if (operation.retry(err)) {
return;
}
// thiz.esConnection = false;
reject(new Error('Cannot connect to ES'));
}
);
});
});
};
BulkWriter.prototype.ensureMappingTemplate = function ensureMappingTemplate(fulfill, reject) {
const thiz = this;
// eslint-disable-next-line prefer-destructuring
let mappingTemplate = thiz.options.mappingTemplate;
if (mappingTemplate === null || typeof mappingTemplate === 'undefined') {
const rawdata = fs.readFileSync(path.join(__dirname, 'index-template-mapping.json'));
mappingTemplate = JSON.parse(rawdata);
}
const tmplCheckMessage = {
name: 'template_' + (typeof thiz.options.indexPrefix === 'function' ? thiz.options.indexPrefix() : thiz.options.indexPrefix)
};
thiz.client.indices.getTemplate(tmplCheckMessage).then(
(res) => {
fulfill(res);
},
(res) => {
if (res.status && res.status === 404) {
const tmplMessage = {
name: 'template_' + (typeof thiz.options.indexPrefix === 'function' ? thiz.options.indexPrefix() : thiz.options.indexPrefix),
create: true,
body: mappingTemplate
};
thiz.client.indices.putTemplate(tmplMessage).then(
(res1) => {
fulfill(res1);
},
(err1) => {
reject(err1);
}
);
}
}
);
};
module.exports = BulkWriter;