]> git.uio.no Git - u/mrichter/AliRoot.git/blob - HLT/BASE/AliHLTSystem.cxx
Fixing bug related to incorrect unloading of shared library and class code.
[u/mrichter/AliRoot.git] / HLT / BASE / AliHLTSystem.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: Matthias Richter <Matthias.Richter@ift.uib.no>        *
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   AliHLTSystem.cxx
19     @author Matthias Richter
20     @date   
21     @brief  Implementation of HLT module management.
22 */
23
24 #if __GNUC__>= 3
25 using namespace std;
26 #endif
27
28 #include <cassert>
29 #include "AliHLTStdIncludes.h"
30 #include "AliHLTSystem.h"
31 #include "AliHLTComponentHandler.h"
32 #include "AliHLTComponent.h"
33 #include "AliHLTConfiguration.h"
34 #include "AliHLTConfigurationHandler.h"
35 #include "AliHLTTask.h"
36 #include "AliHLTModuleAgent.h"
37 #include "AliHLTOfflineInterface.h"
38 #include "AliHLTDataSource.h"
39 #include "AliHLTOUT.h"
40 #include "AliHLTOUTHandler.h"
41 #include "AliHLTOUTTask.h"
42 #include "AliHLTControlTask.h"
43 #include "AliHLTDataBuffer.h"
44 #include "AliHLTMisc.h"
45 #include <TObjArray.h>
46 #include <TObjString.h>
47 #include <TStopwatch.h>
48 #include <TList.h>
49 //#include <TSystem.h>
50 #include <TROOT.h>
51 //#include <TInterpreter.h>
52
53 /** HLT default component libraries */
54 const char* AliHLTSystem::fgkHLTDefaultLibs[]= {
55   "libAliHLTUtil.so", 
56   "libAliHLTRCU.so", 
57   "libAliHLTTPC.so", 
58   //  "libAliHLTSample.so",
59   //  "libAliHLTPHOS.so",
60   "libAliHLTMUON.so",
61   "libAliHLTTRD.so",
62   "libAliHLTITS.so",
63   "libAliHLTGlobal.so",
64   "libAliHLTTrigger.so",
65   NULL
66 };
67
68 /** ROOT macro for the implementation of ROOT specific class methods */
69 ClassImp(AliHLTSystem)
70
71 AliHLTSystem::AliHLTSystem(AliHLTComponentLogSeverity loglevel, const char* name)
72   :
73   fpComponentHandler(AliHLTComponentHandler::CreateHandler()),
74   fpConfigurationHandler(AliHLTConfigurationHandler::CreateHandler()),
75   fTaskList(),
76   fState(0),
77   fChains(),
78   fStopwatches(new TObjArray),
79   fEventCount(-1),
80   fGoodEvents(-1),
81   fpChainHandlers(NULL),
82   fpEsdHandlers(NULL),
83   fpProprietaryHandlers(NULL),
84   fpHLTOUTTask(NULL),
85   fpControlTask(NULL),
86   fName(name)
87   , fECSParams()
88 {
89   // see header file for class documentation
90   // or
91   // refer to README to build package
92   // or
93   // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
94
95   if (fgNofInstances++>0) {
96     // July 2008: multiple instances are now allowed
97     // AliHLTSystem is used in multiple instances for the kChain HLTOUT handler
98     //HLTWarning("multiple instances of AliHLTSystem, you should not use more than one at a time");
99   }
100
101   SetGlobalLoggingLevel(loglevel);
102   SetFrameworkLog(loglevel);
103   if (fpComponentHandler) {
104     AliHLTAnalysisEnvironment env;
105     memset(&env, 0, sizeof(AliHLTAnalysisEnvironment));
106     env.fStructSize=sizeof(AliHLTAnalysisEnvironment);
107     env.fAllocMemoryFunc=AliHLTSystem::AllocMemory;
108     env.fGetEventDoneDataFunc=AliHLTSystem::AllocEventDoneData;
109     env.fLoggingFunc=NULL;
110     fpComponentHandler->SetEnvironment(&env);
111     InitAliLogFunc(fpComponentHandler);
112     if (fgNofInstances==1) {
113     fpComponentHandler->AnnounceVersion();
114     }
115   } else {
116     HLTFatal("can not create Component Handler");
117   }
118   if (fpConfigurationHandler) {
119     AliHLTConfiguration::GlobalInit(fpConfigurationHandler);
120   } else {
121     HLTFatal("can not create Configuration Handler");
122   }
123 }
124
125 AliHLTSystem::~AliHLTSystem()
126 {
127   // see header file for class documentation
128   fgNofInstances--;
129   CleanHLTOUT();
130   CleanTaskList();
131   AliHLTConfiguration::GlobalDeinit(fpConfigurationHandler);
132   if (fpConfigurationHandler) {
133     fpConfigurationHandler->Destroy();
134   }
135   fpConfigurationHandler=NULL;
136   
137   if (fpComponentHandler) {
138     fpComponentHandler->Destroy();
139   }
140   fpComponentHandler=NULL;
141
142   // note: fpHLTOUTTask and fpControlTask are deleted by
143   // CleanTaskList
144 }
145
146 int AliHLTSystem::fgNofInstances=0;
147
148 int AliHLTSystem::AddConfiguration(AliHLTConfiguration* pConf)
149 {
150   // see header file for class documentation
151   HLTLogKeyword("configuration handling");
152   int iResult=0;
153   if (pConf) {
154     HLTError("function not yet implemented");
155     iResult=-ENOSYS;
156   } else {
157     iResult=-EINVAL;
158   }
159   return iResult;
160 }
161
162 int AliHLTSystem::InsertConfiguration(AliHLTConfiguration* pConf, AliHLTConfiguration* pPrec)
163 {
164   // see header file for class documentation
165   HLTLogKeyword("configuration handling");
166   int iResult=0;
167   if (pConf) {
168     if (pPrec) {
169       // find the position
170       HLTError("function not yet implemented");
171       iResult=-ENOSYS;
172     }
173   } else {
174     iResult=-EINVAL;
175   }
176   return iResult;
177 }
178
179 int AliHLTSystem::DeleteConfiguration(AliHLTConfiguration* pConf)
180 {
181   // see header file for class documentation
182   HLTLogKeyword("configuration handling");
183   int iResult=0;
184   if (pConf) {
185     HLTError("function not yet implemented");
186     iResult=-ENOSYS;
187   } else {
188     iResult=-EINVAL;
189   }
190   return iResult;
191 }
192
193 int AliHLTSystem::BuildTaskList(const char* id)
194 {
195   // see header file for class documentation
196   int iResult=0;
197   if (id) {
198     if (fpConfigurationHandler) {
199       AliHLTConfiguration* pConf=fpConfigurationHandler->FindConfiguration(id);
200       if (pConf) {
201         iResult=BuildTaskList(pConf);
202       } else {
203         HLTError("unknown configuration \"%s\"", id);
204         iResult=-EEXIST;
205       }
206     } else {
207       iResult=-EFAULT;
208     }
209   } else {
210     iResult=-EINVAL;
211   }
212   return iResult;
213 }
214
215 int AliHLTSystem::BuildTaskList(AliHLTConfiguration* pConf)
216 {
217   // see header file for class documentation
218   int iResult=0;
219   if (pConf) {
220     AliHLTTask* pTask=NULL;
221     if ((pTask=FindTask(pConf->GetName()))!=NULL) {
222       if (pTask->GetConf()!=pConf) {
223         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);
224         iResult=-EEXIST;
225       }
226       // task for this configuration exists, terminate
227       pTask=NULL;
228     } else if (pConf->SourcesResolved(1)!=1) {
229         HLTError("configuration \"%s\" has unresolved sources, aborting ...", pConf->GetName());
230         iResult=-ENOLINK;
231     } else {
232       pTask=new AliHLTTask(pConf);
233       if (pTask==NULL) {
234         iResult=-ENOMEM;
235       } else {
236         pTask->SetLocalLoggingLevel(GetLocalLoggingLevel());
237       }
238     }
239     static int iterationLevel=0;
240     if (pTask && iResult>=0) {
241       // check for circular dependencies
242       if ((iResult=pConf->FollowDependency(pConf->GetName()))>0) {
243         HLTError("detected circular dependency for configuration \"%s\"", pTask->GetName());
244         pTask->PrintDependencyTree(pTask->GetName(), 1/*use the configuration list*/);
245         HLTError("aborted ...");
246         iResult=-ELOOP;
247       }
248       if (iResult>=0) {
249         // check whether all dependencies are already in the task list
250         // create the missing ones
251         // this step is an iterative process which calls this function again for the missing
252         // configurations, in order to avoid the currently processed task to be created
253         // again it is added to the list temporarily and removed afterwards
254         // This is of high importance to preserve the order of the tasks. Furthermore, the
255         // InsertTask method has to be used in order to set all the cross links right 
256         fTaskList.Add(pTask);
257         AliHLTConfiguration* pDep=pConf->GetFirstSource();
258         while (pDep!=NULL && iResult>=0) {
259           HLTDebug("iteration %d: checking dependency %s (%p)", iterationLevel, pDep->GetName(), pDep);
260           if (FindTask(pDep->GetName())==NULL) {
261             HLTDebug("iteration %d: building task list for configuration %s (%p)", iterationLevel, pDep->GetName(), pDep);
262             iterationLevel++;
263             iResult=BuildTaskList(pDep);
264             iterationLevel--;
265           }
266           pDep=pConf->GetNextSource();
267         }
268         // remove the temporarily added task
269         fTaskList.Remove(pTask);
270
271         // insert the task and set the cross-links
272         if (iResult>=0) {
273           HLTDebug("iteration %d: inserting task %s (%p)", iterationLevel, pTask->GetName(), pTask);
274           iResult=InsertTask(pTask);
275         }
276       } else {
277         delete pTask;
278         pTask=NULL;
279       }
280     }
281   } else {
282     iResult=-EINVAL;
283   }
284   return iResult;
285 }
286
287 int AliHLTSystem::CleanTaskList()
288 {
289   // see header file for class documentation
290   int iResult=0;
291   fpHLTOUTTask=NULL;
292   fpControlTask=NULL;
293   TObjLink* lnk=NULL;
294   while ((lnk=fTaskList.LastLink())!=NULL) {
295     delete (lnk->GetObject());
296     fTaskList.Remove(lnk);
297   }
298
299   return iResult;
300 }
301
302 int AliHLTSystem::InsertTask(AliHLTTask* pTask)
303 {
304   // see header file for class documentation
305   int iResult=0;
306   if (fpControlTask==NULL) {
307     fpControlTask=new AliHLTControlTask;
308     if (!fpControlTask) return -ENOMEM;
309     fTaskList.AddFirst(fpControlTask);
310   }
311   TObjLink *controlLnk=NULL;
312   TObjLink *lnk = fTaskList.FirstLink();
313   assert(!lnk || lnk->GetObject()==fpControlTask || fpControlTask==NULL);
314   if (lnk && lnk->GetObject()==fpControlTask) {
315     if (pTask->GetConf() && pTask->GetConf()->GetFirstSource()==NULL) {
316       pTask->SetDependency(fpControlTask);
317       fpControlTask->SetTarget(pTask);
318     }
319     controlLnk=lnk;
320     lnk=lnk->Next();
321   }
322   if ((iResult=pTask->CheckDependencies())<=0)
323     lnk=NULL;
324   while (lnk && iResult>0) {
325     AliHLTTask* pCurr = (AliHLTTask*)lnk->GetObject();
326     //HLTDebug("checking  \"%s\"", pCurr->GetName());
327     iResult=pTask->Depends(pCurr);
328     if (iResult>0) {
329       iResult=pTask->SetDependency(pCurr);
330       pCurr->SetTarget(pTask);
331       HLTDebug("set dependency  \"%s\" for configuration \"%s\"", pCurr->GetName(), pTask->GetName());
332     }
333     if (pCurr->Depends(pTask)) {
334       // circular dependency
335       HLTError("circular dependency: can not resolve dependencies for configuration \"%s\"", pTask->GetName());
336       iResult=-ELOOP;
337     } else if ((iResult=pTask->CheckDependencies())>0) {
338       lnk = lnk->Next();
339     }
340   }
341   if (iResult==0) {
342       if (lnk) {
343         fTaskList.AddAfter(lnk, pTask);
344       } else if (controlLnk) {
345         fTaskList.AddAfter(controlLnk, pTask);
346       } else {
347         fTaskList.AddFirst(pTask);
348       }
349       HLTDebug("task \"%s\" (%p) inserted (size %d)", pTask->GetName(), pTask, sizeof(AliHLTTask));
350   } else if (iResult>0) {
351     HLTError("can not resolve dependencies for configuration \"%s\" (%d unresolved)", pTask->GetName(), iResult);
352     iResult=-ENOLINK;
353   }
354   return iResult;
355 }
356
357 AliHLTTask* AliHLTSystem::FindTask(const char* id)
358 {
359   // see header file for class documentation
360   AliHLTTask* pTask=NULL;
361   if (id) {
362     pTask=dynamic_cast<AliHLTTask*>(fTaskList.FindObject(id)); 
363   }
364   return pTask;
365 }
366
367 void AliHLTSystem::PrintTaskList()
368 {
369   // see header file for class documentation
370   HLTLogKeyword("task list");
371   TObjLink *lnk = NULL;
372   HLTMessage("Task List");
373   lnk=fTaskList.FirstLink();
374   while (lnk) {
375     TObject* obj=lnk->GetObject();
376     if (obj) {
377       HLTMessage("  %s - status:", obj->GetName());
378       AliHLTTask* pTask=(AliHLTTask*)obj;
379       pTask->PrintStatus();
380     } else {
381     }
382     lnk = lnk->Next();
383   }
384 }
385
386 int AliHLTSystem::Run(Int_t iNofEvents, int bStop, AliHLTUInt64_t trgMask)
387 {
388   // see header file for class documentation
389   int iResult=0;
390   int iCount=0;
391   SetStatusFlags(kRunning);
392   if (fEventCount>=0 || (iResult=InitTasks())>=0) {
393     if (fEventCount>=0 || (iResult=StartTasks())>=0) {
394       if (fEventCount==0) {
395         InitBenchmarking(fStopwatches);
396       } else {
397         // Matthias Oct 11 2008 this is a bug
398         // By resuming the stopwatches at this point, all continued counting, but the
399         // starting and stopping is controlled by the AliHLTStopwatchGuard
400         //ResumeBenchmarking(fStopwatches);    
401       }
402       for (int i=fEventCount; i<fEventCount+iNofEvents && iResult>=0; i++) {
403         if (fpHLTOUTTask) {
404           if (iNofEvents>1 && i==fEventCount) {
405             HLTWarning("can not add more than one event to the HLTOUT, skipping all but last block");
406           }
407           // reset and prepare for new data
408           fpHLTOUTTask->Reset();
409         }
410         if ((iResult=ProcessTasks(i, trgMask))>=0) {
411           fGoodEvents++;
412           iCount++;
413         } else {
414           // TODO: define different running modes to either ignore errors in
415           // event processing or not
416           // currently ignored 
417           iResult=0;
418         }
419         AliHLTDataBuffer::SetGlobalEventCount(iCount);
420       }
421       fEventCount+=iNofEvents;
422       if (bStop) StopTasks();
423       else PauseBenchmarking(fStopwatches);
424     }
425     if (bStop) DeinitTasks();
426   }
427   if (iResult>=0) {
428     iResult=iCount;
429   } else  if (iResult==-126 /*ENOKEY*/) {
430     iResult=0; // do not propagate the error
431   }
432   ClearStatusFlags(kRunning);
433   AliHLTDataBuffer::PrintStatistics();
434   return iResult;
435 }
436
437 int AliHLTSystem::InitTasks()
438 {
439   // see header file for class documentation
440   int iResult=0;
441   TObjLink *lnk=fTaskList.FirstLink();
442
443   if (lnk==NULL) {
444     HLTInfo("Task list is empty, skipping HLT");
445     return -126 /*ENOKEY*/;
446   }
447   while (lnk && iResult>=0) {
448     TObject* obj=lnk->GetObject();
449     if (obj) {
450       AliHLTTask* pTask=(AliHLTTask*)obj;
451       iResult=pTask->Init(NULL, fpComponentHandler);
452 //       ProcInfo_t ProcInfo;
453 //       gSystem->GetProcInfo(&ProcInfo);
454 //       HLTInfo("task %s initialized (%d), current memory usage %d %d", pTask->GetName(), iResult, ProcInfo.fMemResident, ProcInfo.fMemVirtual);
455     } else {
456     }
457     lnk = lnk->Next();
458   }
459   if (iResult<0) {
460     HLTError("can not initialize task list, error %d", iResult);
461   }
462
463   return iResult;
464 }
465
466 int AliHLTSystem::InitBenchmarking(TObjArray* pStopwatches)
467 {
468   // see header file for class documentation
469   int iResult=0;
470   if (pStopwatches==NULL) return 0;
471
472   for (int i=0; i<(int)AliHLTComponent::kSWTypeCount; i++) {
473     TStopwatch* pStopwatch= new TStopwatch;
474     if (pStopwatch) {
475       pStopwatch->Reset();
476       pStopwatches->AddAt(pStopwatch, i);
477     } else {
478       iResult=-ENOMEM;
479       break;
480     }
481   }
482
483   TObjLink *lnk=fTaskList.FirstLink();
484   while (lnk && iResult>=0) {
485     TObject* obj=lnk->GetObject();
486     if (obj) {
487       AliHLTTask* pTask=(AliHLTTask*)obj;
488       AliHLTComponent* pComp=NULL;
489       if (iResult>=0 && (pComp=pTask->GetComponent())!=NULL) {
490         switch (pComp->GetComponentType()) {
491         case AliHLTComponent::kProcessor:
492           pComp->SetStopwatches(pStopwatches);
493           break;
494         case AliHLTComponent::kSource:
495           {
496             // this switch determines whether the time consumption of the
497             // AliHLTComponent base methods should be counted to the input
498             // stopwatch or base stopwatch.
499             //int inputBase=(int)AliHLTComponent::kSWBase;
500             int inputBase=(int)AliHLTComponent::kSWInput;
501             pComp->SetStopwatch(pStopwatches->At(inputBase), AliHLTComponent::kSWBase);
502             pComp->SetStopwatch(pStopwatches->At((int)AliHLTComponent::kSWInput), AliHLTComponent::kSWDA);
503           }
504           break;
505         case AliHLTComponent::kSink:
506           {
507             // this switch determines whether the time consumption of the
508             // AliHLTComponent base methods should be counted to the output
509             // stopwatch or base stopwatch.
510             //int outputBase=(int)AliHLTComponent::kSWBase;
511             int outputBase=(int)AliHLTComponent::kSWOutput;
512             pComp->SetStopwatch(pStopwatches->At(outputBase), AliHLTComponent::kSWBase);
513             pComp->SetStopwatch(pStopwatches->At((int)AliHLTComponent::kSWOutput), AliHLTComponent::kSWDA);
514           }
515           break;
516         default:
517           HLTWarning("unknown component type %d", (int)pComp->GetComponentType());
518         }
519       }
520     } else {
521     }
522     lnk = lnk->Next();
523   }
524   return iResult;
525 }
526
527 int AliHLTSystem::PauseBenchmarking(TObjArray* pStopwatches) const
528 {
529   // see header file for class documentation
530   if (pStopwatches==NULL) return 0;
531
532   for (int i=0; i<(int)AliHLTComponent::kSWTypeCount; i++) {
533     if (!pStopwatches->At(i)) continue;
534     TStopwatch* pSw=dynamic_cast<TStopwatch*>(pStopwatches->At(i));
535     if (pSw) pSw->Stop();
536   }
537   return 0;
538 }
539
540 int AliHLTSystem::ResumeBenchmarking(TObjArray* pStopwatches) const
541 {
542   // see header file for class documentation
543   if (pStopwatches==NULL) return 0;
544
545   for (int i=0; i<(int)AliHLTComponent::kSWTypeCount; i++) {
546     if (!pStopwatches->At(i)) continue;
547     TStopwatch* pSw=dynamic_cast<TStopwatch*>(pStopwatches->At(i));
548     if (pSw) pSw->Continue();
549   }
550   return 0;
551 }
552
553 int AliHLTSystem::PrintBenchmarking(TObjArray* pStopwatches, int bClean) const
554 {
555   // see header file for class documentation
556   int iInitialized=1;
557   if (pStopwatches==NULL) return 0;
558
559   for (int i=0; i<(int)AliHLTComponent::kSWTypeCount; i++) {
560     if (!dynamic_cast<TStopwatch*>(pStopwatches->At(i))) {
561       iInitialized=0;
562       break;
563     }
564   }
565
566   if (iInitialized!=0) {
567     HLTImportant("HLT statistics:\n"
568             "    base:              R:%.3fs C:%.3fs\n"
569             "    input:             R:%.3fs C:%.3fs\n"
570             "    output:            R:%.3fs C:%.3fs\n"
571             "    event processing : R:%.3fs C:%.3fs"
572             , dynamic_cast<TStopwatch*>(pStopwatches->At(AliHLTComponent::kSWBase))->RealTime()
573             , dynamic_cast<TStopwatch*>(pStopwatches->At(AliHLTComponent::kSWBase))->CpuTime()
574             , dynamic_cast<TStopwatch*>(pStopwatches->At(AliHLTComponent::kSWInput))->RealTime()
575             , dynamic_cast<TStopwatch*>(pStopwatches->At(AliHLTComponent::kSWInput))->CpuTime()
576             , dynamic_cast<TStopwatch*>(pStopwatches->At(AliHLTComponent::kSWOutput))->RealTime()
577             , dynamic_cast<TStopwatch*>(pStopwatches->At(AliHLTComponent::kSWOutput))->CpuTime()
578             , dynamic_cast<TStopwatch*>(pStopwatches->At(AliHLTComponent::kSWDA))->RealTime()
579             , dynamic_cast<TStopwatch*>(pStopwatches->At(AliHLTComponent::kSWDA))->CpuTime()
580             );
581   }
582
583   if (bClean) {
584     for (int i=0; i<(int)AliHLTComponent::kSWTypeCount; i++) {
585       TObject* pObj=pStopwatches->RemoveAt(i);
586       if (pObj) delete pObj;
587     }
588   }
589   return 0;
590 }
591
592 int AliHLTSystem::StartTasks()
593 {
594   // see header file for class documentation
595   int iResult=0;
596   TObjLink *lnk=fTaskList.FirstLink();
597   while (lnk && iResult>=0) {
598     TObject* obj=lnk->GetObject();
599     if (obj) {
600       AliHLTTask* pTask=(AliHLTTask*)obj;
601       iResult=pTask->StartRun();
602 //       ProcInfo_t ProcInfo;
603 //       gSystem->GetProcInfo(&ProcInfo);
604 //       HLTInfo("task %s started (%d), current memory usage %d %d", pTask->GetName(), iResult, ProcInfo.fMemResident, ProcInfo.fMemVirtual);
605     } else {
606     }
607     lnk = lnk->Next();
608   }
609   if (iResult<0) {
610     HLTError("can not start task list, error %d", iResult);
611   } else {
612     SetStatusFlags(kStarted);
613     fEventCount=0;
614     fGoodEvents=0;
615     if ((iResult=SendControlEvent(kAliHLTDataTypeSOR))<0) {
616       HLTError("can not send SOR event: error %d", iResult);
617     }
618   }
619   return iResult;
620 }
621
622 int AliHLTSystem::ProcessTasks(Int_t eventNo, AliHLTUInt64_t trgMask)
623 {
624   // see header file for class documentation
625   int iResult=0;
626   HLTDebug("processing event no %d", eventNo);
627   TObjLink *lnk=fTaskList.FirstLink();
628   while (lnk && iResult>=0) {
629     TObject* obj=lnk->GetObject();
630     if (obj) {
631       AliHLTTask* pTask=(AliHLTTask*)obj;
632       iResult=pTask->ProcessTask(eventNo, gkAliEventTypeData, trgMask);
633 //       ProcInfo_t ProcInfo;
634 //       gSystem->GetProcInfo(&ProcInfo);
635 //       HLTInfo("task %s processed (%d), current memory usage %d %d", pTask->GetName(), iResult, ProcInfo.fMemResident, ProcInfo.fMemVirtual);
636     } else {
637     }
638     lnk = lnk->Next();
639   }
640
641   if (iResult>=0) {
642     HLTImportant("Event %d successfully finished (%d)", eventNo, iResult);
643     iResult=0;
644   } else {
645     HLTError("Processing of event %d failed (%d)", eventNo, iResult);
646   }
647
648   return iResult;
649 }
650
651 int AliHLTSystem::StopTasks()
652 {
653   // see header file for class documentation
654   int iResult=0;
655   if ((iResult=SendControlEvent(kAliHLTDataTypeEOR))<0) {
656     HLTError("can not send EOR event");
657   }
658
659   // cleanup blocks from the last event. This is a bit awkward. All output
660   // blocks from the chains need to be stored in the HLTOUT task. Though,
661   // we do not know, whether HLTOUT is going to be processed or not.
662   if (fpHLTOUTTask)
663     fpHLTOUTTask->Reset();
664
665   TObjLink *lnk=fTaskList.FirstLink();
666   while (lnk) {
667     TObject* obj=lnk->GetObject();
668     if (obj) {
669       AliHLTTask* pTask=(AliHLTTask*)obj;
670       int locResult=pTask->EndRun();
671       if (iResult>=0 && locResult<0) iResult=locResult;
672 //       ProcInfo_t ProcInfo;
673 //       gSystem->GetProcInfo(&ProcInfo);
674 //       HLTInfo("task %s stopped (%d), current memory usage %d %d", pTask->GetName(), iResult, ProcInfo.fMemResident, ProcInfo.fMemVirtual);
675     } else {
676     }
677     lnk = lnk->Next();
678   }
679   PrintBenchmarking(fStopwatches, 1 /*clean*/);
680   ClearStatusFlags(kStarted);
681   return iResult;
682 }
683
684 int AliHLTSystem::SendControlEvent(AliHLTComponentDataType dt)
685 {
686   // see header file for class documentation
687   int iResult=0;
688
689   AliHLTComponentBlockDataList controlBlocks;
690   AliHLTComponentBlockData bd;
691
692   // run decriptor block of type kAliHLTDataTypeSOR/kAliHLTDataTypeEOR 
693   AliHLTComponent::FillBlockData(bd);
694   AliHLTRunDesc runDesc;
695   memset(&runDesc, 0, sizeof(AliHLTRunDesc));
696   runDesc.fStructSize=sizeof(AliHLTRunDesc);
697   bd.fPtr=&runDesc;
698   bd.fSize=sizeof(AliHLTRunDesc);
699   bd.fDataType=dt;
700   bd.fSpecification=kAliHLTVoidDataSpec;
701   controlBlocks.push_back(bd);
702
703   // ECS parameter of type kAliHLTDataTypeECSParam
704   if (fECSParams.IsNull())
705     fECSParams="CTP_TRIGGER_CLASS=00:DUMMY-TRIGGER-ALL:00-01-02-03-04-05-06-07-08-09-10-11-12-13-14-15-16-17";
706   AliHLTComponent::FillBlockData(bd);
707   bd.fPtr=(void*)fECSParams.Data();
708   bd.fSize=fECSParams.Length()+1;
709   bd.fDataType=kAliHLTDataTypeECSParam;
710   bd.fSpecification=kAliHLTVoidDataSpec;
711   controlBlocks.push_back(bd);  
712
713   AliHLTControlTask::AliHLTControlEventGuard g(fpControlTask, controlBlocks);
714   HLTDebug("sending event %s, run descriptor %p", AliHLTComponent::DataType2Text(dt).c_str(), &runDesc);
715   TObjLink *lnk=fTaskList.FirstLink();
716   while (lnk && iResult>=0) {
717     TObject* obj=lnk->GetObject();
718     if (obj) {
719       AliHLTTask* pTask=(AliHLTTask*)obj;
720       AliHLTUInt32_t eventType=gkAliEventTypeUnknown;
721       if (dt==kAliHLTDataTypeSOR) eventType=gkAliEventTypeStartOfRun;
722       else if (dt==kAliHLTDataTypeEOR) eventType=gkAliEventTypeEndOfRun;
723       else HLTWarning("unknown control event %s", AliHLTComponent::DataType2Text(dt).c_str());
724       iResult=pTask->ProcessTask(-1, eventType);
725     } else {
726     }
727     lnk = lnk->Next();
728   }
729
730   // control events are not supposed to go into the HLTOUT
731   if (fpHLTOUTTask)
732     fpHLTOUTTask->Reset();
733
734   HLTDebug("event %s done (%d)", AliHLTComponent::DataType2Text(dt).c_str(), iResult);
735   return iResult;
736 }
737
738 int AliHLTSystem::DeinitTasks()
739 {
740   // see header file for class documentation
741   int iResult=0;
742   TObjLink *lnk=fTaskList.LastLink();
743   while (lnk) {
744     TObject* obj=lnk->GetObject();
745     if (obj) {
746       AliHLTTask* pTask=(AliHLTTask*)obj;
747       int localRes=pTask->Deinit();
748       if (iResult>=0) iResult=localRes;
749 //       ProcInfo_t ProcInfo;
750 //       gSystem->GetProcInfo(&ProcInfo);
751 //       HLTInfo("task %s cleaned (%d), current memory usage %d %d", pTask->GetName(), iResult, ProcInfo.fMemResident, ProcInfo.fMemVirtual);
752     } else {
753     }
754     lnk = lnk->Prev();
755   }
756   fEventCount=-1;
757   fGoodEvents=-1;
758
759   return iResult;
760 }
761
762 int AliHLTSystem::CleanHLTOUT()
763 {
764   // see header file for class documentation
765   if (fpChainHandlers) {
766     AliHLTOUT::AliHLTOUTHandlerListEntryVector* pHandlers=reinterpret_cast<AliHLTOUT::AliHLTOUTHandlerListEntryVector*>(fpChainHandlers);
767     fpChainHandlers=NULL;
768     if (pHandlers) {
769       AliHLTOUT::InvalidateBlocks(*pHandlers);
770       AliHLTOUT::RemoveEmptyDuplicateHandlers(*pHandlers);
771     }
772     assert(pHandlers->size()==0);
773     delete pHandlers;
774   }
775
776   if (fpEsdHandlers) {
777     AliHLTOUT::AliHLTOUTHandlerListEntryVector* pHandlers=reinterpret_cast<AliHLTOUT::AliHLTOUTHandlerListEntryVector*>(fpEsdHandlers);
778     fpEsdHandlers=NULL;
779     if (pHandlers) {
780       AliHLTOUT::InvalidateBlocks(*pHandlers);
781       AliHLTOUT::RemoveEmptyDuplicateHandlers(*pHandlers);
782     }
783     assert(pHandlers->size()==0);
784     delete pHandlers;
785   }
786
787   if (fpProprietaryHandlers) {
788     AliHLTOUT::AliHLTOUTHandlerListEntryVector* pHandlers=reinterpret_cast<AliHLTOUT::AliHLTOUTHandlerListEntryVector*>(fpProprietaryHandlers);
789     fpProprietaryHandlers=NULL;
790     if (pHandlers) {
791       AliHLTOUT::InvalidateBlocks(*pHandlers);
792       AliHLTOUT::RemoveEmptyDuplicateHandlers(*pHandlers);
793     }
794     assert(pHandlers->size()==0);
795     delete pHandlers;
796   }
797   return 0;
798 }
799
800 void* AliHLTSystem::AllocMemory( void* /*param*/, unsigned long size )
801 {
802   // see header file for class documentation
803   void* p=NULL;
804   try {
805     p=(void*)new char[size];
806   }
807   catch (...) {
808     AliHLTLogging log;
809     log.LoggingVarargs(kHLTLogError, "AliHLTSystem" , "AllocMemory" , __FILE__ , __LINE__ , "exeption during memory allocation" );
810   }
811   return p;
812 }
813
814 int AliHLTSystem::AllocEventDoneData( void* /*param*/, AliHLTEventID_t /*eventID*/, unsigned long size, AliHLTComponentEventDoneData** edd )
815 {
816   // see header file for class documentation
817   unsigned long blocksize=sizeof(AliHLTComponentEventDoneData)+size;
818   void* block=AllocMemory(NULL, blocksize);
819   if (!block) return -ENOMEM;
820   memset(block, 0, blocksize);
821   *edd=reinterpret_cast<AliHLTComponentEventDoneData*>(block);
822   (*edd)->fStructSize=sizeof(AliHLTComponentEventDoneData);
823   (*edd)->fDataSize=size;
824   (*edd)->fData=reinterpret_cast<AliHLTUInt8_t*>(block)+sizeof(AliHLTComponentEventDoneData);
825   
826   return 0;
827 }
828
829 int AliHLTSystem::Reconstruct(int nofEvents, AliRunLoader* runLoader, 
830                               AliRawReader* rawReader)
831 {
832   // see header file for class documentation
833   int iResult=0;
834   if (runLoader || rawReader || nofEvents==0) {
835     if (nofEvents>0) {HLTInfo("Run Loader %p, Raw Reader %p , %d event(s)", runLoader, rawReader, nofEvents);}
836     if (CheckStatus(kReady)) {
837       if (nofEvents==0) {
838         // special case to close the reconstruction
839         if (!CheckStatus(kError)) {
840         StopTasks();
841         DeinitTasks();
842         CleanHLTOUT();
843         }
844       } else {
845       if ((iResult=AliHLTOfflineInterface::SetParamsToComponents(runLoader, rawReader))>=0) {
846         AliHLTUInt64_t trgMask=0x1;
847         if (runLoader==NULL) {
848           // this is a quick workaround for the case of simulation
849           // the trigger framework is still under development, secondly, AliHLTSimulation
850           // does not yet add the emulated ECS parameters, so no CTP trigger is known in the HLT
851           // AliHLTTask will initialize one dummy CTP trigger class with bit 0, that's why the
852           // default trigger mask is 0x1
853           trgMask=AliHLTMisc::Instance().GetTriggerMask(rawReader);
854         }
855         // the system always remains started after event processing, a specific
856         // call with nofEvents==0 is needed to execute the stop sequence
857         if ((iResult=Run(nofEvents, 0, trgMask))<0) SetStatusFlags(kError);
858       }
859       }
860     } else {
861       HLTError("wrong state %#x, required flags %#x", GetStatusFlags(), kReady);
862     }
863   } else {
864     HLTError("missing RunLoader (%p)/RawReader (%p) instance", runLoader, rawReader);
865     iResult=-EINVAL;
866   }
867   return iResult;
868 }
869
870 int AliHLTSystem::FillESD(int eventNo, AliRunLoader* runLoader, AliESDEvent* esd)
871 {
872   // see header file for class documentation
873   int iResult=0;
874   if (runLoader || esd) {
875     HLTInfo("Event %d: Run Loader %p, ESD %p", eventNo, runLoader, esd);
876     iResult=AliHLTOfflineInterface::FillComponentESDs(eventNo, runLoader, esd);
877   } else {
878     HLTError("missing run loader/ESD instance(s)");
879     iResult=-EINVAL;
880   }
881   return iResult;
882 }
883
884 int AliHLTSystem::ProcessHLTOUT(AliHLTOUT* pHLTOUT, AliESDEvent* esd)
885 {
886   // see header file for class documentation
887   int iResult=0;
888   if (!pHLTOUT) return -EINVAL;
889   HLTDebug("processing %d HLT data blocks", pHLTOUT->GetNofDataBlocks());
890
891   // add the current HLTOUT task to the collection
892   if (fpHLTOUTTask) {
893     AliHLTOUT* pTask=dynamic_cast<AliHLTOUT*>(fpHLTOUTTask);
894     if (pTask && (iResult=pTask->Init())>=0) {
895       if (pTask->GetNofDataBlocks()>0) {
896         pHLTOUT->AddSubCollection(pTask);
897       }
898     } else {
899       HLTWarning("can not initialize HLTOUT sub collection %s for reconstruction chain (%d), data blocks are lost", pTask?fpHLTOUTTask->GetName():"nil", iResult);
900       iResult=0;
901     }
902   }
903
904   
905   //
906   // process all kChain handlers first
907   //
908   if ((iResult=ProcessHLTOUTkChain(pHLTOUT))<0) {
909     HLTWarning("Processing of kChain-type data blocks failed with error code %d", iResult);
910     iResult=0;
911   } 
912
913   if (!fpEsdHandlers)
914     fpEsdHandlers=new AliHLTOUT::AliHLTOUTHandlerListEntryVector;
915   if (!fpProprietaryHandlers)
916     fpProprietaryHandlers=new AliHLTOUT::AliHLTOUTHandlerListEntryVector;
917
918   AliHLTOUT::AliHLTOUTHandlerListEntryVector* pEsdHandlers=reinterpret_cast<AliHLTOUT::AliHLTOUTHandlerListEntryVector*>(fpEsdHandlers);
919   AliHLTOUT::AliHLTOUTHandlerListEntryVector* pProprietaryHandlers=reinterpret_cast<AliHLTOUT::AliHLTOUTHandlerListEntryVector*>(fpProprietaryHandlers);
920   if (!pEsdHandlers || !pProprietaryHandlers) return -ENOMEM;
921
922   // invalidate all blocks
923   AliHLTOUT::InvalidateBlocks(*pEsdHandlers);
924   AliHLTOUT::InvalidateBlocks(*pProprietaryHandlers);
925
926   AliHLTComponentDataTypeList esdBlocks;
927
928   for (iResult=pHLTOUT->SelectFirstDataBlock();
929        iResult>=0;
930        iResult=pHLTOUT->SelectNextDataBlock()) {
931     AliHLTComponentDataType dt=kAliHLTVoidDataType;
932     AliHLTUInt32_t spec=kAliHLTVoidDataSpec;
933     pHLTOUT->GetDataBlockDescription(dt, spec);
934     AliHLTOUTHandler* pHandler=pHLTOUT->GetHandler();
935     AliHLTModuleAgent::AliHLTOUTHandlerType handlerType=pHLTOUT->GetDataBlockHandlerType();
936
937     // default handling for ESD data blocks does not require an explicite handler
938     if (!pHandler && (dt==kAliHLTDataTypeESDObject || dt==kAliHLTDataTypeESDTree)) {
939       handlerType=AliHLTModuleAgent::kEsd;
940     }
941     const char* pMsg="invalid";
942     switch (handlerType) {
943     case AliHLTModuleAgent::kEsd:
944       {
945         if (pHandler) {
946           // schedule for later processing
947           pHLTOUT->InsertHandler(*pEsdHandlers, pHLTOUT->GetDataBlockHandlerDesc());
948         } else {
949           AliHLTComponentDataTypeList::iterator element=esdBlocks.begin();
950           for (; element!=esdBlocks.end(); element++) {
951             if (*element==dt) {
952               HLTWarning("multiple ESDs of identical data type %s, please add appropriate handler to merge ESDs", AliHLTComponent::DataType2Text(dt).c_str());
953               break;
954             }
955           }
956           if (element==esdBlocks.end()) esdBlocks.push_back(dt);
957
958           // write directly
959           const AliHLTUInt8_t* pBuffer=NULL;
960           AliHLTUInt32_t size=0;
961           if (pHLTOUT->GetDataBuffer(pBuffer, size)>=0) {
962             pHLTOUT->WriteESD(pBuffer, size, dt, esd);
963             pHLTOUT->ReleaseDataBuffer(pBuffer);
964           }
965           pHLTOUT->MarkDataBlockProcessed();
966         }
967       }
968       break;
969     case AliHLTModuleAgent::kRawReader:
970       // handled in the AliRawReaderHLT
971       break;
972     case AliHLTModuleAgent::kRawStream:
973       HLTWarning("HLTOUT handler type 'kRawStream' not yet implemented: agent %s, data type %s, specification %#x",
974                  pHLTOUT->GetAgent()?pHLTOUT->GetAgent()->GetModuleId():"<invalid>",
975                  AliHLTComponent::DataType2Text(dt).c_str(), spec);
976       break;
977     case AliHLTModuleAgent::kChain:
978       HLTWarning("HLTOUT handler type 'kChain' has already been processed: agent %s, data type %s, specification %#x\n"
979                  "New block of this type added by the chain? Skipping data block ...",
980                  pHLTOUT->GetAgent()?pHLTOUT->GetAgent()->GetModuleId():"<invalid>",
981                  AliHLTComponent::DataType2Text(dt).c_str(), spec);
982       break;
983     case AliHLTModuleAgent::kProprietary:
984       HLTDebug("processing proprietary data: agent %s, data type %s, specification %#x",
985                  pHLTOUT->GetAgent()?pHLTOUT->GetAgent()->GetModuleId():"<invalid>",
986                  AliHLTComponent::DataType2Text(dt).c_str(), spec);
987       if (pHandler) {
988         AliHLTOUT::AliHLTOUTLockGuard g(pHLTOUT);
989         int res=pHandler->ProcessData(pHLTOUT);
990         if (res<0) {
991           HLTWarning("processing proprietary data failed (%d): agent %s, data type %s, specification %#x",
992                      res, pHLTOUT->GetAgent()?pHLTOUT->GetAgent()->GetModuleId():"<invalid>",
993                      AliHLTComponent::DataType2Text(dt).c_str(), spec);
994         }
995       }
996       break;
997     case AliHLTModuleAgent::kUnknownOutput:
998       pMsg="unknown";
999       // fall trough intended
1000     default:
1001       HLTWarning("%s handler type: agent %s, data type %s, specification %#x, ... skipping data block",
1002                  pMsg, pHLTOUT->GetAgent()?pHLTOUT->GetAgent()->GetModuleId():"<invalid>",
1003                  AliHLTComponent::DataType2Text(dt).c_str(), spec);
1004     }
1005   }
1006   // TODO: the return value of SelectFirst/NextDataBlock must be
1007   // changed in order to avoid this check
1008   if (iResult==-ENOENT) iResult=0;
1009
1010   AliHLTOUT::AliHLTOUTHandlerListEntryVector::iterator handler;
1011
1012   // process and write all esd data blocks
1013   for (handler=pEsdHandlers->begin(); handler!=pEsdHandlers->end() && iResult>=0; handler++) {
1014     AliHLTOUT::AliHLTOUTSelectionGuard g(pHLTOUT, &(*handler));     
1015     AliHLTOUTHandler* pHandler=*handler;
1016     const AliHLTUInt8_t* pBuffer=NULL;
1017     AliHLTUInt32_t size=0;
1018     pHandler->ProcessData(pHLTOUT);
1019     if ((size=pHandler->GetProcessedData(pBuffer))>0) {
1020       AliHLTModuleAgent::AliHLTOUTHandlerDesc desc=*handler;
1021       AliHLTComponentDataType dt=desc;
1022       pHLTOUT->WriteESD(pBuffer, size, dt, esd);
1023       pHandler->ReleaseProcessedData(pBuffer, size);
1024     }
1025     pHLTOUT->MarkDataBlocksProcessed(&(*handler));
1026   }
1027
1028   // process all kProprietary data blocks
1029   for (handler=pProprietaryHandlers->begin(); handler!=pProprietaryHandlers->end() && iResult>=0; handler++) {
1030     AliHLTOUT::AliHLTOUTSelectionGuard g(pHLTOUT, &(*handler));     
1031     AliHLTOUTHandler* pHandler=*handler;
1032     const AliHLTUInt8_t* pBuffer=NULL;
1033     AliHLTUInt32_t size=0;
1034     pHandler->ProcessData(pHLTOUT);
1035     if ((size=pHandler->GetProcessedData(pBuffer))>0) {
1036       HLTWarning("data produced by kProprietary handler ignored");
1037       pHandler->ReleaseProcessedData(pBuffer, size);
1038     }
1039     pHLTOUT->MarkDataBlocksProcessed(&(*handler));
1040   }
1041
1042   // remove all empty handlers form the list (handlers which did not get a block this time)
1043   AliHLTOUT::RemoveEmptyDuplicateHandlers(*pEsdHandlers);
1044   AliHLTOUT::RemoveEmptyDuplicateHandlers(*pProprietaryHandlers);
1045
1046   return iResult;
1047 }
1048
1049 int AliHLTSystem::ProcessHLTOUTkChain(AliHLTOUT* pHLTOUT)
1050 {
1051   // see header file for class documentation
1052   int iResult=0;
1053   if (!pHLTOUT) return -EINVAL;
1054
1055   if (!fpChainHandlers)
1056     fpChainHandlers=new AliHLTOUT::AliHLTOUTHandlerListEntryVector;
1057
1058   AliHLTOUT::AliHLTOUTHandlerListEntryVector* pChainHandlers=reinterpret_cast<AliHLTOUT::AliHLTOUTHandlerListEntryVector*>(fpChainHandlers);
1059   if (!pChainHandlers) return -ENOMEM;
1060
1061   // invalidate all blocks
1062   AliHLTOUT::InvalidateBlocks(*pChainHandlers);
1063
1064   // fill the list
1065   pHLTOUT->FillHandlerList(*pChainHandlers, AliHLTModuleAgent::kChain);
1066
1067   // process all defined chain handlers
1068   AliHLTOUT::AliHLTOUTHandlerListEntryVector::iterator chainHandler;
1069   for (chainHandler=pChainHandlers->begin(); chainHandler!=pChainHandlers->end() && iResult>=0; chainHandler++) {
1070     if (chainHandler->IsEmpty()) continue;
1071     AliHLTOUT::AliHLTOUTSelectionGuard g(pHLTOUT, &(*chainHandler));        
1072     AliHLTOUTHandler* pHandler=*chainHandler;
1073     const AliHLTUInt8_t* pBuffer=NULL;
1074     AliHLTUInt32_t size=0;
1075     pHandler->ProcessData(pHLTOUT);
1076     if ((size=pHandler->GetProcessedData(pBuffer))>0) {
1077       AliHLTModuleAgent::AliHLTOUTHandlerDesc desc=*chainHandler;
1078       AliHLTComponentDataType dt=desc;
1079
1080       pHandler->ReleaseProcessedData(pBuffer, size);
1081     }
1082     pHLTOUT->MarkDataBlocksProcessed(&(*chainHandler));
1083   }
1084
1085   // remove all empty handlers form the list (handlers which did not get a block this time)
1086   AliHLTOUT::RemoveEmptyDuplicateHandlers(*pChainHandlers);
1087
1088   return iResult;
1089 }
1090
1091 int AliHLTSystem::LoadComponentLibraries(const char* libraries)
1092 {
1093   // see header file for class documentation
1094   int iResult=0;
1095   if (libraries) {
1096     if (fpComponentHandler) {
1097       TString libs(libraries);
1098       TObjArray* pTokens=libs.Tokenize(" ");
1099       if (pTokens) {
1100         int iEntries=pTokens->GetEntriesFast();
1101         for (int i=0; i<iEntries && iResult>=0; i++) {
1102           iResult=fpComponentHandler->LoadLibrary((((TObjString*)pTokens->At(i))->GetString()).Data());
1103         }
1104         delete pTokens;
1105       }
1106       if (iResult>=0) {
1107         SetStatusFlags(kLibrariesLoaded);
1108       } else {
1109         // lets see if we need this, probably not
1110         //fpComponentHandler->UnloadLibraries();
1111         ClearStatusFlags(kLibrariesLoaded);
1112       }
1113     } else {
1114       iResult=-EFAULT;
1115       HLTFatal("no component handler available");
1116     }
1117   } else {
1118     iResult=-EINVAL;
1119   }
1120   return iResult;
1121 }
1122
1123 int AliHLTSystem::Configure(AliRunLoader* runloader)
1124 {
1125   // see header file for class documentation
1126   return Configure(NULL, runloader);
1127 }
1128
1129 int AliHLTSystem::Configure(AliRawReader* rawReader, AliRunLoader* runloader)
1130 {
1131   // see header file for class documentation
1132   int iResult=0;
1133   if (CheckStatus(kRunning)) {
1134     HLTError("HLT system in running state, can not configure");
1135     return -EBUSY;
1136   }
1137   ClearStatusFlags(kTaskListCreated);
1138   if (CheckFilter(kHLTLogDebug))
1139     AliHLTModuleAgent::PrintStatus();
1140   if (CheckStatus(kConfigurationLoaded)==0) {
1141     iResult=LoadConfigurations(rawReader, runloader);
1142   } else {
1143     if (fChains.Length()==0) {
1144       HLTError("custom configuration(s) specified, but no configuration to run in local reconstruction, use \'chains=<chain,...>\' option");
1145       iResult=-ENOENT;
1146     }
1147   }
1148   if (iResult>=0) {
1149     SetStatusFlags(kConfigurationLoaded);
1150     if (CheckFilter(kHLTLogDebug))
1151       fpConfigurationHandler->PrintConfigurations();
1152     iResult=BuildTaskListsFromReconstructionChains(rawReader, runloader);
1153     if (iResult>=0) {
1154       SetStatusFlags(kTaskListCreated);
1155     }
1156   }
1157   if (iResult<0) SetStatusFlags(kError);
1158   
1159   return iResult;
1160 }
1161
1162 int AliHLTSystem::ScanOptions(const char* options)
1163 {
1164   // see header file for class documentation
1165   int iResult=0;
1166   if (options) {
1167     //AliHLTComponentHandler::TLibraryMode libMode=AliHLTComponentHandler::kDynamic;
1168     TString libs("");
1169     TString alloptions(options);
1170     TObjArray* pTokens=alloptions.Tokenize(" ");
1171     if (pTokens) {
1172       int iEntries=pTokens->GetEntriesFast();
1173       for (int i=0; i<iEntries; i++) {
1174         TString token=(((TObjString*)pTokens->At(i))->GetString());
1175         if (token.Contains("loglevel=")) {
1176           TString param=token.ReplaceAll("loglevel=", "");
1177           if (param.IsDigit()) {
1178             SetGlobalLoggingLevel((AliHLTComponentLogSeverity)param.Atoi());
1179           } else if (param.BeginsWith("0x") &&
1180                      param.Replace(0,2,"",0).IsHex()) {
1181             int severity=0;
1182             sscanf(param.Data(),"%x", &severity);
1183             SetGlobalLoggingLevel((AliHLTComponentLogSeverity)severity);
1184           } else {
1185             HLTWarning("wrong parameter for option \'loglevel=\', (hex) number expected");
1186           }
1187         } else if (token.Contains("frameworklog=")) {
1188           TString param=token.ReplaceAll("frameworklog=", "");
1189           if (param.IsDigit()) {
1190             SetFrameworkLog((AliHLTComponentLogSeverity)param.Atoi());
1191           } else if (param.BeginsWith("0x") &&
1192                      param.Replace(0,2,"",0).IsHex()) {
1193             int severity=0;
1194             sscanf(param.Data(),"%x", &severity);
1195             SetFrameworkLog((AliHLTComponentLogSeverity)severity);
1196           } else {
1197             HLTWarning("wrong parameter for option \'loglevel=\', (hex) number expected");
1198           }
1199         } else if (token.Contains("alilog=off")) {
1200           SwitchAliLog(0);
1201         } else if (token.Contains("config=")) {
1202           TString param=token.ReplaceAll("config=", "");
1203           Int_t error=0;
1204           gROOT->Macro(param.Data(), &error);
1205           if (error==0) {
1206             SetStatusFlags(kConfigurationLoaded);
1207           } else {
1208             HLTError("can not execute macro \'%s\'", param.Data());
1209             iResult=-EBADF;
1210           }
1211         } else if (token.Contains("chains=")) {
1212           TString param=token.ReplaceAll("chains=", "");
1213           fChains=param.ReplaceAll(",", " ");
1214           if (fChains.IsNull()) fChains=" "; // disable all chains
1215         } else if (token.Contains("libmode=")) {
1216           TString param=token.ReplaceAll("libmode=", "");
1217           param.ReplaceAll(",", " ");
1218           if (fpComponentHandler) {
1219             if (param.CompareTo("static")==0) {
1220               fpComponentHandler->SetLibraryMode(AliHLTComponentHandler::kStatic);
1221             } else if (param.CompareTo("dynamic")==0) {
1222               fpComponentHandler->SetLibraryMode(AliHLTComponentHandler::kDynamic);
1223             } else {
1224               HLTWarning("wrong argument for option \'libmode=\', use \'static\' or \'dynamic\'");
1225             }
1226           }
1227         } else if (token.BeginsWith("ECS=")) {
1228           fECSParams=token.ReplaceAll("ECS=", "");
1229         } else if (token.BeginsWith("lib") && token.EndsWith(".so")) {
1230           libs+=token;
1231           libs+=" ";
1232         } else {
1233           HLTWarning("unknown option \'%s\'", token.Data());
1234         }
1235       }
1236       delete pTokens;
1237     }
1238
1239     if (iResult>=0) {
1240       if (libs.IsNull()) {
1241         const char** deflib=fgkHLTDefaultLibs;
1242         while (*deflib) {
1243           libs+=*deflib++;
1244           libs+=" ";
1245         }
1246       }
1247       if ((!CheckStatus(AliHLTSystem::kLibrariesLoaded)) &&
1248           (LoadComponentLibraries(libs.Data())<0)) {
1249         HLTError("error while loading HLT libraries");
1250         iResult=-EFAULT;
1251       }
1252     }
1253   }
1254   return iResult;
1255 }
1256
1257 int AliHLTSystem::Reset(int bForce)
1258 {
1259   // see header file for class documentation
1260   int iResult=0;
1261   if (!bForce && CheckStatus(kRunning)) {
1262     HLTError("HLT system in running state, can not configure");
1263     return -EBUSY;
1264   }
1265   CleanTaskList();
1266   ClearStatusFlags(~kUninitialized);
1267   return iResult;
1268 }
1269
1270 int AliHLTSystem::LoadConfigurations(AliRawReader* rawReader, AliRunLoader* runloader)
1271 {
1272   // see header file for class documentation
1273   if (CheckStatus(kRunning)) {
1274     HLTError("HLT system in running state, can not configure");
1275     return -EBUSY;
1276   }
1277   int iResult=0;
1278   AliHLTModuleAgent* pAgent=NULL;
1279
1280   // first check for the required libraries and load those
1281   TString extralibs;
1282   for (pAgent=AliHLTModuleAgent::GetFirstAgent(); 
1283        pAgent && iResult>=0;
1284        pAgent=AliHLTModuleAgent::GetNextAgent()) {
1285     const char* deplibs=pAgent->GetRequiredComponentLibraries();
1286     if (deplibs) {
1287       HLTDebug("required libraries \'%s\' for agent %s (%p)", deplibs, pAgent->GetName(), pAgent);
1288       extralibs+=" ";
1289       extralibs+=deplibs;
1290     }
1291   }
1292   if (iResult>=0) {
1293     iResult=LoadComponentLibraries(extralibs.Data());
1294   }
1295
1296   // in order to register the configurations in the correct sequence
1297   // all agents need to be ordered with respect to the required
1298   // libraries. Ordering relies on the naming convention
1299   // libAliHLT<Module>.so
1300   TList agents;
1301   for (pAgent=AliHLTModuleAgent::GetFirstAgent(); 
1302        pAgent && iResult>=0;
1303        pAgent=AliHLTModuleAgent::GetNextAgent()) {
1304     AliHLTModuleAgent* pPrevDep=NULL;
1305     TString dependencies=pAgent->GetRequiredComponentLibraries();
1306     TObjArray* pTokens=dependencies.Tokenize(" ");
1307     if (pTokens) {
1308       for (int n=0; n<pTokens->GetEntriesFast(); n++) {
1309         TString module=((TObjString*)pTokens->At(n))->GetString();
1310         HLTDebug("  checking %s", module.Data());
1311         module.ReplaceAll("libAliHLT", "");
1312         module.ReplaceAll(".so", "");
1313         
1314         for (AliHLTModuleAgent* pCurrent=dynamic_cast<AliHLTModuleAgent*>(pPrevDep==NULL?agents.First():agents.After(pPrevDep));
1315              pCurrent!=NULL; pCurrent=dynamic_cast<AliHLTModuleAgent*>(agents.After(pCurrent))) {
1316           HLTDebug("    checking %s == %s", module.Data(), pCurrent->GetModuleId());
1317
1318           if (module.CompareTo(pCurrent->GetModuleId())==0) {
1319             pPrevDep=pCurrent;
1320             break;
1321           }
1322         }
1323       }
1324       delete pTokens;
1325     }
1326
1327     if (pPrevDep) {
1328       // insert right after the last dependency
1329       agents.AddAfter(pPrevDep, pAgent);
1330       HLTDebug("insert %s after %s", pAgent->GetModuleId(), pPrevDep->GetModuleId());
1331     } else {
1332       // insert at the beginning
1333       agents.AddFirst(pAgent);
1334       HLTDebug("insert %s at beginning", pAgent->GetModuleId());
1335     }
1336   }
1337
1338   // now we load the configurations
1339   if (agents.GetEntries()) {
1340     TIter next(&agents);
1341     while ((pAgent = dynamic_cast<AliHLTModuleAgent*>(next()))) {
1342       HLTDebug("load configurations for agent %s (%p)", pAgent->GetName(), pAgent);
1343       pAgent->CreateConfigurations(fpConfigurationHandler, rawReader, runloader);
1344     }
1345   }
1346
1347   return iResult;
1348 }
1349
1350 int AliHLTSystem::BuildTaskListsFromReconstructionChains(AliRawReader* rawReader, AliRunLoader* runloader)
1351 {
1352   // see header file for class documentation
1353   if (CheckStatus(kRunning)) {
1354     HLTError("HLT system in running state, can not configure");
1355     return -EBUSY;
1356   }
1357   if (!CheckStatus(kConfigurationLoaded)) {
1358     HLTWarning("configurations not yet loaded");
1359     return 0;
1360   }
1361
1362   int iResult=0;
1363   int bHaveOutput=0;
1364
1365   // query chains
1366   TString chains;
1367   if (fChains.Length()>0) {
1368     chains=fChains;
1369     HLTImportant("custom reconstruction chain: %s", chains.Data());
1370   } else {
1371     AliHLTModuleAgent* pAgent=AliHLTModuleAgent::GetFirstAgent();
1372     while ((pAgent || fChains.Length()>0) && iResult>=0) {
1373       const char* agentchains=pAgent->GetReconstructionChains(rawReader, runloader);
1374       if (agentchains) {
1375         if (!chains.IsNull()) chains+=" ";
1376         chains+=agentchains;
1377         HLTInfo("reconstruction chains for agent %s (%p): %s", pAgent->GetName(), pAgent, agentchains);
1378       }
1379       pAgent=AliHLTModuleAgent::GetNextAgent();
1380     }
1381   }
1382
1383   // build task list for chains
1384   TObjArray* pTokens=chains.Tokenize(" ");
1385   if (pTokens) {
1386     int iEntries=pTokens->GetEntriesFast();
1387     for (int i=0; i<iEntries && iResult>=0; i++) {
1388       const char* pCID=((TObjString*)pTokens->At(i))->GetString().Data();
1389       AliHLTConfiguration* pConf=fpConfigurationHandler->FindConfiguration(pCID);
1390       if (pConf) {
1391         iResult=BuildTaskList(pConf);
1392         if (true) { // condition was deprecated but kept for sake of svn diff
1393           // bHaveOutput variable has to be set for both running modes
1394           // AliHLTSimulation and AliHLTReconstruction
1395           assert(fpComponentHandler!=NULL);
1396           TString cid=pConf->GetComponentID();
1397           if (runloader!=NULL && cid.CompareTo("HLTOUT")==0) {
1398             // remove from the input of a global HLTOUT configuration
1399             chains.ReplaceAll(pCID, "");
1400           } else if (bHaveOutput==0) {
1401             // check whether this configuration produces data output
1402             if ((bHaveOutput=fpComponentHandler->HasOutputData(cid.Data()))<0) {
1403               bHaveOutput=0;
1404               chains.ReplaceAll(pCID, "");
1405             }
1406           }
1407         }
1408       } else {
1409         HLTWarning("can not find configuration %s", pCID);
1410       }
1411     }
1412     delete pTokens;
1413   }
1414
1415   // build HLTOUT for simulation
1416   if (iResult>=0 && runloader) {
1417     if (bHaveOutput) {
1418       // there are components in the chain which produce data which need to be
1419       // piped to an HLTOUT
1420       if (fpComponentHandler->FindComponentIndex("HLTOUT")>=0 ||
1421           fpComponentHandler->LoadLibrary("libHLTsim.so")>=0) {
1422         AliHLTConfiguration globalout("_globalout_", "HLTOUT", chains.Data(), NULL);
1423         iResult=BuildTaskList("_globalout_");
1424       } else {
1425         HLTError("can not load libHLTsim.so and HLTOUT component");
1426         iResult=-EFAULT;
1427       }
1428     }
1429   }
1430
1431   // build HLTOUT task for reconstruction
1432   // Matthias 08.07.2008 the rawReader is never set when running embedded into
1433   // AliReconstruction. The system is configured during AliHLTReconstructor::Init
1434   // where the RawReader is not available. It is available in the first invocation
1435   // of Reconstruct.
1436   // 
1437   // That means that policy is slightly changed:
1438   // - if the run loader is available -> AliSimulation
1439   // - no run loader available -> AliReconstruction
1440   if (iResult>=0 && !runloader) {
1441     if (bHaveOutput) {
1442       // there are components in the chain which produce data which need to be
1443       // piped to an HLTOUT sub-collection
1444       if (!fpHLTOUTTask) {
1445         iResult=AddHLTOUTTask(chains.Data());
1446       }
1447     }
1448   }
1449
1450   if (iResult>=0) SetStatusFlags(kTaskListCreated);
1451
1452   return iResult;
1453 }
1454
1455 int AliHLTSystem::AddHLTOUTTask(const char* hltoutchains)
1456 {
1457   // see header file for class documentation
1458   int iResult=0;
1459   if (!hltoutchains || hltoutchains[0]==0) return 0;
1460
1461   // check chains for output
1462   TString chains=hltoutchains;
1463   TObjArray* pTokens=chains.Tokenize(" ");
1464   if (pTokens) {
1465     int iEntries=pTokens->GetEntriesFast();
1466     for (int i=0; i<iEntries && iResult>=0; i++) {
1467       const char* token=((TObjString*)pTokens->At(i))->GetString().Data();
1468       AliHLTConfiguration* pConf=fpConfigurationHandler->FindConfiguration(token);
1469       if (pConf) {
1470         TString cid=pConf->GetComponentID();
1471         if (fpComponentHandler->HasOutputData(cid.Data())) {
1472           continue;
1473         }
1474       } else {
1475         HLTWarning("can not find configuration %s", token);
1476       }
1477       // remove from the list of hltout chains
1478       chains.ReplaceAll(token, "");
1479     }
1480     delete pTokens;
1481   }
1482
1483   // do not create the HLTOUT task if none of the chains have output
1484   if (chains.IsNull()) return 0;
1485
1486   // indicate the task to be available
1487   iResult=1;
1488
1489   if (fpHLTOUTTask) {
1490     if (strcmp(chains.Data(), fpHLTOUTTask->GetSourceChains())==0) {
1491       HLTWarning("HLTOUT task already added for chains \"%s\" %p", chains.Data(), fpHLTOUTTask);
1492     } else {
1493       HLTError("HLTOUT task already added for chains \"%s\" %p, ignoring new chains  \"%s\"",
1494                fpHLTOUTTask->GetSourceChains(), fpHLTOUTTask, chains.Data());
1495     }
1496     return iResult;
1497   }
1498
1499   fpHLTOUTTask=new AliHLTOUTTask(chains);
1500   if (fpHLTOUTTask) {
1501     if (fpHLTOUTTask->GetConf() && fpHLTOUTTask->GetConf()->SourcesResolved()>=0) {
1502       iResult=InsertTask(fpHLTOUTTask);
1503     } else {
1504       HLTError("HLTOUT task (%s) sources not resolved", fpHLTOUTTask->GetName());
1505       iResult=-ENOENT;
1506     }
1507
1508     if (iResult<0) {
1509       delete fpHLTOUTTask;
1510     }
1511
1512   } else {
1513     iResult=-ENOMEM;
1514   }
1515   return iResult;
1516 }
1517
1518 int AliHLTSystem::CheckStatus(int flag)
1519 {
1520   // see header file for class documentation
1521   if (flag==kUninitialized && flag==fState) return 1;
1522   if ((fState&flag)==flag) return 1;
1523   return 0;
1524 }
1525
1526 int AliHLTSystem::GetStatusFlags()
1527 {
1528   // see header file for class documentation
1529   return fState;
1530 }
1531
1532 int AliHLTSystem::SetStatusFlags(int flags)
1533 {
1534   // see header file for class documentation
1535   fState|=flags;
1536   return fState;
1537 }
1538
1539 int AliHLTSystem::ClearStatusFlags(int flags)
1540 {
1541   // see header file for class documentation
1542   fState&=~flags;
1543   return fState;
1544 }
1545
1546 void (*AliHLTSystem::FindDynamicSymbol(const char* library, const char* symbol))()
1547 {
1548   // see header file for class documentation
1549   if (fpComponentHandler==NULL) return NULL;
1550   return fpComponentHandler->FindSymbol(library, symbol);
1551 }
1552
1553 void AliHLTSystem::SetFrameworkLog(AliHLTComponentLogSeverity level) 
1554 {
1555   // see header file for class documentation
1556   SetLocalLoggingLevel(level);
1557   if (fpComponentHandler) fpComponentHandler->SetLocalLoggingLevel(level);
1558   if (fpConfigurationHandler) fpConfigurationHandler->SetLocalLoggingLevel(level);
1559 }
1560
1561 int AliHLTSystem::LoggingVarargs(AliHLTComponentLogSeverity severity, 
1562                                  const char* originClass, const char* originFunc,
1563                                  const char* file, int line, ... ) const
1564 {
1565   // see header file for function documentation
1566   int iResult=0;
1567
1568   va_list args;
1569   va_start(args, line);
1570
1571   if (!fName.IsNull())
1572     AliHLTLogging::SetLogString(this, " (%p)", "%s_pfmt_: ", fName.Data());
1573   iResult=SendMessage(severity, originClass, originFunc, file, line, AliHLTLogging::BuildLogString(NULL, args, !fName.IsNull() /*append if non empty*/));
1574   va_end(args);
1575
1576   return iResult;
1577 }