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