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