-
Notifications
You must be signed in to change notification settings - Fork 6
/
api
executable file
·189 lines (156 loc) · 5.2 KB
/
api
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
#!/usr/bin/env node
'use strict';
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('portal-api:server');
var http = require('http');
var path = require('path');
var fs = require('fs');
var envReader = require('portal-env'); // local npm module
var initializer = require('../routes/initializer.js');
var utils = require('../routes/utils.js');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3001');
app.set('port', port);
console.log("Portal API environment: " + app.get('env'));
const osUsername = getOsUsername();
console.log("Running as user '" + osUsername + "'");
var environment = app.get('env');
var staticConfigPath = envReader.resolveStaticConfig();
var configKey = process.env.PORTAL_CONFIG_KEY;
if (!configKey) {
// Check if we have an *envkey file.
let configKeyFileName = findEnvKeyFileName(staticConfigPath);
if (configKeyFileName) {
console.log('Found config key file ' + configKeyFileName);
configKey = fs.readFileSync(configKeyFileName, 'utf8').trim();
} else {
console.log('INFO: PORTAL_CONFIG_KEY is not set, will not be able to decrypt encrypted environment variables.');
}
}
app.set('config_key', configKey);
// Populate all the environment variables.
envReader.checkEnvironment(staticConfigPath, configKey, environment);
var staticRepo = process.env.PORTAL_API_STATIC_CONFIG;
if (!staticRepo)
throw Error('Environment variable PORTAL_API_STATIC_CONFIG not set.');
app.set('static_config', staticRepo);
debug('Static DB: ' + staticRepo);
var dynamicRepo = process.env.PORTAL_API_DYNAMIC_CONFIG;
if (!dynamicRepo)
throw Error('Environment variable PORTAL_API_DYNAMIC_CONFIG not set.');
app.set('dynamic_config', dynamicRepo);
debug('Dynamic DB: ' + dynamicRepo);
var aesKey = process.env.PORTAL_API_AESKEY;
if (!aesKey)
throw Error('Environment variable PORTAL_API_AESKEY not set. Needed for encrypting files.');
app.set('aes_key', aesKey);
debug('AES encryption key for file encryption set.');
// Check if we need to update the static DB?
try {
envReader.updateConfig(staticRepo, path.join(utils.getInitialConfigDir(), 'static'));
} catch (dbErr) {
console.error(dbErr);
console.error(dbErr.stack);
throw Error("The Configuration update steps failed. Check log files for details.");
}
// Sanity check environment variables
if (!envReader.sanityCheckDir(staticRepo))
throw Error('Environment variables are missing. Check log files for details.');
var server = null;
// How does our dynamic config look?
initializer.checkDynamicConfig(app, function (err, results) {
if (err) {
console.error('initializer.checkDynamicConfig() failed!');
console.error(err);
console.error(err.stack);
process.exit(1);
}
if (results) {
console.error('initializer.checkDynamicConfig() returned messages!');
console.error(JSON.stringify(results, null, 2));
process.exit(1);
}
// Create table of contents for contents
app.content.setup(app);
// Create HTTP server.
server = http.createServer(app);
// Listen on provided port, on all network interfaces.
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
// Graceful shutdown
const shutdown = function (signal) {
app.shuttingDown = true;
console.log("Received " + signal + ". Gracefully shutting down.");
setTimeout(process.exit, 1000);
};
process.on('SIGINT', () => shutdown("SIGINT"));
process.on('SIGTERM', () => shutdown("SIGTERM"));
});
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string' ?
'Pipe ' + port :
'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string' ?
'pipe ' + addr :
'port ' + addr.port;
console.log('Listening on ' + bind);
}
function findEnvKeyFileName(baseDir) {
var fileNames = fs.readdirSync(baseDir);
for (var i = 0; i < fileNames.length; ++i) {
var fileName = fileNames[i];
if (/[a-zA-Z0-9\._]*envkey/.test(fileName))
return path.join(baseDir, fileName);
}
return null;
}
function getOsUsername() {
var username = require('child_process').execSync("whoami", { encoding: 'utf8', timeout: 1000 });
return String(username).trim();
}