]> git.uio.no Git - u/mrichter/AliRoot.git/blob - HLT/BASE/AliHLTSystem.cxx
first implementation of ESD merging (not matching!) on the level of TClonesArrays...
[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   AliHLTComponentDataTypeList esdBlocks;
874
875   for (iResult=pHLTOUT->SelectFirstDataBlock();
876        iResult>=0;
877        iResult=pHLTOUT->SelectNextDataBlock()) {
878     AliHLTComponentDataType dt=kAliHLTVoidDataType;
879     AliHLTUInt32_t spec=kAliHLTVoidDataSpec;
880     pHLTOUT->GetDataBlockDescription(dt, spec);
881     AliHLTOUTHandler* pHandler=pHLTOUT->GetHandler();
882     AliHLTModuleAgent::AliHLTOUTHandlerType handlerType=pHLTOUT->GetDataBlockHandlerType();
883
884     // default handling for ESD data blocks does not require an explicite handler
885     if (!pHandler && (dt==kAliHLTDataTypeESDObject || dt==kAliHLTDataTypeESDTree)) {
886       handlerType=AliHLTModuleAgent::kEsd;
887     }
888     const char* pMsg="invalid";
889     switch (handlerType) {
890     case AliHLTModuleAgent::kEsd:
891       {
892         if (pHandler) {
893           // schedule for later processing
894           pHLTOUT->InsertHandler(*pEsdHandlers, pHLTOUT->GetDataBlockHandlerDesc());
895         } else {
896           AliHLTComponentDataTypeList::iterator element=esdBlocks.begin();
897           for (; element!=esdBlocks.end(); element++) {
898             if (*element==dt) {
899               HLTWarning("multiple ESDs of identical data type %s, please add appropriate handler to merge ESDs", AliHLTComponent::DataType2Text(dt).c_str());
900               break;
901             }
902           }
903           if (element==esdBlocks.end()) esdBlocks.push_back(dt);
904
905           // write directly
906           const AliHLTUInt8_t* pBuffer=NULL;
907           AliHLTUInt32_t size=0;
908           if (pHLTOUT->GetDataBuffer(pBuffer, size)>=0) {
909             pHLTOUT->WriteESD(pBuffer, size, dt, esd);
910             pHLTOUT->ReleaseDataBuffer(pBuffer);
911           }
912           pHLTOUT->MarkDataBlockProcessed();
913         }
914       }
915       break;
916     case AliHLTModuleAgent::kRawReader:
917       // handled in the AliRawReaderHLT
918       break;
919     case AliHLTModuleAgent::kRawStream:
920       HLTWarning("HLTOUT handler type 'kRawStream' not yet implemented: agent %s, data type %s, specification %#x",
921                  pHLTOUT->GetAgent()?pHLTOUT->GetAgent()->GetModuleId():"<invalid>",
922                  AliHLTComponent::DataType2Text(dt).c_str(), spec);
923       break;
924     case AliHLTModuleAgent::kChain:
925       HLTWarning("HLTOUT handler type 'kChain' has already been processed: agent %s, data type %s, specification %#x\n"
926                  "New block of this type added by the chain? Skipping data block ...",
927                  pHLTOUT->GetAgent()?pHLTOUT->GetAgent()->GetModuleId():"<invalid>",
928                  AliHLTComponent::DataType2Text(dt).c_str(), spec);
929       break;
930     case AliHLTModuleAgent::kProprietary:
931       HLTDebug("processing proprietary data: agent %s, data type %s, specification %#x",
932                  pHLTOUT->GetAgent()?pHLTOUT->GetAgent()->GetModuleId():"<invalid>",
933                  AliHLTComponent::DataType2Text(dt).c_str(), spec);
934       if (pHandler) {
935         AliHLTOUT::AliHLTOUTLockGuard g(pHLTOUT);
936         int res=pHandler->ProcessData(pHLTOUT);
937         if (res<0) {
938           HLTWarning("processing proprietary data failed (%d): agent %s, data type %s, specification %#x",
939                      res, pHLTOUT->GetAgent()?pHLTOUT->GetAgent()->GetModuleId():"<invalid>",
940                      AliHLTComponent::DataType2Text(dt).c_str(), spec);
941         }
942       }
943       break;
944     case AliHLTModuleAgent::kUnknownOutput:
945       pMsg="unknown";
946       // fall trough intended
947     default:
948       HLTWarning("%s handler type: agent %s, data type %s, specification %#x, ... skipping data block",
949                  pMsg, pHLTOUT->GetAgent()?pHLTOUT->GetAgent()->GetModuleId():"<invalid>",
950                  AliHLTComponent::DataType2Text(dt).c_str(), spec);
951     }
952   }
953   // TODO: the return value of SelectFirst/NextDataBlock must be
954   // changed in order to avoid this check
955   if (iResult==-ENOENT) iResult=0;
956
957   AliHLTOUT::AliHLTOUTHandlerListEntryVector::iterator handler;
958
959   // process and write all esd data blocks
960   for (handler=pEsdHandlers->begin(); handler!=pEsdHandlers->end() && iResult>=0; handler++) {
961     AliHLTOUT::AliHLTOUTSelectionGuard g(pHLTOUT, &(*handler));     
962     AliHLTOUTHandler* pHandler=*handler;
963     const AliHLTUInt8_t* pBuffer=NULL;
964     AliHLTUInt32_t size=0;
965     pHandler->ProcessData(pHLTOUT);
966     if ((size=pHandler->GetProcessedData(pBuffer))>0) {
967       AliHLTModuleAgent::AliHLTOUTHandlerDesc desc=*handler;
968       AliHLTComponentDataType dt=desc;
969       pHLTOUT->WriteESD(pBuffer, size, dt, esd);
970       pHandler->ReleaseProcessedData(pBuffer, size);
971     }
972     pHLTOUT->MarkDataBlocksProcessed(&(*handler));
973   }
974
975   // process all kProprietary data blocks
976   for (handler=pProprietaryHandlers->begin(); handler!=pProprietaryHandlers->end() && iResult>=0; handler++) {
977     AliHLTOUT::AliHLTOUTSelectionGuard g(pHLTOUT, &(*handler));     
978     AliHLTOUTHandler* pHandler=*handler;
979     const AliHLTUInt8_t* pBuffer=NULL;
980     AliHLTUInt32_t size=0;
981     pHandler->ProcessData(pHLTOUT);
982     if ((size=pHandler->GetProcessedData(pBuffer))>0) {
983       HLTWarning("data produced by kProprietary handler ignored");
984       pHandler->ReleaseProcessedData(pBuffer, size);
985     }
986     pHLTOUT->MarkDataBlocksProcessed(&(*handler));
987   }
988
989   // remove all empty handlers form the list (handlers which did not get a block this time)
990   AliHLTOUT::RemoveEmptyDuplicateHandlers(*pEsdHandlers);
991   AliHLTOUT::RemoveEmptyDuplicateHandlers(*pProprietaryHandlers);
992
993   return iResult;
994 }
995
996 int AliHLTSystem::ProcessHLTOUTkChain(AliHLTOUT* pHLTOUT)
997 {
998   // see header file for class documentation
999   int iResult=0;
1000   if (!pHLTOUT) return -EINVAL;
1001
1002   if (!fpChainHandlers)
1003     fpChainHandlers=new AliHLTOUT::AliHLTOUTHandlerListEntryVector;
1004
1005   AliHLTOUT::AliHLTOUTHandlerListEntryVector* pChainHandlers=reinterpret_cast<AliHLTOUT::AliHLTOUTHandlerListEntryVector*>(fpChainHandlers);
1006   if (!pChainHandlers) return -ENOMEM;
1007
1008   // invalidate all blocks
1009   AliHLTOUT::InvalidateBlocks(*pChainHandlers);
1010
1011   // fill the list
1012   pHLTOUT->FillHandlerList(*pChainHandlers, AliHLTModuleAgent::kChain);
1013
1014   // process all defined chain handlers
1015   AliHLTOUT::AliHLTOUTHandlerListEntryVector::iterator chainHandler;
1016   for (chainHandler=pChainHandlers->begin(); chainHandler!=pChainHandlers->end() && iResult>=0; chainHandler++) {
1017     if (chainHandler->IsEmpty()) continue;
1018     AliHLTOUT::AliHLTOUTSelectionGuard g(pHLTOUT, &(*chainHandler));        
1019     AliHLTOUTHandler* pHandler=*chainHandler;
1020     const AliHLTUInt8_t* pBuffer=NULL;
1021     AliHLTUInt32_t size=0;
1022     pHandler->ProcessData(pHLTOUT);
1023     if ((size=pHandler->GetProcessedData(pBuffer))>0) {
1024       AliHLTModuleAgent::AliHLTOUTHandlerDesc desc=*chainHandler;
1025       AliHLTComponentDataType dt=desc;
1026
1027       pHandler->ReleaseProcessedData(pBuffer, size);
1028     }
1029     pHLTOUT->MarkDataBlocksProcessed(&(*chainHandler));
1030   }
1031
1032   // remove all empty handlers form the list (handlers which did not get a block this time)
1033   AliHLTOUT::RemoveEmptyDuplicateHandlers(*pChainHandlers);
1034
1035   return iResult;
1036 }
1037
1038 int AliHLTSystem::LoadComponentLibraries(const char* libraries)
1039 {
1040   // see header file for class documentation
1041   int iResult=0;
1042   if (libraries) {
1043     if (fpComponentHandler) {
1044       TString libs(libraries);
1045       TObjArray* pTokens=libs.Tokenize(" ");
1046       if (pTokens) {
1047         int iEntries=pTokens->GetEntries();
1048         for (int i=0; i<iEntries && iResult>=0; i++) {
1049           iResult=fpComponentHandler->LoadLibrary((((TObjString*)pTokens->At(i))->GetString()).Data());
1050         }
1051         delete pTokens;
1052       }
1053       if (iResult>=0) {
1054         SetStatusFlags(kLibrariesLoaded);
1055       } else {
1056         // lets see if we need this, probably not
1057         //fpComponentHandler->UnloadLibraries();
1058         ClearStatusFlags(kLibrariesLoaded);
1059       }
1060     } else {
1061       iResult=-EFAULT;
1062       HLTFatal("no component handler available");
1063     }
1064   } else {
1065     iResult=-EINVAL;
1066   }
1067   return iResult;
1068 }
1069
1070 int AliHLTSystem::Configure(AliRunLoader* runloader)
1071 {
1072   // see header file for class documentation
1073   return Configure(NULL, runloader);
1074 }
1075
1076 int AliHLTSystem::Configure(AliRawReader* rawReader, AliRunLoader* runloader)
1077 {
1078   // see header file for class documentation
1079   int iResult=0;
1080   if (CheckStatus(kRunning)) {
1081     HLTError("HLT system in running state, can not configure");
1082     return -EBUSY;
1083   }
1084   ClearStatusFlags(kTaskListCreated);
1085   if (CheckFilter(kHLTLogDebug))
1086     AliHLTModuleAgent::PrintStatus();
1087   if (CheckStatus(kConfigurationLoaded)==0) {
1088     iResult=LoadConfigurations(rawReader, runloader);
1089   } else {
1090     if (fChains.Length()==0) {
1091       HLTError("custom configuration(s) specified, but no configuration to run in local reconstruction, use \'chains=<chain,...>\' option");
1092       iResult=-ENOENT;
1093     }
1094   }
1095   if (iResult>=0) {
1096     SetStatusFlags(kConfigurationLoaded);
1097     if (CheckFilter(kHLTLogDebug))
1098       fpConfigurationHandler->PrintConfigurations();
1099     iResult=BuildTaskListsFromReconstructionChains(rawReader, runloader);
1100     if (iResult>=0) {
1101       SetStatusFlags(kTaskListCreated);
1102     }
1103   }
1104   if (iResult<0) SetStatusFlags(kError);
1105   
1106   return iResult;
1107 }
1108
1109 int AliHLTSystem::ScanOptions(const char* options)
1110 {
1111   // see header file for class documentation
1112   int iResult=0;
1113   if (options) {
1114     //AliHLTComponentHandler::TLibraryMode libMode=AliHLTComponentHandler::kDynamic;
1115     TString libs("");
1116     TString alloptions(options);
1117     TObjArray* pTokens=alloptions.Tokenize(" ");
1118     if (pTokens) {
1119       int iEntries=pTokens->GetEntries();
1120       for (int i=0; i<iEntries; i++) {
1121         TString token=(((TObjString*)pTokens->At(i))->GetString());
1122         if (token.Contains("loglevel=")) {
1123           TString param=token.ReplaceAll("loglevel=", "");
1124           if (param.IsDigit()) {
1125             SetGlobalLoggingLevel((AliHLTComponentLogSeverity)param.Atoi());
1126           } else if (param.BeginsWith("0x") &&
1127                      param.Replace(0,2,"",0).IsHex()) {
1128             int severity=0;
1129             sscanf(param.Data(),"%x", &severity);
1130             SetGlobalLoggingLevel((AliHLTComponentLogSeverity)severity);
1131           } else {
1132             HLTWarning("wrong parameter for option \'loglevel=\', (hex) number expected");
1133           }
1134         } else if (token.Contains("frameworklog=")) {
1135           TString param=token.ReplaceAll("frameworklog=", "");
1136           if (param.IsDigit()) {
1137             SetFrameworkLog((AliHLTComponentLogSeverity)param.Atoi());
1138           } else if (param.BeginsWith("0x") &&
1139                      param.Replace(0,2,"",0).IsHex()) {
1140             int severity=0;
1141             sscanf(param.Data(),"%x", &severity);
1142             SetFrameworkLog((AliHLTComponentLogSeverity)severity);
1143           } else {
1144             HLTWarning("wrong parameter for option \'loglevel=\', (hex) number expected");
1145           }
1146         } else if (token.Contains("alilog=off")) {
1147           SwitchAliLog(0);
1148         } else if (token.Contains("config=")) {
1149           TString param=token.ReplaceAll("config=", "");
1150           Int_t error=0;
1151           gROOT->Macro(param.Data(), &error);
1152           if (error==0) {
1153             SetStatusFlags(kConfigurationLoaded);
1154           } else {
1155             HLTError("can not execute macro \'%s\'", param.Data());
1156             iResult=-EBADF;
1157           }
1158         } else if (token.Contains("chains=")) {
1159           TString param=token.ReplaceAll("chains=", "");
1160           fChains=param.ReplaceAll(",", " ");
1161           if (fChains.IsNull()) fChains=" "; // disable all chains
1162         } else if (token.Contains("libmode=")) {
1163           TString param=token.ReplaceAll("libmode=", "");
1164           param.ReplaceAll(",", " ");
1165           if (fpComponentHandler) {
1166             if (param.CompareTo("static")==0) {
1167               fpComponentHandler->SetLibraryMode(AliHLTComponentHandler::kStatic);
1168             } else if (param.CompareTo("dynamic")==0) {
1169               fpComponentHandler->SetLibraryMode(AliHLTComponentHandler::kDynamic);
1170             } else {
1171               HLTWarning("wrong argument for option \'libmode=\', use \'static\' or \'dynamic\'");
1172             }
1173           }
1174         } else if (token.BeginsWith("lib") && token.EndsWith(".so")) {
1175           libs+=token;
1176           libs+=" ";
1177         } else {
1178           HLTWarning("unknown option \'%s\'", token.Data());
1179         }
1180       }
1181       delete pTokens;
1182     }
1183
1184     if (iResult>=0) {
1185       if (libs.IsNull()) {
1186         const char** deflib=fgkHLTDefaultLibs;
1187         while (*deflib) {
1188           libs+=*deflib++;
1189           libs+=" ";
1190         }
1191       }
1192       if ((!CheckStatus(AliHLTSystem::kLibrariesLoaded)) &&
1193           (LoadComponentLibraries(libs.Data())<0)) {
1194         HLTError("error while loading HLT libraries");
1195         iResult=-EFAULT;
1196       }
1197     }
1198   }
1199   return iResult;
1200 }
1201
1202 int AliHLTSystem::Reset(int bForce)
1203 {
1204   // see header file for class documentation
1205   int iResult=0;
1206   if (!bForce && CheckStatus(kRunning)) {
1207     HLTError("HLT system in running state, can not configure");
1208     return -EBUSY;
1209   }
1210   CleanTaskList();
1211   ClearStatusFlags(~kUninitialized);
1212   return iResult;
1213 }
1214
1215 int AliHLTSystem::LoadConfigurations(AliRawReader* rawReader, AliRunLoader* runloader)
1216 {
1217   // see header file for class documentation
1218   if (CheckStatus(kRunning)) {
1219     HLTError("HLT system in running state, can not configure");
1220     return -EBUSY;
1221   }
1222   int iResult=0;
1223   AliHLTModuleAgent* pAgent=AliHLTModuleAgent::GetFirstAgent();
1224   TString extralibs;
1225   while (pAgent && iResult>=0) {
1226     const char* deplibs=pAgent->GetRequiredComponentLibraries();
1227     if (deplibs) {
1228       HLTDebug("required libraries \'%s\' for agent %s (%p)", deplibs, pAgent->GetName(), pAgent);
1229       extralibs+=deplibs;
1230     }
1231     if (iResult>=0) {
1232       HLTDebug("load configurations for agent %s (%p)", pAgent->GetName(), pAgent);
1233       pAgent->CreateConfigurations(fpConfigurationHandler, rawReader, runloader);
1234       pAgent=AliHLTModuleAgent::GetNextAgent();
1235     }
1236   }
1237   if (iResult>=0) {
1238     iResult=LoadComponentLibraries(extralibs.Data());
1239   }
1240
1241   return iResult;
1242 }
1243
1244 int AliHLTSystem::BuildTaskListsFromReconstructionChains(AliRawReader* rawReader, AliRunLoader* runloader)
1245 {
1246   // see header file for class documentation
1247   if (CheckStatus(kRunning)) {
1248     HLTError("HLT system in running state, can not configure");
1249     return -EBUSY;
1250   }
1251   if (!CheckStatus(kConfigurationLoaded)) {
1252     HLTWarning("configurations not yet loaded");
1253     return 0;
1254   }
1255
1256   int iResult=0;
1257   int bHaveOutput=0;
1258
1259   // query chains
1260   TString chains;
1261   if (fChains.Length()>0) {
1262     chains=fChains;
1263     HLTImportant("custom reconstruction chain: %s", chains.Data());
1264   } else {
1265     AliHLTModuleAgent* pAgent=AliHLTModuleAgent::GetFirstAgent();
1266     while ((pAgent || fChains.Length()>0) && iResult>=0) {
1267       const char* agentchains=pAgent->GetReconstructionChains(rawReader, runloader);
1268       if (agentchains) {
1269         if (!chains.IsNull()) chains+=" ";
1270         chains+=agentchains;
1271         HLTInfo("reconstruction chains for agent %s (%p): %s", pAgent->GetName(), pAgent, agentchains);
1272       }
1273       pAgent=AliHLTModuleAgent::GetNextAgent();
1274     }
1275   }
1276
1277   // build task list for chains
1278   TObjArray* pTokens=chains.Tokenize(" ");
1279   if (pTokens) {
1280     int iEntries=pTokens->GetEntries();
1281     for (int i=0; i<iEntries && iResult>=0; i++) {
1282       const char* pCID=((TObjString*)pTokens->At(i))->GetString().Data();
1283       AliHLTConfiguration* pConf=fpConfigurationHandler->FindConfiguration(pCID);
1284       if (pConf) {
1285         iResult=BuildTaskList(pConf);
1286         if (true) { // condition was deprecated but kept for sake of svn diff
1287           // bHaveOutput variable has to be set for both running modes
1288           // AliHLTSimulation and AliHLTReconstruction
1289           assert(fpComponentHandler!=NULL);
1290           TString cid=pConf->GetComponentID();
1291           if (runloader!=NULL && cid.CompareTo("HLTOUT")==0) {
1292             // remove from the input of a global HLTOUT configuration
1293             chains.ReplaceAll(pCID, "");
1294           } else if (bHaveOutput==0) {
1295             // check whether this configuration produces data output
1296             if ((bHaveOutput=fpComponentHandler->HasOutputData(cid.Data()))<0) {
1297               bHaveOutput=0;
1298               chains.ReplaceAll(pCID, "");
1299             }
1300           }
1301         }
1302       } else {
1303         HLTWarning("can not find configuration %s", pCID);
1304       }
1305     }
1306     delete pTokens;
1307   }
1308
1309   // build HLTOUT for simulation
1310   if (iResult>=0 && runloader) {
1311     if (bHaveOutput) {
1312       // there are components in the chain which produce data which need to be
1313       // piped to an HLTOUT
1314       if (fpComponentHandler->FindComponentIndex("HLTOUT")>=0 ||
1315           fpComponentHandler->LoadLibrary("libHLTsim.so")>=0) {
1316         AliHLTConfiguration globalout("_globalout_", "HLTOUT", chains.Data(), NULL);
1317         iResult=BuildTaskList("_globalout_");
1318       } else {
1319         HLTError("can not load libHLTsim.so and HLTOUT component");
1320         iResult=-EFAULT;
1321       }
1322     }
1323   }
1324
1325   // build HLTOUT task for reconstruction
1326   // Matthias 08.07.2008 the rawReader is never set when running embedded into
1327   // AliReconstruction. The system is configured during AliHLTReconstructor::Init
1328   // where the RawReader is not available. It is available in the first invocation
1329   // of Reconstruct.
1330   // 
1331   // That means that policy is slightly changed:
1332   // - if the run loader is available -> AliSimulation
1333   // - no run loader available -> AliReconstruction
1334   if (iResult>=0 && !runloader) {
1335     if (bHaveOutput) {
1336       // there are components in the chain which produce data which need to be
1337       // piped to an HLTOUT sub-collection
1338       if (!fpHLTOUTTask) {
1339         iResult=AddHLTOUTTask(chains.Data());
1340       }
1341     }
1342   }
1343
1344   if (iResult>=0) SetStatusFlags(kTaskListCreated);
1345
1346   return iResult;
1347 }
1348
1349 int AliHLTSystem::AddHLTOUTTask(const char* hltoutchains)
1350 {
1351   // see header file for class documentation
1352   int iResult=0;
1353   if (!hltoutchains || hltoutchains[0]==0) return 0;
1354
1355   // check chains for output
1356   TString chains=hltoutchains;
1357   TObjArray* pTokens=chains.Tokenize(" ");
1358   if (pTokens) {
1359     int iEntries=pTokens->GetEntries();
1360     for (int i=0; i<iEntries && iResult>=0; i++) {
1361       const char* token=((TObjString*)pTokens->At(i))->GetString().Data();
1362       AliHLTConfiguration* pConf=fpConfigurationHandler->FindConfiguration(token);
1363       if (pConf) {
1364         TString cid=pConf->GetComponentID();
1365         if (fpComponentHandler->HasOutputData(cid.Data())) {
1366           continue;
1367         }
1368       } else {
1369         HLTWarning("can not find configuration %s", token);
1370       }
1371       // remove from the list of hltout chains
1372       chains.ReplaceAll(token, "");
1373     }
1374     delete pTokens;
1375   }
1376
1377   // do not create the HLTOUT task if none of the chains have output
1378   if (chains.IsNull()) return 0;
1379
1380   // indicate the task to be available
1381   iResult=1;
1382
1383   if (fpHLTOUTTask) {
1384     if (strcmp(chains.Data(), fpHLTOUTTask->GetSourceChains())==0) {
1385       HLTWarning("HLTOUT task already added for chains \"%s\" %p", chains.Data(), fpHLTOUTTask);
1386     } else {
1387       HLTError("HLTOUT task already added for chains \"%s\" %p, ignoring new chains  \"%s\"",
1388                fpHLTOUTTask->GetSourceChains(), fpHLTOUTTask, chains.Data());
1389     }
1390     return iResult;
1391   }
1392
1393   fpHLTOUTTask=new AliHLTOUTTask(chains);
1394   if (fpHLTOUTTask) {
1395     if (fpHLTOUTTask->GetConf() && fpHLTOUTTask->GetConf()->SourcesResolved()>=0) {
1396       iResult=InsertTask(fpHLTOUTTask);
1397     } else {
1398       HLTError("HLTOUT task (%s) sources not resolved", fpHLTOUTTask->GetName());
1399       iResult=-ENOENT;
1400     }
1401
1402     if (iResult<0) {
1403       delete fpHLTOUTTask;
1404     }
1405
1406   } else {
1407     iResult=-ENOMEM;
1408   }
1409   return iResult;
1410 }
1411
1412 int AliHLTSystem::CheckStatus(int flag)
1413 {
1414   // see header file for class documentation
1415   if (flag==kUninitialized && flag==fState) return 1;
1416   if ((fState&flag)==flag) return 1;
1417   return 0;
1418 }
1419
1420 int AliHLTSystem::GetStatusFlags()
1421 {
1422   // see header file for class documentation
1423   return fState;
1424 }
1425
1426 int AliHLTSystem::SetStatusFlags(int flags)
1427 {
1428   // see header file for class documentation
1429   fState|=flags;
1430   return fState;
1431 }
1432
1433 int AliHLTSystem::ClearStatusFlags(int flags)
1434 {
1435   // see header file for class documentation
1436   fState&=~flags;
1437   return fState;
1438 }
1439
1440 void* AliHLTSystem::FindDynamicSymbol(const char* library, const char* symbol)
1441 {
1442   // see header file for class documentation
1443   if (fpComponentHandler==NULL) return NULL;
1444   return fpComponentHandler->FindSymbol(library, symbol);
1445 }
1446
1447 void AliHLTSystem::SetFrameworkLog(AliHLTComponentLogSeverity level) 
1448 {
1449   // see header file for class documentation
1450   SetLocalLoggingLevel(level);
1451   if (fpComponentHandler) fpComponentHandler->SetLocalLoggingLevel(level);
1452   if (fpConfigurationHandler) fpConfigurationHandler->SetLocalLoggingLevel(level);
1453 }