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