forked from balderdashy/sails
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
354 lines (266 loc) · 7.32 KB
/
index.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
343
344
345
346
347
348
349
350
351
352
/**
* Module dependencies.
*/
var events = require('events'),
async = require('async'),
util = require('sails-util'),
loadSails = require('./load'),
onTeardown = require('./teardown'),
exposeGlobals = require('./exposeGlobals'),
runBootstrap = require('./bootstrap'),
argv = require('optimist').argv,
Err = require('../../errors'),
Logger = require('captains-log');
// Build logger using command-line config
var log = new Logger(util.getCLIConfig(argv).log);
/**
* Expose `Sails` constructor
*/
module.exports = Sails;
/**
* Sails constructor
*
* @api private
*/
function Sails () {
/**
* Inherit methods from EventEmitter
*/
events.EventEmitter.call(this);
/**
* Remove memory-leak warning about max listeners
* See: http://nodejs.org/docs/latest/api/events.html#events_emitter_setmaxlisteners_n
*/
this.setMaxListeners(0);
/**
* Enable server-side CoffeeScript support
*/
require('coffee-script');
/**
* Keep track of spanwed child processes
*/
this.childProcesses = [];
/**
* Expose utilities
*
* @api private
*/
this.util = util;
/**
* Load the pieces of a Sails app
*
* @api private
*/
this.load = loadSails(this);
/**
* Sails.prototype.initialize()
*
* Start the Sails server
* NOTE: sails.load() should be run first.
*
* @api private
*/
this.initialize = function (cb) {
// Make callback optional
cb = util.optional(cb);
var sails = this;
// Indicate that server is starting
sails.log.verbose('Starting app at ' + sails.config.appPath + '...');
// Calculate base URL and host
sails.getHost = function () {
var hasExplicitHost = sails.config.hooks.http && sails.config.explicitHost;
var host = hasExplicitHost || sails.config.host;
return host;
};
sails.getBaseurl = function () {
var usingSSL = sails.config.ssl.key && sails.config.ssl.cert;
var localAppURL =
( usingSSL ? 'https' : 'http' ) + '://' +
(sails.getHost() || 'localhost') +
(sails.config.port == 80 || sails.config.port == 443 ? '' : ':' + sails.config.port);
return localAppURL;
};
// Optionally expose services, models, sails, _, async, etc. as globals
exposeGlobals(sails)();
// Add beforeShutdown event
onTeardown(sails)();
// Run the app bootstrap
runBootstrap(sails)(function (err) {
if (err) return cb(err);
// And fire the `ready` event
// This is listened to by attached servers, etc.
sails.emit('ready');
cb(null, sails);
});
};
/**
* Sails.prototype.lift()
*
* Loads the app, then starts all attached servers.
*
* @api public
*/
this.lift = function (configOverride, cb) {
// Make callback optional
cb = util.optional(cb);
var sails = this;
async.series([
function (cb) {
sails.load(configOverride, cb);
},
this.initialize
], function sailsReady (err, async_data) {
if (err) return sails.lower(cb);
_printSuccessMsg(sails);
return cb(null, sails);
});
};
/**
* Sails.prototype.lower()
*
* The inverse of `lift()`, this method
* shuts down all attached servers.
*
* It also unbinds listeners and terminates child processes.
*
* @api public
*/
this.lower = function (cb) {
var sails = this;
sails.log.verbose('Lowering sails...');
cb = util.optional(cb);
sails._exiting = true;
// If beforeShutdown logic doesn't exist, return early
if ( !util.isFunction(sails.config.beforeShutdown) ) {
return cb();
}
var beforeShutdown = sails.config.beforeShutdown;
// Wait until beforeShutdown logic runs
beforeShutdown(function (err) {
if (err) sails.log.error(err);
// Kill all child processes
util.each(sails.childProcesses, function kill (childProcess) {
sails.log.verbose('Sent kill signal to child process (' + childProcess.pid + ')...');
try {
childProcess.kill('SIGINT');
}
catch (e) {
sails.log.warn('Error received killing child process: ', e.message);
}
});
// Shut down HTTP server
// TODO: defer this to the http and sockets hooks-- use sails.emit('lowering')
// Shut down Socket server
// wait for all attached servers to stop
var log = sails.log.verbose;
async.series([
function shutdownSockets(cb) {
if (!sails.config.hooks.sockets) {
return cb();
}
try {
log('Shutting down socket server...');
setTimeout(cb, 100);
sails.io.server.unref();
sails.io.server.close();
sails.io.server.on('close', function () {
log('Socket server shut down successfully.');
cb();
});
}
catch (e) { cb(); }
},
function shutdownHTTP(cb) {
try {
log('Shutting down HTTP server...');
setTimeout(cb, 100);
sails.hooks.http.server.unref();
sails.hooks.http.server.close();
sails.hooks.http.server.on('close', function () {
log('HTTP server shut down successfully.');
cb();
});
}
catch (e) { cb(); }
},
function removeListeners(cb) {
// removeAllListeners doesn't work correctly without arguments,
// so we'll do it manually
for (var key in sails._events) {
sails.removeAllListeners(key);
}
cb();
}
], cb);
});
};
// Gather app meta-info and log startup message (the boat).
function _printSuccessMsg( sails ) {
// If `config.noShip` is set, skip the startup message.
if ( ! (sails.config.log && sails.config.log.noShip) ) {
sails.log.ship();
sails.log.info('Server lifted in `' + sails.config.appPath + '`');
sails.log.info('To see your app, visit ' + sails.getBaseurl());
sails.log.info('To shut down Sails, press <CTRL> + C at any time.');
sails.log();
sails.log('--------------------------------------------------------');
sails.log(':: ' + new Date());
sails.log();
sails.log('Environment\t: ' + sails.config.environment);
// Only log the host if an explicit host is set
if (sails.getHost()) {
sails.log('Host\t\t: ' + sails.getHost());
}
sails.log('Port\t\t: ' + sails.config.port);
sails.log('--------------------------------------------------------');
}
}
/**
* Sails.prototype.after()
*
* If `evName` has already fired, trigger fn immediately (with no args)
* Otherwise bind a normal one-time event using `EventEmitter.prototype.once()`.
* This is a lot like jQuery's `$(document).ready()`
*/
this.after = function (evName, fn) {
// TODO: support array of evNames (so we can use this instead of `waitForAll`)
if ( this.warmEvents[evName] ) {
fn();
}
else this.once(evName, fn);
};
/**
* { Sails.prototype.warmEvents }
*
* Events which have occurred at least once
* (Required to support `Sails.prototype.after()`)
*/
this.warmEvents = {};
/**
* Sails.prototype.emit()
*
* Override `EventEmitter.prototype.emit`.
* (Required to support `Sails.prototype.after()`)
*/
var self = this;
var _emit = util.clone(this.emit);
this.emit = function (evName) {
var args = Array.prototype.slice.call(arguments, 0);
self.warmEvents[evName] = true;
_emit.apply(self, args);
};
util.bindAll(this);
}
/**
* Static methods
*
* e.g. `Sails.foo()`
*/
Sails.isLocalSailsValid = require('./isLocalSailsValid');
Sails.isSailsAppSync = require('./isSailsApp');
/**
* Extend from EventEmitter to allow hooks to listen to stuff
*
* @api private
*/
require('util').inherits(Sails, events.EventEmitter);