1 |
|
2 | {spawn} = require "child_process"
|
3 | HOUR_IN_MILLI = 3600000
|
4 |
|
5 | lastCheckInHours = 1
|
6 |
|
7 | knife = "knife"
|
8 | buildKnifeArgs = (role, env) ->
|
9 | curTime = Date.now()
|
10 | freshTime = curTime - (lastCheckInHours * HOUR_IN_MILLI)
|
11 | ["search", "node", "--format=json", "role:#{role} AND chef_environment:#{env} AND ohai_time:[#{freshTime} TO #{curTime}]"]
|
12 |
|
13 | getNodesByRoleAndEnv = (role, env, cb) ->
|
14 | res = ''
|
15 | knifeProc = spawn knife, buildKnifeArgs(role, env)
|
16 |
|
17 | knifeProc.stdout.setEncoding "utf8"
|
18 | knifeProc.stderr.setEncoding "utf8"
|
19 |
|
20 | knifeProc.stdout.on "data", (data) ->
|
21 | res += data
|
22 |
|
23 | knifeProc.stderr.on "data", (data) ->
|
24 | console.log "had an error!", data
|
25 | return cb new Error("knife had an error")
|
26 |
|
27 | knifeProc.on "exit", (code) ->
|
28 | if code
|
29 | console.log "output", res
|
30 | return cb new Error("knife had an error")
|
31 |
|
32 | nodes = JSON.parse res
|
33 | cb null, nodes
|
34 |
|
35 | defaultFindHost = (member) ->
|
36 | member.automatic.cloud.public_hostname
|
37 |
|
38 | module.exports = (opts, cb) ->
|
39 | return cb new Error "no role specified" if not opts.role
|
40 | return cb new Error "no user specified" if not opts.user
|
41 | findHost = opts.findHost || defaultFindHost
|
42 | knife = opts.knifePath || knife
|
43 | lastCheckInHours = opts.checkIn || lastCheckInHours
|
44 |
|
45 | env = opts.env || "_default"
|
46 | getNodesByRoleAndEnv opts.role, env, (err, nodes) ->
|
47 | return cb err if err?
|
48 |
|
49 | return cb new Error("no hosts found!") if not nodes.results
|
50 | members = nodes.rows
|
51 | hosts = []
|
52 | for member in members
|
53 | try
|
54 | hosts.push "#{opts.user}@#{findHost(member)}"
|
55 | catch error
|
56 | return cb new Error("failed to find the hostname using method:\n #{findHost.toString()}")
|
57 |
|
58 | cb null, hosts
|