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