1 // @(#)alimdc:$Name$:$Id$
2 // Author: Fons Rademakers 26/11/99
3 // Updated: Dario Favretto 15/04/2003
8 #include <sys/statvfs.h>
10 #if defined(__APPLE__)
11 #include <sys/param.h>
12 #include <sys/mount.h>
25 #include <TStopwatch.h>
26 #include <TSQLServer.h>
27 #include <TSQLResult.h>
31 #if defined(__APPLE__)
34 #include "AliRawEvent.h"
38 #include "DateEvent.h"
41 #include "libDateEb.h"
46 ClassImp(AliRawEventHeader)
47 ClassImp(AliRawEquipmentHeader)
51 ClassImp(AliRawRFIODB)
52 ClassImp(AliRawCastorDB)
53 ClassImp(AliRawRootdDB)
54 ClassImp(AliRawNullDB)
56 ClassImp(AliTagNullDB)
60 // Which MDC is this...
63 // Fixed file system locations for the different DB's
65 const char* const kFifo = "/tmp/alimdc.fifo";
66 const char* const kRawDBFS[2] = { "/tmp/mdc1", "/tmp/mdc2" };
67 const char* const kTagDBFS = "/tmp/mdc1/tags";
68 const char* const kRunDBFS = "/tmp/mdc1/meta";
69 const char* const kRFIOFS = "rfio:/castor/cern.ch/user/r/rdm";
70 const char* const kCastorFS = "castor:/castor/cern.ch/user/r/rdm";
71 const char* const kRootdFS = "root://localhost//tmp/mdc1";
72 const char* const kAlienHost = "alien://aliens7.cern.ch:15000/?direct";
73 const char* const kAlienDir = "/alice_mdc/DC";
75 const char* const kFifo = "/tmp/alimdc.fifo";
76 const char* const kRawDBFS[2] = { "/data1/mdc", "/data2/mdc" };
77 const char* const kTagDBFS = "/data1/mdc/tags";
78 const char* const kRunDBFS = "/data1/mdc/meta";
79 const char* const kRFIOFS = "rfio:/castor/cern.ch/lcg/dc5";
80 const char* const kCastorFS = "castor:/castor/cern.ch/lcg/dc5";
81 const char* const kRootdFS = "root://localhost//tmp/mdc1";
82 const char* const kAlienHost = "alien://aliens7.cern.ch:15000/?direct";
83 const char* const kAlienDir = "/alice_mdc/DC";
86 // Maximum size of tag db files
87 const Double_t kMaxTagFileSize = 2.5e8; // 250MB
89 Bool_t AliMDC::fgDeleteFiles = kFALSE;
94 //______________________________________________________________________________
95 Bool_t AliRawEventHeader::DataIsSwapped() const
97 // Returns true if event data is swapped.
99 if (TEST_SYSTEM_ATTRIBUTE(fTypeAttribute, ATTR_EVENT_SWAPPED))
104 //______________________________________________________________________________
105 void AliRawEventHeader::Swap()
110 fSize = net2host(fSize);
111 fMagic = net2host(fMagic);
112 fHeadLen = net2host(fHeadLen);
113 fVersion = net2host(fVersion);
114 fType = net2host(fType);
115 fRunNb = net2host(fRunNb);
116 for (int i = 0; i < kIdWords; i++)
117 fId[i] = net2host(fId[i]);
118 for (int i = 0; i < kTriggerWords; i++)
119 fTriggerPattern[i] = net2host(fTriggerPattern[i]);
120 for (int i = 0; i < kDetectorWords; i++)
121 fDetectorPattern[i] = net2host(fDetectorPattern[i]);
122 for (int i = 0; i < kAttributeWords; i++)
123 fTypeAttribute[i] = net2host(fTypeAttribute[i]);
124 fLDCId = net2host(fLDCId);
125 fGDCId = net2host(fGDCId);
129 //______________________________________________________________________________
130 UInt_t AliRawEventHeader::GetEventInRun() const
132 // Get event number in run. Correct for fixed target mode which is used
133 // in the Data Challenge Setup.
135 if (!TEST_SYSTEM_ATTRIBUTE(fTypeAttribute, ATTR_ORBIT_BC)) {
136 return EVENT_ID_GET_NB_IN_RUN(fId);
141 //______________________________________________________________________________
142 const char *AliRawEventHeader::GetTypeName() const
144 // Get event type as a string.
148 return "START_OF_RUN";
153 case kStartOfRunFiles:
154 return "START_OF_RUN_FILES";
157 return "END_OF_RUN_FILES";
160 return "START_OF_BURST";
163 return "END_OF_BURST";
166 return "PHYSICS_EVENT";
168 case kCalibrationEvent:
169 return "CALIBRATION_EVENT";
172 return "EVENT_FORMAT_ERROR";
175 return "*** UNKNOWN EVENT TYPE ***";
181 //______________________________________________________________________________
182 void AliRawEquipmentHeader::Swap()
184 // Swap equipment header data. There is no way to see if the data
185 // has already been swapped. This method is only called when the
186 // header is read from the DATE event builder (GDC).
188 fSize = net2host(fSize);
189 fEquipmentType = net2host(fEquipmentType);
190 fEquipmentID = net2host(fEquipmentID);
191 fBasicElementSizeType = net2host(fBasicElementSizeType);
192 for (int i = 0; i < kAttributeWords; i++)
193 fTypeAttribute[i] = net2host(fTypeAttribute[i]);
197 //______________________________________________________________________________
198 AliRawEvent::AliRawEvent()
200 // Create ALICE event object. If ownData is kFALSE we will use a static
201 // raw data object, otherwise a private copy will be made.
210 //______________________________________________________________________________
211 AliRawEventHeader *AliRawEvent::GetHeader()
213 // Get event header part of AliRawEvent.
216 fEvtHdr = new AliRawEventHeader;
221 //______________________________________________________________________________
222 AliRawEquipmentHeader *AliRawEvent::GetEquipmentHeader()
224 // Get equipment header part of AliRawEvent.
227 fEqpHdr = new AliRawEquipmentHeader;
232 //______________________________________________________________________________
233 AliRawData *AliRawEvent::GetRawData()
235 // Get raw data part of AliRawEvent.
238 fRawData = new AliRawData;
243 //______________________________________________________________________________
244 AliRawEvent *AliRawEvent::NextSubEvent()
246 // Returns next sub-event object.
249 fSubEvents = new TObjArray(100); // arbitrary, probably enough to prevent resizing
251 if (fSubEvents->GetSize() <= fNSubEvents) {
252 fSubEvents->Expand(fNSubEvents+10);
253 Warning("NextSubEvent", "expanded fSubEvents by 10 to %d",
254 fSubEvents->GetSize());
258 if (!(ev = (AliRawEvent *)fSubEvents->At(fNSubEvents))) {
259 ev = new AliRawEvent;
260 fSubEvents->AddAt(ev, fNSubEvents);
268 //______________________________________________________________________________
269 AliRawEvent *AliRawEvent::GetSubEvent(Int_t index) const
271 // Get specified sub event. Returns 0 if sub event does not exist.
276 return (AliRawEvent *) fSubEvents->At(index);
279 //______________________________________________________________________________
280 void AliRawEvent::Reset()
282 // Reset the event in case it needs to be re-used (avoiding costly
283 // new/delete cycle). We reset the size marker for the AliRawData
284 // objects and the sub event counter.
286 for (int i = 0; i < fNSubEvents; i++) {
287 AliRawEvent *ev = (AliRawEvent *)fSubEvents->At(i);
288 ev->GetRawData()->SetSize(0);
293 //______________________________________________________________________________
294 AliRawEvent::~AliRawEvent()
296 // Clean up event object. Delete also, possible, private raw data.
302 fSubEvents->Delete();
306 //______________________________________________________________________________
307 AliStats::AliStats(const char *filename, Int_t compmode, Bool_t filter)
309 // Create statistics object.
317 fFileName = filename;
318 fCompMode = compmode;
323 //______________________________________________________________________________
324 AliStats::~AliStats()
326 // Cleanup stats object.
331 //______________________________________________________________________________
332 AliStats &AliStats::operator=(const AliStats &rhs)
334 // AliStats assignment operator.
337 TObject::operator=(rhs);
338 fEvents = rhs.fEvents;
339 fFirstRun = rhs.fFirstRun;
340 fFirstEvent = rhs.fFirstEvent;
341 fLastRun = rhs.fLastRun;
342 fLastEvent = rhs.fLastEvent;
345 fFileName = rhs.fFileName;
346 fFileSize = rhs.fFileSize;
347 fCompFactor = rhs.fCompFactor;
348 fCompMode = rhs.fCompMode;
349 fFilter = rhs.fFilter;
350 fRTHist = rhs.fRTHist ? (TH1F*) rhs.fRTHist->Clone() : 0;
356 //______________________________________________________________________________
357 void AliStats::Fill(Float_t time)
359 // Fill histogram. This histogram shows the (hopefully constant) time
360 // it takes to fill the ROOT DB.
361 // Expects to be called 100 times for each file.
364 fRTHist = new TH1F("rtime","Real-time to write data chunk", 100, 0, 100);
365 fRTHist->SetDirectory(0);
368 fRTHist->Fill(fChunk, time);
372 //______________________________________________________________________________
373 void AliStats::WriteToDB(AliRawDB *rawdb)
375 // Write stats to raw DB, local run DB and global MySQL DB.
377 AliRawEventHeader &header = *rawdb->GetEvent()->GetHeader();
379 // Write stats into RawDB
380 TDirectory *ds = gDirectory;
381 rawdb->GetDB()->cd();
382 SetEvents(rawdb->GetEvents());
383 SetLastId(header.GetRunNumber(), header.GetEventInRun());
384 SetFileSize(rawdb->GetBytesWritten());
385 SetCompressionFactor(rawdb->GetCompressionFactor());
390 // Write stats also in the bookkeeping RunDB
391 AliRunDB *rundb = new AliRunDB(kTRUE);
393 rundb->UpdateRDBMS(this);
394 rundb->UpdateAliEn(this);
398 //______________________________________________________________________________
399 AliRawDB::AliRawDB(AliRawEvent *event, Double_t maxsize, Int_t compress,
402 // Create a new raw DB containing at most maxsize bytes.
406 fCompress = compress;
408 // Consistency check with DATE header file
409 if (fEvent->GetHeader()->HeaderSize() != EVENT_HEAD_BASE_SIZE) {
410 Error("AliRawDB", "inconsistency between DATE and AliRawEvent headers");
421 //______________________________________________________________________________
422 Bool_t AliRawDB::FSHasSpace(const char *fs) const
424 // Check for at least fMaxSize bytes of free space on the file system.
425 // If the space is not available return kFALSE, kTRUE otherwise.
427 Long_t id, bsize, blocks, bfree;
429 if (gSystem->GetFsInfo(fs, &id, &bsize, &blocks, &bfree) == 1) {
430 Error("FSHasSpace", "could not stat file system %s", fs);
434 // Leave 5 percent of diskspace free
435 Double_t avail = Double_t(bfree) * 0.95;
436 if (avail*bsize > fMaxSize)
439 Warning("FSHasSpace", "no space on file system %s", fs);
443 //______________________________________________________________________________
444 const char *AliRawDB::GetFileName() const
446 // Return filename based on hostname and date and time. This will make
447 // each file unique. Also makes sure (via FSHasSpace()) that there is
448 // enough space on the file system to store the file. Returns 0 in
449 // case of error or interrupt signal.
451 static TString fname;
452 static Bool_t fstoggle = kFALSE;
454 TString fs = fstoggle ? kRawDBFS[1] : kRawDBFS[0];
457 TString hostname = gSystem->HostName();
459 if ((pos = hostname.Index(".")) != kNPOS)
460 hostname.Remove(pos);
462 if (!FSHasSpace(fs)) {
464 fstoggle = !fstoggle;
465 fs = fstoggle ? kRawDBFS[1] : kRawDBFS[0];
466 if (FSHasSpace(fs)) break;
467 Info("GetFileName", "sleeping 30 seconds before retrying...");
468 gSystem->Sleep(30000); // sleep for 30 seconds
469 if (gAliMDC && gAliMDC->StopLoop())
474 fname = fs + "/" + hostname + "_";
475 fname += dt.GetDate();
477 fname += dt.GetTime();
480 fstoggle = !fstoggle;
485 //______________________________________________________________________________
486 Bool_t AliRawDB::Create()
488 // Create a new raw DB.
490 const Int_t kMaxRetry = 200;
491 const Int_t kMaxSleep = 1; // seconds
492 const Int_t kMaxSleepLong = 10; // seconds
496 if (gAliMDC && gAliMDC->StopLoop())
499 const char *fname = GetFileName();
501 Error("Create", "error getting raw DB file name");
507 fRawDB = TFile::Open(fname, GetOpenOption(),
508 Form("ALICE MDC%d raw DB", kMDC), fCompress,
511 if (retry < kMaxRetry) {
512 Warning("Create", "failure to open file, sleeping %d %s before retrying...",
513 kMaxSleep, kMaxSleep==1 ? "second" : "seconds");
514 gSystem->Sleep(kMaxSleep*1000);
517 Error("Create", "failure to open file %s after %d tries", fname, kMaxRetry);
521 Warning("Create", "succeeded to open file after %d retries", retry);
523 if (fRawDB->IsZombie()) {
524 if (fRawDB->GetErrno() == ENOSPC ||
525 fRawDB->GetErrno() == 1018 || // SECOMERR
526 fRawDB->GetErrno() == 1027) { // SESYSERR
527 fRawDB->ResetErrno();
529 Warning("Create", "file is a zombie (no space), sleeping %d %s before retrying...",
530 kMaxSleepLong, kMaxSleepLong==1 ? "second" : "seconds");
531 gSystem->Sleep(kMaxSleepLong*1000); // sleep 10 seconds before retrying
534 Error("Create", "file %s is zombie", fname);
535 fRawDB->ResetErrno();
538 if (retry < kMaxRetry) {
539 Warning("Create", "file is a zombie, sleeping %d %s before retrying...",
540 kMaxSleep, kMaxSleep==1 ? "second" : "seconds");
541 gSystem->Sleep(kMaxSleep*1000);
544 Error("Create", "failure to open file %s after %d tries", fname, kMaxRetry);
548 // Create raw data TTree
554 //______________________________________________________________________________
555 void AliRawDB::MakeTree()
557 // Create ROOT Tree object container.
559 fTree = new TTree("RAW", Form("ALICE MDC%d raw data tree", kMDC));
560 fTree->SetAutoSave(2000000000); // autosave when 2 Gbyte written
562 Int_t bufsize = 256000;
563 // splitting 29.6 MB/s, no splitting 35.3 MB/s on P4 2GHz 15k SCSI
566 fTree->Branch("rawevent", "AliRawEvent", &fEvent, bufsize, split);
569 //______________________________________________________________________________
570 void AliRawDB::Close()
581 // Close DB, this also deletes the fTree
584 if (AliMDC::DeleteFiles()) {
585 gSystem->Unlink(fRawDB->GetName());
591 // Create semaphore to say this file is finished
592 Int_t tfd = ::creat(Form("%s.done", fRawDB->GetName()), 0644);
599 //______________________________________________________________________________
600 Bool_t AliRawDB::NextFile()
602 // Close te current file and open a new one.
603 // Returns kFALSE in case opening failed.
607 if (!Create()) return kFALSE;
611 //______________________________________________________________________________
612 Float_t AliRawDB::GetCompressionFactor() const
614 // Return compression factor.
616 if (fTree->GetZipBytes() == 0.)
619 return fTree->GetTotBytes()/fTree->GetZipBytes();
623 //______________________________________________________________________________
624 AliRawRFIODB::AliRawRFIODB(AliRawEvent *event, Double_t maxsize, Int_t compress)
625 : AliRawDB(event, maxsize, compress, kFALSE)
627 // Create a new raw DB that will be accessed via RFIO.
631 // Set STAGE_POOL environment variable to current host
633 // THESE ENVIRONMENT SYMBOLS ARE NOW DEFINED BY THE ALICE DATE SETUP
634 // THEREFORE WE SHALL NOT USE ANY HARDCODED VALUES BUT RATHER USE
635 // WHATEVER HAS BEEN SET IN THE DATE SITE
636 //gSystem->Setenv("STAGE_POOL", "lcg00");
637 //gSystem->Setenv("STAGE_HOST", "stage013");
639 // however for sanity we check if they are really set
640 if (!gSystem->Getenv("STAGE_POOL"))
641 Error("AliRawRFIODB", "STAGE_POOL not set");
642 if (!gSystem->Getenv("STAGE_HOST"))
643 Error("AliRawRFIODB", "STAGE_HOST not set");
651 fRawDB->UseCache(50, 0x200000); //0x100000 = 1MB)
654 //______________________________________________________________________________
655 const char *AliRawRFIODB::GetFileName() const
657 // Return filename based on hostname and date and time. This will make
658 // each file unique. Also the directory will be made unique for each
659 // day by adding the date to the fs. Assumes there is always enough
660 // space on the device.
662 static TString fname;
664 TString fs = kRFIOFS;
667 // make a new subdirectory for each day
671 Long_t id, size, flags, time;
672 if (gSystem->GetPathInfo(fs, &id, &size, &flags, &time) == 1) {
673 // directory does not exist, create it
674 if (gSystem->mkdir(fs, kTRUE) == -1) {
675 Error("GetFileName", "cannot create dir %s, using %s", fs.Data(),
680 // FIXME: should check if fs is a directory
682 TString hostname = gSystem->HostName();
684 if ((pos = hostname.Index(".")) != kNPOS)
685 hostname.Remove(pos);
687 fname = fs + "/" + hostname + "_";
688 fname += dt.GetDate();
690 fname += dt.GetTime();
696 //______________________________________________________________________________
697 void AliRawRFIODB::Close()
699 // Close raw RFIO DB.
708 // Close DB, this also deletes the fTree
711 if (AliMDC::DeleteFiles()) {
712 TUrl u(fRawDB->GetName());
713 gSystem->Exec(Form("rfrm %s", u.GetFile()));
721 //______________________________________________________________________________
722 AliRawCastorDB::AliRawCastorDB(AliRawEvent *event, Double_t maxsize, Int_t compress)
723 : AliRawDB(event, maxsize, compress, kFALSE)
725 // Create a new raw DB that will be accessed via CASTOR and rootd.
729 // Set STAGE_POOL environment variable to current host
731 // THESE ENVIRONMENT SYMBOLS ARE NOW DEFINED BY THE ALICE DATE SETUP
732 // THEREFORE WE SHALL NOT USE ANY HARDCODED VALUES BUT RATHER USE
733 // WHATEVER HAS BEEN SET IN THE DATE SITE
734 //gSystem->Setenv("STAGE_POOL", "lcg00");
735 //gSystem->Setenv("STAGE_HOST", "stage013");
737 // however for sanity we check if they are really set
738 if (!gSystem->Getenv("STAGE_POOL"))
739 Error("AliRawRFIODB", "STAGE_POOL not set");
740 if (!gSystem->Getenv("STAGE_HOST"))
741 Error("AliRawRFIODB", "STAGE_HOST not set");
749 fRawDB->UseCache(50, 0x200000); //0x100000 = 1MB)
752 //______________________________________________________________________________
753 const char *AliRawCastorDB::GetFileName() const
755 // Return filename based on hostname and date and time. This will make
756 // each file unique. Also the directory will be made unique for each
757 // day by adding the date to the fs. Assumes there is always enough
758 // space on the device.
760 static TString fname;
762 TString fs = kCastorFS;
763 TString fsr = kRFIOFS;
766 // make a new subdirectory for each day
773 Long_t id, size, flags, time;
774 if (gSystem->GetPathInfo(fsr, &id, &size, &flags, &time) == 1) {
775 // directory does not exist, create it
776 if (gSystem->mkdir(fsr, kTRUE) == -1) {
777 Error("GetFileName", "cannot create dir %s, using %s", fsr.Data(),
782 // FIXME: should check if fs is a directory
784 TString hostname = gSystem->HostName();
786 if ((pos = hostname.Index(".")) != kNPOS)
787 hostname.Remove(pos);
789 fname = fs + "/" + hostname + "_";
790 fname += dt.GetDate();
792 fname += dt.GetTime();
798 //______________________________________________________________________________
799 void AliRawCastorDB::Close()
801 // Close raw CASTOR/rootd DB.
810 // Close DB, this also deletes the fTree
813 if (AliMDC::DeleteFiles()) {
814 TUrl u(fRawDB->GetName());
815 gSystem->Exec(Form("rfrm %s", u.GetFile()));
823 //______________________________________________________________________________
824 AliRawRootdDB::AliRawRootdDB(AliRawEvent *event, Double_t maxsize, Int_t compress)
825 : AliRawDB(event, maxsize, compress, kFALSE)
827 // Create a new raw DB that will be accessed via rootd daemon.
832 fRawDB->UseCache(50, 0x200000); //0x100000 = 1MB)
835 //______________________________________________________________________________
836 const char *AliRawRootdDB::GetFileName() const
838 // Return filename based on hostname and date and time. This will make
839 // each file unique. Also the directory will be made unique for each
840 // day by adding the date to the fs. Assumes there is always enough
841 // space on the device.
843 static TString fname;
845 TString fs = kRootdFS;
849 // make a new subdirectory for each day
853 Long_t id, size, flags, time;
854 if (gSystem->GetPathInfo(fs, &id, &size, &flags, &time) == 1) {
855 // directory does not exist, create it
856 if (gSystem->mkdir(fs, kTRUE) == -1) {
857 Error("GetFileName", "cannot create dir %s, using %s", fs.Data(),
862 // FIXME: should check if fs is a directory
865 TString hostname = gSystem->HostName();
867 if ((pos = hostname.Index(".")) != kNPOS)
868 hostname.Remove(pos);
870 fname = fs + "/" + hostname + "_";
871 fname += dt.GetDate();
873 fname += dt.GetTime();
879 //______________________________________________________________________________
880 void AliRawRootdDB::Close()
882 // Close raw rootd DB.
891 // Close DB, this also deletes the fTree
895 // can use services of TFTP
896 if (AliMDC::DeleteFiles())
897 gSystem->Exec(Form("rfrm %s", fRawDB->GetName()));
905 //______________________________________________________________________________
906 AliRawNullDB::AliRawNullDB(AliRawEvent *event, Double_t maxsize, Int_t compress)
907 : AliRawDB(event, maxsize, compress, kFALSE)
909 // Create a new raw DB that will wrtie to /dev/null.
915 //______________________________________________________________________________
916 const char *AliRawNullDB::GetFileName() const
918 // Return /dev/null as filename.
923 //______________________________________________________________________________
924 void AliRawNullDB::Close()
926 // Close raw RFIO DB.
935 // Close DB, this also deletes the fTree
943 //______________________________________________________________________________
944 AliTagDB::AliTagDB(AliRawEventHeader *header, Double_t maxsize, Bool_t create)
957 //______________________________________________________________________________
958 Bool_t AliTagDB::Create()
960 // Create a new tag DB.
962 fTagDB = new TFile(GetFileName(), "RECREATE",
963 Form("ALICE MDC%d tag DB", kMDC), 1);
964 if (fTagDB->IsZombie()) {
965 Error("Create", "error opening tag DB");
970 // Create ROOT Tree object container
971 fTree = new TTree("TAG", Form("ALICE MDC%d header data tree", kMDC));
972 fTree->SetAutoSave(100000000); // autosave when 100 Mbyte written
974 Int_t bufsize = 32000;
976 fTree->Branch("header", "AliRawEventHeader", &fHeader, bufsize, split);
981 //______________________________________________________________________________
982 void AliTagDB::Close()
993 // Close DB, this also deletes the fTree
996 if (AliMDC::DeleteFiles())
997 gSystem->Unlink(fTagDB->GetName());
1003 //______________________________________________________________________________
1004 Bool_t AliTagDB::NextFile()
1006 // Close te current file and open a new one.
1007 // Returns kFALSE in case opening failed.
1011 if (!Create()) return kFALSE;
1015 //______________________________________________________________________________
1016 Float_t AliTagDB::GetCompressionFactor() const
1018 // Return compression factor.
1020 if (fTree->GetZipBytes() == 0.)
1023 return fTree->GetTotBytes()/fTree->GetZipBytes();
1026 //______________________________________________________________________________
1027 const char *AliTagDB::GetFileName() const
1029 // Return filename based on hostname and date and time. This will make
1030 // each file unique. The tags will be stored in the /data1/tags directory.
1032 static char fname[64];
1033 const char *fs = kTagDBFS;
1035 // check that fs exists (crude check fails if fs is a file)
1036 gSystem->MakeDirectory(fs);
1040 strcpy(hostname, gSystem->HostName());
1043 if ((s = strchr(hostname, '.')))
1048 sprintf(fname, "%s/%s_%d_%d.root", fs, hostname, dt.GetDate(), dt.GetTime());
1054 //______________________________________________________________________________
1055 AliTagNullDB::AliTagNullDB(AliRawEventHeader *header, Double_t maxsize) :
1056 AliTagDB(header, maxsize, kFALSE)
1058 // Create tag db writing to /dev/null.
1064 //______________________________________________________________________________
1065 const char *AliTagNullDB::GetFileName() const
1067 // Return /dev/null as filename.
1072 //______________________________________________________________________________
1073 void AliTagNullDB::Close()
1075 // Close null tag DB.
1077 if (!fTagDB) return;
1084 // Close DB, this also deletes the fTree
1092 //______________________________________________________________________________
1093 AliRunDB::AliRunDB(Bool_t noLocalDB)
1095 // Open run database, and get or create tree.
1099 if (noLocalDB) return;
1102 char hostname[64], filename[64];
1103 const char *fs = kRunDBFS;
1105 // check that fs exists (crude check fails if fs is a file)
1106 gSystem->MakeDirectory(fs);
1108 strcpy(hostname, gSystem->HostName());
1111 if ((s = strchr(hostname, '.')))
1114 sprintf(filename, "%s/%s_rundb.root", fs, hostname);
1116 if (!gSystem->AccessPathName(filename, kFileExists))
1117 fRunDB = new TFile(filename, "UPDATE");
1119 fRunDB = new TFile(filename, "CREATE", Form("ALICE MDC%d Run DB", kMDC));
1122 //______________________________________________________________________________
1123 void AliRunDB::Update(AliStats *stats)
1125 // Add stats object to database.
1127 if (!stats || !fRunDB) return;
1129 TDirectory *ds = gDirectory;
1133 char *s = (char*)strrchr(stats->GetFileName(), '/');
1138 strcpy(sname, stats->GetFileName());
1139 s = strchr(sname, '.');
1142 stats->Write(sname);
1147 //______________________________________________________________________________
1148 void AliRunDB::UpdateRDBMS(AliStats *stats)
1150 // Add stats object to central MySQL DB.
1155 char bt[25], et[25];
1157 strcpy(bt, stats->GetBeginTime().AsSQLString());
1158 strcpy(et, stats->GetEndTime().AsSQLString());
1160 sprintf(sql, "INSERT INTO mdc%dcatalog VALUES (0, '%s', %d, "
1161 "%d, %d, %d, %d, %d, %d, %.2f, '%s', '%s', '%s')", kMDC,
1162 stats->GetFileName(), (int)stats->GetFileSize(), stats->GetEvents(),
1163 stats->GetFirstRun(), stats->GetFirstEvent(), stats->GetLastRun(),
1164 stats->GetLastEvent(), stats->GetCompressionMode(),
1165 stats->GetCompressionFactor(), stats->GetFilterState() ? "on" : "off",
1168 // open connection to MySQL server on pcsalo
1169 TSQLServer *db = TSQLServer::Connect("mysql://pcsalo.cern.ch/mdc", "alice", "amdc");
1171 if (!db || db->IsZombie()) {
1172 Error("UpdateRDBMS", "failed to connect to MySQL server on pcsalo");
1173 printf("%s\n", sql);
1178 TSQLResult *res = db->Query(sql);
1181 Error("UpdateRDBMS", Form("insert into mdc%dcatalog failed", kMDC));
1182 printf("%s\n", sql);
1189 //______________________________________________________________________________
1190 void AliRunDB::UpdateAliEn(AliStats *stats)
1192 // Record file in AliEn catalog.
1196 TGrid *g = TGrid::Connect(kAlienHost, "");
1198 TString lfn = kAlienDir;
1201 // make a subdirectory for each day
1203 lfn += dt.GetDate();
1205 // check if directory exists, if not create it
1206 Grid_ResultHandle_t res = 0;
1207 if (!(res = g->OpenDir(lfn))) {
1208 // directory does not exist, create it
1209 if (g->Mkdir(lfn) == -1) {
1210 Error("UpdateAliEn", "cannot create directory %s", lfn.Data());
1214 if (res) g->CloseResult(res);
1217 lfn += gSystem->BaseName(stats->GetFileName());
1219 Int_t result = g->AddFile(lfn, stats->GetFileName(),
1220 (int)stats->GetFileSize());
1223 Error("UpdateAliEn", "error adding file to AliEn catalog");
1224 printf("AliEn: AddFile(%s, %s, %d)\n", lfn.Data(), stats->GetFileName(),
1225 (int)stats->GetFileSize());
1231 //______________________________________________________________________________
1232 void AliRunDB::Close()
1234 // Close run database.
1236 if (fRunDB) fRunDB->Close();
1240 //----------------- Use SIGUSR1 to interupt endless loop -----------------------
1241 class AliMDCInterruptHandler : public TSignalHandler {
1243 AliMDCInterruptHandler(AliMDC *mdc) : TSignalHandler(kSigUser1, kFALSE), fMDC(mdc) { }
1245 Info("Notify", "received a SIGUSR1 signal");
1246 fMDC->SetStopLoop();
1250 AliMDC *fMDC; // alimdc to signal
1252 AliMDCInterruptHandler(const AliMDCInterruptHandler &);
1253 void operator=(const AliMDCInterruptHandler &);
1256 //______________________________________________________________________________
1257 AliMDC::AliMDC(Int_t fd, Int_t compress, Double_t maxFileSize, Bool_t useFilter,
1258 EWriteMode mode, Bool_t useLoop, Bool_t delFiles)
1260 // Create MDC processor object.
1263 fCompress = compress;
1264 fMaxFileSize = maxFileSize;
1265 fUseFilter = useFilter;
1273 fgDeleteFiles = delFiles;
1277 if (!ebRegister()) {
1278 Error("AliMDC", "cannot register with the event builder (%s)",
1284 if ((mkfifo(kFifo, 0644) < 0) && (errno != EEXIST)) {
1285 Error("AliMDC", "cannot create fifo %s", kFifo);
1288 if ((chmod(kFifo, 0666) == -1) && (errno != EPERM)) {
1289 Error("AliMDC", "cannot change permission of fifo %s", kFifo);
1292 if ((fFd = open(kFifo, O_RDONLY)) == -1) {
1293 Error("AliMDC", "cannot open input file %s", kFifo);
1301 printf("<AliMDC::AliMDC>: input = %s, rawdb size = %f, filter = %s, "
1302 "looping = %s, compression = %d, delete files = %s",
1303 fUseFifo ? "fifo" : (fUseEb ? "eb" : "file"), fMaxFileSize,
1304 fUseFilter ? "on" : "off", fUseLoop ? "yes" : "no", fCompress,
1305 fgDeleteFiles ? "yes" : "no");
1306 if (fWriteMode == kRFIO)
1307 printf(", use RFIO\n");
1308 else if (fWriteMode == kROOTD)
1309 printf(", use rootd\n");
1310 else if (fWriteMode == kCASTOR)
1311 printf(", use CASTOR/rootd\n");
1312 else if (fWriteMode == kDEVNULL)
1313 printf(", write raw data to /dev/null\n");
1317 // install SIGUSR1 handler to allow clean interrupts
1318 gSystem->AddSignalHandler(new AliMDCInterruptHandler(this));
1323 //______________________________________________________________________________
1326 // Run the MDC processor. Read from the input stream and only return
1327 // when the input gave and EOF or a fatal error occured. On success 0
1328 // is returned, 1 in case of a fatality.
1333 // Make sure needed directories exist
1334 const char *dirs[4];
1335 dirs[0] = kRawDBFS[0];
1336 dirs[1] = kRawDBFS[1];
1339 for (int idir = 0; idir < 4; idir++) {
1340 gSystem->ResetErrno();
1341 gSystem->MakeDirectory(dirs[idir]);
1342 if (gSystem->GetErrno() && gSystem->GetErrno() != EEXIST) {
1343 SysError("Run", "mkdir %s", dirs[idir]);
1348 // Used for statistics
1350 Double_t told = 0, tnew = 0;
1351 Float_t chunkSize = fMaxFileSize/100, nextChunk = chunkSize;
1353 // Event object used to store event data.
1354 AliRawEvent *event = new AliRawEvent;
1356 // Create new raw DB.
1358 if (fWriteMode == kRFIO)
1359 rawdb = new AliRawRFIODB(event, fMaxFileSize, fCompress);
1360 else if (fWriteMode == kROOTD)
1361 rawdb = new AliRawRootdDB(event, fMaxFileSize, fCompress);
1362 else if (fWriteMode == kCASTOR)
1363 rawdb = new AliRawCastorDB(event, fMaxFileSize, fCompress);
1364 else if (fWriteMode == kDEVNULL)
1365 rawdb = new AliRawNullDB(event, fMaxFileSize, fCompress);
1367 rawdb = new AliRawDB(event, fMaxFileSize, fCompress);
1369 if (rawdb->IsZombie()) return 1;
1370 printf("Filling raw DB %s\n", rawdb->GetDBName());
1372 // Create new tag DB.
1373 AliTagDB *tagdb = 0;
1375 // no tagdb for the time being to get maximum speed
1376 if (fWriteMode == kDEVNULL)
1377 tagdb = new AliTagNullDB(event->GetHeader(), kMaxTagFileSize);
1379 tagdb = new AliTagDB(event->GetHeader(), kMaxTagFileSize);
1380 if (tagdb->IsZombie())
1383 printf("Filling tag DB %s\n", tagdb->GetDBName());
1386 // Create AliStats object
1387 AliStats *stats = new AliStats(rawdb->GetDBName(), fCompress, fUseFilter);
1389 // Shortcut for easy header access
1390 AliRawEventHeader &header = *event->GetHeader();
1392 // Process input stream
1395 while (!(eorFlag = ebEor())) {
1396 struct iovec *ebvec;
1397 if ((ebvec = ebGetNextEvent()) == (void *)-1) {
1398 Error("Run", "error getting next event (%s)", ebGetLastError());
1402 // no event, sleep for 1 second and try again
1403 gSystem->Sleep(1000);
1406 char *ebdata = (char *) ebvec[0].iov_base;
1412 // Read event header
1413 if ((status = ReadHeader(header, ebdata)) != header.HeaderSize()) {
1417 ::lseek(fFd, 0, SEEK_SET);
1421 printf("<AliMDC::Run>: EOF, processed %d events\n", fNumEvents);
1429 // If we were in looping mode stop directly after a SIGUSR1 signal
1431 Info("Run", "Stopping loop, processed %d events", fNumEvents);
1435 // Check if event has any hard track flagged
1436 Bool_t callFilter = kFALSE;
1437 // This needs to be re-engineered for the next ADC...
1438 //if (fUseFilter && TEST_USER_ATTRIBUTE(header.GetTypeAttribute(), 0))
1439 // callFilter = kTRUE;
1441 // Check event type and skip "Start of Run", "End of Run",
1442 // "Start of Run Files" and "End of Run Files"
1443 switch (header.GetType()) {
1446 case kStartOfRunFiles:
1447 case kEndOfRunFiles:
1449 Int_t skip = header.GetEventSize() - header.HeaderSize();
1451 ::lseek(fFd, skip, SEEK_CUR);
1454 Info("Run", "Skipping %s (%d bytes)", header.GetTypeName(), skip);
1459 Int_t s = header.GetEventSize() - header.HeaderSize();
1460 Info("Run", "Processing %s (%d bytes)", header.GetTypeName(), s);
1464 // Amount of data left to read for this event
1465 Int_t toRead = header.GetEventSize() - header.HeaderSize();
1467 // If there is less data for this event than the next sub-event
1468 // header, something is wrong. Skip to next event...
1469 if (toRead < header.HeaderSize()) {
1472 "header size (%d) exceeds number of bytes to read (%d)\n",
1473 header.HeaderSize(), toRead);
1476 if ((status = DumpEvent(toRead)) != toRead) {
1481 Error("Run", "discarding event %d (too little data for header)", fNumEvents);
1485 // Loop over all sub-events... (LDCs)
1487 while (toRead > 0) {
1489 ebdata = (char *)ebvec[nsub].iov_base;
1493 Info("Run", "reading LDC %d", nsub);
1495 AliRawEvent *subEvent = event->NextSubEvent();
1497 // Read sub-event header
1498 AliRawEventHeader &subHeader = *subEvent->GetHeader();
1499 if ((status = ReadHeader(subHeader, ebdata)) != subHeader.HeaderSize()) {
1501 Error("Run", "unexpected EOF reading sub-event header");
1510 toRead -= subHeader.HeaderSize();
1513 ebdata = (char *)(ebvec[nsub].iov_base) + subHeader.HeaderSize();
1516 Int_t rawSize = subHeader.GetEventSize() - subHeader.HeaderSize();
1518 // Read Equipment Header (in case of physics or calibration event)
1519 if (header.GetType() == kPhysicsEvent ||
1520 header.GetType() == kCalibrationEvent) {
1521 AliRawEquipmentHeader &equipment = *subEvent->GetEquipmentHeader();
1522 Int_t equipHeaderSize = equipment.HeaderSize();
1523 if ((status = ReadEquipmentHeader(equipment, header.DataIsSwapped(),
1524 ebdata)) != equipHeaderSize) {
1526 Error("Run", "unexpected EOF reading equipment-header");
1531 toRead -= equipHeaderSize;
1532 rawSize -= equipHeaderSize;
1534 ebdata = (char *)(ebvec[nsub].iov_base) + subHeader.HeaderSize() +
1539 // Make sure raw data less than left over bytes for current event
1540 if (rawSize > toRead) {
1542 Warning("Run", "raw data size (%d) exceeds number of bytes "
1543 "to read (%d)\n", rawSize, toRead);
1546 if ((status = DumpEvent(toRead)) != toRead) {
1551 Error("Run", "discarding event %d (too much data)", fNumEvents);
1555 // Read sub-event raw data
1556 AliRawData &subRaw = *subEvent->GetRawData();
1557 if ((status = ReadRawData(subRaw, rawSize, ebdata)) != rawSize) {
1559 Error("Run", "unexpected EOF reading sub-event raw data");
1566 if (TEST_USER_ATTRIBUTE(subHeader.GetTypeAttribute(), 0))
1569 // set size of all sectors without hard track flag to 0
1578 // Set stat info for first event of this file
1579 if (rawdb->GetEvents() == 0)
1580 stats->SetFirstId(header.GetRunNumber(), header.GetEventInRun());
1582 // Store raw event in tree
1585 // Store header in tree
1586 if (tagdb) tagdb->Fill();
1590 if (!(fNumEvents%10))
1591 printf("Processed event %d (%d)\n", fNumEvents, rawdb->GetEvents());
1593 // Filling time statistics
1594 if (rawdb->GetBytesWritten() > nextChunk) {
1595 tnew = timer.RealTime();
1596 stats->Fill(tnew-told);
1599 nextChunk += chunkSize;
1602 // Check size of raw db. If bigger than maxFileSize, close file
1603 // and continue with new file.
1604 if (rawdb->FileFull()) {
1606 printf("Written raw DB at a rate of %.1f MB/s\n",
1607 rawdb->GetBytesWritten() / timer.RealTime() / 1000000.);
1609 // Write stats object to raw db, run db, MySQL and AliEn
1610 stats->WriteToDB(rawdb);
1613 if (!rawdb->NextFile()) {
1614 Error("Run", "error opening next raw data file");
1618 printf("Filling raw DB %s\n", rawdb->GetDBName());
1619 stats = new AliStats(rawdb->GetDBName(), fCompress, fUseFilter);
1623 nextChunk = chunkSize;
1626 // Check size of tag db
1627 if (tagdb && tagdb->FileFull()) {
1628 if (!tagdb->NextFile())
1631 printf("Filling tag DB %s\n", tagdb->GetDBName());
1634 // Make top event object ready for next event data
1635 //printf("Event %d has %d sub-events\n", fNumEvents, event->GetNSubEvents());
1639 if (!ebReleaseEvent(ebvec)) {
1640 Error("Run", "problem releasing event (%s)", ebGetLastError());
1646 printf("Written raw DB at a rate of %.1f MB/s\n",
1647 rawdb->GetBytesWritten() / timer.RealTime() / 1000000.);
1649 // Write stats to raw db and run db and delete stats object
1650 stats->WriteToDB(rawdb);
1659 // Close input source
1664 if (fUseFifo && ::unlink(kFifo) == -1) {
1665 SysError("Run", "unlink");
1673 Info("Run", "event builder reported end of run (%d)", eorFlag);
1680 //______________________________________________________________________________
1681 Int_t AliMDC::Read(void *buffer, Int_t length)
1683 // Read exactly length bytes into buffer. Returns number of bytes
1684 // received, returns -1 in case of error and 0 for EOF.
1688 if (fFd < 0) return -1;
1691 char *buf = (char *)buffer;
1693 for (n = 0; n < length; n += nrecv) {
1694 if ((nrecv = read(fFd, buf+n, length-n)) <= 0) {
1698 SysError("Read", "read");
1705 //______________________________________________________________________________
1706 Int_t AliMDC::ReadHeader(AliRawEventHeader &header, void *eb)
1708 // Read header info from DATE data stream. Returns bytes read (i.e.
1709 // AliRawEventHeader::HeaderSize()), -1 in case of error and 0 for EOF.
1714 // read from event builder memory area
1715 memcpy(header.HeaderBegin(), eb, header.HeaderSize());
1716 nrecv = header.HeaderSize();
1718 // read from fifo or file
1719 if ((nrecv = Read(header.HeaderBegin(), header.HeaderSize())) !=
1720 header.HeaderSize()) {
1727 // Swap header data if needed
1728 if (header.IsSwapped())
1731 // Is header valid...
1732 if (!header.IsValid()) {
1733 Error("ReadHeader", "invalid header format");
1734 // try recovery... how?
1737 if (header.GetEventSize() < (UInt_t)header.HeaderSize()) {
1738 Error("ReadHeader", "invalid header size");
1739 // try recovery... how?
1746 //______________________________________________________________________________
1747 Int_t AliMDC::ReadEquipmentHeader(AliRawEquipmentHeader &header,
1748 Bool_t isSwapped, void *eb)
1750 // Read equipment header info from DATE data stream. Returns bytes read
1751 // (i.e. AliRawEquipmentHeader::HeaderSize()), -1 in case of error and
1752 // 0 for EOF. If isSwapped is kTRUE the event data is byte swapped
1753 // and we will swap the header to host format.
1758 // read from event builder memory area
1759 memcpy(header.HeaderBegin(), eb, header.HeaderSize());
1760 nrecv = header.HeaderSize();
1762 // read from fifo or file
1763 if ((nrecv = Read(header.HeaderBegin(), header.HeaderSize())) !=
1764 header.HeaderSize()) {
1771 // Swap equipment header data if needed
1775 if (header.GetEquipmentSize() < (UInt_t)header.HeaderSize()) {
1776 Error("ReadEquipmentHeader", "invalid equipment header size");
1777 // try recovery... how?
1784 //______________________________________________________________________________
1785 Int_t AliMDC::ReadRawData(AliRawData &raw, Int_t size, void *eb)
1787 // Read raw data from DATE data stream. Returns bytes read (i.e.
1788 // AliRawEventHeader::HeaderSize()), -1 in case of error and 0 for EOF.
1793 // read from event builder memory area
1794 raw.SetBuffer(eb, size);
1797 // read from fifo or file
1799 if ((nrecv = Read(raw.GetBuffer(), size)) != size) {
1801 Error("ReadRawData", "unexpected EOF");
1811 //______________________________________________________________________________
1812 Int_t AliMDC::DumpEvent(Int_t toRead)
1814 // This case should not happen, but if it does try to handle it
1815 // gracefully by reading the rest of the event and discarding it.
1816 // Returns bytes read, -1 in case of fatal error and 0 for EOF.
1818 Error("DumpEvent", "dumping %d bytes of event %d", toRead, fNumEvents);
1821 char *tbuf = new char[toRead];
1822 if ((nrecv = Read(tbuf, toRead)) != toRead) {
1824 Error("DumpEvent", "unexpected EOF");
1835 #include <AliTPCL3Tunnel.h>
1838 //______________________________________________________________________________
1839 Int_t AliMDC::Filter(AliRawData &raw)
1841 // Call 3rd level filter for this raw data segment.
1844 AliTPCL3Tunnel *tunnel = 0;
1847 tunnel = new AliTPCL3Tunnel(Form("%s/TPCparams.root",
1848 gSystem->Getenv("ALITPC")));
1851 Int_t obytes, nbytes;
1852 obytes = nbytes = raw.GetSize();
1853 char *outbuf = tunnel->EvalTrack((char *)raw.GetBuffer(), nbytes);
1855 raw.SetSize(nbytes);
1856 memcpy(raw.GetBuffer(), outbuf, nbytes);
1858 printf("Filter called for event %d: reduced from %d to %d\n", fNumEvents,
1864 printf("Filter called for event %d\n", fNumEvents);