forked from docktor/docktor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
executable file
·83 lines (65 loc) · 2.8 KB
/
server.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
'use strict';
/**
* Module dependencies.
*/
var init = require('./config/init')(),
config = require('./config/config'),
mongoose = require('mongoose'),
scheduler = require('./config/scheduler'),
cluster = require('cluster'),
os = require('os');
// Code to run if we're in the master process
if (config.cluster && cluster.isMaster) {
// Count the machine's CPUs
var cpuCount = os.cpus().length;
// Create a worker for each CPU
for (var i = 0; i < cpuCount; i += 1) {
cluster.fork();
}
// Code to run if we're in a worker process
} else {
// Authorize Docktor to fetch HTTPS resources with self signed certificates (i.e. Docker daemon protected with TLS config)
// Needed only when Docktor is itself hosted with HTTPS
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
// Bootstrap db connection
var db = mongoose.connect(config.db, function (err) {
if (err) {
console.error('\x1b[31m', 'Could not connect to MongoDB!');
console.log(err);
}
});
scheduler.start();
// Init the express application
var app = require('./config/express')(db);
// Bootstrap passport config
require('./config/passport')();
var http = require('http');
// Start the app using HTTPs if certifcate and private key are defined
if (!config.httpsPrivateKey || !config.httpsCertificate) {
http.createServer(app).listen(config.httpPort);
console.log('Docktor application started on HTTP port ' + config.httpPort + '. (no certificate or private key defined for HTTPS)');
} else {
var fs = require('fs');
var https = require('https');
var privateKey = config.httpsPrivateKey ? fs.readFileSync(config.httpsPrivateKey, 'utf8') : undefined;
var certificate = config.httpsCertificate ? fs.readFileSync(config.httpsCertificate, 'utf8') : undefined;
var credentials = { key: privateKey, cert: certificate };
var express = require('express');
var redirectApp = express();
var redirectServer = http.createServer(redirectApp);
redirectApp.use(function requireHTTPS(req, res, next) {
if (!req.secure) {
var host = req.headers.host || 'localhost:' + config.httpPort;
var hostSplit = host.split(':');
console.log('redirect to https://' + hostSplit[0] + ':' + config.httpsPort + req.url);
return res.redirect('https://' + hostSplit[0] + ':' + config.httpsPort + req.url);
}
next();
});
redirectServer.listen(config.httpPort);
https.createServer(credentials, app).listen(config.httpsPort);
console.log('Docktor application started on HTTPs port ' + config.httpsPort);
}
// Expose app
exports = module.exports = app;
}