]> git.uio.no Git - u/mrichter/AliRoot.git/blob - HLT/BASE/AliHLTSystem.cxx
getting rid of runtime warnings
[u/mrichter/AliRoot.git] / HLT / BASE / AliHLTSystem.cxx
1 // $Id$
2
3 //**************************************************************************
4 //* This file is property of and copyright by the ALICE HLT Project        * 
5 //* ALICE Experiment at CERN, All rights reserved.                         *
6 //*                                                                        *
7 //* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no>        *
8 //*                  for The ALICE HLT Project.                            *
9 //*                                                                        *
10 //* Permission to use, copy, modify and distribute this software and its   *
11 //* documentation strictly for non-commercial purposes is hereby granted   *
12 //* without fee, provided that the above copyright notice appears in all   *
13 //* copies and that both the copyright notice and this permission notice   *
14 //* appear in the supporting documentation. The authors make no claims     *
15 //* about the suitability of this software for any purpose. It is          *
16 //* provided "as is" without express or implied warranty.                  *
17 //**************************************************************************
18
19 /** @file   AliHLTSystem.cxx
20     @author Matthias Richter
21     @date   
22     @brief  Implementation of HLT module management.
23 */
24
25 #if __GNUC__>= 3
26 using namespace std;
27 #endif
28
29 #include <cassert>
30 #include "AliHLTStdIncludes.h"
31 #include "AliHLTSystem.h"
32 #include "AliHLTComponentHandler.h"
33 #include "AliHLTComponent.h"
34 #include "AliHLTConfiguration.h"
35 #include "AliHLTConfigurationHandler.h"
36 #include "AliHLTTask.h"
37 #include "AliHLTModuleAgent.h"
38 #include "AliHLTOfflineInterface.h"
39 #include "AliHLTDataSource.h"
40 #include "AliHLTOUT.h"
41 #include "AliHLTOUTHandler.h"
42 #include <TObjArray.h>
43 #include <TObjString.h>
44 #include <TStopwatch.h>
45 //#include <TSystem.h>
46 #include <TROOT.h>
47 //#include <TInterpreter.h>
48
49 /** HLT default component libraries */
50 const char* AliHLTSystem::fgkHLTDefaultLibs[]= {
51   "libAliHLTUtil.so", 
52   "libAliHLTRCU.so", 
53   "libAliHLTTPC.so", 
54   //  "libAliHLTSample.so",
55   //"libAliHLTPHOS.so",
56   //"libAliHLTMUON.so",
57   "libAliHLTTRD.so",
58   "libAliHLTTrigger.so",
59   NULL
60 };
61
62 /** ROOT macro for the implementation of ROOT specific class methods */
63 ClassImp(AliHLTSystem)
64
65 AliHLTSystem::AliHLTSystem()
66   :
67   fpComponentHandler(new AliHLTComponentHandler()),
68   fpConfigurationHandler(new AliHLTConfigurationHandler()),
69   fTaskList(),
70   fState(0),
71   fChains(),
72   fStopwatches(new TObjArray),
73   fEventCount(-1),
74   fGoodEvents(-1)
75 {
76   // see header file for class documentation
77   // or
78   // refer to README to build package
79   // or
80   // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
81
82   if (fgNofInstances++>0)
83     HLTWarning("multiple instances of AliHLTSystem, you should not use more than one at a time");
84
85   SetGlobalLoggingLevel(kHLTLogDefault);
86   SetFrameworkLog(kHLTLogDefault);
87   if (fpComponentHandler) {
88     AliHLTComponentEnvironment env;
89     memset(&env, 0, sizeof(AliHLTComponentEnvironment));
90     env.fAllocMemoryFunc=AliHLTSystem::AllocMemory;
91     env.fLoggingFunc=NULL;
92     fpComponentHandler->SetEnvironment(&env);
93     InitAliLogFunc(fpComponentHandler);
94     fpComponentHandler->AnnounceVersion();
95   } else {
96     HLTFatal("can not create Component Handler");
97   }
98   if (fpConfigurationHandler) {
99     AliHLTConfiguration::GlobalInit(fpConfigurationHandler);
100   } else {
101     HLTFatal("can not create Configuration Handler");
102   }
103 }
104
105 AliHLTSystem::~AliHLTSystem()
106 {
107   // see header file for class documentation
108   fgNofInstances--;
109   CleanTaskList();
110   AliHLTConfiguration::GlobalDeinit(fpConfigurationHandler);
111   if (fpConfigurationHandler) {
112     delete fpConfigurationHandler;
113   }
114   fpConfigurationHandler=NULL;
115   
116   if (fpComponentHandler) {
117     delete fpComponentHandler;
118   }
119   fpComponentHandler=NULL;
120 }
121
122 int AliHLTSystem::fgNofInstances=0;
123
124 int AliHLTSystem::AddConfiguration(AliHLTConfiguration* pConf)
125 {
126   // see header file for class documentation
127   HLTLogKeyword("configuration handling");
128   int iResult=0;
129   if (pConf) {
130     HLTError("function not yet implemented");
131     iResult=-ENOSYS;
132   } else {
133     iResult=-EINVAL;
134   }
135   return iResult;
136 }
137
138 int AliHLTSystem::InsertConfiguration(AliHLTConfiguration* pConf, AliHLTConfiguration* pPrec)
139 {
140   // see header file for class documentation
141   HLTLogKeyword("configuration handling");
142   int iResult=0;
143   if (pConf) {
144     if (pPrec) {
145       // find the position
146       HLTError("function not yet implemented");
147       iResult=-ENOSYS;
148     }
149   } else {
150     iResult=-EINVAL;
151   }
152   return iResult;
153 }
154
155 int AliHLTSystem::DeleteConfiguration(AliHLTConfiguration* pConf)
156 {
157   // see header file for class documentation
158   HLTLogKeyword("configuration handling");
159   int iResult=0;
160   if (pConf) {
161     HLTError("function not yet implemented");
162     iResult=-ENOSYS;
163   } else {
164     iResult=-EINVAL;
165   }
166   return iResult;
167 }
168
169 int AliHLTSystem::BuildTaskList(const char* id)
170 {
171   // see header file for class documentation
172   int iResult=0;
173   if (id) {
174     if (fpConfigurationHandler) {
175       AliHLTConfiguration* pConf=fpConfigurationHandler->FindConfiguration(id);
176       if (pConf) {
177         iResult=BuildTaskList(pConf);
178       } else {
179         HLTError("unknown configuration \"%s\"", id);
180         iResult=-EEXIST;
181       }
182     } else {
183       iResult=-EFAULT;
184     }
185   } else {
186     iResult=-EINVAL;
187   }
188   return iResult;
189 }
190
191 int AliHLTSystem::BuildTaskList(AliHLTConfiguration* pConf)
192 {
193   // see header file for class documentation
194   int iResult=0;
195   if (pConf) {
196     AliHLTTask* pTask=NULL;
197     if ((pTask=FindTask(pConf->GetName()))!=NULL) {
198       if (pTask->GetConf()!=pConf) {
199         HLTError("configuration mismatch, there is already a task with configuration name \"%s\", but it is different. Most likely configuration %p is not registered properly", pConf->GetName(), pConf);
200         iResult=-EEXIST;
201       }
202       // task for this configuration exists, terminate
203       pTask=NULL;
204     } else if (pConf->SourcesResolved(1)!=1) {
205         HLTError("configuration \"%s\" has unresolved sources, aborting ...", pConf->GetName());
206         iResult=-ENOLINK;
207     } else {
208       pTask=new AliHLTTask(pConf);
209       if (pTask==NULL) {
210         iResult=-ENOMEM;
211       } else {
212         pTask->SetLocalLoggingLevel(GetLocalLoggingLevel());
213       }
214     }
215     static int iterationLevel=0;
216     if (pTask && iResult>=0) {
217       // check for circular dependencies
218       if ((iResult=pConf->FollowDependency(pConf->GetName()))>0) {
219         HLTError("detected circular dependency for configuration \"%s\"", pTask->GetName());
220         pTask->PrintDependencyTree(pTask->GetName(), 1/*use the configuration list*/);
221         HLTError("aborted ...");
222         iResult=-ELOOP;
223       }
224       if (iResult>=0) {
225         // check whether all dependencies are already in the task list
226         // create the missing ones
227         // this step is an iterative process which calls this function again for the missing
228         // configurations, in order to avoid the currently processed task to be created
229         // again it is added to the list temporarily and removed afterwards
230         // This is of high importance to preserve the order of the tasks. Furthermore, the
231         // InsertTask method has to be used in order to set all the cross links right 
232         fTaskList.Add(pTask);
233         AliHLTConfiguration* pDep=pConf->GetFirstSource();
234         while (pDep!=NULL && iResult>=0) {
235           HLTDebug("iteration %d: checking dependency %s (%p)", iterationLevel, pDep->GetName(), pDep);
236           if (FindTask(pDep->GetName())==NULL) {
237             HLTDebug("iteration %d: building task list for configuration %s (%p)", iterationLevel, pDep->GetName(), pDep);
238             iterationLevel++;
239             iResult=BuildTaskList(pDep);
240             iterationLevel--;
241           }
242           pDep=pConf->GetNextSource();
243         }
244         // remove the temporarily added task
245         fTaskList.Remove(pTask);
246
247         // insert the task and set the cross-links
248         if (iResult>=0) {
249           HLTDebug("iteration %d: inserting task %s (%p)", iterationLevel, pTask->GetName(), pTask);
250           iResult=InsertTask(pTask);
251         }
252       } else {
253         delete pTask;
254         pTask=NULL;
255       }
256     }
257   } else {
258     iResult=-EINVAL;
259   }
260   return iResult;
261 }
262
263 int AliHLTSystem::CleanTaskList()
264 {
265   // see header file for class documentation
266   int iResult=0;
267   TObjLink* lnk=NULL;
268   while ((lnk=fTaskList.LastLink())!=NULL) {
269     delete (lnk->GetObject());
270     fTaskList.Remove(lnk);
271   }
272   return iResult;
273 }
274
275 int AliHLTSystem::InsertTask(AliHLTTask* pTask)
276 {
277   // see header file for class documentation
278   int iResult=0;
279   TObjLink *lnk = NULL;
280   if ((iResult=pTask->CheckDependencies())>0)
281     lnk=fTaskList.FirstLink();
282   while (lnk && iResult>0) {
283     AliHLTTask* pCurr = (AliHLTTask*)lnk->GetObject();
284     //HLTDebug("checking  \"%s\"", pCurr->GetName());
285     iResult=pTask->Depends(pCurr);
286     if (iResult>0) {
287       iResult=pTask->SetDependency(pCurr);
288       pCurr->SetTarget(pTask);
289       HLTDebug("set dependency  \"%s\" for configuration \"%s\"", pCurr->GetName(), pTask->GetName());
290     }
291     if (pCurr->Depends(pTask)) {
292       // circular dependency
293       HLTError("circular dependency: can not resolve dependencies for configuration \"%s\"", pTask->GetName());
294       iResult=-ELOOP;
295     } else if ((iResult=pTask->CheckDependencies())>0) {
296       lnk = lnk->Next();
297     }
298   }
299   if (iResult==0) {
300       if (lnk) {
301         fTaskList.AddAfter(lnk, pTask);
302       } else {
303         fTaskList.AddFirst(pTask);
304       }
305       HLTDebug("task \"%s\" (%p) inserted (size %d)", pTask->GetName(), pTask, sizeof(AliHLTTask));
306   } else if (iResult>0) {
307     HLTError("can not resolve dependencies for configuration \"%s\" (%d unresolved)", pTask->GetName(), iResult);
308     iResult=-ENOLINK;
309   }
310   return iResult;
311 }
312
313 AliHLTTask* AliHLTSystem::FindTask(const char* id)
314 {
315   // see header file for class documentation
316   AliHLTTask* pTask=NULL;
317   if (id) {
318     pTask=dynamic_cast<AliHLTTask*>(fTaskList.FindObject(id)); 
319   }
320   return pTask;
321 }
322
323 void AliHLTSystem::PrintTaskList()
324 {
325   // see header file for class documentation
326   HLTLogKeyword("task list");
327   TObjLink *lnk = NULL;
328   HLTMessage("Task List");
329   lnk=fTaskList.FirstLink();
330   while (lnk) {
331     TObject* obj=lnk->GetObject();
332     if (obj) {
333       HLTMessage("  %s - status:", obj->GetName());
334       AliHLTTask* pTask=(AliHLTTask*)obj;
335       pTask->PrintStatus();
336     } else {
337     }
338     lnk = lnk->Next();
339   }
340 }
341
342 int AliHLTSystem::Run(Int_t iNofEvents, int bStop)
343 {
344   // see header file for class documentation
345   int iResult=0;
346   int iCount=0;
347   SetStatusFlags(kRunning);
348   if (fEventCount>=0 || (iResult=InitTasks())>=0) {
349     if (fEventCount>=0 || (iResult=StartTasks())>=0) {
350       if (fEventCount==0) {
351         InitBenchmarking(fStopwatches);
352       } else {
353         //ResumeBenchmarking(fStopwatches);    
354       }
355       for (int i=fEventCount; i<fEventCount+iNofEvents && iResult>=0; i++) {
356         if ((iResult=ProcessTasks(i))>=0) {
357           fGoodEvents++;
358           iCount++;
359         } else {
360           // TODO: define different running modes to either ignore errors in
361           // event processing or not
362           // currently ignored 
363           iResult=0;
364         }
365       }
366       fEventCount+=iNofEvents;
367       if (bStop) StopTasks();
368       //else PauseBenchmarking(fStopwatches);
369     }
370     if (bStop) DeinitTasks();
371   }
372   if (iResult>=0) {
373     iResult=iCount;
374   } else  if (iResult==-126 /*ENOKEY*/) {
375     iResult=0; // do not propagate the error
376   }
377   ClearStatusFlags(kRunning);
378   return iResult;
379 }
380
381 int AliHLTSystem::InitTasks()
382 {
383   // see header file for class documentation
384   int iResult=0;
385   TObjLink *lnk=fTaskList.FirstLink();
386
387   if (lnk==NULL) {
388     HLTWarning("Task list is empty, skipping HLT");
389     return -126 /*ENOKEY*/;
390   }
391   while (lnk && iResult>=0) {
392     TObject* obj=lnk->GetObject();
393     if (obj) {
394       AliHLTTask* pTask=(AliHLTTask*)obj;
395       iResult=pTask->Init(NULL, fpComponentHandler);
396 //       ProcInfo_t ProcInfo;
397 //       gSystem->GetProcInfo(&ProcInfo);
398 //       HLTInfo("task %s initialized (%d), current memory usage %d %d", pTask->GetName(), iResult, ProcInfo.fMemResident, ProcInfo.fMemVirtual);
399     } else {
400     }
401     lnk = lnk->Next();
402   }
403   if (iResult<0) {
404     HLTError("can not initialize task list, error %d", iResult);
405   }
406
407   return iResult;
408 }
409
410 int AliHLTSystem::InitBenchmarking(TObjArray* pStopwatches)
411 {
412   // see header file for class documentation
413   int iResult=0;
414   if (pStopwatches==NULL) return 0;
415
416   for (int i=0; i<(int)AliHLTComponent::kSWTypeCount; i++) {
417     TStopwatch* pStopwatch= new TStopwatch;
418     if (pStopwatch) {
419       pStopwatch->Reset();
420       pStopwatches->AddAt(pStopwatch, i);
421     } else {
422       iResult=-ENOMEM;
423       break;
424     }
425   }
426
427   TObjLink *lnk=fTaskList.FirstLink();
428   while (lnk && iResult>=0) {
429     TObject* obj=lnk->GetObject();
430     if (obj) {
431       AliHLTTask* pTask=(AliHLTTask*)obj;
432       AliHLTComponent* pComp=NULL;
433       if (iResult>=0 && (pComp=pTask->GetComponent())!=NULL) {
434         switch (pComp->GetComponentType()) {
435         case AliHLTComponent::kProcessor:
436           pComp->SetStopwatches(pStopwatches);
437           break;
438         case AliHLTComponent::kSource:
439           {
440             // this switch determines whether the time consumption of the
441             // AliHLTComponent base methods should be counted to the input
442             // stopwatch or base stopwatch.
443             //int inputBase=(int)AliHLTComponent::kSWBase;
444             int inputBase=(int)AliHLTComponent::kSWInput;
445             pComp->SetStopwatch(pStopwatches->At(inputBase), AliHLTComponent::kSWBase);
446             pComp->SetStopwatch(pStopwatches->At((int)AliHLTComponent::kSWInput), AliHLTComponent::kSWDA);
447           }
448           break;
449         case AliHLTComponent::kSink:
450           {
451             // this switch determines whether the time consumption of the
452             // AliHLTComponent base methods should be counted to the output
453             // stopwatch or base stopwatch.
454             //int outputBase=(int)AliHLTComponent::kSWBase;
455             int outputBase=(int)AliHLTComponent::kSWOutput;
456             pComp->SetStopwatch(pStopwatches->At(outputBase), AliHLTComponent::kSWBase);
457             pComp->SetStopwatch(pStopwatches->At((int)AliHLTComponent::kSWOutput), AliHLTComponent::kSWDA);
458           }
459           break;
460         default:
461           HLTWarning("unknown component type %d", (int)pComp->GetComponentType());
462         }
463       }
464     } else {
465     }
466     lnk = lnk->Next();
467   }
468   return iResult;
469 }
470
471 int AliHLTSystem::PrintBenchmarking(TObjArray* pStopwatches, int bClean)
472 {
473   // see header file for class documentation
474   int iInitialized=1;
475   if (pStopwatches==NULL) return 0;
476
477   for (int i=0; i<(int)AliHLTComponent::kSWTypeCount; i++) {
478     if (!dynamic_cast<TStopwatch*>(pStopwatches->At(i))) {
479       iInitialized=0;
480       break;
481     }
482   }
483
484   if (iInitialized!=0) {
485     HLTInfo("HLT statistics:\n"
486             "    base:              R:%.3fs C:%.3fs\n"
487             "    input:             R:%.3fs C:%.3fs\n"
488             "    output:            R:%.3fs C:%.3fs\n"
489             "    event processing : R:%.3fs C:%.3fs"
490             , dynamic_cast<TStopwatch*>(pStopwatches->At(AliHLTComponent::kSWBase))->RealTime()
491             , dynamic_cast<TStopwatch*>(pStopwatches->At(AliHLTComponent::kSWBase))->CpuTime()
492             , dynamic_cast<TStopwatch*>(pStopwatches->At(AliHLTComponent::kSWInput))->RealTime()
493             , dynamic_cast<TStopwatch*>(pStopwatches->At(AliHLTComponent::kSWInput))->CpuTime()
494             , dynamic_cast<TStopwatch*>(pStopwatches->At(AliHLTComponent::kSWOutput))->RealTime()
495             , dynamic_cast<TStopwatch*>(pStopwatches->At(AliHLTComponent::kSWOutput))->CpuTime()
496             , dynamic_cast<TStopwatch*>(pStopwatches->At(AliHLTComponent::kSWDA))->RealTime()
497             , dynamic_cast<TStopwatch*>(pStopwatches->At(AliHLTComponent::kSWDA))->CpuTime()
498             );
499   }
500
501   if (bClean) {
502     for (int i=0; i<(int)AliHLTComponent::kSWTypeCount; i++) {
503       TObject* pObj=pStopwatches->RemoveAt(i);
504       if (pObj) delete pObj;
505     }
506   }
507   return 0;
508 }
509
510 int AliHLTSystem::StartTasks()
511 {
512   // see header file for class documentation
513   int iResult=0;
514   TObjLink *lnk=fTaskList.FirstLink();
515   while (lnk && iResult>=0) {
516     TObject* obj=lnk->GetObject();
517     if (obj) {
518       AliHLTTask* pTask=(AliHLTTask*)obj;
519       iResult=pTask->StartRun();
520 //       ProcInfo_t ProcInfo;
521 //       gSystem->GetProcInfo(&ProcInfo);
522 //       HLTInfo("task %s started (%d), current memory usage %d %d", pTask->GetName(), iResult, ProcInfo.fMemResident, ProcInfo.fMemVirtual);
523     } else {
524     }
525     lnk = lnk->Next();
526   }
527   if (iResult<0) {
528     HLTError("can not start task list, error %d", iResult);
529   } else {
530     fEventCount=0;
531     fGoodEvents=0;
532     if ((iResult=SendControlEvent(kAliHLTDataTypeSOR))<0) {
533       HLTError("can not send SOR event");
534     }
535   }
536   return iResult;
537 }
538
539 int AliHLTSystem::ProcessTasks(Int_t eventNo)
540 {
541   // see header file for class documentation
542   int iResult=0;
543   HLTDebug("processing event no %d", eventNo);
544   TObjLink *lnk=fTaskList.FirstLink();
545   while (lnk && iResult>=0) {
546     TObject* obj=lnk->GetObject();
547     if (obj) {
548       AliHLTTask* pTask=(AliHLTTask*)obj;
549       iResult=pTask->ProcessTask(eventNo);
550 //       ProcInfo_t ProcInfo;
551 //       gSystem->GetProcInfo(&ProcInfo);
552 //       HLTInfo("task %s processed (%d), current memory usage %d %d", pTask->GetName(), iResult, ProcInfo.fMemResident, ProcInfo.fMemVirtual);
553     } else {
554     }
555     lnk = lnk->Next();
556   }
557
558   if (iResult>=0) {
559     HLTImportant("Event %d successfully finished (%d)", eventNo, iResult);
560     iResult=0;
561   } else {
562     HLTError("Processing of event %d failed (%d)", eventNo, iResult);
563   }
564
565   return iResult;
566 }
567
568 int AliHLTSystem::StopTasks()
569 {
570   // see header file for class documentation
571   int iResult=0;
572   if ((iResult=SendControlEvent(kAliHLTDataTypeEOR))<0) {
573     HLTError("can not send EOR event");
574   }
575   TObjLink *lnk=fTaskList.FirstLink();
576   while (lnk) {
577     TObject* obj=lnk->GetObject();
578     if (obj) {
579       AliHLTTask* pTask=(AliHLTTask*)obj;
580       int locResult=pTask->EndRun();
581       if (iResult>=0 && locResult<0) iResult=locResult;
582 //       ProcInfo_t ProcInfo;
583 //       gSystem->GetProcInfo(&ProcInfo);
584 //       HLTInfo("task %s stopped (%d), current memory usage %d %d", pTask->GetName(), iResult, ProcInfo.fMemResident, ProcInfo.fMemVirtual);
585     } else {
586     }
587     lnk = lnk->Next();
588   }
589   PrintBenchmarking(fStopwatches, 1 /*clean*/);
590   return iResult;
591 }
592
593 int AliHLTSystem::SendControlEvent(AliHLTComponentDataType dt)
594 {
595   // see header file for class documentation
596
597   // disabled for the moment
598   return 0;
599
600   int iResult=0;
601   AliHLTRunDesc runDesc;
602   memset(&runDesc, 0, sizeof(AliHLTRunDesc));
603   runDesc.fStructSize=sizeof(AliHLTRunDesc);
604   AliHLTDataSource::AliSpecialEventGuard g(&runDesc, dt, kAliHLTVoidDataSpec);
605   HLTDebug("sending event %s, run descriptor %p", AliHLTComponent::DataType2Text(dt).c_str(), &runDesc);
606   TObjLink *lnk=fTaskList.FirstLink();
607   while (lnk && iResult>=0) {
608     TObject* obj=lnk->GetObject();
609     if (obj) {
610       AliHLTTask* pTask=(AliHLTTask*)obj;
611       iResult=pTask->ProcessTask(-1);
612     } else {
613     }
614     lnk = lnk->Next();
615   }
616   HLTDebug("event %s done (%d)", AliHLTComponent::DataType2Text(dt).c_str(), iResult);
617   return iResult;
618 }
619
620 int AliHLTSystem::DeinitTasks()
621 {
622   // see header file for class documentation
623   int iResult=0;
624   TObjLink *lnk=fTaskList.FirstLink();
625   while (lnk && iResult>=0) {
626     TObject* obj=lnk->GetObject();
627     if (obj) {
628       AliHLTTask* pTask=(AliHLTTask*)obj;
629       iResult=pTask->Deinit();
630 //       ProcInfo_t ProcInfo;
631 //       gSystem->GetProcInfo(&ProcInfo);
632 //       HLTInfo("task %s cleaned (%d), current memory usage %d %d", pTask->GetName(), iResult, ProcInfo.fMemResident, ProcInfo.fMemVirtual);
633     } else {
634     }
635     lnk = lnk->Next();
636   }
637   fEventCount=-1;
638   fGoodEvents=-1;
639
640   return iResult;
641 }
642
643 void* AliHLTSystem::AllocMemory( void* /*param*/, unsigned long size )
644 {
645   // see header file for class documentation
646   void* p=NULL;
647   try {
648     p=(void*)new char[size];
649   }
650   catch (...) {
651     AliHLTLogging log;
652     log.LoggingVarargs(kHLTLogError, "AliHLTSystem" , "AllocMemory" , __FILE__ , __LINE__ , "exeption during memory allocation" );
653   }
654   return p;
655 }
656
657 int AliHLTSystem::Reconstruct(int nofEvents, AliRunLoader* runLoader, 
658                               AliRawReader* rawReader)
659 {
660   // see header file for class documentation
661   int iResult=0;
662   if (runLoader || rawReader || nofEvents==0) {
663     if (nofEvents>0) {HLTInfo("Run Loader %p, Raw Reader %p , %d event(s)", runLoader, rawReader, nofEvents);}
664     if (CheckStatus(kReady)) {
665       if (nofEvents==0) {
666         // special case to close the reconstruction
667         if (!CheckStatus(kError)) {
668         StopTasks();
669         DeinitTasks();
670         }
671       } else {
672       if ((iResult=AliHLTOfflineInterface::SetParamsToComponents(runLoader, rawReader))>=0) {
673         // the system always remains started after event processing, a specific
674         // call with nofEvents==0 is needed to execute the stop sequence
675         if ((iResult=Run(nofEvents, 0))<0) SetStatusFlags(kError);
676       }
677       }
678     } else {
679       HLTError("wrong state %#x, required flags %#x", GetStatusFlags(), kReady);
680     }
681   } else {
682     HLTError("missing RunLoader (%p)/RawReader (%p) instance", runLoader, rawReader);
683     iResult=-EINVAL;
684   }
685   return iResult;
686 }
687
688 int AliHLTSystem::FillESD(int eventNo, AliRunLoader* runLoader, AliESDEvent* esd)
689 {
690   // see header file for class documentation
691   int iResult=0;
692   if (runLoader || esd) {
693     HLTInfo("Event %d: Run Loader %p, ESD %p", eventNo, runLoader, esd);
694     iResult=AliHLTOfflineInterface::FillComponentESDs(eventNo, runLoader, esd);
695   } else {
696     HLTError("missing run loader/ESD instance(s)");
697     iResult=-EINVAL;
698   }
699   return iResult;
700 }
701
702 int AliHLTSystem::ProcessHLTOUT(AliHLTOUT* pHLTOUT, AliESDEvent* esd)
703 {
704   // see header file for class documentation
705   int iResult=0;
706   if (!pHLTOUT) return -EINVAL;
707
708   HLTDebug("processing %d HLT data blocks", pHLTOUT->GetNofDataBlocks());
709   AliHLTOUT::AliHLTOUTHandlerListEntryVector esdHandlers;
710   for (iResult=pHLTOUT->SelectFirstDataBlock();
711        iResult>=0;
712        iResult=pHLTOUT->SelectNextDataBlock()) {
713     AliHLTComponentDataType dt=kAliHLTVoidDataType;
714     AliHLTUInt32_t spec=kAliHLTVoidDataSpec;
715     pHLTOUT->GetDataBlockDescription(dt, spec);
716     AliHLTOUTHandler* pHandler=pHLTOUT->GetHandler();
717     AliHLTModuleAgent::AliHLTOUTHandlerType handlerType=pHLTOUT->GetDataBlockHandlerType();
718     if (!pHandler && (dt==kAliHLTDataTypeESDObject || dt==kAliHLTDataTypeESDTree)) {
719       handlerType=AliHLTModuleAgent::kEsd;
720     }
721     const char* pMsg="invalid";
722     switch (handlerType) {
723     case AliHLTModuleAgent::kEsd:
724       {
725         if (pHandler) {
726           // preprocess and write later
727           AliHLTOUT::AliHLTOUTLockGuard g(pHLTOUT);
728           pHandler->ProcessData(pHLTOUT);
729           pHLTOUT->InsertHandler(esdHandlers, pHLTOUT->GetDataBlockHandlerDesc());
730         } else {
731           // write directly
732           const AliHLTUInt8_t* pBuffer=NULL;
733           AliHLTUInt32_t size=0;
734           if (pHLTOUT->GetDataBuffer(pBuffer, size)>=0) {
735             pHLTOUT->WriteESD(pBuffer, size, dt);
736             pHLTOUT->ReleaseDataBuffer(pBuffer);
737           }
738         }
739       }
740       break;
741     case AliHLTModuleAgent::kRawReader:
742       // handled in the AliRawReaderHLT
743       break;
744     case AliHLTModuleAgent::kRawStream:
745       HLTWarning("HLTOUT handler type 'kRawStream' not yet implemented: agent %s, data type %s, specification %#x",
746                  pMsg, pHLTOUT->GetAgent()?pHLTOUT->GetAgent()->GetModuleId():"invalid",
747                  AliHLTComponent::DataType2Text(dt).c_str(), spec);
748       break;
749     case AliHLTModuleAgent::kChain:
750       HLTWarning("HLTOUT handler type 'kChain' not yet implemented: agent %s, data type %s, specification %#x",
751                  pMsg, pHLTOUT->GetAgent()?pHLTOUT->GetAgent()->GetModuleId():"invalid",
752                  AliHLTComponent::DataType2Text(dt).c_str(), spec);
753       break;
754     case AliHLTModuleAgent::kProprietary:
755       HLTDebug("processing proprietary data: agent %s, data type %s, specification %#x",
756                  pMsg, pHLTOUT->GetAgent()?pHLTOUT->GetAgent()->GetModuleId():"invalid",
757                  AliHLTComponent::DataType2Text(dt).c_str(), spec);
758       if (pHandler) {
759         AliHLTOUT::AliHLTOUTLockGuard g(pHLTOUT);
760         int res=pHandler->ProcessData(pHLTOUT);
761         if (res<0) {
762           HLTWarning("processing proprietary data failed (%d): agent %s, data type %s, specification %#x",
763                      res, pMsg, pHLTOUT->GetAgent()?pHLTOUT->GetAgent()->GetModuleId():"invalid",
764                      AliHLTComponent::DataType2Text(dt).c_str(), spec);
765         }
766       }
767       break;
768     case AliHLTModuleAgent::kUnknownOutput:
769       pMsg="unknown";
770       // fall trough intended
771     default:
772       HLTWarning("%s handler type: agent %s, data type %s, specification %#x, ... skipping data block",
773                  pMsg, pHLTOUT->GetAgent()?pHLTOUT->GetAgent()->GetModuleId():"invalid",
774                  AliHLTComponent::DataType2Text(dt).c_str(), spec);
775     }
776   }
777   // TODO: the return value of SelectFirst/NextDataBlock must be
778   // changed in order to avoid this check
779   if (iResult==-ENOENT) iResult=0;
780
781   AliHLTOUT::AliHLTOUTHandlerListEntryVector::iterator esdHandler;
782   // write all postponed esd data blocks
783   // first come first serve: the ESD of the first handler is also filled into
784   // the main ESD. Has to be changed later.
785   AliESDEvent* pMasterESD=esd;
786   for (esdHandler=esdHandlers.begin(); esdHandler!=esdHandlers.end() && iResult>=0; esdHandler++) {
787     AliHLTOUTHandler* pHandler=*esdHandler;
788     const AliHLTUInt8_t* pBuffer=NULL;
789     AliHLTUInt32_t size=0;
790     if ((size=pHandler->GetProcessedData(pBuffer))>0) {
791       AliHLTModuleAgent::AliHLTOUTHandlerDesc desc=*esdHandler;
792       AliHLTComponentDataType dt=desc;
793       pHLTOUT->WriteESD(pBuffer, size, dt);
794       if (pMasterESD) {
795         pHLTOUT->WriteESD(pBuffer, size, dt, pMasterESD);
796         pMasterESD=NULL;
797       }
798       pHandler->ReleaseProcessedData(pBuffer, size);
799     }
800   }
801
802   return iResult;
803 }
804
805 int AliHLTSystem::LoadComponentLibraries(const char* libraries)
806 {
807   // see header file for class documentation
808   int iResult=0;
809   if (libraries) {
810     if (fpComponentHandler) {
811       TString libs(libraries);
812       TObjArray* pTokens=libs.Tokenize(" ");
813       if (pTokens) {
814         int iEntries=pTokens->GetEntries();
815         for (int i=0; i<iEntries && iResult>=0; i++) {
816           iResult=fpComponentHandler->LoadLibrary((((TObjString*)pTokens->At(i))->GetString()).Data());
817         }
818         delete pTokens;
819       }
820       if (iResult>=0) {
821         SetStatusFlags(kLibrariesLoaded);
822       } else {
823         // lets see if we need this, probably not
824         //fpComponentHandler->UnloadLibraries();
825         ClearStatusFlags(kLibrariesLoaded);
826       }
827     } else {
828       iResult=-EFAULT;
829       HLTFatal("no component handler available");
830     }
831   } else {
832     iResult=-EINVAL;
833   }
834   return iResult;
835 }
836
837 int AliHLTSystem::Configure(AliRunLoader* runloader)
838 {
839   // see header file for class documentation
840   return Configure(NULL, runloader);
841 }
842
843 int AliHLTSystem::Configure(AliRawReader* rawReader, AliRunLoader* runloader)
844 {
845   // see header file for class documentation
846   int iResult=0;
847   if (CheckStatus(kRunning)) {
848     HLTError("HLT system in running state, can not configure");
849     return -EBUSY;
850   }
851   ClearStatusFlags(kTaskListCreated);
852   if (CheckFilter(kHLTLogDebug))
853     AliHLTModuleAgent::PrintStatus();
854   if (CheckStatus(kConfigurationLoaded)==0) {
855     iResult=LoadConfigurations(rawReader, runloader);
856   } else {
857     if (fChains.Length()==0) {
858       HLTError("custom configuration(s) specified, but no configuration to run in local reconstruction, use \'localrec=<conf>\' option");
859       iResult=-ENOENT;
860     }
861   }
862   if (iResult>=0) {
863     SetStatusFlags(kConfigurationLoaded);
864     if (CheckFilter(kHLTLogDebug))
865       fpConfigurationHandler->PrintConfigurations();
866     iResult=BuildTaskListsFromReconstructionChains(rawReader, runloader);
867     if (iResult>=0) {
868       SetStatusFlags(kTaskListCreated);
869     }
870   }
871   if (iResult<0) SetStatusFlags(kError);
872   
873   return iResult;
874 }
875
876 int AliHLTSystem::ScanOptions(const char* options)
877 {
878   // see header file for class documentation
879   int iResult=0;
880   if (options) {
881     //AliHLTComponentHandler::TLibraryMode libMode=AliHLTComponentHandler::kDynamic;
882     TString libs("");
883     TString alloptions(options);
884     TObjArray* pTokens=alloptions.Tokenize(" ");
885     if (pTokens) {
886       int iEntries=pTokens->GetEntries();
887       for (int i=0; i<iEntries; i++) {
888         TString token=(((TObjString*)pTokens->At(i))->GetString());
889         if (token.Contains("loglevel=")) {
890           TString param=token.ReplaceAll("loglevel=", "");
891           if (param.IsDigit()) {
892             SetGlobalLoggingLevel((AliHLTComponentLogSeverity)param.Atoi());
893           } else if (param.BeginsWith("0x") &&
894                      param.Replace(0,2,"",0).IsHex()) {
895             int severity=0;
896             sscanf(param.Data(),"%x", &severity);
897             SetGlobalLoggingLevel((AliHLTComponentLogSeverity)severity);
898           } else {
899             HLTWarning("wrong parameter for option \'loglevel=\', (hex) number expected");
900           }
901         } else if (token.Contains("frameworklog=")) {
902           TString param=token.ReplaceAll("frameworklog=", "");
903           if (param.IsDigit()) {
904             SetFrameworkLog((AliHLTComponentLogSeverity)param.Atoi());
905           } else if (param.BeginsWith("0x") &&
906                      param.Replace(0,2,"",0).IsHex()) {
907             int severity=0;
908             sscanf(param.Data(),"%x", &severity);
909             SetFrameworkLog((AliHLTComponentLogSeverity)severity);
910           } else {
911             HLTWarning("wrong parameter for option \'loglevel=\', (hex) number expected");
912           }
913         } else if (token.Contains("alilog=off")) {
914           SwitchAliLog(0);
915         } else if (token.Contains("config=")) {
916           TString param=token.ReplaceAll("config=", "");
917           Int_t error=0;
918           gROOT->Macro(param.Data(), &error);
919           if (error==0) {
920             SetStatusFlags(kConfigurationLoaded);
921           } else {
922             HLTError("can not execute macro \'%s\'", param.Data());
923             iResult=-EBADF;
924           }
925         } else if (token.Contains("chains=")) {
926           TString param=token.ReplaceAll("chains=", "");
927           fChains=param.ReplaceAll(",", " ");
928         } else if (token.Contains("libmode=")) {
929           TString param=token.ReplaceAll("libmode=", "");
930           param.ReplaceAll(",", " ");
931           if (fpComponentHandler) {
932             if (param.CompareTo("static")==0) {
933               fpComponentHandler->SetLibraryMode(AliHLTComponentHandler::kStatic);
934             } else if (param.CompareTo("dynamic")==0) {
935               fpComponentHandler->SetLibraryMode(AliHLTComponentHandler::kDynamic);
936             } else {
937               HLTWarning("wrong argument for option \'libmode=\', use \'static\' or \'dynamic\'");
938             }
939           }
940         } else if (token.BeginsWith("lib") && token.EndsWith(".so")) {
941           libs+=token;
942           libs+=" ";
943         } else {
944           HLTWarning("unknown option \'%s\'", token.Data());
945         }
946       }
947       delete pTokens;
948     }
949
950     if (iResult>=0) {
951       if (libs.IsNull()) {
952         const char** deflib=fgkHLTDefaultLibs;
953         while (*deflib) {
954           libs+=*deflib++;
955           libs+=" ";
956         }
957       }
958       if ((!CheckStatus(AliHLTSystem::kLibrariesLoaded)) &&
959           (LoadComponentLibraries(libs.Data())<0)) {
960         HLTError("error while loading HLT libraries");
961         iResult=-EFAULT;
962       }
963     }
964   }
965   return iResult;
966 }
967
968 int AliHLTSystem::Reset(int bForce)
969 {
970   // see header file for class documentation
971   int iResult=0;
972   if (!bForce && CheckStatus(kRunning)) {
973     HLTError("HLT system in running state, can not configure");
974     return -EBUSY;
975   }
976   CleanTaskList();
977   ClearStatusFlags(~kUninitialized);
978   return iResult;
979 }
980
981 int AliHLTSystem::LoadConfigurations(AliRawReader* rawReader, AliRunLoader* runloader)
982 {
983   // see header file for class documentation
984   if (CheckStatus(kRunning)) {
985     HLTError("HLT system in running state, can not configure");
986     return -EBUSY;
987   }
988   int iResult=0;
989   AliHLTModuleAgent* pAgent=AliHLTModuleAgent::GetFirstAgent();
990   while (pAgent && iResult>=0) {
991     const char* deplibs=pAgent->GetRequiredComponentLibraries();
992     if (deplibs) {
993       HLTDebug("load libraries \'%s\' for agent %s (%p)", deplibs, pAgent->GetName(), pAgent);
994       iResult=LoadComponentLibraries(deplibs);
995     }
996     if (iResult>=0) {
997       HLTDebug("load configurations for agent %s (%p)", pAgent->GetName(), pAgent);
998       pAgent->CreateConfigurations(fpConfigurationHandler, rawReader, runloader);
999       pAgent=AliHLTModuleAgent::GetNextAgent();
1000     }
1001   }
1002   return iResult;
1003 }
1004
1005 int AliHLTSystem::BuildTaskListsFromReconstructionChains(AliRawReader* rawReader, AliRunLoader* runloader)
1006 {
1007   // see header file for class documentation
1008   if (CheckStatus(kRunning)) {
1009     HLTError("HLT system in running state, can not configure");
1010     return -EBUSY;
1011   }
1012   if (!CheckStatus(kConfigurationLoaded)) {
1013     HLTWarning("configurations not yet loaded");
1014     return 0;
1015   }
1016
1017   int iResult=0;
1018   int bHaveOutput=0;
1019
1020   // query chains
1021   TString chains;
1022   if (fChains.Length()>0) {
1023     chains=fChains;
1024     HLTImportant("custom reconstruction chain: %s", chains.Data());
1025   } else {
1026     AliHLTModuleAgent* pAgent=AliHLTModuleAgent::GetFirstAgent();
1027     while ((pAgent || fChains.Length()>0) && iResult>=0) {
1028       const char* agentchains=pAgent->GetReconstructionChains(rawReader, runloader);
1029       if (agentchains) {
1030         if (!chains.IsNull()) chains+="";
1031         chains+=agentchains;
1032         HLTInfo("reconstruction chains for agent %s (%p): %s", pAgent->GetName(), pAgent, agentchains);
1033       }
1034       pAgent=AliHLTModuleAgent::GetNextAgent();
1035     }
1036   }
1037
1038   // build task list for chains
1039   TObjArray* pTokens=chains.Tokenize(" ");
1040   if (pTokens) {
1041     int iEntries=pTokens->GetEntries();
1042     for (int i=0; i<iEntries && iResult>=0; i++) {
1043       const char* pCID=((TObjString*)pTokens->At(i))->GetString().Data();
1044       AliHLTConfiguration* pConf=fpConfigurationHandler->FindConfiguration(pCID);
1045       if (pConf) {
1046         iResult=BuildTaskList(pConf);
1047         if (runloader) {
1048           assert(fpComponentHandler!=NULL);
1049           TString cid=pConf->GetComponentID();
1050           if (cid.CompareTo("HLTOUT")==0) {
1051             // remove from the input of a global HLTOUT configuration
1052             chains.ReplaceAll(pCID, "");
1053           } else if (bHaveOutput==0) {
1054             // check whether this configuration produces data output
1055             if ((bHaveOutput=fpComponentHandler->HasOutputData(cid.Data()))<0) {
1056               bHaveOutput=0;
1057               chains.ReplaceAll(pCID, "");
1058             }
1059           }
1060         }
1061       } else {
1062         HLTWarning("can not find configuration %s", pCID);
1063       }
1064     }
1065     delete pTokens;
1066   }
1067
1068   // build HLTOUT for simulation
1069   if (iResult>=0 && runloader) {
1070     if (bHaveOutput) {
1071       // there are components in the chain which produce data which need to be
1072       // piped to an HLTOUT
1073       if (fpComponentHandler->FindComponentIndex("HLTOUT")>=0 ||
1074           LoadComponentLibraries("libHLTsim.so")>=0) {
1075         AliHLTConfiguration globalout("_globalout_", "HLTOUT", chains.Data(), NULL);
1076         iResult=BuildTaskList("_globalout_");
1077       } else {
1078         HLTError("can not load libHLTsim.so and HLTOUT component");
1079         iResult=-EFAULT;
1080       }
1081     }
1082   }
1083
1084   if (iResult>=0) SetStatusFlags(kTaskListCreated);
1085
1086   return iResult;
1087 }
1088
1089 int AliHLTSystem::CheckStatus(int flag)
1090 {
1091   // see header file for class documentation
1092   if (flag==kUninitialized && flag==fState) return 1;
1093   if ((fState&flag)==flag) return 1;
1094   return 0;
1095 }
1096
1097 int AliHLTSystem::GetStatusFlags()
1098 {
1099   // see header file for class documentation
1100   return fState;
1101 }
1102
1103 int AliHLTSystem::SetStatusFlags(int flags)
1104 {
1105   // see header file for class documentation
1106   fState|=flags;
1107   return fState;
1108 }
1109
1110 int AliHLTSystem::ClearStatusFlags(int flags)
1111 {
1112   // see header file for class documentation
1113   fState&=~flags;
1114   return fState;
1115 }
1116
1117 void* AliHLTSystem::FindDynamicSymbol(const char* library, const char* symbol)
1118 {
1119   // see header file for class documentation
1120   if (fpComponentHandler==NULL) return NULL;
1121   return fpComponentHandler->FindSymbol(library, symbol);
1122 }
1123
1124 void AliHLTSystem::SetFrameworkLog(AliHLTComponentLogSeverity level) 
1125 {
1126   // see header file for class documentation
1127   SetLocalLoggingLevel(level);
1128   if (fpComponentHandler) fpComponentHandler->SetLocalLoggingLevel(level);
1129   if (fpConfigurationHandler) fpConfigurationHandler->SetLocalLoggingLevel(level);
1130 }