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