2 /**************************************************************************
3 * This file is property of and copyright by the ALICE HLT Project *
4 * ALICE Experiment at CERN, All rights reserved. *
6 * Primary Authors: Artur Szostak <artursz@iafrica.com> *
7 * for The ALICE HLT Project. *
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 **************************************************************************/
18 /// @file AliHLTGlobalTriggerComponent.cxx
19 /// @author Artur Szostak <artursz@iafrica.com>
21 /// @brief Implementation of the AliHLTGlobalTriggerComponent component class.
23 /// The AliHLTGlobalTriggerComponent class applies the global HLT trigger to all
24 /// trigger information produced by components deriving from AliHLTTrigger.
26 #include "AliHLTGlobalTriggerComponent.h"
27 #include "AliHLTGlobalTriggerDecision.h"
28 #include "AliHLTGlobalTrigger.h"
29 #include "AliHLTGlobalTriggerConfig.h"
30 #include "AliHLTTriggerMenu.h"
31 #include "AliHLTCTPData.h"
32 #include "AliCDBManager.h"
33 #include "AliCDBStorage.h"
34 #include "AliCDBEntry.h"
35 #include "AliRawDataHeader.h"
40 #include "TClonesArray.h"
41 #include "TObjString.h"
43 #include "TInterpreter.h"
53 ClassImp(AliHLTGlobalTriggerComponent)
55 const char* AliHLTGlobalTriggerComponent::fgkTriggerMenuCDBPath = "HLT/ConfigHLT/HLTGlobalTrigger";
61 * This method is used as a comparison functor with the STL sort routines.
63 bool AliHLTDescendingNumbers(UInt_t a, UInt_t b)
70 AliHLTGlobalTriggerComponent::AliHLTGlobalTriggerComponent() :
74 fRuntimeCompile(true),
75 fDeleteCodeFile(false),
76 fMakeSoftwareTriggers(true),
80 fBufferSizeConst(2*(sizeof(AliHLTGlobalTriggerDecision) + sizeof(AliHLTReadoutList))),
81 fBufferSizeMultiplier(1.),
82 fIncludePaths(TObjString::Class()),
83 fIncludeFiles(TObjString::Class()),
86 fDataEventsOnly(true),
89 fSoftwareTrigger(true, "SOFTWARE"),
92 // Default constructor.
94 ClearInfoForNewEvent(false);
98 AliHLTGlobalTriggerComponent::~AliHLTGlobalTriggerComponent()
100 // Default destructor.
102 if (fTrigger != NULL) delete fTrigger;
105 fCTPDecisions->Delete();
106 delete fCTPDecisions;
111 void AliHLTGlobalTriggerComponent::GetOutputDataTypes(AliHLTComponentDataTypeList& list) const
113 // Returns the kAliHLTDataTypeGlobalTrigger type as output.
114 list.push_back(kAliHLTDataTypeGlobalTrigger);
118 void AliHLTGlobalTriggerComponent::GetOutputDataSize(unsigned long& constBase, double& inputMultiplier)
120 // Returns the output data size estimate.
122 constBase = fBufferSizeConst;
123 inputMultiplier = fBufferSizeMultiplier;
127 Int_t AliHLTGlobalTriggerComponent::DoInit(int argc, const char** argv)
129 // Initialises the global trigger component.
134 fDeleteCodeFile = false;
135 fMakeSoftwareTriggers = true;
136 const char* configFileName = NULL;
137 const char* codeFileName = NULL;
138 fIncludePaths.Clear();
139 fIncludeFiles.Clear();
140 SetBit(kIncludeInput);
141 fDataEventsOnly = true;
143 for (int i = 0; i < argc; i++)
145 if (strcmp(argv[i], "-config") == 0)
147 if (configFileName != NULL)
149 HLTWarning("Trigger configuration macro was already specified."
150 " Will replace previous value given by -config."
155 HLTError("The trigger configuration macro filename was not specified." );
158 configFileName = argv[i+1];
163 if (strcmp(argv[i], "-includepath") == 0)
167 HLTError("The include path was not specified." );
172 new (fIncludePaths[fIncludePaths.GetEntriesFast()]) TObjString(argv[i+1]);
174 catch (const std::bad_alloc&)
176 HLTError("Could not allocate more memory for the fIncludePaths array.");
183 if (strcmp(argv[i], "-include") == 0)
187 HLTError("The include file name was not specified." );
192 new (fIncludeFiles[fIncludeFiles.GetEntriesFast()]) TObjString(argv[i+1]);
194 catch (const std::bad_alloc&)
196 HLTError("Could not allocate more memory for the fIncludeFiles array.");
203 if (strcmp(argv[i], "-debug") == 0)
205 if (fDebugMode == true)
207 HLTWarning("The debug flag was already specified. Ignoring this instance.");
213 if (strcmp(argv[i], "-cint") == 0)
215 fRuntimeCompile = false;
219 if (strcmp(argv[i], "-usecode") == 0)
221 if (codeFileName != NULL)
223 HLTWarning("Custom trigger code file was already specified."
224 " Will replace previous value given by -usecode."
229 HLTError("The custom trigger code filename was not specified." );
232 codeFileName = argv[i+1];
235 HLTError("The custom trigger class name was not specified." );
238 fClassName = argv[i+2];
243 if (strcmp(argv[i], "-skipctp") == 0)
245 HLTInfo("Skipping CTP counters in trigger decision");
250 if (strcmp(argv[i], "-forward-input") == 0)
252 HLTInfo("Forwarding input objects and trigger decisions");
253 SetBit(kForwardInput);
254 SetBit(kIncludeShort);
255 SetBit(kIncludeInput, false);
259 if (strstr(argv[i], "-include-input") == argv[i])
261 SetBit(kForwardInput,false);
262 TString param=argv[i];
263 param.ReplaceAll("-include-input", "");
264 if (param.CompareTo("=none")==0)
266 HLTInfo("skipping objects and trigger decisions");
267 SetBit(kIncludeShort, false);
268 SetBit(kIncludeInput, false);
270 else if (param.CompareTo("=short")==0)
272 HLTInfo("including short info on objects and trigger decisions");
273 SetBit(kIncludeShort);
274 SetBit(kIncludeInput, false);
276 else if (param.CompareTo("=both")==0)
278 HLTInfo("including input objects, trigger decisions and short info");
279 SetBit(kIncludeShort);
280 SetBit(kIncludeInput);
282 else if (param.CompareTo("=objects")==0 || param.IsNull())
284 HLTInfo("including input objects and trigger decisions");
285 SetBit(kIncludeShort, false);
286 SetBit(kIncludeInput);
290 HLTError("unknown parameter '%s' for argument '-include-input'", param.Data());
295 if (strcmp(argv[i], "-process-all-events") == 0)
297 fDataEventsOnly = false;
301 if (strstr(argv[i], "-monitoring") == argv[i])
303 TString param=argv[i];
304 param.ReplaceAll("-monitoring", "");
308 // enable monitoring trigger for all events
312 // enable monitoring trigger once every n seconds
313 param.ReplaceAll("=", "");
314 if (param.IsDigit()) {
315 fMonitorPeriod=param.Atoi();
317 HLTError("expecting number as parameter for argument '-monitoring=', got %s, skipping monitoring trigger", param.Data());
323 if (strcmp(argv[i], "-dont-make-software-triggers") == 0)
325 fMakeSoftwareTriggers = false;
329 HLTError("Unknown option '%s'.", argv[i]);
333 const AliHLTTriggerMenu* menu = NULL;
334 if (configFileName != NULL)
337 cmd += configFileName;
338 gROOT->ProcessLine(cmd);
339 menu = AliHLTGlobalTriggerConfig::Menu();
342 // Try load the trigger menu from the CDB if it is not loaded yet with the
344 int result = -ENOENT;
347 result = LoadTriggerMenu(fgkTriggerMenuCDBPath, menu);
351 HLTError("No trigger menu configuration found or specified.");
355 if (codeFileName == NULL)
357 result = GenerateTrigger(menu, fClassName, fCodeFileName, fIncludePaths, fIncludeFiles);
358 if (result == 0) fDeleteCodeFile = true;
362 result = LoadTriggerClass(codeFileName, fIncludePaths);
363 if (result == 0) fCodeFileName = codeFileName;
365 if (result != 0) return result;
369 fTrigger = AliHLTGlobalTrigger::CreateNew(fClassName.Data());
371 catch (const std::bad_alloc&)
373 HLTError("Could not allocate memory for the AliHLTGlobalTrigger instance.");
376 if (fTrigger == NULL)
378 HLTError("Could not create a new instance of '%s'.", fClassName.Data());
382 fTrigger->FillFromMenu(*menu);
383 if (fTrigger->CallFailed()) return -EPROTO;
385 // setup the CTP accounting in AliHLTComponent
388 // Set the default values from the trigger menu.
389 SetDescription(menu->DefaultDescription());
390 SetTriggerDomain(menu->DefaultTriggerDomain());
392 fTotalEventCounter = 0;
397 Int_t AliHLTGlobalTriggerComponent::DoDeinit()
399 // Cleans up the global trigger component.
401 if (fTrigger != NULL)
408 fCTPDecisions->Delete();
409 delete fCTPDecisions;
413 Int_t result = UnloadTriggerClass(fCodeFileName);
414 if (result != 0) return result;
416 if (fDeleteCodeFile and !fCodeFileName.IsNull() && gSystem->AccessPathName(fCodeFileName)==0 && !fDebugMode) {
417 fCodeFileName.ReplaceAll(".cxx", "*");
418 TString command="rm "; command+=fCodeFileName;
419 gSystem->Exec(command);
422 fDeleteCodeFile=false;
428 AliHLTComponent* AliHLTGlobalTriggerComponent::Spawn()
430 // Creates a new object instance.
431 AliHLTComponent* comp = NULL;
434 comp = new AliHLTGlobalTriggerComponent;
436 catch (const std::bad_alloc&)
438 HLTError("Could not allocate memory for a new instance of AliHLTGlobalTriggerComponent.");
445 int AliHLTGlobalTriggerComponent::DoTrigger()
447 // This method will apply the global trigger decision.
449 if (fTrigger == NULL)
451 HLTFatal("Global trigger implementation object is NULL!");
455 AliHLTUInt32_t eventType=0;
456 if (!IsDataEvent(&eventType)) {
457 if (eventType==gkAliEventTypeEndOfRun) PrintStatistics(fTrigger, kHLTLogImportant, 0);
460 IgnoreEvent(); // dont generate any trigger decision.
465 // Copy the trigger counters in case we need to set them back to their original
466 // value because the PushBack method fails with ENOSPC.
467 TArrayL64 originalCounters = fTrigger->GetCounters();
468 if (fTrigger->CallFailed()) return -EPROTO;
470 fTrigger->NewEvent();
471 if (fTrigger->CallFailed()) return -EPROTO;
473 // Fill in the input data.
474 const TObject* obj = GetFirstInputObject();
477 fTrigger->Add(obj, GetDataType(), GetSpecification());
478 if (fTrigger->CallFailed()) return -EPROTO;
479 obj = GetNextInputObject();
482 // add trigger decisions for every CTP class
483 const AliHLTCTPData* pCTPData=CTPData();
485 AddCTPDecisions(fTrigger, pCTPData, GetTriggerData());
488 bool softwareTriggerIsValid = FillSoftwareTrigger();
489 if (softwareTriggerIsValid)
491 fTrigger->Add(&fSoftwareTrigger, kAliHLTDataTypeTriggerDecision, kAliHLTVoidDataSpec);
494 // Calculate the global trigger result and trigger domain, then create and push
495 // back the new global trigger decision object.
497 AliHLTTriggerDomain triggerDomain;
498 bool triggerResult = fTrigger->CalculateTriggerDecision(triggerDomain, description);
499 if (fTrigger->CallFailed()) return -EPROTO;
500 AliHLTGlobalTriggerDecision decision(
502 // The following will cause the decision to be generated with default values
503 // (set in fTriggerDomain and fDescription) if the trigger result is false.
504 (triggerResult == true) ? triggerDomain : GetTriggerDomain(),
505 (triggerResult == true) ? description.Data() : GetDescription()
508 decision.SetUniqueID(fUniqueID);
509 decision.SetCounters(fTrigger->GetCounters(), fTotalEventCounter+1);
510 if (fTrigger->CallFailed()) return -EPROTO;
512 TClonesArray shortInfo(TNamed::Class(), GetNumberOfInputBlocks());
514 // Add the input objects used to make the global decision.
515 obj = GetFirstInputObject();
518 const AliHLTTriggerDecision* intrig = dynamic_cast<const AliHLTTriggerDecision*>(obj);
520 if (TestBit(kForwardInput)) Forward(obj);
522 if (TestBit(kIncludeInput))
526 decision.AddTriggerInput(*intrig);
530 // The const_cast should be safe in this case because the list of inputObjects
531 // will be added to the global decision with AddInputObjectRef, which only
532 // modifies the kCanDelete bit and nothing else.
533 // This is necessary since GetFirstInputObject only returns const objects.
534 decision.AddInputObjectRef( const_cast<TObject*>(obj) );
538 if (TestBit(kIncludeShort))
540 int entries = shortInfo.GetEntriesFast();
543 new (shortInfo[entries]) TNamed(obj->GetName(), obj->GetTitle());
545 catch (const std::bad_alloc&)
547 HLTError("Could not allocate more memory for the short list of input objects.");
552 shortInfo[entries]->SetBit(BIT(16)); // indicate that this is a trigger decision
553 shortInfo[entries]->SetBit(BIT(15), intrig->Result());
557 obj = GetNextInputObject();
559 if (TestBit(kIncludeShort)) decision.AddInputObjectRef(&shortInfo);
561 // The const_cast should be safe in this case because AddInputObjectRef just
562 // modifies the kCanDelete bit and nothing else.
563 if (!TestBit(kSkipCTP) && CTPData()) decision.AddInputObjectRef(const_cast<AliHLTCTPData*>(CTPData()));
565 if (softwareTriggerIsValid and TestBit(kIncludeInput)) decision.AddTriggerInput(fSoftwareTrigger);
567 static UInt_t lastTime=0;
569 if (time.Get()-lastTime>60) {
571 PrintStatistics(fTrigger, kHLTLogImportant);
574 // add readout filter to event done data
575 CreateEventDoneReadoutFilter(decision.TriggerDomain(), 3);
577 // add monitoring filter to event done data if enabled by setting
578 // a monitoring period >=0: -1 means off, 0 means for every event
579 // configured by argument '-monitoring[=n]'
580 if (fMonitorPeriod>=0) {
581 static UInt_t lastMonitorEvent=0;
583 AliHLTTriggerDomain monitoringFilter(decision.TriggerDomain());
584 if (decision.Result() &&
585 int(time.Get()-lastMonitorEvent)>fMonitorPeriod) {
586 lastMonitorEvent=time.Get();
587 // add monitoring event command for triggered events
588 CreateEventDoneReadoutFilter(decision.TriggerDomain(), 5);
590 // empty filter list if events are not triggered
591 // or within the monitoring interval
592 monitoringFilter.Clear();
594 // add monitoring filter list
595 CreateEventDoneReadoutFilter(monitoringFilter, 4);
598 if (TriggerEvent(&decision, kAliHLTDataTypeGlobalTrigger) == -ENOSPC)
600 // Increase the estimated buffer space required if the PushBack methods in TriggerEvent
601 // returned the "no buffer space" error code. Also remember to set the trigger counters
602 // back to what they were, otherwise triggers will be double counted when we try to reprocess
603 // this event with larger buffers.
604 fBufferSizeConst += 1024*1024;
605 fBufferSizeMultiplier *= 2.;
606 fTrigger->SetCounters(originalCounters);
607 if (fTrigger->CallFailed()) return -EPROTO;
611 ++fTotalEventCounter;
616 int AliHLTGlobalTriggerComponent::Reconfigure(const char* cdbEntry, const char* chainId)
618 // Reconfigure the component by loading the trigger menu and recreating the
619 // trigger logic class.
621 const char* path = fgkTriggerMenuCDBPath;
622 const char* id = "(unknown)";
623 if (cdbEntry != NULL) path = cdbEntry;
624 if (chainId != NULL and chainId[0] != '\0') id = chainId;
625 HLTInfo("Reconfiguring from '%s' for chain component '%s'.", path, id);
627 const AliHLTTriggerMenu* menu = NULL;
628 int result = LoadTriggerMenu(path, menu);
629 if (result != 0) return result;
632 TString codeFileName;
633 result = GenerateTrigger(menu, className, codeFileName, fIncludePaths, fIncludeFiles);
634 if (result != 0) return result;
636 AliHLTGlobalTrigger* trigger = NULL;
639 trigger = AliHLTGlobalTrigger::CreateNew(className.Data());
641 catch (const std::bad_alloc&)
643 HLTError("Could not allocate memory for the AliHLTGlobalTrigger instance.");
648 HLTError("Could not create a new instance of '%s'.", className.Data());
649 // Make sure to cleanup after the new code file.
650 UnloadTriggerClass(codeFileName);
651 if (not codeFileName.IsNull() and gSystem->AccessPathName(codeFileName)==0 and not fDebugMode)
653 codeFileName.ReplaceAll(".cxx", "*");
654 TString command="rm "; command+=codeFileName;
655 gSystem->Exec(command);
660 if (fTrigger != NULL)
667 fTrigger->FillFromMenu(*menu);
668 if (fTrigger->CallFailed()) return -EPROTO;
670 // Set the default values from the trigger menu.
671 SetDescription(menu->DefaultDescription());
672 SetTriggerDomain(menu->DefaultTriggerDomain());
674 // Cleanup the old class code.
675 UnloadTriggerClass(fCodeFileName);
676 if (fDeleteCodeFile and not fCodeFileName.IsNull() and gSystem->AccessPathName(fCodeFileName)==0 and not fDebugMode)
678 fCodeFileName.ReplaceAll(".cxx", "*");
679 TString command="rm "; command+=fCodeFileName;
680 gSystem->Exec(command);
682 fCodeFileName = codeFileName;
683 fDeleteCodeFile = true; // Since we generated a new class.
689 int AliHLTGlobalTriggerComponent::LoadTriggerMenu(const char* cdbPath, const AliHLTTriggerMenu*& menu)
691 // Loads the trigger menu object from the CDB path.
693 HLTDebug("Trying to load trigger menu from '%s'.", cdbPath);
694 if (AliCDBManager::Instance() == NULL)
696 HLTError("CDB manager object not found.");
699 AliCDBStorage* store = AliCDBManager::Instance()->GetDefaultStorage();
702 HLTError("Could not get the the default storage for the CDB.");
705 Int_t version = store->GetLatestVersion(cdbPath, GetRunNo());
706 Int_t subVersion = store->GetLatestSubVersion(cdbPath, GetRunNo(), version);
707 AliCDBEntry* entry = AliCDBManager::Instance()->Get(cdbPath, GetRunNo(), version, subVersion);
710 HLTError("Could not get the CDB entry for \"%s\".", cdbPath);
713 TObject* obj = entry->GetObject();
716 HLTError("Configuration object for \"%s\" is missing.", cdbPath);
719 if (obj->IsA() != AliHLTTriggerMenu::Class())
721 HLTError("Wrong type for configuration object in \"%s\". Found a %s but we expect a AliHLTTriggerMenu.",
722 cdbPath, obj->ClassName()
726 menu = static_cast<AliHLTTriggerMenu*>(obj);
731 void AliHLTGlobalTriggerComponent::GenerateFileName(TString& name, TString& filename)
733 // Creates a unique file name for the generated code.
735 TUUID guid = GenerateGUID();
742 fUniqueID = bufAsInt[0];
743 TString guidstr = guid.AsString();
744 // Replace '-' with '_' in string.
745 for (int i = 0; i < guidstr.Length(); ++i)
747 if (guidstr[i] == '-') guidstr[i] = '_';
749 name = "AliHLTGlobalTriggerImpl_";
751 filename = name + ".cxx";
753 // For good measure, check that the file names are not used. If they are then regenerate.
754 fstream file(filename.Data(), ios_base::in);
758 GenerateFileName(name, filename);
763 int AliHLTGlobalTriggerComponent::GenerateTrigger(
764 const AliHLTTriggerMenu* menu, TString& name, TString& filename,
765 const TClonesArray& includePaths, const TClonesArray& includeFiles
768 // Generates the global trigger class that will implement the specified trigger menu.
769 // See header for more details.
771 GenerateFileName(name, filename);
772 HLTDebug("Generating custom HLT trigger class named %s, in file %s, using trigger menu %p.",
773 name.Data(), filename.Data(), ((void*)menu)
776 // Open a text file to write the code and generate the new class.
777 fstream code(filename.Data(), ios_base::out | ios_base::trunc);
780 HLTError("Could not open file '%s' for writing.", filename.Data());
784 TClonesArray symbols(AliHLTTriggerMenuSymbol::Class());
785 int result = BuildSymbolList(menu, symbols);
786 if (result != 0) return result;
788 code << "#if !defined(__CINT__) || defined(__MAKECINT__)" << endl;
789 code << "#include <cstring>" << endl;
790 code << "#include \"TClass.h\"" << endl;
791 code << "#include \"TString.h\"" << endl;
792 code << "#include \"TClonesArray.h\"" << endl;
793 code << "#include \"AliHLTLogging.h\"" << endl;
794 code << "#include \"AliHLTGlobalTrigger.h\"" << endl;
795 code << "#include \"AliHLTGlobalTriggerDecision.h\"" << endl;
796 code << "#include \"AliHLTDomainEntry.h\"" << endl;
797 code << "#include \"AliHLTTriggerDomain.h\"" << endl;
798 code << "#include \"AliHLTReadoutList.h\"" << endl;
799 code << "#include \"AliHLTTriggerMenu.h\"" << endl;
800 code << "#include \"AliHLTTriggerMenuItem.h\"" << endl;
801 code << "#include \"AliHLTTriggerMenuSymbol.h\"" << endl;
803 // Add any include files that were specified on the command line.
804 for (Int_t i = 0; i < includeFiles.GetEntriesFast(); i++)
806 TString file = static_cast<TObjString*>(includeFiles.UncheckedAt(i))->String();
807 code << "#include \"" << file.Data() << "\"" << endl;
812 code << "#else" << endl;
813 code << "const char* gFunctionName = \"???\";" << endl;
814 code << "#define HLTDebug(msg) if (CheckFilter(kHLTLogDebug) && CheckGroup(Class_Name())) SendMessage(kHLTLogDebug, Class_Name(), ::gFunctionName, __FILE__, __LINE__, msg)" << endl;
816 code << "#endif" << endl;
818 code << "class " << name << " :" << endl;
819 // Add appropriate #ifdef sections since we need to prevent inheritance from
820 // AliHLTGlobalTrigger. CINT does not seem to support multiple inheritance nor
821 // multiple levels of inheritance. Neither of the following schemes worked:
823 // 1) class AliHLTGlobalTrigger : public AliHLTLogging {};
824 // class AliHLTGlobalTriggerImpl_xyz : public AliHLTGlobalTrigger {};
826 // 2) class AliHLTGlobalTrigger {};
827 // class AliHLTGlobalTriggerImpl_xyz : public AliHLTGlobalTrigger, public AliHLTLogging {};
829 // Thus, we are forced to just inherit from AliHLTLogging when running in the CINT
830 // interpreter. But we anyway have to call the global trigger implementation class
831 // through the AliHLTGlobalTriggerWrapper so this is not such a problem.
832 code << "#if !defined(__CINT__) || defined(__MAKECINT__)" << endl;
833 code << " public AliHLTGlobalTrigger," << endl;
834 code << "#endif" << endl;
835 code << " public AliHLTLogging" << endl;
837 code << "public:" << endl;
839 // Generate constructor method.
840 code << " " << name << "() :" << endl;
841 code << "#if !defined(__CINT__) || defined(__MAKECINT__)" << endl;
842 code << " AliHLTGlobalTrigger()," << endl;
843 code << "#endif" << endl;
844 code << " AliHLTLogging()";
845 // Write the symbols in the trigger menu in the initialisation list.
846 for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
849 AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
850 code << " " << symbol->Name() << "()," << endl;
851 if (strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0)
853 code << " " << symbol->Name() << "TriggerDomain()," << endl;
855 code << " " << symbol->Name() << "DomainEntry(kAliHLTAnyDataType)";
857 for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
859 code << "," << endl << " fMenuItemDescription" << i << "()";
861 code << endl << " {" << endl;
864 code << "#ifdef __CINT__" << endl;
865 code << " gFunctionName = \"" << name.Data() <<"\";" << endl;
866 code << "#endif" << endl;
867 code << " SetLocalLoggingLevel(kHLTLogAll);" << endl;
868 code << " HLTDebug(Form(\"Creating new instance at %p.\", this));" << endl;
870 code << " }" << endl;
872 code << " virtual ~" << name << "() {" << endl;
875 code << "#ifdef __CINT__" << endl;
876 code << " gFunctionName = \"~" << name.Data() << "\";" << endl;
877 code << "#endif" << endl;
878 code << " HLTDebug(Form(\"Deleting instance at %p.\", this));" << endl;
880 code << " }" << endl;
882 // Generate the FillFromMenu method.
883 code << " virtual void FillFromMenu(const AliHLTTriggerMenu& menu) {" << endl;
886 code << "#ifdef __CINT__" << endl;
887 code << " gFunctionName = \"FillFromMenu\";" << endl;
888 code << "#endif" << endl;
889 code << " HLTDebug(Form(\"Filling description entries from trigger menu for global trigger %p.\", this));" << endl;
891 code << " fCounter.Set(menu.NumberOfItems());" << endl;
892 for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
894 code << " fMenuItemDescription" << i << " = (menu.Item(" << i
895 << ") != NULL) ? menu.Item(" << i << ")->Description() : \"\";" << endl;
899 code << " HLTDebug(Form(\"Finished filling description entries from trigger menu.\"));" << endl;
900 code << " HLTDebug(Form(\"Filling domain entries from trigger menu symbols for global trigger %p.\", this));" << endl;
902 code << " for (Int_t i = 0; i < menu.SymbolArray().GetEntriesFast(); i++) {" << endl;
903 // 30 Oct 2009 - CINT sometimes evaluates the dynamic_cast incorrectly.
904 // Have to use the TClass system for extra protection.
905 code << " if (menu.SymbolArray().UncheckedAt(i) == NULL) continue;" << endl;
906 code << " if (menu.SymbolArray().UncheckedAt(i)->IsA() != AliHLTTriggerMenuSymbol::Class()) continue;" << endl;
907 code << " const AliHLTTriggerMenuSymbol* symbol = dynamic_cast<const"
908 " AliHLTTriggerMenuSymbol*>(menu.SymbolArray().UncheckedAt(i));" << endl;
909 code << " if (symbol == NULL) continue;" << endl;
910 for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
912 AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
913 code << " if (strcmp(symbol->RealName(), \"" << symbol->RealName() << "\") == 0) {" << endl;
916 code << " HLTDebug(Form(\"Assinging domain entry value corresponding with symbol '%s' to '%s'.\","
917 " symbol->RealName(), symbol->BlockType().AsString().Data()));" << endl;
919 code << " " << symbol->Name() << "DomainEntry = symbol->BlockType();" << endl;
920 code << " continue;" << endl;
921 code << " }" << endl;
923 code << " }" << endl;
924 // The following is an optimisation where symbols without any assignment operators
925 // are treated as constant and only initialised in FillFromMenu rather than reseting
926 // them in the NewEvent method.
927 // Note: we putting this initialisation into the constructor can lead to seg faults
928 // under CINT interpretation. Thus we must put it into the FillFromMenu method instead.
929 for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
931 AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
932 if (TString(symbol->AssignExpression()) != "") continue;
933 if (strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0) continue;
934 // CINT has problems with the implicit equals operator for complex types, so if
935 // the type has an equals operater we need to write the operator call explicitly.
936 TClass* clas = TClass::GetClass(symbol->Type());
937 if (clas != NULL and clas->GetMethodAny("operator=") != NULL)
939 code << " " << symbol->Name() << ".operator = (" << symbol->DefaultValue() << ");" << endl;
943 code << " " << symbol->Name() << " = " << symbol->DefaultValue() << ";" << endl;
948 code << " HLTDebug(Form(\"Finished filling domain entries from trigger menu symbols.\"));" << endl;
950 code << " }" << endl;
952 // Generate the NewEvent method.
953 code << " virtual void NewEvent() {" << endl;
956 code << "#ifdef __CINT__" << endl;
957 code << " gFunctionName = \"NewEvent\";" << endl;
958 code << "#endif" << endl;
959 code << " HLTDebug(Form(\"New event for global trigger object %p, initialising variables to default values.\", this));" << endl;
961 // Write code to initialise the symbols in the trigger menu to their default values.
962 for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
964 AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
965 // The following is an optimisation. If the symbol does not have an assignment expression
966 // then it is effectively a constant symbol and can be initialised earlier and only once.
967 // In this case we initialise it in the FillFromMenu method instead.
968 if (TString(symbol->AssignExpression()) == "") continue;
969 // CINT has problems with the implicit equals operator for complex types, so if
970 // the type has an equals operater we need to write the operator call explicitly.
971 TClass* clas = TClass::GetClass(symbol->Type());
972 if (clas != NULL and clas->GetMethodAny("operator=") != NULL)
974 code << " " << symbol->Name() << ".operator = (" << symbol->DefaultValue() << ");" << endl;
978 code << " " << symbol->Name() << " = " << symbol->DefaultValue() << ";" << endl;
980 if (strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0)
982 code << " " << symbol->Name() << "TriggerDomain.Clear();" << endl;
987 code << " HLTDebug(Form(\"Finished initialising variables.\"));" << endl;
989 code << " }" << endl;
991 // Generate the Add method.
992 bool haveAssignments = false;
993 for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
995 // First check if we have any symbols with assignment expressions.
996 // This is needed to get rid of the on the fly compilation warning about '_object_' not being used.
997 AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
998 TString expr = symbol->AssignExpression();
999 if (expr == "") continue; // Skip entries that have no assignment expression.
1000 haveAssignments = true;
1003 if (haveAssignments or fDebugMode)
1005 code << " virtual void Add(const TObject* _object_, const AliHLTComponentDataType& _type_, AliHLTUInt32_t _spec_) {" << endl;
1009 code << " virtual void Add(const TObject* /*_object_*/, const AliHLTComponentDataType& _type_, AliHLTUInt32_t _spec_) {" << endl;
1013 code << "#ifdef __CINT__" << endl;
1014 code << " gFunctionName = \"Add\";" << endl;
1015 code << "#endif" << endl;
1017 code << " AliHLTDomainEntry _type_spec_(_type_, _spec_);" << endl;
1020 code << " HLTDebug(Form(\"Adding TObject %p, with class name '%s' from data block"
1021 " '%s', to global trigger object %p\", _object_, _object_->ClassName(),"
1022 " _type_spec_.AsString().Data(), this));" << endl;
1023 code << " _object_->Print();" << endl;
1024 code << " bool _object_assigned_ = false;" << endl;
1026 for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
1028 // Write code to check if the block type, specification and class name is correct.
1029 // Then write code to assign the variable from the input object.
1030 AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
1031 TString expr = symbol->AssignExpression();
1032 if (expr == "") continue; // Skip entries that have no assignment expression.
1033 bool isTrigDecision = strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0;
1038 code << " HLTDebug(Form(\"Trying to match input object to class '"
1039 << symbol->ObjectClass() << "', trigger name '" << symbol->RealName()
1040 << "' and block type '%s'\", " << symbol->Name()
1041 << "DomainEntry.AsString().Data()));" << endl;
1045 code << " HLTDebug(Form(\"Trying to match input object to class '"
1046 << symbol->ObjectClass() << "' and block type '%s'\", "
1047 << symbol->Name() << "DomainEntry.AsString().Data()));" << endl;
1050 // 30 Oct 2009 - CINT sometimes evaluates the dynamic_cast incorrectly.
1051 // Have to use the TClass system for extra protection.
1052 code << " const " << symbol->ObjectClass() << "* " << symbol->Name() << "_object_ = NULL;" << endl;
1053 code << " if (_object_->InheritsFrom(" << symbol->ObjectClass() << "::Class())) " << symbol->Name()
1054 << "_object_ = dynamic_cast<const " << symbol->ObjectClass()
1055 << "*>(_object_);" << endl;
1056 code << " if (" << symbol->Name() << "_object_ != NULL && ";
1059 code << "strcmp(" << symbol->Name() << "_object_->Name(), \""
1060 << symbol->RealName() << "\") == 0 && ";
1062 code << symbol->Name() << "DomainEntry == _type_spec_) {" << endl;
1063 TString fullname = symbol->Name();
1064 fullname += "_object_";
1065 expr.ReplaceAll("this", fullname);
1066 code << " this->" << symbol->Name() << " = " << expr.Data() << ";" << endl;
1069 code << " this->" << symbol->Name() << "TriggerDomain = "
1070 << fullname.Data() << "->TriggerDomain();" << endl;
1074 code << " HLTDebug(Form(\"Added TObject %p with class name '%s' to variable "
1075 << symbol->Name() << "\", _object_, _object_->ClassName()));" << endl;
1076 code << " _object_assigned_ = true;" << endl;
1078 code << " }" << endl;
1082 code << " if (! _object_assigned_) {" << endl;
1083 code << " HLTDebug(Form(\"Did not assign TObject %p"
1084 " with class name '%s' to any variable.\", _object_, _object_->ClassName()));"
1086 code << " }" << endl;
1088 code << " }" << endl;
1090 // Generate the CalculateTriggerDecision method.
1091 // This requires code to be generated that checks which items in the trigger menu
1092 // have their conditions asserted and then the trigger domain is generated from
1093 // those fired items.
1094 // The processing will start from the highest priority trigger group and stop
1095 // after at least one trigger from the current priority group being processed
1096 // is positive. For each priority group all the trigger menu items are checked.
1097 // Their combined trigger condition expression must be true for the trigger priority
1098 // group to be triggered positive. The full condition expression is formed by
1099 // concatenating the individual condition expressions. If no trailing operators are
1100 // used in the individual expressions then the default condition operator is placed
1101 // between two concatenated condition expressions.
1102 // If a trigger priority group has at least one trigger fired then the trigger domain
1103 // is calculated such that it will give the same result as the concatenated trigger
1104 // domain merging expressions for all the individual trigger menu items with
1105 // positive results. Again, if no trailing operators are used in the individual
1106 // merging expressions then the default domain operator is placed between two
1107 // expression fragments.
1108 code << " virtual bool CalculateTriggerDecision(AliHLTTriggerDomain& _domain_, TString& _description_) {" << endl;
1111 code << "#ifdef __CINT__" << endl;
1112 code << " gFunctionName = \"CalculateTriggerDecision\";" << endl;
1113 code << "#endif" << endl;
1114 code << " HLTDebug(Form(\"Calculating global HLT trigger result with trigger object at %p.\", this));" << endl;
1117 // Build a list of priorities used in the trigger menu.
1118 std::vector<UInt_t> priorities;
1119 for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
1121 const AliHLTTriggerMenuItem* item = menu->Item(i);
1122 bool priorityNotInList = std::find(priorities.begin(), priorities.end(), item->Priority()) == priorities.end();
1123 if (priorityNotInList) priorities.push_back(item->Priority());
1125 std::sort(priorities.begin(), priorities.end(), AliHLTDescendingNumbers);
1126 // From the priority list, build the priority groups in the correct order,
1127 // i.e. highest priority first.
1128 // The priority group is a list of vectors of integers. The integers are the
1129 // index numbers into the trigger menu item list for the items which form part
1130 // of the priority group.
1131 std::vector<std::vector<Int_t> > priorityGroup;
1132 priorityGroup.insert(priorityGroup.begin(), priorities.size(), std::vector<Int_t>());
1133 for (size_t n = 0; n < priorities.size(); n++)
1135 UInt_t priority = priorities[n];
1136 for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
1138 const AliHLTTriggerMenuItem* item = menu->Item(i);
1139 if (item->Priority() == priority) priorityGroup[n].push_back(i);
1143 for (size_t n = 0; n < priorityGroup.size(); n++)
1147 code << " HLTDebug(Form(\"Processing trigger priority group " << priorities[n] << "\"));" << endl;
1150 if (n == 0) code << "UInt_t ";
1151 code << "_previous_match_ = 0xFFFFFFFF;" << endl;
1153 if (n == 0) code << "bool ";
1154 code << "_trigger_matched_ = false;" << endl;
1156 if (n == 0) code << "bool ";
1157 code << "_group_result_ = false;" << endl;
1158 std::vector<TString> conditionOperator;
1159 conditionOperator.insert(conditionOperator.begin(), priorityGroup[n].size(), TString(""));
1160 std::vector<TString> domainOperator;
1161 domainOperator.insert(domainOperator.begin(), priorityGroup[n].size(), TString(""));
1162 for (size_t m = 0; m < priorityGroup[n].size(); m++)
1164 UInt_t i = priorityGroup[n][m];
1165 const AliHLTTriggerMenuItem* item = menu->Item(i);
1166 TString triggerCondition = item->TriggerCondition();
1167 TString mergeExpr = item->MergeExpression();
1168 // Replace the symbols found in the trigger condition and merging expressions
1169 // with appropriate compilable versions.
1170 for (Int_t j = 0; j < symbols.GetEntriesFast(); j++)
1172 AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(j) );
1173 bool symbolNamesDifferent = strcmp(symbol->RealName(), symbol->Name()) != 0;
1174 if (strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0)
1176 TString newname = symbol->Name();
1177 newname += "TriggerDomain";
1178 mergeExpr.ReplaceAll(symbol->RealName(), newname);
1182 if (symbolNamesDifferent) mergeExpr.ReplaceAll(symbol->RealName(), symbol->Name());
1184 if (symbolNamesDifferent) triggerCondition.ReplaceAll(symbol->RealName(), symbol->Name());
1186 // We allow the trigger conditions and merging expressions to have trailing operators.
1187 // Thus, we need to extract the operators and cleanup the expressions so that they will
1188 // compile. This means that we silently ignore the trailing operator if not needed.
1189 if (ExtractedOperator(triggerCondition, conditionOperator[m]))
1191 // If the trailing operator is the same as the default operator then reset
1192 // the value in the operator list so that the default is used in the generated
1193 // code. This creates more compact code.
1194 if (conditionOperator[m] == menu->DefaultConditionOperator()) conditionOperator[m] = "";
1196 if (ExtractedOperator(mergeExpr, domainOperator[m]))
1198 if (domainOperator[m] == menu->DefaultDomainOperator()) domainOperator[m] = "";
1202 code << " HLTDebug(Form(\"Trying trigger condition " << i
1203 << " (Description = '%s').\", fMenuItemDescription" << i << ".Data()));"
1207 if (n == 0 and m == 0) code << "bool ";
1208 code << "_item_result_ = false;" << endl;
1209 code << " if (" << triggerCondition << ") {" << endl;
1210 code << " ++fCounter[" << i << "];" << endl;
1211 const char* indentation = "";
1212 if (item->PreScalar() != 0)
1215 code << " if ((fCounter[" << i << "] % " << item->PreScalar() << ") == 1) {" << endl;
1217 code << indentation << " _item_result_ = true;" << endl;
1220 code << indentation << " HLTDebug(Form(\"Matched trigger condition " << i
1221 << " (Description = '%s').\", fMenuItemDescription" << i << ".Data()));" << endl;
1223 if (item->PreScalar() != 0)
1225 code << " }" << endl;
1227 code << " }" << endl;
1230 // Since this is the first item of the trigger group,
1231 // the generated trigger logic can be simplified a little.
1232 code << " _group_result_ = _item_result_;" << endl;
1233 code << " if (_item_result_) {" << endl;
1234 code << " _domain_ = " << mergeExpr.Data() << ";" << endl;
1235 code << " _description_ = fMenuItemDescription" << i << ";" << endl;
1236 code << " _previous_match_ = " << i << ";" << endl;
1237 code << " _trigger_matched_ = true;" << endl;
1238 code << " }" << endl;
1242 if (conditionOperator[m-1] == "")
1244 code << " _group_result_ = _group_result_ "
1245 << menu->DefaultConditionOperator() << " _item_result_;" << endl;
1249 code << " _group_result_ = _group_result_ "
1250 << conditionOperator[m-1] << " _item_result_;" << endl;
1252 code << " if (_item_result_) {" << endl;
1253 code << " if (_trigger_matched_) {" << endl;
1254 bool switchWillBeEmpty = true;
1255 for (size_t k = 0; k < m; k++)
1257 if (domainOperator[k] == "") continue;
1258 switchWillBeEmpty = false;
1260 if (switchWillBeEmpty)
1262 code << " _domain_ = _domain_ " << menu->DefaultDomainOperator() << " "
1263 << mergeExpr.Data() << ";" << endl;
1267 code << " switch(_previous_match_) {" << endl;
1268 for (size_t k = 0; k < m; k++)
1270 if (domainOperator[k] == "") continue;
1271 code << " case " << k << ": _domain_ = _domain_ "
1272 << domainOperator[k] << " " << mergeExpr.Data() << "; break;" << endl;
1274 code << " default: _domain_ = _domain_ "
1275 << menu->DefaultDomainOperator() << " " << mergeExpr.Data() << ";" << endl;
1276 code << " }" << endl;
1278 code << " _description_ += \",\";" << endl;
1279 code << " _description_ += fMenuItemDescription" << i << ";" << endl;
1280 code << " } else {" << endl;
1281 code << " _domain_ = " << mergeExpr.Data() << ";" << endl;
1282 code << " _description_ = fMenuItemDescription" << i << ";" << endl;
1283 code << " }" << endl;
1284 code << " _previous_match_ = " << i << ";" << endl;
1285 code << " _trigger_matched_ = true;" << endl;
1286 code << " }" << endl;
1289 code << " if (_group_result_) {" << endl;
1292 if (n < priorities.size() - 1)
1294 code << " HLTDebug(Form(\"Matched triggers in trigger priority group " << priorities[n]
1295 << ". Stopping processing here because all other trigger groups have lower priority.\"));" << endl;
1299 code << " HLTDebug(Form(\"Matched triggers in trigger priority group " << priorities[n] << ".\"));" << endl;
1302 code << " return true;" << endl;
1303 code << " }" << endl;
1305 code << " _domain_.Clear();" << endl;
1306 code << " _description_ = \"\";" << endl;
1307 code << " return false;" << endl;
1308 code << " }" << endl;
1310 // Generate getter and setter methods for the counters.
1311 code << " const TArrayL64& GetCounters() const { return fCounter; }" << endl;
1312 code << " void SetCounters(const TArrayL64& counters) { fCounter = counters; }" << endl;
1314 code << "private:" << endl;
1315 // Add the symbols in the trigger menu to the list of private variables.
1316 for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
1318 AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
1319 code << " " << symbol->Type() << " " << symbol->Name() << ";" << endl;
1320 if (strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0)
1322 code << " AliHLTTriggerDomain " << symbol->Name() << "TriggerDomain;" << endl;
1324 code << " AliHLTDomainEntry " << symbol->Name() << "DomainEntry;" << endl;
1326 for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
1328 code << " TString fMenuItemDescription" << i << ";" << endl;
1330 code << " TArrayL64 fCounter;" << endl;
1331 code << "#if !defined(__CINT__) || defined(__MAKECINT__)" << endl;
1332 code << " ClassDef(" << name.Data() << ", 0)" << endl;
1333 code << "#else" << endl;
1334 code << " virtual const char* Class_Name() const { return \"" << name.Data() << "\"; }" << endl;
1335 code << "#endif" << endl;
1336 code << "};" << endl;
1337 code << "#if !defined(__CINT__) || defined(__MAKECINT__)" << endl;
1338 code << "ClassImp(" << name.Data() << ")" << endl;
1339 code << "#endif" << endl;
1343 // Now we need to compile and load the new class.
1344 result = LoadTriggerClass(filename, includePaths);
1349 int AliHLTGlobalTriggerComponent::LoadTriggerClass(
1350 const char* filename, const TClonesArray& includePaths
1353 // Loads the code for a custom global trigger class implementation on the fly.
1355 HLTDebug("Loading HLT trigger class from file '%s'.", filename);
1357 TString compiler = gSystem->GetBuildCompilerVersion();
1358 if (fRuntimeCompile && (compiler.Contains("gcc") or compiler.Contains("icc")))
1360 TString includePath;
1361 #if defined(PKGINCLUDEDIR)
1362 // this is especially for the HLT build system where the package is installed
1363 // in a specific directory including proper treatment of include files
1364 includePath.Form("-I%s", PKGINCLUDEDIR);
1366 // the default AliRoot behavior, all include files can be found in the
1367 // $ALICE_ROOT subfolders
1368 includePath = "-I${ALICE_ROOT}/include -I${ALICE_ROOT}/HLT/BASE -I${ALICE_ROOT}/HLT/trigger";
1370 // Add any include paths that were specified on the command line.
1371 for (Int_t i = 0; i < includePaths.GetEntriesFast(); i++)
1373 TString path = static_cast<TObjString*>(includePaths.UncheckedAt(i))->String();
1374 includePath += " -I";
1375 includePath += path;
1377 HLTDebug("using include settings: %s", includePath.Data());
1378 gSystem->SetIncludePath(includePath);
1379 gSystem->SetFlagsOpt("-O3 -DNDEBUG");
1380 gSystem->SetFlagsDebug("-g3 -DDEBUG -D__DEBUG");
1385 result = gSystem->CompileMacro(filename, "g");
1389 result = gSystem->CompileMacro(filename, "O");
1391 if (result != kTRUE)
1393 HLTFatal("Could not compile and load global trigger menu implementation.");
1399 // Store the library state to be checked later in UnloadTriggerClass.
1400 fLibStateAtLoad = gSystem->GetLibraries();
1402 // If we do not support the compiler then try interpret the class instead.
1403 TString cmd = ".L ";
1405 Int_t errorcode = TInterpreter::kNoError;
1406 gROOT->ProcessLine(cmd, &errorcode);
1407 if (errorcode != TInterpreter::kNoError)
1409 HLTFatal("Could not load interpreted global trigger menu implementation"
1410 " (Interpreter error code = %d).",
1421 int AliHLTGlobalTriggerComponent::UnloadTriggerClass(const char* filename)
1423 // Unloads the code previously loaded by LoadTriggerClass.
1425 HLTDebug("Unloading HLT trigger class in file '%s'.", filename);
1427 TString compiler = gSystem->GetBuildCompilerVersion();
1428 if (fRuntimeCompile && (compiler.Contains("gcc") or compiler.Contains("icc")))
1430 // Generate the library name.
1431 TString libname = filename;
1432 Ssiz_t dotpos = libname.Last('.');
1433 if (0 <= dotpos and dotpos < libname.Length()) libname[dotpos] = '_';
1435 libname += gSystem->GetSoExt();
1437 // This is a workaround for a problem with unloading shared libraries in ROOT.
1438 // If the trigger logic library is loaded before the libAliHLTHOMER.so library
1439 // or any other library is loaded afterwards, then during the gInterpreter->UnloadFile
1440 // call all the subsequent libraries get unloded. This means that any objects created
1441 // from classes implemented in the libAliHLTHOMER.so library will generate segfaults
1442 // since the executable code has been unloaded.
1443 // We need to check if there are any more libraries loaded after the class we
1444 // are unloading and in that case don't unload the class.
1445 TString libstring = gSystem->GetLibraries();
1446 TString token, lastlib;
1448 Int_t numOfLibs = 0, posOfLib = -1;
1449 while (libstring.Tokenize(token, from, " "))
1453 if (token.Contains(libname)) posOfLib = numOfLibs;
1455 if (numOfLibs != posOfLib)
1457 HLTWarning(Form("ROOT limitation! Cannot properly cleanup and unload the shared"
1458 " library '%s' since another library '%s' was loaded afterwards. Trying to"
1459 " unload this library will remove the others and lead to serious memory faults.",
1460 libname.Data(), lastlib.Data()
1467 if ((path = gSystem->DynamicPathName(libname)) != NULL)
1469 result = gInterpreter->UnloadFile(path);
1472 if (result != TInterpreter::kNoError) return -ENOENT;
1476 // This is again a workaround for the problem with unloading files in ROOT.
1477 // If the trigger logic class is loaded before the libAliHLTHOMER.so library
1478 // or any other library is loaded afterwards, then during the gInterpreter->UnloadFile
1479 // call all the subsequent libraries get unloded.
1480 // We need to check if the list of loaded libraries has changed since the last
1481 // call to LoadTriggerClass. If it has then don't unload the class.
1482 if (fLibStateAtLoad != gSystem->GetLibraries())
1484 TString libstring = gSystem->GetLibraries();
1487 while (libstring.Tokenize(token, from, " "))
1489 if (not fLibStateAtLoad.Contains(token)) break;
1491 HLTWarning(Form("ROOT limitation! Cannot properly cleanup and unload the file"
1492 " '%s' since another library '%s' was loaded afterwards. Trying to unload"
1493 " this file will remove the other library and lead to serious memory faults.",
1494 filename, token.Data()
1499 // If we did not compile the trigger logic then remove the interpreted class.
1500 TString cmd = ".U ";
1502 Int_t errorcode = TInterpreter::kNoError;
1503 gROOT->ProcessLine(cmd, &errorcode);
1504 if (errorcode != TInterpreter::kNoError)
1506 HLTFatal("Could not unload interpreted global trigger menu implementation"
1507 " (Interpreter error code = %d).",
1518 int AliHLTGlobalTriggerComponent::FindSymbol(const char* name, const TClonesArray& list)
1520 // Searches for the named symbol in the given list.
1521 // See header for more details.
1523 for (int i = 0; i < list.GetEntriesFast(); i++)
1525 const AliHLTTriggerMenuSymbol* symbol = dynamic_cast<const AliHLTTriggerMenuSymbol*>( list.UncheckedAt(i) );
1526 if (symbol == NULL) continue;
1527 if (strcmp(symbol->Name(), name) == 0) return i;
1536 * Helper routine to compare two trigger menu symbols to see if b is a subset of a.
1537 * \returns true if b is a subset of a or they are unrelated.
1539 bool AliHLTCheckForContainment(const AliHLTTriggerMenuSymbol* a, const AliHLTTriggerMenuSymbol* b)
1541 TString bstr = b->Name();
1542 return bstr.Contains(a->Name());
1545 } // end of namespace
1548 int AliHLTGlobalTriggerComponent::BuildSymbolList(const AliHLTTriggerMenu* menu, TClonesArray& list)
1550 // Builds the list of symbols to use in the custom global trigger menu
1551 // implementation class.
1552 // See header for more details.
1554 // Note: when we build the symbol list we must use the symbol name as returned
1555 // by the Name() method and not the RealName() method when using FindSymbol.
1556 // This is so that we avoid problems with the generated code not compiling
1557 // because names like "abc-xyz" and "abc_xyz" are synonymous.
1558 // Name() returns the converted C++ symbol name as used in the generated code.
1560 for (UInt_t i = 0; i < menu->NumberOfSymbols(); i++)
1562 const AliHLTTriggerMenuSymbol* symbol = menu->Symbol(i);
1563 if (FindSymbol(symbol->Name(), list) != -1)
1565 HLTError("Multiple symbols with the name '%s' defined in the trigger menu.", symbol->Name());
1570 new (list[list.GetEntriesFast()]) AliHLTTriggerMenuSymbol(*symbol);
1572 catch (const std::bad_alloc&)
1574 HLTError("Could not allocate more memory for the symbols list when adding a trigger menu symbol.");
1578 Int_t initialEntryCount = list.GetEntriesFast();
1580 // Note: the \\. must not be the first element in the character class, otherwise
1581 // it is interpreted as an "any character" dot symbol.
1582 TRegexp exp("[_a-zA-Z][-\\._a-zA-Z0-9]*");
1583 for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
1585 const AliHLTTriggerMenuItem* item = menu->Item(i);
1586 TString str = item->TriggerCondition();
1591 Ssiz_t pos = exp.Index(str, &length, start);
1592 if (pos == kNPOS) break;
1595 // Check if there is a numerical character before the found
1596 // regular expression. If so, then the symbol is not a valid one
1597 // and should be skipped.
1600 bool notValid = false;
1603 case '0': case '1': case '2': case '3': case '4':
1604 case '5': case '6': case '7': case '8': case '9':
1611 if (notValid) continue;
1613 TString s = str(pos, length);
1615 if (s == "and" or s == "and_eq" or s == "bitand" or s == "bitor" or
1616 s == "compl" or s == "not" or s == "not_eq" or s == "or" or
1617 s == "or_eq" or s == "xor" or s == "xor_eq" or s == "true" or
1621 // Ignore iso646.h and other keywords.
1625 // We need to handle the special case where the symbol contains a dot.
1626 // In C++ this is a dereferencing operator. So we need to check if the
1627 // current symbol we are handling starts with the same string as any of
1628 // the existing symbols defined manually in the symbols table.
1629 // If we do find such a case then revert to treating the dot as an operator
1630 // rather than part of the symbol name. i.e. skip adding the automatic symbol.
1631 bool dereferencedSymbol = false;
1632 for (int j = 0; j < initialEntryCount; j++)
1634 const AliHLTTriggerMenuSymbol* symbol = dynamic_cast<const AliHLTTriggerMenuSymbol*>( list.UncheckedAt(j) );
1635 if (symbol == NULL) continue;
1636 TString symstr = symbol->Name();
1638 if (s.BeginsWith(symstr))
1640 dereferencedSymbol = true;
1644 if (dereferencedSymbol) continue;
1646 // Need to create the symbols first and check if its name is in the list
1647 // before actually adding it to the symbols list.
1648 AliHLTTriggerMenuSymbol newSymbol;
1649 newSymbol.Name(s.Data());
1650 newSymbol.Type("bool");
1651 newSymbol.ObjectClass("AliHLTTriggerDecision");
1652 newSymbol.AssignExpression("this->Result()");
1653 newSymbol.DefaultValue("false");
1654 if (FindSymbol(newSymbol.Name(), list) == -1)
1658 new (list[list.GetEntriesFast()]) AliHLTTriggerMenuSymbol(newSymbol);
1660 catch (const std::bad_alloc&)
1662 HLTError("Could not allocate more memory for the symbols list when adding a trigger name symbol.");
1667 while (start < str.Length());
1670 // This last part is necessary to make sure that symbols are replaced in the
1671 // trigger condition and domain merging expressions in a greedy manner.
1672 // I.e. we need to make sure that if one symbol's string representation is
1673 // contained inside another (string subset) that the longer symbol name is
1674 // always first in the symbols list.
1675 // This will work because the symbol table is traversed from first to last
1676 // element and TString::ReplaceAll is used to replace the substrings inside
1677 // the AliHLTGlobalTriggerComponent::GenerateTrigger method.
1678 std::vector<AliHLTTriggerMenuSymbol*> orderedList;
1679 for (Int_t i = 0; i < list.GetEntriesFast(); i++)
1681 orderedList.push_back( static_cast<AliHLTTriggerMenuSymbol*>(list.UncheckedAt(i)) );
1683 std::sort(orderedList.begin(), orderedList.end(), AliHLTCheckForContainment);
1684 //std::sort(orderedList.begin(), orderedList.end());
1685 // Now swap values around according to the orderedList.
1686 for (Int_t i = 0; i < list.GetEntriesFast(); i++)
1688 AliHLTTriggerMenuSymbol* target = static_cast<AliHLTTriggerMenuSymbol*>(list.UncheckedAt(i));
1689 AliHLTTriggerMenuSymbol tmp = *target;
1690 *target = *orderedList[i];
1691 *orderedList[i] = tmp;
1698 bool AliHLTGlobalTriggerComponent::ExtractedOperator(TString& expr, TString& op)
1700 // Extracts the trailing operator from the expression.
1703 // First skip the trailing whitespace.
1704 bool whitespace = true;
1705 for (i = expr.Length()-1; i >= 0 and whitespace; i--)
1709 case ' ': case '\t': case '\r': case '\n':
1716 if (i < 0 or whitespace) return false;
1718 // Now find the first whitespace character before the trailing symbol.
1719 bool nonwhitespace = true;
1720 for (; i >= 0 and nonwhitespace; i--)
1724 case ' ': case '\t': case '\r': case '\n':
1725 nonwhitespace = false;
1728 nonwhitespace = true;
1731 if (i < 0 or nonwhitespace) return false;
1733 // Extract the last symbols and check if it is a valid operator.
1736 if (s == "and" or s == "and_eq" or s == "bitand" or s == "bitor" or
1737 s == "compl" or s == "not" or s == "not_eq" or s == "or" or
1738 s == "or_eq" or s == "xor" or s == "xor_eq" or s == "&&" or
1739 s == "&=" or s == "&" or s == "|" or s == "~" or s == "!" or
1740 s == "!=" or s == "||" or s == "|=" or s == "^" or s == "^=" or
1741 s == "==" or s == "+" or s == "-" or s == "*" or s == "/" or
1742 s == "%" or s == ">" or s == "<" or s == ">=" or s == "<="
1754 bool AliHLTGlobalTriggerComponent::FillSoftwareTrigger()
1756 // Fills the fSoftwareTrigger structure.
1757 const AliRawDataHeader* cdh;
1758 if (ExtractTriggerData(*GetTriggerData(), NULL, NULL, &cdh, NULL) != 0) return false;
1759 UChar_t l1msg = cdh->GetL1TriggerMessage();
1760 if ((l1msg & 0x1) == 0x0) return false; // skip physics events.
1761 // From here on everything must be a software trigger.
1762 if (((l1msg >> 2) & 0xF) == 0xE)
1764 fSoftwareTrigger.Name("START_OF_DATA");
1765 fSoftwareTrigger.Description("Generated internal start of data trigger.");
1767 else if (((l1msg >> 2) & 0xF) == 0xF)
1769 fSoftwareTrigger.Name("END_OF_DATA");
1770 fSoftwareTrigger.Description("Generated internal end of data trigger.");
1772 else if (((l1msg >> 6) & 0x1) == 0x1)
1774 fSoftwareTrigger.Name("CALIBRATION");
1775 fSoftwareTrigger.Description("Generated internal calibration trigger.");
1779 fSoftwareTrigger.Name("SOFTWARE");
1780 fSoftwareTrigger.Description("Generated internal software trigger.");
1782 UInt_t detectors = cdh->GetSubDetectors();
1783 fSoftwareTrigger.ReadoutList( AliHLTReadoutList(Int_t(detectors)) );
1788 int AliHLTGlobalTriggerComponent::PrintStatistics(const AliHLTGlobalTrigger* pTrigger, AliHLTComponentLogSeverity level, int offset) const
1790 // print some statistics
1791 int totalEvents=GetEventCount()+offset;
1792 const TArrayL64& counters = pTrigger->GetCounters();
1793 if (pTrigger->CallFailed()) return -EPROTO;
1794 for (int i = 0; i < counters.GetSize(); i++) {
1795 ULong64_t count = counters[i];
1797 if (totalEvents>0) ratio=100*(float)count/totalEvents;
1798 HLTLog(level, "Item %d: total events: %d - counted events: %llu (%.1f%%)", i, totalEvents, count, ratio);
1803 int AliHLTGlobalTriggerComponent::AddCTPDecisions(AliHLTGlobalTrigger* pTrigger, const AliHLTCTPData* pCTPData, const AliHLTComponentTriggerData* trigData)
1805 // add trigger decisions for the valid CTP classes
1806 if (!pCTPData || !pTrigger) return 0;
1808 AliHLTUInt64_t triggerMask=pCTPData->Mask();
1809 AliHLTUInt64_t bit0=0x1;
1810 if (!fCTPDecisions) {
1813 fCTPDecisions=new TClonesArray(AliHLTTriggerDecision::Class(), gkNCTPTriggerClasses);
1815 catch (const std::bad_alloc&)
1817 HLTError("Could not allocate memory for the CTP decisions array.");
1820 if (!fCTPDecisions) return -ENOMEM;
1824 fCTPDecisions->ExpandCreate(gkNCTPTriggerClasses);
1826 catch (const std::bad_alloc&)
1828 HLTError("Could not allocate more memory for the CTP decisions array.");
1831 for (int i=0; i<gkNCTPTriggerClasses; i++) {
1832 const char* name=pCTPData->Name(i);
1833 if (triggerMask&(bit0<<i) && name) {
1834 AliHLTTriggerDecision* pDecision=dynamic_cast<AliHLTTriggerDecision*>(fCTPDecisions->At(i));
1837 delete fCTPDecisions;
1841 pDecision->Name(name);
1846 for (int i=0; i<gkNCTPTriggerClasses; i++) {
1847 const char* name=pCTPData->Name(i);
1848 if ((triggerMask&(bit0<<i))==0 || name==NULL) continue;
1849 AliHLTTriggerDecision* pDecision=dynamic_cast<AliHLTTriggerDecision*>(fCTPDecisions->At(i));
1850 HLTDebug("updating CTP trigger decision %d %s (%p casted %p)", i, name, fCTPDecisions->At(i), pDecision);
1851 if (!pDecision) return -ENOENT;
1854 // 13 March 2010 - Optimisation:
1855 // Dont use the EvaluateCTPTriggerClass method, which uses slow TFormula objects.
1856 AliHLTUInt64_t triggers = 0;
1857 if (trigData) triggers = pCTPData->ActiveTriggers(*trigData);
1858 else triggers = pCTPData->Triggers();
1859 result = (triggers&((AliHLTUInt64_t)0x1<<i)) ? true : false;
1860 //if (trigData) result=pCTPData->EvaluateCTPTriggerClass(name, *trigData);
1861 //else result=pCTPData->EvaluateCTPTriggerClass(name);
1862 pDecision->Result(result);
1863 pDecision->TriggerDomain().Clear();
1864 if (trigData) pDecision->TriggerDomain().Add(pCTPData->ReadoutList(*trigData));
1865 else pDecision->TriggerDomain().Add(pCTPData->ReadoutList());
1867 pTrigger->Add(fCTPDecisions->At(i), kAliHLTDataTypeTriggerDecision, kAliHLTVoidDataSpec);
1868 if (pTrigger->CallFailed()) return -EPROTO;