3 //**************************************************************************
4 //* This file is property of and copyright by the ALICE HLT Project *
5 //* ALICE Experiment at CERN, All rights reserved. *
7 //* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no> *
8 //* Timm Steinbeck <timm@kip.uni-heidelberg.de> *
9 //* for The ALICE HLT Project. *
11 //* Permission to use, copy, modify and distribute this software and its *
12 //* documentation strictly for non-commercial purposes is hereby granted *
13 //* without fee, provided that the above copyright notice appears in all *
14 //* copies and that both the copyright notice and this permission notice *
15 //* appear in the supporting documentation. The authors make no claims *
16 //* about the suitability of this software for any purpose. It is *
17 //* provided "as is" without express or implied warranty. *
18 //**************************************************************************
20 // @file AliHLTComponent.cxx
21 // @author Matthias Richter, Timm Steinbeck
23 // @brief Base class implementation for HLT components. */
24 // @note The class is both used in Online (PubSub) and Offline (AliRoot)
32 //#include "AliHLTStdIncludes.h"
33 #include "AliHLTComponent.h"
34 #include "AliHLTComponentHandler.h"
35 #include "AliHLTMessage.h"
36 #include "AliHLTCTPData.h"
37 #include "AliRawDataHeader.h"
40 #include "TObjArray.h"
41 #include "TObjectTable.h"
43 #include "TStopwatch.h"
48 #include "AliHLTMemoryFile.h"
49 #include "AliHLTMisc.h"
55 * default compression level for ROOT objects
57 #define ALIHLTCOMPONENT_DEFAULT_OBJECT_COMPRESSION 5
58 #define ALIHLTCOMPONENT_STATTIME_SCALER 1000000
60 /** ROOT macro for the implementation of ROOT specific class methods */
61 ClassImp(AliHLTComponent);
63 /** stopwatch macro using the stopwatch guard */
64 #define ALIHLTCOMPONENT_STOPWATCH(type) AliHLTStopwatchGuard swguard(fpStopwatches!=NULL?reinterpret_cast<TStopwatch*>(fpStopwatches->At((int)type)):NULL)
65 //#define ALIHLTCOMPONENT_STOPWATCH(type)
67 /** stopwatch macro for operations of the base class */
68 #define ALIHLTCOMPONENT_BASE_STOPWATCH() ALIHLTCOMPONENT_STOPWATCH(kSWBase)
69 /** stopwatch macro for operations of the detector algorithm (DA) */
70 #define ALIHLTCOMPONENT_DA_STOPWATCH() ALIHLTCOMPONENT_STOPWATCH(kSWDA)
72 AliHLTComponent::AliHLTComponent()
80 fCurrentInputBlock(-1),
81 fSearchDataType(kAliHLTVoidDataType),
86 fOutputBufferFilled(0),
88 fpStopwatches(new TObjArray(kSWTypeCount)),
91 fCDBSetRunNoFunc(false),
96 fEventType(gkAliEventTypeUnknown),
99 fEventDoneDataSize(0),
100 fCompressionLevel(ALIHLTCOMPONENT_DEFAULT_OBJECT_COMPRESSION)
104 , fLastPushBackTime(-1)
106 // see header file for class documentation
108 // refer to README to build package
110 // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
111 memset(&fEnvironment, 0, sizeof(AliHLTAnalysisEnvironment));
112 if (fgpComponentHandler)
113 fgpComponentHandler->ScheduleRegister(this);
114 //SetLocalLoggingLevel(kHLTLogDefault);
117 AliHLTComponent::~AliHLTComponent()
119 // see header file for function documentation
120 if (fpBenchmark) delete fpBenchmark;
123 CleanupInputObjects();
124 if (fpStopwatches!=NULL) delete fpStopwatches;
126 AliHLTMemoryFilePList::iterator element=fMemFiles.begin();
127 while (element!=fMemFiles.end()) {
129 if ((*element)->IsClosed()==0) {
130 HLTWarning("memory file has not been closed, possible data loss or incomplete buffer");
131 // close but do not flush as we dont know whether the buffer is still valid
132 (*element)->CloseMemoryFile(0);
144 delete [] reinterpret_cast<AliHLTUInt8_t*>( fEventDoneData );
153 AliHLTComponentHandler* AliHLTComponent::fgpComponentHandler=NULL;
155 int AliHLTComponent::SetGlobalComponentHandler(AliHLTComponentHandler* pCH, int bOverwrite)
157 // see header file for function documentation
159 if (fgpComponentHandler==NULL || bOverwrite!=0)
160 fgpComponentHandler=pCH;
166 int AliHLTComponent::UnsetGlobalComponentHandler()
168 // see header file for function documentation
169 return SetGlobalComponentHandler(NULL,1);
172 int AliHLTComponent::SetComponentEnvironment(const AliHLTAnalysisEnvironment* comenv, void* environParam)
174 // see header file for function documentation
175 HLTLogKeyword(fChainId.c_str());
178 memset(&fEnvironment, 0, sizeof(AliHLTAnalysisEnvironment));
179 memcpy(&fEnvironment, comenv, comenv->fStructSize<sizeof(AliHLTAnalysisEnvironment)?comenv->fStructSize:sizeof(AliHLTAnalysisEnvironment));
180 fEnvironment.fStructSize=sizeof(AliHLTAnalysisEnvironment);
181 fEnvironment.fParam=environParam;
186 int AliHLTComponent::Init(const AliHLTAnalysisEnvironment* comenv, void* environParam, int argc, const char** argv )
188 // see header file for function documentation
189 HLTLogKeyword(fChainId.c_str());
192 SetComponentEnvironment(comenv, environParam);
195 fLastPushBackTime=-1;
198 const char** pArguments=NULL;
203 pArguments=new const char*[argc];
205 for (int i=0; i<argc && iResult>=0; i++) {
206 if (fComponentArgs.size()>0) fComponentArgs+=" ";
207 fComponentArgs+=argv[i];
209 if (argument.IsNull()) continue;
212 if (argument.CompareTo("-benchmark")==0) {
215 } else if (argument.BeginsWith("-loglevel=")) {
216 TString parameter=argument.ReplaceAll("-loglevel=", "");
217 parameter.Remove(TString::kLeading, ' '); // remove all blanks
218 if (parameter.BeginsWith("0x") &&
219 parameter.Replace(0,2,"",0).IsHex()) {
220 unsigned int loglevel=kHLTLogNone;
221 sscanf(parameter.Data(),"%x", &loglevel);
222 SetLocalLoggingLevel((AliHLTComponentLogSeverity)loglevel);
224 HLTError("wrong parameter for argument %s, hex number expected", argument.Data());
227 // -object-compression=
228 } else if (argument.BeginsWith("-object-compression=")) {
229 argument.ReplaceAll("-object-compression=", "");
230 if (argument.IsDigit()) {
231 fCompressionLevel=argument.Atoi();
232 if (fCompressionLevel<0 || fCompressionLevel>9) {
233 HLTWarning("invalid compression level %d, setting to default %d", fCompressionLevel, ALIHLTCOMPONENT_DEFAULT_OBJECT_COMPRESSION);
234 fCompressionLevel=ALIHLTCOMPONENT_DEFAULT_OBJECT_COMPRESSION;
237 HLTError("wrong parameter for argument -object-compression, number expected");
240 } else if (argument.BeginsWith("-pushback-period=")) {
241 argument.ReplaceAll("-pushback-period=", "");
242 if (argument.IsDigit()) {
243 fPushbackPeriod=argument.Atoi();
245 HLTError("wrong parameter for argument -pushback-period, number expected");
247 // -disable-component-stat
248 } else if (argument.CompareTo("-disable-component-stat")==0) {
249 fFlags|=kDisableComponentStat;
251 pArguments[iNofChildArgs++]=argv[i];
259 HLTError("missing parameter for argument %s", argument.Data());
263 iResult=CheckOCDBEntries();
266 iResult=DoInit(iNofChildArgs, pArguments);
271 // find out if the component wants to get the steering events
273 AliHLTComponentDataTypeList inputDt;
274 GetInputDataTypes(inputDt);
275 bool bRequireSteeringBlocks=false;
276 for (AliHLTComponentDataTypeList::iterator dt=inputDt.begin();
277 dt!=inputDt.end() && !bRequireSteeringBlocks;
279 bRequireSteeringBlocks|=MatchExactly(*dt,kAliHLTDataTypeSOR);
280 bRequireSteeringBlocks|=MatchExactly(*dt,kAliHLTDataTypeRunType);
281 bRequireSteeringBlocks|=MatchExactly(*dt,kAliHLTDataTypeEOR);
282 bRequireSteeringBlocks|=MatchExactly(*dt,kAliHLTDataTypeDDL);
283 bRequireSteeringBlocks|=MatchExactly(*dt,kAliHLTDataTypeComponentStatistics);
285 if (bRequireSteeringBlocks) fFlags|=kRequireSteeringBlocks;
287 if (pArguments) delete [] pArguments;
289 #if defined(HLT_COMPONENT_STATISTICS)
290 // benchmarking stopwatch for the component statistics
291 fpBenchmark=new TStopwatch;
292 #endif // HLT_COMPONENT_STATISTICS
297 int AliHLTComponent::Deinit()
299 // see header file for function documentation
300 HLTLogKeyword(fChainId.c_str());
304 // TODO: the warning should be kept, but the condition is wrong since the
305 // AliHLTRunDesc is set before the SOR event in the SetRunDescription
306 // method. A couple of state flags should be defined but that is a bit more
307 // work to do. For the moment disable the warning (2009-07-01)
308 // 2009-09-08: now, the info is not cleared in the ProcessEvent, because it
309 // might be needed by components during the event processing.
310 //HLTWarning("did not receive EOR for run %d", fpRunDesc->fRunNo);
311 AliHLTRunDesc* pRunDesc=fpRunDesc;
325 int AliHLTComponent::InitCDB(const char* cdbPath, AliHLTComponentHandler* pHandler)
327 // see header file for function documentation
329 HLTInfo("Using CDB: %s", cdbPath);
331 // I have to think about separating the library handling from the
332 // component handler. Requiring the component handler here is not
333 // the cleanest solution.
334 // We presume the library already to be loaded, which is the case
335 // because it is loaded in the initialization of the logging functionality
338 AliHLTMiscInitCDB_t pFunc=(AliHLTMiscInitCDB_t)pHandler->FindSymbol(ALIHLTMISC_LIBRARY, ALIHLTMISC_INIT_CDB);
341 if (cdbPath && cdbPath[0]!=0) {
343 // very temporary fix, have to check for other formats
344 if (!path.BeginsWith("local://")) {
349 if ((iResult=(*pFunc)(path.Data()))>=0) {
350 if (!(fCDBSetRunNoFunc=pHandler->FindSymbol(ALIHLTMISC_LIBRARY, ALIHLTMISC_SET_CDB_RUNNO))) {
351 Message(NULL, kHLTLogWarning, "AliHLTComponent::InitCDB", "init CDB",
352 "can not find function to set CDB run no");
356 Message(NULL, kHLTLogError, "AliHLTComponent::InitCDB", "init CDB",
357 "can not find initialization function");
366 int AliHLTComponent::SetCDBRunNo(int runNo)
368 // see header file for function documentation
369 if (!fCDBSetRunNoFunc) return 0;
370 return (*((AliHLTMiscSetCDBRunNo_t)fCDBSetRunNoFunc))(runNo);
373 int AliHLTComponent::SetRunDescription(const AliHLTRunDesc* desc, const char* /*runType*/)
375 // see header file for function documentation
376 if (!desc) return -EINVAL;
377 if (desc->fStructSize!=sizeof(AliHLTRunDesc)) {
378 HLTError("invalid size of RunDesc struct (%ul)", desc->fStructSize);
383 fpRunDesc=new AliHLTRunDesc;
384 if (!fpRunDesc) return -ENOMEM;
385 *fpRunDesc=kAliHLTVoidRunDesc;
388 if (fpRunDesc->fRunNo!=kAliHLTVoidRunNo && fpRunDesc->fRunNo!=desc->fRunNo) {
389 HLTWarning("Run description has already been set");
392 SetCDBRunNo(fpRunDesc->fRunNo);
393 // TODO: we have to decide about the runType
397 int AliHLTComponent::SetComponentDescription(const char* desc)
399 // see header file for function documentation
403 TString descriptor=desc;
404 TObjArray* pTokens=descriptor.Tokenize(" ");
406 for (int i=0; i<pTokens->GetEntriesFast() && iResult>=0; i++) {
407 TString argument=((TObjString*)pTokens->At(i++))->GetString();
408 if (!argument || argument.IsNull()) continue;
411 if (argument.BeginsWith("chainid")) {
412 argument.ReplaceAll("chainid", "");
413 if (argument.BeginsWith("=")) {
414 fChainId=argument.Replace(0,1,"");
415 fChainIdCrc=CalculateChecksum((const AliHLTUInt8_t*)fChainId.c_str(), fChainId.length());
416 HLTDebug("setting component description: chain id %s crc 0x%8x", fChainId.c_str(), fChainIdCrc);
421 HLTWarning("unknown component description %s", argument.Data());
430 int AliHLTComponent::ConfigureFromArgumentString(int argc, const char** argv)
432 // see header file for function documentation
434 vector<const char*> array;
435 TObjArray choppedArguments;
438 for (i=0; i<argc && iResult>=0; i++) {
440 if (argument.IsWhitespace()) continue;
442 // special handling for single component arguments ending with
443 // a sequence of blanks
444 argument.Remove(0, argument.First(' '));
445 if (argument.IsWhitespace()) {
446 array.push_back(argv[i]);
450 // extra blank to insert blank token before leading quotes
453 // insert blank in consecutive quotes to correctly tokenize
454 argument.ReplaceAll("''", "' '");
455 // replace newlines by blanks
456 argument.ReplaceAll("\n", " ");
457 if (argument.IsNull()) continue;
458 TObjArray* pTokensQuote=argument.Tokenize("'");
460 if (pTokensQuote->GetEntriesFast()>0) {
461 for (int k=0; k<pTokensQuote->GetEntriesFast(); k++) {
462 argument=((TObjString*)pTokensQuote->At(k))->GetString();
463 if (argument.IsWhitespace()) continue;
465 // every second entry is enclosed by quotes and thus
466 // one single argument
467 array.push_back(argument.Data());
469 TObjArray* pTokens=argument.Tokenize(" ");
471 if (pTokens->GetEntriesFast()>0) {
472 for (int n=0; n<pTokens->GetEntriesFast(); n++) {
473 choppedArguments.AddLast(pTokens->At(n));
474 TString data=((TObjString*)pTokens->At(n))->GetString();
475 if (!data.IsNull()) {
476 array.push_back(data.Data());
479 pTokens->SetOwner(kFALSE);
485 pTokensQuote->SetOwner(kFALSE);
491 for (i=0; (unsigned)i<array.size() && iResult>=0;) {
492 int result=ScanConfigurationArgument(array.size()-i, &array[i]);
494 HLTWarning("unknown component argument %s", array[i]);
496 } else if (result>0) {
500 if (iResult==-EINVAL) {
501 HLTError("unknown argument %s", array[i]);
502 } else if (iResult==-EPROTO) {
503 HLTError("missing/wrong parameter for argument %s (%s)", array[i], (array.size()>(unsigned)i+1)?array[i+1]:"missing");
505 HLTError("scan of argument %s failed (%d)", array[i], iResult);
513 int AliHLTComponent::ConfigureFromCDBTObjString(const char* entries, const char* key)
515 // load a list of OCDB objects and configure from the objects
516 // can either be a TObjString or a TMap with a TObjString:TObjString key-value pair
519 TString confEntries=entries;
520 TObjArray* pTokens=confEntries.Tokenize(" ");
522 for (int n=0; n<pTokens->GetEntriesFast(); n++) {
523 const char* path=((TObjString*)pTokens->At(n))->GetString().Data();
524 const char* chainId=GetChainId();
525 HLTInfo("configure from entry \"%s\"%s%s, chain id %s", path, key?" key ":"",key?key:"", (chainId!=NULL && chainId[0]!=0)?chainId:"<none>");
526 TObject* pOCDBObject = LoadAndExtractOCDBObject(path, key);
528 TObjString* pString=dynamic_cast<TObjString*>(pOCDBObject);
530 TMap* pMap=dynamic_cast<TMap*>(pOCDBObject);
532 // this is the case where no key has been specified and the OCDB
533 // object is a TMap, search for the default key
534 TObject* pObject=pMap->GetValue("default");
535 if (pObject && (pString=dynamic_cast<TObjString*>(pObject))!=NULL) {
536 HLTInfo("using default key of TMap of configuration object \"%s\"", path);
538 HLTError("no default key available in TMap of configuration object \"%s\"", path);
546 HLTInfo("received configuration object string: \'%s\'", pString->GetString().Data());
547 arguments+=pString->GetString().Data();
550 HLTError("configuration object \"%s\"%s%s has wrong type, required TObjString", path, key?" key ":"",key?key:"");
554 HLTError("can not fetch object \"%s\" from OCDB", path);
560 if (iResult>=0 && !arguments.IsNull()) {
561 const char* array=arguments.Data();
562 iResult=ConfigureFromArgumentString(1, &array);
567 TObject* AliHLTComponent::LoadAndExtractOCDBObject(const char* path, int version, int subVersion, const char* key)
569 // see header file for function documentation
570 AliCDBEntry* pEntry=AliHLTMisc::Instance().LoadOCDBEntry(path, GetRunNo(), version, subVersion);
571 if (!pEntry) return NULL;
572 TObject* pObject=AliHLTMisc::Instance().ExtractObject(pEntry);
573 TMap* pMap=dynamic_cast<TMap*>(pObject);
575 pObject=pMap->GetValue(key);
577 pObject=pMap->GetValue("default");
579 HLTWarning("can not find object for key \"%s\" in TMap of configuration object \"%s\", using key \"default\"", key, path);
583 HLTError("can not find object for key \"%s\" in TMap of configuration object \"%s\"", key, path);
590 int AliHLTComponent::DoInit( int /*argc*/, const char** /*argv*/)
592 // default implementation, childs can overload
593 HLTLogKeyword("dummy");
597 int AliHLTComponent::DoDeinit()
599 // default implementation, childs can overload
600 HLTLogKeyword("dummy");
604 int AliHLTComponent::Reconfigure(const char* /*cdbEntry*/, const char* /*chainId*/)
606 // default implementation, childs can overload
607 HLTLogKeyword("dummy");
611 int AliHLTComponent::ReadPreprocessorValues(const char* /*modules*/)
613 // default implementation, childs can overload
614 HLTLogKeyword("dummy");
618 int AliHLTComponent::ScanConfigurationArgument(int /*argc*/, const char** /*argv*/)
620 // default implementation, childs can overload
621 HLTLogKeyword("dummy");
622 HLTWarning("The function needs to be implemented by the component");
626 int AliHLTComponent::StartOfRun()
628 // default implementation, childs can overload
629 HLTLogKeyword("dummy");
633 int AliHLTComponent::EndOfRun()
635 // default implementation, childs can overload
636 HLTLogKeyword("dummy");
641 int AliHLTComponent::GetOutputDataTypes(AliHLTComponentDataTypeList& /*tgtList*/)
643 // default implementation, childs can overload
644 HLTLogKeyword("dummy");
648 void AliHLTComponent::GetOCDBObjectDescription( TMap* const /*targetArray*/)
650 // default implementation, childs can overload
651 HLTLogKeyword("dummy");
654 int AliHLTComponent::CheckOCDBEntries(const TMap* const externList)
656 // check the availability of the OCDB entry descriptions in the TMap
657 // key : complete OCDB path of the entry
658 // value : auxiliary object - short description
659 // if the external map was not provided the function invokes
660 // interface function GetOCDBObjectDescription() to retrieve the list.
663 iResult=AliHLTMisc::Instance().CheckOCDBEntries(externList);
667 pMap->SetOwnerKeyValue(kTRUE);
668 GetOCDBObjectDescription(pMap);
669 iResult=AliHLTMisc::Instance().CheckOCDBEntries(pMap);
678 void AliHLTComponent::DataType2Text( const AliHLTComponentDataType& type, char output[kAliHLTComponentDataTypefIDsize+kAliHLTComponentDataTypefOriginSize+2] ) const
680 // see header file for function documentation
681 memset( output, 0, kAliHLTComponentDataTypefIDsize+kAliHLTComponentDataTypefOriginSize+2 );
682 strncat( output, type.fOrigin, kAliHLTComponentDataTypefOriginSize );
683 strcat( output, ":" );
684 strncat( output, type.fID, kAliHLTComponentDataTypefIDsize );
687 string AliHLTComponent::DataType2Text( const AliHLTComponentDataType& type, int mode)
689 // see header file for function documentation
693 // aligned to 8 and 4 chars respectively, blocks enclosed in quotes and
694 // separated by blank e.g.
700 for (i=0; i<kAliHLTComponentDataTypefIDsize; i++) {
701 unsigned char* puc=(unsigned char*)type.fID;
703 sprintf(tmp, "\\%x", type.fID[i]);
705 sprintf(tmp, "%c", type.fID[i]);
709 for (i=0; i<kAliHLTComponentDataTypefOriginSize; i++) {
710 unsigned char* puc=(unsigned char*)type.fOrigin;
712 sprintf(tmp, "\\%x", type.fOrigin[i]);
714 sprintf(tmp, "%c", type.fOrigin[i]);
721 // origin typeid as numbers separated by colon e.g.
722 // aligned to 8 and 4 chars respectively, all characters separated by
724 // '84'80'67'32':'68'68'76'95'82'65'87'32'
728 for (i=0; i<kAliHLTComponentDataTypefOriginSize; i++) {
729 sprintf(tmp, "'%d", type.fOrigin[i]);
733 for (i=0; i<kAliHLTComponentDataTypefIDsize; i++) {
734 sprintf(tmp, "%d'", type.fID[i]);
740 // origin typeid separated by colon e.g.
741 // aligned to 8 and 4 chars respectively, all characters separated by
743 // 'T'P'C' ':'D'D'L'_'R'A'W' '
747 for (i=0; i<kAliHLTComponentDataTypefOriginSize; i++) {
748 unsigned char* puc=(unsigned char*)type.fOrigin;
750 sprintf(tmp, "'\\%x", type.fOrigin[i]);
752 sprintf(tmp, "'%c", type.fOrigin[i]);
756 for (i=0; i<kAliHLTComponentDataTypefIDsize; i++) {
757 unsigned char* puc=(unsigned char*)type.fID;
759 sprintf(tmp, "\\%x'", type.fID[i]);
761 sprintf(tmp, "%c'", type.fID[i]);
768 // aligned to 8 and 4 chars respectively, separated by colon e.g.
770 if (type==kAliHLTVoidDataType) {
773 // some gymnastics in order to avoid a '0' which is part of either or both
774 // ID and origin terminating the whole string. Unfortunately, string doesn't
775 // stop appending at the '0' if the number of elements to append was
776 // explicitely specified
778 tmp.append(type.fOrigin, kAliHLTComponentDataTypefOriginSize);
779 out.append(tmp.c_str());
782 tmp.append(type.fID, kAliHLTComponentDataTypefIDsize);
783 out.append(tmp.c_str());
789 void* AliHLTComponent::AllocMemory( unsigned long size )
791 // see header file for function documentation
792 if (fEnvironment.fAllocMemoryFunc)
793 return (*fEnvironment.fAllocMemoryFunc)(fEnvironment.fParam, size );
794 HLTFatal("no memory allocation handler registered");
798 int AliHLTComponent::MakeOutputDataBlockList( const AliHLTComponentBlockDataList& blocks, AliHLTUInt32_t* blockCount,
799 AliHLTComponentBlockData** outputBlocks )
801 // see header file for function documentation
802 if ( blockCount==NULL || outputBlocks==NULL )
804 AliHLTUInt32_t count = blocks.size();
808 *outputBlocks = NULL;
811 *outputBlocks = reinterpret_cast<AliHLTComponentBlockData*>( AllocMemory( sizeof(AliHLTComponentBlockData)*count ) );
812 if ( !*outputBlocks )
814 for ( unsigned long i = 0; i < count; i++ ) {
815 (*outputBlocks)[i] = blocks[i];
816 if (MatchExactly(blocks[i].fDataType, kAliHLTAnyDataType)) {
817 (*outputBlocks)[i].fDataType=GetOutputDataType();
818 /* data type was set to the output data type by the PubSub AliRoot
819 Wrapper component, if data type of the block was ********:****.
820 Now handled by the component base class in order to have same
821 behavior when running embedded in AliRoot
822 memset((*outputBlocks)[i].fDataType.fID, '*', kAliHLTComponentDataTypefIDsize);
823 memset((*outputBlocks)[i].fDataType.fOrigin, '*', kAliHLTComponentDataTypefOriginSize);
832 int AliHLTComponent::GetEventDoneData( unsigned long size, AliHLTComponentEventDoneData** edd ) const
834 // see header file for function documentation
835 if (fEnvironment.fGetEventDoneDataFunc)
836 return (*fEnvironment.fGetEventDoneDataFunc)(fEnvironment.fParam, fCurrentEvent, size, edd );
840 int AliHLTComponent::ReserveEventDoneData( unsigned long size )
842 // see header file for function documentation
845 unsigned long capacity=fEventDoneDataSize;
846 if (fEventDoneData) capacity-=sizeof(AliHLTComponentEventDoneData)+fEventDoneData->fDataSize;
848 unsigned long newSize=sizeof(AliHLTComponentEventDoneData)+size+(fEventDoneDataSize-capacity);
849 AliHLTComponentEventDoneData* newEDD = reinterpret_cast<AliHLTComponentEventDoneData*>( new AliHLTUInt8_t[newSize] );
852 newEDD->fStructSize = sizeof(AliHLTComponentEventDoneData);
853 newEDD->fDataSize = 0;
854 newEDD->fData = reinterpret_cast<AliHLTUInt8_t*>(newEDD)+newEDD->fStructSize;
855 if (fEventDoneData) {
856 memcpy( newEDD->fData, fEventDoneData->fData, fEventDoneData->fDataSize );
857 newEDD->fDataSize = fEventDoneData->fDataSize;
858 delete [] reinterpret_cast<AliHLTUInt8_t*>( fEventDoneData );
860 fEventDoneData = newEDD;
861 fEventDoneDataSize = newSize;
867 int AliHLTComponent::PushEventDoneData( AliHLTUInt32_t eddDataWord )
869 // see header file for function documentation
872 if (fEventDoneData->fDataSize+sizeof(AliHLTUInt32_t)>fEventDoneDataSize)
874 *reinterpret_cast<AliHLTUInt32_t*>((reinterpret_cast<AliHLTUInt8_t*>(fEventDoneData->fData)+fEventDoneData->fDataSize)) = eddDataWord;
875 fEventDoneData->fDataSize += sizeof(AliHLTUInt32_t);
879 void AliHLTComponent::ReleaseEventDoneData()
881 // see header file for function documentation
883 delete [] reinterpret_cast<AliHLTUInt8_t*>( fEventDoneData );
884 fEventDoneData = NULL;
885 fEventDoneDataSize = 0;
889 int AliHLTComponent::FindMatchingDataTypes(AliHLTComponent* pConsumer, AliHLTComponentDataTypeList* tgtList)
891 // see header file for function documentation
894 AliHLTComponentDataTypeList itypes;
895 AliHLTComponentDataTypeList otypes;
896 otypes.push_back(GetOutputDataType());
897 if (MatchExactly(otypes[0],kAliHLTMultipleDataType)) {
900 if ((count=GetOutputDataTypes(otypes))>0) {
901 } else if (GetComponentType()!=kSink) {
902 HLTWarning("component %s indicates multiple output data types but GetOutputDataTypes returns %d", GetComponentID(), count);
905 pConsumer->GetInputDataTypes(itypes);
906 AliHLTComponentDataTypeList::iterator otype=otypes.begin();
907 for (;otype!=otypes.end();otype++) {
908 //PrintDataTypeContent((*otype), "publisher \'%s\'");
909 if ((*otype)==(kAliHLTAnyDataType|kAliHLTDataOriginPrivate)) {
910 if (tgtList) tgtList->push_back(*otype);
915 AliHLTComponentDataTypeList::iterator itype=itypes.begin();
916 for ( ; itype!=itypes.end() && (*itype)!=(*otype) ; itype++) {/* empty body */};
917 //if (itype!=itypes.end()) PrintDataTypeContent(*itype, "consumer \'%s\'");
918 if (itype!=itypes.end()) {
919 if (tgtList) tgtList->push_back(*otype);
929 void AliHLTComponent::PrintDataTypeContent(AliHLTComponentDataType& dt, const char* format)
931 // see header file for function documentation
932 const char* fmt="\'%s\'";
933 if (format) fmt=format;
934 AliHLTLogging::Message(NULL, kHLTLogNone, NULL , NULL, Form(fmt, (DataType2Text(dt)).c_str()));
935 AliHLTLogging::Message(NULL, kHLTLogNone, NULL , NULL,
936 Form("%x %x %x %x %x %x %x %x : %x %x %x %x",
951 void AliHLTComponent::FillBlockData( AliHLTComponentBlockData& blockData )
953 // see header file for function documentation
954 blockData.fStructSize = sizeof(blockData);
955 FillShmData( blockData.fShmKey );
956 blockData.fOffset = ~(AliHLTUInt32_t)0;
957 blockData.fPtr = NULL;
959 FillDataType( blockData.fDataType );
960 blockData.fSpecification = kAliHLTVoidDataSpec;
963 void AliHLTComponent::FillShmData( AliHLTComponentShmData& shmData )
965 // see header file for function documentation
966 shmData.fStructSize = sizeof(shmData);
967 shmData.fShmType = gkAliHLTComponentInvalidShmType;
968 shmData.fShmID = gkAliHLTComponentInvalidShmID;
971 void AliHLTComponent::FillDataType( AliHLTComponentDataType& dataType )
973 // see header file for function documentation
974 dataType=kAliHLTAnyDataType;
977 void AliHLTComponent::CopyDataType(AliHLTComponentDataType& tgtdt, const AliHLTComponentDataType& srcdt)
979 // see header file for function documentation
980 memcpy(&tgtdt.fID[0], &srcdt.fID[0], kAliHLTComponentDataTypefIDsize);
981 memcpy(&tgtdt.fOrigin[0], &srcdt.fOrigin[0], kAliHLTComponentDataTypefOriginSize);
984 void AliHLTComponent::SetDataType(AliHLTComponentDataType& tgtdt, const char* id, const char* origin)
986 // see header file for function documentation
987 tgtdt.fStructSize=sizeof(AliHLTComponentDataType);
989 memset(&tgtdt.fID[0], 0, kAliHLTComponentDataTypefIDsize);
990 strncpy(&tgtdt.fID[0], id, strlen(id)<(size_t)kAliHLTComponentDataTypefIDsize?strlen(id):kAliHLTComponentDataTypefIDsize);
993 memset(&tgtdt.fOrigin[0], 0, kAliHLTComponentDataTypefOriginSize);
994 strncpy(&tgtdt.fOrigin[0], origin, strlen(origin)<(size_t)kAliHLTComponentDataTypefOriginSize?strlen(origin):kAliHLTComponentDataTypefOriginSize);
998 void AliHLTComponent::SetDataType(AliHLTComponentDataType& dt, AliHLTUInt64_t id, AliHLTUInt32_t origin)
1000 // see header file for function documentation
1001 dt.fStructSize=sizeof(AliHLTComponentDataType);
1002 assert(kAliHLTComponentDataTypefIDsize==sizeof(id));
1003 assert(kAliHLTComponentDataTypefOriginSize==sizeof(origin));
1004 memcpy(&dt.fID, &id, kAliHLTComponentDataTypefIDsize);
1005 memcpy(&dt.fOrigin, &origin, kAliHLTComponentDataTypefOriginSize);
1008 void AliHLTComponent::FillEventData(AliHLTComponentEventData& evtData)
1010 // see header file for function documentation
1011 memset(&evtData, 0, sizeof(AliHLTComponentEventData));
1012 evtData.fStructSize=sizeof(AliHLTComponentEventData);
1013 evtData.fEventID=kAliHLTVoidEventID;
1016 void AliHLTComponent::PrintComponentDataTypeInfo(const AliHLTComponentDataType& dt)
1018 // see header file for function documentation
1020 msg.Form("AliHLTComponentDataType(%d): ID=\"", dt.fStructSize);
1021 for ( int i = 0; i < kAliHLTComponentDataTypefIDsize; i++ ) {
1022 if (dt.fID[i]!=0) msg+=dt.fID[i];
1025 msg+="\" Origin=\"";
1026 for ( int i = 0; i < kAliHLTComponentDataTypefOriginSize; i++ ) {
1027 if (dt.fOrigin[i]!=0) msg+=dt.fOrigin[i];
1031 AliHLTLogging::Message(NULL, kHLTLogNone, NULL , NULL, msg.Data());
1034 int AliHLTComponent::GetEventCount() const
1036 // see header file for function documentation
1040 int AliHLTComponent::IncrementEventCounter()
1042 // see header file for function documentation
1043 if (fEventCount>=0) fEventCount++;
1047 int AliHLTComponent::GetNumberOfInputBlocks() const
1049 // see header file for function documentation
1050 if (fpInputBlocks!=NULL) {
1051 return fCurrentEventData.fBlockCnt;
1056 AliHLTEventID_t AliHLTComponent::GetEventId() const
1058 // see header file for function documentation
1059 if (fpInputBlocks!=NULL) {
1060 return fCurrentEventData.fEventID;
1065 const TObject* AliHLTComponent::GetFirstInputObject(const AliHLTComponentDataType& dt,
1066 const char* classname,
1069 // see header file for function documentation
1070 ALIHLTCOMPONENT_BASE_STOPWATCH();
1072 if (classname) fClassName=classname;
1073 else fClassName.clear();
1074 int idx=FindInputBlock(fSearchDataType, 0, 1);
1077 HLTDebug("found block %d when searching for data type %s", idx, DataType2Text(dt).c_str());
1078 if ((pObj=GetInputObject(idx, fClassName.c_str(), bForce))!=NULL) {
1079 fCurrentInputBlock=idx;
1086 const TObject* AliHLTComponent::GetFirstInputObject(const char* dtID,
1087 const char* dtOrigin,
1088 const char* classname,
1091 // see header file for function documentation
1092 ALIHLTCOMPONENT_BASE_STOPWATCH();
1093 AliHLTComponentDataType dt;
1094 SetDataType(dt, dtID, dtOrigin);
1095 return GetFirstInputObject(dt, classname, bForce);
1098 const TObject* AliHLTComponent::GetNextInputObject(int bForce)
1100 // see header file for function documentation
1101 ALIHLTCOMPONENT_BASE_STOPWATCH();
1102 int idx=FindInputBlock(fSearchDataType, fCurrentInputBlock+1, 1);
1103 //HLTDebug("found block %d when searching for data type %s", idx, DataType2Text(fSearchDataType).c_str());
1106 if ((pObj=GetInputObject(idx, fClassName.c_str(), bForce))!=NULL) {
1107 fCurrentInputBlock=idx;
1113 int AliHLTComponent::FindInputBlock(const AliHLTComponentDataType& dt, int startIdx, int bObject) const
1115 // see header file for function documentation
1116 int iResult=-ENOENT;
1117 if (fpInputBlocks!=NULL) {
1118 int idx=startIdx<0?0:startIdx;
1119 for ( ; (UInt_t)idx<fCurrentEventData.fBlockCnt && iResult==-ENOENT; idx++) {
1120 if (dt!=fpInputBlocks[idx].fDataType) continue;
1123 if (fpInputBlocks[idx].fPtr==NULL) continue;
1124 AliHLTUInt32_t firstWord=*((AliHLTUInt32_t*)fpInputBlocks[idx].fPtr);
1125 if (firstWord!=fpInputBlocks[idx].fSize-sizeof(AliHLTUInt32_t)) continue;
1133 TObject* AliHLTComponent::CreateInputObject(int idx, int bForce)
1135 // see header file for function documentation
1137 if (fpInputBlocks!=NULL) {
1138 if ((UInt_t)idx<fCurrentEventData.fBlockCnt) {
1139 if (fpInputBlocks[idx].fPtr) {
1140 AliHLTUInt32_t firstWord=*((AliHLTUInt32_t*)fpInputBlocks[idx].fPtr);
1141 if (firstWord==fpInputBlocks[idx].fSize-sizeof(AliHLTUInt32_t)) {
1142 HLTDebug("create object from block %d size %d", idx, fpInputBlocks[idx].fSize);
1143 AliHLTMessage msg(fpInputBlocks[idx].fPtr, fpInputBlocks[idx].fSize);
1144 TClass* objclass=msg.GetClass();
1145 pObj=msg.ReadObject(objclass);
1146 if (pObj && objclass) {
1147 HLTDebug("object %p type %s created", pObj, objclass->GetName());
1151 } else if (bForce!=0) {
1152 HLTError("size mismatch: block size %d, indicated %d", fpInputBlocks[idx].fSize, firstWord+sizeof(AliHLTUInt32_t));
1155 HLTFatal("block descriptor empty");
1158 HLTError("index %d out of range %d", idx, fCurrentEventData.fBlockCnt);
1161 HLTError("no input blocks available");
1167 TObject* AliHLTComponent::GetInputObject(int idx, const char* /*classname*/, int bForce)
1169 // see header file for function documentation
1170 if (fpInputObjects==NULL) {
1171 fpInputObjects=new TObjArray(fCurrentEventData.fBlockCnt);
1174 if (fpInputObjects) {
1175 pObj=fpInputObjects->At(idx);
1177 pObj=CreateInputObject(idx, bForce);
1179 fpInputObjects->AddAt(pObj, idx);
1183 HLTFatal("memory allocation failed: TObjArray of size %d", fCurrentEventData.fBlockCnt);
1188 int AliHLTComponent::CleanupInputObjects()
1190 // see header file for function documentation
1191 if (!fpInputObjects) return 0;
1192 TObjArray* array=fpInputObjects;
1193 fpInputObjects=NULL;
1194 for (int i=0; i<array->GetEntriesFast(); i++) {
1195 TObject* pObj=array->At(i);
1196 // grrr, garbage collection strikes back: When read via AliHLTMessage
1197 // (CreateInputObject), and written to a TFile afterwards, the
1198 // TFile::Close calls ROOOT's garbage collection. No clue why the
1199 // object ended up in the key list and needs to be deleted
1201 // Matthias 09.11.2008 follow up
1202 // This approach doesn't actually work in all cases: the object table
1203 // can be switched off globally, the flag needs to be checked here as
1204 // well in order to avoid memory leaks.
1205 // This means we have to find another solution for the problem if it
1208 (!TObject::GetObjectStat() || gObjectTable->PtrIsValid(pObj))) {
1216 AliHLTComponentDataType AliHLTComponent::GetDataType(const TObject* pObject)
1218 // see header file for function documentation
1219 ALIHLTCOMPONENT_BASE_STOPWATCH();
1220 AliHLTComponentDataType dt=kAliHLTVoidDataType;
1221 int idx=fCurrentInputBlock;
1223 if (fpInputObjects==NULL || (idx=fpInputObjects->IndexOf(pObject))>=0) {
1225 HLTError("unknown object %p", pObject);
1229 if ((UInt_t)idx<fCurrentEventData.fBlockCnt) {
1230 dt=fpInputBlocks[idx].fDataType;
1232 HLTFatal("severe internal error, index out of range");
1238 AliHLTUInt32_t AliHLTComponent::GetSpecification(const TObject* pObject)
1240 // see header file for function documentation
1241 ALIHLTCOMPONENT_BASE_STOPWATCH();
1242 AliHLTUInt32_t iSpec=kAliHLTVoidDataSpec;
1243 int idx=fCurrentInputBlock;
1245 if (fpInputObjects==NULL || (idx=fpInputObjects->IndexOf(pObject))>=0) {
1247 HLTError("unknown object %p", pObject);
1251 if ((UInt_t)idx<fCurrentEventData.fBlockCnt) {
1252 iSpec=fpInputBlocks[idx].fSpecification;
1254 HLTFatal("severe internal error, index out of range");
1260 int AliHLTComponent::Forward(const TObject* pObject)
1262 // see header file for function documentation
1264 int idx=fCurrentInputBlock;
1266 if (fpInputObjects==NULL || (idx=fpInputObjects->IndexOf(pObject))>=0) {
1268 HLTError("unknown object %p", pObject);
1273 fOutputBlocks.push_back(fpInputBlocks[idx]);
1278 int AliHLTComponent::Forward(const AliHLTComponentBlockData* pBlock)
1280 // see header file for function documentation
1282 int idx=fCurrentInputBlock;
1284 if ((idx=FindInputBlock(pBlock))>=0) {
1286 HLTError("unknown Block %p", pBlock);
1291 // check for fpInputBlocks pointer done in FindInputBlock
1292 fOutputBlocks.push_back(fpInputBlocks[idx]);
1297 const AliHLTComponentBlockData* AliHLTComponent::GetFirstInputBlock(const AliHLTComponentDataType& dt)
1299 // see header file for function documentation
1300 ALIHLTCOMPONENT_BASE_STOPWATCH();
1303 int idx=FindInputBlock(fSearchDataType, 0);
1304 const AliHLTComponentBlockData* pBlock=NULL;
1306 // check for fpInputBlocks pointer done in FindInputBlock
1307 pBlock=&fpInputBlocks[idx];
1308 fCurrentInputBlock=idx;
1313 const AliHLTComponentBlockData* AliHLTComponent::GetFirstInputBlock(const char* dtID,
1314 const char* dtOrigin)
1316 // see header file for function documentation
1317 ALIHLTCOMPONENT_BASE_STOPWATCH();
1318 AliHLTComponentDataType dt;
1319 SetDataType(dt, dtID, dtOrigin);
1320 return GetFirstInputBlock(dt);
1323 const AliHLTComponentBlockData* AliHLTComponent::GetInputBlock(int index) const
1325 // see header file for function documentation
1326 ALIHLTCOMPONENT_BASE_STOPWATCH();
1327 assert( 0 <= index and index < (int)fCurrentEventData.fBlockCnt );
1328 return &fpInputBlocks[index];
1331 const AliHLTComponentBlockData* AliHLTComponent::GetNextInputBlock()
1333 // see header file for function documentation
1334 ALIHLTCOMPONENT_BASE_STOPWATCH();
1335 int idx=FindInputBlock(fSearchDataType, fCurrentInputBlock+1);
1336 const AliHLTComponentBlockData* pBlock=NULL;
1338 // check for fpInputBlocks pointer done in FindInputBlock
1339 pBlock=&fpInputBlocks[idx];
1340 fCurrentInputBlock=idx;
1345 int AliHLTComponent::FindInputBlock(const AliHLTComponentBlockData* pBlock) const
1347 // see header file for function documentation
1348 int iResult=-ENOENT;
1349 if (fpInputBlocks!=NULL) {
1351 if (pBlock>=fpInputBlocks && pBlock<fpInputBlocks+fCurrentEventData.fBlockCnt) {
1352 iResult=(int)(pBlock-fpInputBlocks);
1361 AliHLTUInt32_t AliHLTComponent::GetSpecification(const AliHLTComponentBlockData* pBlock)
1363 // see header file for function documentation
1364 ALIHLTCOMPONENT_BASE_STOPWATCH();
1365 AliHLTUInt32_t iSpec=kAliHLTVoidDataSpec;
1366 int idx=fCurrentInputBlock;
1368 if (fpInputObjects==NULL || (idx=FindInputBlock(pBlock))>=0) {
1370 HLTError("unknown Block %p", pBlock);
1374 // check for fpInputBlocks pointer done in FindInputBlock
1375 iSpec=fpInputBlocks[idx].fSpecification;
1380 int AliHLTComponent::PushBack(TObject* pObject, const AliHLTComponentDataType& dt, AliHLTUInt32_t spec,
1381 void* pHeader, int headerSize)
1383 // see header file for function documentation
1384 ALIHLTCOMPONENT_BASE_STOPWATCH();
1387 if (fPushbackPeriod>0) {
1388 // suppress the output
1390 if (fLastPushBackTime<0 || (int)time.Get()-fLastPushBackTime<fPushbackPeriod) return 0;
1393 AliHLTMessage msg(kMESS_OBJECT);
1394 msg.SetCompressionLevel(fCompressionLevel);
1395 msg.WriteObject(pObject);
1396 Int_t iMsgLength=msg.Length();
1398 // Matthias Sep 2008
1399 // NOTE: AliHLTMessage does implement it's own SetLength method
1400 // which is not architecture independent. The original SetLength
1401 // stores the size always in network byte order.
1402 // I'm trying to remember the rational for that, might be that
1403 // it was just some lack of knowledge. Want to change this, but
1404 // has to be done carefullt to be backward compatible.
1405 msg.SetLength(); // sets the length to the first (reserved) word
1407 // does nothing if the level is 0
1410 char *mbuf = msg.Buffer();
1411 if (msg.CompBuffer()) {
1412 msg.SetLength(); // set once more to have to byte order
1413 mbuf = msg.CompBuffer();
1414 iMsgLength = msg.CompLength();
1417 iResult=InsertOutputBlock(mbuf, iMsgLength, dt, spec, pHeader, headerSize);
1419 HLTDebug("object %s (%p) size %d compression %d inserted to output", pObject->ClassName(), pObject, iMsgLength, msg.GetCompressionLevel());
1421 fLastObjectSize=iMsgLength;
1423 HLTError("object serialization failed for object %p", pObject);
1432 int AliHLTComponent::PushBack(TObject* pObject, const char* dtID, const char* dtOrigin, AliHLTUInt32_t spec,
1433 void* pHeader, int headerSize)
1435 // see header file for function documentation
1436 ALIHLTCOMPONENT_BASE_STOPWATCH();
1437 AliHLTComponentDataType dt;
1438 SetDataType(dt, dtID, dtOrigin);
1439 return PushBack(pObject, dt, spec, pHeader, headerSize);
1442 int AliHLTComponent::PushBack(const void* pBuffer, int iSize, const AliHLTComponentDataType& dt, AliHLTUInt32_t spec,
1443 const void* pHeader, int headerSize)
1445 // see header file for function documentation
1446 ALIHLTCOMPONENT_BASE_STOPWATCH();
1447 if (fPushbackPeriod>0) {
1448 // suppress the output
1450 if (fLastPushBackTime<0 || (int)time.Get()-fLastPushBackTime<fPushbackPeriod) return 0;
1453 return InsertOutputBlock(pBuffer, iSize, dt, spec, pHeader, headerSize);
1456 int AliHLTComponent::PushBack(const void* pBuffer, int iSize, const char* dtID, const char* dtOrigin, AliHLTUInt32_t spec,
1457 const void* pHeader, int headerSize)
1459 // see header file for function documentation
1460 ALIHLTCOMPONENT_BASE_STOPWATCH();
1461 AliHLTComponentDataType dt;
1462 SetDataType(dt, dtID, dtOrigin);
1463 return PushBack(pBuffer, iSize, dt, spec, pHeader, headerSize);
1466 int AliHLTComponent::InsertOutputBlock(const void* pBuffer, int iBufferSize, const AliHLTComponentDataType& dt, AliHLTUInt32_t spec,
1467 const void* pHeader, int iHeaderSize)
1469 // see header file for function documentation
1471 int iBlkSize = iBufferSize + iHeaderSize;
1473 if ((pBuffer!=NULL && iBufferSize>0) || (pHeader!=NULL && iHeaderSize>0)) {
1474 if (fpOutputBuffer && iBlkSize<=(int)(fOutputBufferSize-fOutputBufferFilled)) {
1475 AliHLTUInt8_t* pTgt=fpOutputBuffer+fOutputBufferFilled;
1477 // copy header if provided but skip if the header is the target location
1478 // in that case it has already been copied
1479 if (pHeader!=NULL && pHeader!=pTgt) {
1480 memcpy(pTgt, pHeader, iHeaderSize);
1483 pTgt += (AliHLTUInt8_t) iHeaderSize;
1485 // copy buffer if provided but skip if buffer is the target location
1486 // in that case it has already been copied
1487 if (pBuffer!=NULL && pBuffer!=pTgt) {
1488 memcpy(pTgt, pBuffer, iBufferSize);
1490 //AliHLTUInt32_t firstWord=*((AliHLTUInt32_t*)pBuffer);
1491 //HLTDebug("copy %d bytes from %p to output buffer %p, first word %#x", iBufferSize, pBuffer, pTgt, firstWord);
1493 //HLTDebug("buffer inserted to output: size %d data type %s spec %#x", iBlkSize, DataType2Text(dt).c_str(), spec);
1495 if (fpOutputBuffer) {
1496 HLTError("too little space in output buffer: %d of %d, required %d", fOutputBufferSize-fOutputBufferFilled, fOutputBufferSize, iBlkSize);
1498 HLTError("output buffer not available");
1504 AliHLTComponentBlockData bd;
1505 FillBlockData( bd );
1506 bd.fOffset = fOutputBufferFilled;
1507 bd.fSize = iBlkSize;
1509 bd.fSpecification = spec;
1510 fOutputBlocks.push_back( bd );
1511 fOutputBufferFilled+=bd.fSize;
1517 int AliHLTComponent::EstimateObjectSize(TObject* pObject) const
1519 // see header file for function documentation
1520 if (!pObject) return 0;
1522 AliHLTMessage msg(kMESS_OBJECT);
1523 msg.WriteObject(pObject);
1524 return msg.Length();
1527 AliHLTMemoryFile* AliHLTComponent::CreateMemoryFile(int capacity, const char* dtID,
1528 const char* dtOrigin,
1529 AliHLTUInt32_t spec)
1531 // see header file for function documentation
1532 ALIHLTCOMPONENT_BASE_STOPWATCH();
1533 AliHLTComponentDataType dt;
1534 SetDataType(dt, dtID, dtOrigin);
1535 return CreateMemoryFile(capacity, dt, spec);
1538 AliHLTMemoryFile* AliHLTComponent::CreateMemoryFile(int capacity,
1539 const AliHLTComponentDataType& dt,
1540 AliHLTUInt32_t spec)
1542 // see header file for function documentation
1543 ALIHLTCOMPONENT_BASE_STOPWATCH();
1544 AliHLTMemoryFile* pFile=NULL;
1545 if (capacity>=0 && static_cast<unsigned int>(capacity)<=fOutputBufferSize-fOutputBufferFilled){
1546 AliHLTUInt8_t* pTgt=fpOutputBuffer+fOutputBufferFilled;
1547 pFile=new AliHLTMemoryFile((char*)pTgt, capacity);
1549 unsigned int nofBlocks=fOutputBlocks.size();
1550 if (nofBlocks+1>fMemFiles.size()) {
1551 fMemFiles.resize(nofBlocks+1, NULL);
1553 if (nofBlocks<fMemFiles.size()) {
1554 fMemFiles[nofBlocks]=pFile;
1555 AliHLTComponentBlockData bd;
1556 FillBlockData( bd );
1557 bd.fOffset = fOutputBufferFilled;
1558 bd.fSize = capacity;
1560 bd.fSpecification = spec;
1561 fOutputBufferFilled+=bd.fSize;
1562 fOutputBlocks.push_back( bd );
1564 HLTError("can not allocate/grow object array");
1565 pFile->CloseMemoryFile(0);
1571 HLTError("can not create memory file of size %d (%d available)", capacity, fOutputBufferSize-fOutputBufferFilled);
1576 AliHLTMemoryFile* AliHLTComponent::CreateMemoryFile(const char* dtID,
1577 const char* dtOrigin,
1578 AliHLTUInt32_t spec,
1581 // see header file for function documentation
1582 ALIHLTCOMPONENT_BASE_STOPWATCH();
1583 AliHLTComponentDataType dt;
1584 SetDataType(dt, dtID, dtOrigin);
1585 int size=fOutputBufferSize-fOutputBufferFilled;
1586 if (capacity<0 || capacity>1.0) {
1587 HLTError("invalid parameter: capacity %f", capacity);
1590 size=(int)(size*capacity);
1591 return CreateMemoryFile(size, dt, spec);
1594 AliHLTMemoryFile* AliHLTComponent::CreateMemoryFile(const AliHLTComponentDataType& dt,
1595 AliHLTUInt32_t spec,
1598 // see header file for function documentation
1599 ALIHLTCOMPONENT_BASE_STOPWATCH();
1600 int size=fOutputBufferSize-fOutputBufferFilled;
1601 if (capacity<0 || capacity>1.0) {
1602 HLTError("invalid parameter: capacity %f", capacity);
1605 size=(int)(size*capacity);
1606 return CreateMemoryFile(size, dt, spec);
1609 int AliHLTComponent::Write(AliHLTMemoryFile* pFile, const TObject* pObject,
1610 const char* key, int option)
1612 // see header file for function documentation
1614 if (pFile && pObject) {
1616 iResult=pObject->Write(key, option);
1620 iResult=-pFile->GetErrno();
1621 if (iResult==-ENOSPC) {
1622 HLTError("error writing memory file, buffer too small");
1631 int AliHLTComponent::CloseMemoryFile(AliHLTMemoryFile* pFile)
1633 // see header file for function documentation
1636 AliHLTMemoryFilePList::iterator element=fMemFiles.begin();
1638 while (element!=fMemFiles.end() && iResult>=0) {
1639 if (*element && *element==pFile) {
1640 iResult=pFile->CloseMemoryFile();
1642 // sync memory files and descriptors
1644 fOutputBlocks[i].fSize=(*element)->GetSize()+(*element)->GetHeaderSize();
1652 HLTError("can not find memory file %p", pFile);
1660 int AliHLTComponent::CreateEventDoneData(AliHLTComponentEventDoneData edd)
1662 // see header file for function documentation
1665 AliHLTComponentEventDoneData* newEDD = NULL;
1667 unsigned long newSize=edd.fDataSize;
1669 newSize += fEventDoneData->fDataSize;
1671 if (newSize>fEventDoneDataSize) {
1672 newEDD = reinterpret_cast<AliHLTComponentEventDoneData*>( new AliHLTUInt8_t[ sizeof(AliHLTComponentEventDoneData)+newSize ] );
1675 newEDD->fStructSize = sizeof(AliHLTComponentEventDoneData);
1676 newEDD->fDataSize = newSize;
1677 newEDD->fData = reinterpret_cast<AliHLTUInt8_t*>(newEDD)+newEDD->fStructSize;
1678 unsigned long long offset = 0;
1679 if (fEventDoneData) {
1680 memcpy( newEDD->fData, fEventDoneData->fData, fEventDoneData->fDataSize );
1681 offset += fEventDoneData->fDataSize;
1683 memcpy( reinterpret_cast<AliHLTUInt8_t*>(newEDD->fData)+offset, edd.fData, edd.fDataSize );
1685 delete [] reinterpret_cast<AliHLTUInt8_t*>( fEventDoneData );
1686 fEventDoneData = newEDD;
1687 fEventDoneDataSize = newSize;
1690 memcpy( reinterpret_cast<AliHLTUInt8_t*>(fEventDoneData->fData)+fEventDoneData->fDataSize, edd.fData, edd.fDataSize );
1691 fEventDoneData->fDataSize += edd.fDataSize;
1696 int AliHLTComponent::ProcessEvent( const AliHLTComponentEventData& evtData,
1697 const AliHLTComponentBlockData* blocks,
1698 AliHLTComponentTriggerData& trigData,
1699 AliHLTUInt8_t* outputPtr,
1700 AliHLTUInt32_t& size,
1701 AliHLTUInt32_t& outputBlockCnt,
1702 AliHLTComponentBlockData*& outputBlocks,
1703 AliHLTComponentEventDoneData*& edd )
1705 // see header file for function documentation
1706 HLTLogKeyword(fChainId.c_str());
1707 ALIHLTCOMPONENT_BASE_STOPWATCH();
1709 fCurrentEvent=evtData.fEventID;
1710 fCurrentEventData=evtData;
1711 fpInputBlocks=blocks;
1712 fCurrentInputBlock=-1;
1713 fSearchDataType=kAliHLTAnyDataType;
1714 fpOutputBuffer=outputPtr;
1715 fOutputBufferSize=size;
1716 fOutputBufferFilled=0;
1717 fOutputBlocks.clear();
1721 AliHLTComponentBlockDataList forwardedBlocks;
1723 // optional component statistics
1724 AliHLTComponentStatisticsList compStats;
1725 bool bAddComponentTableEntry=false;
1726 vector<AliHLTUInt32_t> parentComponentTables;
1727 #if defined(HLT_COMPONENT_STATISTICS)
1728 if ((fFlags&kDisableComponentStat)==0) {
1729 AliHLTComponentStatistics outputStat;
1730 memset(&outputStat, 0, sizeof(AliHLTComponentStatistics));
1731 outputStat.fStructSize=sizeof(AliHLTComponentStatistics);
1732 outputStat.fId=fChainIdCrc;
1734 fpBenchmark->Stop();
1735 outputStat.fComponentCycleTime=(AliHLTUInt32_t)(fpBenchmark->RealTime()*ALIHLTCOMPONENT_STATTIME_SCALER);
1736 fpBenchmark->Reset();
1737 fpBenchmark->Start();
1739 compStats.push_back(outputStat);
1741 #endif // HLT_COMPONENT_STATISTICS
1743 // data processing is skipped
1744 // - if there are only steering events in the block list.
1745 // For the sake of data source components data processing
1746 // is not skipped if there is no block list at all or if it
1747 // just contains the eventType block
1748 // - always skipped if the event is of type
1749 // - gkAliEventTypeConfiguration
1750 // - gkAliEventTypeReadPreprocessor
1751 const unsigned int skipModeDefault=0x1;
1752 const unsigned int skipModeForce=0x2;
1753 unsigned int bSkipDataProcessing=skipModeDefault;
1755 // find special events
1756 if (fpInputBlocks && evtData.fBlockCnt>0) {
1757 // first look for all special events and execute in the appropriate
1758 // sequence afterwords
1759 int indexComConfEvent=-1;
1760 int indexUpdtDCSEvent=-1;
1761 int indexSOREvent=-1;
1762 int indexEOREvent=-1;
1763 int indexECSParamBlock=-1;
1764 for (unsigned int i=0; i<evtData.fBlockCnt && iResult>=0; i++) {
1765 if (fpInputBlocks[i].fDataType==kAliHLTDataTypeSOR) {
1767 // the AliHLTCalibrationProcessor relies on the SOR and EOR events
1768 bSkipDataProcessing&=~skipModeDefault;
1769 } else if (fpInputBlocks[i].fDataType==kAliHLTDataTypeRunType) {
1771 // handling is not clear yet
1772 if (fpInputBlocks[i].fPtr) {
1773 HLTDebug("got run type \"%s\"\n", fpInputBlocks[i].fPtr);
1775 } else if (fpInputBlocks[i].fDataType==kAliHLTDataTypeEOR) {
1777 // the calibration processor relies on the SOR and EOR events
1778 bSkipDataProcessing&=~skipModeDefault;
1779 } else if (fpInputBlocks[i].fDataType==kAliHLTDataTypeDDL) {
1781 // this event is most likely deprecated
1782 } else if (fpInputBlocks[i].fDataType==kAliHLTDataTypeComConf) {
1783 indexComConfEvent=i;
1784 } else if (fpInputBlocks[i].fDataType==kAliHLTDataTypeUpdtDCS) {
1785 indexUpdtDCSEvent=i;
1786 } else if (fpInputBlocks[i].fDataType==kAliHLTDataTypeEvent) {
1787 fEventType=fpInputBlocks[i].fSpecification;
1789 // skip always in case of gkAliEventTypeConfiguration
1790 if (fpInputBlocks[i].fSpecification==gkAliEventTypeConfiguration) bSkipDataProcessing|=skipModeForce;
1792 // skip always in case of gkAliEventTypeReadPreprocessor
1793 if (fpInputBlocks[i].fSpecification==gkAliEventTypeReadPreprocessor) bSkipDataProcessing|=skipModeForce;
1795 // never skip if the event type block is the only block
1796 if (evtData.fBlockCnt==1) bSkipDataProcessing&=~skipModeDefault;
1798 } else if (fpInputBlocks[i].fDataType==kAliHLTDataTypeComponentStatistics) {
1799 if (compStats.size()>0) {
1800 AliHLTUInt8_t* pData=reinterpret_cast<AliHLTUInt8_t*>(fpInputBlocks[i].fPtr);
1801 for (AliHLTUInt32_t offset=0;
1802 offset+sizeof(AliHLTComponentStatistics)<=fpInputBlocks[i].fSize;
1803 offset+=sizeof(AliHLTComponentStatistics)) {
1804 AliHLTComponentStatistics* pStat=reinterpret_cast<AliHLTComponentStatistics*>(pData+offset);
1805 if (pStat && compStats[0].fLevel<=pStat->fLevel) {
1806 compStats[0].fLevel=pStat->fLevel+1;
1808 compStats.push_back(*pStat);
1811 } else if (fpInputBlocks[i].fDataType==kAliHLTDataTypeComponentTable) {
1812 forwardedBlocks.push_back(fpInputBlocks[i]);
1813 parentComponentTables.push_back(fpInputBlocks[i].fSpecification);
1814 } else if (fpInputBlocks[i].fDataType==kAliHLTDataTypeECSParam) {
1815 indexECSParamBlock=i;
1817 // the processing function is called if there is at least one
1818 // non-steering data block. Steering blocks are not filtered out
1819 // for sake of performance
1820 bSkipDataProcessing&=~skipModeDefault;
1821 if (compStats.size()>0) {
1822 compStats[0].fInputBlockCount++;
1823 compStats[0].fTotalInputSize+=fpInputBlocks[i].fSize;
1828 if (indexSOREvent>=0) {
1830 bAddComponentTableEntry=true;
1831 if (fpRunDesc==NULL) {
1832 fpRunDesc=new AliHLTRunDesc;
1833 if (fpRunDesc) *fpRunDesc=kAliHLTVoidRunDesc;
1836 AliHLTRunDesc rundesc;
1837 if ((iResult=CopyStruct(&rundesc, sizeof(AliHLTRunDesc), indexSOREvent, "AliHLTRunDesc", "SOR"))>0) {
1838 if (fpRunDesc->fRunNo==kAliHLTVoidRunNo) {
1840 HLTDebug("set run decriptor, run no %d", fpRunDesc->fRunNo);
1841 SetCDBRunNo(fpRunDesc->fRunNo);
1842 } else if (fpRunDesc->fRunNo!=rundesc.fRunNo) {
1843 HLTWarning("already set run properties run no %d, ignoring SOR with run no %d", fpRunDesc->fRunNo, rundesc.fRunNo);
1850 if (indexECSParamBlock>=0) {
1851 if (fpInputBlocks[indexECSParamBlock].fSize>0) {
1852 const char* param=reinterpret_cast<const char*>(fpInputBlocks[indexECSParamBlock].fPtr);
1853 TString paramString;
1854 if (param[fpInputBlocks[indexECSParamBlock].fSize-1]!=0) {
1855 HLTWarning("ECS parameter string not terminated");
1856 paramString.Insert(0, param, fpInputBlocks[indexECSParamBlock].fSize);
1861 ScanECSParam(paramString.Data());
1863 HLTWarning("empty ECS parameter received");
1866 // TODO: later on we might throw a warning here since the CTP trigger classes
1867 // should be mandatory
1870 if (indexEOREvent>=0) {
1871 fLastPushBackTime=0; // always send at EOR
1872 bAddComponentTableEntry=true;
1873 if (fpRunDesc!=NULL) {
1875 AliHLTRunDesc rundesc;
1876 if ((iResult=CopyStruct(&rundesc, sizeof(AliHLTRunDesc), indexEOREvent, "AliHLTRunDesc", "SOR"))>0) {
1877 if (fpRunDesc->fRunNo!=rundesc.fRunNo) {
1878 HLTWarning("run no mismatch: SOR %d, EOR %d", fpRunDesc->fRunNo, rundesc.fRunNo);
1880 HLTDebug("EOR run no %d", fpRunDesc->fRunNo);
1883 // we do not unload the fpRunDesc struct here in order to have the run information
1884 // available during the event processing
1885 // https://savannah.cern.ch/bugs/?39711
1886 // the info will be cleared in DeInit
1889 HLTWarning("did not receive SOR, ignoring EOR");
1892 if (indexComConfEvent>=0 || fEventType==gkAliEventTypeConfiguration) {
1894 if (indexComConfEvent>=0 && fpInputBlocks[indexComConfEvent].fPtr!=NULL && fpInputBlocks[indexComConfEvent].fSize>0) {
1895 cdbEntry.Append(reinterpret_cast<const char*>(fpInputBlocks[indexComConfEvent].fPtr), fpInputBlocks[indexComConfEvent].fSize);
1897 HLTDebug("received component configuration command: entry %s", cdbEntry.IsNull()?"none":cdbEntry.Data());
1898 int tmpResult=Reconfigure(cdbEntry[0]==0?NULL:cdbEntry.Data(), fChainId.c_str());
1900 HLTWarning("reconfiguration of component %p (%s) failed with error code %d", this, GetComponentID(), tmpResult);
1903 if (indexUpdtDCSEvent>=0 || fEventType==gkAliEventTypeReadPreprocessor) {
1905 if (fpInputBlocks[indexUpdtDCSEvent].fPtr!=NULL && fpInputBlocks[indexUpdtDCSEvent].fSize>0) {
1906 modules.Append(reinterpret_cast<const char*>(fpInputBlocks[indexUpdtDCSEvent].fPtr), fpInputBlocks[indexUpdtDCSEvent].fSize);
1908 HLTDebug("received preprocessor update command: detectors %s", modules.IsNull()?"ALL":modules.Data());
1909 int tmpResult=ReadPreprocessorValues(modules[0]==0?"ALL":modules.Data());
1911 HLTWarning("preprocessor update of component %p (%s) failed with error code %d", this, GetComponentID(), tmpResult);
1915 // processing function needs to be called if there are no input data
1916 // blocks in order to make data source components working.
1917 bSkipDataProcessing&=~skipModeDefault;
1920 // data processing is not skipped if the component explicitly asks
1921 // for the private blocks
1922 if ((fFlags&kRequireSteeringBlocks)!=0) bSkipDataProcessing=0;
1925 // set the active triggers for this event
1926 fpCTPData->SetTriggers(trigData);
1927 // increment CTP trigger counters if available
1928 if (IsDataEvent()) fpCTPData->Increment(trigData);
1931 AliHLTComponentBlockDataList blockData;
1932 if (iResult>=0 && !bSkipDataProcessing)
1933 { // dont delete, sets the scope for the stopwatch guard
1934 // do not use ALIHLTCOMPONENT_DA_STOPWATCH(); macro
1935 // in order to avoid 'shadowed variable' warning
1936 AliHLTStopwatchGuard swguard2(fpStopwatches!=NULL?reinterpret_cast<TStopwatch*>(fpStopwatches->At((int)kSWDA)):NULL);
1937 iResult=DoProcessing(evtData, blocks, trigData, outputPtr, size, blockData, edd);
1938 } // end of the scope of the stopwatch guard
1939 if (iResult>=0 && !bSkipDataProcessing) {
1940 if (fOutputBlocks.size()>0) {
1941 // High Level interface
1943 //HLTDebug("got %d block(s) via high level interface", fOutputBlocks.size());
1944 // sync memory files and descriptors
1945 AliHLTMemoryFilePList::iterator element=fMemFiles.begin();
1947 while (element!=fMemFiles.end() && iResult>=0) {
1949 if ((*element)->IsClosed()==0) {
1950 HLTWarning("memory file has not been closed, force flush");
1951 iResult=CloseMemoryFile(*element);
1958 // create the descriptor list
1959 if (blockData.size()>0) {
1960 HLTError("low level and high interface must not be mixed; use PushBack methods to insert data blocks");
1963 if (compStats.size()>0 && IsDataEvent()) {
1964 int offset=AddComponentStatistics(fOutputBlocks, fpOutputBuffer, fOutputBufferSize, fOutputBufferFilled, compStats);
1965 if (offset>0) fOutputBufferFilled+=offset;
1967 if (bAddComponentTableEntry) {
1968 int offset=AddComponentTableEntry(fOutputBlocks, fpOutputBuffer, fOutputBufferSize, fOutputBufferFilled, parentComponentTables);
1969 if (offset>0) size+=offset;
1971 if (forwardedBlocks.size()>0) {
1972 fOutputBlocks.insert(fOutputBlocks.end(), forwardedBlocks.begin(), forwardedBlocks.end());
1974 iResult=MakeOutputDataBlockList(fOutputBlocks, &outputBlockCnt, &outputBlocks);
1975 size=fOutputBufferFilled;
1979 // Low Level interface
1980 if (compStats.size()>0) {
1981 int offset=AddComponentStatistics(blockData, fpOutputBuffer, fOutputBufferSize, size, compStats);
1982 if (offset>0) size+=offset;
1984 if (bAddComponentTableEntry) {
1985 int offset=AddComponentTableEntry(blockData, fpOutputBuffer, fOutputBufferSize, size, parentComponentTables);
1986 if (offset>0) size+=offset;
1988 if (forwardedBlocks.size()>0) {
1989 blockData.insert(blockData.end(), forwardedBlocks.begin(), forwardedBlocks.end());
1991 iResult=MakeOutputDataBlockList(blockData, &outputBlockCnt, &outputBlocks);
1994 HLTFatal("component %s (%p): can not convert output block descriptor list", GetComponentID(), this);
1997 if (iResult<0 || bSkipDataProcessing) {
2001 CleanupInputObjects();
2002 if (iResult>=0 && IsDataEvent()) {
2003 IncrementEventCounter();
2005 if (outputBlockCnt==0) {
2006 // no output blocks, set size to 0
2010 // reset the internal EventData struct
2011 FillEventData(fCurrentEventData);
2013 // reset the active triggers
2014 if (fpCTPData) fpCTPData->SetTriggers(0);
2016 // set the time for the pushback period
2017 if (fPushbackPeriod>0) {
2018 // suppress the output
2020 if (fLastPushBackTime<0 || (int)time.Get()-fLastPushBackTime>=fPushbackPeriod) {
2021 fLastPushBackTime=time.Get();
2028 int AliHLTComponent::AddComponentStatistics(AliHLTComponentBlockDataList& blocks,
2029 AliHLTUInt8_t* buffer,
2030 AliHLTUInt32_t bufferSize,
2031 AliHLTUInt32_t offset,
2032 AliHLTComponentStatisticsList& stats) const
2034 // see header file for function documentation
2036 if ((fFlags&kDisableComponentStat)!=0) return 0;
2037 #if defined(HLT_COMPONENT_STATISTICS)
2038 if (stats.size()==0) return -ENOENT;
2039 // check if there is space for at least one entry
2040 if (offset+sizeof(AliHLTComponentStatistics)>bufferSize) return 0;
2041 stats[0].fTotalOutputSize=offset;
2042 stats[0].fOutputBlockCount=blocks.size();
2044 fpBenchmark->Stop();
2045 stats[0].fTime=(AliHLTUInt32_t)(fpBenchmark->RealTime()*ALIHLTCOMPONENT_STATTIME_SCALER);
2046 stats[0].fCTime=(AliHLTUInt32_t)(fpBenchmark->CpuTime()*ALIHLTCOMPONENT_STATTIME_SCALER);
2047 fpBenchmark->Continue();
2049 if (offset+stats.size()*sizeof(AliHLTComponentStatistics)>bufferSize) {
2050 AliHLTUInt32_t removedLevel=0;
2052 // remove all entries of the level of the last entry
2053 removedLevel=stats.back().fLevel;
2054 AliHLTComponentStatisticsList::iterator element=stats.begin();
2056 while (element!=stats.end()) {
2057 if (element->fLevel<=removedLevel) {
2058 element=stats.erase(element);
2063 } while (stats.size()>1 &&
2064 (offset+stats.size()*sizeof(AliHLTComponentStatistics)>bufferSize));
2066 assert(stats.size()>0);
2067 if (stats.size()==0) return 0;
2069 if (offset+stats.size()*sizeof(AliHLTComponentStatistics)<=bufferSize) {
2070 AliHLTComponentBlockData bd;
2071 FillBlockData( bd );
2072 bd.fOffset = offset;
2073 bd.fSize = stats.size()*sizeof(AliHLTComponentStatistics);
2074 bd.fDataType = kAliHLTDataTypeComponentStatistics;
2075 bd.fSpecification = kAliHLTVoidDataSpec;
2076 unsigned int master=0;
2077 for (unsigned int i=1; i<blocks.size(); i++) {
2078 if (blocks[i].fSize>blocks[master].fSize &&
2079 !MatchExactly(blocks[i].fDataType, kAliHLTVoidDataType|kAliHLTDataOriginPrivate))
2082 if (blocks.size()>0 && !MatchExactly(blocks[master].fDataType, kAliHLTVoidDataType|kAliHLTDataOriginPrivate)) {
2083 // take the data origin of the biggest block as specification
2084 // this is similar to the treatment in the HOMER interface. For traditional
2085 // reasons, the bytes are swapped there on a little endian architecture, so
2086 // we do it as well.
2087 memcpy(&bd.fSpecification, &blocks[master].fDataType.fOrigin, sizeof(bd.fSpecification));
2088 #ifdef R__BYTESWAP // set on little endian architectures
2089 bd.fSpecification=((bd.fSpecification & 0xFFULL) << 24) |
2090 ((bd.fSpecification & 0xFF00ULL) << 8) |
2091 ((bd.fSpecification & 0xFF0000ULL) >> 8) |
2092 ((bd.fSpecification & 0xFF000000ULL) >> 24);
2095 memcpy(buffer+offset, &(stats[0]), bd.fSize);
2096 blocks.push_back(bd);
2100 if (blocks.size() && buffer && bufferSize && offset && stats.size()) {
2101 // get rid of warning
2103 #endif // HLT_COMPONENT_STATISTICS
2107 int AliHLTComponent::AddComponentTableEntry(AliHLTComponentBlockDataList& blocks,
2108 AliHLTUInt8_t* buffer,
2109 AliHLTUInt32_t bufferSize,
2110 AliHLTUInt32_t offset,
2111 const vector<AliHLTUInt32_t>& parents) const
2113 // see header file for function documentation
2115 if ((fFlags&kDisableComponentStat)!=0) return 0;
2116 #if defined(HLT_COMPONENT_STATISTICS)
2117 // the payload consists of the AliHLTComponentTableEntry struct,
2118 // followed by a an array of 32bit crc chain ids and the component
2119 // description string
2120 unsigned int payloadSize=sizeof(AliHLTComponentTableEntry);
2121 payloadSize+=parents.size()*sizeof(AliHLTUInt32_t);
2123 // the component description has the following format:
2124 // chain-id{component-id:arguments}
2125 const char* componentId=const_cast<AliHLTComponent*>(this)->GetComponentID();
2126 unsigned int descriptionSize=fChainId.size()+1;
2127 descriptionSize+=2; // the '{}' around the component id
2128 descriptionSize+=strlen(componentId);
2129 descriptionSize+=1; // the ':' between component id and arguments
2130 descriptionSize+=fComponentArgs.size();
2132 payloadSize+=descriptionSize;
2133 if (buffer && (offset+payloadSize<=bufferSize)) {
2134 AliHLTUInt8_t* pTgt=buffer+offset;
2135 memset(pTgt, 0, payloadSize);
2138 AliHLTComponentTableEntry* pEntry=reinterpret_cast<AliHLTComponentTableEntry*>(pTgt);
2139 pEntry->fStructSize=sizeof(AliHLTComponentTableEntry);
2140 pEntry->fNofParents=parents.size();
2141 pEntry->fSizeDescription=descriptionSize;
2142 pTgt=pEntry->fBuffer;
2144 // write array of parents
2145 if (parents.size()>0) {
2146 unsigned int copy=parents.size()*sizeof(vector<AliHLTUInt32_t>::value_type);
2147 memcpy(pTgt, &parents[0], parents.size()*sizeof(vector<AliHLTUInt32_t>::value_type));
2151 // write component description
2152 memcpy(pTgt, fChainId.c_str(), fChainId.size());
2153 pTgt+=fChainId.size();
2155 memcpy(pTgt, componentId, strlen(componentId));
2156 pTgt+=strlen(componentId);
2158 memcpy(pTgt, fComponentArgs.c_str(), fComponentArgs.size());
2159 pTgt+=fComponentArgs.size();
2163 AliHLTComponentBlockData bd;
2164 FillBlockData( bd );
2165 bd.fOffset = offset;
2166 bd.fSize = payloadSize;
2167 bd.fDataType = kAliHLTDataTypeComponentTable;
2168 bd.fSpecification = fChainIdCrc;
2169 blocks.push_back(bd);
2173 if (blocks.size() && buffer && bufferSize && offset && parents.size()) {
2174 // get rid of warning
2176 #endif // HLT_COMPONENT_STATISTICS
2180 AliHLTComponent::AliHLTStopwatchGuard::AliHLTStopwatchGuard()
2185 // standard constructor (not for use)
2188 AliHLTComponent::AliHLTStopwatchGuard::AliHLTStopwatchGuard(TStopwatch* pStopwatch)
2190 fpStopwatch(pStopwatch),
2195 // check for already existing guard
2196 if (fgpCurrent) fpPrec=fgpCurrent;
2199 // stop the preceeding guard if it controls a different stopwatch
2201 if (fpPrec && fpPrec!=this) bStart=fpPrec->Hold(fpStopwatch);
2203 // start the stopwatch if the current guard controls a different one
2204 if (fpStopwatch && bStart==1) fpStopwatch->Start(kFALSE);
2207 AliHLTComponent::AliHLTStopwatchGuard::AliHLTStopwatchGuard(const AliHLTStopwatchGuard&)
2213 // copy constructor not for use
2217 AliHLTComponent::AliHLTStopwatchGuard& AliHLTComponent::AliHLTStopwatchGuard::operator=(const AliHLTStopwatchGuard&)
2220 // assignment operator not for use
2227 AliHLTComponent::AliHLTStopwatchGuard* AliHLTComponent::AliHLTStopwatchGuard::fgpCurrent=NULL;
2229 AliHLTComponent::AliHLTStopwatchGuard::~AliHLTStopwatchGuard()
2233 // resume the preceeding guard if it controls a different stopwatch
2235 if (fpPrec && fpPrec!=this) bStop=fpPrec->Resume(fpStopwatch);
2237 // stop the stopwatch if the current guard controls a different one
2238 if (fpStopwatch && bStop==1) fpStopwatch->Stop();
2240 // resume to the preceeding guard
2244 int AliHLTComponent::AliHLTStopwatchGuard::Hold(const TStopwatch* pSucc)
2246 // see header file for function documentation
2247 if (fpStopwatch!=NULL && fpStopwatch!=pSucc) fpStopwatch->Stop();
2248 return fpStopwatch!=pSucc?1:0;
2251 int AliHLTComponent::AliHLTStopwatchGuard::Resume(const TStopwatch* pSucc)
2253 // see header file for function documentation
2254 if (fpStopwatch!=NULL && fpStopwatch!=pSucc) fpStopwatch->Start(kFALSE);
2255 return fpStopwatch!=pSucc?1:0;
2258 int AliHLTComponent::SetStopwatch(TObject* pSW, AliHLTStopwatchType type)
2260 // see header file for function documentation
2262 if (pSW!=NULL && type<kSWTypeCount) {
2263 if (fpStopwatches) {
2264 TObject* pObj=fpStopwatches->At((int)type);
2265 if (pSW==NULL // explicit reset
2266 || pObj==NULL) { // explicit set
2267 fpStopwatches->AddAt(pSW, (int)type);
2268 } else if (pObj!=pSW) {
2269 HLTWarning("stopwatch %d already set, reset first", (int)type);
2279 int AliHLTComponent::SetStopwatches(TObjArray* pStopwatches)
2281 // see header file for function documentation
2282 if (pStopwatches==NULL) return -EINVAL;
2285 for (int i=0 ; i<(int)kSWTypeCount && pStopwatches->GetEntriesFast(); i++)
2286 SetStopwatch(pStopwatches->At(i), (AliHLTStopwatchType)i);
2290 AliHLTUInt32_t AliHLTComponent::GetRunNo() const
2292 // see header file for function documentation
2294 // 2010-02-11 OCDB is now the reliable source for the run number, it is
2295 // initialized either by aliroot or the external interface depending
2296 // on the environment. It turned out that the rundescriptor is not set
2297 // in the aliroot mode, resulting in an invalid run number. However this
2298 // did not cause problems until now. OCDB initialization has been revised
2299 // already in 10/2009. This was a remnant.
2300 // Have to check whether we get rid of the rundescriptor at some point.
2301 if (fpRunDesc==NULL) return AliHLTMisc::Instance().GetCDBRunNo();
2302 if (fpRunDesc->fRunNo!=(unsigned)AliHLTMisc::Instance().GetCDBRunNo()) {
2303 HLTWarning("run number mismatch: ocdb %d run descriptor %d", AliHLTMisc::Instance().GetCDBRunNo(), fpRunDesc->fRunNo);
2305 return fpRunDesc->fRunNo;
2308 AliHLTUInt32_t AliHLTComponent::GetRunType() const
2310 // see header file for function documentation
2311 if (fpRunDesc==NULL) return kAliHLTVoidRunType;
2312 return fpRunDesc->fRunType;
2315 AliHLTUInt32_t AliHLTComponent::GetTimeStamp() const
2317 // see header file for function documentation
2318 if (fCurrentEventData.fEventCreation_s) {
2319 return fCurrentEventData.fEventCreation_s;
2321 // using the actual UTC if the time stamp was not set by the framework
2322 return static_cast<AliHLTUInt32_t>(time(NULL));
2325 AliHLTUInt32_t AliHLTComponent::GetPeriodNumber() const
2327 // see header file for function documentation
2328 return (GetEventId()>>36)&0xfffffff;
2331 AliHLTUInt32_t AliHLTComponent::GetOrbitNumber() const
2333 // see header file for function documentation
2334 return (GetEventId()>>12)&0xffffff;
2337 AliHLTUInt16_t AliHLTComponent::GetBunchCrossNumber() const
2339 // see header file for function documentation
2340 return GetEventId()&0xfff;
2343 bool AliHLTComponent::IsDataEvent(AliHLTUInt32_t* pTgt) const
2345 // see header file for function documentation
2346 if (pTgt) *pTgt=fEventType;
2347 return (fEventType==gkAliEventTypeData ||
2348 fEventType==gkAliEventTypeDataReplay ||
2349 fEventType==gkAliEventTypeCalibration);
2352 int AliHLTComponent::CopyStruct(void* pStruct, unsigned int iStructSize, unsigned int iBlockNo,
2353 const char* structname, const char* eventname)
2355 // see header file for function documentation
2357 if (pStruct!=NULL && iStructSize>sizeof(AliHLTUInt32_t)) {
2358 if (fpInputBlocks!=NULL && iBlockNo<fCurrentEventData.fBlockCnt) {
2359 AliHLTUInt32_t* pTgt=(AliHLTUInt32_t*)pStruct;
2360 if (fpInputBlocks[iBlockNo].fPtr && fpInputBlocks[iBlockNo].fSize) {
2361 AliHLTUInt32_t copy=*((AliHLTUInt32_t*)fpInputBlocks[iBlockNo].fPtr);
2362 if (fpInputBlocks[iBlockNo].fSize!=copy) {
2363 HLTWarning("%s event: mismatch of block size (%d) and structure size (%d)", eventname, fpInputBlocks[iBlockNo].fSize, copy);
2364 if (copy>fpInputBlocks[iBlockNo].fSize) copy=fpInputBlocks[iBlockNo].fSize;
2366 if (copy!=iStructSize) {
2367 HLTWarning("%s event: mismatch in %s version (data type version %d)", eventname, structname, ALIHLT_DATA_TYPES_VERSION);
2368 if (copy>iStructSize) {
2371 memset(pTgt, 0, iStructSize);
2374 memcpy(pTgt, fpInputBlocks[iBlockNo].fPtr, copy);
2378 HLTWarning("%s event: missing data block", eventname);
2384 HLTError("invalid struct");
2390 AliHLTUInt32_t AliHLTComponent::CalculateChecksum(const AliHLTUInt8_t* buffer, int size)
2392 // see header file for function documentation
2393 AliHLTUInt32_t remainder = 0;
2394 const AliHLTUInt8_t crcwidth=(8*sizeof(AliHLTUInt32_t));
2395 const AliHLTUInt32_t topbit=1 << (crcwidth-1);
2396 const AliHLTUInt32_t polynomial=0xD8; /* 11011 followed by 0's */
2399 // http://www.netrino.com/Embedded-Systems/How-To/CRC-Calculation-C-Code
2402 * Perform modulo-2 division, a byte at a time.
2404 for (int byte = 0; byte < size; ++byte)
2407 * Bring the next byte into the remainder.
2409 remainder ^= (buffer[byte] << (crcwidth - 8));
2412 * Perform modulo-2 division, a bit at a time.
2414 for (uint8_t bit = 8; bit > 0; --bit)
2417 * Try to divide the current data bit.
2419 if (remainder & topbit)
2421 remainder = (remainder << 1) ^ polynomial;
2425 remainder = (remainder << 1);
2431 * The final remainder is the CRC result.
2436 int AliHLTComponent::ExtractComponentTableEntry(const AliHLTUInt8_t* pBuffer, AliHLTUInt32_t size,
2437 string& retChainId, string& retCompId, string& retCompArgs,
2438 vector<AliHLTUInt32_t>& parents)
2440 // see header file for function documentation
2443 retCompArgs.clear();
2445 if (!pBuffer || size==0) return 0;
2447 const AliHLTComponentTableEntry* pEntry=reinterpret_cast<const AliHLTComponentTableEntry*>(pBuffer);
2448 if (size<8/* the initial size of the structure*/ ||
2449 pEntry==NULL || pEntry->fStructSize<8) return -ENOMSG;
2450 const AliHLTUInt32_t* pParents=reinterpret_cast<const AliHLTUInt32_t*>(pEntry->fBuffer);
2451 const AliHLTUInt8_t* pEnd=pBuffer+size;
2453 if (pParents+pEntry->fNofParents>=reinterpret_cast<const AliHLTUInt32_t*>(pEnd)) return -ENODEV;
2454 for (unsigned int i=0; i<pEntry->fNofParents; i++, pParents++) {
2455 parents.push_back(*pParents);
2458 const char* pDescription=reinterpret_cast<const char*>(pParents);
2459 if (pDescription+pEntry->fSizeDescription>=reinterpret_cast<const char*>(pEnd) ||
2460 *(pDescription+pEntry->fSizeDescription)!=0) {
2464 TString descriptor=reinterpret_cast<const char*>(pDescription);
2468 TObjArray* pTokens=descriptor.Tokenize("{");
2471 if (pTokens->GetEntriesFast()>n) {
2472 retChainId=((TObjString*)pTokens->At(n++))->GetString();
2474 if (pTokens->GetEntriesFast()>n) {
2475 compId=((TObjString*)pTokens->At(n++))->GetString();
2479 if (!compId.IsNull() && (pTokens=compId.Tokenize(":"))!=NULL) {
2481 if (pTokens->GetEntriesFast()>n) {
2482 compId=((TObjString*)pTokens->At(n++))->GetString();
2484 if (pTokens->GetEntriesFast()>n) {
2485 compArgs=((TObjString*)pTokens->At(n++))->GetString();
2489 compId.ReplaceAll("}", "");
2490 compArgs.ReplaceAll("}", "");
2493 retCompArgs=compArgs;
2495 if (retChainId.size()==0) return -ENODATA;
2500 int AliHLTComponent::ExtractTriggerData(
2501 const AliHLTComponentTriggerData& trigData,
2502 const AliHLTUInt8_t (**attributes)[gkAliHLTBlockDAttributeCount],
2503 AliHLTUInt64_t* status,
2504 const AliRawDataHeader** cdh,
2505 AliHLTReadoutList* readoutlist,
2509 // see header file for function documentation
2511 // Check that the trigger data structure is the correct size.
2512 if (trigData.fStructSize != sizeof(AliHLTComponentTriggerData))
2517 log.LoggingVarargs(kHLTLogError, Class_Name(), FUNCTIONNAME(), __FILE__, __LINE__,
2518 "Invalid trigger structure size: %d but expected %d.", trigData.fStructSize, sizeof(AliHLTComponentTriggerData)
2524 // Get the size of the AliHLTEventTriggerData structure without the readout list part.
2525 // The way we do this here should also handle memory alignment correctly.
2526 AliHLTEventTriggerData* dummy = NULL;
2527 size_t sizeWithoutReadout = (char*)(&dummy->fReadoutList) - (char*)(dummy);
2529 // Check that the trigger data pointer points to data of a size we can handle.
2530 // Either it is the size of AliHLTEventTriggerData or the size of the old
2531 // version of AliHLTEventTriggerData using AliHLTEventDDLV0.
2532 if (trigData.fDataSize != sizeof(AliHLTEventTriggerData) and
2533 trigData.fDataSize != sizeWithoutReadout + sizeof(AliHLTEventDDLV0)
2539 log.LoggingVarargs(kHLTLogError, Class_Name(), FUNCTIONNAME(), __FILE__, __LINE__,
2540 "Invalid trigger data size: %d but expected %d.", trigData.fDataSize, sizeof(AliHLTEventTriggerData)
2546 AliHLTEventTriggerData* evtData = reinterpret_cast<AliHLTEventTriggerData*>(trigData.fData);
2547 assert(evtData != NULL);
2549 // Check that the CDH has 8 words.
2550 if (cdh != NULL and evtData->fCommonHeaderWordCnt != 8)
2555 log.LoggingVarargs(kHLTLogError, Class_Name(), FUNCTIONNAME(), __FILE__, __LINE__,
2556 "Common Data Header (CDH) has wrong number of data words: %d but expected %d",
2557 evtData->fCommonHeaderWordCnt, sizeof(AliRawDataHeader)/sizeof(AliHLTUInt32_t)
2563 // Check that the readout list has the correct count of words. i.e. something we can handle,
2564 if (readoutlist != NULL and
2565 evtData->fReadoutList.fCount != (unsigned)gkAliHLTDDLListSizeV0 and
2566 evtData->fReadoutList.fCount != (unsigned)gkAliHLTDDLListSizeV1
2572 log.LoggingVarargs(kHLTLogError, Class_Name(), FUNCTIONNAME(), __FILE__, __LINE__,
2573 "Readout list structure has wrong number of data words: %d but expected %d",
2574 evtData->fReadoutList.fCount, gkAliHLTDDLListSize
2580 if (attributes != NULL)
2582 *attributes = &evtData->fAttributes;
2586 *status = evtData->fHLTStatus;
2590 const AliRawDataHeader* cdhptr = reinterpret_cast<const AliRawDataHeader*>(&evtData->fCommonHeader);
2593 if (readoutlist != NULL)
2595 *readoutlist = AliHLTReadoutList(evtData->fReadoutList);
2600 int AliHLTComponent::LoggingVarargs(AliHLTComponentLogSeverity severity,
2601 const char* originClass, const char* originFunc,
2602 const char* file, int line, ... ) const
2604 // see header file for function documentation
2608 va_start(args, line);
2610 // logging function needs to be const in order to be called from const member functions
2611 // without problems. But at this point we face the problem with virtual members which
2612 // are not necessarily const.
2613 AliHLTComponent* nonconst=const_cast<AliHLTComponent*>(this);
2614 AliHLTLogging::SetLogString(this, ", %p", "%s (%s_pfmt_): ",
2615 fChainId[0]!=0?fChainId.c_str():nonconst->GetComponentID(),
2616 nonconst->GetComponentID());
2617 iResult=SendMessage(severity, originClass, originFunc, file, line, AliHLTLogging::BuildLogString(NULL, args, true /*append*/));
2623 TUUID AliHLTComponent::GenerateGUID()
2625 // Generates a globally unique identifier.
2627 // Start by creating a new UUID. We cannot use the one automatically generated
2628 // by ROOT because the algorithm used will not guarantee unique IDs when generating
2629 // these UUIDs at a high rate in parallel.
2631 // We then use the generated UUID to form part of the random number seeds which
2632 // will be used to generate a proper random UUID. For good measure we use a MD5
2633 // hash also. Note that we want to use the TUUID class because it will combine the
2634 // host address information into the UUID. Using gSystem->GetHostByName() apparently
2635 // can cause problems on Windows machines with a firewall, because it always tries
2636 // to contact a DNS. The TUUID class handles this case appropriately.
2645 md5.Update(buf, sizeof(buf));
2648 dword[0] += gSystem->GetUid();
2649 dword[1] += gSystem->GetGid();
2650 dword[2] += gSystem->GetPid();
2651 for (int i = 0; i < 4; ++i)
2653 gRandom->SetSeed(dword[i]);
2654 dword[i] = gRandom->Integer(0xFFFFFFFF);
2656 md52.Update(buf, sizeof(buf));
2658 // To keep to the standard we need to set the version and reserved bits.
2659 word[3] = (word[3] & 0x0FFF) | 0x4000;
2660 buf[8] = (buf[8] & 0x3F) | 0x80;
2662 // Create the name of the new class and file.
2664 sprintf(uuidstr, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
2665 dword[0], word[2], word[3], buf[8], buf[9], buf[10], buf[11], buf[12], buf[13], buf[14], buf[15]
2668 uuid.SetUUID(uuidstr);
2672 int AliHLTComponent::ScanECSParam(const char* ecsParam)
2674 // see header file for function documentation
2676 // format of the parameter string from ECS
2677 // <command>;<parameterkey>=<parametervalue>;<parameterkey>=<parametervalue>;...
2678 // search for a subset of the parameterkeys
2682 // CTP_TRIGGER_CLASS=
2683 // DATA_FORMAT_VERSION=
2685 // HLT_OUT_DDL_LIST=
2686 // HLT_TRIGGER_CODE=
2689 // The command apears not to be sent by the online framework
2691 TString string=ecsParam;
2692 TObjArray* parameter=string.Tokenize(";");
2694 for (int i=0; i<parameter->GetEntriesFast(); i++) {
2695 TString entry=((TObjString*)parameter->At(i))->GetString();
2696 HLTDebug("scanning ECS entry: %s", entry.Data());
2697 TObjArray* entryParams=entry.Tokenize("=");
2699 if (entryParams->GetEntriesFast()>1) {
2700 if ((((TObjString*)entryParams->At(0))->GetString()).CompareTo("CTP_TRIGGER_CLASS")==0) {
2701 int result=InitCTPTriggerClasses((((TObjString*)entryParams->At(1))->GetString()).Data());
2702 if (iResult>=0 && result<0) iResult=result;
2704 // TODO: scan the other parameters
2705 // e.g. consistency check of run number
2717 int AliHLTComponent::SetupCTPData()
2719 // see header file for function documentation
2720 if (fpCTPData) delete fpCTPData;
2721 fpCTPData=new AliHLTCTPData;
2722 if (!fpCTPData) return -ENOMEM;
2726 int AliHLTComponent::InitCTPTriggerClasses(const char* ctpString)
2728 // see header file for function documentation
2729 if (!fpCTPData) return 0; // silently accept as the component has to announce that it want's the CTP info
2730 return fpCTPData->InitCTPTriggerClasses(ctpString);
2733 bool AliHLTComponent::EvaluateCTPTriggerClass(const char* expression, AliHLTComponentTriggerData& trigData) const
2735 // see header file for function documentation
2737 static bool bWarningThrown=false;
2738 if (!bWarningThrown) HLTError("Trigger classes not initialized, use SetupCTPData from DoInit()");
2739 bWarningThrown=true;
2743 return fpCTPData->EvaluateCTPTriggerClass(expression, trigData);
2746 int AliHLTComponent::CheckCTPTrigger(const char* name) const
2748 // see header file for function documentation
2750 static bool bWarningThrown=false;
2751 if (!bWarningThrown) HLTError("Trigger classes not initialized, use SetupCTPData from DoInit()");
2752 bWarningThrown=true;
2756 return fpCTPData->CheckTrigger(name);
2759 Double_t AliHLTComponent::GetBz()
2762 return AliHLTMisc::Instance().GetBz();
2765 Double_t AliHLTComponent::GetBz(const Double_t *r)
2767 // Returns Bz (kG) at the point "r" .
2768 return AliHLTMisc::Instance().GetBz(r);
2771 void AliHLTComponent::GetBxByBz(const Double_t r[3], Double_t b[3])
2773 // Returns Bx, By and Bz (kG) at the point "r" .
2774 AliHLTMisc::Instance().GetBxByBz(r, b);