Application.cc 50.6 KB
Newer Older
1
// $Id$
2
3
4

/*************************************************************************
 * XDAQ Components for Distributed Data Acquisition                      *
5
 * Copyright (C) 2000-2020, CERN.                                        *
6
 * All rights reserved.                                                  *
7
 * Authors: J. Gutleber, L. Orsini and D. Simelevicius                   *
8
 *                                                                       *
9
10
 * For the licensing terms see LICENSE.                                  *
 * For the list of contributors see CREDITS.                             *
11
 *************************************************************************/
12
 
13
#include <sstream>
14
15
16
#include <string>
#include <regex>

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
#include "cgicc/CgiDefs.h"
#include "cgicc/Cgicc.h"
#include "cgicc/HTTPHTMLHeader.h"
#include "cgicc/HTMLClasses.h"
#include "cgicc/HTTPResponseHeader.h" 

#include "toolbox/task/WorkLoopFactory.h"
#include "toolbox/Runtime.h"
#include "toolbox/TimeVal.h"
#include "toolbox/stl.h"
#include "toolbox/regex.h"
#include "toolbox/task/TimerListener.h"
#include "toolbox/task/TimerFactory.h"

#include "xdaq/ApplicationGroup.h" 
#include "xdaq/ApplicationRegistry.h" 
#include "xdaq/ApplicationDescriptorImpl.h"

#include "xoap/domutils.h"

#include "xoap/MessageReference.h"
#include "xoap/MessageFactory.h"
#include "xoap/SOAPEnvelope.h"
#include "xoap/SOAPPart.h"
#include "xoap/SOAPBody.h"
#include "xoap/SOAPBodyElement.h"
#include "xoap/Method.h"
#include "xoap/domutils.h"
#include "xoap/DOMParser.h"
#include "xoap/SOAPHeader.h"
#include "xoap/Event.h"
#include <xercesc/util/XMLURL.hpp>
#include "xoap/DOMParserFactory.h"
#include "xoap/DOMParser.h"

#include "xgi/Table.h" 
53
#include "xgi/framework/Method.h" 
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include "xcept/tools.h"

#include "sentinel/Sentinel.h"
#include "sentinel/spotlightocci/Application.h"
#include "sentinel/spotlightocci/ExceptionEvent.h"
#include "sentinel/spotlightocci/RevokeEvent.h"

#include "xdata/exdr/Serializer.h"
#include "xdata/InfoSpaceFactory.h"
#include "xdata/exdr/FixedSizeInputStreamBuffer.h"
#include "xdata/Table.h"

#include "xdaq/XceptSerializer.h"

XDAQ_INSTANTIATOR_IMPL(sentinel::spotlightocci::Application);

70
sentinel::spotlightocci::Application::Application(xdaq::ApplicationStub* s) 
71
	: xdaq::Application(s), xgi::framework::UIManager(this),
72
	dispatcher_("urn:xdaq-workloop:spotlight", "waiting", 0.8),
73
74
	repository_(0)
{	
75
76
77
	s->getDescriptor()->setAttribute("icon", "/sentinel/spotlightocci/images/spotlight-occi-icon.png");
	s->getDescriptor()->setAttribute("icon16x16", "/sentinel/spotlightocci/images/spotlight-occi-icon.png");
	s->getDescriptor()->setAttribute("service", "sentinelspotlight2g");
78

79
	// Direct eventing addresses
80
81
	this->getApplicationInfoSpace()->fireItemAvailable("eventings", &eventings_);

82
	// Eventing addresses by pattern
83
	eventingReplicas_ = 0;
84
85
86
	this->getApplicationInfoSpace()->fireItemAvailable("eventingReplicas", &eventingReplicas_);
	this->getApplicationInfoSpace()->fireItemAvailable("eventingPattern", &eventingPattern_);

87
88
	subscribeGroup_ = "";
	this->getApplicationInfoSpace()->fireItemAvailable("subscribeGroup", &subscribeGroup_);
89

90
91
92
	jelFileName_ = "";
	this->getApplicationInfoSpace()->fireItemAvailable("jelFileName", &jelFileName_);

93
94
95
96
	// Activates work loop for dashboard asynchronous operations (SOAP messages)
	dispatcher_.addActionListener(this);
	(void) toolbox::task::getWorkLoopFactory()->getWorkLoop("urn:xdaq-workloop:spotlight", "waiting")->activate();

97
98
99
100
101

	// Set Oracle connection details
	databaseUser_ = "";
	databasePassword_ = "";
	databaseTnsName_ = "";
102
103
	oclFileName_ = "";
	this->getApplicationInfoSpace()->fireItemAvailable("oclFileName", &oclFileName_);
104
105
106
107
	this->getApplicationInfoSpace()->fireItemAvailable("databaseUser", &databaseUser_);
	this->getApplicationInfoSpace()->fireItemAvailable("databasePassword", &databasePassword_);
	this->getApplicationInfoSpace()->fireItemAvailable("databaseTnsName", &databaseTnsName_);

108
109
110
	scatterReadNum_ = 100;
	this->getApplicationInfoSpace()->fireItemAvailable("scatterReadNum", &scatterReadNum_);

111
112
113
	// Which flashlist tags to retrieve from the ws-eventing
	topic_ = "sentinel";
	this->getApplicationInfoSpace()->fireItemAvailable("topic", &topic_);
114

115
116
117
118
119
120
121
122
123
124
	scanPeriod_ = "PT10S";
	this->getApplicationInfoSpace()->fireItemAvailable("scanPeriod",&scanPeriod_);
	subscribeExpiration_ = "PT30S";
	this->getApplicationInfoSpace()->fireItemAvailable("subscribeExpiration",&subscribeExpiration_);
	dataInputSubscription_ = true;
	this->getApplicationInfoSpace()->fireItemAvailable("dataInputSubscription", &dataInputSubscription_);

	// bind SOAP interface for incoming 'notify' messages containing exceptions
	//
	b2in::nub::bind(this, &sentinel::spotlightocci::Application::onMessage );
125
126

	// bind HTTP callbacks
127
	xgi::framework::deferredbind(this, this,  &sentinel::spotlightocci::Application::Default, "Default");
128
129
	xgi::bind(this, &sentinel::spotlightocci::Application::statisticsTabPage, "statisticsTabPage");

130
131
132
133
134
135
136
	xgi::bind(this, &sentinel::spotlightocci::Application::rearm, "rearm");

	// Retrieves a complete exception. View takes two parameter
	// 'uniqueid' is the uuid of the exception to be retrieved
	// 'format' indicates the result format. The default is 'html', also 'xml' is supported.
	//
	xgi::bind(this, &sentinel::spotlightocci::Application::view, "view");
137

138
139
	// Clear all exceptions, cleanup and close files
	xgi::bind(this, &sentinel::spotlightocci::Application::reset, "reset");
140

141
142
	// DB operation
	//xgi::bind(this, &sentinel::spotlightocci::Application::files, "files");
143

144
145
146
	// Generate a test exception
	xgi::bind(this, &sentinel::spotlightocci::Application::generate, "generate");
	xgi::bind(this, &sentinel::spotlightocci::Application::inject, "inject");
147

148
149
150
151
152
	// List takes two parameters: 
	// 'timeBack' indicates how much bach in the the retrieve list should go
	// 'maxResults' indicates the maximum number of exceptions to be retrieved
	//
	xgi::bind(this, &sentinel::spotlightocci::Application::catalog, "catalog");
153

154
155
156
157
158
159
160
	// lastStoredEvents?start=<LAST STORE TIME>
	// retrieve all exceptions using storeTime field between <LAST STORE TIME> and now.
	// Return also the newest exception storeTime in the result set.
	// If start=EMPTY, return the newest exception in the database
	//
	xgi::bind(this, &sentinel::spotlightocci::Application::lastStoredEvents, "lastStoredEvents");
	xgi::bind(this, &sentinel::spotlightocci::Application::events, "events");
161
	xgi::bind(this, &sentinel::spotlightocci::Application::query, "query");
162

163
164
	// Bind setting of default parameters
	getApplicationInfoSpace()->addListener(this, "urn:xdaq-event:setDefaultValues");
165
	getApplicationContext()->addActionListener(this); // attach to endpoint available events
166

167
168
169
170
171
172
173
174
	exceptionsLostCounter_ = 0;
}

sentinel::spotlightocci::Application::~Application()
{

}

175
void sentinel::spotlightocci::Application::inject(xgi::Input * in, xgi::Output * out ) 
176
177
178
179
180
181
182
183
184
185
186
187
188
{
                                
        try                     
        {
		std::string identifier = "toolbox::exception::Test";
		std::string notifier   = "http://lxcmd113.cern.ch:9920/urn:xdaq-application:lid=10";
		std::string severity   = "error";
		std::string className   = "xmas::sensor2g::Application";
		std::string tag   = "";
		std::string instance   = "";
		std::string unamespace   = "urn:jobcontrol:jid";
		std::string uvalue   = "34";
		std::string group =  this->getApplicationDescriptor()->getAttribute("group");
189
		std::string args;
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

                cgicc::Cgicc cgi(in);
                cgicc::const_form_iterator fi = cgi.getElement("identifier");
                if (fi != cgi.getElements().end())
                {               
                        identifier = (*fi).getValue();
                }               
                                
                fi = cgi.getElement("notifier");                
                if (fi != cgi.getElements().end())
                {               
                        notifier = (*fi).getValue();
                }


                fi = cgi.getElement("severity");
                if (fi != cgi.getElements().end())
                {
                        severity = (*fi).getValue();
                }

                fi = cgi.getElement("class");
                if (fi != cgi.getElements().end())
                {
                        className = (*fi).getValue();
                }

                fi = cgi.getElement("tag");
                if (fi != cgi.getElements().end())
                {
                        tag = (*fi).getValue();
                }

                fi = cgi.getElement("instance");
                if (fi != cgi.getElements().end())
                {
                        instance = (*fi).getValue();
                }
                fi = cgi.getElement("unamespace");
                if (fi != cgi.getElements().end())
                {
                        unamespace = (*fi).getValue();
                }
                fi = cgi.getElement("uvalue");
                if (fi != cgi.getElements().end())
                {
                        uvalue = (*fi).getValue();
                }
238
239
240
241
242
                fi = cgi.getElement("args");
                if (fi != cgi.getElements().end())
                {
                        args = (*fi).getValue();
                }
243
244
245
246
		
  		xcept::Exception exception1 ( "toolbox::exception::TestLowLevel", "low level",  __FILE__, __LINE__, __FUNCTION__);
                xcept::Exception exception2(  "xoap::exception::TestMidLevel", "mid level",  __FILE__, __LINE__, __FUNCTION__, exception1);
                xcept::Exception exception3(  identifier, "this is an exception", __FILE__, __LINE__, __FUNCTION__, exception2);
247
248
249
250
                xcept::Exception exception4(  identifier, "this is an exception", __FILE__, __LINE__, __FUNCTION__, exception3);
                xcept::Exception exception5(  identifier, "this is an exception", __FILE__, __LINE__, __FUNCTION__, exception4);
                xcept::Exception exception6(  identifier, "this is an exception", __FILE__, __LINE__, __FUNCTION__, exception5);
                xcept::Exception exception7(  identifier, "this is an exception", __FILE__, __LINE__, __FUNCTION__, exception6);
251

252
253
254
255
256
257
		exception7.setProperty("notifier",notifier);
		exception7.setProperty("severity",severity);
		exception7.setProperty("urn:xdaq-application:class",className);
		exception7.setProperty("tag",tag);
		exception7.setProperty("urn:xdaq-application:instance",instance);
		exception7.setProperty(unamespace,uvalue);
258
		exception7.setProperty("urn:xdaq-application:group",group);
259
		exception7.setProperty("args",args);
260

261
                repository_->store(exception7);
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279

        }
	catch (sentinel::spotlightocci::exception::FailedToStore &se)
	{

                std::stringstream msg;
                msg << "Failed to process 'view' request, error: " << se.what();
                XCEPT_RETHROW (xgi::exception::Exception, msg.str(),se);
	}
        catch (std::exception &se)
        {
                std::stringstream msg;
                msg << "Failed to process 'view' request, error: " << se.what();
                XCEPT_RAISE (xgi::exception::Exception, msg.str());
	}
}


280
void sentinel::spotlightocci::Application::generate(xgi::Input * in, xgi::Output * out ) 
281
282
283
284
285
286
287
288
289
290
{
	static int count = 0;

	if (repository_ == 0)
	{
		XCEPT_RAISE (xgi::exception::Exception, "Failed to generate test exceptions, repository is null");
	}

	try
	{
291
		for (size_t j = 0; j < 2; ++j)
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
		{
			toolbox::TimeVal start = toolbox::TimeVal::gettimeofday();
			for (size_t i = 0; i < 2000; ++i)
			{
				++count;

				std::stringstream msg;
				msg << "This is exception number " << count;

				xcept::Exception exception1 ( "toolbox::exception::TestLowLevel", "low level",  __FILE__, __LINE__, __FUNCTION__);
				xcept::Exception exception2(  "xoap::exception::TestMidLevel", "mid level",  __FILE__, __LINE__, __FUNCTION__, exception1);
				xcept::Exception exception3(  "xdaq::exception::TestHighLevel", msg.str(), __FILE__, __LINE__, __FUNCTION__, exception2); 
				exception3.setProperty("notifier","http://lxcmd113.cern.ch:9920/urn:xdaq-application:lid=10");	
				exception3.setProperty("severity","error");
				exception3.setProperty("urn:xdaq-application:class","xmas::sensor2g::Application");
				exception3.setProperty("tag","fu");
				exception3.setProperty("urn:xdaq-application:instance","34");

				repository_->store(exception3);


				/*xcept::Exception exception4 ( "toolbox::exception::TestHighevel", "high level",  __FILE__, __LINE__, __FUNCTION__);
				exception4.setProperty("urn:tracker-fed:instance","56");
				exception4.setProperty("urn:jobcontrol:jid","5600");
                                xcept::Exception exception5(  "xoap::exception::TestMidLevel", "mid level",  __FILE__, __LINE__, __FUNCTION__, exception4);
                                exception5.setProperty("notifier","http://lxcmd113.cern.ch:9920/urn:xdaq-application:lid=10");
                                exception5.setProperty("severity","alarm");
                                exception5.setProperty("class","xmas::las2g::Application");
				exception5.setProperty("tag","");
				exception5.setProperty("urn:xdaq-application:instance","56");
				exception5.setProperty("urn:tracker-fed:instance","56");
				exception5.setProperty("urn:jobcontrol:jid","5600");

                                repository_->store(exception5);*/

				//::sleep(2);
			}

			std::cout << std::endl;
			toolbox::TimeVal stop = toolbox::TimeVal::gettimeofday();

			std::cout << "Total: " << ((double)(stop-start)) << " sec" << std::endl;
			std::cout << "Rate: " << 1/(((double)(stop-start))/2000.0) << " Hz" << std::endl;
			
		}

		std::cout << "Finished generate." << std::endl;
	}
	catch (sentinel::spotlightocci::exception::Exception& e)
	{
		out->getHTTPResponseHeader().addHeader("Content-Type", "text/html");
		XCEPT_RETHROW (xgi::exception::Exception, "Test failed", e);
	}
}

//
// Infoapace listener
//
void sentinel::spotlightocci::Application::actionPerformed( xdata::Event& event) 
{
	if (event.type() == "urn:xdaq-event:setDefaultValues")
353
	{
354
355
356
357
358
359
		if ( oclFileName_.toString() != "" ) // for backward compatibility if paramater not specified
		{
			// makes use of the credential as specified in the OCL file for the current default zone (-z zonename or XDAQ_ZONE or default)
			this->loadOCL(oclFileName_.toString());
		}

360
		b2inEventingProxy_ = new b2in::utils::ServiceProxy(this,"b2in-eventing",subscribeGroup_.toString(),this);
361
362
363

		try
		{
364
			repository_ = new sentinel::spotlightocci::Repository(this,
365
				databaseUser_.toString(), databasePassword_.toString(), databaseTnsName_.toString(), scatterReadNum_); // open for current write and read usage
366
367
368
369
370
371
		}
		catch( sentinel::spotlightocci::exception::Exception & e)
		{
			LOG4CPLUS_FATAL (this->getApplicationLogger(), xcept::stdformat_exception_history(e));
			return;
		}
372

373
374
375
376
377
		try
		{
			if (!toolbox::task::getTimerFactory()->hasTimer("spotlight"))
			{
				(void) toolbox::task::getTimerFactory()->createTimer("spotlight");
378
			}
379
380
381
382
			toolbox::task::Timer * timer = toolbox::task::getTimerFactory()->getTimer("spotlight");
			toolbox::TimeVal start;
			start = toolbox::TimeVal::gettimeofday();

383
384
385
386
387
388
389
390
			// submit scan task
			if ( dataInputSubscription_ )
			{
				toolbox::TimeInterval interval2;
				interval2.fromString(scanPeriod_);
				LOG4CPLUS_INFO (this->getApplicationLogger(), "Schedule discovery timer for " << interval2.toString());
				timer->scheduleAtFixedRate( start, this, interval2, 0, "discovery-staging" );
			}
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
		}
		catch (toolbox::task::exception::InvalidListener& e)
		{
			LOG4CPLUS_FATAL (this->getApplicationLogger(), xcept::stdformat_exception_history(e));
		}
		catch (toolbox::task::exception::InvalidSubmission& e)
		{
			LOG4CPLUS_FATAL (this->getApplicationLogger(), xcept::stdformat_exception_history(e));
		}
		catch (toolbox::task::exception::NotActive& e)
		{
			LOG4CPLUS_FATAL (this->getApplicationLogger(), xcept::stdformat_exception_history(e));
		}
		catch (toolbox::exception::Exception& e)
		{
			LOG4CPLUS_FATAL (this->getApplicationLogger(), xcept::stdformat_exception_history(e));
		}
		//
		if ( jelFileName_.toString() != "" ) // for backward compatibility if paramater not specified
		{
			this->loadJEL(jelFileName_.toString());
		}
413

414
415
416
417
418
419
420
	}
	else
	{
		LOG4CPLUS_ERROR (this->getApplicationLogger(), "Received unsupported event type '" << event.type() << "'");
	}
}
void sentinel::spotlightocci::Application::onMessage (toolbox::mem::Reference * msg, xdata::Properties & plist)
421
        
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
{
	std::string name = plist.getProperty("urn:sentinel-event:name");
	if( name != "revoke" && name != "notify" )
	{
		// unexpected message
		if(msg != 0) msg->release();
		return;
	}

	//TODO error handling
 	xdata::exdr::FixedSizeInputStreamBuffer inBuffer((char*) msg->getDataLocation(), msg->getDataSize());         
	xcept::Exception* newException = new xcept::Exception();
	xdaq::XceptSerializer::importFrom (&inBuffer, *newException);

	toolbox::Event * event;
	if ( name == "revoke")
	{
		event = new  sentinel::spotlightocci::RevokeEvent(newException,"");
	}
	else /* if (name == "notify" ) */
	{
		event = new  sentinel::spotlightocci::ExceptionEvent(newException,"");
	}
	
	 // process exception in a separate thread, to release the HTTP emebedded server
	
	if(msg != 0)  msg->release();

	toolbox::task::EventReference e(event);
	try
	{
        	dispatcher_.fireEvent (e);
	}
	catch(toolbox::task::exception::Overflow & e )
	{
        	exceptionsLostCounter_++;
        	std::stringstream msg;
        	msg << "Exceptions lost: " << exceptionsLostCounter_  << ", " << e.what() ;
        	LOG4CPLUS_FATAL  (this->getApplicationLogger(), msg.str());
       	
	}
	catch(toolbox::task::exception::OverThreshold & e )
	{
        	// message is lost, keep counting
        	exceptionsLostCounter_++;
	}
	catch(toolbox::task::exception::InternalError & e )
	{
        	// dead band ignore
        	exceptionsLostCounter_++;
        	std::stringstream msg;
        	msg << "Exceptions lost: " << exceptionsLostCounter_  << ", " << e.what() ;
        	LOG4CPLUS_FATAL  (this->getApplicationLogger(), msg.str());
	}                               
}

void sentinel::spotlightocci::Application::asynchronousExceptionNotification(xcept::Exception& e)
{
	//TODO
}

void sentinel::spotlightocci::Application::refreshSubscriptionsToEventing()
484
	
485
486
487
488
{
        if (subscriptions_.empty())
        {
                LOG4CPLUS_DEBUG (this->getApplicationLogger(), "Prepare subscription records");
489
                const xdaq::Network * network = 0;
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
                std::string networkName =  this->getApplicationDescriptor()->getAttribute("network");
                try
                {
                        network = this->getApplicationContext()->getNetGroup()->getNetwork(networkName);
                }
                catch (xdaq::exception::NoNetwork& nn)
                {
                        std::stringstream msg;
                        msg << "Failed to access b2in network " << networkName << ", not configured";
                        XCEPT_RETHROW (sentinel::exception::Exception, msg.str(), nn);
                }
                pt::Address::Reference localAddress = network->getAddress(this->getApplicationContext()->getContextDescriptor());


                std::set<std::string> topics = toolbox::parseTokenSet ( topic_.toString(), "," );
                std::set<std::string>::iterator i;
                for (i = topics.begin(); i != topics.end(); ++i)
                {
                        if ( subscriptions_.find(*i) == subscriptions_.end())
                        {
                                xdata::Properties plist;
                                toolbox::net::UUID identifier;
                                plist.setProperty("urn:b2in-protocol:service", "b2in-eventing"); // for remote dispatching

                                plist.setProperty("urn:b2in-eventing:action", "subscribe");
                                plist.setProperty("urn:b2in-eventing:id", identifier.toString());
                                plist.setProperty("urn:b2in-eventing:topic", (*i)); // Subscribe to collected data
                                plist.setProperty("urn:b2in-eventing:subscriberurl", localAddress->toString());
518
                                plist.setProperty("urn:b2in-eventing:subscriberservice", "sentinelspotlight2g");
519
                                plist.setProperty("urn:b2in-eventing:expires", subscribeExpiration_.toString("xs:duration"));
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
                                subscriptions_[(*i)] = plist;
                        }
                }
        }

        LOG4CPLUS_DEBUG (this->getApplicationLogger(), "subscribe/Renew");
        b2in::utils::MessengerCache * messengerCache = 0;
        try
        {
                messengerCache = b2inEventingProxy_->getMessengerCache();
        }
        catch(b2in::utils::exception::Exception & e)
        {
                        XCEPT_RETHROW (sentinel::exception::Exception, "cannot access messenger cache", e);
        }

	// This lock is available all the time excepted when an asynchronous send will fail and a cache invalidate is performed
        // Therefore there is no loss of efficiency.
        //

        std::list<std::string> destinations = messengerCache->getDestinations();

        for (std::list<std::string>::iterator j = destinations.begin(); j != destinations.end(); j++ )
        {
                //
                // Subscribe to OR Renew all existing subscriptions
                //
                std::map<std::string, xdata::Properties>::iterator i;
                for ( i = subscriptions_.begin(); i != subscriptions_.end(); ++i)
                {
                        try
                        {
                                // plist is already prepared for a subscribe/resubscribe message
                                //
                                LOG4CPLUS_DEBUG (this->getApplicationLogger(), "Subscribe to topic " << (*i).first << " on url " << (*j));
                                messengerCache->send((*j),0,(*i).second);
                        }
                        catch (b2in::nub::exception::InternalError & e)
                        {
                                std::stringstream msg;
                                msg << "failed to send subscription for topic (internal error) " << (*i).first << " to url " << (*j);

                                LOG4CPLUS_ERROR (this->getApplicationLogger(), msg.str());

                                XCEPT_DECLARE_NESTED(sentinel::exception::Exception, ex , msg.str(), e);
                                this->notifyQualified("fatal",ex);
                                return;
                        }
                        catch ( b2in::nub::exception::QueueFull & e )
                        {
                                std::stringstream msg;
                                msg << "failed to send subscription for topic (queue full) " << (*i).first << " to url " << (*j);

                                LOG4CPLUS_ERROR (this->getApplicationLogger(), msg.str());

                                XCEPT_DECLARE_NESTED(sentinel::exception::Exception, ex , msg.str(), e);
                                this->notifyQualified("error",ex);
                                return;
                        }
                        catch ( b2in::nub::exception::OverThreshold & e)
                        {
                                // ignore just count to avoid verbosity                                
                                std::stringstream msg;
                                msg << "failed to send subscription for topic (over threshold) " << (*i).first << " to url " << (*j);
                                LOG4CPLUS_ERROR (this->getApplicationLogger(), msg.str());
                                return;
                        }
                }
                LOG4CPLUS_DEBUG(this->getApplicationLogger(), "done with subscription");
        }
}

void sentinel::spotlightocci::Application::timeExpired(toolbox::task::TimerEvent& e)
{
594
	std::string name = e.getTimerTask()->name;
595
596
597

	if (name == "discovery-staging")
	{
598
		if (eventingList_.size() == 0)
599
		{
600
601
602
603
604
605
606
607
			try
			{
				b2inEventingProxy_->scan();
			}
			catch (b2in::utils::exception::Exception& e)
			{
				LOG4CPLUS_FATAL (this->getApplicationLogger(), xcept::stdformat_exception_history(e));
			}
608
609
610
611
612
613
614
615
616
617
		}

		try
		{
			this->refreshSubscriptionsToEventing();
		}
		catch (sentinel::exception::Exception& e)
		{
			LOG4CPLUS_FATAL (this->getApplicationLogger(), xcept::stdformat_exception_history(e));
		}
618
619
620
621
622
623
	}
}

//
// XGI SUpport
//
624
void sentinel::spotlightocci::Application::view(xgi::Input * in, xgi::Output * out ) 
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
{
	if (!repository_)
	{
		// If we are in maintenance phase, raise an exception
		XCEPT_RAISE (xgi::exception::Exception, "Repository temporarily unavailable.");
	}
	
	std::string uniqueid;
	std::string datetime = "";
	std::string format = "json"; // by default output json format
	std::string dbname = ""; // by default operate on the main database
	
	try
        {
                cgicc::Cgicc cgi(in);
		cgicc::const_form_iterator fi = cgi.getElement("uniqueid");
		if (fi != cgi.getElements().end())
		{
			uniqueid = (*fi).getValue();
		}
		else
		{
			XCEPT_RAISE (xgi::exception::Exception, "Missing 'uniqueid' parameter");
		}

		fi = cgi.getElement("datetime");		
		if (fi != cgi.getElements().end())
                {
                        datetime = (*fi).getValue();
                }

		
		fi = cgi.getElement("fmt");		
		if (fi != cgi.getElements().end())
		{
			format = (*fi).getValue();
		}
		
		fi = cgi.getElement("dbname");		
		if (fi != cgi.getElements().end())
		{
			dbname = (*fi).getValue();
		}
	}
	catch (toolbox::exception::Exception & e)
	{
		out->getHTTPResponseHeader().addHeader("Content-Type", "text/html");
                XCEPT_RETHROW(xgi::exception::Exception, "invalid time",e);

	}
	catch (std::exception &se)
	{
		std::stringstream msg;
		msg << "Failed to process 'view' request, error: " << se.what();
		XCEPT_RAISE (xgi::exception::Exception, msg.str());
	}
		
	if (format == "json")
	{		
		try
		{
			repository_->retrieve(uniqueid, datetime, format, out);
			out->getHTTPResponseHeader().addHeader("Content-Type", "text/json");
		}
		catch (sentinel::spotlightocci::exception::NotFound &e)
		{
			std::stringstream msg;
			msg << "Failed to retrieve exception '" << uniqueid << "'";
			out->getHTTPResponseHeader().addHeader("Content-Type", "text/html");
			XCEPT_RETHROW (xgi::exception::Exception, msg.str(), e);
		}
	}	
}

699
void sentinel::spotlightocci::Application::catalog(xgi::Input * in, xgi::Output * out ) 
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
{
	std::string format = "json"; // by default output json format
	std::string dbname = ""; // by default, operate on the main database

	// By default, retrieve errors from the last 1 hour
	toolbox::TimeInterval window (3600,0);
	toolbox::TimeVal start = toolbox::TimeVal::gettimeofday() - window;
	toolbox::TimeVal end = toolbox::TimeVal::gettimeofday();

	try
	{
		cgicc::Cgicc cgi(in);
		cgicc::const_form_iterator fi;
		
		fi = cgi.getElement("start");
		if (fi != cgi.getElements().end())
		{
			start.fromString((*fi).getValue(),"",toolbox::TimeVal::gmt);
		}
		
		fi = cgi.getElement("end");
		if (fi != cgi.getElements().end())
		{
			end.fromString((*fi).getValue(),"",toolbox::TimeVal::gmt);
		}
		
		fi = cgi.getElement("fmt");		
		if (fi != cgi.getElements().end())
		{
			format = (*fi).getValue();
		}
		
	}
	catch (toolbox::exception::Exception & e)
	{
		out->getHTTPResponseHeader().addHeader("Content-Type", "text/html");
                XCEPT_RETHROW(xgi::exception::Exception, "invalid time",e);

	}
	catch (const std::exception & e)
	{
		out->getHTTPResponseHeader().addHeader("Content-Type", "text/html");
                XCEPT_RAISE(xgi::exception::Exception, e.what());
	}
	
	try
	{
		repository_->catalog (out, start, end, format);		
	}
	catch (sentinel::spotlightocci::exception::NotFound& e)
	{
		out->getHTTPResponseHeader().addHeader("Content-Type", "text/html");
		XCEPT_RETHROW (xgi::exception::Exception, "Failed to retrieve data from repository", e);
	}
}

756
void sentinel::spotlightocci::Application::lastStoredEvents(xgi::Input * in, xgi::Output * out ) 
757
{
758

759
760
761
762
763
	std::string format = "json"; // by default output json format
	std::string dbname = ""; // by default, operate on the main database

	toolbox::TimeVal start = toolbox::TimeVal::gettimeofday();

764
765
766
767
768
769
770
	out->getHTTPResponseHeader().addHeader("Expires", "0");
	out->getHTTPResponseHeader().addHeader("Cache-Control",
					 "no-store, no-cache, must-revalidate, max-age=0");
	out->getHTTPResponseHeader().addHeader("Cache-Control",
					 "post-check=0, pre-check=0");
	out->getHTTPResponseHeader().addHeader("Pragma", "no-cache");

771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
	try
	{
		cgicc::Cgicc cgi(in);
		cgicc::const_form_iterator fi;
		
		fi = cgi.getElement("start");
		if (fi != cgi.getElements().end())
		{
			start.fromString((*fi).getValue(),"",toolbox::TimeVal::gmt);
		}
		
		fi = cgi.getElement("fmt");		
		if (fi != cgi.getElements().end())
		{
			format = (*fi).getValue();
		}
		
	}
	catch (toolbox::exception::Exception & e)
	{
		out->getHTTPResponseHeader().addHeader("Content-Type", "text/html");
                XCEPT_RETHROW(xgi::exception::Exception, "invalid time",e);

	}
	catch (const std::exception & e)
	{
		out->getHTTPResponseHeader().addHeader("Content-Type", "text/html");
                XCEPT_RAISE(xgi::exception::Exception, e.what());
	}
	
	try
	{
		// This function will return based on storeTime everything that is younger than 'start'
		// If there is nothing, return an empty data set, but always return the youngest store time
		//
		repository_->lastStoredEvents (out, start, format);		
	}
	catch (sentinel::spotlightocci::exception::NotFound& e)
	{
		out->getHTTPResponseHeader().addHeader("Content-Type", "text/html");
		std::cout << xcept::stdformat_exception_history(e) << std::endl;
		XCEPT_RETHROW (xgi::exception::Exception, "Failed to retrieve data from repository", e);
	}
}
//--
816
void sentinel::spotlightocci::Application::events(xgi::Input * in, xgi::Output * out ) 
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
{
	std::string format = "json"; // by default output json format
	std::string dbname = ""; // by default, operate on the main database

	// By default, retrieve errors from the last 1 hour
	toolbox::TimeInterval window (3600,0);
	toolbox::TimeVal start = toolbox::TimeVal::gettimeofday() - window;
	toolbox::TimeVal end = toolbox::TimeVal::gettimeofday();

	try
	{
		cgicc::Cgicc cgi(in);
		cgicc::const_form_iterator fi;
		
		fi = cgi.getElement("start");
		if (fi != cgi.getElements().end())
		{
			start.fromString((*fi).getValue(),"",toolbox::TimeVal::gmt);
		}
		
		fi = cgi.getElement("end");
		if (fi != cgi.getElements().end())
		{
			end.fromString((*fi).getValue(),"",toolbox::TimeVal::gmt);
		}
		
		fi = cgi.getElement("fmt");		
		if (fi != cgi.getElements().end())
		{
			format = (*fi).getValue();
		}
		
	}
	catch (toolbox::exception::Exception & e)
	{
		out->getHTTPResponseHeader().addHeader("Content-Type", "text/html");
                XCEPT_RETHROW(xgi::exception::Exception, "invalid time",e);

	}
	catch (const std::exception & e)
	{
		out->getHTTPResponseHeader().addHeader("Content-Type", "text/html");
                XCEPT_RAISE(xgi::exception::Exception, e.what());
	}
	
	try
	{
		repository_->events (out, start, end, format);		
	}
	catch (sentinel::spotlightocci::exception::NotFound& e)
	{
		out->getHTTPResponseHeader().addHeader("Content-Type", "text/html");
		XCEPT_RETHROW (xgi::exception::Exception, "Failed to retrieve data from repository", e);
	}
}

873
void sentinel::spotlightocci::Application::query(xgi::Input * in, xgi::Output * out )
874
875
876
877
878
879
880
881
882
883
884
885
886
887
{
	std::cout << "Application::query" << std::endl;
        std::string format = "json"; // by default output json format
        std::string dbname = ""; // by default, operate on the main database
	std::string statement = "";

        try
        {
                cgicc::Cgicc cgi(in);
                cgicc::const_form_iterator fi;

                fi = cgi.getElement("statement");
                if (fi != cgi.getElements().end())
                {
888
                	format = cgicc::form_urldecode((*fi).getValue()); // need to decode for coldspot
889

890
			LOG4CPLUS_DEBUG(this->getApplicationLogger(),"query is:" << format);
891
			//std::cout << "Statement received: " << format << std::endl;
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
		}
        }
        catch (toolbox::exception::Exception & e)
        {
                out->getHTTPResponseHeader().addHeader("Content-Type", "text/html");
                XCEPT_RETHROW(xgi::exception::Exception, "invalid time",e);

        }
        catch (const std::exception & e)
        {
                out->getHTTPResponseHeader().addHeader("Content-Type", "text/html");
                XCEPT_RAISE(xgi::exception::Exception, e.what());
        }

        try
        {
                repository_->query (out, format);
        }
        catch (sentinel::spotlightocci::exception::NotFound& e)
        {
                out->getHTTPResponseHeader().addHeader("Content-Type", "text/html");
                XCEPT_RETHROW (xgi::exception::Exception, "Failed to retrieve data from repository", e);
        }
}


918
//--
919
void sentinel::spotlightocci::Application::Default(xgi::Input * in, xgi::Output * out ) 
920
921
922
923
924
{	
	this->mainPage(in,out);
}

/*
925
void sentinel::spotlightocci::Application::files(xgi::Input * in, xgi::Output * out ) 
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
{	
	std::string fmt = "json"; // default
	try
	{
		cgicc::Cgicc cgi(in);
		cgicc::const_form_iterator fi = cgi.getElement("fmt");
		if (fi != cgi.getElements().end())
		{
			fmt = (*fi).getValue();
		}
	}
	catch (std::exception &se)
	{
		std::stringstream msg;
		msg << "Failed to process 'databases' request, error: " << se.what();
		XCEPT_RAISE (xgi::exception::Exception, msg.str());
	}
		
	std::vector<std::string> files = repository_->getFiles();
	std::vector<std::string>::iterator i = files.begin();
	*out << "[";
	do
	{
		*out << "\"" << (*i) << "\"";
		++i;
		if (i != files.end())
		{
			*out << ",";
		}
	} while (i != files.end());
	*out << "]";
}
*/


961
void sentinel::spotlightocci::Application::rearm(xgi::Input * in, xgi::Output * out ) 
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
{	
	std::string exception = ""; // default
	std::vector<cgicc::FormEntry> exceptions; // list of exceptions to be rearmed
	std::string user = "unknown";
	 
	try
	{
		cgicc::Cgicc cgi(in);
		
		const cgicc::CgiEnvironment& env = cgi.getEnvironment();
		user = env.getRemoteUser();
				
		cgi.getElement("exception", exceptions);
				
		if(exceptions.empty()) 
		{
		     XCEPT_RAISE (xgi::exception::Exception,"Missing exception(uuid) for rearm");
		}
		
		/* cgicc::const_form_iterator fi = cgi.getElement("exception");
		if (fi != cgi.getElements().end())
		{
			exception = (*fi).getValue();
		}
		else
		{
			XCEPT_RAISE (xgi::exception::Exception,"Missing exception(uuid) for rearm");
		}
		*/
		
	}
	catch (std::exception &se)
	{
		std::stringstream msg;
		msg << "Failed to process rearm request, error: " << se.what();
		XCEPT_RAISE (xgi::exception::Exception, msg.str());
	}

	try
	{
		if (repository_)
		{
			for(std::string::size_type i = 0; i < exceptions.size(); ++i) 
			{
				exception = exceptions[i].getValue();
				repository_->rearm(exception, user); 
1008
			}
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
		}
		else
		{
			XCEPT_RAISE (xgi::exception::Exception,"Failed to rearm exception, repository not initialized");
		}
	}
	catch (sentinel::spotlightocci::exception::FailedToStore& st)
	{
		std::stringstream msg;
		msg << "Failed to rearm exception '" << exception << "'";
		XCEPT_RETHROW(xgi::exception::Exception, msg.str(),st);
	}
}

1023
void sentinel::spotlightocci::Application::reset(xgi::Input * in, xgi::Output * out ) 
1024
1025
1026
1027
1028
1029
1030
1031
{	
	LOG4CPLUS_INFO (this->getApplicationLogger(), "Performing repository reset");
	repository_->reset();
	LOG4CPLUS_INFO (this->getApplicationLogger(), "Reset finished");	

	this->Default(in, out);
}

1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
// Load JEL
void sentinel::spotlightocci::Application::loadOCL(const std::string & fname)
{

	std::vector < std::string > files;
	try
	{
		files = toolbox::getRuntime()->expandPathName(fname);
	}
	catch (toolbox::exception::Exception& e)
	{
		std::stringstream msg;
		msg << "Failed to expand OCL filename from '" << fname << "', ";
		LOG4CPLUS_FATAL (this->getApplicationLogger(), xcept::stdformat_exception_history(e));
		return;
	}

	std::string zone = this->getApplicationContext()->getDefaultZoneName();
1050
1051
	try
	{
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
		//LOG4CPLUS_INFO (this->getApplicationLogger(), "Load OCL from '" << files[0]  << "'");
		DOMDocument* doc = xoap::getDOMParserFactory()->get("configure")->loadXML( files[0] );
		DOMNodeList* list = doc->getElementsByTagNameNS(xoap::XStr("http://xdaq.web.cern.ch/xdaq/xsd/2016/oraclecl"),xoap::XStr("XaasZone") );

		std::string defautZone = this->getApplicationContext()->getDefaultZoneName();

		for (XMLSize_t j = 0; j < list->getLength(); j++)
		{
			DOMNode* zoneNode = list->item(j);
			std::string zoneName  = xoap::getNodeAttribute (zoneNode, "zone");   // new network name

			if (defautZone == zoneName )
			{
					DOMNodeList* credentials = zoneNode->getChildNodes();
					for (unsigned int j = 0; j < credentials->getLength(); j++ )
					{
							DOMNode* c = credentials->item(j);
							if  (( c->getNodeType() == DOMNode::ELEMENT_NODE ) && ( xoap::XMLCh2String(c->getLocalName()) == "databaseUser" ))
							{
								databaseUser_ = xoap::XMLCh2String(c->getFirstChild()->getNodeValue());

							}
							else if  (( c->getNodeType() == DOMNode::ELEMENT_NODE ) && ( xoap::XMLCh2String(c->getLocalName()) == "databasePassword" ))
							{
								databasePassword_ = xoap::XMLCh2String(c->getFirstChild()->getNodeValue());

							}
							else if  (( c->getNodeType() == DOMNode::ELEMENT_NODE ) && ( xoap::XMLCh2String(c->getLocalName()) == "databaseTnsName" ))
							{
								databaseTnsName_ = xoap::XMLCh2String(c->getFirstChild()->getNodeValue());

							}
					}
					//std::cout << "found zone: " << zoneName << " in OCL"  << std::endl;
					//std::cout << "databaseUser_: " << databaseUser_.toString()  << std::endl;
					//std::cout << "databasePassword_: " << databasePassword_.toString()  << std::endl;
					//std::cout << "databaseTnsName_: " << databaseTnsName_.toString()  << std::endl;
					break;
			}


		}
		doc->release();
		//LOG4CPLUS_INFO (this->getApplicationLogger(), "Loaded OCL from '" << fname << "'");
	}
	catch (xoap::exception::Exception& e)
	{
		std::stringstream msg;
		msg << "Failed to load OCL file from '" << fname << "'";
		LOG4CPLUS_FATAL (this->getApplicationLogger(), xcept::stdformat_exception_history(e));

	}

}


1108
1109
1110
// Load JEL
void sentinel::spotlightocci::Application::loadJEL(const std::string & fname)
{
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
	std::vector < std::string > files;
	try
	{
		files = toolbox::getRuntime()->expandPathName(fname);
	}
	catch (toolbox::exception::Exception& e)
	{
		std::stringstream msg;
		msg << "Failed to expand filter filename from '" << fname << "', ";
		LOG4CPLUS_FATAL (this->getApplicationLogger(), xcept::stdformat_exception_history(e));
		return;
	}
1123

1124
1125
	try
	{
1126
1127
1128
		LOG4CPLUS_INFO (this->getApplicationLogger(), "Load JEL from '" << files[0]  << "'");
		DOMDocument* doc = xoap::getDOMParserFactory()->get("configure")->loadXML( files[0] );
		DOMNodeList* list = doc->getElementsByTagNameNS(xoap::XStr("http://xdaq.web.cern.ch/xdaq/xsd/2010/spotlight"),xoap::XStr("rule") );
1129

1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
		for (XMLSize_t j = 0; j < list->getLength(); j++)
		{
			//std::cout << "set rule:" << std::endl;
			DOMNode* node = list->item(j);
			DOMNamedNodeMap* attributes = node->getAttributes();
			xdata::Properties p;
			for (unsigned int i = 0; i < attributes->getLength(); i++ )
			{
				std::string valueStr  = xoap::XMLCh2String( attributes->item(i)->getNodeValue() );
				std::string nameStr  = xoap::XMLCh2String( attributes->item(i)->getNodeName() );
				p.setProperty(nameStr,valueStr);
				//std::cout << "attribute" << nameStr << " regexp " << valueStr << std::endl;
			}
			jel_.push_back(p);
		}
		doc->release();
		LOG4CPLUS_INFO (this->getApplicationLogger(), "Loaded JEL from '" << fname << "'");
	}
	catch (xoap::exception::Exception& e)
	{
		std::stringstream msg;
		msg << "Failed to load configuration file from '" << fname << "'";
		LOG4CPLUS_FATAL (this->getApplicationLogger(), xcept::stdformat_exception_history(e));
		
	}
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165

}

// apply Junk Exception List
bool sentinel::spotlightocci::Application::applyJEL( xcept::Exception & e)
{
	
	LOG4CPLUS_DEBUG (this->getApplicationLogger(), "check JEL rules");
	size_t labelCounter = 0;
	std::list<xdata::Properties>::iterator i;
	std::string name = e.name();
1166
1167
	for (i = jel_.begin(); i != jel_.end(); ++i)
	{ 
1168
1169
1170
		std::stringstream label;
		label << "r" << labelCounter;	
	
1171
		if ( this->match(e,(*i)) )
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
		{
			// junk exception counter
			if ( jec_.find(name) != jec_.end() )
			{
				if ( jec_[name].find(label.str()) != jec_[name].end())
				{
					jec_[name][label.str()] += 1;
				}
				else
				{
					jec_[name][label.str()] = 1;
				}
			}
			else
			{
				jec_[name][label.str()] = 1;

			}
			return true;
		}
		labelCounter++;
	}

	return false;
}

std::string sentinel::spotlightocci::Application::mapToAttributeName(const std::string & name)
{
	if ((name  == "class") || ( name == "instance") || ( name == "lid") || ( name == "context") 
		|| ( name == "group") || ( name == "service") || ( name == "zone") )
1202
	{
1203
1204
		std::string v = "urn:xdaq-application:";
		v += name;
1205
1206
		return v;
	}
1207
1208
1209
	return name;
}

1210
bool sentinel::spotlightocci::Application::match(xcept::Exception & e, std::map<std::string, std::string>& filter)
1211
{
1212
1213
	// Algorithm requires that all filter expressions match!
	//
1214
1215

	//std::cout << "apply rule" << std::endl;
1216
1217
1218
1219
1220
	std::map<std::string, std::string>::iterator i;
	for (i = filter.begin(); i != filter.end(); ++i)
	{
		try
		{
1221
1222
1223
1224
1225
1226
1227
			//--

			std::string name = this->mapToAttributeName((*i).first);
			//--
			// extract property from exception
			std::string value = e.getProperty(name);
			//std::cout << "check attribute:" << name << " regex:" << (*i).second << " on value: " << value;
1228
1229
			if ( ! toolbox::regx_match_nocase(value, (*i).second ) )
			{
1230
				//std::cout << " -> does not match" << std::endl;
1231
1232
1233
1234
1235
1236
1237
1238
1239
				return false;
			}
		}
		catch (xdata::exception::Exception& e)
		{
			// doesn't match the column name
			return false;
		}
	}
1240
	//std::cout << " -> it matches!" << std::endl;
1241
1242
	return true;
}
1243
1244
1245

void sentinel::spotlightocci::Application::actionPerformed( toolbox::Event& event) 
{
1246
1247
1248
1249
	if (event.type() == "urn:xdaq-event:profile-loaded")
	{
		LOG4CPLUS_DEBUG(this->getApplicationLogger(), "Setting proxy to b2in-eventing services " );

1250
1251
1252
1253
1254
1255
1256
		for (xdata::Vector<xdata::String>::iterator i = eventings_.begin(); i != eventings_.end(); i++)
		{
			eventingList_.push_back(i->toString());
		}

		std::string eventingPattern = eventingPattern_.toString();
		for (unsigned int i = 0; i < eventingReplicas_; ++i)
1257
		{
1258
1259
1260
			std::string s = std::to_string(i);
			std::string eventing;
			try
1261
			{
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
				eventing = std::regex_replace(eventingPattern, std::regex("#"), s);
			}
			catch (std::regex_error & e)
			{
				std::stringstream msg;
				msg << "Failed to process eventing pattern: '" << eventingPattern << "'. " << e.what();
				XCEPT_DECLARE(sentinel::spotlightocci::exception::Exception, ex, msg.str());
				LOG4CPLUS_ERROR(this->getApplicationLogger(), xcept::stdformat_exception_history(ex));
				break;
			}
			eventingList_.push_back(eventing);
		}

		for(std::string eventing : eventingList_)
		{
			try
			{
				LOG4CPLUS_DEBUG(this->getApplicationLogger(), "Adding eventing on " << eventing);
				xdata::String url(eventing);
				b2inEventingProxy_->addURL(url);
			}
			catch(b2in::utils::exception::Exception & e)
			{
				std::stringstream msg;
				msg << "Failed to add b2in-eventing address";
				XCEPT_DECLARE_NESTED(sentinel::spotlightocci::exception::Exception, ex, msg.str(),e);
				LOG4CPLUS_ERROR (this->getApplicationLogger(), xcept::stdformat_exception_history(ex));
1289
1290
1291
			}
		}
	}
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352

	if (event.type() == "urn:sentinel-spotlight:ExceptionEvent") 
	{
		// Synchronous store operation
		//
		sentinel::spotlightocci::ExceptionEvent& e = dynamic_cast<sentinel::spotlightocci::ExceptionEvent&>(event);

		// Apply antispam filter
		if ( jel_.size() != 0  && this->applyJEL(*(e.getException()) ))
		{
			// discard exception 
			//std::cout << "Discard junk exception" << std::endl;
			return;
		}	
		
		// If the DB has not yet been opened or created, open it
		try
		{
			if (repository_)
			{
				repository_->store(*(e.getException())); // After use, event and exception go away automatically
			}
			else
			{
				// Repository not initialized
				LOG4CPLUS_FATAL (this->getApplicationLogger(), "Failed to store excpetion, repository not initialized");
			}
		}
		catch (sentinel::spotlightocci::exception::FailedToStore& st)
		{
			LOG4CPLUS_FATAL (this->getApplicationLogger(), xcept::stdformat_exception_history(st));
		}
	}
	else if (event.type() == "urn:sentinel-spotlight:RevokeEvent") 
	{
		// Synchronous store operation
		//
		sentinel::spotlightocci::RevokeEvent& e = dynamic_cast<sentinel::spotlightocci::RevokeEvent&>(event);
		// If the DB has not yet been opened or created, open it
		try
		{
			if (repository_)
			{
				repository_->revoke(*(e.getException())); // After use, event and exception go away automatically
			}
			else
			{
				// Repository not initialized
				LOG4CPLUS_FATAL (this->getApplicationLogger(), "Failed to revoke exception, repository not initialized");
			}
		}
		catch (sentinel::spotlightocci::exception::FailedToStore& st)
		{
			LOG4CPLUS_FATAL (this->getApplicationLogger(), xcept::stdformat_exception_history(st));
		}

	}
	
}


1353
void sentinel::spotlightocci::Application::mainPage (xgi::Input * in, xgi::Output * out) 
1354
1355
{
	// Begin of tabs
1356
        *out << "<div class=\"xdaq-tab-wrapper\">" << std::endl;
1357
1358
  
  	// Tab 1      
1359
        *out << "<div class=\"xdaq-tab\" title=\"Hotspot\">" << std::endl;
1360
1361
1362
1363
        this->HotspotTabPage(out);
        *out << "</div>";
        
        // Tab 2
1364
        *out << "<div class=\"xdaq-tab\" title=\"Statistics\">" << std::endl;
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375

        // Make statistics an optional callback
        //this->StatisticsTabPage(out);

        std::stringstream baseurl;
		baseurl << this->getApplicationDescriptor()->getContextDescriptor()->getURL() << "/" << this->getApplicationDescriptor()->getURN();
        *out << "<button id=\"loadStatistics\" data-url=\"" << baseurl.str() << "/statisticsTabPage\">Load Statistics</button> Warning! This may take a while <img src=\"/hyperdaq/images/framework/xdaq-ajax-loader.gif\" class=\"xdaq-ajax-loader\" />";
        *out << "<br /><br /><hr /><br />" << std::endl;
        *out << "<div id=\"statisticsContent\"></div>" << std::endl;
		*out << "<script type=\"text/javascript\" src=\"/sentinel/spotlightocci/html/js/xdaq-sentinel-spotlightocci.js\"></script>" 					<< std::endl;

1376
        *out << "</div>";
1377
1378

        // Tab 3
1379
        *out << "<div class=\"xdaq-tab\" title=\"JEL\">" << std::endl;
1380
1381
        this->JELTabPage(out);
        *out << "</div>";
1382
1383
1384
1385

        *out << "</div>"; // end of tab pane
}

1386
void sentinel::spotlightocci::Application::statisticsTabPage (xgi::Input * in, xgi::Output * out) 
1387
{
1388
	if (repository_ == 0)
1389
	{
1390
1391
1392
1393
1394
		// Instead of raising, display an error message in framework - This is only triggered by a web page access anyway
		//XCEPT_RAISE(xgi::exception::Exception, "Repository unavailable.");
		XCEPT_DECLARE(xgi::exception::Exception, e, "Repository unavailable");
		*out << xcept::htmlformat_exception_history(e) << std::endl;
		return;
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
	}
	/*! Output summary page with the following information
	 
	 State of database file (opened/closed)
	 Path and filename to database
	 Last exception stored
	 Number of exceptions stored in file
	 average time to store an exception
	 theoretical average rate to store exceptions
	 average time to retrieve catalog
	 theoretical averate rate to retrieve catalog
	 average time to retrieve a single exception by uuid
	 theoretical averate rate to retrieve single exceptions by uuid
	 */
1409

1410
	*out << cgicc::table().set("class", "xdaq-table") << std::endl;
1411

1412
1413
1414
1415
	// Output the header line with the column names
	//
	*out << cgicc::thead() << std::endl;
	*out << cgicc::tr() << std::endl;
1416
1417
	*out << cgicc::th("Latest Exception") << std::endl;
	*out << cgicc::th("Oldest Exception") << std::endl;
1418
	*out << cgicc::th("# Exceptions") << std::endl;
1419
	*out << cgicc::th("Size") << std::endl;
1420
1421
1422
1423
1424
1425
	*out << cgicc::th("Read Exception Time") << std::endl;
	*out << cgicc::th("Read Catalog Time") << std::endl;
	*out << cgicc::th("Write Exception Tme") << std::endl;
	*out << cgicc::th("Read Exception Rate") << std::endl;
	*out << cgicc::th("Read Catalog Rate") << std::endl;
	*out << cgicc::th("Write Exception Rate") << std::endl;
1426
1427
	*out << cgicc::tr() << std::endl;
	*out << cgicc::thead() << std::endl;
1428

1429
	*out << cgicc::tbody() << std::endl;
1430
1431
1432

	std::list < toolbox::Properties > plist = repository_->getOpenArchivesInfo();
	for (std::list<toolbox::Properties>::iterator i = plist.begin(); i != plist.end(); i++)
1433
1434
	{
		*out << cgicc::tr() << std::endl;
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
		*out << cgicc::td((*i).getProperty("latest")) << std::endl;
		*out << cgicc::td((*i).getProperty("oldest")) << std::endl;
		*out << cgicc::td((*i).getProperty("count")) << std::endl;
		*out << cgicc::td((*i).getProperty("size")) << std::endl;
		*out << cgicc::td((*i).getProperty("readexceptiontime")) << std::endl;
		*out << cgicc::td((*i).getProperty("readcatalogtime")) << std::endl;
		*out << cgicc::td((*i).getProperty("writeexceptiontime")) << std::endl;
		*out << cgicc::td((*i).getProperty("readexceptionrate")) << std::endl;
		*out << cgicc::td((*i).getProperty("readcatalograte")) << std::endl;
		*out << cgicc::td((*i).getProperty("writeexceptionrate")) << std::endl;
1445
		*out << cgicc::tr() << std::endl;
1446

1447
	}
1448

1449
	*out << cgicc::tbody() << std::endl;
1450
1451
	*out << cgicc::table() << std::endl;

1452
	*out << cgicc::br() << std::endl;
1453

1454
	out->getHTTPResponseHeader().addHeader("Content-Type", "text/plain");
1455
}
1456

1457
void sentinel::spotlightocci::Application::JELTabPage (xgi::Output * out) 
1458
{
1459
	*out << cgicc::table().set("class", "xdaq-table") << std::endl;
1460

1461
1462
1463
1464
1465
1466
1467
1468
	// Output the header line with the column names
	//
	*out << cgicc::thead() << std::endl;
	*out << cgicc::tr() << std::endl;
	*out << cgicc::th("Name") << std::endl;
	*out << cgicc::th("Matching Rules") << std::endl;
	*out << cgicc::tr() << std::endl;
	*out << cgicc::thead() << std::endl;
1469

1470
	*out << cgicc::tbody() << std::endl;
1471

1472
1473
1474
1475
1476
1477
1478
	for (std::map<std::string, std::map<std::string, size_t> >::iterator i = jec_.begin(); i != jec_.end(); i++)
	{
		*out << cgicc::tr() << std::endl;
		*out << cgicc::td((*i).first) << std::endl;
		std::stringstream counters;
		for (std::map<std::string, size_t>::iterator j = (*i).second.begin(); j != (*i).second.end(); j++)
		{
1479
			counters << (*j).first << "(" << (*j).second << ") ";
1480
1481
1482
		}
		*out << cgicc::td(counters.str()) << std::endl;
		*out << cgicc::tr() << std::endl;
1483
1484

	}
1485
1486
1487
	*out << cgicc::tbody() << std::endl;
	*out << cgicc::table() << std::endl;

1488
1489
}

1490
void sentinel::spotlightocci::Application::HotspotTabPage (xgi::Output * out) 
1491
1492
1493
1494
{
	std::string zone = this->getApplicationContext()->getDefaultZoneName();

	std::stringstream to;
1495
	to << this->getApplicationDescriptor()->getContextDescriptor()->getURL();
1496
	std::string url = cgicc::form_urlencode(to.str());
1497

1498
1499
	*out << "<a href=\"http://xubernetes.cms/" << zone << "/hotspot/" << "\" target=\"_blank\"><button><br/><img src=\"/sentinel/images/hotspot-icon.png\" style=\"height: 80px;\"><br />Hotspot<br/><br/></button></a>";
	*out << " <a href=\"http://xubernetes.cms/" << zone << "/coldspot/" << "\" target=\"_blank\"><button><br/><img src=\"/sentinel/images/coldspot-icon.png\" style=\"height: 80px;\"><br />Coldspot<br/><br/></button></a>";
1500
}