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 *kFifo = "/tmp/alimdc.fifo";
66 const char *kRawDBFS[2] = { "/tmp/mdc1", "/tmp/mdc2" };
67 const char *kTagDBFS = "/tmp/mdc1/tags";
68 const char *kRunDBFS = "/tmp/mdc1/meta";
69 const char *kRFIOFS = "rfio:/castor/cern.ch/user/r/rdm";
70 const char *kCastorFS = "castor:/castor/cern.ch/user/r/rdm";
71 const char *kRootdFS = "root://localhost//tmp/mdc1";
72 const char *kAlienHost = "alien://aliens7.cern.ch:15000/?direct";
73 const char *kAlienDir = "/alice_mdc/DC";
75 const char *kFifo = "/tmp/alimdc.fifo";
76 const char *kRawDBFS[2] = { "/data1/mdc", "/data2/mdc" };
77 const char *kTagDBFS = "/data1/mdc/tags";
78 const char *kRunDBFS = "/data1/mdc/meta";
79 const char *kRFIOFS = "rfio:/castor/cern.ch/lcg/dc5";
80 const char *kCastorFS = "castor:/castor/cern.ch/lcg/dc5";
81 const char *kRootdFS = "root://localhost//tmp/mdc1";
82 const char *kAlienHost = "alien://aliens7.cern.ch:15000/?direct";
83 const char *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.
204 fEvtHdr = new AliRawEventHeader;
210 //______________________________________________________________________________
211 AliRawEquipmentHeader *AliRawEvent::GetEquipmentHeader()
213 // Get equipment header part of AliRawEvent.
216 fEqpHdr = new AliRawEquipmentHeader;
221 //______________________________________________________________________________
222 AliRawData *AliRawEvent::GetRawData()
224 // Get raw data part of AliRawEvent.
227 fRawData = new AliRawData;
232 //______________________________________________________________________________
233 AliRawEvent *AliRawEvent::NextSubEvent()
235 // Returns next sub-event object.
238 fSubEvents = new TObjArray(100); // arbitrary, probably enough to prevent resizing
240 if (fSubEvents->GetSize() <= fNSubEvents) {
241 fSubEvents->Expand(fNSubEvents+10);
242 Warning("NextSubEvent", "expanded fSubEvents by 10 to %d",
243 fSubEvents->GetSize());
247 if (!(ev = (AliRawEvent *)fSubEvents->At(fNSubEvents))) {
248 ev = new AliRawEvent;
249 fSubEvents->AddAt(ev, fNSubEvents);
257 //______________________________________________________________________________
258 AliRawEvent *AliRawEvent::GetSubEvent(Int_t index) const
260 // Get specified sub event. Returns 0 if sub event does not exist.
265 return (AliRawEvent *) fSubEvents->At(index);
268 //______________________________________________________________________________
269 void AliRawEvent::Reset()
271 // Reset the event in case it needs to be re-used (avoiding costly
272 // new/delete cycle). We reset the size marker for the AliRawData
273 // objects and the sub event counter.
275 for (int i = 0; i < fNSubEvents; i++) {
276 AliRawEvent *ev = (AliRawEvent *)fSubEvents->At(i);
277 ev->GetRawData()->SetSize(0);
282 //______________________________________________________________________________
283 AliRawEvent::~AliRawEvent()
285 // Clean up event object. Delete also, possible, private raw data.
291 fSubEvents->Delete();
295 //______________________________________________________________________________
296 AliStats::AliStats(const char *filename, Int_t compmode, Bool_t filter)
298 // Create statistics object.
306 fFileName = filename;
307 fCompMode = compmode;
312 //______________________________________________________________________________
313 AliStats::~AliStats()
315 // Cleanup stats object.
320 //______________________________________________________________________________
321 AliStats &AliStats::operator=(const AliStats &rhs)
323 // AliStats assignment operator.
326 TObject::operator=(rhs);
327 fEvents = rhs.fEvents;
328 fFirstRun = rhs.fFirstRun;
329 fFirstEvent = rhs.fFirstEvent;
330 fLastRun = rhs.fLastRun;
331 fLastEvent = rhs.fLastEvent;
334 fFileName = rhs.fFileName;
335 fFileSize = rhs.fFileSize;
336 fCompFactor = rhs.fCompFactor;
337 fCompMode = rhs.fCompMode;
338 fFilter = rhs.fFilter;
339 fRTHist = rhs.fRTHist ? (TH1F*) rhs.fRTHist->Clone() : 0;
345 //______________________________________________________________________________
346 void AliStats::Fill(Float_t time)
348 // Fill histogram. This histogram shows the (hopefully constant) time
349 // it takes to fill the ROOT DB.
350 // Expects to be called 100 times for each file.
353 fRTHist = new TH1F("rtime","Real-time to write data chunk", 100, 0, 100);
354 fRTHist->SetDirectory(0);
357 fRTHist->Fill(fChunk, time);
361 //______________________________________________________________________________
362 void AliStats::WriteToDB(AliRawDB *rawdb)
364 // Write stats to raw DB, local run DB and global MySQL DB.
366 AliRawEventHeader &header = *rawdb->GetEvent()->GetHeader();
368 // Write stats into RawDB
369 TDirectory *ds = gDirectory;
370 rawdb->GetDB()->cd();
371 SetEvents(rawdb->GetEvents());
372 SetLastId(header.GetRunNumber(), header.GetEventInRun());
373 SetFileSize(rawdb->GetBytesWritten());
374 SetCompressionFactor(rawdb->GetCompressionFactor());
379 // Write stats also in the bookkeeping RunDB
380 AliRunDB *rundb = new AliRunDB(kTRUE);
382 rundb->UpdateRDBMS(this);
383 rundb->UpdateAliEn(this);
387 //______________________________________________________________________________
388 AliRawDB::AliRawDB(AliRawEvent *event, Double_t maxsize, Int_t compress,
391 // Create a new raw DB containing at most maxsize bytes.
395 fCompress = compress;
397 // Consistency check with DATE header file
398 if (fEvent->GetHeader()->HeaderSize() != EVENT_HEAD_BASE_SIZE) {
399 Error("AliRawDB", "inconsistency between DATE and AliRawEvent headers");
410 //______________________________________________________________________________
411 Bool_t AliRawDB::FSHasSpace(const char *fs)
413 // Check for at least fMaxSize bytes of free space on the file system.
414 // If the space is not available return kFALSE, kTRUE otherwise.
416 Long_t id, bsize, blocks, bfree;
418 if (gSystem->GetFsInfo(fs, &id, &bsize, &blocks, &bfree) == 1) {
419 Error("FSHasSpace", "could not stat file system %s", fs);
423 // Leave 5 percent of diskspace free
424 Double_t avail = Double_t(bfree) * 0.95;
425 if (avail*bsize > fMaxSize)
428 Warning("FSHasSpace", "no space on file system %s", fs);
432 //______________________________________________________________________________
433 const char *AliRawDB::GetFileName()
435 // Return filename based on hostname and date and time. This will make
436 // each file unique. Also makes sure (via FSHasSpace()) that there is
437 // enough space on the file system to store the file. Returns 0 in
438 // case of error or interrupt signal.
440 static TString fname;
441 static Bool_t fstoggle = kFALSE;
443 TString fs = fstoggle ? kRawDBFS[1] : kRawDBFS[0];
446 TString hostname = gSystem->HostName();
448 if ((pos = hostname.Index(".")) != kNPOS)
449 hostname.Remove(pos);
451 if (!FSHasSpace(fs)) {
453 fstoggle = !fstoggle;
454 fs = fstoggle ? kRawDBFS[1] : kRawDBFS[0];
455 if (FSHasSpace(fs)) break;
456 Info("GetFileName", "sleeping 30 seconds before retrying...");
457 gSystem->Sleep(30000); // sleep for 30 seconds
458 if (gAliMDC && gAliMDC->StopLoop())
463 fname = fs + "/" + hostname + "_";
464 fname += dt.GetDate();
466 fname += dt.GetTime();
469 fstoggle = !fstoggle;
474 //______________________________________________________________________________
475 Bool_t AliRawDB::Create()
477 // Create a new raw DB.
479 const Int_t maxRetry = 200;
480 const Int_t maxSleep = 1; // seconds
481 const Int_t maxSleepLong = 10; // seconds
485 if (gAliMDC && gAliMDC->StopLoop())
488 const char *fname = GetFileName();
490 Error("Create", "error getting raw DB file name");
496 fRawDB = TFile::Open(fname, GetOpenOption(),
497 Form("ALICE MDC%d raw DB", kMDC), fCompress);
499 if (retry < maxRetry) {
500 Warning("Create", "failure to open file, sleeping %d %s before retrying...",
501 maxSleep, maxSleep==1 ? "second" : "seconds");
502 gSystem->Sleep(maxSleep*1000);
505 Error("Create", "failure to open file %s after %d tries", fname, maxRetry);
508 if (fRawDB->IsZombie()) {
509 if (fRawDB->GetErrno() == ENOSPC ||
510 fRawDB->GetErrno() == 1018 || // SECOMERR
511 fRawDB->GetErrno() == 1027) { // SESYSERR
512 fRawDB->ResetErrno();
514 Warning("Create", "file is a zombie (no space), sleeping %d %s before retrying...",
515 maxSleepLong, maxSleepLong==1 ? "second" : "seconds");
516 gSystem->Sleep(maxSleepLong*1000); // sleep 10 seconds before retrying
519 Error("Create", "file %s is zombie", fname);
520 fRawDB->ResetErrno();
523 if (retry < maxRetry) {
524 Warning("Create", "file is a zombie, sleeping %d %s before retrying...",
525 maxSleep, maxSleep==1 ? "second" : "seconds");
526 gSystem->Sleep(maxSleep*1000);
529 Error("Create", "failure to open file %s after %d tries", fname, maxRetry);
533 // Create raw data TTree
539 //______________________________________________________________________________
540 void AliRawDB::MakeTree()
542 // Create ROOT Tree object container.
544 fTree = new TTree("RAW", Form("ALICE MDC%d raw data tree", kMDC));
545 fTree->SetAutoSave(2000000000); // autosave when 2 Gbyte written
547 Int_t bufsize = 256000;
548 // splitting 29.6 MB/s, no splitting 35.3 MB/s on P4 2GHz 15k SCSI
551 fTree->Branch("rawevent", "AliRawEvent", &fEvent, bufsize, split);
554 //______________________________________________________________________________
555 void AliRawDB::Close()
566 // Close DB, this also deletes the fTree
569 if (AliMDC::DeleteFiles()) {
570 gSystem->Unlink(fRawDB->GetName());
576 // Create semaphore to say this file is finished
577 Int_t tfd = ::creat(Form("%s.done", fRawDB->GetName()), 0644);
584 //______________________________________________________________________________
585 Bool_t AliRawDB::NextFile()
587 // Close te current file and open a new one.
588 // Returns kFALSE in case opening failed.
592 if (!Create()) return kFALSE;
596 //______________________________________________________________________________
597 Float_t AliRawDB::GetCompressionFactor() const
599 // Return compression factor.
601 if (fTree->GetZipBytes() == 0.)
604 return fTree->GetTotBytes()/fTree->GetZipBytes();
608 //______________________________________________________________________________
609 AliRawRFIODB::AliRawRFIODB(AliRawEvent *event, Double_t maxsize, Int_t compress)
610 : AliRawDB(event, maxsize, compress, kFALSE)
612 // Create a new raw DB that will be accessed via RFIO.
616 // Set STAGE_POOL environment variable to current host
618 // THESE ENVIRONMENT SYMBOLS ARE NOW DEFINED BY THE ALICE DATE SETUP
619 // THEREFORE WE SHALL NOT USE ANY HARDCODED VALUES BUT RATHER USE
620 // WHATEVER HAS BEEN SET IN THE DATE SITE
621 //gSystem->Setenv("STAGE_POOL", "lcg00");
622 //gSystem->Setenv("STAGE_HOST", "stage013");
630 fRawDB->UseCache(50, 0x200000); //0x100000 = 1MB)
633 //______________________________________________________________________________
634 const char *AliRawRFIODB::GetFileName()
636 // Return filename based on hostname and date and time. This will make
637 // each file unique. Also the directory will be made unique for each
638 // day by adding the date to the fs. Assumes there is always enough
639 // space on the device.
641 static TString fname;
643 TString fs = kRFIOFS;
646 // make a new subdirectory for each day
650 Long_t id, size, flags, time;
651 if (gSystem->GetPathInfo(fs, &id, &size, &flags, &time) == 1) {
652 // directory does not exist, create it
653 if (gSystem->mkdir(fs, kTRUE) == -1) {
654 Error("GetFileName", "cannot create dir %s, using %s", fs.Data(),
659 // FIXME: should check if fs is a directory
661 TString hostname = gSystem->HostName();
663 if ((pos = hostname.Index(".")) != kNPOS)
664 hostname.Remove(pos);
666 fname = fs + "/" + hostname + "_";
667 fname += dt.GetDate();
669 fname += dt.GetTime();
675 //______________________________________________________________________________
676 void AliRawRFIODB::Close()
678 // Close raw RFIO DB.
687 // Close DB, this also deletes the fTree
690 if (AliMDC::DeleteFiles()) {
691 TUrl u(fRawDB->GetName());
692 gSystem->Exec(Form("rfrm %s", u.GetFile()));
700 //______________________________________________________________________________
701 AliRawCastorDB::AliRawCastorDB(AliRawEvent *event, Double_t maxsize, Int_t compress)
702 : AliRawDB(event, maxsize, compress, kFALSE)
704 // Create a new raw DB that will be accessed via CASTOR and rootd.
708 // Set STAGE_POOL environment variable to current host
710 // THESE ENVIRONMENT SYMBOLS ARE NOW DEFINED BY THE ALICE DATE SETUP
711 // THEREFORE WE SHALL NOT USE ANY HARDCODED VALUES BUT RATHER USE
712 // WHATEVER HAS BEEN SET IN THE DATE SITE
713 //gSystem->Setenv("STAGE_POOL", "lcg00");
714 //gSystem->Setenv("STAGE_HOST", "stage013");
722 fRawDB->UseCache(50, 0x200000); //0x100000 = 1MB)
725 //______________________________________________________________________________
726 const char *AliRawCastorDB::GetFileName()
728 // Return filename based on hostname and date and time. This will make
729 // each file unique. Also the directory will be made unique for each
730 // day by adding the date to the fs. Assumes there is always enough
731 // space on the device.
733 static TString fname;
735 TString fs = kCastorFS;
736 TString fsr = kRFIOFS;
739 // make a new subdirectory for each day
746 Long_t id, size, flags, time;
747 if (gSystem->GetPathInfo(fsr, &id, &size, &flags, &time) == 1) {
748 // directory does not exist, create it
749 if (gSystem->mkdir(fsr, kTRUE) == -1) {
750 Error("GetFileName", "cannot create dir %s, using %s", fsr.Data(),
755 // FIXME: should check if fs is a directory
757 TString hostname = gSystem->HostName();
759 if ((pos = hostname.Index(".")) != kNPOS)
760 hostname.Remove(pos);
762 fname = fs + "/" + hostname + "_";
763 fname += dt.GetDate();
765 fname += dt.GetTime();
771 //______________________________________________________________________________
772 void AliRawCastorDB::Close()
774 // Close raw CASTOR/rootd DB.
783 // Close DB, this also deletes the fTree
786 if (AliMDC::DeleteFiles()) {
787 TUrl u(fRawDB->GetName());
788 gSystem->Exec(Form("rfrm %s", u.GetFile()));
796 //______________________________________________________________________________
797 AliRawRootdDB::AliRawRootdDB(AliRawEvent *event, Double_t maxsize, Int_t compress)
798 : AliRawDB(event, maxsize, compress, kFALSE)
800 // Create a new raw DB that will be accessed via rootd daemon.
805 fRawDB->UseCache(50, 0x200000); //0x100000 = 1MB)
808 //______________________________________________________________________________
809 const char *AliRawRootdDB::GetFileName()
811 // Return filename based on hostname and date and time. This will make
812 // each file unique. Also the directory will be made unique for each
813 // day by adding the date to the fs. Assumes there is always enough
814 // space on the device.
816 static TString fname;
818 TString fs = kRootdFS;
822 // make a new subdirectory for each day
826 Long_t id, size, flags, time;
827 if (gSystem->GetPathInfo(fs, &id, &size, &flags, &time) == 1) {
828 // directory does not exist, create it
829 if (gSystem->mkdir(fs, kTRUE) == -1) {
830 Error("GetFileName", "cannot create dir %s, using %s", fs.Data(),
835 // FIXME: should check if fs is a directory
838 TString hostname = gSystem->HostName();
840 if ((pos = hostname.Index(".")) != kNPOS)
841 hostname.Remove(pos);
843 fname = fs + "/" + hostname + "_";
844 fname += dt.GetDate();
846 fname += dt.GetTime();
852 //______________________________________________________________________________
853 void AliRawRootdDB::Close()
855 // Close raw rootd DB.
864 // Close DB, this also deletes the fTree
868 // can use services of TFTP
869 if (AliMDC::DeleteFiles())
870 gSystem->Exec(Form("rfrm %s", fRawDB->GetName()));
878 //______________________________________________________________________________
879 AliRawNullDB::AliRawNullDB(AliRawEvent *event, Double_t maxsize, Int_t compress)
880 : AliRawDB(event, maxsize, compress, kFALSE)
882 // Create a new raw DB that will wrtie to /dev/null.
888 //______________________________________________________________________________
889 const char *AliRawNullDB::GetFileName()
891 // Return /dev/null as filename.
896 //______________________________________________________________________________
897 void AliRawNullDB::Close()
899 // Close raw RFIO DB.
908 // Close DB, this also deletes the fTree
916 //______________________________________________________________________________
917 AliTagDB::AliTagDB(AliRawEventHeader *header, Double_t maxsize, Bool_t create)
930 //______________________________________________________________________________
931 Bool_t AliTagDB::Create()
933 // Create a new tag DB.
935 fTagDB = new TFile(GetFileName(), "RECREATE",
936 Form("ALICE MDC%d tag DB", kMDC), 1);
937 if (fTagDB->IsZombie()) {
938 Error("Create", "error opening tag DB");
943 // Create ROOT Tree object container
944 fTree = new TTree("TAG", Form("ALICE MDC%d header data tree", kMDC));
945 fTree->SetAutoSave(100000000); // autosave when 100 Mbyte written
947 Int_t bufsize = 32000;
949 fTree->Branch("header", "AliRawEventHeader", &fHeader, bufsize, split);
954 //______________________________________________________________________________
955 void AliTagDB::Close()
966 // Close DB, this also deletes the fTree
969 if (AliMDC::DeleteFiles())
970 gSystem->Unlink(fTagDB->GetName());
976 //______________________________________________________________________________
977 Bool_t AliTagDB::NextFile()
979 // Close te current file and open a new one.
980 // Returns kFALSE in case opening failed.
984 if (!Create()) return kFALSE;
988 //______________________________________________________________________________
989 Float_t AliTagDB::GetCompressionFactor() const
991 // Return compression factor.
993 if (fTree->GetZipBytes() == 0.)
996 return fTree->GetTotBytes()/fTree->GetZipBytes();
999 //______________________________________________________________________________
1000 const char *AliTagDB::GetFileName()
1002 // Return filename based on hostname and date and time. This will make
1003 // each file unique. The tags will be stored in the /data1/tags directory.
1005 static char fname[64];
1006 const char *fs = kTagDBFS;
1008 // check that fs exists (crude check fails if fs is a file)
1009 gSystem->MakeDirectory(fs);
1013 strcpy(hostname, gSystem->HostName());
1016 if ((s = strchr(hostname, '.')))
1021 sprintf(fname, "%s/%s_%d_%d.root", fs, hostname, dt.GetDate(), dt.GetTime());
1027 //______________________________________________________________________________
1028 AliTagNullDB::AliTagNullDB(AliRawEventHeader *header, Double_t maxsize) :
1029 AliTagDB(header, maxsize, kFALSE)
1031 // Create tag db writing to /dev/null.
1037 //______________________________________________________________________________
1038 const char *AliTagNullDB::GetFileName()
1040 // Return /dev/null as filename.
1045 //______________________________________________________________________________
1046 void AliTagNullDB::Close()
1048 // Close null tag DB.
1050 if (!fTagDB) return;
1057 // Close DB, this also deletes the fTree
1065 //______________________________________________________________________________
1066 AliRunDB::AliRunDB(Bool_t noLocalDB)
1068 // Open run database, and get or create tree.
1072 if (noLocalDB) return;
1075 char hostname[64], filename[64];
1076 const char *fs = kRunDBFS;
1078 // check that fs exists (crude check fails if fs is a file)
1079 gSystem->MakeDirectory(fs);
1081 strcpy(hostname, gSystem->HostName());
1084 if ((s = strchr(hostname, '.')))
1087 sprintf(filename, "%s/%s_rundb.root", fs, hostname);
1089 if (!gSystem->AccessPathName(filename, kFileExists))
1090 fRunDB = new TFile(filename, "UPDATE");
1092 fRunDB = new TFile(filename, "CREATE", Form("ALICE MDC%d Run DB", kMDC));
1095 //______________________________________________________________________________
1096 void AliRunDB::Update(AliStats *stats)
1098 // Add stats object to database.
1100 if (!stats || !fRunDB) return;
1102 TDirectory *ds = gDirectory;
1106 char *s = (char*)strrchr(stats->GetFileName(), '/');
1111 strcpy(sname, stats->GetFileName());
1112 s = strchr(sname, '.');
1115 stats->Write(sname);
1120 //______________________________________________________________________________
1121 void AliRunDB::UpdateRDBMS(AliStats *stats)
1123 // Add stats object to central MySQL DB.
1128 char bt[25], et[25];
1130 strcpy(bt, stats->GetBeginTime().AsSQLString());
1131 strcpy(et, stats->GetEndTime().AsSQLString());
1133 sprintf(sql, "INSERT INTO mdc%dcatalog VALUES (0, '%s', %d, "
1134 "%d, %d, %d, %d, %d, %d, %.2f, '%s', '%s', '%s')", kMDC,
1135 stats->GetFileName(), (int)stats->GetFileSize(), stats->GetEvents(),
1136 stats->GetFirstRun(), stats->GetFirstEvent(), stats->GetLastRun(),
1137 stats->GetLastEvent(), stats->GetCompressionMode(),
1138 stats->GetCompressionFactor(), stats->GetFilterState() ? "on" : "off",
1141 // open connection to MySQL server on pcsalo
1142 TSQLServer *db = TSQLServer::Connect("mysql://pcsalo.cern.ch/mdc", "alice", "amdc");
1144 if (!db || db->IsZombie()) {
1145 Error("UpdateRDBMS", "failed to connect to MySQL server on pcsalo");
1146 printf("%s\n", sql);
1151 TSQLResult *res = db->Query(sql);
1154 Error("UpdateRDBMS", Form("insert into mdc%dcatalog failed", kMDC));
1155 printf("%s\n", sql);
1162 //______________________________________________________________________________
1163 void AliRunDB::UpdateAliEn(AliStats *stats)
1165 // Record file in AliEn catalog.
1169 TGrid *g = TGrid::Connect(kAlienHost, "");
1171 TString lfn = kAlienDir;
1173 lfn += gSystem->BaseName(stats->GetFileName());
1175 Int_t result = g->AddFile(lfn, stats->GetFileName(),
1176 (int)stats->GetFileSize());
1179 Error("UpdateAliEn", "error adding file to AliEn catalog");
1180 printf("AliEn: AddFile(%s, %s, %d)\n", lfn.Data(), stats->GetFileName(),
1181 (int)stats->GetFileSize());
1187 //______________________________________________________________________________
1188 void AliRunDB::Close()
1190 // Close run database.
1192 if (fRunDB) fRunDB->Close();
1196 //----------------- Use SIGUSR1 to interupt endless loop -----------------------
1197 class AliMDCInterruptHandler : public TSignalHandler {
1199 AliMDC *fMDC; // alimdc to signal
1201 AliMDCInterruptHandler(AliMDC *mdc) : TSignalHandler(kSigUser1, kFALSE), fMDC(mdc) { }
1203 Info("Notify", "received a SIGUSR1 signal");
1204 fMDC->SetStopLoop();
1209 //______________________________________________________________________________
1210 AliMDC::AliMDC(Int_t fd, Int_t compress, Double_t maxFileSize, Bool_t useFilter,
1211 EWriteMode mode, Bool_t useLoop, Bool_t delFiles)
1213 // Create MDC processor object.
1216 fCompress = compress;
1217 fMaxFileSize = maxFileSize;
1218 fUseFilter = useFilter;
1226 fgDeleteFiles = delFiles;
1230 if (!ebRegister()) {
1231 Error("AliMDC", "cannot register with the event builder (%s)",
1237 if ((mkfifo(kFifo, 0644) < 0) && (errno != EEXIST)) {
1238 Error("AliMDC", "cannot create fifo %s", kFifo);
1241 if ((chmod(kFifo, 0666) == -1) && (errno != EPERM)) {
1242 Error("AliMDC", "cannot change permission of fifo %s", kFifo);
1245 if ((fFd = open(kFifo, O_RDONLY)) == -1) {
1246 Error("AliMDC", "cannot open input file %s", kFifo);
1254 printf("<AliMDC::AliMDC>: input = %s, rawdb size = %f, filter = %s, "
1255 "looping = %s, compression = %d, delete files = %s",
1256 fUseFifo ? "fifo" : (fUseEb ? "eb" : "file"), fMaxFileSize,
1257 fUseFilter ? "on" : "off", fUseLoop ? "yes" : "no", fCompress,
1258 fgDeleteFiles ? "yes" : "no");
1259 if (fWriteMode == kRFIO)
1260 printf(", use RFIO\n");
1261 else if (fWriteMode == kROOTD)
1262 printf(", use rootd\n");
1263 else if (fWriteMode == kCASTOR)
1264 printf(", use CASTOR/rootd\n");
1265 else if (fWriteMode == kDEVNULL)
1266 printf(", write raw data to /dev/null\n");
1270 // install SIGUSR1 handler to allow clean interrupts
1271 gSystem->AddSignalHandler(new AliMDCInterruptHandler(this));
1276 //______________________________________________________________________________
1279 // Run the MDC processor. Read from the input stream and only return
1280 // when the input gave and EOF or a fatal error occured. On success 0
1281 // is returned, 1 in case of a fatality.
1286 // Make sure needed directories exist
1287 const char *dirs[4];
1288 dirs[0] = kRawDBFS[0];
1289 dirs[1] = kRawDBFS[1];
1292 for (int idir = 0; idir < 4; idir++) {
1293 gSystem->ResetErrno();
1294 gSystem->MakeDirectory(dirs[idir]);
1295 if (gSystem->GetErrno() && gSystem->GetErrno() != EEXIST) {
1296 SysError("Run", "mkdir %s", dirs[idir]);
1301 // Used for statistics
1303 Double_t told = 0, tnew = 0;
1304 Float_t chunkSize = fMaxFileSize/100, nextChunk = chunkSize;
1306 // Event object used to store event data.
1307 AliRawEvent *event = new AliRawEvent;
1309 // Create new raw DB.
1311 if (fWriteMode == kRFIO)
1312 rawdb = new AliRawRFIODB(event, fMaxFileSize, fCompress);
1313 else if (fWriteMode == kROOTD)
1314 rawdb = new AliRawRootdDB(event, fMaxFileSize, fCompress);
1315 else if (fWriteMode == kCASTOR)
1316 rawdb = new AliRawCastorDB(event, fMaxFileSize, fCompress);
1317 else if (fWriteMode == kDEVNULL)
1318 rawdb = new AliRawNullDB(event, fMaxFileSize, fCompress);
1320 rawdb = new AliRawDB(event, fMaxFileSize, fCompress);
1322 if (rawdb->IsZombie()) return 1;
1323 printf("Filling raw DB %s\n", rawdb->GetDBName());
1325 // Create new tag DB.
1326 AliTagDB *tagdb = 0;
1328 // no tagdb for the time being to get maximum speed
1329 if (fWriteMode == kDEVNULL)
1330 tagdb = new AliTagNullDB(event->GetHeader(), kMaxTagFileSize);
1332 tagdb = new AliTagDB(event->GetHeader(), kMaxTagFileSize);
1333 if (tagdb->IsZombie())
1336 printf("Filling tag DB %s\n", tagdb->GetDBName());
1339 // Create AliStats object
1340 AliStats *stats = new AliStats(rawdb->GetDBName(), fCompress, fUseFilter);
1342 // Shortcut for easy header access
1343 AliRawEventHeader &header = *event->GetHeader();
1345 // Process input stream
1348 while (!(eorFlag = ebEor())) {
1349 struct iovec *ebvec;
1350 if ((ebvec = ebGetNextEvent()) == (void *)-1) {
1351 Error("Run", "error getting next event (%s)", ebGetLastError());
1355 // no event, sleep for 1 second and try again
1356 gSystem->Sleep(1000);
1359 char *ebdata = (char *) ebvec[0].iov_base;
1365 // Read event header
1366 if ((status = ReadHeader(header, ebdata)) != header.HeaderSize()) {
1370 ::lseek(fFd, 0, SEEK_SET);
1374 printf("<AliMDC::Run>: EOF, processed %d events\n", fNumEvents);
1382 // If we were in looping mode stop directly after a SIGUSR1 signal
1384 Info("Run", "Stopping loop, processed %d events", fNumEvents);
1388 // Check if event has any hard track flagged
1389 Bool_t callFilter = kFALSE;
1390 // This needs to be re-engineered for the next ADC...
1391 //if (fUseFilter && TEST_USER_ATTRIBUTE(header.GetTypeAttribute(), 0))
1392 // callFilter = kTRUE;
1394 // Check event type and skip "Start of Run", "End of Run",
1395 // "Start of Run Files" and "End of Run Files"
1396 switch (header.GetType()) {
1399 case kStartOfRunFiles:
1400 case kEndOfRunFiles:
1402 Int_t skip = header.GetEventSize() - header.HeaderSize();
1404 ::lseek(fFd, skip, SEEK_CUR);
1407 Info("Run", "Skipping %s (%d bytes)", header.GetTypeName(), skip);
1413 Int_t s = header.GetEventSize() - header.HeaderSize();
1414 Info("Run", "Processing %s (%d bytes)", header.GetTypeName(), s);
1418 // Amount of data left to read for this event
1419 Int_t toRead = header.GetEventSize() - header.HeaderSize();
1421 // If there is less data for this event than the next sub-event
1422 // header, something is wrong. Skip to next event...
1423 if (toRead < header.HeaderSize()) {
1426 "header size (%d) exceeds number of bytes to read (%d)\n",
1427 header.HeaderSize(), toRead);
1430 if ((status = DumpEvent(toRead)) != toRead) {
1435 Error("Run", "discarding event %d (too little data for header)", fNumEvents);
1439 // Loop over all sub-events... (LDCs)
1441 while (toRead > 0) {
1443 ebdata = (char *)ebvec[nsub].iov_base;
1447 Info("Run", "reading LDC %d", nsub);
1449 AliRawEvent *subEvent = event->NextSubEvent();
1451 // Read sub-event header
1452 AliRawEventHeader &subHeader = *subEvent->GetHeader();
1453 if ((status = ReadHeader(subHeader, ebdata)) != subHeader.HeaderSize()) {
1455 Error("Run", "unexpected EOF reading sub-event header");
1464 toRead -= subHeader.HeaderSize();
1467 ebdata = (char *)(ebvec[nsub].iov_base) + subHeader.HeaderSize();
1470 Int_t rawSize = subHeader.GetEventSize() - subHeader.HeaderSize();
1472 // Read Equipment Header (in case of physics or calibration event)
1473 if (header.GetType() == kPhysicsEvent ||
1474 header.GetType() == kCalibrationEvent) {
1475 AliRawEquipmentHeader &equipment = *subEvent->GetEquipmentHeader();
1476 Int_t equipHeaderSize = equipment.HeaderSize();
1477 if ((status = ReadEquipmentHeader(equipment, header.DataIsSwapped(),
1478 ebdata)) != equipHeaderSize) {
1480 Error("Run", "unexpected EOF reading equipment-header");
1485 toRead -= equipHeaderSize;
1486 rawSize -= equipHeaderSize;
1488 ebdata = (char *)(ebvec[nsub].iov_base) + subHeader.HeaderSize() +
1493 // Make sure raw data less than left over bytes for current event
1494 if (rawSize > toRead) {
1496 Warning("Run", "raw data size (%d) exceeds number of bytes "
1497 "to read (%d)\n", rawSize, toRead);
1500 if ((status = DumpEvent(toRead)) != toRead) {
1505 Error("Run", "discarding event %d (too much data)", fNumEvents);
1509 // Read sub-event raw data
1510 AliRawData &subRaw = *subEvent->GetRawData();
1511 if ((status = ReadRawData(subRaw, rawSize, ebdata)) != rawSize) {
1513 Error("Run", "unexpected EOF reading sub-event raw data");
1520 if (TEST_USER_ATTRIBUTE(subHeader.GetTypeAttribute(), 0))
1523 // set size of all sectors without hard track flag to 0
1532 // Set stat info for first event of this file
1533 if (rawdb->GetEvents() == 0)
1534 stats->SetFirstId(header.GetRunNumber(), header.GetEventInRun());
1536 // Store raw event in tree
1539 // Store header in tree
1540 if (tagdb) tagdb->Fill();
1544 if (!(fNumEvents%10))
1545 printf("Processed event %d (%d)\n", fNumEvents, rawdb->GetEvents());
1547 // Filling time statistics
1548 if (rawdb->GetBytesWritten() > nextChunk) {
1549 tnew = timer.RealTime();
1550 stats->Fill(tnew-told);
1553 nextChunk += chunkSize;
1556 // Check size of raw db. If bigger than maxFileSize, close file
1557 // and continue with new file.
1558 if (rawdb->FileFull()) {
1560 printf("Written raw DB at a rate of %.1f MB/s\n",
1561 rawdb->GetBytesWritten() / timer.RealTime() / 1000000.);
1563 // Write stats object to raw db, run db, MySQL and AliEn
1564 stats->WriteToDB(rawdb);
1567 if (!rawdb->NextFile()) {
1568 Error("Run", "error opening next raw data file");
1572 printf("Filling raw DB %s\n", rawdb->GetDBName());
1573 stats = new AliStats(rawdb->GetDBName(), fCompress, fUseFilter);
1577 nextChunk = chunkSize;
1580 // Check size of tag db
1581 if (tagdb && tagdb->FileFull()) {
1582 if (!tagdb->NextFile())
1585 printf("Filling tag DB %s\n", tagdb->GetDBName());
1588 // Make top event object ready for next event data
1589 //printf("Event %d has %d sub-events\n", fNumEvents, event->GetNSubEvents());
1593 if (!ebReleaseEvent(ebvec)) {
1594 Error("Run", "problem releasing event (%s)", ebGetLastError());
1600 printf("Written raw DB at a rate of %.1f MB/s\n",
1601 rawdb->GetBytesWritten() / timer.RealTime() / 1000000.);
1603 // Write stats to raw db and run db and delete stats object
1604 stats->WriteToDB(rawdb);
1613 // Close input source
1618 if (fUseFifo && ::unlink(kFifo) == -1) {
1619 SysError("Run", "unlink");
1627 Info("Run", "event builder reported end of run (%d)", eorFlag);
1634 //______________________________________________________________________________
1635 Int_t AliMDC::Read(void *buffer, Int_t length)
1637 // Read exactly length bytes into buffer. Returns number of bytes
1638 // received, returns -1 in case of error and 0 for EOF.
1642 if (fFd < 0) return -1;
1645 char *buf = (char *)buffer;
1647 for (n = 0; n < length; n += nrecv) {
1648 if ((nrecv = read(fFd, buf+n, length-n)) <= 0) {
1652 SysError("Read", "read");
1659 //______________________________________________________________________________
1660 Int_t AliMDC::ReadHeader(AliRawEventHeader &header, void *eb)
1662 // Read header info from DATE data stream. Returns bytes read (i.e.
1663 // AliRawEventHeader::HeaderSize()), -1 in case of error and 0 for EOF.
1668 // read from event builder memory area
1669 memcpy(header.HeaderBegin(), eb, header.HeaderSize());
1670 nrecv = header.HeaderSize();
1672 // read from fifo or file
1673 if ((nrecv = Read(header.HeaderBegin(), header.HeaderSize())) !=
1674 header.HeaderSize()) {
1681 // Swap header data if needed
1682 if (header.IsSwapped())
1685 // Is header valid...
1686 if (!header.IsValid()) {
1687 Error("ReadHeader", "invalid header format");
1688 // try recovery... how?
1691 if (header.GetEventSize() < (UInt_t)header.HeaderSize()) {
1692 Error("ReadHeader", "invalid header size");
1693 // try recovery... how?
1700 //______________________________________________________________________________
1701 Int_t AliMDC::ReadEquipmentHeader(AliRawEquipmentHeader &header,
1702 Bool_t isSwapped, void *eb)
1704 // Read equipment header info from DATE data stream. Returns bytes read
1705 // (i.e. AliRawEquipmentHeader::HeaderSize()), -1 in case of error and
1706 // 0 for EOF. If isSwapped is kTRUE the event data is byte swapped
1707 // and we will swap the header to host format.
1712 // read from event builder memory area
1713 memcpy(header.HeaderBegin(), eb, header.HeaderSize());
1714 nrecv = header.HeaderSize();
1716 // read from fifo or file
1717 if ((nrecv = Read(header.HeaderBegin(), header.HeaderSize())) !=
1718 header.HeaderSize()) {
1725 // Swap equipment header data if needed
1729 if (header.GetEquipmentSize() < (UInt_t)header.HeaderSize()) {
1730 Error("ReadEquipmentHeader", "invalid equipment header size");
1731 // try recovery... how?
1738 //______________________________________________________________________________
1739 Int_t AliMDC::ReadRawData(AliRawData &raw, Int_t size, void *eb)
1741 // Read raw data from DATE data stream. Returns bytes read (i.e.
1742 // AliRawEventHeader::HeaderSize()), -1 in case of error and 0 for EOF.
1747 // read from event builder memory area
1748 raw.SetBuffer(eb, size);
1751 // read from fifo or file
1753 if ((nrecv = Read(raw.GetBuffer(), size)) != size) {
1755 Error("ReadRawData", "unexpected EOF");
1765 //______________________________________________________________________________
1766 Int_t AliMDC::DumpEvent(Int_t toRead)
1768 // This case should not happen, but if it does try to handle it
1769 // gracefully by reading the rest of the event and discarding it.
1770 // Returns bytes read, -1 in case of fatal error and 0 for EOF.
1772 Error("DumpEvent", "dumping %d bytes of event %d", toRead, fNumEvents);
1775 char *tbuf = new char[toRead];
1776 if ((nrecv = Read(tbuf, toRead)) != toRead) {
1778 Error("DumpEvent", "unexpected EOF");
1789 #include <AliTPCL3Tunnel.h>
1792 //______________________________________________________________________________
1793 Int_t AliMDC::Filter(AliRawData &raw)
1795 // Call 3rd level filter for this raw data segment.
1798 AliTPCL3Tunnel *tunnel = 0;
1801 tunnel = new AliTPCL3Tunnel(Form("%s/TPCparams.root",
1802 gSystem->Getenv("ALITPC")));
1805 Int_t obytes, nbytes;
1806 obytes = nbytes = raw.GetSize();
1807 char *outbuf = tunnel->EvalTrack((char *)raw.GetBuffer(), nbytes);
1809 raw.SetSize(nbytes);
1810 memcpy(raw.GetBuffer(), outbuf, nbytes);
1812 printf("Filter called for event %d: reduced from %d to %d\n", fNumEvents,
1818 printf("Filter called for event %d\n", fNumEvents);