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