-
Notifications
You must be signed in to change notification settings - Fork 75
/
app.js
executable file
·182 lines (155 loc) · 5.69 KB
/
app.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
// Copyright 2015, EMC, Inc.
/* jshint node: true */
"use strict";
module.exports = Runner;
var di = require('di');
var onFinished = require('on-finished');
di.annotate(Runner, new di.Provide('rest'));
di.annotate(Runner, new di.Inject(
'Services.Configuration',
'Logger',
'uuid',
'Constants',
'Protocol.Events',
'Services.Lookup',
'Errors',
'Events'
)
);
function Runner(configureFile, Logger, uuid, constants,
eventsProtocol, lookupService, Errors, events) {
var logger = Logger.initialize('TaskGraph');
var server;
function start() {
var app = require('express')();
var http = require('http');
var swaggerTools = require('swagger-tools');
var rewriter = require('express-urlrewrite');
var swaggerOptions = {
swaggerUi: '/swagger.json',
controllers: './api/rest',
// Conditionally turn on stubs (mock mode)
useStubs: process.env.NODE_ENV === 'development' ? true : false
};
// The Swagger document (require it, build it programmatically,
// fetch it from a URL, ...)
var swaggerDoc = require('./api/swagger.json');
// Initialize the Swagger middleware
swaggerTools.initializeMiddleware(swaggerDoc, function (middleware) {
//re-route common and current
//var versionPath = configuration.get('versionBase', '2.0');
app.use(require('body-parser').json({limit: '10mb'}));
app.use(rewriter('/api/current/*', '/api/2.0/$1'));
app.use(rewriter('/api/common/*', '/api/2.0/$1'));
// Imaging Event Middleware
// Interpret Swagger resources and attach metadata to request -
// must be first in swagger-tools middleware chain
app.use(middleware.swaggerMetadata());
// Validate Swagger requests
app.use(middleware.swaggerValidator());
app.use(httpEventMiddleware);
// Route validated requests to appropriate controller
app.use(middleware.swaggerRouter(swaggerOptions));
// Serve the Swagger documents and Swagger UI
app.use(middleware.swaggerUi());
// Start the server
var config = {
hostname: configureFile.get ('taskGraphEndpoint', {address: '0.0.0.0'})['address'],
httpPort: configureFile.get('taskGraphEndpoint', {port: 9005})['port']
};
server = http.createServer(app);
server.on('close', function() {
logger.info('Server Closing.');
});
server.listen(config.httpPort, config.hostname, function () {
logger.info('Your server is listening on port %d'.format(config.httpPort));
logger.info('Swagger-ui is available on http://%s:%d/docs'
.format(config.hostname, config.httpPort));
});
});
}
function stop() {
server.close();
}
function httpEventMiddleware(req, res, next) {
req._startAt = process.hrtime();
res.locals.ipAddress = remoteAddress(req);
res.locals.scope = ['global'];
res.locals.uuid = uuid.v4();
onFinished(res, function () {
if (!req._startAt) {
return '';
}
var diff = process.hrtime(req._startAt),
ms = diff[0] * 1e3 + diff[1] * 1e-6;
var data = {
ipAddress: res.locals.ipAddress
};
if (res.locals.identifier) {
data.id = res.locals.identifier;
}
logger.debug(
'http: ' + req.method +
' ' + res.statusCode +
' ' + ms.toFixed(3) +
' - ' + res.locals.uuid +
' - ' + req.originalUrl,
data
);
if(res.statusCode > 299 ){
if(configureFile.get("minLogLevel") > constants.Logging.Levels.debug){
logger.error(
'http: ' + req.method +
' ' + res.statusCode +
' ' + ms.toFixed(3) +
' - ' + res.locals.uuid +
' - ' + req.originalUrl,
data
);
}
logger.error('http: ' + JSON.stringify(res.body));
}
eventsProtocol.publishHttpResponse(
res.locals.identifier || 'external',
{
address: res.locals.ipAddress,
method: req.method,
url: req.originalUrl,
statusCode: res.statusCode,
time: ms.toFixed(3)
}
);
});
lookupService.ipAddressToNodeId(res.locals.ipAddress).then(function (nodeId) {
res.locals.identifier = nodeId;
return [ constants.Scope.Global ];
}).then(function(scope) {
res.locals.scope = scope;
}).catch(Errors.NotFoundError, function () {
// No longer log NotFoundErrors
}).catch(function (error) {
events.ignoreError(error);
}).finally(function () {
next();
});
}
function remoteAddress(req) {
if(req.get("X-Real-IP")) {
return req.get("X-Real-IP");
}
if (req.ip) {
return req.ip;
}
if (req._remoteAddress) {
return req._remoteAddress;
}
if (req.connection) {
return req.connection.remoteAddress;
}
return undefined;
}
return {
start: start,
stop: stop
};
}