forked from actionhero/actionhero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathactionhero.js
342 lines (296 loc) · 11.3 KB
/
actionhero.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
'use strict'
// //////////////////////////////////////////////////////////////////////////
// actionhero framework in node.js
// http://www.actionherojs.com
// https://github.com/actionhero/actionhero
const path = require('path')
const async = require('async')
// HELPERS ///
const fatalError = function (api, errors, type) {
if (errors && !(errors instanceof Array)) { errors = [errors] }
if (errors) {
if (api.log) {
api.log(`Error with initializer step: ${type}`, 'emerg')
errors.forEach((error) => { api.log(error.stack, 'emerg') })
} else {
console.error('Error with initializer step: ' + type)
errors.forEach((error) => { console.error(error.stack) })
}
api.commands.stop.call(api, () => {
process.exit(1)
})
}
}
const sortNumber = function (a, b) {
return a - b
}
let startCount = 0
const flattenOrderedInitialzer = function (collection) {
let output = []
let keys = []
for (let key in collection) {
keys.push(parseInt(key))
}
keys.sort(sortNumber)
keys.forEach((key) => {
collection[key].forEach((d) => {
output.push(d)
})
})
return output
}
// ACTIONHERO //
const actionhero = function () {
this.initializers = {}
this.api = {
running: false,
initialized: false,
shuttingDown: false
}
}
actionhero.prototype.initialize = function (params, callback) {
this.api.commands = {
initialize: (params, callback) => { this.initialize(params, callback) },
start: (params, callback) => { this.start(params, callback) },
stop: (callback) => { this.stop(callback) },
restart: (callback) => { this.restart(callback) }
}
this.api.projectRoot = process.cwd()
if (process.env.project_root) {
this.api.projectRoot = process.env.project_root
} else if (process.env.projectRoot) {
this.api.projectRoot = process.env.projectRoot
} else if (process.env.PROJECT_ROOT) {
this.api.projectRoot = process.env.PROJECT_ROOT
}
if (!callback && typeof params === 'function') {
callback = params; params = {}
}
if (params === null) { params = {} }
this.startingParams = params
this.api._startingParams = this.startingParams
this.api.initializerDefaults = {
load: 1000,
start: 1000,
stop: 1000
}
let loadInitializerRankings = {}
let startInitializerRankings = {}
let stopInitializerRankings = {}
this.configInitializers = []
this.loadInitializers = []
this.startInitializers = []
this.stopInitializers = [];
// we need to load the config first
[
path.resolve(__dirname, 'initializers', 'utils.js'),
path.resolve(__dirname, 'initializers', 'config.js')
].forEach((file) => {
let filename = file.replace(/^.*[\\/]/, '')
let initializer = filename.split('.')[0]
delete require.cache[require.resolve(file)]
this.initializers[initializer] = require(file)
this.configInitializers.push((next) => {
this.initializers[initializer].initialize(this.api, next)
})
})
this.configInitializers.push(() => {
let customInitializers = []
let duplicatedInitializers = []
this.api.config.general.paths.initializer.forEach((startPath) => {
customInitializers = customInitializers.concat(this.api.utils.recursiveDirectoryGlob(startPath))
})
// load all other initializers
this.api.utils.arrayUniqueify(
this.api.utils.recursiveDirectoryGlob(path.join(__dirname, 'initializers'))
.sort()
.concat(
customInitializers
.sort()
)
).forEach((f) => {
let file = path.normalize(f)
let initializer = path.basename(f).split('.')[0]
let fileParts = file.split('.')
let ext = fileParts[(fileParts.length - 1)]
if (ext === 'js') {
// check if initializer already exists (exclude utils and config)
if (this.initializers[initializer] &&
file !== path.resolve(__dirname, 'initializers', 'utils.js') &&
file !== path.resolve(__dirname, 'initializers', 'config.js')) {
duplicatedInitializers.push(file)
} else {
delete require.cache[require.resolve(file)]
this.initializers[initializer] = require(file)
}
const loadFunction = (next) => {
this.api.watchFileAndAct(file, () => {
this.api.log(`*** Rebooting due to initializer change (${file}) ***`, 'info')
this.api.commands.restart()
})
if (typeof this.initializers[initializer].initialize === 'function') {
if (typeof this.api.log === 'function') { this.api.log(`Loading initializer: ${initializer}`, 'debug', file) }
try {
this.initializers[initializer].initialize(this.api, (error) => {
try { this.api.log(`Loaded initializer: ${initializer}`, 'debug', file) } catch (e) { }
next(error)
})
} catch (e) {
this.api.log(`Exception occured in initializer: ${initializer} during load`, 'warning', e)
next(e)
}
} else {
next()
}
}
const startFunction = (next) => {
if (typeof this.initializers[initializer].start === 'function') {
if (typeof this.api.log === 'function') { this.api.log(`Starting initializer: ${initializer}`, 'debug', file) }
try {
this.initializers[initializer].start(this.api, (error) => {
this.api.log(`Started initializer: ${initializer}`, 'debug', file)
next(error)
})
} catch (e) {
this.api.log(`Exception occured in initializer: ${initializer} during start`, 'warning', e)
next(e)
}
} else {
next()
}
}
const stopFunction = (next) => {
if (typeof this.initializers[initializer].stop === 'function') {
if (typeof this.api.log === 'function') { this.api.log(`Stopping initializer: ${initializer}`, 'debug', file) }
try {
this.initializers[initializer].stop(this.api, (error) => {
this.api.log(`Stopped initializer: ${initializer}`, 'debug', file)
next(error)
})
} catch (e) {
this.api.log(`Exception occured in initializer: ${initializer} during stop`, 'warning', e)
next(e)
}
} else {
next()
}
}
if (this.initializers[initializer].loadPriority === undefined) {
this.initializers[initializer].loadPriority = this.api.initializerDefaults.load
}
if (this.initializers[initializer].startPriority === undefined) {
this.initializers[initializer].startPriority = this.api.initializerDefaults.start
}
if (this.initializers[initializer].stopPriority === undefined) {
this.initializers[initializer].stopPriority = this.api.initializerDefaults.stop
}
if (loadInitializerRankings[this.initializers[initializer].loadPriority] === undefined) {
loadInitializerRankings[this.initializers[initializer].loadPriority] = []
}
if (startInitializerRankings[this.initializers[initializer].startPriority] === undefined) {
startInitializerRankings[this.initializers[initializer].startPriority] = []
}
if (stopInitializerRankings[this.initializers[initializer].stopPriority] === undefined) {
stopInitializerRankings[this.initializers[initializer].stopPriority] = []
}
if (this.initializers[initializer].loadPriority > 0) {
loadInitializerRankings[this.initializers[initializer].loadPriority].push(loadFunction)
}
if (this.initializers[initializer].startPriority > 0) {
startInitializerRankings[this.initializers[initializer].startPriority].push(startFunction)
}
if (this.initializers[initializer].stopPriority > 0) {
stopInitializerRankings[this.initializers[initializer].stopPriority].push(stopFunction)
}
}
})
// flatten all the ordered initializer methods
this.loadInitializers = flattenOrderedInitialzer(loadInitializerRankings)
this.startInitializers = flattenOrderedInitialzer(startInitializerRankings)
this.stopInitializers = flattenOrderedInitialzer(stopInitializerRankings)
this.loadInitializers.push(() => {
process.nextTick(() => {
this.api.initialized = true
if (duplicatedInitializers.length > 0) {
duplicatedInitializers.forEach(initializer => this.api.log(`Initializer ${initializer} already exists!`, 'error'))
this.api.commands.stop.call(this.api, () => {
process.exit(1)
})
}
callback(null, this.api)
})
})
async.series(this.loadInitializers, (errors) => { fatalError(this.api, errors, 'initialize') })
})
async.series(this.configInitializers, (errors) => { fatalError(this.api, errors, 'config') })
}
actionhero.prototype.start = function (params, callback) {
if (!callback && typeof params === 'function') {
callback = params; params = {}
}
const _start = () => {
this.api.running = true
this.api.log('*** Starting ActionHero ***', 'notice')
this.startInitializers.push(() => {
this.api.bootTime = new Date().getTime()
if (startCount === 0) {
this.api.log('*** ActionHero Started ***', 'alert')
} else {
this.api.log('*** ActionHero Restarted ***', 'alert')
}
startCount++
callback(null, this.api)
})
async.series(this.startInitializers, (errors) => { fatalError(this.api, errors, 'start') })
}
if (this.api.initialized === true) {
_start()
} else {
this.initialize(params, () => {
_start()
})
}
}
actionhero.prototype.stop = function (callback) {
if (this.api.running === true) {
this.api.shuttingDown = true
this.api.running = false
this.api.initialized = false
this.api.log('Shutting down open servers and stopping task processing...', 'notice')
this.stopInitializers.push(() => {
this.api.unWatchAllFiles()
this.api.pids.clearPidFile()
this.api.log('*** ActionHero Stopped ***', 'alert')
this.api.log('***', 'debug')
delete this.api.shuttingDown
// reset initializers to prevent duplicate check on restart
this.initializers = {}
process.nextTick(() => {
if (typeof callback === 'function') { callback(null, this.api) }
})
})
async.series(this.stopInitializers, (errors) => { fatalError(this.api, errors, 'stop') })
} else if (this.api.shuttingDown === true) {
// double sigterm; ignore it
} else {
if (this.api.log) { this.api.log('Cannot shut down actionhero, not running', 'error') }
if (typeof callback === 'function') { callback(null, this.api) }
}
}
actionhero.prototype.restart = function (callback) {
if (this.api.running === true) {
this.stop((error) => {
if (error) { this.api.log(error, 'error') }
this.start(this.startingParams, (error) => {
if (error) { this.api.log(error, 'error') }
if (typeof callback === 'function') { callback(null, this.api) }
})
})
} else {
this.start(this.startingParams, (error) => {
if (error) { this.api.log(error, 'error') }
if (typeof callback === 'function') { callback(null, this.api) }
})
}
}
module.exports = actionhero