-
Notifications
You must be signed in to change notification settings - Fork 731
/
Connection.js
399 lines (352 loc) · 11.5 KB
/
Connection.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
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
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you 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.
*/
'use strict'
const assert = require('assert')
const { inspect } = require('util')
const hpagent = require('hpagent')
const http = require('http')
const https = require('https')
const debug = require('debug')('elasticsearch')
const { pipeline } = require('stream')
const INVALID_PATH_REGEX = /[^\u0021-\u00ff]/
const {
ConnectionError,
RequestAbortedError,
TimeoutError,
ConfigurationError
} = require('./errors')
class Connection {
constructor (opts) {
this.url = opts.url
this.ssl = opts.ssl || null
this.id = opts.id || stripAuth(opts.url.href)
this.headers = prepareHeaders(opts.headers, opts.auth)
this.deadCount = 0
this.resurrectTimeout = 0
this.caFingerprint = opts.caFingerprint
this._openRequests = 0
this._status = opts.status || Connection.statuses.ALIVE
this.roles = Object.assign({}, defaultRoles, opts.roles)
if (!['http:', 'https:'].includes(this.url.protocol)) {
throw new ConfigurationError(`Invalid protocol: '${this.url.protocol}'`)
}
if (typeof opts.agent === 'function') {
this.agent = opts.agent(opts)
} else if (opts.agent === false) {
this.agent = undefined
} else {
const agentOptions = Object.assign({}, {
keepAlive: true,
keepAliveMsecs: 1000,
maxSockets: 256,
maxFreeSockets: 256,
scheduling: 'lifo'
}, opts.agent)
if (opts.proxy) {
agentOptions.proxy = opts.proxy
this.agent = this.url.protocol === 'http:'
? new hpagent.HttpProxyAgent(agentOptions)
: new hpagent.HttpsProxyAgent(Object.assign({}, agentOptions, this.ssl))
} else {
this.agent = this.url.protocol === 'http:'
? new http.Agent(agentOptions)
: new https.Agent(Object.assign({}, agentOptions, this.ssl))
}
}
this.makeRequest = this.url.protocol === 'http:'
? http.request
: https.request
}
request (params, callback) {
this._openRequests++
let cleanedListeners = false
const requestParams = this.buildRequestObject(params)
// https://github.com/nodejs/node/commit/b961d9fd83
if (INVALID_PATH_REGEX.test(requestParams.path) === true) {
callback(new TypeError(`ERR_UNESCAPED_CHARACTERS: ${requestParams.path}`), null)
/* istanbul ignore next */
return { abort: () => {} }
}
debug('Starting a new request', params)
const request = this.makeRequest(requestParams)
const onResponse = response => {
cleanListeners()
this._openRequests--
callback(null, response)
}
const onTimeout = () => {
cleanListeners()
this._openRequests--
request.once('error', () => {}) // we need to catch the request aborted error
request.abort()
callback(new TimeoutError('Request timed out', params), null)
}
const onError = err => {
cleanListeners()
this._openRequests--
let message = err.message
if (err.code === 'ECONNRESET') {
/* istanbul ignore next */
const socket = request.socket || {}
/* istanbul ignore next */
message += ` - Local: ${socket.localAddress || 'unknown'}:${socket.localPort || 'unknown'}, Remote: ${socket.remoteAddress || 'unknown'}:${socket.remotePort || 'unknown'}`
}
callback(new ConnectionError(message), null)
}
const onAbort = () => {
cleanListeners()
request.once('error', () => {}) // we need to catch the request aborted error
debug('Request aborted', params)
this._openRequests--
callback(new RequestAbortedError(), null)
}
const onSocket = socket => {
/* istanbul ignore else */
if (!socket.isSessionReused()) {
socket.once('secureConnect', () => {
const issuerCertificate = getIssuerCertificate(socket)
/* istanbul ignore next */
if (issuerCertificate == null) {
onError(new Error('Invalid or malformed certificate'))
request.once('error', () => {}) // we need to catch the request aborted error
return request.abort()
}
// Check if fingerprint matches
/* istanbul ignore else */
if (this.caFingerprint !== issuerCertificate.fingerprint256) {
onError(new Error('Server certificate CA fingerprint does not match the value configured in caFingerprint'))
request.once('error', () => {}) // we need to catch the request aborted error
return request.abort()
}
})
}
}
request.on('response', onResponse)
request.on('timeout', onTimeout)
request.on('error', onError)
request.on('abort', onAbort)
if (this.caFingerprint != null) {
request.on('socket', onSocket)
}
// Disables the Nagle algorithm
request.setNoDelay(true)
// starts the request
if (isStream(params.body) === true) {
pipeline(params.body, request, err => {
/* istanbul ignore if */
if (err != null && cleanedListeners === false) {
cleanListeners()
this._openRequests--
callback(err, null)
}
})
} else {
request.end(params.body)
}
return request
function cleanListeners () {
request.removeListener('response', onResponse)
request.removeListener('timeout', onTimeout)
request.removeListener('error', onError)
request.removeListener('abort', onAbort)
request.removeListener('socket', onSocket)
cleanedListeners = true
}
}
// TODO: write a better closing logic
close (callback = () => {}) {
debug('Closing connection', this.id)
if (this._openRequests > 0) {
setTimeout(() => this.close(callback), 1000)
} else {
if (this.agent !== undefined) {
this.agent.destroy()
}
callback()
}
}
setRole (role, enabled) {
if (validRoles.indexOf(role) === -1) {
throw new ConfigurationError(`Unsupported role: '${role}'`)
}
if (typeof enabled !== 'boolean') {
throw new ConfigurationError('enabled should be a boolean')
}
this.roles[role] = enabled
return this
}
get status () {
return this._status
}
set status (status) {
assert(
~validStatuses.indexOf(status),
`Unsupported status: '${status}'`
)
this._status = status
}
buildRequestObject (params) {
const url = this.url
const request = {
protocol: url.protocol,
hostname: url.hostname[0] === '['
? url.hostname.slice(1, -1)
: url.hostname,
hash: url.hash,
search: url.search,
pathname: url.pathname,
path: '',
href: url.href,
origin: url.origin,
// https://github.com/elastic/elasticsearch-js/issues/843
port: url.port !== '' ? url.port : undefined,
headers: this.headers,
agent: this.agent
}
const paramsKeys = Object.keys(params)
for (let i = 0, len = paramsKeys.length; i < len; i++) {
const key = paramsKeys[i]
if (key === 'path') {
request.pathname = resolve(request.pathname, params[key])
} else if (key === 'querystring' && !!params[key] === true) {
if (request.search === '') {
request.search = '?' + params[key]
} else {
request.search += '&' + params[key]
}
} else if (key === 'headers') {
request.headers = Object.assign({}, request.headers, params.headers)
} else {
request[key] = params[key]
}
}
request.path = request.pathname + request.search
return request
}
// Handles console.log and utils.inspect invocations.
// We want to hide `auth`, `agent` and `ssl` since they made
// the logs very hard to read. The user can still
// access them with `instance.agent` and `instance.ssl`.
[inspect.custom] (depth, options) {
const {
authorization,
...headers
} = this.headers
return {
url: stripAuth(this.url.toString()),
id: this.id,
headers,
deadCount: this.deadCount,
resurrectTimeout: this.resurrectTimeout,
_openRequests: this._openRequests,
status: this.status,
roles: this.roles
}
}
toJSON () {
const {
authorization,
...headers
} = this.headers
return {
url: stripAuth(this.url.toString()),
id: this.id,
headers,
deadCount: this.deadCount,
resurrectTimeout: this.resurrectTimeout,
_openRequests: this._openRequests,
status: this.status,
roles: this.roles
}
}
}
Connection.statuses = {
ALIVE: 'alive',
DEAD: 'dead'
}
Connection.roles = {
MASTER: 'master',
DATA: 'data',
INGEST: 'ingest',
ML: 'ml'
}
const defaultRoles = {
[Connection.roles.MASTER]: true,
[Connection.roles.DATA]: true,
[Connection.roles.INGEST]: true,
[Connection.roles.ML]: false
}
const validStatuses = Object.keys(Connection.statuses)
.map(k => Connection.statuses[k])
const validRoles = Object.keys(Connection.roles)
.map(k => Connection.roles[k])
function stripAuth (url) {
if (url.indexOf('@') === -1) return url
return url.slice(0, url.indexOf('//') + 2) + url.slice(url.indexOf('@') + 1)
}
function isStream (obj) {
return obj != null && typeof obj.pipe === 'function'
}
function resolve (host, path) {
const hostEndWithSlash = host[host.length - 1] === '/'
const pathStartsWithSlash = path[0] === '/'
if (hostEndWithSlash === true && pathStartsWithSlash === true) {
return host + path.slice(1)
} else if (hostEndWithSlash !== pathStartsWithSlash) {
return host + path
} else {
return host + '/' + path
}
}
function prepareHeaders (headers = {}, auth) {
if (auth != null && headers.authorization == null) {
/* istanbul ignore else */
if (auth.apiKey) {
if (typeof auth.apiKey === 'object') {
headers.authorization = 'ApiKey ' + Buffer.from(`${auth.apiKey.id}:${auth.apiKey.api_key}`).toString('base64')
} else {
headers.authorization = `ApiKey ${auth.apiKey}`
}
} else if (auth.bearer) {
headers.authorization = `Bearer ${auth.bearer}`
} else if (auth.username && auth.password) {
headers.authorization = 'Basic ' + Buffer.from(`${auth.username}:${auth.password}`).toString('base64')
}
}
return headers
}
function getIssuerCertificate (socket) {
let certificate = socket.getPeerCertificate(true)
while (certificate && Object.keys(certificate).length > 0) {
// invalid certificate
if (certificate.issuerCertificate == null) {
return null
}
// We have reached the root certificate.
// In case of self-signed certificates, `issuerCertificate` may be a circular reference.
if (certificate.fingerprint256 === certificate.issuerCertificate.fingerprint256) {
break
}
// continue the loop
certificate = certificate.issuerCertificate
}
return certificate
}
module.exports = Connection
module.exports.internals = { prepareHeaders, getIssuerCertificate }