-
Notifications
You must be signed in to change notification settings - Fork 28
/
unique_service_by_hosts_cidr.js
53 lines (45 loc) · 1.51 KB
/
unique_service_by_hosts_cidr.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
function uniqueServicesByHostsCIDR () {
// Print a unique service list for hosts CIDR range
//
// Created by: Matt Burch
// Usage: uniqueServicesByHostsCIDR('x.x.x.x/x') or uniqueServicesByHostsCIDR('x.x.x.x/x','y.y.y.y/y')
//
var hostTargets = []
var projectId = Session.get('projectId')
var nets = Array.prototype.slice.call(arguments, 0)
var hosts = Hosts.find({
projectId: projectId
}).fetch()
var hostip = {}
var hostid = {}
var ids = []
function dec2Bin (octet, cidr) {
var pad = '00000000'
var bin = parseInt(octet[0], 10).toString(2)
var bincidr = (bin.length >= pad.length ? bin : pad.slice(0, pad.length - bin.length) + bin)
for (var i = 1; i <= octet.length; i++) {
bin = parseInt(octet[i], 10).toString(2)
bincidr += (bin.length >= pad.length ? bin : pad.slice(0, pad.length - bin.length) + bin)
}
return bincidr.slice(0, parseInt(cidr, 10))
}
hosts.forEach(function (host) {
var ip = host.ipv4.split('.')
hostip[dec2Bin(ip, 32)] = host.ipv4
hostid[host.ipv4] = host._id
})
nets.forEach(function (cidr) {
cidr = cidr.split('/')
var net = cidr[0].split('.')
var netbin = dec2Bin(net, cidr[1])
for (var key in hostip) {
if ((key.slice(0, parseInt(cidr[1], 10))) === netbin) {
ids.push(hostid[hostip[key]])
}
}
})
var services = Services.find({projectId: projectId, hostId: {$in: ids}}).fetch()
return _.uniq(_.pluck(services, 'port')).sort(function (a, b) {
return a - b
}).join(',')
}