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