-
Notifications
You must be signed in to change notification settings - Fork 4
/
server.js
executable file
·240 lines (220 loc) · 8.29 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
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
var express = require('express'),
config = require('./config'),
api = require('./APIServer'),
notifier = require('./notifier'),
cron = require('node-schedule'),
contextBroker = require('./orion_context_broker/cb_handler'),
url = require('url'),
bodyParser = require('body-parser'),
async = require('async'),
winston = require('winston'),
request = require('request'),
mkdirp = require('mkdirp');
"use strict";
var logger = new winston.Logger( {
transports: [
new winston.transports.File({
level: 'debug',
filename: './log/all-log',
colorize: false
}),
new winston.transports.Console({
level: 'info',
colorize: true
})
],
exitOnError: false
});
mkdirp('./log', function(err) {
if (err) {
logger.info('Error creating "./log" path');
}
});
var db = require(config.database);
db.init(); // Initialize the database
var app = express();
var acc_modules = {};
exports.init = function() {
app.listen(app.get('port'));
}
var notify = function(callback) {
db.getApiKeys(function(err, api_keys) {
if (err) {
return callback(err);
} else if (api_keys.length == 0){
logger.log('debug', "No data availiable");
return callback(null);
} else {
async.each(api_keys, function(api_key, callback) {
db.getResources(api_key, function(err, resources) {
if (err) {
return callback(err);
} else if (resources.length == 0) {
logger.log('debug', "No data availiable");
return callback(null);
} else {
async.each(resources, function(resource, callback) {
db.getNotificationInfo(api_key, resource, function(err, info) {
if (err) {
return callback(err);
} else {
notifier.notify(info);
return callback(null);
}
});
});
}
});
});
}
});
}
/* Create daemon to update WStore every day
* Cron format:
* [MINUTE] [HOUR] [DAY OF MONTH] [MONTH OF YEAR] [DAY OF WEEK] [YEAR (optional)]
*/
var job = cron.scheduleJob('00 00 * * *', function() {
logger.info('Sending accounting information...');
notify(function(err) {
if (err) {
logger.error('Error while notifying the WStore');
}
});
});
logger.info("Loading accounting modules...");
// Load accounting modules
for (var u in config.modules.accounting) {
try {
acc_modules[config.modules.accounting[u]] = require("./acc_modules/" + config.modules.accounting[u]).count;
} catch (e) {
logger.error("No accounting module for unit '%s': missing file acc_modules\/%s.js" + config.modules.accounting[u], config.modules.accounting[u]);
}
}
// Start ContextBroker Server for subscription notifications if it is enabled in the config
if (config.resources.contextBroker) {
logger.info("Loading module for Orion Context Broker...");
contextBroker.run();
}
notify(function(err) {
logger.info("Notifying the WStore...");
if (err){
logger.warn("Notification to the WStore failed");
}
});
// Auxiliar function for accounting
exports.count = function(user, API_KEY, publicPath, unit, response, callback) {
acc_modules[unit](response, function(err, amount) {
if (err) {
return callback(err);
} else {
db.count(user, API_KEY, publicPath, amount, function(err){
if (err) {
return callback(err);
} else {
return callback(null);
}
});
}
});
};
// Auxiliar functon that handles ContextBroker request
var CBrequestHandler = function(req, response, service, options, unit) {
var userID = req.get('X-Actor-ID');
var API_KEY = req.get('X-API-KEY');
var publicPath = req.path;
contextBroker.getOperation(service.url, req, function(err, operation) {
if (err) {
logger.error('Error obtaining the operation based on CB path %s', url.parse(options.url).pathname );
} else if (operation === 'subscribe' || operation === 'unsubscribe') { // (un)subscription request
contextBroker.requestHandler(req, response, service, unit, operation, function(err) {
if (err) {
logger.error('Error processing CB request');
}
});
} else {
request(options, function(error, resp, body) {
if (error) {
response.status(500).send(error);
logger.warn("An error ocurred requesting Context-Broker");
} else {
for (var i in resp.headers) {
response.setHeader(i, resp.headers[i])
}
exports.count(userID, API_KEY, publicPath, unit, body, function(err){
if(err) {
logger.warn("[%s] An error ocurred while making the accounting", API_KEY);
}
response.send(body);
});
}
});
}
});
}
// Auxiliar function that handles generic requests (no ContextBroker)
var requestHandler = function(req, response, options, unit) {
var userID = req.get('X-Actor-ID');
var API_KEY = req.get('X-API-KEY');
var publicPath = req.path;
request(options, function(error, resp, body) {
if (error) {
response.status(500).send(error);
logger.warn("An error ocurred requesting the endpoint");
} else {
for (var i in resp.headers) {
response.setHeader(i, resp.headers[i])
}
exports.count(userID, API_KEY, publicPath, unit, body, function(err){
if(err) {
logger.warn("[%s] An error ocurred while making the accounting", API_KEY);
}
response.send(body);
});
}
});
}
var handler = function(request, response) {
var userID = request.get('X-Actor-ID');
var API_KEY = request.get('X-API-KEY');
var publicPath = request.path;
logger.log('debug', "[%s] New request", API_KEY);
if(userID === undefined) {
logger.log('debug', "[%s] Undefined username", API_KEY);
response.status(400).json({ error: 'Undefined "X-Actor-ID" header'});
} else if (API_KEY === undefined) {
logger.log('debug', "[%s] Undefined API_KEY", API_KEY);
response.status(400).json({ error: 'Undefined "X-API-KEY" header'});
} else {
db.checkInfo(userID, API_KEY, publicPath, function(err, unit) {
if (err) {
response.status(500).end();
} else if (unit === null) { // Invalid API_KEY, user or path
response.status(401).json({ error: 'Invalid API_KEY, user or path'});
} else {
db.getService(publicPath ,function(err, service) {
if (err) {
response.status(500).end();
} else {
var options = {
url: service.url,
json: true,
method: request.method,
headers: request.headers,
body: request.body
};
if (config.resources.contextBroker && /\/(v1|v1\/registry|ngsi10|ngsi9)\/((\w+)\/?)*$/.test(url.parse(options.url).pathname)) { // Orion ContextBroker request
CBrequestHandler(request, response, service, options, unit);
} else {
requestHandler(request, response, options, unit)
}
}
});
}
});
}
};
app.set('port', config.accounting_proxy.port);
app.use(bodyParser.json());
app.use('/', handler);
api.run();
module.exports.app = app;