-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspread.js
57 lines (54 loc) · 1.93 KB
/
spread.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
var clone = require('clone')
var utils = require('./utils')
module.exports = function(nodes, current, diff, opts) {
diff.add.sort(utils.sortByMemoryAndCpu)
var postRunWithHosts = clone(diff.keep)
var validHosts = []
diff.add = diff.add.map(function(container) {
validHosts = calculateValidHosts(postRunWithHosts, nodes, container)
if (validHosts.length == 0)
throw new Error("No more valid nodes. Consider increasing # nodes available.")
container.host = leastBusyHost(postRunWithHosts, validHosts)
postRunWithHosts = postRunWithHosts.concat(container)
return container
})
return diff
}
function leastBusyHost(runningContainers, hosts) {
var _hosts = {}
hosts.forEach(function(h) {
_hosts[h.hostname] = h
})
var hostnames = hosts.map(function(h) { return h.hostname })
var weights = runningContainers.reduce(function(map, container) {
if (!map[container.host.hostname])
map[container.host.hostname] = 1
else
map[container.host.hostname] += 1
return map
},{})
var hostname = hostnames.reduce(function(curr, next) {
var curr_weight = weights[curr] || 0
var next_weight = weights[next] || 0
return (next_weight > curr_weight) ? curr : next
}, hostnames[0])
return _hosts[hostname]
}
function calculateValidHosts(containers, hosts, next) {
return hosts.filter(function(host) {
var usedMem = containers.reduce(function(total, container) {
if (container.host.hostname == host.hostname) total += container.memory
return total
},0)
var usedCpu = containers.reduce(function(total, container) {
if (container.host.hostname == host.hostname) total += container.cpu
return total
},0)
var availableMem = host.memory - usedMem
var availableCpu = host.cpus.reduce(function(speed, cpu) {
speed += cpu.speed
return speed
},0) - usedCpu
return (next.memory < availableMem && next.cpu < availableCpu)
})
}