UNPKG

11.2 kBJavaScriptView Raw
1/**
2 * File: logger.js
3 *
4 * Authors: Luis Fernando Garcia
5 * Jose Gonzalez
6 * Universidad Politéctica de Madrid (UPM)
7 *
8 * Date: 07/10/2014
9 *
10 * Description: XIMM-NAM Adapter -
11 *
12 * License:
13 *
14 * Redistribution and use in source and binary forms, with or without modification,
15 * are permitted provided that the following conditions are met:
16 *
17 * * Redistributions of source code must retain the following copyright notice,
18 * this list of conditions and the disclaimer below.
19 *
20 * Copyright (c) 2003-2008, Universidad Politécnica de Madrid (UPM)
21 *
22 * All rights reserved.
23 *
24 * * Redistribution in binary form must reproduce the above copyright notice,
25 * this list of conditions and the following disclaimer in the documentation
26 * and/or other materials provided with the distribution.
27 *
28 * * Neither the name of Universidad Politécnica de Madrid nor the names of its
29 * contributors may be used to endorse or promote products derived from this
30 * software without explicit prior written permission.
31 *
32 * You are under no obligation whatsoever to provide any enhancements to Universidad
33 * Politécnica de Madrid,or its contributors. If you choose to provide your enhance-
34 * ments, or if you choose to otherwise publish or distribute your enhancement, in
35 * source code form without contemporaneously requiring end users to enter into a
36 * separate written license agreement for such enhancements, then you thereby grant
37 * Universidad Politécnica de Madrid, its contributors, and its members a non-exclusive,
38 * royalty-free, perpetual license to copy, display, install, use, modify, prepare
39 * derivative works, incorporate into the software or other computer software, dis-
40 * tribute, and sublicense your enhancements or derivative works thereof, in binary
41 * and source code form.
42 *
43 * DISCLAIMER - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
44 * “AS IS” AND WITH ALL FAULTS. THE UNIVERSIDAD POLITECNICA DE MADRID, ITS CONTRI-
45 * BUTORS, AND ITS MEMBERS DO NOT IN ANY WAY WARRANT, GUARANTEE, OR ASSUME ANY RES-
46 * PONSIBILITY, LIABILITY OR OTHER UNDERTAKING WITH RESPECT TO THE SOFTWARE. ANY E-
47 * XPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRAN-
48 * TIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT
49 * ARE HEREBY DISCLAIMED AND THE ENTIRE RISK OF SATISFACTORY QUALITY, PERFORMANCE,
50 * ACCURACY, AND EFFORT IS WITH THE USER THEREOF. IN NO EVENT SHALL THE COPYRIGHT
51 * OWNER, CONTRIBUTORS, OR THE UNIVERSITY CORPORATION FOR ADVANCED INTERNET DEVELO-
52 * PMENT, INC. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
53 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTIT-
54 * UTE GOODS OR SERVICES; REMOVAL OR REINSTALLATION LOSS OF USE, DATA, SAVINGS OR
55 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILIT-
56 * Y, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHE-
57 * RWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRUBUTION OF THIS SOFTWARE, EVEN
58 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
59 *
60 */
61
62/**
63 * NAM-XIFI
64 * Module dependencies.
65 */
66
67
68var express = require('express')
69 , routes = require('./routes')
70 , http = require('http')
71 , path = require('path')
72 , sessionController = require('./routes/session_controller.js')
73 , userController = require('./routes/user_controller.js')
74 , partials = require ('express-partials')
75 , config = require('./config/config.json')
76 , pingctl = require('./routes/ping_controller.js')
77 , bdwControler = require('./routes/bdw_controller.js')
78 , owdControler = require('./routes/owd_controller.js')
79 , onDemandControler = require('./routes/onDemand_controller.js')
80 , schedule = require('./routes/schedule_controller.js')
81 , auth = require('./routes/authToken_controller.js')
82 , mongoose = require('mongoose')
83 , superagent = require('superagent')
84 , logger = require('./logger')
85 , nconf = require('nconf');
86
87
88//
89// Setup nconf to use (in-order):
90// 1. Command-line arguments
91// 2. Environment variables
92// 3. A file located at './config/config.json'
93//
94nconf.argv()
95 .env()
96 .file({ file: __dirname +'/config/config.json' });
97
98
99process.on('uncaughtException', function (err) {
100 logger.info('Caught exception: ' + err);
101});
102
103
104//Expose version through `pkginfo`
105
106require('pkginfo')(module, 'version');
107
108
109// Try to load the nam_adapter file `config.js` from the specified location.
110
111try {
112 logger.config.loadSync();
113}
114catch (ex) { }
115
116
117var app = express();
118var util = require('util');
119
120// all environments
121
122app.set('port', process.env.PORT || config.port_NAM_Adapter);
123app.set('views', __dirname + '/views');
124app.set('view engine', 'ejs');
125app.use(partials());
126app.use(express.favicon());
127app.use(express.logger('dev'));
128app.use(express.bodyParser());
129app.use(express.bodyParser());
130app.use(express.methodOverride());
131app.use(express.cookieParser('perfsonarPASS'));
132app.use(express.session());
133app.use(app.router);
134app.use(express.static(path.join(__dirname, 'public')));
135
136app.use(function(err, req, res, next) {
137 if (util.isError(err)) {
138 next(err);
139 } else {
140 logger.info.error(err);
141 res.redirect('/');
142 }
143 });
144
145//development only
146if ('development' == app.get('env')) {
147 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
148} else {
149 app.use(express.errorHandler());
150}
151
152// Helper:
153app.use(function(req, res, next) {
154 //req.flash()
155 //res.locals.flash = function() { return req.flash()};
156 res.locals.session = req.session;
157 next();
158});
159
160//connection database mongodb
161mongoose.connect('mongodb://localhost/NAM_adapter', function(err, res) {
162 if(err) {
163 logger.error('ERROR: connecting to Database. ' + err);
164 } else {
165 logger.info('Connected to Database');
166 }
167
168});
169
170var myToken = undefined;
171
172/**
173 * DB Modules
174 *
175**/
176
177routeTest = require('./routes/testshows')(app);
178routeHostRegister = require('./routes/hosts')(app);
179routeHostData = require('./routes/host_data')(app);
180routeRegionRegister = require('./routes/regions')(app);
181routeScheduledTest = require('./routes/scheduledMeasures')(app);
182
183
184/**
185 *
186 * Routes
187 *
188**/
189
190
191// Config Routes
192
193
194app.get('/login', sessionController.new);
195app.post('/login', sessionController.create);
196app.get('/logout', sessionController.destroy);
197
198app.get('/users', userController.index);
199app.delete('/users', userController.delUsersAll);
200
201app.get('/', routes.index);
202app.get('/config',
203 sessionController.requiresLogin,
204 routes.config);
205
206app.post('/config',
207 sessionController.requiresLogin,
208 routes.configChange);
209
210app.get('/config/owd',
211 sessionController.requiresLogin,
212 routes.owd);
213app.get('/config/bdw',
214 sessionController.requiresLogin,
215 routes.bdw);
216
217app.get('/config/packetsloss',
218 sessionController.requiresLogin,
219 routes.packetsLoss);
220
221app.get('/config/scheduled/:id',
222 sessionController.requiresLogin,
223 routes.editScheduled);
224app.put('/config/scheduled/:id',
225 sessionController.requiresLogin,
226 routes.changeScheduled);
227
228
229//Webservices - Routes
230
231//WS-Route - Ping
232app.get('/monitoring/ping/:addressHost/:format?/:count?', pingctl.ping);
233
234
235//WS-Route - On-Demand Test
236app.get('/monitoring/host2host/:typeTest/:regionIdS-:hostIdS;:regionIdD-:hostIdD',
237
238 onDemandControler.requiresAvailableRegions,
239 onDemandControler.requiresAvailableHosts,
240 onDemandControler.runTest
241);
242
243
244//WS-Route - BDW
245app.get('/monitoring/bdw/:regionD-:hostD',
246 //auth.authToken,
247 bdwControler.testbw);
248app.get('/monitoring/bdw/:regionD:hostD/:regionS:hostS',
249 //auth.authToken,
250 bdwControler.testbwSource);
251app.get('/monitoring/iperf/:ipS?', bdwControler.iperf_server);
252
253
254//WS-Route - OWD
255app.get('/monitoring/owd/:regionD-:hostD',
256 //auth.authToken,
257 owdControler.testowd);
258app.get('/monitoring/owd/:regionD-:hostD/:regionS-:hostS',
259 //auth.authToken,
260 owdControler.testOwdSource);
261app.get('/monitoring/owdserver/:time', owdControler.owd_server);
262
263//WS-Route - Schedule test
264
265app.post('/monitoring/schedule/:regionIdS-:hostIdS',
266
267 schedule.requiresAvailableHosts,
268 auth.authToken,
269 schedule.schedule
270 );
271
272
273app.post('/monitoring/schedule', schedule.scheduleTest);
274app.get('/monitoring/schedule/bdw/:regionD-:hostD', bdwControler.testbw);
275app.get('/monitoring/schedule/owd/:regionD-:hostD', owdControler.testowd);
276
277app.put('/monitoring/schedule/scheduleId', auth.authToken, schedule.killSchedule);
278
279
280//save host data
281
282//
283// Set a pid variable on `nconf`.
284//
285nconf.set('pid', process.pid);
286
287nconf.save();
288
289userController.addUser("userxifi", "userxifi", "xifiMaster2014")
290
291
292var host_data = {
293 hostId: config.hostId,
294 regionId: config.regionId,
295 type: "vm",
296 ipAddress: config.ip_address.public_ip,
297 ip_address: config.ip_address,
298
299 port_NAM: config.port_NAM_Adapter,
300 packetLoss_status: config.packetLoss_status,
301 bdw_status: config.bdw_status,
302 owd_status: config.owd_status,
303 BDW_endpoint_dest_schedule: [ config.bdw_endpoint_default ],
304
305 OWD_endpoint_dest_schedule: [ config.owd_endpoint_default ]
306
307 };
308
309// deleting all Active Scheduled Measures.
310deleteAllActiveScheduled();
311//Update Host Data from config file.
312findAndUpdateHostData(host_data)
313
314
315//Authentication IDM
316
317
318logger.info(host_data)
319
320auth.authenticate (function (status, resp) {
321
322 myToken = JSON.parse(resp).access.token;
323
324 logger.info('Success authenticating NAM. NAM Auth-token: ', myToken);
325
326 //Auto-Register Host
327
328 auth.authenticate_user (function (status, resp) {
329
330 var token = JSON.parse(resp).access.token.id;
331
332 logger.info('Success authenticating user. Auth-token: ', token);
333
334 superagent.post(config.ls_global + '/regions/')
335 .set('X-Auth-Token', token)
336 .send({
337 "link": "http://138.4.47.33:3000/monitoring",
338 "id": config.regionId
339
340
341 })
342 .end(function(error,res){
343 if(!error){
344 //logger.info("Autoregister OK");
345 }else {
346 logger.error("Error: Autoregister fail, " + error);
347 }
348
349 });
350
351 superagent.post(config.ls_global + '/nam/hosts')
352 .set('X-Auth-Token', token)
353 .send(host_data)
354 .end(function(error,res){
355
356 if(!error && res.statusCode==200){
357
358 if(res.body.hostId){
359 logger.info("Autoregister OK");}
360 else {
361 logger.info(res.body);
362 logger.info("Host already exists in NAM DB")
363 }
364 }else {
365
366 logger.error("Error: Autoregister fail, " + error);
367 }
368
369 });
370
371
372 }, function (status, err) {
373 logger.error('Error in keystone communication', err);
374 });
375
376
377
378
379}, function (status, e) {
380 logger.error('Error in keystone communication', e);
381});
382
383
384http.createServer(app).listen(app.get('port'), function(){
385 logger.info('NAM Adapter server listening on port ' + app.get('port'));
386});
387