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