-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
488 lines (383 loc) · 11.8 KB
/
index.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
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
'use strict'
const BaseFacility = require('bfx-facs-base')
const async = require('async')
const { TaskQueue } = require('@bitfinex/lib-js-util-task-queue')
const debug = require('debug')('facs:kea')
class KEAFacility extends BaseFacility {
constructor (caller, opts, ctx) {
super(caller, opts, ctx)
this.name = 'kea'
this._hasConf = true
this.leases = []
super.init()
this.taskQueue = new TaskQueue(1)
if (!this.opts.fac_http) {
throw new Error('ERR_FAC_HTTP_NOTFOUND')
}
this.fac_http = this.opts.fac_http
}
async _prepareLeases () {
if (this.taskQueue.queue.idle()) {
await this.fetchConf()
await this.fetchLeases()
}
}
async sendCommand (command, service, args = undefined) {
const body = {
command,
service
}
if (args) {
body.arguments = args
}
const data = await this.fac_http.post(this.conf.url, { body, encoding: 'json' })
return { data: data.body }
}
async fetchConf () {
this.serverConf = (await this.sendCommand('config-get', ['dhcp4'])).data[0].arguments.Dhcp4
this.subnets = this.serverConf.subnet4
}
async sendMultipleCommands (command, service, args, maxParallel = 10) {
const responses = {
success: [],
error: []
}
await async.parallelLimit(args.map((val, index) => {
return async () => {
try {
const res = await this.sendCommand(command, service, val)
if (res.data[0].result === 0) {
responses.success.push({ index, res: res.data[0], val })
} else {
responses.error.push({ index, res: res.data[0] })
}
} catch (error) {
console.error(error)
responses.error.push({ index, error })
}
}
}
), maxParallel)
return responses
}
_addJob (request) {
return this.taskQueue.pushTask(async () => {
try {
const response = await request.process()
return {
success: true,
request: request.payload,
response: (request.respKey ? { [request.respKey]: response } : {})
}
} catch (error) {
return {
success: false,
request: request.payload,
error: error.message
}
}
})
}
async _lease4GetAll () {
try {
const res = await this.sendCommand('lease4-get-all', ['dhcp4'])
if (!res.data[0].arguments) {
return res.data[0].text
}
return res.data[0].arguments.leases
} catch (error) {
console.error(error)
}
}
async _lease4set () {
try {
const res = await this.sendCommand('lease4-get-all', ['dhcp4'])
return res.data[0].arguments.leases
} catch (error) {
console.error(error)
}
}
async fetchLeases () {
const res = await this._lease4GetAll()
this.leases = res.map((val) => ({ mac: val['hw-address'], ip: val['ip-address'], subnetId: val['subnet-id'] }))
}
async setLeases (leases) {
const args = leases.map(lease => ({ 'ip-address': lease.ip, 'hw-address': lease.mac, 'subnet-id': lease.subnetId }))
const response = await this.sendMultipleCommands('lease4-add', ['dhcp4'], args)
response.success.forEach((res) => {
const val = res.val
this.leases.push({ mac: val['hw-address'], ip: val['ip-address'], subnetId: val['subnet-id'] })
})
return response
}
async freeLeases (leases) {
const args = leases.map(lease => ({ 'ip-address': lease.ip, 'hw-address': lease.mac }))
const response = await this.sendMultipleCommands('lease4-del', ['dhcp4'], args)
response.success.forEach((res) => {
const val = res.val
this.leases = this.leases.filter((lease) => !(lease.mac === val['hw-address'] && lease.ip === val['ip-address']))
})
}
async getSubnetId (subnet) {
const subnetObj = this.subnets.find((val) => val.subnet === subnet)
if (subnetObj) {
return subnetObj.id
}
return null
}
async getAvailableIp (subnetId) {
const subnet = this.subnets.find((val) => val.id === subnetId)
if (!subnet) {
throw new Error('Invalid subnetId')
}
this.fetchLeases()
const leasesInSubnet = this.leases.filter((val) => val.subnetId === subnetId)
const allocatedIps = leasesInSubnet.map((val) => val.ip)
allocatedIps.push(subnet.subnet.split('/')[0])
const ipRange = this.getIpsInSubnet(subnet.subnet, subnet.pools)
const availableIps = ipRange.filter((val) => !allocatedIps.includes(val))
if (availableIps.length === 0) {
throw new Error('No available ip')
}
return availableIps[0]
}
getIpsInSubnet (subnetCIDR, pools) {
const [subnet, prefixLength] = subnetCIDR.split('/')
const ipParts = subnet.split('.').map(Number)
const prefix = parseInt(prefixLength, 10)
const subnetNumeric = (ipParts[0] << 24) | (ipParts[1] << 16) | (ipParts[2] << 8) | ipParts[3]
const numAddresses = 2 ** (32 - prefix)
const networkNumeric = subnetNumeric & ((2 ** 32 - 1) << (32 - prefix))
const usableIPs = []
for (let i = 2; i < numAddresses - 2; i++) {
const numericIP = networkNumeric + i
const ipAddress = [
(numericIP >>> 24) & 255,
(numericIP >>> 16) & 255,
(numericIP >>> 8) & 255,
numericIP & 255
].join('.')
if (pools.length > 0 && !this.isIpInPools(ipAddress, pools)) {
continue
}
usableIPs.push(ipAddress)
}
return usableIPs
}
isIpInPools (ip, pools) {
for (let i = 0; i < pools.length; i++) {
if (this.isIpInPool(ip, pools[i].pool)) return true
}
return false
}
isIpInPool (ip, pool) {
const [startIP, endIP] = pool.split('-')
const startIPArray = startIP.split('.').map(Number)
const endIPArray = endIP.split('.').map(Number)
const ipArray = ip.split('.').map(Number)
for (let i = 0; i < 4; i++) {
if (ipArray[i] < startIPArray[i] || ipArray[i] > endIPArray[i]) {
return false
}
}
return true
}
async _setIp ({ mac, subnet, forceSetIp = false }) {
debug('setIp', mac, subnet, forceSetIp)
if (!mac || !subnet) {
throw new Error('ERR_MAC_AND_SUBNET_REQUIRED')
}
const subnetId = await this.getSubnetId(subnet)
debug('subnetId', subnetId)
if (!subnetId) {
debug('subnet not found', subnet)
throw new Error('ERR_SUBNET_NOT_FOUND')
}
const lease = this.leases.find(l => l.mac.toLowerCase() === mac.toLowerCase() && l.subnetId === subnetId)
debug('lease', lease)
const otherSubnetLeases = this.leases.filter(l => l.mac.toLowerCase() === mac.toLowerCase() && l.subnetId !== subnetId)
debug('otherSubnetLeases', otherSubnetLeases)
if (lease) {
debug('lease found')
// release ips on other subnets
if (otherSubnetLeases.length > 0 && forceSetIp) {
await this._releaseIpsForLeases(otherSubnetLeases)
}
await this.setLeases([{
ip: lease.ip,
mac,
subnetId
}])
debug('returning lease.ip', lease.ip)
return lease.ip
}
if (otherSubnetLeases.length > 0) {
if (!forceSetIp) {
debug('ERR_IN_ANOTHER_SUBNET', otherSubnetLeases, subnetId)
throw new Error('ERR_IN_ANOTHER_SUBNET')
}
await this._releaseAllIpsForMac(mac)
}
const ip = await this.getAvailableIp(subnetId)
if (!ip) {
debug('ERR_NO_AVAILABLE_IP')
throw new Error('ERR_NO_AVAILABLE_IP')
}
debug('ip found', ip)
await this.setLeases([{
ip,
mac,
subnetId
}])
return ip
}
async _releaseAllIpsForMac (mac) {
const leases = this.leases.filter(l => l.mac.toLowerCase() === mac.toLowerCase())
await this._releaseIpsForLeases(leases)
}
async _releaseIpsForLeases (leases) {
for (const lease of leases) {
await this._releaseIp({ ip: lease.ip })
}
}
async _assignIp ({ mac, ip, subnetId }) {
debug('assignIp', mac, ip, subnetId)
if (!mac || !ip || !subnetId) {
throw new Error('ERR_MAC_AND_IP_AND_SUBNETID_REQUIRED')
}
const subnet = this.subnets.find(s => s.id === subnetId)
if (!subnet) {
throw new Error('ERR_SUBNET_NOT_FOUND')
}
const lease = this.leases.find(l => l.mac.toLowerCase() === mac.toLowerCase())
if (lease) {
if (lease.ip !== ip) {
throw new Error('ERR_IP_NOT_MATCH')
}
if (lease.subnetId !== subnetId) {
throw new Error('ERR_IN_ANOTHER_SUBNET')
}
return ip
}
await this.setLeases([{
ip,
mac,
subnetId
}])
return ip
}
async _assignIps (reqs) {
await this._prepareLeases()
const res = []
for (let i = 0; i < reqs.length; i++) {
const req = reqs[i]
res.push(this._addJob({
payload: { mac: req.mac, ip: req.ip, subnetId: req.subnetId },
respKey: 'ip',
process: async () => {
return await this._assignIp(req, true)
}
}))
}
return (await Promise.allSettled(res)).map(r => ({ success: r.value.success, mac: r.value.request.mac, ip: r.value.response, error: r.value.error }))
}
async _releaseIp ({ ip }) {
debug('releaseIp', ip)
if (!ip) {
debug('ERR_IP_REQUIRED')
throw new Error('ERR_IP_REQUIRED')
}
const lease = this.leases.find(l => l.ip === ip)
if (!lease) {
throw new Error('ERR_IP_NOT_FOUND')
}
debug('lease found', lease)
await this.freeLeases([{
ip: lease.ip,
mac: lease.mac
}])
return 1
}
async setIps (reqs) {
await this._prepareLeases()
const res = []
for (let i = 0; i < reqs.length; i++) {
const req = reqs[i]
res.push(this._addJob({
payload: { mac: req.mac },
respKey: 'ip',
process: async () => {
return await this._setIp(req, true)
}
}))
}
return (await Promise.allSettled(res)).map(r => ({ success: r.value.success, mac: r.value.request.mac, ip: r.value.response, error: r.value.error }))
}
async setIp ({ mac, subnet, forceSetIp = false }, retry = false) {
await this._prepareLeases()
const jobStatus = await this._addJob({
payload: { mac },
respKey: 'ip',
process: async () => {
return await this._setIp({ mac, subnet, forceSetIp })
}
})
if (!retry || jobStatus.success) {
if (jobStatus.success) {
return jobStatus.response.ip
} else {
throw new Error(jobStatus.error)
}
}
await this._prepareLeases()
return this.setIp({ mac, subnet, forceSetIp })
}
async releaseIp ({ ip }, retry = false) {
await this._prepareLeases()
const jobStatus = await this._addJob({
payload: { ip },
process: async () => {
return await this._releaseIp({ ip })
}
})
if (!retry || jobStatus.success) {
if (jobStatus.success) {
return 1
} else {
throw new Error(jobStatus.error)
}
}
await this._prepareLeases()
return this.releaseIp({ ip })
}
async getLeases () {
await this._prepareLeases()
return await this.leases.map((val) => ({ mac: val.mac, ip: val.ip }))
}
async releaseIps (reqs) {
await this._prepareLeases()
const res = []
for (let i = 0; i < reqs.length; i++) {
const req = reqs[i]
res.push(this._addJob({
payload: { ip: req.ip },
process: async () => {
return await this._releaseIp(req, true)
}
}))
}
return (await Promise.allSettled(res)).map(r => ({ success: r.value.success, ip: r.value.request.ip, error: r.value.error }))
}
async exportLeases () {
const res = await this._lease4GetAll()
return res.map(val => ({
'ip-address': val['ip-address'],
'hw-address': val['hw-address'],
'subnet-id': val['subnet-id']
}))
}
async importLeases (req) {
return await this._assignIps(req)
}
}
module.exports = KEAFacility