Repository navigation
Expand file tree
/
Copy pathprocesses.coffee
More file actions
executable file
·350 lines (293 loc) · 11.7 KB
/
Copy pathprocesses.coffee
File metadata and controls
executable file
·350 lines (293 loc) · 11.7 KB
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
# this is a work in progress.
# it's doing proper cleanup and management of child processes
# use it with care, not all edge cases are covered.
#
# author @devrim
traverse = require 'traverse'
_ = require 'underscore'
fs = require "fs"
os = require "os"
hat = require 'hat'
{exec,spawn,fork} = require "child_process"
{EventEmitter} = require "events"
Worker = require 'koding-worker'
{mq, kontrold} = require 'koding-config-manager'
try
fs.mkdirSync __dirname+"/.tmp/"
catch e
flipped = (fn) -> -> fn.apply this, [ arguments... ].reverse()
wait = flipped setTimeout
# do nothing, probably dir is already there.
################################
### HANDLE SIGNALS and KILLS ###
################################
# guaranteed death.
process.on 'SIGTERM', =>
console.log "going down"
process.exit 0
module.exports = class Processes extends EventEmitter
constructor:(options = {})->
{main} = options
@list = {}
@child = null
@workerProcess = {}
@disableRestart = no
@childProcessesContainerDir = "#{__dirname}/.tmp"
if main
previouschildProcessesContainerDir = "#{@childProcessesContainerDir}.#{Date.now()}"
fs.renameSync @childProcessesContainerDir, previouschildProcessesContainerDir
fs.mkdirSync @childProcessesContainerDir
exec "rm -rf #{previouschildProcessesContainerDir}",(err,stdout,stderr)->
if err
console.log "couldn't delete previous process tree at #{previouschildProcessesContainerDir}"
#else
# console.log "previous process tree is deleted."
fork: (options, callback) ->
options.fork = yes
@_run options, callback, (cb) =>
callback cb
spawn: (options, callback) ->
options.spawn = yes
@_run options, callback
exec: (cmd, callback) ->
@spawn
name : Date.now()
cmd : cmd
restart : no
stdout : process.stdout
stderr : process.stderr
onExit : callback
run: (cmd, callback=->)->
# sp = require('child_process').spawn("bash -c", cmd.split(" "))
# sp.stdout.on "data", (data) ->
# console.log "[#{cmd}]"+(data+"").replace("\n","")
# sp.stderr.on "data", (data) -> console.log "[#{cmd}]"+(data+"").replace("\n","")
# # sp.on "close", (code) -> callback sp.pid
# sp.on "exit", (code) -> callback sp.pid
ch = require('child_process').exec cmd,callback # cmdA is split wrongly when quotation marks are involved
ch.stdout.pipe process.stdout
ch.stderr.pipe process.stderr
# our main function is this. Either it is started normal, or it is wrapped
# via kontrold amqp process
_run: (options, callback) ->
{ name, restartTimeout, verbose } = options
options.name ?= Date.now()
options.stdout ?= process.stdout
options.stderr ?= process.stderr
options.verbose ?= yes
options.restart ?= yes
options.restartTimeout ?= 100
if options.kontrol?.enabled
console.log "[PROCESSES][#{name}] kontrold enabled with mode: '#{options.kontrol.startMode}'"
@kontroldProcess options
else
@child = @startProcess options
@populateChildObject options, @child
getDate: ->
d = new Date()
pad = (n) ->
(if n < 10 then "0" + n else n)
"#{d.getUTCFullYear()}-#{pad d.getUTCMonth() + 1}-#{pad d.getUTCDate()}T#{pad d.getUTCHours()}:#{pad d.getUTCMinutes()}:#{pad d.getUTCSeconds()}Z"
startProcess: (options) ->
{ name, opts, cmd, stdout, stderr, verbose } = options
if "string" is typeof options.cmd
cmdA = cmd.split " "
else
console.log e = "[PROCESSES][ERROR][#{name}] Can't start without a valid cmd param." if verbose
if options.fork
[ process, args... ] = cmdA
@child = fork process, args, opts
else
# @child = spawn cmdA[0],cmdA[1...]
@child = exec cmd # cmdA is split wrongly when quotation marks are involved
@child.stdout.pipe stdout if stdout
@child.stderr.pipe stderr if stderr
return @child
kontroldProcess: (options) ->
{ name, onExit, restart, restartTimeout, verbose } = options
console.log "[PROCESSES][#{name}] force mode enabled. Trying to stop and kill all other #{name} workers" if verbose and options.kontrol.forceStart
if options.kontrol.binary?
uuid = options.kontrol.binary
binaryEnabled = yes
else
uuid = hat()
binaryEnabled = no
mq.vhost = kontrold.vhost # use a different vhost for our workers
workerProc = new Worker {
mq
command : if options.kontrol.registerToProxy then "addWithProxy" else "add"
hostname : options.kontrol.hostname
name : name
uuid : uuid
option : options.kontrol.startMode
interval : options.reportInterval
port : options.kontrol.port
proxyName : options.kontrol.proxyName
binary : binaryEnabled
}
@workerProcess[name] = workerProc
workerProc.connect()
console.log "[PROCESSES][#{name}] connected to kontrold. waiting for instructions..." if verbose
#############
### Start ###
#############
workerProc.on 'permissionToRun', =>
# Don't create a new fork if we start it again (i.e after a stop)
unless @list[name]?.name is name
console.log "[PROCESSES][#{name}] received 'add' message from Kontrold. starting child_process." if verbose
@child = @startProcess options
@populateChildObject options, @child
#############
### Child ###
#############
workerProc.startReporter "ack"
workerProc.stopReporter "add"
# Update kontrold worker information with our newly created pid.
workerProc.fetchWorkerExchange (workerExchange) =>
{ worker } = workerProc
worker.message.command = "update"
worker.status = 0
worker.pid = @list[name].pid
worker.timestamp = @getDate()
workerExchange.publish "input.worker", { worker }, {
appId: "#{@workerProcess[name].worker.uuid}"
}
#############
### Kill ###
#############
workerProc.on 'killWorkerProcess', =>
console.log "killing worker:", name
workerProc.worker.status = 1
console.log "[PROCESSES][#{name}] received 'kill' message from Kontrold. Sending SIGTERM to the child_process." if verbose
# @child.kill 'SIGKILL' #try this in the future
# @workerProcess[name].stopReporter() #TODO think about it
@kill name
workerProc.on 'killForceWorkerProcess', =>
@disableRestart = yes
console.log "killing worker:", name
workerProc.worker.status = 1
console.log "[PROCESSES][#{name}] received 'killForce' message from Kontrold. Sending SIGTERM to the child_process." if verbose
# @child.kill 'SIGKILL' #try this in the future
# @workerProcess[name].stopReporter() #TODO think about it
@kill name
populateChildObject: (options, child) ->
{ name, onMessage, modulePath, args, restart, restartTimeout, cmd, log,
onExit, stdout, stderr, verbose, die } = options
onExit ?= ->
console.log "[PROCESSES][#{name}] started the process: #{name} with pid: #{@child.pid}" if verbose
@createPidFile child.pid, name
childObj =
name : name
process : child
pid : child.pid
verbose : verbose
workerProc = @workerProcess[name]
if cmd
childObj.cmd = cmd
else if modulePath
childObj.fork = { modulePath, args, options }
if @list[name]
d = Date.now()
console.log "[WARN][Processes] process name '#{name}' not unique. to be able to kill it properly it is now: #{name}-#{d}" if verbose
name += "-#{d}"
@list[name] = childObj
if die?.after
console.log "[PROCESSES][#{name}]i will kill this process:#{name} every #{die.after}msecs" if verbose
wait die.after, =>
console.log "[PROCESSES][#{name}]it's time you die process:#{name}" if verbose
@kill name
child.on 'exit', =>
console.log "[PROCESSES][#{name}] observing a process exiting", child.pid
console.log "[PROCESSES][#{name}] did exit." if verbose
@emit "exit", child.pid, name
delete @list[name]
if workerProc?
workerProc.stopReporter "ack"
workerProc.stopReporter "add"
workerProc.connection.end()
workerProc.connection.destroy()
delete @workerProcess[name] if @workerProcess[name] is workerProc
child.on 'close', =>
console.log "[PROCESSES][#{name}] did close." if verbose
@emit "close", child.pid, name
onExit child.pid, name
if @disableRestart is yes
console.log "[PROCESSES][#{name}] restart is disabled because of force mode." if verbose
@disableRestart = no
return
if restart is yes
restartTimeout = 1 unless restartTimeout
wait restartTimeout, => @_run options
console.log "[PROCESSES][#{name}] restarting the process in #{restartTimeout} msecs." if verbose
child.on 'message', (msg) =>
onMessage msg if "function" is typeof onMessage
if msg['process-monitor']
delete msg['process-monitor']
if workerProc?
msg['uuid'] = workerProc.worker.uuid
workerProc.fetchWorkerExchange (workerExchange) =>
workerProc.worker.message.command = "ack"
workerExchange.publish "input.worker", {
monitor: msg
}, {
appId: "#{@workerProcess[name].worker.uuid}"
}
return childObj
createPidFile : (pid, name) ->
fs.writeFileSync "#{@childProcessesContainerDir}/#{process.pid}.#{pid}",""
get : (name) ->
if @list[name]
return @list[name].process
else
console.log "[ERROR][Processes] #{name} Can't be found."
fetchChildren: (parentPid, callback) ->
findChildren = (arr, pid) ->
findChildrenRec = (pid, root = yes) ->
c={}
pid = "#{pid}"
i = -1
arr.forEach (item)->
[parent,child] = item.split "."
if parent is pid
c[child] = findChildrenRec child, no
return c
arr = traverse(findChildrenRec pid).paths()
arr.forEach (group) -> group.reverse()
arr = _.sortBy arr, (a) -> a.length * -1
return _.uniq _.flatten arr, yes
fs.readdir @childProcessesContainerDir, (err, list) ->
if err
callback err
else
callback null, findChildren list, parentPid
killAllChildren: (parentPid, callback) ->
@fetchChildren parentPid, (err, orderedKillList) ->
console.log "ordered kill list: #{orderedKillList}"
unless err
pidPair = []
orderedKillList.forEach (pid)->
console.log "killing children: #{pid}"
try
pidPair.push pid
process.kill +pid
if pidPair.length is 2
pidPair.reverse()
deleteFile = pidPair.join(".")
console.log "deleting #{deleteFile}"
fs.unlinkSync deleteFile
pidPair.shift()
catch e
console.log "child process #{pid} did not exist. not killed by me."
callback null
sendMessage: (name, msg) ->
if @list[name]?.process?.send
@list[name].process.send msg
kill: (name, callback=(->)) ->
unless @list[name]
console.log "[PROCESSES][#{name}] cant kill #{name}, couldn't find it."
else
pid = @list[name].pid
console.log "[PROCESSES][#{name}] killing parent: #{pid}"
@killAllChildren pid, (err, res) ->
console.log "[PROCESSES][#{name}] killing #{name} #{pid}"
process.kill pid