]> git.uio.no Git - u/mrichter/AliRoot.git/blame - HLT/trigger/AliHLTGlobalTriggerComponent.cxx
Added the possibility to prefix run numbers with a string. Can be used in correlation...
[u/mrichter/AliRoot.git] / HLT / trigger / AliHLTGlobalTriggerComponent.cxx
CommitLineData
3da1c6d7 1// $Id$
1b9a175e 2/**************************************************************************
3 * This file is property of and copyright by the ALICE HLT Project *
4 * ALICE Experiment at CERN, All rights reserved. *
5 * *
6 * Primary Authors: Artur Szostak <artursz@iafrica.com> *
7 * for The ALICE HLT Project. *
8 * *
9 * Permission to use, copy, modify and distribute this software and its *
10 * documentation strictly for non-commercial purposes is hereby granted *
11 * without fee, provided that the above copyright notice appears in all *
12 * copies and that both the copyright notice and this permission notice *
13 * appear in the supporting documentation. The authors make no claims *
14 * about the suitability of this software for any purpose. It is *
15 * provided "as is" without express or implied warranty. *
16 **************************************************************************/
17
18/// @file AliHLTGlobalTriggerComponent.cxx
19/// @author Artur Szostak <artursz@iafrica.com>
20/// @date 26 Nov 2008
21/// @brief Implementation of the AliHLTGlobalTriggerComponent component class.
22///
23/// The AliHLTGlobalTriggerComponentComponent class applies the global HLT trigger to all
24/// trigger information produced by components deriving from AliHLTTrigger.
25
26#include "AliHLTGlobalTriggerComponent.h"
e2bb8ddd 27#include "AliHLTGlobalTriggerDecision.h"
28#include "AliHLTGlobalTrigger.h"
52f67e50 29#include "AliHLTGlobalTriggerConfig.h"
30#include "AliHLTTriggerMenu.h"
474952b2 31#include "AliHLTCTPData.h"
3da1c6d7 32#include "AliCDBManager.h"
33#include "AliCDBStorage.h"
34#include "AliCDBEntry.h"
e2bb8ddd 35#include "TUUID.h"
36#include "TROOT.h"
72bc5ab0 37#include "TSystem.h"
52f67e50 38#include "TRegexp.h"
39#include "TClonesArray.h"
40#include "TObjString.h"
1b820a65 41#include "TString.h"
52f67e50 42#include "TInterpreter.h"
d4ed5215 43#include "TDatime.h"
81d62bb4 44#include "TClass.h"
d543303d 45#include "TNamed.h"
e2bb8ddd 46#include <fstream>
47#include <cerrno>
566a01d0 48#include <cassert>
81d62bb4 49#include <vector>
50#include <algorithm>
1b9a175e 51
52ClassImp(AliHLTGlobalTriggerComponent)
53
3da1c6d7 54const char* AliHLTGlobalTriggerComponent::fgkTriggerMenuCDBPath = "HLT/ConfigHLT/HLTGlobalTrigger";
55
1b9a175e 56
81d62bb4 57namespace
58{
59 /**
60 * This method is used as a comparison functor with the STL sort routines.
61 */
62 bool AliHLTDescendingNumbers(UInt_t a, UInt_t b)
63 {
64 return a > b;
65 }
66} // end of namespace
67
68
1b9a175e 69AliHLTGlobalTriggerComponent::AliHLTGlobalTriggerComponent() :
e2bb8ddd 70 AliHLTTrigger(),
52f67e50 71 fTrigger(NULL),
72bc5ab0 72 fDebugMode(false),
566a01d0 73 fRuntimeCompile(true),
81d62bb4 74 fDeleteCodeFile(false),
566a01d0 75 fCodeFileName(),
81d62bb4 76 fClassName(),
77 fCTPDecisions(NULL),
78 fBufferSizeConst(2*(sizeof(AliHLTGlobalTriggerDecision) + sizeof(AliHLTReadoutList))),
79 fBufferSizeMultiplier(1.),
80 fIncludePaths(TObjString::Class()),
1b820a65 81 fIncludeFiles(TObjString::Class()),
6598c82b 82 fLibStateAtLoad(),
3d6ea577 83 fBits(0),
84 fDataEventsOnly(true)
1b9a175e 85{
86 // Default constructor.
acc7214e 87
88 ClearInfoForNewEvent(false);
1b9a175e 89}
90
91
92AliHLTGlobalTriggerComponent::~AliHLTGlobalTriggerComponent()
93{
94 // Default destructor.
e2bb8ddd 95
96 if (fTrigger != NULL) delete fTrigger;
566a01d0 97
98 if (fCTPDecisions) {
99 fCTPDecisions->Delete();
100 delete fCTPDecisions;
101 }
1b9a175e 102}
103
104
025443e0 105void AliHLTGlobalTriggerComponent::GetOutputDataTypes(AliHLTComponentDataTypeList& list) const
106{
107 // Returns the kAliHLTDataTypeGlobalTrigger type as output.
108 list.push_back(kAliHLTDataTypeGlobalTrigger);
109}
110
111
1b9a175e 112void AliHLTGlobalTriggerComponent::GetOutputDataSize(unsigned long& constBase, double& inputMultiplier)
113{
114 // Returns the output data size estimate.
115
81d62bb4 116 constBase = fBufferSizeConst;
117 inputMultiplier = fBufferSizeMultiplier;
1b9a175e 118}
119
120
52f67e50 121Int_t AliHLTGlobalTriggerComponent::DoInit(int argc, const char** argv)
1b9a175e 122{
e2bb8ddd 123 // Initialises the global trigger component.
124
52f67e50 125 fDebugMode = false;
81d62bb4 126 fClassName = "";
127 fCodeFileName = "";
128 fDeleteCodeFile = false;
52f67e50 129 const char* configFileName = NULL;
130 const char* codeFileName = NULL;
81d62bb4 131 fIncludePaths.Clear();
132 fIncludeFiles.Clear();
6598c82b 133 SetBit(kIncludeInput);
3d6ea577 134 fDataEventsOnly = true;
52f67e50 135
136 for (int i = 0; i < argc; i++)
137 {
138 if (strcmp(argv[i], "-config") == 0)
139 {
140 if (configFileName != NULL)
141 {
142 HLTWarning("Trigger configuration macro was already specified."
143 " Will replace previous value given by -config."
144 );
145 }
146 if (argc <= i+1)
147 {
148 HLTError("The trigger configuration macro filename was not specified." );
149 return -EINVAL;
150 }
151 configFileName = argv[i+1];
152 i++;
153 continue;
154 }
155
156 if (strcmp(argv[i], "-includepath") == 0)
157 {
158 if (argc <= i+1)
159 {
160 HLTError("The include path was not specified." );
161 return -EINVAL;
162 }
81d62bb4 163 new (fIncludePaths[fIncludePaths.GetEntriesFast()]) TObjString(argv[i+1]);
52f67e50 164 i++;
165 continue;
166 }
167
168 if (strcmp(argv[i], "-include") == 0)
169 {
170 if (argc <= i+1)
171 {
172 HLTError("The include file name was not specified." );
173 return -EINVAL;
174 }
81d62bb4 175 new (fIncludeFiles[fIncludeFiles.GetEntriesFast()]) TObjString(argv[i+1]);
52f67e50 176 i++;
177 continue;
178 }
179
180 if (strcmp(argv[i], "-debug") == 0)
181 {
182 if (fDebugMode == true)
183 {
184 HLTWarning("The debug flag was already specified. Ignoring this instance.");
185 }
186 fDebugMode = true;
566a01d0 187 continue;
188 }
189
190 if (strcmp(argv[i], "-cint") == 0)
191 {
192 fRuntimeCompile = false;
52f67e50 193 continue;
194 }
195
196 if (strcmp(argv[i], "-usecode") == 0)
197 {
198 if (codeFileName != NULL)
199 {
200 HLTWarning("Custom trigger code file was already specified."
201 " Will replace previous value given by -usecode."
202 );
203 }
204 if (argc <= i+1)
205 {
206 HLTError("The custom trigger code filename was not specified." );
207 return -EINVAL;
208 }
209 codeFileName = argv[i+1];
210 if (argc <= i+2)
211 {
212 HLTError("The custom trigger class name was not specified." );
213 return -EINVAL;
214 }
81d62bb4 215 fClassName = argv[i+2];
52f67e50 216 i += 2;
217 continue;
218 }
474952b2 219
220 if (strcmp(argv[i], "-skipctp") == 0)
221 {
222 HLTInfo("Skipping CTP counters in trigger decision");
6598c82b 223 SetBit(kSkipCTP);
224 continue;
225 }
226
227 if (strcmp(argv[i], "-forward-input") == 0)
228 {
229 HLTInfo("Forwarding input objects and trigger decisions");
230 SetBit(kForwardInput);
231 SetBit(kIncludeShort);
232 SetBit(kIncludeInput, false);
233 continue;
234 }
235
d543303d 236 if (strstr(argv[i], "-include-input") == argv[i])
6598c82b 237 {
238 SetBit(kForwardInput,false);
239 TString param=argv[i];
240 param.ReplaceAll("-include-input", "");
241 if (param.CompareTo("=none")==0)
242 {
243 HLTInfo("skipping objects and trigger decisions");
244 SetBit(kIncludeShort, false);
245 SetBit(kIncludeInput, false);
246 }
247 else if (param.CompareTo("=short")==0)
248 {
d543303d 249 HLTInfo("including short info on objects and trigger decisions");
6598c82b 250 SetBit(kIncludeShort);
251 SetBit(kIncludeInput, false);
252 }
d543303d 253 else if (param.CompareTo("=both")==0)
254 {
255 HLTInfo("including input objects, trigger decisions and short info");
256 SetBit(kIncludeShort);
257 SetBit(kIncludeInput);
258 }
6598c82b 259 else if (param.CompareTo("=objects")==0 || param.IsNull())
260 {
261 HLTInfo("including input objects and trigger decisions");
262 SetBit(kIncludeShort, false);
263 SetBit(kIncludeInput);
264 }
265 else
266 {
267 HLTError("unknown parameter '%s' for argument '-include-input'", param.Data());
268 }
474952b2 269 continue;
270 }
3d6ea577 271
272 if (strcmp(argv[i], "-process-all-events") == 0)
273 {
274 fDataEventsOnly = false;
275 continue;
276 }
277
52f67e50 278 HLTError("Unknown option '%s'.", argv[i]);
279 return -EINVAL;
280 } // for loop
281
282 const AliHLTTriggerMenu* menu = NULL;
283 if (configFileName != NULL)
284 {
285 TString cmd = ".x ";
286 cmd += configFileName;
287 gROOT->ProcessLine(cmd);
288 menu = AliHLTGlobalTriggerConfig::Menu();
289 }
290
3da1c6d7 291 // Try load the trigger menu from the CDB if it is not loaded yet with the
292 // -config option
81d62bb4 293 int result = -ENOENT;
294 if (menu == NULL)
3da1c6d7 295 {
81d62bb4 296 result = LoadTriggerMenu(fgkTriggerMenuCDBPath, menu);
3da1c6d7 297 }
52f67e50 298 if (menu == NULL)
299 {
300 HLTError("No trigger menu configuration found or specified.");
81d62bb4 301 return result;
52f67e50 302 }
303
52f67e50 304 if (codeFileName == NULL)
305 {
81d62bb4 306 result = GenerateTrigger(menu, fClassName, fCodeFileName, fIncludePaths, fIncludeFiles);
307 if (result == 0) fDeleteCodeFile = true;
52f67e50 308 }
309 else
310 {
81d62bb4 311 result = LoadTriggerClass(codeFileName, fIncludePaths);
312 if (result == 0) fCodeFileName = codeFileName;
52f67e50 313 }
e2bb8ddd 314 if (result != 0) return result;
315
81d62bb4 316 fTrigger = AliHLTGlobalTrigger::CreateNew(fClassName.Data());
e2bb8ddd 317 if (fTrigger == NULL)
318 {
81d62bb4 319 HLTError("Could not create a new instance of '%s'.", fClassName.Data());
e2bb8ddd 320 return -EIO;
321 }
322
52f67e50 323 fTrigger->FillFromMenu(*menu);
325e5e42 324 if (fTrigger->CallFailed()) return -EPROTO;
474952b2 325
326 // setup the CTP accounting in AliHLTComponent
566a01d0 327 SetupCTPData();
474952b2 328
acc7214e 329 // Set the default values from the trigger menu.
330 SetDescription(menu->DefaultDescription());
331 SetTriggerDomain(menu->DefaultTriggerDomain());
332
e2bb8ddd 333 return 0;
334}
335
1b9a175e 336
e2bb8ddd 337Int_t AliHLTGlobalTriggerComponent::DoDeinit()
338{
339 // Cleans up the global trigger component.
340
341 if (fTrigger != NULL)
342 {
343 delete fTrigger;
344 fTrigger = NULL;
345 }
346
566a01d0 347 if (fCTPDecisions) {
348 fCTPDecisions->Delete();
349 delete fCTPDecisions;
350 }
351 fCTPDecisions=NULL;
81d62bb4 352
353 Int_t result = UnloadTriggerClass(fCodeFileName);
354 if (result != 0) return result;
355
356 if (fDeleteCodeFile and !fCodeFileName.IsNull() && gSystem->AccessPathName(fCodeFileName)==0 && !fDebugMode) {
357 fCodeFileName.ReplaceAll(".cxx", "*");
358 TString command="rm "; command+=fCodeFileName;
359 gSystem->Exec(command);
360 }
361 fCodeFileName="";
362 fDeleteCodeFile=false;
566a01d0 363
1b9a175e 364 return 0;
365}
4f1d6b68 366
367
368AliHLTComponent* AliHLTGlobalTriggerComponent::Spawn()
369{
370 // Creates a new object instance.
371
372 return new AliHLTGlobalTriggerComponent;
373}
374
e2bb8ddd 375
376int AliHLTGlobalTriggerComponent::DoTrigger()
377{
378 // This method will apply the global trigger decision.
379
380 if (fTrigger == NULL)
381 {
382 HLTFatal("Global trigger implementation object is NULL!");
383 return -EIO;
384 }
2974f8dc 385
386 AliHLTUInt32_t eventType=0;
387 if (!IsDataEvent(&eventType)) {
388 if (eventType==gkAliEventTypeEndOfRun) PrintStatistics(fTrigger, kHLTLogImportant, 0);
3d6ea577 389 if (fDataEventsOnly)
390 {
391 IgnoreEvent();
392 return 0;
393 }
2974f8dc 394 }
395
81d62bb4 396 // Copy the trigger counters in case we need to set them back to their original
397 // value because the PushBack method fails with ENOSPC.
398 TArrayL64 originalCounters = fTrigger->GetCounters();
325e5e42 399 if (fTrigger->CallFailed()) return -EPROTO;
81d62bb4 400
e2bb8ddd 401 fTrigger->NewEvent();
325e5e42 402 if (fTrigger->CallFailed()) return -EPROTO;
e2bb8ddd 403
404 // Fill in the input data.
405 const TObject* obj = GetFirstInputObject();
406 while (obj != NULL)
52f67e50 407 {
408 fTrigger->Add(obj, GetDataType(), GetSpecification());
325e5e42 409 if (fTrigger->CallFailed()) return -EPROTO;
52f67e50 410 obj = GetNextInputObject();
411 }
412
a489a8dd 413 // add trigger decisions for every CTP class
414 const AliHLTCTPData* pCTPData=CTPData();
415 if (pCTPData) {
566a01d0 416 AddCTPDecisions(fTrigger, pCTPData, GetTriggerData());
a489a8dd 417 }
418
52f67e50 419 // Calculate the global trigger result and trigger domain, then create and push
420 // back the new global trigger decision object.
421 TString description;
acc7214e 422 AliHLTTriggerDomain triggerDomain;
423 bool triggerResult = fTrigger->CalculateTriggerDecision(triggerDomain, description);
325e5e42 424 if (fTrigger->CallFailed()) return -EPROTO;
acc7214e 425 AliHLTGlobalTriggerDecision decision(
426 triggerResult,
427 // The following will cause the decision to be generated with default values
428 // (set in fTriggerDomain and fDescription) if the trigger result is false.
429 (triggerResult == true) ? triggerDomain : GetTriggerDomain(),
430 (triggerResult == true) ? description.Data() : GetDescription()
431 );
48d98db9 432
433 // mask the readout list according to the CTP trigger
434 // if the classes have been initialized (mask non-zero)
48d98db9 435 if (pCTPData && pCTPData->Mask()) {
436 AliHLTEventDDL eventDDL=pCTPData->ReadoutList(*GetTriggerData());
437 AliHLTReadoutList ctpreadout(eventDDL);
45398383 438 ctpreadout.Enable(AliHLTReadoutList::kHLT);
439 AliHLTReadoutList maskedList=decision.ReadoutList();
440 maskedList.AndEq(ctpreadout);
441 decision.ReadoutList(maskedList);
48d98db9 442 }
443
81d62bb4 444 decision.SetCounters(fTrigger->GetCounters(), GetEventCount()+1);
325e5e42 445 if (fTrigger->CallFailed()) return -EPROTO;
446
d4ed5215 447 static UInt_t lastTime=0;
448 TDatime time;
6eed6bca 449 if (time.Get()-lastTime>60) {
d4ed5215 450 lastTime=time.Get();
6eed6bca 451 PrintStatistics(fTrigger, kHLTLogImportant);
d4ed5215 452 }
52f67e50 453
454 // Add the input objects used to the global decision.
d543303d 455 TClonesArray* pShortInfo=NULL;
6598c82b 456 if (TestBit(kIncludeShort)) {
d543303d 457 pShortInfo=new TClonesArray(TNamed::Class(), GetNumberOfInputBlocks());
6598c82b 458 }
52f67e50 459 obj = GetFirstInputObject();
460 while (obj != NULL)
e2bb8ddd 461 {
6598c82b 462 if (TestBit(kForwardInput)) {
463 Forward(obj);
464 }
465 if (TestBit(kIncludeInput)) {
e2bb8ddd 466 if (obj->IsA() == AliHLTTriggerDecision::Class())
467 {
52f67e50 468 decision.AddTriggerInput( *static_cast<const AliHLTTriggerDecision*>(obj) );
e2bb8ddd 469 }
470 else
471 {
52f67e50 472 decision.AddInputObject(obj);
e2bb8ddd 473 }
6598c82b 474 }
d543303d 475
476 if (TestBit(kIncludeShort)) {
477 int entries=pShortInfo->GetEntriesFast();
478 new ((*pShortInfo)[entries]) TNamed(obj->GetName(), obj->GetTitle());
479 if (obj->IsA() == AliHLTTriggerDecision::Class()) {
480 (*pShortInfo)[entries]->SetBit(BIT(16)); // indicate that this is a trigger decision
481 (*pShortInfo)[entries]->SetBit(BIT(15), ((AliHLTTriggerDecision*)obj)->Result());
482 }
483 }
484
e2bb8ddd 485 obj = GetNextInputObject();
486 }
d543303d 487 if (pShortInfo) {
488 decision.AddInputObject(pShortInfo);
489 pShortInfo->Delete();
490 delete pShortInfo;
491 pShortInfo=NULL;
492 }
2974f8dc 493
6598c82b 494 if (!TestBit(kSkipCTP) && CTPData()) decision.AddInputObject(CTPData());
474952b2 495
2974f8dc 496 CreateEventDoneReadoutFilter(decision.TriggerDomain(), 3);
497 CreateEventDoneReadoutFilter(decision.TriggerDomain(), 4);
72e31932 498 if (TriggerEvent(&decision) == -ENOSPC)
81d62bb4 499 {
500 // Increase the estimated buffer space required if the PushBack methods in TriggerEvent
501 // returned the "no buffer space" error code. Also remember to set the trigger counters
502 // back to what they were, otherwise triggers will be double counted when we try to reprocess
503 // this event with larger buffers.
504 fBufferSizeConst += 1024*1024;
505 fBufferSizeMultiplier *= 2.;
506 fTrigger->SetCounters(originalCounters);
325e5e42 507 if (fTrigger->CallFailed()) return -EPROTO;
81d62bb4 508 return -ENOSPC;
509 }
510 return 0;
511}
512
513
514int AliHLTGlobalTriggerComponent::Reconfigure(const char* cdbEntry, const char* chainId)
515{
516 // Reconfigure the component by loading the trigger menu and recreating the
517 // trigger logic class.
518
519 const char* path = fgkTriggerMenuCDBPath;
520 const char* id = "(unknown)";
521 if (cdbEntry != NULL) path = cdbEntry;
522 if (chainId != NULL and chainId[0] != '\0') id = chainId;
523 HLTInfo("Reconfiguring from '%s' for chain component '%s'.", path, id);
524
525 const AliHLTTriggerMenu* menu = NULL;
526 int result = LoadTriggerMenu(path, menu);
527 if (result != 0) return result;
528
529 TString className;
530 TString codeFileName;
531 result = GenerateTrigger(menu, className, codeFileName, fIncludePaths, fIncludeFiles);
532 if (result != 0) return result;
533
534 AliHLTGlobalTrigger* trigger = AliHLTGlobalTrigger::CreateNew(className.Data());
535 if (trigger == NULL)
536 {
537 HLTError("Could not create a new instance of '%s'.", className.Data());
538 // Make sure to cleanup after the new code file.
539 UnloadTriggerClass(codeFileName);
540 if (not codeFileName.IsNull() and gSystem->AccessPathName(codeFileName)==0 and not fDebugMode)
541 {
542 codeFileName.ReplaceAll(".cxx", "*");
543 TString command="rm "; command+=codeFileName;
544 gSystem->Exec(command);
545 }
546 return -EIO;
547 }
548
549 if (fTrigger != NULL)
550 {
551 delete fTrigger;
552 fTrigger = NULL;
553 }
554
555 fTrigger = trigger;
556 fTrigger->FillFromMenu(*menu);
325e5e42 557 if (fTrigger->CallFailed()) return -EPROTO;
81d62bb4 558
559 // Set the default values from the trigger menu.
560 SetDescription(menu->DefaultDescription());
561 SetTriggerDomain(menu->DefaultTriggerDomain());
562
563 // Cleanup the old class code.
564 UnloadTriggerClass(fCodeFileName);
565 if (fDeleteCodeFile and not fCodeFileName.IsNull() and gSystem->AccessPathName(fCodeFileName)==0 and not fDebugMode)
566 {
567 fCodeFileName.ReplaceAll(".cxx", "*");
568 TString command="rm "; command+=fCodeFileName;
569 gSystem->Exec(command);
570 }
571 fCodeFileName = codeFileName;
572 fDeleteCodeFile = true; // Since we generated a new class.
573
574 return 0;
575}
576
577
578int AliHLTGlobalTriggerComponent::LoadTriggerMenu(const char* cdbPath, const AliHLTTriggerMenu*& menu)
579{
580 // Loads the trigger menu object from the CDB path.
581
582 HLTDebug("Trying to load trigger menu from '%s'.", cdbPath);
583 if (AliCDBManager::Instance() == NULL)
584 {
585 HLTError("CDB manager object not found.");
586 return -EIO;
587 }
588 AliCDBStorage* store = AliCDBManager::Instance()->GetDefaultStorage();
589 if (store == NULL)
590 {
591 HLTError("Could not get the the default storage for the CDB.");
592 return -EIO;
593 }
594 Int_t version = store->GetLatestVersion(cdbPath, GetRunNo());
595 Int_t subVersion = store->GetLatestSubVersion(cdbPath, GetRunNo(), version);
596 AliCDBEntry* entry = AliCDBManager::Instance()->Get(cdbPath, GetRunNo(), version, subVersion);
597 if (entry == NULL)
598 {
599 HLTError("Could not get the CDB entry for \"%s\".", cdbPath);
600 return -EIO;
601 }
602 TObject* obj = entry->GetObject();
603 if (obj == NULL)
604 {
605 HLTError("Configuration object for \"%s\" is missing.", cdbPath);
606 return -ENOENT;
607 }
608 if (obj->IsA() != AliHLTTriggerMenu::Class())
609 {
610 HLTError("Wrong type for configuration object in \"%s\". Found a %s but we expect a AliHLTTriggerMenu.",
611 cdbPath, obj->ClassName()
612 );
613 return -EPROTO;
614 }
615 menu = static_cast<AliHLTTriggerMenu*>(obj);
e2bb8ddd 616 return 0;
617}
618
619
52f67e50 620int AliHLTGlobalTriggerComponent::GenerateTrigger(
81d62bb4 621 const AliHLTTriggerMenu* menu, TString& name, TString& filename,
52f67e50 622 const TClonesArray& includePaths, const TClonesArray& includeFiles
623 )
e2bb8ddd 624{
625 // Generates the global trigger class that will implement the specified trigger menu.
52f67e50 626 // See header for more details.
e2bb8ddd 627
81d62bb4 628 HLTDebug("Generating custom HLT trigger class named %s using trigger menu %p.", ((void*)menu), name.Data());
629
e2bb8ddd 630 // Create a new UUID and replace the '-' characters with '_' to make it a valid
631 // C++ symbol name.
632 TUUID uuid;
633 TString uuidstr = uuid.AsString();
634 for (Int_t i = 0; i < uuidstr.Length(); i++)
635 {
636 if (uuidstr[i] == '-') uuidstr[i] = '_';
637 }
638
639 // Create the name of the new class.
640 name = "AliHLTGlobalTriggerImpl_";
641 name += uuidstr;
81d62bb4 642 filename = name + ".cxx";
e2bb8ddd 643
52f67e50 644 // Open a text file to write the code and generate the new class.
81d62bb4 645 fstream code(filename.Data(), ios_base::out | ios_base::trunc);
e2bb8ddd 646 if (not code.good())
647 {
81d62bb4 648 HLTError("Could not open file '%s' for writing.", filename.Data());
e2bb8ddd 649 return -EIO;
650 }
651
52f67e50 652 TClonesArray symbols(AliHLTTriggerMenuSymbol::Class());
653 int result = BuildSymbolList(menu, symbols);
654 if (result != 0) return result;
655
81d62bb4 656 code << "#if !defined(__CINT__) || defined(__MAKECINT__)" << endl;
52f67e50 657 code << "#include <cstring>" << endl;
658 code << "#include \"TString.h\"" << endl;
659 code << "#include \"TClonesArray.h\"" << endl;
81d62bb4 660 code << "#include \"AliHLTLogging.h\"" << endl;
e2bb8ddd 661 code << "#include \"AliHLTGlobalTrigger.h\"" << endl;
662 code << "#include \"AliHLTGlobalTriggerDecision.h\"" << endl;
52f67e50 663 code << "#include \"AliHLTDomainEntry.h\"" << endl;
664 code << "#include \"AliHLTTriggerDomain.h\"" << endl;
665 code << "#include \"AliHLTReadoutList.h\"" << endl;
666 code << "#include \"AliHLTTriggerMenu.h\"" << endl;
667 code << "#include \"AliHLTTriggerMenuItem.h\"" << endl;
668 code << "#include \"AliHLTTriggerMenuSymbol.h\"" << endl;
669
670 // Add any include files that were specified on the command line.
671 for (Int_t i = 0; i < includeFiles.GetEntriesFast(); i++)
672 {
7da191b6 673 TString file = static_cast<TObjString*>(includeFiles.UncheckedAt(i))->String();
52f67e50 674 code << "#include \"" << file.Data() << "\"" << endl;
675 }
676
81d62bb4 677 if (fDebugMode)
678 {
679 code << "#else" << endl;
680 code << "const char* gFunctionName = \"???\";" << endl;
681 code << "#define HLTDebug(msg) if (CheckFilter(kHLTLogDebug) && CheckGroup(Class_Name())) SendMessage(kHLTLogDebug, Class_Name(), ::gFunctionName, __FILE__, __LINE__, msg)" << endl;
682 }
683 code << "#endif" << endl;
684
685 code << "class " << name << " :" << endl;
686 // Add appropriate #ifdef sections since we need to prevent inheritance from
687 // AliHLTGlobalTrigger. CINT does not seem to support multiple inheritance nor
688 // multiple levels of inheritance. Neither of the following schemes worked:
689 //
690 // 1) class AliHLTGlobalTrigger : public AliHLTLogging {};
691 // class AliHLTGlobalTriggerImpl_xyz : public AliHLTGlobalTrigger {};
692 //
693 // 2) class AliHLTGlobalTrigger {};
694 // class AliHLTGlobalTriggerImpl_xyz : public AliHLTGlobalTrigger, public AliHLTLogging {};
695 //
696 // Thus, we are forced to just inherit from AliHLTLogging when running in the CINT
697 // interpreter. But we anyway have to call the global trigger implementation class
698 // through the AliHLTGlobalTriggerWrapper so this is not such a problem.
699 code << "#if !defined(__CINT__) || defined(__MAKECINT__)" << endl;
700 code << " public AliHLTGlobalTrigger," << endl;
701 code << "#endif" << endl;
702 code << " public AliHLTLogging" << endl;
e2bb8ddd 703 code << "{" << endl;
704 code << "public:" << endl;
52f67e50 705
81d62bb4 706 // Generate constructor method.
707 code << " " << name << "() :" << endl;
708 code << "#if !defined(__CINT__) || defined(__MAKECINT__)" << endl;
709 code << " AliHLTGlobalTrigger()," << endl;
710 code << "#endif" << endl;
711 code << " AliHLTLogging()";
52f67e50 712 // Write the symbols in the trigger menu in the initialisation list.
713 for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
714 {
715 code << "," << endl;
716 AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
717 code << " " << symbol->Name() << "()," << endl;
718 if (strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0)
719 {
720 code << " " << symbol->Name() << "TriggerDomain()," << endl;
721 }
722 code << " " << symbol->Name() << "DomainEntry(kAliHLTAnyDataType)";
723 }
724 for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
725 {
726 code << "," << endl << " fMenuItemDescription" << i << "()";
727 }
728 code << endl << " {" << endl;
729 if (fDebugMode)
730 {
81d62bb4 731 code << "#ifdef __CINT__" << endl;
732 code << " gFunctionName = \"" << name.Data() <<"\";" << endl;
733 code << "#endif" << endl;
52f67e50 734 code << " SetLocalLoggingLevel(kHLTLogAll);" << endl;
81d62bb4 735 code << " HLTDebug(Form(\"Creating new instance at %p.\", this));" << endl;
52f67e50 736 }
e2bb8ddd 737 code << " }" << endl;
52f67e50 738
e2bb8ddd 739 code << " virtual ~" << name << "() {" << endl;
52f67e50 740 if (fDebugMode)
741 {
81d62bb4 742 code << "#ifdef __CINT__" << endl;
743 code << " gFunctionName = \"~" << name.Data() << "\";" << endl;
744 code << "#endif" << endl;
745 code << " HLTDebug(Form(\"Deleting instance at %p.\", this));" << endl;
52f67e50 746 }
e2bb8ddd 747 code << " }" << endl;
52f67e50 748
749 // Generate the FillFromMenu method.
750 code << " virtual void FillFromMenu(const AliHLTTriggerMenu& menu) {" << endl;
751 if (fDebugMode)
752 {
81d62bb4 753 code << "#ifdef __CINT__" << endl;
754 code << " gFunctionName = \"FillFromMenu\";" << endl;
755 code << "#endif" << endl;
756 code << " HLTDebug(Form(\"Filling description entries from trigger menu for global trigger %p.\", this));" << endl;
52f67e50 757 }
81d62bb4 758 code << " fCounter.Set(menu.NumberOfItems());" << endl;
52f67e50 759 for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
760 {
761 code << " fMenuItemDescription" << i << " = (menu.Item(" << i
762 << ") != NULL) ? menu.Item(" << i << ")->Description() : \"\";" << endl;
763 }
764 if (fDebugMode)
765 {
81d62bb4 766 code << " HLTDebug(Form(\"Finished filling description entries from trigger menu.\"));" << endl;
767 code << " HLTDebug(Form(\"Filling domain entries from trigger menu symbols for global trigger %p.\", this));" << endl;
52f67e50 768 }
769 code << " for (Int_t i = 0; i < menu.SymbolArray().GetEntriesFast(); i++) {" << endl;
325e5e42 770 // 30 Oct 2009 - CINT sometimes evaluates the dynamic_cast incorrectly.
771 // Have to use the TClass system for extra protection.
772 code << " if (menu.SymbolArray().UncheckedAt(i) == NULL) continue;" << endl;
773 code << " if (menu.SymbolArray().UncheckedAt(i)->IsA() != AliHLTTriggerMenuSymbol::Class()) continue;" << endl;
52f67e50 774 code << " const AliHLTTriggerMenuSymbol* symbol = dynamic_cast<const"
775 " AliHLTTriggerMenuSymbol*>(menu.SymbolArray().UncheckedAt(i));" << endl;
776 code << " if (symbol == NULL) continue;" << endl;
777 for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
778 {
779 AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
025443e0 780 code << " if (strcmp(symbol->RealName(), \"" << symbol->RealName() << "\") == 0) {" << endl;
52f67e50 781 if (fDebugMode)
782 {
81d62bb4 783 code << " HLTDebug(Form(\"Assinging domain entry value corresponding with symbol '%s' to '%s'.\","
025443e0 784 " symbol->RealName(), symbol->BlockType().AsString().Data()));" << endl;
52f67e50 785 }
786 code << " " << symbol->Name() << "DomainEntry = symbol->BlockType();" << endl;
787 code << " continue;" << endl;
788 code << " }" << endl;
789 }
790 code << " }" << endl;
791 if (fDebugMode)
792 {
81d62bb4 793 code << " HLTDebug(Form(\"Finished filling domain entries from trigger menu symbols.\"));" << endl;
52f67e50 794 }
e2bb8ddd 795 code << " }" << endl;
52f67e50 796
797 // Generate the NewEvent method.
798 code << " virtual void NewEvent() {" << endl;
799 if (fDebugMode)
800 {
81d62bb4 801 code << "#ifdef __CINT__" << endl;
802 code << " gFunctionName = \"NewEvent\";" << endl;
803 code << "#endif" << endl;
804 code << " HLTDebug(Form(\"New event for global trigger object %p, initialising variables to default values.\", this));" << endl;
52f67e50 805 }
806 // Write code to initialise the symbols in the trigger menu to their default values.
807 for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
808 {
809 AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
81d62bb4 810 // CINT has problems with the implicit equals operator for complex types, so if
811 // the type has a equals operater we need to write the operator call explicitly.
812 TClass* clas = TClass::GetClass(symbol->Type());
813 if (clas != NULL and clas->GetMethodAny("operator=") != NULL)
814 {
815 code << " " << symbol->Name() << ".operator = (" << symbol->DefaultValue() << ");" << endl;
816 }
817 else
818 {
819 code << " " << symbol->Name() << " = " << symbol->DefaultValue() << ";" << endl;
820 }
52f67e50 821 if (strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0)
822 {
823 code << " " << symbol->Name() << "TriggerDomain.Clear();" << endl;
824 }
825 }
826 if (fDebugMode)
827 {
81d62bb4 828 code << " HLTDebug(Form(\"Finished initialising variables.\"));" << endl;
52f67e50 829 }
e2bb8ddd 830 code << " }" << endl;
52f67e50 831
832 // Generate the Add method.
833 code << " virtual void Add(const TObject* _object_, const AliHLTComponentDataType& _type_, AliHLTUInt32_t _spec_) {" << endl;
81d62bb4 834 if (fDebugMode)
835 {
836 code << "#ifdef __CINT__" << endl;
837 code << " gFunctionName = \"Add\";" << endl;
838 code << "#endif" << endl;
839 }
52f67e50 840 code << " AliHLTDomainEntry _type_spec_(_type_, _spec_);" << endl;
841 if (fDebugMode)
842 {
81d62bb4 843 code << " HLTDebug(Form(\"Adding TObject %p, with class name '%s' from data block"
52f67e50 844 " '%s', to global trigger object %p\", _object_, _object_->ClassName(),"
81d62bb4 845 " _type_spec_.AsString().Data(), this));" << endl;
52f67e50 846 code << " _object_->Print();" << endl;
847 code << " bool _object_assigned_ = false;" << endl;
848 }
849 for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
850 {
851 // Write code to check if the block type, specification and class name is correct.
852 // Then write code to assign the variable from the input object.
853 AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
854 TString expr = symbol->AssignExpression();
855 if (expr == "") continue; // Skip entries that have no assignment expression.
856 bool isTrigDecision = strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0;
857 if (fDebugMode)
858 {
859 if (isTrigDecision)
860 {
81d62bb4 861 code << " HLTDebug(Form(\"Trying to match input object to class '"
f48dcb4e 862 << symbol->ObjectClass() << "', trigger name '" << symbol->RealName()
52f67e50 863 << "' and block type '%s'\", " << symbol->Name()
81d62bb4 864 << "DomainEntry.AsString().Data()));" << endl;
52f67e50 865 }
866 else
867 {
81d62bb4 868 code << " HLTDebug(Form(\"Trying to match input object to class '"
52f67e50 869 << symbol->ObjectClass() << "' and block type '%s'\", "
81d62bb4 870 << symbol->Name() << "DomainEntry.AsString().Data()));" << endl;
52f67e50 871 }
872 }
325e5e42 873 // 30 Oct 2009 - CINT sometimes evaluates the dynamic_cast incorrectly.
874 // Have to use the TClass system for extra protection.
875 code << " const " << symbol->ObjectClass() << "* " << symbol->Name() << "_object_ = NULL;" << endl;
876 code << " if (_object_->IsA() == " << symbol->ObjectClass() << "::Class()) " << symbol->Name()
52f67e50 877 << "_object_ = dynamic_cast<const " << symbol->ObjectClass()
878 << "*>(_object_);" << endl;
81d62bb4 879 code << " if (" << symbol->Name() << "_object_ != NULL && ";
52f67e50 880 if (isTrigDecision)
881 {
882 code << "strcmp(" << symbol->Name() << "_object_->Name(), \""
e9f09f57 883 << symbol->RealName() << "\") == 0 && ";
52f67e50 884 }
885 code << symbol->Name() << "DomainEntry == _type_spec_) {" << endl;
886 TString fullname = symbol->Name();
887 fullname += "_object_";
888 expr.ReplaceAll("this", fullname);
889 code << " this->" << symbol->Name() << " = " << expr.Data() << ";" << endl;
890 if (isTrigDecision)
891 {
892 code << " this->" << symbol->Name() << "TriggerDomain = "
893 << fullname.Data() << "->TriggerDomain();" << endl;
894 }
895 if (fDebugMode)
896 {
81d62bb4 897 code << " HLTDebug(Form(\"Added TObject %p with class name '%s' to variable "
898 << symbol->Name() << "\", _object_, _object_->ClassName()));" << endl;
52f67e50 899 code << " _object_assigned_ = true;" << endl;
900 }
901 code << " }" << endl;
902 }
903 if (fDebugMode)
904 {
81d62bb4 905 code << " if (! _object_assigned_) {" << endl;
906 code << " HLTDebug(Form(\"Did not assign TObject %p"
907 " with class name '%s' to any variable.\", _object_, _object_->ClassName()));"
52f67e50 908 << endl;
81d62bb4 909 code << " }" << endl;
52f67e50 910 }
e2bb8ddd 911 code << " }" << endl;
52f67e50 912
913 // Generate the CalculateTriggerDecision method.
81d62bb4 914 // This requires code to be generated that checks which items in the trigger menu
915 // have their conditions asserted and then the trigger domain is generated from
916 // those fired items.
917 // The processing will start from the highest priority trigger group and stop
918 // after at least one trigger from the current priority group being processed
919 // is positive. For each priority group all the trigger menu items are checked.
920 // Their combined trigger condition expression must be true for the trigger priority
921 // group to be triggered positive. The full condition expression is formed by
922 // concatenating the individual condition expressions. If no trailing operators are
923 // used in the individual expressions then the default condition operator is placed
924 // between two concatenated condition expressions.
925 // If a trigger priority group has at least one trigger fired then the trigger domain
926 // is calculated such that it will give the same result as the concatenated trigger
927 // domain merging expressions for all the individual trigger menu items with
928 // positive results. Again, if no trailing operators are used in the individual
929 // merging expressions then the default domain operator is placed between two
930 // expression fragments.
52f67e50 931 code << " virtual bool CalculateTriggerDecision(AliHLTTriggerDomain& _domain_, TString& _description_) {" << endl;
932 if (fDebugMode)
933 {
81d62bb4 934 code << "#ifdef __CINT__" << endl;
935 code << " gFunctionName = \"CalculateTriggerDecision\";" << endl;
936 code << "#endif" << endl;
937 code << " HLTDebug(Form(\"Calculating global HLT trigger result with trigger object at %p.\", this));" << endl;
52f67e50 938 }
81d62bb4 939
940 // Build a list of priorities used in the trigger menu.
941 std::vector<UInt_t> priorities;
52f67e50 942 for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
943 {
944 const AliHLTTriggerMenuItem* item = menu->Item(i);
81d62bb4 945 bool priorityNotInList = std::find(priorities.begin(), priorities.end(), item->Priority()) == priorities.end();
946 if (priorityNotInList) priorities.push_back(item->Priority());
947 }
948 std::sort(priorities.begin(), priorities.end(), AliHLTDescendingNumbers);
949 // From the priority list, build the priority groups in the correct order,
950 // i.e. highest priority first.
951 // The priority group is a list of vectors of integers. The integers are the
952 // index numbers into the trigger menu item list for the items which form part
953 // of the priority group.
954 std::vector<std::vector<Int_t> > priorityGroup;
955 priorityGroup.insert(priorityGroup.begin(), priorities.size(), std::vector<Int_t>());
956 for (size_t n = 0; n < priorities.size(); n++)
957 {
958 UInt_t priority = priorities[n];
959 for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
52f67e50 960 {
81d62bb4 961 const AliHLTTriggerMenuItem* item = menu->Item(i);
962 if (item->Priority() == priority) priorityGroup[n].push_back(i);
52f67e50 963 }
81d62bb4 964 }
965
966 for (size_t n = 0; n < priorityGroup.size(); n++)
967 {
52f67e50 968 if (fDebugMode)
969 {
81d62bb4 970 code << " HLTDebug(Form(\"Processing trigger priority group " << priorities[n] << "\"));" << endl;
52f67e50 971 }
81d62bb4 972 code << " ";
973 if (n == 0) code << "UInt_t ";
974 code << "_previous_match_ = 0xFFFFFFFF;" << endl;
975 code << " ";
976 if (n == 0) code << "bool ";
977 code << "_trigger_matched_ = false;" << endl;
978 code << " ";
979 if (n == 0) code << "bool ";
980 code << "_group_result_ = false;" << endl;
981 std::vector<TString> conditionOperator;
982 conditionOperator.insert(conditionOperator.begin(), priorityGroup[n].size(), TString(""));
983 std::vector<TString> domainOperator;
984 domainOperator.insert(domainOperator.begin(), priorityGroup[n].size(), TString(""));
985 for (size_t m = 0; m < priorityGroup[n].size(); m++)
52f67e50 986 {
81d62bb4 987 UInt_t i = priorityGroup[n][m];
988 const AliHLTTriggerMenuItem* item = menu->Item(i);
989 TString triggerCondition = item->TriggerCondition();
990 TString mergeExpr = item->MergeExpression();
991 // Replace the symbols found in the trigger condition and merging expressions
992 // with appropriate compilable versions.
993 for (Int_t j = 0; j < symbols.GetEntriesFast(); j++)
994 {
995 AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(j) );
996 bool symbolNamesDifferent = strcmp(symbol->RealName(), symbol->Name()) != 0;
997 if (strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0)
998 {
999 TString newname = symbol->Name();
1000 newname += "TriggerDomain";
1001 mergeExpr.ReplaceAll(symbol->RealName(), newname);
1002 }
1003 else
1004 {
1005 if (symbolNamesDifferent) mergeExpr.ReplaceAll(symbol->RealName(), symbol->Name());
1006 }
1007 if (symbolNamesDifferent) triggerCondition.ReplaceAll(symbol->RealName(), symbol->Name());
1008 }
1009 // We allow the trigger conditions and merging expressions to have trailing operators.
1010 // Thus, we need to extract the operators and cleanup the expressions so that they will
1011 // compile. This means that we silently ignore the trailing operator if not needed.
1012 if (ExtractedOperator(triggerCondition, conditionOperator[m]))
1013 {
1014 // If the trailing operator is the same as the default operator then reset
1015 // the value in the operator list so that the default is used in the generated
1016 // code. This creates more compact code.
1017 if (conditionOperator[m] == menu->DefaultConditionOperator()) conditionOperator[m] = "";
1018 }
1019 if (ExtractedOperator(mergeExpr, domainOperator[m]))
1020 {
1021 if (domainOperator[m] == menu->DefaultDomainOperator()) domainOperator[m] = "";
1022 }
1023 if (fDebugMode)
1024 {
1025 code << " HLTDebug(Form(\"Trying trigger condition " << i
1026 << " (Description = '%s').\", fMenuItemDescription" << i << ".Data()));"
1027 << endl;
1028 }
1029 code << " ";
1030 if (n == 0 and m == 0) code << "bool ";
1031 code << "_item_result_ = false;" << endl;
1032 code << " if (" << triggerCondition << ") {" << endl;
1033 code << " ++fCounter[" << i << "];" << endl;
1034 const char* indentation = "";
1035 if (item->PreScalar() != 0)
1036 {
1037 indentation = " ";
1038 code << " if ((fCounter[" << i << "] % " << item->PreScalar() << ") == 1) {" << endl;
1039 }
1040 code << indentation << " _item_result_ = true;" << endl;
1041 if (fDebugMode)
1042 {
1043 code << indentation << " HLTDebug(Form(\"Matched trigger condition " << i
1044 << " (Description = '%s').\", fMenuItemDescription" << i << ".Data()));" << endl;
1045 }
1046 if (item->PreScalar() != 0)
1047 {
1048 code << " }" << endl;
1049 }
1050 code << " }" << endl;
1051 if (m == 0)
1052 {
1053 // Since this is the first item of the trigger group,
1054 // the generated trigger logic can be simplified a little.
1055 code << " _group_result_ = _item_result_;" << endl;
1056 code << " if (_item_result_) {" << endl;
1057 code << " _domain_ = " << mergeExpr.Data() << ";" << endl;
1058 code << " _description_ = fMenuItemDescription" << i << ";" << endl;
1059 code << " _previous_match_ = " << i << ";" << endl;
1060 code << " _trigger_matched_ = true;" << endl;
1061 code << " }" << endl;
1062 }
1063 else
1064 {
325e5e42 1065 if (conditionOperator[m-1] == "")
81d62bb4 1066 {
1067 code << " _group_result_ = _group_result_ "
1068 << menu->DefaultConditionOperator() << " _item_result_;" << endl;
1069 }
1070 else
1071 {
325e5e42 1072 code << " _group_result_ = _group_result_ "
1073 << conditionOperator[m-1] << " _item_result_;" << endl;
81d62bb4 1074 }
1075 code << " if (_item_result_) {" << endl;
1076 code << " if (_trigger_matched_) {" << endl;
325e5e42 1077 bool switchWillBeEmpty = true;
81d62bb4 1078 for (size_t k = 0; k < m; k++)
1079 {
1080 if (domainOperator[k] == "") continue;
1081 switchWillBeEmpty = false;
1082 }
1083 if (switchWillBeEmpty)
1084 {
1085 code << " _domain_ = _domain_ " << menu->DefaultDomainOperator() << " "
1086 << mergeExpr.Data() << ";" << endl;
1087 }
1088 else
1089 {
1090 code << " switch(_previous_match_) {" << endl;
1091 for (size_t k = 0; k < m; k++)
1092 {
1093 if (domainOperator[k] == "") continue;
1094 code << " case " << k << ": _domain_ = _domain_ "
1095 << domainOperator[k] << " " << mergeExpr.Data() << "; break;" << endl;
1096 }
1097 code << " default: _domain_ = _domain_ "
1098 << menu->DefaultDomainOperator() << " " << mergeExpr.Data() << ";" << endl;
1099 code << " }" << endl;
1100 }
1101 code << " _description_ += \",\";" << endl;
1102 code << " _description_ += fMenuItemDescription" << i << ";" << endl;
1103 code << " } else {" << endl;
1104 code << " _domain_ = " << mergeExpr.Data() << ";" << endl;
1105 code << " _description_ = fMenuItemDescription" << i << ";" << endl;
1106 code << " }" << endl;
1107 code << " _previous_match_ = " << i << ";" << endl;
1108 code << " _trigger_matched_ = true;" << endl;
1109 code << " }" << endl;
1110 }
52f67e50 1111 }
81d62bb4 1112 code << " if (_group_result_) {" << endl;
52f67e50 1113 if (fDebugMode)
1114 {
81d62bb4 1115 if (n < priorities.size() - 1)
1116 {
1117 code << " HLTDebug(Form(\"Matched triggers in trigger priority group " << priorities[n]
1118 << ". Stopping processing here because all other trigger groups have lower priority.\"));" << endl;
1119 }
1120 else
1121 {
1122 code << " HLTDebug(Form(\"Matched triggers in trigger priority group " << priorities[n] << ".\"));" << endl;
1123 }
52f67e50 1124 }
81d62bb4 1125 code << " return true;" << endl;
52f67e50 1126 code << " }" << endl;
1127 }
81d62bb4 1128 code << " _domain_.Clear();" << endl;
1129 code << " _description_ = \"\";" << endl;
1130 code << " return false;" << endl;
e2bb8ddd 1131 code << " }" << endl;
52f67e50 1132
81d62bb4 1133 // Generate getter and setter methods for the counters.
1134 code << " const TArrayL64& GetCounters() const { return fCounter; }" << endl;
1135 code << " void SetCounters(const TArrayL64& counters) { fCounter = counters; }" << endl;
52f67e50 1136
e2bb8ddd 1137 code << "private:" << endl;
52f67e50 1138 // Add the symbols in the trigger menu to the list of private variables.
1139 for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
1140 {
1141 AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
1142 code << " " << symbol->Type() << " " << symbol->Name() << ";" << endl;
1143 if (strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0)
1144 {
1145 code << " AliHLTTriggerDomain " << symbol->Name() << "TriggerDomain;" << endl;
1146 }
1147 code << " AliHLTDomainEntry " << symbol->Name() << "DomainEntry;" << endl;
1148 }
1149 for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
1150 {
1151 code << " TString fMenuItemDescription" << i << ";" << endl;
1152 }
81d62bb4 1153 code << " TArrayL64 fCounter;" << endl;
1154 code << "#if !defined(__CINT__) || defined(__MAKECINT__)" << endl;
1155 code << " ClassDef(" << name.Data() << ", 0)" << endl;
1156 code << "#else" << endl;
1157 code << " virtual const char* Class_Name() const { return \"" << name.Data() << "\"; }" << endl;
1158 code << "#endif" << endl;
e2bb8ddd 1159 code << "};" << endl;
81d62bb4 1160 code << "#if !defined(__CINT__) || defined(__MAKECINT__)" << endl;
1161 code << "ClassImp(" << name.Data() << ")" << endl;
1162 code << "#endif" << endl;
e2bb8ddd 1163
1164 code.close();
1165
52f67e50 1166 // Now we need to compile and load the new class.
81d62bb4 1167 result = LoadTriggerClass(filename, includePaths);
52f67e50 1168 return result;
1169}
1170
1171
1172int AliHLTGlobalTriggerComponent::LoadTriggerClass(
1173 const char* filename, const TClonesArray& includePaths
1174 )
1175{
1176 // Loads the code for a custom global trigger class implementation on the fly.
1177
81d62bb4 1178 HLTDebug("Loading HLT trigger class from file '%s'.", filename);
1179
52f67e50 1180 TString compiler = gSystem->GetBuildCompilerVersion();
566a01d0 1181 if (fRuntimeCompile && (compiler.Contains("gcc") or compiler.Contains("icc")))
1182 {
1183 TString includePath;
1184#if defined(PKGINCLUDEDIR)
1185 // this is especially for the HLT build system where the package is installed
1186 // in a specific directory including proper treatment of include files
1187 includePath.Form("-I%s", PKGINCLUDEDIR);
1188#else
1189 // the default AliRoot behavior, all include files can be found in the
1190 // $ALICE_ROOT subfolders
1191 includePath = "-I${ALICE_ROOT}/include -I${ALICE_ROOT}/HLT/BASE -I${ALICE_ROOT}/HLT/trigger";
1192#endif
52f67e50 1193 // Add any include paths that were specified on the command line.
1194 for (Int_t i = 0; i < includePaths.GetEntriesFast(); i++)
1195 {
7da191b6 1196 TString path = static_cast<TObjString*>(includePaths.UncheckedAt(i))->String();
81d62bb4 1197 includePath += " -I";
52f67e50 1198 includePath += path;
1199 }
81d62bb4 1200 HLTDebug("using include settings: %s", includePath.Data());
52f67e50 1201 gSystem->SetIncludePath(includePath);
1202 gSystem->SetFlagsOpt("-O3 -DNDEBUG");
1203 gSystem->SetFlagsDebug("-g3 -DDEBUG -D__DEBUG");
1204
1205 int result = kTRUE;
1206 if (fDebugMode)
1207 {
1208 result = gSystem->CompileMacro(filename, "g");
1209 }
1210 else
1211 {
1212 result = gSystem->CompileMacro(filename, "O");
1213 }
1214 if (result != kTRUE)
1215 {
1216 HLTFatal("Could not compile and load global trigger menu implementation.");
1217 return -ENOENT;
1218 }
1219 }
1220 else
1221 {
1b820a65 1222 // Store the library state to be checked later in UnloadTriggerClass.
1223 fLibStateAtLoad = gSystem->GetLibraries();
1224
52f67e50 1225 // If we do not support the compiler then try interpret the class instead.
81d62bb4 1226 TString cmd = ".L ";
52f67e50 1227 cmd += filename;
1228 Int_t errorcode = TInterpreter::kNoError;
1229 gROOT->ProcessLine(cmd, &errorcode);
1230 if (errorcode != TInterpreter::kNoError)
1231 {
1232 HLTFatal("Could not load interpreted global trigger menu implementation"
1233 " (Interpreter error code = %d).",
1234 errorcode
1235 );
1236 return -ENOENT;
1237 }
1238 }
1239
1240 return 0;
1241}
1242
1243
81d62bb4 1244int AliHLTGlobalTriggerComponent::UnloadTriggerClass(const char* filename)
1245{
1246 // Unloads the code previously loaded by LoadTriggerClass.
1247
1248 HLTDebug("Unloading HLT trigger class in file '%s'.", filename);
1249
1250 TString compiler = gSystem->GetBuildCompilerVersion();
1251 if (fRuntimeCompile && (compiler.Contains("gcc") or compiler.Contains("icc")))
1252 {
1b820a65 1253 // Generate the library name.
81d62bb4 1254 TString libname = filename;
1255 Ssiz_t dotpos = libname.Last('.');
1256 if (0 <= dotpos and dotpos < libname.Length()) libname[dotpos] = '_';
1257 libname += ".";
1258 libname += gSystem->GetSoExt();
1259
1b820a65 1260 // This is a workaround for a problem with unloading shared libraries in ROOT.
1261 // If the trigger logic library is loaded before the libAliHLTHOMER.so library
1262 // or any other library is loaded afterwards, then during the gInterpreter->UnloadFile
1263 // call all the subsequent libraries get unloded. This means that any objects created
1264 // from classes implemented in the libAliHLTHOMER.so library will generate segfaults
1265 // since the executable code has been unloaded.
1266 // We need to check if there are any more libraries loaded after the class we
1267 // are unloading and in that case don't unload the class.
1268 TString libstring = gSystem->GetLibraries();
1269 TString token, lastlib;
1270 Ssiz_t from = 0;
1271 Int_t numOfLibs = 0, posOfLib = -1;
1272 while (libstring.Tokenize(token, from, " "))
1273 {
1274 ++numOfLibs;
1275 lastlib = token;
1276 if (token.Contains(libname)) posOfLib = numOfLibs;
1277 }
1278 if (numOfLibs != posOfLib)
1279 {
1280 HLTWarning(Form("ROOT limitation! Cannot properly cleanup and unload the shared"
1281 " library '%s' since another library '%s' was loaded afterwards. Trying to"
1282 " unload this library will remove the others and lead to serious memory faults.",
1283 libname.Data(), lastlib.Data()
1284 ));
1285 return 0;
1286 }
1287
81d62bb4 1288 char* path = NULL;
1289 int result = 0;
1290 if ((path = gSystem->DynamicPathName(libname)) != NULL)
1291 {
1292 result = gInterpreter->UnloadFile(path);
1293 delete [] path;
1294 }
1295 if (result != TInterpreter::kNoError) return -ENOENT;
1296 }
1297 else
1298 {
1b820a65 1299 // This is again a workaround for the problem with unloading files in ROOT.
1300 // If the trigger logic class is loaded before the libAliHLTHOMER.so library
1301 // or any other library is loaded afterwards, then during the gInterpreter->UnloadFile
1302 // call all the subsequent libraries get unloded.
1303 // We need to check if the list of loaded libraries has changed since the last
1304 // call to LoadTriggerClass. If it has then don't unload the class.
1305 if (fLibStateAtLoad != gSystem->GetLibraries())
1306 {
1307 TString libstring = gSystem->GetLibraries();
1308 TString token;
1309 Ssiz_t from = 0;
1310 while (libstring.Tokenize(token, from, " "))
1311 {
1312 if (not fLibStateAtLoad.Contains(token)) break;
1313 }
1314 HLTWarning(Form("ROOT limitation! Cannot properly cleanup and unload the file"
1315 " '%s' since another library '%s' was loaded afterwards. Trying to unload"
1316 " this file will remove the other library and lead to serious memory faults.",
1317 filename, token.Data()
1318 ));
1319 return 0;
1320 }
1321
1322 // If we did not compile the trigger logic then remove the interpreted class.
81d62bb4 1323 TString cmd = ".U ";
1324 cmd += filename;
1325 Int_t errorcode = TInterpreter::kNoError;
1326 gROOT->ProcessLine(cmd, &errorcode);
1327 if (errorcode != TInterpreter::kNoError)
1328 {
1329 HLTFatal("Could not unload interpreted global trigger menu implementation"
1330 " (Interpreter error code = %d).",
1331 errorcode
1332 );
1333 return -ENOENT;
1334 }
1335 }
1336
1337 return 0;
1338}
1339
1340
52f67e50 1341int AliHLTGlobalTriggerComponent::FindSymbol(const char* name, const TClonesArray& list)
1342{
1343 // Searches for the named symbol in the given list.
1344 // See header for more details.
1345
1346 for (int i = 0; i < list.GetEntriesFast(); i++)
1347 {
1348 const AliHLTTriggerMenuSymbol* symbol = dynamic_cast<const AliHLTTriggerMenuSymbol*>( list.UncheckedAt(i) );
1349 if (symbol == NULL) continue;
1350 if (strcmp(symbol->Name(), name) == 0) return i;
1351 }
1352 return -1;
1353}
1354
1355
1356int AliHLTGlobalTriggerComponent::BuildSymbolList(const AliHLTTriggerMenu* menu, TClonesArray& list)
1357{
1358 // Builds the list of symbols to use in the custom global trigger menu
1359 // implementation class.
1360 // See header for more details.
1361
025443e0 1362 // Note: when we build the symbol list we must use the symbol name as returned
1363 // by the Name() method and not the RealName() method when using FindSymbol.
1364 // This is so that we avoid problems with the generated code not compiling
1365 // because names like "abc-xyz" and "abc_xyz" are synonymous.
1366 // Name() returns the converted C++ symbol name as used in the generated code.
1367
52f67e50 1368 for (UInt_t i = 0; i < menu->NumberOfSymbols(); i++)
1369 {
1370 const AliHLTTriggerMenuSymbol* symbol = menu->Symbol(i);
1371 if (FindSymbol(symbol->Name(), list) != -1)
1372 {
1373 HLTError("Multiple symbols with the name '%s' defined in the trigger menu.", symbol->Name());
1374 return -EIO;
1375 }
1376 new (list[list.GetEntriesFast()]) AliHLTTriggerMenuSymbol(*symbol);
1377 }
1378
f48dcb4e 1379 TRegexp exp("[_a-zA-Z][-_a-zA-Z0-9]*");
3da1c6d7 1380 TRegexp hexexp("x[a-fA-F0-9]+");
52f67e50 1381 for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
1382 {
1383 const AliHLTTriggerMenuItem* item = menu->Item(i);
81d62bb4 1384 TString str = item->TriggerCondition();
52f67e50 1385 Ssiz_t start = 0;
1386 do
1387 {
1388 Ssiz_t length = 0;
1389 Ssiz_t pos = exp.Index(str, &length, start);
1390 if (pos == kNPOS) break;
52f67e50 1391 start = pos+length;
1392
3da1c6d7 1393 // Check if there is a numerical character before the found
1394 // regular expression. If so, then the symbol is not a valid one
1395 // and should be skipped.
1396 if (pos > 0)
1397 {
1398 bool notValid = false;
1399 switch (str[pos-1])
1400 {
1401 case '0': case '1': case '2': case '3': case '4':
1402 case '5': case '6': case '7': case '8': case '9':
1403 notValid = true;
1404 break;
1405 default:
1406 notValid = false;
1407 break;
1408 }
1409 if (notValid) continue;
1410 }
1411 TString s = str(pos, length);
1412
52f67e50 1413 if (s == "and" or s == "and_eq" or s == "bitand" or s == "bitor" or
1414 s == "compl" or s == "not" or s == "not_eq" or s == "or" or
1415 s == "or_eq" or s == "xor" or s == "xor_eq" or s == "true" or
1416 s == "false"
1417 )
1418 {
1419 // Ignore iso646.h and other keywords.
1420 continue;
1421 }
3da1c6d7 1422
025443e0 1423 // Need to create the symbols first and check if its name is in the list
1424 // before actually adding it to the symbols list.
1425 AliHLTTriggerMenuSymbol newSymbol;
1426 newSymbol.Name(s.Data());
1427 newSymbol.Type("bool");
1428 newSymbol.ObjectClass("AliHLTTriggerDecision");
1429 newSymbol.AssignExpression("this->Result()");
1430 newSymbol.DefaultValue("false");
1431 if (FindSymbol(newSymbol.Name(), list) == -1)
52f67e50 1432 {
52f67e50 1433 new (list[list.GetEntriesFast()]) AliHLTTriggerMenuSymbol(newSymbol);
1434 }
1435 }
1436 while (start < str.Length());
1437 }
1438
e2bb8ddd 1439 return 0;
1440}
1441
81d62bb4 1442
1443bool AliHLTGlobalTriggerComponent::ExtractedOperator(TString& expr, TString& op)
1444{
1445 // Extracts the trailing operator from the expression.
1446
1447 Ssiz_t i = 0;
1448 // First skip the trailing whitespace.
1449 bool whitespace = true;
1450 for (i = expr.Length()-1; i >= 0 and whitespace; i--)
1451 {
1452 switch (expr[i])
1453 {
1454 case ' ': case '\t': case '\r': case '\n':
1455 whitespace = true;
1456 break;
1457 default:
1458 whitespace = false;
1459 }
1460 }
1461 if (i < 0 or whitespace) return false;
1462
1463 // Now find the first whitespace character before the trailing symbol.
1464 bool nonwhitespace = true;
1465 for (; i >= 0 and nonwhitespace; i--)
1466 {
1467 switch (expr[i])
1468 {
1469 case ' ': case '\t': case '\r': case '\n':
1470 nonwhitespace = false;
1471 break;
1472 default:
1473 nonwhitespace = true;
1474 }
1475 }
1476 if (i < 0 or nonwhitespace) return false;
1477
1478 // Extract the last symbols and check if it is a valid operator.
1479 TString s = expr;
1480 s.Remove(0, i+2);
1481 if (s == "and" or s == "and_eq" or s == "bitand" or s == "bitor" or
1482 s == "compl" or s == "not" or s == "not_eq" or s == "or" or
1483 s == "or_eq" or s == "xor" or s == "xor_eq" or s == "&&" or
1484 s == "&=" or s == "&" or s == "|" or s == "~" or s == "!" or
1485 s == "!=" or s == "||" or s == "|=" or s == "^" or s == "^=" or
1486 s == "==" or s == "+" or s == "-" or s == "*" or s == "/" or
1487 s == "%" or s == ">" or s == "<" or s == ">=" or s == "<="
1488 )
1489 {
1490 expr.Remove(i+1);
1491 op = s;
1492 return true;
1493 }
1494
1495 return false;
1496}
1497
1498
2974f8dc 1499int AliHLTGlobalTriggerComponent::PrintStatistics(const AliHLTGlobalTrigger* pTrigger, AliHLTComponentLogSeverity level, int offset) const
1500{
1501 // print some statistics
8b29f84f 1502 int totalEvents=GetEventCount()+offset;
325e5e42 1503 const TArrayL64& counters = pTrigger->GetCounters();
1504 if (pTrigger->CallFailed()) return -EPROTO;
1505 for (int i = 0; i < counters.GetSize(); i++) {
1506 ULong64_t count = counters[i];
8b29f84f 1507 float ratio=0;
1508 if (totalEvents>0) ratio=100*(float)count/totalEvents;
81d62bb4 1509 HLTLog(level, "Item %d: total events: %d - counted events: %llu (%.1f%%)", i, totalEvents, count, ratio);
2974f8dc 1510 }
2974f8dc 1511 return 0;
1512}
566a01d0 1513
1514int AliHLTGlobalTriggerComponent::AddCTPDecisions(AliHLTGlobalTrigger* pTrigger, const AliHLTCTPData* pCTPData, const AliHLTComponentTriggerData* trigData)
1515{
1516 // add trigger decisions for the valid CTP classes
1517 if (!pCTPData || !pTrigger) return 0;
1518
1519 AliHLTUInt64_t triggerMask=pCTPData->Mask();
1520 AliHLTUInt64_t bit0=0x1;
1521 if (!fCTPDecisions) {
1522 fCTPDecisions=new TClonesArray(AliHLTTriggerDecision::Class(), gkNCTPTriggerClasses);
1523 if (!fCTPDecisions) return -ENOMEM;
1524
1525 fCTPDecisions->ExpandCreate(gkNCTPTriggerClasses);
1526 for (int i=0; i<gkNCTPTriggerClasses; i++) {
1527 const char* name=pCTPData->Name(i);
1528 if (triggerMask&(bit0<<i) && name) {
1529 AliHLTTriggerDecision* pDecision=dynamic_cast<AliHLTTriggerDecision*>(fCTPDecisions->At(i));
1530 assert(pDecision);
1531 if (!pDecision) {
1532 delete fCTPDecisions;
1533 fCTPDecisions=NULL;
1534 return -ENOENT;
1535 }
1536 pDecision->Name(name);
1537 }
1538 }
1539 }
1540
1541 for (int i=0; i<gkNCTPTriggerClasses; i++) {
1542 const char* name=pCTPData->Name(i);
1543 if ((triggerMask&(bit0<<i))==0 || name==NULL) continue;
1544 AliHLTTriggerDecision* pDecision=dynamic_cast<AliHLTTriggerDecision*>(fCTPDecisions->At(i));
1545 HLTDebug("updating CTP trigger decision %d %s (%p casted %p)", i, name, fCTPDecisions->At(i), pDecision);
1546 if (!pDecision) return -ENOENT;
1547
1548 bool result=false;
1549 if (trigData) result=pCTPData->EvaluateCTPTriggerClass(name, *trigData);
1550 else result=pCTPData->EvaluateCTPTriggerClass(name);
1551 pDecision->Result(result);
1552 pDecision->TriggerDomain().Clear();
1553 if (trigData) pDecision->TriggerDomain().Add(pCTPData->ReadoutList(*trigData));
1554 else pDecision->TriggerDomain().Add(pCTPData->ReadoutList());
1555
1556 pTrigger->Add(fCTPDecisions->At(i), kAliHLTDataTypeTriggerDecision, kAliHLTVoidDataSpec);
325e5e42 1557 if (pTrigger->CallFailed()) return -EPROTO;
566a01d0 1558 }
1559
1560 return 0;
1561}