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