1 // @(#)alimdc:$Name: $:$Id$
2 // Author: Fons Rademakers 26/11/99
3 // Updated: Dario Favretto 15/04/2003
5 /**************************************************************************
6 * Copyright(c) 1998-2003, ALICE Experiment at CERN, All rights reserved. *
8 * Author: The ALICE Off-line Project. *
9 * Contributors are mentioned in the code where appropriate. *
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 **************************************************************************/
22 //////////////////////////////////////////////////////////////////////////
26 // Set of classes defining the ALICE RAW event format. The AliRawEventV2//
27 // class defines a RAW event. It consists of an AliEventHeader object //
28 // an AliEquipmentHeader object, an AliRawData object and an array of //
29 // sub-events, themselves also being AliRawEventV2s. The number of //
30 // sub-events depends on the number of DATE LDC's. //
31 // The AliRawEventV2 objects are written to a ROOT file using different //
32 // technologies, i.e. to local disk via AliRawDB or via rfiod using //
33 // AliRawRFIODB or via rootd using AliRawRootdDB or to CASTOR via //
34 // rootd using AliRawCastorDB (and for performance testing there is //
35 // also AliRawNullDB). //
36 // The AliStats class provides statics information that is added as //
37 // a single keyed object to each raw file. //
38 // The AliTagDB provides an interface to a TAG database. //
39 // The AliMDC class is usid by the "alimdc" stand-alone program //
40 // that reads data directly from DATE. //
42 //////////////////////////////////////////////////////////////////////////
44 #include <sys/types.h>
51 #include <TStopwatch.h>
52 #include <TPluginManager.h>
53 #include <TBufferFile.h>
54 #include <TProcessID.h>
58 #include "libDateEb.h"
64 #include <AliESDEvent.h>
66 #include "AliRawEventV2.h"
67 #include "AliRawEventHeaderBase.h"
68 #include "AliRawEquipmentV2.h"
69 #include "AliRawEquipmentHeader.h"
70 #include "AliRawDataArrayV2.h"
71 #include "AliRawData.h"
73 #include "AliRawRFIODB.h"
74 #include "AliRawCastorDB.h"
75 #include "AliRawRootdDB.h"
76 #include "AliRawNullDB.h"
78 #include "AliRawEventTag.h"
79 #include "AliFilter.h"
87 const char* const AliMDC::fgkFilterName[kNFilters] = {"AliHoughFilter"};
89 //______________________________________________________________________________
90 AliMDC::AliMDC(Int_t compress, Bool_t deleteFiles, EFilterMode filterMode,
91 Double_t maxSizeTagDB, const char* fileNameTagDB,
92 const char *guidFileFolder,
94 fEvent(new AliRawEventV2),
98 fEventTag(new AliRawEventTag),
100 fBasketSize(basketsize),
101 fDeleteFiles(deleteFiles),
102 fFilterMode(filterMode),
105 fIsTagDBCreated(kFALSE),
106 fMaxSizeTagDB(maxSizeTagDB),
107 fFileNameTagDB(fileNameTagDB),
108 fGuidFileFolder(guidFileFolder)
110 // Create MDC processor object.
111 // compress is the file compression mode.
112 // If deleteFiles is kTRUE the raw data files will be deleted after they
114 // If the filterMode if kFilterOff no filter algorithm will be, if it is
115 // kFilterTransparent the algorthims will be run but no events will be
116 // rejected, if it is kFilterOn the filters will be run and the event will
117 // be rejected if all filters return kFALSE.
118 // If maxSizeTagDB is greater than 0 it determines the maximal size of the
119 // tag DB and then fileNameTagDB is the directory name for the tag DB.
120 // Otherwise fileNameTagDB is the file name of the tag DB. If it is NULL
121 // no tag DB will be created.
122 // Optional 'guidFileFolder' specifies the folder in which *.guid files
123 // will be stored. In case this option is not given, the *.guid files
124 // will be written to the same folder as the raw-data files.
126 // Set the maximum tree size to 19GB
127 // in order to allow big raw data files
128 TTree::SetMaxTreeSize(20000000000LL);
130 AliRawEquipmentHeader::Class()->IgnoreTObjectStreamer();
131 AliRawEquipmentV2::Class()->IgnoreTObjectStreamer();
132 AliRawEventV2::Class()->IgnoreTObjectStreamer();
133 AliRawDataArrayV2::Class()->IgnoreTObjectStreamer();
135 TBufferFile::SetGlobalReadParam(5);
137 // This line is needed in case of a stand-alone application w/o
138 // $ROOTSYS/etc/system.rootrc file
139 gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo",
145 if (fFilterMode != kFilterOff) {
146 fESD = new AliESDEvent();
149 // Create the guid files folder if it does not exist
150 if (!fGuidFileFolder.IsNull()) {
151 gSystem->ResetErrno();
152 gSystem->MakeDirectory(fGuidFileFolder.Data());
153 if (gSystem->GetErrno() && gSystem->GetErrno() != EEXIST) {
154 SysError("AliMDC", "mkdir %s", fGuidFileFolder.Data());
158 // install SIGUSR1 handler to allow clean interrupts
159 gSystem->AddSignalHandler(new AliMDCInterruptHandler(this));
161 // create the high level filters
162 if (fFilterMode != kFilterOff) {
163 for (Int_t iFilter = 0; iFilter < kNFilters; iFilter++) {
164 TClass* filterClass = gROOT->GetClass(fgkFilterName[iFilter]);
166 Warning("AliMDC", "no filter class %s found", fgkFilterName[iFilter]);
169 AliFilter* filter = (AliFilter*) filterClass->New();
171 Warning("AliMDC", "creation of filter %s failed", fgkFilterName[iFilter]);
174 fFilters.Add(filter);
179 //______________________________________________________________________________
185 if(fTagDB) delete fTagDB;
192 //______________________________________________________________________________
193 Int_t AliMDC::Open(EWriteMode mode, const char* fileName,
194 Double_t maxFileSize,
195 const char* fs1, const char* fs2)
197 // open a new raw DB file
200 fRawDB = new AliRawRFIODB(fEvent, fESD, fCompress, fileName, fBasketSize);
201 else if (mode == kROOTD)
202 fRawDB = new AliRawRootdDB(fEvent, fESD, fCompress, fileName, fBasketSize);
203 else if (mode == kCASTOR)
204 fRawDB = new AliRawCastorDB(fEvent, fESD, fCompress, fileName, fBasketSize);
205 else if (mode == kDEVNULL)
206 fRawDB = new AliRawNullDB(fEvent, fESD, fCompress, fileName, fBasketSize);
208 fRawDB = new AliRawDB(fEvent, fESD, fCompress, fileName, fBasketSize);
209 fRawDB->SetDeleteFiles(fDeleteFiles);
211 if (fRawDB->IsZombie()) {
217 if (fileName == NULL) {
218 fRawDB->SetMaxSize(maxFileSize);
219 fRawDB->SetFS(fs1, fs2);
220 if (!fRawDB->Create()) {
227 if (!fRawDB->WriteGuidFile(fGuidFileFolder)) {
233 Info("Open", "Filling raw DB %s\n", fRawDB->GetDBName());
238 //______________________________________________________________________________
239 Int_t AliMDC::ProcessEvent(void* event, Bool_t isIovecArray)
241 // Convert the DATE event to an AliRawEventV2 object and store it in the raw DB,
242 // optionally also run the filter.
243 // event is either a pointer to the streamlined event
244 // or, if isIovecArray is kTRUE, a pointer to an array of iovecs with one
245 // iovec per subevent (used by the event builder).
246 // The return value is the number of written bytes or an error code
247 const Long64_t kFileSizeErrorLevel = 19000000000LL;
249 Int_t objectNumber = TProcessID::GetObjectCount();
251 Long64_t currentFileSize = GetTotalSize();
252 // AliDebug(1,Form("current file size is %lld bytes",currentFileSize));
253 if(currentFileSize > kFileSizeErrorLevel) {
254 Error("ProcessEvent", "file size (%lu) exceeds the limit "
260 char* data = (char*) event;
261 if (isIovecArray) data = (char*) ((iovec*) event)[0].iov_base;
263 // Shortcut for easy header access
264 AliRawEventHeaderBase *header = fEvent->GetHeader(data);
267 if ((status = header->ReadHeader(data)) != (Int_t)header->GetHeadSize()) {
268 Error("ProcessEvent","Wrong event header format (%d != %d)",
269 status,(Int_t)header->GetHeadSize());
273 // if (AliDebugLevel() > 2) ToAliDebug(3, header->Dump(););
275 // Check event type and skip "Start of Run", "End of Run",
276 // "Start of Run Files" and "End of Run Files"
277 Int_t size = header->GetEventSize() - header->GetHeadSize();
278 UInt_t eventType = header->Get("Type");
280 // AliDebug(1, Form("Processing %s (%d bytes)", header->GetTypeName(), size));
282 // Amount of data left to read for this event
285 // StartOfRun, EndOfRun etc. events have no payload
286 // Nevertheless, store the event headers in the tree
289 // If there is less data for this event than the next sub-event
290 // header, something is wrong. Skip to next event...
291 if (toRead < (Int_t)header->GetHeadSize()) {
292 Error("ProcessEvent", "header size (%d) exceeds number of bytes "
293 "to read (%d)", header->GetHeadSize(), toRead);
294 if (AliDebugLevel() > 0) ToAliDebug(1, header->Dump(););
295 return kErrHeaderSize;
298 // Loop over all sub-events... (LDCs)
301 if (isIovecArray) data = (char*) ((iovec*) event)[nsub].iov_base;
303 // AliDebug(1, Form("reading LDC %d", nsub));
305 AliRawEventV2 *subEvent = fEvent->NextSubEvent();
307 // Read sub-event header
308 AliRawEventHeaderBase *subHeader = subEvent->GetHeader(data);
309 if ((status = subHeader->ReadHeader(data)) != (Int_t)subHeader->GetHeadSize()) {
310 return kErrSubHeader;
313 // if (AliDebugLevel() > 2) ToAliDebug(3, subHeader->Dump(););
315 toRead -= subHeader->GetHeadSize();
317 Int_t rawSize = subHeader->GetEventSize() - subHeader->GetHeadSize();
319 // Make sure raw data less than left over bytes for current event
320 if (rawSize > toRead) {
321 Warning("ProcessEvent", "raw data size (%d) exceeds number of "
322 "bytes to read (%d)\n", rawSize, toRead);
323 if (AliDebugLevel() > 0) ToAliDebug(1, subHeader->Dump(););
327 // Read Equipment Headers (in case of physics or calibration event)
328 if (eventType == AliRawEventHeaderBase::kPhysicsEvent ||
329 eventType == AliRawEventHeaderBase::kCalibrationEvent ||
330 eventType == AliRawEventHeaderBase::kSystemSoftwareTriggerEvent ||
331 eventType == AliRawEventHeaderBase::kDetectorSoftwareTriggerEvent ||
332 eventType == AliRawEventHeaderBase::kStartOfData ||
333 eventType == AliRawEventHeaderBase::kEndOfData) {
334 while (rawSize > 0) {
335 AliRawEquipmentV2 &equipment = *subEvent->NextEquipment();
336 AliRawEquipmentHeader &equipmentHeader =
337 *equipment.GetEquipmentHeader();
338 Int_t equipHeaderSize = equipmentHeader.HeaderSize();
339 if ((status = ReadEquipmentHeader(equipmentHeader, header->DataIsSwapped(),
340 data)) != equipHeaderSize) {
341 return kErrEquipmentHeader;
344 // if (AliDebugLevel() > 2) ToAliDebug(3, equipmentHeader.Dump(););
346 toRead -= equipHeaderSize;
347 rawSize -= equipHeaderSize;
349 // Read equipment raw data
350 AliRawDataArrayV2 *arr = fRawDB->GetRawDataArray(equipmentHeader.GetEquipmentSize(),
351 equipmentHeader.GetId());
352 AliRawData &subRaw = *equipment.NextRawData(arr);
354 Int_t eqSize = equipmentHeader.GetEquipmentSize() - equipHeaderSize;
355 if ((status = ReadRawData(subRaw, eqSize, data)) != eqSize) {
356 return kErrEquipment;
363 } else { // Read only raw data but no equipment header
365 AliRawEquipmentV2 &equipment = *subEvent->NextEquipment();
366 AliRawEquipmentHeader &equipmentHeader =
367 *equipment.GetEquipmentHeader();
368 equipmentHeader.Reset();
369 AliRawDataArrayV2 *arr = fRawDB->GetRawDataArray(equipmentHeader.GetEquipmentSize(),
370 equipmentHeader.GetId());
371 AliRawData &subRaw = *equipment.NextRawData(arr);
372 if ((status = ReadRawData(subRaw, rawSize, data)) != rawSize) {
373 return kErrEquipment;
383 // High Level Event Filter
384 if (fFilterMode != kFilterOff) {
385 if (eventType == AliRawEventHeaderBase::kPhysicsEvent ||
386 eventType == AliRawEventHeaderBase::kCalibrationEvent ||
387 eventType == AliRawEventHeaderBase::kSystemSoftwareTriggerEvent ||
388 eventType == AliRawEventHeaderBase::kDetectorSoftwareTriggerEvent ||
389 eventType == AliRawEventHeaderBase::kStartOfData ||
390 eventType == AliRawEventHeaderBase::kEndOfData) {
391 Bool_t result = kFALSE;
392 for (Int_t iFilter = 0; iFilter < fFilters.GetEntriesFast(); iFilter++) {
393 AliFilter* filter = (AliFilter*) fFilters[iFilter];
394 if (!filter) continue;
395 if (filter->Filter(fEvent, fESD)) result = kTRUE;
397 if ((fFilterMode == kFilterOn) && !result) return kFilterReject;
401 // Store raw event in tree
402 Int_t nBytes = fRawDB->Fill();
404 TProcessID::SetObjectCount(objectNumber);
406 // Fill the event tag object
407 fEventTag->SetHeader(header);
408 fEventTag->SetGUID(fRawDB->GetDB()->GetUUID().AsString());
409 fEventTag->SetEventNumber(fRawDB->GetEvents()-1);
411 // Create Tag DB here only after the raw data header
412 // version was already identified
413 if (!fIsTagDBCreated) {
414 if (!fFileNameTagDB.IsNull()) {
415 if (fMaxSizeTagDB > 0) {
416 fTagDB = new AliTagDB(fEventTag, NULL);
417 fTagDB->SetMaxSize(fMaxSizeTagDB);
418 fTagDB->SetFS(fFileNameTagDB.Data());
419 if (!fTagDB->Create()) return kErrTagFile;
421 fTagDB = new AliTagDB(fEventTag, fFileNameTagDB.Data());
422 if (fTagDB->IsZombie()) return kErrTagFile;
425 fIsTagDBCreated = kTRUE;
428 // Store event tag in tree
429 if (fTagDB) fTagDB->Fill();
431 // Make top event object ready for next event data
435 // Clean up HLT ESD for the next event
436 if (fESD) fESD->Reset();
444 //______________________________________________________________________________
445 Long64_t AliMDC::GetTotalSize()
447 // return the total current raw DB file size
449 if (!fRawDB) return -1;
451 return fRawDB->GetTotalSize();
454 //______________________________________________________________________________
455 Long64_t AliMDC::Close()
457 // close the current raw DB file
459 if (!fRawDB) return -1;
461 Long64_t filesize = fRawDB->Close();
467 //______________________________________________________________________________
468 Long64_t AliMDC::AutoSave()
470 // Auto-save the raw-data
471 // and esd (if any) trees
473 if (!fRawDB) return -1;
475 return fRawDB->AutoSave();
478 //______________________________________________________________________________
479 Int_t AliMDC::Run(const char* inputFile, Bool_t loop,
480 EWriteMode mode, Double_t maxFileSize,
481 const char* fs1, const char* fs2)
483 // Run the MDC processor. Read from the input stream and only return
484 // when the input gave and EOF or a fatal error occured. On success 0
485 // is returned, 1 in case of a fatality.
486 // inputFile is the name of the DATE input file; if NULL the input will
487 // be taken from the event builder.
488 // If loop is set the same input file will be reused in an infinite loop.
489 // mode specifies the type of the raw DB.
490 // maxFileSize is the maximal size of the raw DB.
491 // fs1 and fs2 are the file system locations of the raw DB.
493 Info("Run", "input = %s, rawdb size = %f, filter = %s, "
494 "looping = %s, compression = %d, delete files = %s",
495 inputFile ? inputFile : "event builder", maxFileSize,
496 fFilterMode == kFilterOff ? "off" :
497 (fFilterMode == kFilterOn ? "on" : "transparent"),
498 loop ? "yes" : "no", fCompress, fDeleteFiles ? "yes" : "no");
500 // Open the input file
503 if ((fd = open(inputFile, O_RDONLY)) == -1) {
504 Error("Run", "cannot open input file %s", inputFile);
509 // Used for statistics
512 Float_t chunkSize = maxFileSize/100, nextChunk = chunkSize;
514 // Create new raw DB.
517 if (Open(mode,NULL,maxFileSize,fs1,fs2) < 0) return 1;
519 // Process input stream
524 UInt_t eventSize = 0;
527 AliRawEventHeaderBase header;
528 AliRawEventHeaderBase *hdr = NULL;
532 // If we were in looping mode stop directly after a SIGUSR1 signal
534 Info("Run", "Stopping loop, processed %d events", numEvents);
538 if (!inputFile) { // get data from event builder
540 if ((eorFlag = ebEor())) break;
541 if ((event = (char*)ebGetNextEvent()) == (char*)-1) {
542 Error("Run", "error getting next event (%s)", ebGetLastError());
546 // no event, sleep for 1 second and try again
547 gSystem->Sleep(1000);
551 Error("Run", "AliMDC was compiled without event builder support");
557 } else { // get data from a file
560 if ((nrecv = Read(fd, header.HeaderBaseBegin(), header.HeaderBaseSize())) !=
561 header.HeaderBaseSize()) {
562 if (nrecv == 0) { // eof
564 ::lseek(fd, 0, SEEK_SET);
570 Error("Run", "error reading base header");
577 char *data = (char *)header.HeaderBaseBegin();
579 hdr = AliRawEventHeaderBase::Create(data);
582 memcpy(hdr->HeaderBaseBegin(), header.HeaderBaseBegin(), header.HeaderBaseSize());
585 if ((nrecv = Read(fd, hdr->HeaderBegin(), hdr->HeaderSize())) !=
587 if (nrecv == 0) { // eof
589 ::lseek(fd, 0, SEEK_SET);
597 Error("Run", "error reading header");
604 if (eventSize < hdr->GetEventSize()) {
606 eventSize = 2 * hdr->GetEventSize();
607 event = new char[eventSize];
609 memcpy(event, header.HeaderBaseBegin(), header.HeaderBaseSize());
610 memcpy(event+hdr->HeaderBaseSize(), hdr->HeaderBegin(), hdr->HeaderSize());
611 if (hdr->GetExtendedDataSize() != 0)
612 memcpy(event+hdr->HeaderBaseSize()+hdr->HeaderSize(),
613 hdr->GetExtendedData(), hdr->GetExtendedDataSize());
614 Int_t size = hdr->GetEventSize() - hdr->GetHeadSize();
615 if (Read(fd, event + hdr->GetHeadSize(), size) != size) {
616 Error("Run", "error reading data");
624 Int_t result = ProcessEvent(event, !inputFile);
626 Error("Run", "error writing data. Error code: %d",result);
633 // Filling time statistics
634 if (fRawDB->GetBytesWritten() > nextChunk) {
635 nextChunk += chunkSize;
638 // Check size of raw db. If bigger than maxFileSize, close file
639 // and continue with new file.
640 if (fRawDB->GetBytesWritten() > maxFileSize) {
642 printf("Written raw DB at a rate of %.1f MB/s\n",
643 fRawDB->GetBytesWritten() / timer.RealTime() / 1000000.);
645 if (!fRawDB->NextFile()) {
646 Error("Run", "error opening next raw data file");
648 if (inputFile) delete[] event;
653 printf("Filling raw DB %s\n", fRawDB->GetDBName());
655 nextChunk = chunkSize;
658 // Check size of tag db
659 if (fTagDB && fTagDB->FileFull()) {
660 if (!fTagDB->NextFile()) {
664 printf("Filling tag DB %s\n", fTagDB->GetDBName());
669 // Make top event object ready for next event data
670 //printf("Event %d has %d sub-events\n", numEvents, fEvent->GetNSubEvents());
672 // Clean up HLT ESD for the next event
673 // if (fESD) fESD->Reset();
677 if (!ebReleaseEvent((iovec*)event)) {
678 Error("Run", "problem releasing event (%s)", ebGetLastError());
687 printf("Written raw DB at a rate of %.1f MB/s\n",
688 fRawDB->GetBytesWritten() / timer.RealTime() / 1000000.);
690 // Write stats to raw db and run db and delete stats object
697 Info("Run", "event builder reported end of run (%d)", eorFlag);
701 // Close input source
709 //______________________________________________________________________________
710 Int_t AliMDC::Read(Int_t fd, void *buffer, Int_t length)
712 // Read exactly length bytes into buffer. Returns number of bytes
713 // received, returns -1 in case of error and 0 for EOF.
717 if (fd < 0) return -1;
720 char *buf = (char *)buffer;
722 for (n = 0; n < length; n += nrecv) {
723 if ((nrecv = read(fd, buf+n, length-n)) <= 0) {
727 SysError("Read", "read");
734 //______________________________________________________________________________
735 Int_t AliMDC::ReadEquipmentHeader(AliRawEquipmentHeader &header,
736 Bool_t isSwapped, char*& data)
738 // Read equipment header info from DATE data stream. Returns bytes read
739 // (i.e. AliRawEquipmentHeader::HeaderSize()), -1 in case of error and
740 // 0 for EOF. If isSwapped is kTRUE the event data is byte swapped
741 // and we will swap the header to host format.
743 memcpy(header.HeaderBegin(), data, header.HeaderSize());
744 data += header.HeaderSize();
746 // Swap equipment header data if needed
750 if (header.GetEquipmentSize() < (UInt_t)header.HeaderSize()) {
751 Error("ReadEquipmentHeader", "invalid equipment header size");
752 // try recovery... how?
756 return header.HeaderSize();
759 //______________________________________________________________________________
760 Int_t AliMDC::ReadRawData(AliRawData &raw, Int_t size, char*& data)
762 // Read raw data from DATE data stream. Returns bytes read (i.e.
763 // size), -1 in case of error and 0 for EOF.
765 raw.SetBuffer(data, size);
771 //______________________________________________________________________________
774 // Stop the event loop
777 if (fRawDB) fRawDB->Stop();