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 AliRawEvent //
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 AliRawEvents. The number of //
30 // sub-events depends on the number of DATE LDC's. //
31 // The AliRawEvent 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>
56 #include "libDateEb.h"
62 #include <AliESDEvent.h>
64 #include "AliRawEvent.h"
65 #include "AliRawEventHeaderBase.h"
66 #include "AliRawEquipment.h"
67 #include "AliRawEquipmentHeader.h"
68 #include "AliRawData.h"
71 #include "AliRawRFIODB.h"
72 #include "AliRawCastorDB.h"
73 #include "AliRawRootdDB.h"
74 #include "AliRawNullDB.h"
76 #include "AliRawEventTag.h"
77 #include "AliFilter.h"
85 const char* const AliMDC::fgkFilterName[kNFilters] = {"AliHoughFilter"};
87 //______________________________________________________________________________
88 AliMDC::AliMDC(Int_t compress, Bool_t deleteFiles, EFilterMode filterMode,
89 Double_t maxSizeTagDB, const char* fileNameTagDB,
90 const char *guidFileFolder,
92 fEvent(new AliRawEvent),
97 fEventTag(new AliRawEventTag),
99 fBasketSize(basketsize),
100 fDeleteFiles(deleteFiles),
101 fFilterMode(filterMode),
104 fIsTagDBCreated(kFALSE),
105 fMaxSizeTagDB(maxSizeTagDB),
106 fFileNameTagDB(fileNameTagDB),
107 fGuidFileFolder(guidFileFolder)
109 // Create MDC processor object.
110 // compress is the file compression mode.
111 // If deleteFiles is kTRUE the raw data files will be deleted after they
113 // If the filterMode if kFilterOff no filter algorithm will be, if it is
114 // kFilterTransparent the algorthims will be run but no events will be
115 // rejected, if it is kFilterOn the filters will be run and the event will
116 // be rejected if all filters return kFALSE.
117 // If maxSizeTagDB is greater than 0 it determines the maximal size of the
118 // tag DB and then fileNameTagDB is the directory name for the tag DB.
119 // Otherwise fileNameTagDB is the file name of the tag DB. If it is NULL
120 // no tag DB will be created.
121 // Optional 'guidFileFolder' specifies the folder in which *.guid files
122 // will be stored. In case this option is not given, the *.guid files
123 // will be written to the same folder as the raw-data files.
125 // Set the maximum tree size to 19GB
126 // in order to allow big raw data files
127 TTree::SetMaxTreeSize(20000000000LL);
129 // This line is needed in case of a stand-alone application w/o
130 // $ROOTSYS/etc/system.rootrc file
131 gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo",
137 if (fFilterMode != kFilterOff) {
138 fESD = new AliESDEvent();
141 // Create the guid files folder if it does not exist
142 if (!fGuidFileFolder.IsNull()) {
143 gSystem->ResetErrno();
144 gSystem->MakeDirectory(fGuidFileFolder.Data());
145 if (gSystem->GetErrno() && gSystem->GetErrno() != EEXIST) {
146 SysError("AliMDC", "mkdir %s", fGuidFileFolder.Data());
150 // install SIGUSR1 handler to allow clean interrupts
151 gSystem->AddSignalHandler(new AliMDCInterruptHandler(this));
153 // create the high level filters
154 if (fFilterMode != kFilterOff) {
155 for (Int_t iFilter = 0; iFilter < kNFilters; iFilter++) {
156 TClass* filterClass = gROOT->GetClass(fgkFilterName[iFilter]);
158 Warning("AliMDC", "no filter class %s found", fgkFilterName[iFilter]);
161 AliFilter* filter = (AliFilter*) filterClass->New();
163 Warning("AliMDC", "creation of filter %s failed", fgkFilterName[iFilter]);
166 fFilters.Add(filter);
171 //______________________________________________________________________________
177 if(fTagDB) delete fTagDB;
185 //______________________________________________________________________________
186 Int_t AliMDC::Open(EWriteMode mode, const char* fileName,
187 Double_t maxFileSize,
188 const char* fs1, const char* fs2)
190 // open a new raw DB file
193 fRawDB = new AliRawRFIODB(fEvent, fESD, fCompress, fileName);
194 else if (mode == kROOTD)
195 fRawDB = new AliRawRootdDB(fEvent, fESD, fCompress, fileName);
196 else if (mode == kCASTOR)
197 fRawDB = new AliRawCastorDB(fEvent, fESD, fCompress, fileName);
198 else if (mode == kDEVNULL)
199 fRawDB = new AliRawNullDB(fEvent, fESD, fCompress, fileName);
201 fRawDB = new AliRawDB(fEvent, fESD, fCompress, fileName);
202 fRawDB->SetDeleteFiles(fDeleteFiles);
204 if (fRawDB->IsZombie()) {
210 if (fileName == NULL) {
211 fRawDB->SetMaxSize(maxFileSize);
212 fRawDB->SetFS(fs1, fs2);
213 if (!fRawDB->Create()) {
220 if (!fRawDB->WriteGuidFile(fGuidFileFolder)) {
226 Info("Open", "Filling raw DB %s\n", fRawDB->GetDBName());
228 // Create AliStats object
229 fStats = new AliStats(fRawDB->GetDBName(), fCompress,
230 fFilterMode != kFilterOff);
234 //______________________________________________________________________________
235 Int_t AliMDC::ProcessEvent(void* event, Bool_t isIovecArray)
237 // Convert the DATE event to an AliRawEvent object and store it in the raw DB,
238 // optionally also run the filter.
239 // event is either a pointer to the streamlined event
240 // or, if isIovecArray is kTRUE, a pointer to an array of iovecs with one
241 // iovec per subevent (used by the event builder).
242 // The return value is the number of written bytes or an error code
243 const Long64_t kFileSizeErrorLevel = 19000000000LL;
245 Long64_t currentFileSize = GetTotalSize();
246 AliDebug(1,Form("current file size is %lld bytes",currentFileSize));
247 if(currentFileSize > kFileSizeErrorLevel) {
248 Error("ProcessEvent", "file size (%lu) exceeds the limit "
254 char* data = (char*) event;
255 if (isIovecArray) data = (char*) ((iovec*) event)[0].iov_base;
257 // Shortcut for easy header access
258 AliRawEventHeaderBase *header = fEvent->GetHeader(data);
261 if ((status = header->ReadHeader(data)) != (Int_t)header->GetHeadSize()) {
265 if (AliDebugLevel() > 2) ToAliDebug(3, header->Dump(););
267 // Check event type and skip "Start of Run", "End of Run",
268 // "Start of Run Files" and "End of Run Files"
269 Int_t size = header->GetEventSize() - header->GetHeadSize();
271 AliDebug(1, Form("Processing %s (%d bytes)", header->GetTypeName(), size));
273 // Amount of data left to read for this event
276 // StartOfRun, EndOfRun etc. events have no payload
277 // Nevertheless, store the event headers in the tree
280 // If there is less data for this event than the next sub-event
281 // header, something is wrong. Skip to next event...
282 if (toRead < (Int_t)header->GetHeadSize()) {
283 Error("ProcessEvent", "header size (%d) exceeds number of bytes "
284 "to read (%d)", header->GetHeadSize(), toRead);
285 if (AliDebugLevel() > 0) ToAliDebug(1, header->Dump(););
286 return kErrHeaderSize;
289 // Loop over all sub-events... (LDCs)
292 if (isIovecArray) data = (char*) ((iovec*) event)[nsub].iov_base;
294 AliDebug(1, Form("reading LDC %d", nsub));
296 AliRawEvent *subEvent = fEvent->NextSubEvent();
298 // Read sub-event header
299 AliRawEventHeaderBase *subHeader = subEvent->GetHeader(data);
300 if ((status = subHeader->ReadHeader(data)) != (Int_t)subHeader->GetHeadSize()) {
301 return kErrSubHeader;
304 if (AliDebugLevel() > 2) ToAliDebug(3, subHeader->Dump(););
306 toRead -= subHeader->GetHeadSize();
308 Int_t rawSize = subHeader->GetEventSize() - subHeader->GetHeadSize();
310 // Make sure raw data less than left over bytes for current event
311 if (rawSize > toRead) {
312 Warning("ProcessEvent", "raw data size (%d) exceeds number of "
313 "bytes to read (%d)\n", rawSize, toRead);
314 if (AliDebugLevel() > 0) ToAliDebug(1, subHeader->Dump(););
318 // Read Equipment Headers (in case of physics or calibration event)
319 if (header->Get("Type") == AliRawEventHeaderBase::kPhysicsEvent ||
320 header->Get("Type") == AliRawEventHeaderBase::kCalibrationEvent ||
321 header->Get("Type") == AliRawEventHeaderBase::kSystemSoftwareTriggerEvent ||
322 header->Get("Type") == AliRawEventHeaderBase::kDetectorSoftwareTriggerEvent) {
323 while (rawSize > 0) {
324 AliRawEquipment &equipment = *subEvent->NextEquipment();
325 AliRawEquipmentHeader &equipmentHeader =
326 *equipment.GetEquipmentHeader();
327 Int_t equipHeaderSize = equipmentHeader.HeaderSize();
328 if ((status = ReadEquipmentHeader(equipmentHeader, header->DataIsSwapped(),
329 data)) != equipHeaderSize) {
330 return kErrEquipmentHeader;
333 if (AliDebugLevel() > 2) ToAliDebug(3, equipmentHeader.Dump(););
335 toRead -= equipHeaderSize;
336 rawSize -= equipHeaderSize;
338 // Read equipment raw data
339 AliRawData &subRaw = *equipment.GetRawData();
341 Int_t eqSize = equipmentHeader.GetEquipmentSize() - equipHeaderSize;
342 if ((status = ReadRawData(subRaw, eqSize, data)) != eqSize) {
343 return kErrEquipment;
350 } else { // Read only raw data but no equipment header
352 AliRawEquipment &equipment = *subEvent->NextEquipment();
353 AliRawData &subRaw = *equipment.GetRawData();
354 if ((status = ReadRawData(subRaw, rawSize, data)) != rawSize) {
355 return kErrEquipment;
365 // High Level Event Filter
366 if (fFilterMode != kFilterOff) {
367 if (header->Get("Type") == AliRawEventHeaderBase::kPhysicsEvent ||
368 header->Get("Type") == AliRawEventHeaderBase::kCalibrationEvent ||
369 header->Get("Type") == AliRawEventHeaderBase::kSystemSoftwareTriggerEvent ||
370 header->Get("Type") == AliRawEventHeaderBase::kDetectorSoftwareTriggerEvent) {
371 Bool_t result = kFALSE;
372 for (Int_t iFilter = 0; iFilter < fFilters.GetEntriesFast(); iFilter++) {
373 AliFilter* filter = (AliFilter*) fFilters[iFilter];
374 if (!filter) continue;
375 if (filter->Filter(fEvent, fESD)) result = kTRUE;
377 if ((fFilterMode == kFilterOn) && !result) return kFilterReject;
381 // Set stat info for first event of this file
382 if (fRawDB->GetEvents() == 0)
383 fStats->SetFirstId(header->Get("RunNb"), header->GetP("Id")[0]);
385 // Store raw event in tree
386 Int_t nBytes = fRawDB->Fill();
388 // Fill the event tag object
389 fEventTag->SetHeader(fEvent->GetHeader());
390 fEventTag->SetGUID(fRawDB->GetDB()->GetUUID().AsString());
391 fEventTag->SetEventNumber(fRawDB->GetEvents()-1);
393 // Create Tag DB here only after the raw data header
394 // version was already identified
395 if (!fIsTagDBCreated) {
396 if (!fFileNameTagDB.IsNull()) {
397 if (fMaxSizeTagDB > 0) {
398 fTagDB = new AliTagDB(fEventTag, NULL);
399 fTagDB->SetMaxSize(fMaxSizeTagDB);
400 fTagDB->SetFS(fFileNameTagDB.Data());
401 if (!fTagDB->Create()) return kErrTagFile;
403 fTagDB = new AliTagDB(fEventTag, fFileNameTagDB.Data());
404 if (fTagDB->IsZombie()) return kErrTagFile;
407 fIsTagDBCreated = kTRUE;
410 // Store event tag in tree
411 if (fTagDB) fTagDB->Fill();
413 // Make top event object ready for next event data
415 // Clean up HLT ESD for the next event
416 if (fESD) fESD->Reset();
424 //______________________________________________________________________________
425 Long64_t AliMDC::GetTotalSize()
427 // return the total current raw DB file size
429 if (!fRawDB) return -1;
431 return fRawDB->GetTotalSize();
434 //______________________________________________________________________________
435 Long64_t AliMDC::Close()
437 // close the current raw DB file
439 if (!fRawDB) return -1;
441 fRawDB->WriteStats(fStats);
442 Long64_t filesize = fRawDB->Close();
450 //______________________________________________________________________________
451 Long64_t AliMDC::AutoSave()
453 // Auto-save the raw-data
454 // and esd (if any) trees
456 if (!fRawDB) return -1;
458 return fRawDB->AutoSave();
461 //______________________________________________________________________________
462 Int_t AliMDC::Run(const char* inputFile, Bool_t loop,
463 EWriteMode mode, Double_t maxFileSize,
464 const char* fs1, const char* fs2)
466 // Run the MDC processor. Read from the input stream and only return
467 // when the input gave and EOF or a fatal error occured. On success 0
468 // is returned, 1 in case of a fatality.
469 // inputFile is the name of the DATE input file; if NULL the input will
470 // be taken from the event builder.
471 // If loop is set the same input file will be reused in an infinite loop.
472 // mode specifies the type of the raw DB.
473 // maxFileSize is the maximal size of the raw DB.
474 // fs1 and fs2 are the file system locations of the raw DB.
476 Info("Run", "input = %s, rawdb size = %f, filter = %s, "
477 "looping = %s, compression = %d, delete files = %s",
478 inputFile ? inputFile : "event builder", maxFileSize,
479 fFilterMode == kFilterOff ? "off" :
480 (fFilterMode == kFilterOn ? "on" : "transparent"),
481 loop ? "yes" : "no", fCompress, fDeleteFiles ? "yes" : "no");
483 // Open the input file
486 if ((fd = open(inputFile, O_RDONLY)) == -1) {
487 Error("Run", "cannot open input file %s", inputFile);
492 // Used for statistics
495 Double_t told = 0, tnew = 0;
496 Float_t chunkSize = maxFileSize/100, nextChunk = chunkSize;
498 // Create new raw DB.
501 if (Open(mode,NULL,maxFileSize,fs1,fs2) < 0) return 1;
503 // Process input stream
508 UInt_t eventSize = 0;
511 AliRawEventHeaderBase header;
515 // If we were in looping mode stop directly after a SIGUSR1 signal
517 Info("Run", "Stopping loop, processed %d events", numEvents);
521 if (!inputFile) { // get data from event builder
523 if ((eorFlag = ebEor())) break;
524 if ((event = (char*)ebGetNextEvent()) == (char*)-1) {
525 Error("Run", "error getting next event (%s)", ebGetLastError());
529 // no event, sleep for 1 second and try again
530 gSystem->Sleep(1000);
534 Error("Run", "AliMDC was compiled without event builder support");
542 } else { // get data from a file
545 if ((nrecv = Read(fd, header.HeaderBaseBegin(), header.HeaderBaseSize())) !=
546 header.HeaderBaseSize()) {
547 if (nrecv == 0) { // eof
549 ::lseek(fd, 0, SEEK_SET);
555 Error("Run", "error reading base header");
562 char *data = (char *)header.HeaderBaseBegin();
563 AliRawEventHeaderBase *hdr = AliRawEventHeaderBase::Create(data);
565 if ((nrecv = Read(fd, hdr->HeaderBegin(), hdr->HeaderSize())) !=
567 if (nrecv == 0) { // eof
569 ::lseek(fd, 0, SEEK_SET);
577 Error("Run", "error reading header");
584 if (eventSize < hdr->GetEventSize()) {
586 eventSize = 2 * hdr->GetEventSize();
587 event = new char[eventSize];
589 memcpy(event, header.HeaderBaseBegin(), header.HeaderBaseSize());
590 memcpy(event+hdr->HeaderBaseSize(), hdr->HeaderBegin(), hdr->HeaderSize());
591 if (hdr->GetExtendedDataSize() != 0)
592 memcpy(event+hdr->HeaderBaseSize()+hdr->HeaderSize(),
593 hdr->GetExtendedData(), hdr->GetExtendedDataSize());
594 Int_t size = hdr->GetEventSize() - hdr->GetHeadSize();
595 if (Read(fd, event + hdr->GetHeadSize(), size) != size) {
596 Error("Run", "error reading data");
605 Int_t result = ProcessEvent(event, !inputFile);
607 Error("Run", "error writing data. Error code: %d",result);
612 printf("Processed event %d (%d)\n", numEvents, fRawDB->GetEvents());
616 // Filling time statistics
617 if (fRawDB->GetBytesWritten() > nextChunk) {
618 tnew = timer.RealTime();
619 fStats->Fill(tnew-told);
622 nextChunk += chunkSize;
625 // Check size of raw db. If bigger than maxFileSize, close file
626 // and continue with new file.
627 if (fRawDB->GetBytesWritten() > maxFileSize) {
629 printf("Written raw DB at a rate of %.1f MB/s\n",
630 fRawDB->GetBytesWritten() / timer.RealTime() / 1000000.);
632 // Write stats object to raw db, run db, MySQL and AliEn
633 fRawDB->WriteStats(fStats);
637 if (!fRawDB->NextFile()) {
638 Error("Run", "error opening next raw data file");
640 if (inputFile) delete[] event;
644 printf("Filling raw DB %s\n", fRawDB->GetDBName());
645 fStats = new AliStats(fRawDB->GetDBName(), fCompress,
646 fFilterMode != kFilterOff);
650 nextChunk = chunkSize;
653 // Check size of tag db
654 if (fTagDB && fTagDB->FileFull()) {
655 if (!fTagDB->NextFile()) {
659 printf("Filling tag DB %s\n", fTagDB->GetDBName());
664 // Make top event object ready for next event data
665 //printf("Event %d has %d sub-events\n", numEvents, fEvent->GetNSubEvents());
667 // Clean up HLT ESD for the next event
668 // if (fESD) fESD->Reset();
672 if (!ebReleaseEvent((iovec*)event)) {
673 Error("Run", "problem releasing event (%s)", ebGetLastError());
680 printf("Written raw DB at a rate of %.1f MB/s\n",
681 fRawDB->GetBytesWritten() / timer.RealTime() / 1000000.);
683 // Write stats to raw db and run db and delete stats object
690 Info("Run", "event builder reported end of run (%d)", eorFlag);
694 // Close input source
702 //______________________________________________________________________________
703 Int_t AliMDC::Read(Int_t fd, void *buffer, Int_t length)
705 // Read exactly length bytes into buffer. Returns number of bytes
706 // received, returns -1 in case of error and 0 for EOF.
710 if (fd < 0) return -1;
713 char *buf = (char *)buffer;
715 for (n = 0; n < length; n += nrecv) {
716 if ((nrecv = read(fd, buf+n, length-n)) <= 0) {
720 SysError("Read", "read");
727 //______________________________________________________________________________
728 Int_t AliMDC::ReadEquipmentHeader(AliRawEquipmentHeader &header,
729 Bool_t isSwapped, char*& data)
731 // Read equipment header info from DATE data stream. Returns bytes read
732 // (i.e. AliRawEquipmentHeader::HeaderSize()), -1 in case of error and
733 // 0 for EOF. If isSwapped is kTRUE the event data is byte swapped
734 // and we will swap the header to host format.
736 memcpy(header.HeaderBegin(), data, header.HeaderSize());
737 data += header.HeaderSize();
739 // Swap equipment header data if needed
743 if (header.GetEquipmentSize() < (UInt_t)header.HeaderSize()) {
744 Error("ReadEquipmentHeader", "invalid equipment header size");
745 // try recovery... how?
749 return header.HeaderSize();
752 //______________________________________________________________________________
753 Int_t AliMDC::ReadRawData(AliRawData &raw, Int_t size, char*& data)
755 // Read raw data from DATE data stream. Returns bytes read (i.e.
756 // size), -1 in case of error and 0 for EOF.
758 raw.SetBuffer(data, size);
764 //______________________________________________________________________________
767 // Stop the event loop
770 if (fRawDB) fRawDB->Stop();