CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_5_3_6/src/EventFilter/Goodies/src/iDie.cc

Go to the documentation of this file.
00001 #include "iDie.h"
00002 
00003 #include "xdaq/NamespaceURI.h"
00004 
00005 #include "xoap/SOAPEnvelope.h"
00006 #include "xoap/SOAPBody.h"
00007 #include "xoap/domutils.h"
00008 
00009 #include <boost/tokenizer.hpp>
00010 
00011 #include <netinet/in.h>
00012 #include <sstream>
00013 #include <errno.h>
00014 #include <iomanip>
00015 #include <algorithm>
00016 
00017 #include <sys/time.h>
00018 #include <sys/types.h>
00019 #include <sys/stat.h>
00020 //#include <sys/dir.h>
00021 #include <time.h>
00022 #include <math.h>
00023 
00024 #include "cgicc/CgiDefs.h"
00025 #include "cgicc/Cgicc.h"
00026 #include "cgicc/FormEntry.h"
00027 #include "cgicc/FormFile.h"
00028 #include "cgicc/HTMLClasses.h"
00029 
00030 #include "EventFilter/Utilities/interface/DebugUtils.h"
00031 
00032 //#include "FWCore/PythonParameterSet/interface/MakeParameterSets.h"
00033 //#undef HAVE_STAT
00034 #include "FWCore/PluginManager/interface/PluginManager.h"
00035 #include "FWCore/PluginManager/interface/PresenceFactory.h"
00036 #include "FWCore/PluginManager/interface/standard.h"
00037 #include "EventFilter/Utilities/interface/ParameterSetRetriever.h"
00038 #include "FWCore/PythonParameterSet/interface/PythonProcessDesc.h"
00039 #include "FWCore/ParameterSet/interface/ProcessDesc.h"
00040 #include "FWCore/ServiceRegistry/interface/Service.h"
00041 
00042 #include "DQMServices/Core/src/DQMService.h"
00043 using namespace evf;
00044 
00045 #define ROLL 20
00046 #define PASTUPDATES 4
00047 
00049 // construction/destruction
00051 
00052 //______________________________________________________________________________
00053 iDie::iDie(xdaq::ApplicationStub *s) 
00054   : xdaq::Application(s)
00055   , log_(getApplicationLogger())
00056   , dqmState_("Null")
00057   , instance_(0)
00058   , runNumber_(0)
00059   , lastRunNumberSet_(0)
00060   , dqmCollectorHost_()
00061   , dqmCollectorPort_()
00062   , totalCores_(0)
00063   , nstates_(0)
00064   , cpustat_(std::vector<std::vector<int> >(0))
00065   , last_ls_(0)
00066   , f_(0)
00067   , t_(0)
00068   , b_(0)
00069   , b1_(0)
00070   , b2_(0)
00071   , b3_(0)
00072   , b4_(0)
00073   , datap_(0)
00074   , trppriv_(0)
00075   , nModuleLegendaMessageReceived_(0)
00076   , nPathLegendaMessageReceived_(0)
00077   , nModuleLegendaMessageWithDataReceived_(0)
00078   , nPathLegendaMessageWithDataReceived_(0)
00079   , nModuleHistoMessageReceived_(0)
00080   , nPathHistoMessageReceived_(0)
00081   , nDatasetLegendaMessageReceived_(0)
00082   , nDatasetLegendaMessageWithDataReceived_(0)
00083   , evtProcessor_(0)
00084   , meInitialized_(false)
00085   , meInitializedStreams_(false)
00086   , meInitializedDatasets_(false)
00087   , dqmService_(nullptr)
00088   , dqmStore_(nullptr)
00089   , dqmEnabled_(false)
00090   , saveLsInterval_(10)
00091   , ilumiprev_(0)
00092   , dqmSaveDir_("")
00093   , dqmFilesWritable_(true)
00094   , topLevelFolder_("DAQ")
00095   , savedForLs_(0)
00096   , reportingStart_(0)
00097   , dsMismatch(0)
00098 {
00099   // initialize application info
00100   url_     =
00101     getApplicationDescriptor()->getContextDescriptor()->getURL()+"/"+
00102     getApplicationDescriptor()->getURN();
00103   class_   =getApplicationDescriptor()->getClassName();
00104   instance_=getApplicationDescriptor()->getInstance();
00105   hostname_=getApplicationDescriptor()->getContextDescriptor()->getURL();
00106   getApplicationDescriptor()->setAttribute("icon", "/evf/images/idieapp.jpg");
00107 
00108   //soap interface
00109   xoap::bind(this,&evf::iDie::fsmCallback,"Configure",XDAQ_NS_URI);
00110   xoap::bind(this,&evf::iDie::fsmCallback,"Enable",   XDAQ_NS_URI);
00111   xoap::bind(this,&evf::iDie::fsmCallback,"Stop",     XDAQ_NS_URI);
00112   xoap::bind(this,&evf::iDie::fsmCallback,"Halt",     XDAQ_NS_URI);
00113 
00114   // web interface
00115   xgi::bind(this,&evf::iDie::defaultWeb,               "Default");
00116   xgi::bind(this,&evf::iDie::summaryTable,             "summary");
00117   xgi::bind(this,&evf::iDie::detailsTable,             "details");
00118   xgi::bind(this,&evf::iDie::dumpTable,                "dump"   );
00119   xgi::bind(this,&evf::iDie::updater,                  "updater");
00120   xgi::bind(this,&evf::iDie::iChoke,                   "iChoke" );
00121   xgi::bind(this,&evf::iDie::iChokeMiniInterface,      "iChokeMiniInterface" );
00122   xgi::bind(this,&evf::iDie::spotlight,                "Spotlight" );
00123   xgi::bind(this,&evf::iDie::postEntry,                "postEntry");
00124   xgi::bind(this,&evf::iDie::postEntryiChoke,          "postChoke");
00125   //  gui_->setSmallAppIcon("/evf/images/Hilton.gif");
00126   //  gui_->setLargeAppIcon("/evf/images/Hilton.gif");
00127 
00128   xdata::InfoSpace *ispace = getApplicationInfoSpace();
00129   ispace->fireItemAvailable("runNumber",            &runNumber_                   );
00130   getApplicationInfoSpace()->addItemChangedListener("runNumber",              this);
00131   ispace->fireItemAvailable("dqmCollectorHost",         &dqmCollectorHost_        );
00132   ispace->fireItemAvailable("dqmCollectorPort",         &dqmCollectorPort_        );
00133   ispace->fireItemAvailable("saveLsInterval",           &saveLsInterval_          );
00134   ispace->fireItemAvailable("dqmSaveDir",               &dqmSaveDir_              );
00135   ispace->fireItemAvailable("dqmFilesWritableByAll",    &dqmFilesWritable_        );
00136   ispace->fireItemAvailable("dqmTopLevelFolder",        &topLevelFolder_          );
00137   ispace->fireItemAvailable("dqmEnabled",               &dqmEnabled_              );
00138 
00139   // timestamps
00140   lastModuleLegendaMessageTimeStamp_.tv_sec=0;
00141   lastModuleLegendaMessageTimeStamp_.tv_usec=0;
00142   lastPathLegendaMessageTimeStamp_.tv_sec=0;
00143   lastPathLegendaMessageTimeStamp_.tv_usec=0;
00144   lastDatasetLegendaMessageTimeStamp_.tv_sec=0;
00145   lastDatasetLegendaMessageTimeStamp_.tv_usec=0;
00146   runStartDetectedTimeStamp_.tv_sec=0;
00147   runStartDetectedTimeStamp_.tv_usec=0;
00148 
00149   //dqm python configuration
00150   configString_= "import FWCore.ParameterSet.Config as cms\n";
00151   configString_+="process = cms.Process(\"iDieDQM\")\n";
00152   configString_+="process.source = cms.Source(\"EmptySource\")\n";
00153   configString_+="process.DQMStore = cms.Service(\"DQMStore\",\n";
00154   configString_+="  referenceFileName = cms.untracked.string(''),\n";
00155   configString_+="  verbose = cms.untracked.int32(0),\n";
00156   configString_+="  verboseQT = cms.untracked.int32(0),\n";
00157   configString_+="  collateHistograms = cms.untracked.bool(False))\n";
00158   configString_+="process.DQM = cms.Service(\"DQM\",\n";
00159   configString_+="  debug = cms.untracked.bool(False),\n";
00160   configString_+="  publishFrequency = cms.untracked.double(1.0),\n";
00161   configString_+="  collectorPort = cms.untracked.int32(EMPTYPORT),\n";
00162   configString_+="  collectorHost = cms.untracked.string('EMPTYHOST'),\n";
00163   configString_+="  filter = cms.untracked.string(''),\n";
00164   configString_+="  verbose = cms.untracked.bool(False))\n";
00165   configString_+="process.p = cms.Path()\n";
00166 
00167   epInstances   =     {7,    8,     12,  16, 24,  32};
00168   epMax         =     {8,    8,     24,  32, 24,  32};
00169   HTscaling     =     {1,    1,   0.28,0.28, 0.28,0.28};
00170   machineWeight =     {91.6, 91.6, 253, 352, 253, 352};
00171   machineWeightInst = {80.15,91.6, 196, 275, 253, 352};
00172 
00173   for (unsigned int i=0;i<epInstances.size();i++) {
00174     currentLs_.push_back(0);
00175     nbSubsList[epInstances[i]]=i;
00176     nbSubsListInv[i]=epInstances[i];
00177     std::map<unsigned int, unsigned int> mptmp;
00178     occupancyNameMap.push_back(mptmp);
00179   }
00180   nbSubsClasses = epInstances.size();
00181   lsHistory = new std::deque<lsStat*>[nbSubsClasses];
00182   //umask for setting permissions of created directories
00183   umask(000);
00184 
00185 }
00186 
00187 
00188 //______________________________________________________________________________
00189 iDie::~iDie()
00190 {
00191 }
00192 
00193 //______________________________________________________________________________
00194 void iDie::actionPerformed(xdata::Event& e)
00195 {
00196   
00197   if (e.type()=="ItemChangedEvent" ) {
00198     std::string item = dynamic_cast<xdata::ItemChangedEvent&>(e).itemName();
00199     
00200     if ( item == "runNumber") {
00201       LOG4CPLUS_WARN(getApplicationLogger(),
00202                      "New Run was started - iDie will reset");
00203       reset();
00204 
00205       dqmState_ = "Prepared";
00206       if (dqmEnabled_.value_) { 
00207         if (!evtProcessor_) initFramework();
00208         if (!meInitialized_) initMonitorElements();
00209         doFlush();
00210       }
00211     }
00212     
00213   }
00214 }
00215 
00216 //______________________________________________________________________________
00217 xoap::MessageReference iDie::fsmCallback(xoap::MessageReference msg)
00218   throw (xoap::exception::Exception)
00219 {
00220   
00221   xoap::SOAPPart     part    =msg->getSOAPPart();
00222   xoap::SOAPEnvelope env     =part.getEnvelope();
00223   xoap::SOAPBody     body    =env.getBody();
00224   DOMNode           *node    =body.getDOMNode();
00225   DOMNodeList       *bodyList=node->getChildNodes();
00226   DOMNode           *command =0;
00227   std::string             commandName;
00228   
00229   for (unsigned int i=0;i<bodyList->getLength();i++) {
00230     command = bodyList->item(i);
00231     if(command->getNodeType() == DOMNode::ELEMENT_NODE) {
00232       commandName = xoap::XMLCh2String(command->getLocalName());
00233       break;
00234     }
00235   }
00236   
00237   if (commandName.empty()) {
00238     XCEPT_RAISE(xoap::exception::Exception,"Command not found.");
00239   }
00240   
00241   // fire appropriate event and create according response message
00242   try {
00243 
00244     // response string
00245     xoap::MessageReference reply = xoap::createMessage();
00246     xoap::SOAPEnvelope envelope  = reply->getSOAPPart().getEnvelope();
00247     xoap::SOAPName responseName  = envelope.createName(commandName+"Response",
00248                                                        "xdaq",XDAQ_NS_URI);
00249     xoap::SOAPBodyElement responseElem =
00250       envelope.getBody().addBodyElement(responseName);
00251     
00252     // generate correct return state string
00253     std::string state;
00254     if(commandName == "Configure") {dqmState_ = "Ready"; state = "Ready";}
00255     else if(commandName == "Enable") {dqmState_ = "Enabled"; state = "Enabled";}
00256     else if(commandName == "Stop" || commandName == "Halt") {
00257       //remove histograms
00258       std::cout << " Stopping/Halting iDie. command=" << commandName << " initialized=" << meInitialized_ << std::endl;
00259       if (meInitialized_) {
00260         dqmState_ = "Removed";
00261         usleep(10000);//propagating dqmState to caches
00262         meInitialized_=false;
00263         meInitializedStreams_=false;
00264         meInitializedDatasets_=false;
00265         sleep(1);//making sure that any running ls update finishes
00266 
00267         dqmStore_->setCurrentFolder(topLevelFolder_.value_ + "/Layouts/");
00268         dqmStore_->removeContents();
00269         dqmStore_->setCurrentFolder(topLevelFolder_.value_ + "/Layouts/Streams/");
00270         dqmStore_->removeContents();
00271         dqmStore_->setCurrentFolder(topLevelFolder_.value_ + "/Layouts/Datasets/");
00272         dqmStore_->removeContents();
00273         dqmStore_->setCurrentFolder(topLevelFolder_.value_ + "/EventInfo/");
00274         dqmStore_->removeContents();
00275         doFlush(); 
00276       }
00277       if (reportingStart_) delete reportingStart_;
00278       reportingStart_=0;
00279       state = "Ready";
00280     }
00281     //else if(commandName == "Halt") state = "Halted";
00282     else state = "BOH";
00283 
00284     xoap::SOAPName    stateName     = envelope.createName("state",
00285                                                           "xdaq",XDAQ_NS_URI);
00286     xoap::SOAPElement stateElem     = responseElem.addChildElement(stateName);
00287     xoap::SOAPName    attributeName = envelope.createName("stateName",
00288                                                           "xdaq",XDAQ_NS_URI);
00289     stateElem.addAttribute(attributeName,state);
00290     
00291     return reply;
00292   }
00293   catch (toolbox::fsm::exception::Exception & e) {
00294     XCEPT_RETHROW(xoap::exception::Exception,"invalid command.",e);
00295   }     
00296   
00297 
00298 
00299 }
00300 
00301 //______________________________________________________________________________
00302 void iDie::defaultWeb(xgi::Input *in,xgi::Output *out)
00303   throw (xgi::exception::Exception)
00304 {
00305   cgicc::Cgicc cgi(in);
00306   std::string method = cgi.getEnvironment().getRequestMethod();
00307   if(method == "POST"){
00308     unsigned int run = 0;
00309     std::vector<cgicc::FormEntry> el1 = cgi.getElements();
00310     cgi.getElement("run",el1);
00311     if(el1.size()!=0){
00312       run = el1[0].getIntegerValue();
00313       if(run > runNumber_.value_ || runNumber_.value_==0){
00314         runNumber_.value_ = run;
00315         if(runNumber_.value_!=0) 
00316           {
00317             reset();
00318             if(f_ == 0)
00319               {
00320                 std::ostringstream ost;
00321                 ost << "microReport"<<runNumber_<<".root";
00322                 f_ = new TFile(ost.str().c_str(),"RECREATE","microreport");
00323               }
00324           }
00325       }
00326     }
00327     internal::fu fuinstance;
00328 
00329     fuinstance.ccount = 0;
00330     std::string hostname = cgi.getEnvironment().getRemoteHost();
00331     std::transform(hostname.begin(), hostname.end(),
00332                    hostname.begin(), ::toupper);
00333     fus_[hostname] = fuinstance;
00334   }
00335   else{
00336     *out << "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">" 
00337          << "<html><head><title>" << getApplicationDescriptor()->getClassName()
00338          << getApplicationDescriptor()->getInstance() << "</title>"
00339          << "<meta https-equiv=\"REFRESH\" content=\"0;url=/evf/html/idiePage.html\">"
00340          << "</head></html>";
00341   }
00342 }
00343 
00344 //______________________________________________________________________________
00345 void iDie::updater(xgi::Input *in,xgi::Output *out)
00346   throw (xgi::exception::Exception)
00347 {
00348   *out << runNumber_.value_ << std::endl;
00349 }
00350 //______________________________________________________________________________
00351 void iDie::summaryTable(xgi::Input *in,xgi::Output *out)
00352   throw (xgi::exception::Exception)
00353 {
00354     *out << "<tr><td>"<<fus_.size()<<"</td><td>" << totalCores_ 
00355          << "</td><td></td></tr>" << std::endl;
00356 }
00357 
00358 //______________________________________________________________________________
00359 void iDie::detailsTable(xgi::Input *in,xgi::Output *out)
00360   throw (xgi::exception::Exception)
00361 {
00362   timeval tv;
00363   gettimeofday(&tv,0);
00364   time_t now = tv.tv_sec;
00365   for(ifmap i = fus_.begin(); i != fus_.end(); i++)
00366     if((*i).second.ccount != 0){
00367       *out << "<tr><td " 
00368            << (now-(*i).second.tstamp<300 ? "style=\"background-color:red\"" : "")
00369            << ">"<<(*i).first<<"</td><td>" 
00370            << (*i).second.ccount << "</td>"
00371            << "<td onClick=loaddump(\'" << url_.value_ << "/dump?name="
00372            << (*i).first << "\')>" << (*i).second.cpids.back()
00373            << "</td><td>" <<(*i).second.signals.back() 
00374            << "</td></tr>" << std::endl;
00375     }
00376 }
00377 
00378 //______________________________________________________________________________
00379 void iDie::dumpTable(xgi::Input *in,xgi::Output *out)
00380   throw (xgi::exception::Exception)
00381 {
00382   cgicc::Cgicc cgi(in); 
00383 
00384   std::vector<cgicc::FormEntry> el1;
00385   cgi.getElement("name",el1);
00386   if(el1.size()!=0){
00387     std::string hostname = el1[0].getValue();
00388     std::transform(hostname.begin(), hostname.end(),
00389                    hostname.begin(), ::toupper);
00390     ifmap fi = fus_.find(hostname);    
00391     if(fi!=fus_.end()){
00392       *out << (*fi).second.stacktraces.back() << std::endl;
00393     }
00394     else{ 
00395       for(fi=fus_.begin(); fi != fus_.end(); fi++) 
00396         std::cout << "known hosts: " << (*fi).first << std::endl;
00397     }
00398   }
00399 }
00400 
00401 //______________________________________________________________________________
00402 void iDie::iChokeMiniInterface(xgi::Input *in,xgi::Output *out)
00403   throw (xgi::exception::Exception)
00404 {
00405   unsigned int i = 0;
00406 
00407   if(last_ls_==0) return; //wait until at least one complete cycle so we have all arrays sized correctly !!!
00408   *out << "<div id=\"cls\">" << last_ls_ << "</div>" 
00409        << "<div id=\"clr\">" << cpuentries_[last_ls_-1] << "</div>" << std::endl;
00410   sorted_indices tmp(cpustat_[last_ls_-1]);
00411   //  std::sort(tmp.begin(),tmp.end());// figure out how to remap indices of legenda
00412   *out << "<tbody id=\"cpue\">";
00413   while(i<nstates_){
00414     if(tmp[i]!=0) *out << "<tr><td>" << mapmod_[tmp.ii(i)] << "</td>" << "<td>" 
00415                        << float(tmp[i])/float(cpuentries_[last_ls_-1]) << "</td></tr>";
00416     i++;
00417   }
00418   *out << "</tbody>\n";
00419   *out << "<tbody id=\"cpui\"><tr><td></td>";
00420   unsigned int begin = last_ls_<5 ? 0 : last_ls_-5;
00421   for(i=begin; i < last_ls_; i++)
00422     *out << "<td>" << i +1 << "</td>";
00423   *out << "</tr><tr><td></td>";
00424   for(i=begin; i < last_ls_; i++)
00425     *out << "<td>" << float(cpustat_[i][2])/float(cpuentries_[i]) << "</td>";
00426   *out << "</tr></tbody>\n";
00427 
00428   *out << "<tbody id=\"rate\"><tr><td></td>";
00429   begin = last_ls_<5 ? 0 : last_ls_-5;
00430   for(i=begin; i < last_ls_; i++)
00431     *out << "<td>" << float(trp_[i].eventSummary.totalEventsPassed)/float(trp_[i].eventSummary.totalEvents) << "</td>"; 
00432   *out << "</tr>\n<tr><td></td>";
00433   for(i=begin; i < last_ls_; i++)
00434     *out << "<td>" << trp_[i].eventSummary.totalEvents << "</td>"; 
00435   *out << "</tr>\n<tr><td></td>";
00436   for(int j = 0; j < trp_[0].trigPathsInMenu; j++)
00437     {
00438       *out << "<tr><td></td>";
00439       for(i=begin; i < last_ls_; i++)
00440         *out << "<td>" << trp_[i].trigPathSummaries[j].timesPassed << "("
00441              << trp_[i].trigPathSummaries[j].timesPassedL1 << ")("
00442              << trp_[i].trigPathSummaries[j].timesPassedPs << ")</td>";
00443       *out << "<td>" << mappath_[j] << "</td>";
00444       *out << "</tr>\n";
00445     }
00446   for(int j = 0; j < trp_[0].endPathsInMenu; j++)
00447     {
00448       *out << "<tr><td></td>";
00449       for(i=begin; i < last_ls_; i++)
00450         *out << "<td>" << trp_[i].endPathSummaries[j].timesPassed << "</td>";
00451       *out << "<td>" << mappath_[j+trp_[last_ls_-1].trigPathsInMenu] << "</td>";
00452       *out << "</tr>\n";
00453     }
00454   *out << "</tbody>\n";
00455 }
00456 
00457 //______________________________________________________________________________
00458 void iDie::iChoke(xgi::Input *in,xgi::Output *out)
00459   throw (xgi::exception::Exception)
00460 {
00461     *out << "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">" 
00462          << "<html><head><title>" << getApplicationDescriptor()->getClassName()
00463          << getApplicationDescriptor()->getInstance() << "</title>"
00464          << "<meta https-equiv=\"REFRESH\" content=\"0;url=/evf/html/ichokePage.html\">"
00465          << "</head></html>";
00466 
00467 
00468 
00469 }
00470 
00471 //______________________________________________________________________________
00472 void iDie::postEntry(xgi::Input*in,xgi::Output*out)
00473   throw (xgi::exception::Exception)
00474 {
00475 
00476   timeval tv;
00477   gettimeofday(&tv,0);
00478   time_t now = tv.tv_sec;
00479 
00480   try {
00481     cgicc::Cgicc cgi(in); 
00482     unsigned int run = 0;
00483     pid_t cpid = 0;
00484     /*  cgicc::CgiEnvironment cgie(in);
00485         cout << "query = "  << cgie.getContentLength() << endl;
00486         */
00487     std::vector<cgicc::FormEntry> el1;
00488     el1 = cgi.getElements();
00489     //   for(unsigned int i = 0; i < el1.size(); i++)
00490     //     std::cout << "name="<<el1[i].getName() << std::endl;
00491     el1.clear();
00492     cgi.getElement("run",el1);
00493     if(el1.size()!=0)
00494     {
00495       run =  el1[0].getIntegerValue();
00496     }
00497     el1.clear();
00498     cgi.getElement("stacktrace",el1);
00499     if(el1.size()!=0)
00500     {
00501       cpid = run;
00502       //      std::cout << "=============== stacktrace =============" << std::endl;
00503       //      std::cout << el1[0].getValue() << std::endl;
00504       if(el1[0].getValue().find("Dead")==0){
00505 
00506         std::string host = cgi.getEnvironment().getRemoteHost();
00507         std::transform(host.begin(), host.end(),
00508                        host.begin(), ::toupper);
00509         ifmap fi = fus_.find(host);
00510         if(fi!=fus_.end()){
00511           fus_.erase(fi);
00512         }
00513         if(fus_.size()==0) { //close the root file if we know the run is over
00514 
00515           if(f_!=0){
00516             f_->cd();
00517             f_->Write();
00518           }
00519           if(t_ != 0) {
00520             delete t_;
00521             t_ = 0;
00522           }
00523           if(f_!=0){
00524             f_->Close();
00525             delete f_; f_ = 0;
00526           }
00527         }
00528       }
00529       else{
00530         totalCores_++;
00531         std::string st = el1[0].getValue();
00532         std::string sig; 
00533         size_t psig = st.find("signal");
00534         if(psig != std::string::npos)
00535           sig = st.substr(psig,9);
00536         std::string host = cgi.getEnvironment().getRemoteHost();
00537         std::transform(host.begin(), host.end(),
00538                        host.begin(), ::toupper);
00539         ifmap fi = fus_.find(host);
00540         if(fi!=fus_.end()){
00541           (*fi).second.tstamp = now;
00542           (*fi).second.ccount++;
00543           (*fi).second.cpids.push_back(cpid);
00544           (*fi).second.signals.push_back(sig);
00545           (*fi).second.stacktraces.push_back(st);
00546         }
00547       }
00548     }
00549     el1.clear();
00550     cgi.getElement("legenda",el1);
00551     if(el1.size()!=0)
00552     {
00553       parsePathLegenda(el1[0].getValue());
00554     }
00555     cgi.getElement("LegendaAux",el1);
00556     if (el1.size()!=0)
00557     {
00558       parseDatasetLegenda(el1[0].getValue());
00559     }
00560     cgi.getElement("trp",el1);
00561     if(el1.size()!=0)
00562     {
00563       unsigned int lsid = run;
00564       parsePathHisto((unsigned char*)(el1[0].getValue().c_str()),lsid);
00565     }
00566     el1.clear();
00567   }
00568   catch (edm::Exception &e) {
00569     LOG4CPLUS_ERROR(getApplicationLogger(),"Caught edm exception in postEntry: " << e.what());
00570   }
00571   catch (cms::Exception &e) {
00572     LOG4CPLUS_ERROR(getApplicationLogger(),"Caught cms exception in postEntry: " << e.what());
00573   }
00574   catch (std::exception &e) {
00575     LOG4CPLUS_ERROR(getApplicationLogger(),"Caught std exception in postEntry: " << e.what());
00576   }
00577   catch (...) {
00578     LOG4CPLUS_ERROR(getApplicationLogger(),"Caught unknown exception in postEntry");
00579   }
00580 
00581 }
00582 
00583 //______________________________________________________________________________
00584 void iDie::postEntryiChoke(xgi::Input*in,xgi::Output*out)
00585   throw (xgi::exception::Exception)
00586 {
00587   //  std::cout << "postEntryiChoke " << std::endl;
00588  
00589   if (dqmEnabled_.value_) {
00590     if (!evtProcessor_) initFramework();
00591     if (!meInitialized_) {
00592       if (dqmState_!="Removed") initMonitorElements();
00593     }
00594   }
00595 
00596 
00597   unsigned int lsid = 0;
00598   try {
00599     cgicc::Cgicc cgi(in); 
00600     /*  cgicc::CgiEnvironment cgie(in);
00601         cout << "query = "  << cgie.getContentLength() << endl;
00602         */
00603     std::vector<cgicc::FormEntry> el1;
00604     el1 = cgi.getElements();
00605     //   for(unsigned int i = 0; i < el1.size(); i++)
00606     //     std::cout << "name="<<el1[i].getName() << std::endl;
00607     el1.clear();
00608     cgi.getElement("run",el1);
00609     if(el1.size()!=0)
00610     {
00611       lsid =  el1[0].getIntegerValue();
00612     }
00613     el1.clear();
00614 
00615     //with the first message for the new lsid, resize all containers so 
00616     // a web access won't address an invalid location in case it interleaves between 
00617     // the first cpustat update and the first scalers update or viceversa
00618     if(lsid!=0){
00619       if(lsid>cpustat_.size()){
00620         cpustat_.resize(lsid,std::vector<int>(nstates_,0));
00621         cpuentries_.resize(lsid,0);
00622       }
00623       if(lsid>trp_.size()){
00624         trp_.resize(lsid);
00625         funcs::reset(&trp_[lsid-1]);
00626         trpentries_.resize(lsid,0);
00627       }
00628       if(last_ls_ < lsid) {
00629         last_ls_ = lsid; 
00630         funcs::reset(&trp_[lsid-1]);
00631         if(t_ && (last_ls_%10==0)) t_->Write();
00632       } 
00633     }
00634 
00635     cgi.getElement("legenda",el1);
00636     if(el1.size()!=0)
00637     {
00638       parseModuleLegenda(el1[0].getValue());
00639     }
00640     cgi.getElement("trp",el1);
00641     if(el1.size()!=0)
00642     {
00643       parseModuleHisto(el1[0].getValue().c_str(),lsid);
00644     }
00645     el1.clear();
00646   }
00647 
00648   catch (edm::Exception &e) {
00649     LOG4CPLUS_ERROR(getApplicationLogger(),"Caught edm exception in postEntryiChoke: " << e.what());
00650   }
00651   catch (cms::Exception &e) {
00652     LOG4CPLUS_ERROR(getApplicationLogger(),"Caught cms exception in postEntryiChoke: " << e.what());
00653   }
00654   catch (std::exception &e) {
00655     LOG4CPLUS_ERROR(getApplicationLogger(),"Caught std exception in postEntryiChoke: " << e.what());
00656   }
00657   catch (...) {
00658     LOG4CPLUS_ERROR(getApplicationLogger(),"Caught unknown exception in postEntryiChoke");
00659   }
00660 }
00661 
00662 
00663 void iDie::reset()
00664 {
00665   fus_.erase(fus_.begin(),fus_.end());
00666   totalCores_=0;
00667   last_ls_ = 0;
00668   trp_.clear();
00669   trpentries_.clear();
00670   cpustat_.clear();
00671   cpuentries_.clear();
00672 
00673   if(f_!=0){
00674     f_->cd();
00675     f_->Write();
00676   }
00677 
00678   if(t_ != 0)
00679   {
00680     delete t_; t_=0;
00681   }
00682 
00683   if(f_!=0){
00684     f_->Close();
00685     delete f_; f_ = 0;
00686   }
00687   if(datap_ != 0)
00688     {delete datap_; datap_ = 0;}
00689   b_=0; b1_=0; b2_=0; b3_=0; b4_=0;
00690 
00691 }
00692 
00693 void iDie::parseModuleLegenda(std::string leg)
00694 {
00695   nModuleLegendaMessageReceived_++;
00696   if(leg=="") return;
00697   gettimeofday(&lastModuleLegendaMessageTimeStamp_,0);
00698   nModuleLegendaMessageWithDataReceived_++;
00699   mapmod_.clear();
00700   //  if(cpustat_) delete cpustat_;
00701   boost::char_separator<char> sep(",");
00702   boost::tokenizer<boost::char_separator<char> > tokens(leg, sep);
00703   for (boost::tokenizer<boost::char_separator<char> >::iterator tok_iter = tokens.begin();
00704        tok_iter != tokens.end(); ++tok_iter){
00705     mapmod_.push_back((*tok_iter));
00706   }
00707   nstates_ = mapmod_.size();
00708   //  cpustat_ = new int[nstates_];
00709 //   for(int i = 0; i < nstates_; i++)
00710 //     cpustat_[i]=0;   
00711 //   cpuentries_ = 0;
00712 }
00713 
00714 void iDie::parseModuleHisto(const char *crp, unsigned int lsid)
00715 {
00716   if(lsid==0) return;
00717   nModuleHistoMessageReceived_++;
00718   int *trp = (int*)crp;
00719   if(t_==0 && f_!=0){
00720     datap_ = new int[nstates_+5];
00721     std::ostringstream ost;
00722     ost<<mapmod_[0]<<"/I";
00723     for(unsigned int i = 1; i < nstates_; i++)
00724       ost<<":"<<mapmod_[i];
00725     ost<<":nsubp:instance:nproc:ncpubusy";//
00726     f_->cd();
00727     t_ = new TTree("microReport","microstate report tree");
00728     t_->SetAutoSave(500000);
00729     b_ = t_->Branch("microstates",datap_,ost.str().c_str());
00730     b1_ = t_->Branch("ls",&lsid,"ls/I");
00731 
00732   }
00733 
00734   memcpy(datap_,trp,(nstates_+5)*sizeof(int));
00735   //check ls for subprocess type
00736   unsigned int datapLen_ = nstates_+5;
00737   unsigned int nbsubs_ = datap_[datapLen_-5];
00738   unsigned int nbproc_ = datap_[datapLen_-3];
00739   unsigned int ncpubusy_ = datap_[datapLen_-2];
00740   unsigned int deltaTms_ = datap_[datapLen_-1];
00741 
00742   //find index number
00743   int nbsIdx = -1;
00744 
00745   /* debugging test
00746   unsigned int randls = 0;
00747   unsigned int randslot = 0;
00748   if (lsid>3) {
00749     randslot = rand();
00750     if (randslot%2) nbsubs_=7;
00751     else nbsubs_=8;
00752     randls = rand();
00753     randls%=3;
00754     lsid-=randls;
00755   }
00756   */
00757 
00758   if (meInitialized_ && nbSubsList.find(nbsubs_)!=nbSubsList.end() && lsid) {
00759      nbsIdx = nbSubsList[nbsubs_];
00760     if (currentLs_[nbsIdx]<lsid) {//new lumisection for this ep class
00761       if (currentLs_[nbsIdx]!=0) {
00762         if (lsHistory[nbsIdx].size()) {
00763           
00764           //refresh run/lumi number and timestamp
00765           runId_->Fill(runNumber_.value_);
00766           lumisecId_->Fill(currentLs_[nbsIdx]);
00767           struct timeval now;
00768           gettimeofday(&now, 0);
00769           eventTimeStamp_->Fill(  now.tv_sec + 1e-6*now.tv_usec );
00770 
00771           //do histogram updates for the lumi
00772           lsStat * lst = lsHistory[nbsIdx].back();
00773           fillDQMStatHist(nbsIdx,currentLs_[nbsIdx]);
00774           fillDQMModFractionHist(nbsIdx,currentLs_[nbsIdx],lst->getNSampledNonIdle(),
00775               lst->getOffendersVector());
00776           doFlush();
00777           perLumiFileSaver(currentLs_[nbsIdx]);
00778           perTimeFileSaver();
00779         }
00780       }
00781 
00782       currentLs_[nbsIdx]=lsid;
00783 
00784       //add elements for new lumisection, fill the gap if needed
00785       unsigned int lclast = commonLsHistory.size() ? commonLsHistory.back()->ls_:0;
00786       for (unsigned int newls=lclast+1;newls<=lsid;newls++) {
00787           commonLsHistory.push_back(new commonLsStat(newls,epInstances.size()));
00788       }
00789 
00790       unsigned int lhlast = lsHistory[nbsIdx].size() ? lsHistory[nbsIdx].back()->ls_:0;
00791       for (size_t newls=lhlast+1;newls<=lsid;newls++) {
00792         lsHistory[nbsIdx].push_back(new lsStat(newls,nbsubs_,nModuleLegendaMessageReceived_,nstates_));
00793       }
00794 
00795       //remove old elements from queues
00796       while (commonLsHistory.size()>ROLL) {delete commonLsHistory.front(); commonLsHistory.pop_front();}
00797       while (lsHistory[nbsIdx].size()>ROLL) {delete lsHistory[nbsIdx].front(); lsHistory[nbsIdx].pop_front();}
00798     }
00799     if (currentLs_[nbsIdx]>=lsid) { // update for current or previous lumis
00800       unsigned int qsize=lsHistory[nbsIdx].size();
00801       unsigned int delta = currentLs_[nbsIdx]-lsid;
00802       if (qsize>delta && delta<ROLL) {
00803         lsStat * lst = (lsHistory[nbsIdx])[qsize-delta-1];
00804         unsigned int cumulative_ = 0;
00805         auto fillvec = lst->getModuleSamplingPtr();
00806         for (unsigned int i=0;i<nstates_;i++) {
00807           cumulative_+=datap_[i];
00808           if (fillvec) {
00809             fillvec[i].second+=datap_[i];
00810           }
00811         }
00812         unsigned int busyCounts = cumulative_-datap_[2];
00813         lst->update(busyCounts,datap_[2],nbproc_,ncpubusy_,deltaTms_);
00814       }
00815     }
00816   }
00817   else {
00818     //no predefined plots for this number of sub processes
00819   }
00820 
00821   if(t_!=0){
00822     t_->SetEntries(t_->GetEntries()+1); b_->Fill(); b1_->Fill();
00823   }
00824 
00825   for(unsigned int i=0;i<nstates_; i++)
00826     {
00827       cpustat_[lsid-1][i] += trp[i];
00828       cpuentries_[lsid-1] += trp[i];
00829     }
00830 }
00831 
00832 
00833 void iDie::parsePathLegenda(std::string leg)
00834 {
00835   nPathLegendaMessageReceived_++;
00836   if(leg=="")return;
00837   gettimeofday(&lastPathLegendaMessageTimeStamp_,0);
00838   nPathLegendaMessageWithDataReceived_++;
00839   mappath_.clear();
00840   boost::char_separator<char> sep(",");
00841   boost::tokenizer<boost::char_separator<char> > tokens(leg, sep);
00842   endPathNames_.clear();
00843   for (boost::tokenizer<boost::char_separator<char> >::iterator tok_iter = tokens.begin();
00844        tok_iter != tokens.end(); ++tok_iter){
00845       mappath_.push_back((*tok_iter));
00846 
00847       if (std::string(*tok_iter).find("Output")!=std::string::npos) {
00848         std::string path_token = *tok_iter;
00849         if (path_token.find("=")!=std::string::npos)
00850           endPathNames_.push_back(path_token.substr(path_token.find("=")+1));
00851         else
00852           endPathNames_.push_back(*tok_iter);
00853       }
00854   }
00855   //look for daqval-type menu if no "Output" endpaths found
00856   if (!endPathNames_.size()) {
00857           
00858     for (boost::tokenizer<boost::char_separator<char> >::iterator tok_iter = tokens.begin();
00859         tok_iter != tokens.end(); ++tok_iter){
00860 
00861       if (std::string(*tok_iter).find("output")!=std::string::npos) {
00862         std::string path_token = *tok_iter;
00863         if (path_token.find("=")!=std::string::npos)
00864           endPathNames_.push_back(path_token.substr(path_token.find("=")+1));
00865         else
00866           endPathNames_.push_back(*tok_iter);
00867       }
00868     }
00869   }
00870 }
00871 
00872 void iDie::parseDatasetLegenda(std::string leg)
00873 {
00874   nDatasetLegendaMessageReceived_++;
00875   datasetNames_.clear();
00876   dsMismatch=0;
00877   if(leg=="")return;
00878   gettimeofday(&lastDatasetLegendaMessageTimeStamp_,0);
00879   nDatasetLegendaMessageWithDataReceived_++;
00880   try {
00881     boost::char_separator<char> sep(",");
00882     boost::tokenizer<boost::char_separator<char> > tokens(leg, sep);
00883     for (boost::tokenizer<boost::char_separator<char> >::iterator tok_iter = tokens.begin();
00884         tok_iter != tokens.end(); ++tok_iter) {
00885       datasetNames_.push_back((*tok_iter));
00886     }
00887   }
00888   catch (...) {}
00889 }
00890 
00891 void iDie::parsePathHisto(const unsigned char *crp, unsigned int lsid)
00892 {
00893   if(lsid==0) return;
00894   nPathHistoMessageReceived_++;
00895 //   if(lsid>=trp_.size()){
00896 //     trp_.resize(lsid);
00897 //     funcs::reset(&trp_[lsid-1]);
00898 //     trpentries_.resize(lsid,0);
00899 //   }
00900   trppriv_ = (TriggerReportStatic*)crp;
00901   for( int i=0; i< trppriv_->trigPathsInMenu; i++)
00902     {
00903       r_.ptimesRun[i] = trppriv_->trigPathSummaries[i].timesRun;
00904       r_.ptimesPassedPs[i] = trppriv_->trigPathSummaries[i].timesPassedPs;
00905       r_.ptimesPassedL1[i] = trppriv_->trigPathSummaries[i].timesPassedL1;
00906       r_.ptimesPassed[i] = trppriv_->trigPathSummaries[i].timesPassed;
00907       r_.ptimesFailed[i] = trppriv_->trigPathSummaries[i].timesFailed;
00908       r_.ptimesExcept[i] = trppriv_->trigPathSummaries[i].timesExcept;
00909     }
00910   //find |common ls history" object for current ls
00911   commonLsStat * cst = 0;
00912   if (meInitialized_) {
00913     if (commonLsHistory.size()) cst=commonLsHistory.back();
00914     if (cst && cst->ls_>=lsid) {
00915       unsigned int countback=commonLsHistory.size()-1;
00916       while (cst->ls_>lsid && countback) {
00917         countback--;
00918         cst=commonLsHistory[countback];
00919       }
00920     }
00921   }
00922 
00923   for( int i=0; i< trppriv_->endPathsInMenu; i++)
00924     {
00925       r_.etimesRun[i] = trppriv_->endPathSummaries[i].timesRun;
00926       r_.etimesPassedPs[i] = trppriv_->endPathSummaries[i].timesPassedPs;
00927       r_.etimesPassedL1[i] = trppriv_->endPathSummaries[i].timesPassedL1;
00928       r_.etimesPassed[i] = trppriv_->endPathSummaries[i].timesPassed;
00929       r_.etimesFailed[i] = trppriv_->endPathSummaries[i].timesFailed;
00930       r_.etimesExcept[i] = trppriv_->endPathSummaries[i].timesExcept;
00931       if (cst) {
00932         if ((unsigned)i < cst->endPathCounts_.size()) cst->endPathCounts_[i]+=r_.etimesPassed[i];
00933         else cst->endPathCounts_.push_back(r_.etimesPassed[i]);
00934       }
00935     }
00936 
00937   //mismatch in expected and reported dataset number
00938   if (trppriv_->datasetsInMenu!=(int)datasetNames_.size())
00939   {
00940     dsMismatch++;
00941     if  (!(dsMismatch%100) || dsMismatch<10) {
00942       LOG4CPLUS_WARN(getApplicationLogger(),"mismatch in number of datasets! " 
00943           << trppriv_->datasetsInMenu << " in report, " << datasetNames_.size() 
00944           << " from legend! received legends:"<< nDatasetLegendaMessageWithDataReceived_);
00945     }
00946   }
00947 
00948   for( int i=0; i< trppriv_->datasetsInMenu; i++)
00949   {
00950     if (cst) {
00951       if ((unsigned)i < cst->datasetCounts_.size()) cst->datasetCounts_[i]+=trppriv_->datasetSummaries[i].timesPassed;
00952       else cst->datasetCounts_.push_back(trppriv_->datasetSummaries[i].timesPassed);
00953     }
00954   }
00955 
00956   r_.nproc = trppriv_->eventSummary.totalEvents;
00957   r_.nsub = trppriv_->nbExpected;
00958   r_.nrep = trppriv_->nbReporting;
00959 
00960 
00961   if(t_!=0 && f_!=0 && b2_==0){
00962 
00963     b2_ = t_->Branch("rate",&r_,"nproc/I:nsub:nrep");
00964     std::ostringstream ost1;
00965     ost1 << "p_nrun[" << trppriv_->trigPathsInMenu
00966          << "]/I:p_npps[" << trppriv_->trigPathsInMenu
00967          << "]:p_npl1[" << trppriv_->trigPathsInMenu
00968          << "]:p_npp[" << trppriv_->trigPathsInMenu 
00969          << "]:p_npf[" << trppriv_->trigPathsInMenu
00970          << "]:p_npe[" << trppriv_->trigPathsInMenu <<"]";
00971 
00972     b3_ = t_->Branch("paths",r_.ptimesRun,ost1.str().c_str());
00973     std::ostringstream ost2;
00974     ost2 << "ep_nrun[" << trppriv_->endPathsInMenu
00975          << "]/I:en_npps[" << trppriv_->endPathsInMenu
00976          << "]:ep_npl1[" << trppriv_->endPathsInMenu
00977          << "]:ep_npp[" << trppriv_->endPathsInMenu
00978          << "]:ep_npf[" << trppriv_->endPathsInMenu
00979          << "]:ep_npe[" << trppriv_->endPathsInMenu << "]";
00980     b4_ = t_->Branch("endpaths",r_.etimesRun,ost2.str().c_str());
00981   }
00982   if(b2_!=0) b2_->Fill();
00983   if(b3_!=0) b3_->Fill();
00984   if(b4_!=0) b4_->Fill();
00985 
00986   funcs::addToReport(&trp_[lsid-1],trppriv_,lsid);
00987   trpentries_[lsid-1]++;
00988 
00989 }
00990 
00991 // web pages
00992 
00993 void iDie::spotlight(xgi::Input *in,xgi::Output *out)
00994   throw (xgi::exception::Exception)
00995 {
00996 
00997   std::string urn = getApplicationDescriptor()->getURN();
00998 
00999   *out << "<!-- base href=\"/" <<  urn
01000        << "\"> -->" << std::endl;
01001   *out << "<html>"                                                   << std::endl;
01002   *out << "<head>"                                                   << std::endl;
01003   *out << "<link type=\"text/css\" rel=\"stylesheet\"";
01004   *out << " href=\"/evf/html/styles.css\"/>"                   << std::endl;
01005   *out << "<title>" << getApplicationDescriptor()->getClassName() 
01006        << getApplicationDescriptor()->getInstance() 
01007        << " MAIN</title>"     << std::endl;
01008   *out << "</head>"                                                  << std::endl;
01009   *out << "<body>"                                                   << std::endl;
01010   *out << "<table border=\"0\" width=\"100%\">"                      << std::endl;
01011   *out << "<tr>"                                                     << std::endl;
01012   *out << "  <td align=\"left\">"                                    << std::endl;
01013   *out << "    <img"                                                 << std::endl;
01014   *out << "     align=\"middle\""                                    << std::endl;
01015   *out << "     src=\"/evf/images/spoticon.jpg\""                            << std::endl;
01016   *out << "     alt=\"main\""                                        << std::endl;
01017   *out << "     width=\"64\""                                        << std::endl;
01018   *out << "     height=\"64\""                                       << std::endl;
01019   *out << "     border=\"\"/>"                                       << std::endl;
01020   *out << "    <b>"                                                  << std::endl;
01021   *out << getApplicationDescriptor()->getClassName() 
01022        << getApplicationDescriptor()->getInstance()                  << std::endl;
01023   *out << "    </b>"                                                 << std::endl;
01024   *out << "  </td>"                                                  << std::endl;
01025   *out << "  <td width=\"32\">"                                      << std::endl;
01026   *out << "    <a href=\"/urn:xdaq-application:lid=3\">"             << std::endl;
01027   *out << "      <img"                                               << std::endl;
01028   *out << "       align=\"middle\""                                  << std::endl;
01029   *out << "       src=\"/hyperdaq/images/HyperDAQ.jpg\""             << std::endl;
01030   *out << "       alt=\"HyperDAQ\""                                  << std::endl;
01031   *out << "       width=\"32\""                                      << std::endl;
01032   *out << "       height=\"32\""                                     << std::endl;
01033   *out << "       border=\"\"/>"                                     << std::endl;
01034   *out << "    </a>"                                                 << std::endl;
01035   *out << "  </td>"                                                  << std::endl;
01036   *out << "  <td width=\"32\">"                                      << std::endl;
01037   *out << "  </td>"                                                  << std::endl;
01038   *out << "  <td width=\"32\">"                                      << std::endl;
01039   *out << "    <a href=\"/" << urn << "/\">"                         << std::endl;
01040   *out << "      <img"                                               << std::endl;
01041   *out << "       align=\"middle\""                                  << std::endl;
01042   *out << "       src=\"/evf/images/idieapp.jpg\""                   << std::endl;
01043   *out << "       alt=\"main\""                                      << std::endl;
01044   *out << "       width=\"32\""                                      << std::endl;
01045   *out << "       height=\"32\""                                     << std::endl;
01046   *out << "       border=\"\"/>"                                     << std::endl;
01047   *out << "    </a>"                                                 << std::endl;
01048   *out << "  </td>"                                                  << std::endl;
01049   *out << "</tr>"                                                    << std::endl;
01050   *out << "</table>"                                                 << std::endl;
01051   *out << "<hr/>"                                                    << std::endl;
01052   *out << "<table><tr><th>Parameter</th><th>Value</th></tr>"         << std::endl;
01053   *out << "<tr><td>module legenda messages received</td><td>" 
01054        << nModuleLegendaMessageReceived_ << "</td></tr>"      << std::endl;
01055   *out << "<tr><td>path legenda messages received</td><td>" 
01056        << nPathLegendaMessageReceived_ << "</td></tr>"        << std::endl;
01057   *out << "<tr><td>module legenda messages with data</td><td>" 
01058        << nModuleLegendaMessageWithDataReceived_ << "</td></tr>"      << std::endl;
01059   *out << "<tr><td>path legenda messages with data</td><td>" 
01060        << nPathLegendaMessageWithDataReceived_ << "</td></tr>"        << std::endl;
01061   *out << "<tr><td>dataset legenda messages with data</td><td>" 
01062        << nDatasetLegendaMessageWithDataReceived_ << "</td></tr>"        << std::endl;
01063   *out << "<tr><td>module histo messages received</td><td>" 
01064        << nModuleHistoMessageReceived_<< "</td></tr>"        << std::endl;
01065   *out << "<tr><td>path histo messages received</td><td>" 
01066        << nPathHistoMessageReceived_<< "</td></tr>"        << std::endl;
01067   tm *uptm = localtime(&lastPathLegendaMessageTimeStamp_.tv_sec);
01068   char datestring[256];
01069   strftime(datestring, sizeof(datestring),"%c", uptm);
01070   *out << "<tr><td>time stamp of last path legenda with data</td><td>" 
01071        << datestring << "</td></tr>"        << std::endl;
01072   uptm = localtime(&lastModuleLegendaMessageTimeStamp_.tv_sec);
01073   strftime(datestring, sizeof(datestring),"%c", uptm);
01074   *out << "<tr><td>time stamp of last module legenda with data</td><td>" 
01075        << datestring << "</td></tr>"        << std::endl;
01076   *out << "</table></body>" << std::endl;
01077 
01078 }
01079 
01080 void iDie::initFramework()
01081 {
01082 
01083   //ParameterSetRetriever pr(configString_);
01084   //std::string configuration_ = pr.getAsString();
01085 
01086   std::string configuration_ = configString_;
01087   configuration_.replace(configuration_.find("EMPTYHOST"),9,dqmCollectorHost_.value_);
01088 
01089   //check if port is a number
01090   {
01091     std::string & s = dqmCollectorPort_.value_;
01092     std::string::const_iterator it = s.begin();
01093     while (it != s.end() && std::isdigit(*it)) ++it;
01094     if (it != s.end() || s.empty()) dqmCollectorPort_="0";
01095   }
01096   configuration_.replace(configuration_.find("EMPTYPORT"),9,dqmCollectorPort_.value_);
01097 
01098   PythonProcessDesc ppdesc = PythonProcessDesc(configuration_);
01099   boost::shared_ptr<edm::ProcessDesc> pdesc;
01100   std::vector<std::string> defaultServices = {"InitRootHandlers"};
01101   pdesc = ppdesc.processDesc();
01102   pdesc->addServices(defaultServices);
01103 
01104   if (!pServiceSets_) {
01105     pServiceSets_ = pdesc->getServicesPSets();
01106     edmplugin::PluginManager::configure(edmplugin::standard::config());
01107   }
01108   try {
01109     edm::PresenceFactory *pf = edm::PresenceFactory::get();
01110     if(pf != 0) {
01111       pf->makePresence("MessageServicePresence").release();
01112     }
01113     else {
01114     LOG4CPLUS_WARN(getApplicationLogger(),"Unable to create message service presence");
01115     }
01116   } 
01117   catch(edm::Exception e) {
01118     LOG4CPLUS_WARN(getApplicationLogger(),e.what());
01119   }
01120 
01121   catch(cms::Exception e) {
01122     LOG4CPLUS_WARN(getApplicationLogger(),e.what());
01123   }
01124  
01125   catch(std::exception e) {
01126     LOG4CPLUS_WARN(getApplicationLogger(),e.what());
01127   }
01128   catch(...) {
01129     LOG4CPLUS_WARN(getApplicationLogger(),"Unknown Exception (Message Presence)");
01130   }
01131 
01132   try {
01133   serviceToken_ = edm::ServiceRegistry::createSet(*pServiceSets_);
01134   }
01135   catch (...) {
01136     LOG4CPLUS_WARN(getApplicationLogger(),"Failed creation of service token ");
01137     dqmEnabled_.value_=false;
01138   }
01139   edm::ServiceRegistry::Operate operate(serviceToken_);
01140 
01141   evtProcessor_ = new edm::EventProcessor(pdesc,
01142       serviceToken_,
01143       edm::serviceregistry::kTokenOverrides);
01144 
01145   try{
01146     if(edm::Service<DQMStore>().isAvailable())
01147       dqmStore_ = edm::Service<DQMStore>().operator->();
01148   }
01149   catch(...) {
01150     LOG4CPLUS_WARN(getApplicationLogger(),"exception when trying to get service DQMStore");
01151     dqmEnabled_.value_=false;
01152   }
01153   try{
01154     if(edm::Service<DQMService>().isAvailable())
01155       dqmService_ = edm::Service<DQMService>().operator->();
01156   }
01157   catch(...) {
01158     LOG4CPLUS_WARN(getApplicationLogger(),"exception when trying to get service DQMService");
01159     dqmEnabled_.value_=false;
01160   }
01161   if (!dqmEnabled_.value_) LOG4CPLUS_ERROR(getApplicationLogger(),"Failed to initialize DQMService/DQMStore");
01162 
01163   if (dqmState_!="Removed")
01164     initMonitorElements();
01165 
01166 }
01167 
01168 void iDie::initMonitorElements()
01169 {
01170   if (!evtProcessor_) return;
01171   dqmStore_->cd();
01172 
01173   meVecRate_.clear();
01174   meVecTime_.clear();
01175   meVecOffenders_.clear();
01176   for (unsigned int i=0;i<epInstances.size();i++) {
01177           currentLs_[i]=0;
01178   }
01179   ilumiprev_ = 0;
01180   savedForLs_=0;
01181   summaryLastLs_ = 0;
01182   pastSavedFiles_.clear();
01183   
01184   dqmStore_->setCurrentFolder(topLevelFolder_.value_ + "/EventInfo/");
01185   runId_     = dqmStore_->bookInt("iRun");
01186   runId_->Fill(-1);
01187   lumisecId_ = dqmStore_->bookInt("iLumiSection");
01188   lumisecId_->Fill(-1);
01189   eventId_ = dqmStore_->bookInt("iEvent");
01190   eventId_->Fill(-1);
01191   eventTimeStamp_ = dqmStore_->bookFloat("eventTimeStamp");
01192 
01193   dqmStore_->setCurrentFolder(topLevelFolder_.value_ + "/Layouts/");
01194   for (unsigned int i=0;i<nbSubsClasses;i++) {
01195     std::ostringstream str;
01196     str << nbSubsListInv[i];
01197     meVecRate_.push_back(dqmStore_->book1D("EVENT_RATE_"+TString(str.str().c_str()),
01198           "Average event rate for nodes with " + TString(str.str().c_str()) + " EP instances",
01199           4000,1.,4001));
01200     meVecTime_.push_back(dqmStore_->book1D("EVENT_TIME_"+TString(str.str().c_str()),
01201           "Average event processing time for nodes with " + TString(str.str().c_str()) + " EP instances",
01202           4000,1.,4001));
01203     meVecOffenders_.push_back(dqmStore_->book2D("MODULE_FRACTION_"+TString(str.str().c_str()),
01204           "Module processing time fraction_"+ TString(str.str().c_str()),
01205           ROLL,1.,1.+ROLL,MODNAMES,0,MODNAMES));
01206     //fill 1 in underrflow bin
01207     meVecOffenders_[i]->Fill(0,1);
01208     occupancyNameMap[i].clear();
01209   }
01210   rateSummary_   = dqmStore_->book2D("00_RATE_SUMMARY","Rate Summary (Hz)",ROLL,0,ROLL,epInstances.size()+1,0,epInstances.size()+1);
01211   reportPeriodSummary_   = dqmStore_->book2D("00_REPORT_PERIOD_SUMMARY","Average report period (s)",ROLL,0,ROLL,epInstances.size()+1,0,epInstances.size()+1);
01212   timingSummary_ = dqmStore_->book2D("01_TIMING_SUMMARY","Event Time Summary (ms)",ROLL,0,ROLL,epInstances.size()+1,0,epInstances.size()+1);
01213   busySummary_ = dqmStore_->book2D("02_BUSY_SUMMARY","Busy fraction ",ROLL,0,ROLL,epInstances.size()+2,0,epInstances.size()+2);
01214   busySummary2_ = dqmStore_->book2D("03_BUSY_SUMMARY_PROCSTAT","Busy fraction from /proc/stat",ROLL,0,ROLL,epInstances.size()+2,0,epInstances.size()+2);
01215   busySummaryUncorr1_ = dqmStore_->book2D("04_BUSY_SUMMARY_UNCORR","Busy fraction (uncorrected)",
01216       ROLL,0,ROLL,epInstances.size()+2,0,epInstances.size()+2);
01217   busySummaryUncorr2_ = dqmStore_->book2D("05_BUSY_SUMMARY_UNCORR_PROCSTAT","Busy fraction from /proc/stat(uncorrected)",
01218       ROLL,0,ROLL,epInstances.size()+2,0,epInstances.size()+2);
01219   fuReportsSummary_ = dqmStore_->book2D("06_EP_REPORTS_SUMMARY","Number of reports received",ROLL,0,ROLL,epInstances.size()+1,0,epInstances.size()+1);
01220 
01221   //busyModules_  = dqmStore_->book2D("MODULES_BUSY",ROLL,1.,1.+ROLL,MODNAMES,0,MODNAMES);
01222   //everything goes into layouts folder
01223   std::ostringstream busySummaryTitle;
01224   busySummaryTitle << "DAQ HLT Farm busy (%) for run "<< runNumber_.value_;
01225   lastRunNumberSet_ = runNumber_.value_;
01226   daqBusySummary_ = dqmStore_->book1D("reportSummaryMap",busySummaryTitle.str(),4000,1,4001.);
01227   daqBusySummary2_ = dqmStore_->book1D("reportSummaryMap_PROCSTAT","DAQ HLT Farm busy (%) from /proc/stat",4000,1,4001.);
01228 
01229   for (size_t i=1;i<=ROLL;i++) {
01230     std::ostringstream ostr;
01231     ostr << i;
01232     rateSummary_->setBinLabel(i,ostr.str(),1);
01233     reportPeriodSummary_->setBinLabel(i,ostr.str(),1);
01234     timingSummary_->setBinLabel(i,ostr.str(),1);
01235     busySummary_->setBinLabel(i,ostr.str(),1);
01236     busySummary2_->setBinLabel(i,ostr.str(),1);
01237     busySummaryUncorr1_->setBinLabel(i,ostr.str(),1);
01238     busySummaryUncorr2_->setBinLabel(i,ostr.str(),1);
01239     fuReportsSummary_->setBinLabel(i,ostr.str(),1);
01240   }
01241   for (size_t i=1;i<epInstances.size()+1;i++) {
01242     std::ostringstream ostr;
01243     ostr << epInstances[i-1];
01244     rateSummary_->setBinLabel(i,ostr.str(),2);
01245     reportPeriodSummary_->setBinLabel(i,ostr.str(),2);
01246     timingSummary_->setBinLabel(i,ostr.str(),2);
01247     busySummary_->setBinLabel(i,ostr.str(),2);
01248     busySummary2_->setBinLabel(i,ostr.str(),2);
01249     busySummaryUncorr1_->setBinLabel(i,ostr.str(),2);
01250     busySummaryUncorr2_->setBinLabel(i,ostr.str(),2);
01251     fuReportsSummary_->setBinLabel(i,ostr.str(),2);
01252   }
01253   rateSummary_->setBinLabel(epInstances.size()+1,"All",2);
01254   //timingSummary_->setBinLabel(i,"Avg",2);
01255   busySummary_->setBinLabel(epInstances.size()+1,"%Conf",2);
01256   busySummary_->setBinLabel(epInstances.size()+2,"%Max",2);
01257   busySummary2_->setBinLabel(epInstances.size()+1,"%Conf",2);
01258   busySummary2_->setBinLabel(epInstances.size()+2,"%Max",2);
01259   fuReportsSummary_->setBinLabel(epInstances.size()+1,"All",2);
01260 
01261   //wipe out all ls history
01262   for (size_t i=0;i<epInstances.size();i++) {
01263     while (lsHistory[i].size()) {
01264       delete lsHistory[i].front();
01265       lsHistory[i].pop_front();
01266     }
01267   }
01268   while (commonLsHistory.size()) {
01269     delete commonLsHistory.front();
01270     commonLsHistory.pop_front();
01271   }
01272   meInitialized_=true;
01273 
01274 }
01275 
01276 void iDie::initMonitorElementsStreams() {
01277   if (!dqmEnabled_.value_ || !evtProcessor_) return;
01278   if (meInitializedStreams_) return;
01279 
01280   //add OUTPUT Stream histograms
01281   endPathRates_.clear();
01282   dqmStore_->setCurrentFolder(topLevelFolder_.value_ + "/Layouts/Streams/");
01283   for (size_t i=0;i<endPathNames_.size();i++) {
01284     endPathRates_.push_back(dqmStore_->book1D(endPathNames_[i]+"_RATE",endPathNames_[i]+" events/s",4000,1,4001.));
01285   }
01286   meInitializedStreams_=true;
01287 }
01288 
01289 
01290 void iDie::initMonitorElementsDatasets() {
01291   if (!dqmEnabled_.value_ || !evtProcessor_) return;
01292   if (meInitializedDatasets_) return;
01293 
01294   //add OUTPUT Stream histograms
01295   datasetRates_.clear();
01296   dqmStore_->setCurrentFolder(topLevelFolder_.value_ + "/Layouts/Datasets/");
01297   for (size_t i=0;i<datasetNames_.size();i++) {
01298     datasetRates_.push_back(dqmStore_->book1D(datasetNames_[i]+"_RATE",datasetNames_[i]+" events/s",4000,1,4001.));
01299   }
01300   meInitializedDatasets_=true;
01301 }
01302 
01303 
01304 void iDie::deleteFramework()
01305 {
01306   if (evtProcessor_) delete evtProcessor_;
01307 }
01308 
01309 void iDie::fillDQMStatHist(unsigned int nbsIdx, unsigned int lsid)
01310 {
01311   if (!evtProcessor_ || lsid==0) return;
01312   unsigned int qsize = lsHistory[nbsIdx].size();
01313   //may be larger size
01314   unsigned int cqsize = lsHistory[nbsIdx].size();
01315 
01316   //update lumis
01317   if (qsize) {
01318     for (int i =(int)qsize-1;i>=0 && i>=(int)qsize-PASTUPDATES;i--) {
01319       unsigned int qpos=(unsigned int) i;
01320       unsigned int forls = lsid - (qsize-1-i);
01321       lsStat * lst = (lsHistory[nbsIdx])[qpos];
01322       unsigned int clsPos = unsigned((int)qpos+ (int)cqsize - (int)qsize);
01323       commonLsStat * clst = commonLsHistory[unsigned((int)qpos+ (int)cqsize - (int)qsize)];
01324 
01325       meVecRate_[nbsIdx]->setBinContent(forls,lst->getRatePerMachine());
01326       meVecRate_[nbsIdx]->setBinError(forls,lst->getRateErrPerMachine());
01327       meVecTime_[nbsIdx]->setBinContent(forls>2? forls:0,lst->getEvtTime()*1000);//msec
01328       meVecTime_[nbsIdx]->setBinError(forls>2? forls:0,lst->getEvtTimeErr()*1000);//msec
01329       updateRollingHistos(nbsIdx, forls,lst,clst,i==(int)qsize-1);
01330       commonLsStat * prevclst = clsPos>0 ? commonLsHistory[clsPos-1]:nullptr;
01331       updateStreamHistos(forls,clst,prevclst);
01332       updateDatasetHistos(forls,clst,prevclst);
01333     }
01334   }
01335 }
01336 
01337 void iDie::updateRollingHistos(unsigned int nbsIdx, unsigned int lsid, lsStat * lst, commonLsStat  * clst, bool roll) {
01338   unsigned int lsidBin;
01339   if (roll) {
01340     if (lsid>ROLL) {
01341       lsidBin=ROLL;
01342       if (lsid>summaryLastLs_) { //last ls in plots isn't up to date
01343         unsigned int lsdiff = lsid-summaryLastLs_;
01344         for (unsigned int i=1;i<=ROLL;i++) {
01345           if (i<ROLL) {
01346             bool emptyBin=false;
01347             if (i>ROLL-lsdiff) emptyBin=true;
01348             for (unsigned int j=1;j<=epInstances.size()+1;j++) {
01349               rateSummary_->setBinContent(i,j,emptyBin? 0 : rateSummary_->getBinContent(i+lsdiff,j));
01350               reportPeriodSummary_->setBinContent(i,j,emptyBin? 0 : reportPeriodSummary_->getBinContent(i+lsdiff,j));
01351               timingSummary_->setBinContent(i,j,emptyBin ? 0 : timingSummary_->getBinContent(i+lsdiff,j));
01352               busySummary_->setBinContent(i,j,emptyBin ? 0 : busySummary_->getBinContent(i+lsdiff,j));
01353               busySummary2_->setBinContent(i,j,emptyBin ? 0 : busySummary2_->getBinContent(i+lsdiff,j));
01354               busySummaryUncorr1_->setBinContent(i,j,emptyBin ? 0 : busySummaryUncorr1_->getBinContent(i+lsdiff,j));
01355               busySummaryUncorr2_->setBinContent(i,j,emptyBin ? 0 : busySummaryUncorr2_->getBinContent(i+lsdiff,j));
01356               fuReportsSummary_->setBinContent(i,j,emptyBin ? 0 : fuReportsSummary_->getBinContent(i+lsdiff,j));
01357             }
01358             busySummary_->setBinContent(i,epInstances.size()+2,emptyBin ? 0 : busySummary2_->getBinContent(i+lsdiff,epInstances.size()+2));
01359             busySummary2_->setBinContent(i,epInstances.size()+2,emptyBin ? 0 : busySummary2_->getBinContent(i+lsdiff,epInstances.size()+2));
01360           }
01361 
01362           std::ostringstream ostr;
01363           ostr << lsid-ROLL+i;
01364           rateSummary_->setBinLabel(i,ostr.str(),1);
01365           reportPeriodSummary_->setBinLabel(i,ostr.str(),1);
01366           timingSummary_->setBinLabel(i,ostr.str(),1);
01367           busySummary_->setBinLabel(i,ostr.str(),1);
01368           busySummary2_->setBinLabel(i,ostr.str(),1);
01369           busySummaryUncorr1_->setBinLabel(i,ostr.str(),1);
01370           busySummaryUncorr2_->setBinLabel(i,ostr.str(),1);
01371           fuReportsSummary_->setBinLabel(i,ostr.str(),1);
01372 
01373         }
01374         summaryLastLs_=lsid;
01375       }
01376       else if (lsid<summaryLastLs_) {
01377         if (summaryLastLs_-lsid>=ROLL) return;//very old
01378         lsidBin=ROLL-(summaryLastLs_-lsid);
01379       }
01380     }
01381     else if (lsid) {lsidBin=lsid;summaryLastLs_=lsid;} else return;
01382   }
01383   else {// previous lumisection updates
01384     unsigned int roll_pos = ROLL-(summaryLastLs_-lsid);
01385     lsidBin=lsid > roll_pos ? roll_pos : lsid;
01386   }
01387 
01388   //how busy is it with current setup
01389   float busyCorr = lst->getFracBusy() * (float)epInstances[nbsIdx]/epMax[nbsIdx];
01390   //max based on how much is configured and max possible
01391   float fracMax  = 0.5 + (std::max(epInstances[nbsIdx]-epMax[nbsIdx]/2.,0.)/(epMax[nbsIdx])) *HTscaling[nbsIdx];
01392   if (epInstances[nbsIdx]<epMax[nbsIdx]/2) {
01393           fracMax = epInstances[nbsIdx]/((double)epMax[nbsIdx]);
01394   }
01395 
01396   //corrections for the HT effect
01397   float busyFr=0;
01398   float busyCPUFr=0;
01399   float busyFrTheor=0;
01400   float busyFrCPUTheor=0;
01401 
01402   //microstates based calculation
01403   if (busyCorr>0.5) {//take into account HT scaling for the busy fraction
01404     busyFr=(0.5 + (busyCorr-0.5)*HTscaling[nbsIdx])/fracMax;
01405     busyFrTheor = (0.5+(busyCorr-0.5)*HTscaling[nbsIdx])/ (0.5+0.5*HTscaling[nbsIdx]);
01406   }
01407   else {//below the HT threshold
01408     busyFr=busyCorr / fracMax;
01409     busyFrTheor = busyCorr / (0.5+0.5*HTscaling[nbsIdx]);
01410   }
01411 
01412   //proc/stat based calculation
01413   float busyCorr_CPU = lst->getFracCPUBusy();
01414   if (busyCorr_CPU>0.5) {
01415     busyCPUFr=(0.5 + (busyCorr_CPU-0.5)*HTscaling[nbsIdx])/fracMax;
01416     busyFrCPUTheor = (0.5+(busyCorr_CPU-0.5)*HTscaling[nbsIdx])/ (0.5+0.5*HTscaling[nbsIdx]);
01417   }
01418   else {
01419     busyCPUFr=busyCorr_CPU / fracMax;
01420     busyFrCPUTheor = busyCorr_CPU / (0.5+0.5*HTscaling[nbsIdx]);
01421   }
01422 
01423   //average
01424   clst->setBusyForClass(nbsIdx,lst->getRate(),busyFr,busyFrTheor,busyCPUFr,busyFrCPUTheor,lst->getReports());
01425   float busyAvg = clst->getBusyTotalFrac(false,machineWeightInst);
01426   float busyAvgCPU = clst->getBusyTotalFrac(true,machineWeightInst);
01427 
01428   //rounding
01429   busyFr=fround(busyFr,0.001f);
01430   busyCPUFr=fround(busyCPUFr,0.001f);
01431   busyFrTheor=fround(busyFrTheor,0.001f);
01432   busyFrCPUTheor=fround(busyFrCPUTheor,0.001f);
01433   busyAvg=fround(busyAvg,0.001f);
01434 
01435   //filling plots
01436   daqBusySummary_->setBinContent(lsid,busyAvg*100.);
01437   daqBusySummary_->setBinError(lsid,0);
01438   daqBusySummary2_->setBinContent(lsid,busyAvgCPU*100.);
01439   daqBusySummary2_->setBinError(lsid,0);
01440 
01441   //"rolling" histograms
01442   rateSummary_->setBinContent(lsidBin,nbsIdx+1,lst->getRate());
01443   reportPeriodSummary_->setBinContent(lsidBin,nbsIdx+1,lst->getDt());
01444   timingSummary_->setBinContent(lsidBin,nbsIdx+1,lst->getEvtTime()*1000);
01445   fuReportsSummary_->setBinContent(lsidBin,nbsIdx+1,lst->getReports());
01446   busySummary_->setBinContent(lsidBin,nbsIdx+1,fround(busyFr,0.001f));
01447   busySummary2_->setBinContent(lsidBin,nbsIdx+1,fround(busyCPUFr,0.001f));
01448   busySummaryUncorr1_->setBinContent(lsidBin,nbsIdx+1,fround(lst->getFracBusy(),0.001f));
01449   busySummaryUncorr2_->setBinContent(lsidBin,nbsIdx+1,fround(lst->getFracCPUBusy(),0.001f));
01450 
01451   rateSummary_->setBinContent(lsidBin,epInstances.size()+1,clst->getTotalRate());
01452   fuReportsSummary_->setBinContent(lsidBin,epInstances.size()+1,clst->getNReports());
01453 
01454   busySummary_->setBinContent(lsidBin,epInstances.size()+1,fround(busyAvg,0.001f));
01455   busySummary2_->setBinContent(lsidBin,epInstances.size()+1,fround(busyAvgCPU,0.001f));
01456   busySummary_->setBinContent(lsidBin,epInstances.size()+2,fround(clst->getBusyTotalFracTheor(false,machineWeight),0.001f));
01457   busySummary2_->setBinContent(lsidBin,epInstances.size()+2,fround(clst->getBusyTotalFracTheor(true,machineWeight),0.001f));
01458 
01459 }
01460 
01461 void iDie::updateStreamHistos(unsigned int forls, commonLsStat *clst, commonLsStat *prevclst)
01462 {
01463   if (endPathRates_.size()!=endPathNames_.size()) meInitializedStreams_=false; 
01464   initMonitorElementsStreams();//reinitialize (conditionally)
01465   for (size_t i=0;i<endPathRates_.size();i++) {
01466     unsigned int count_current=0;
01467     unsigned int count_last=0;
01468     if (clst->endPathCounts_.size()>i) {
01469       count_current=clst->endPathCounts_[i];
01470     }
01471     endPathRates_[i]->setBinContent(forls,(count_current-count_last)/23.1);//approx ls
01472   } 
01473 }
01474 
01475 
01476 void iDie::updateDatasetHistos(unsigned int forls, commonLsStat *clst, commonLsStat *prevclst)
01477 {
01478   if (datasetRates_.size()!=datasetNames_.size()) meInitializedDatasets_=false; 
01479   initMonitorElementsDatasets();//reinitialize (conditionally)
01480   for (size_t i=0;i<datasetRates_.size();i++) {
01481     unsigned int count_current=0;
01482     unsigned int count_last=0;
01483     if (clst->datasetCounts_.size()>i) {
01484       count_current=clst->datasetCounts_[i];
01485     }
01486     datasetRates_[i]->setBinContent(forls,(count_current-count_last)/23.1);//approx ls
01487   } 
01488 }
01489 
01490 
01491 void iDie::fillDQMModFractionHist(unsigned int nbsIdx, unsigned int lsid, unsigned int nonIdle, std::vector<std::pair<unsigned int,unsigned int>> offenders)
01492 {
01493   if (!evtProcessor_) return;
01494   MonitorElement * me = meVecOffenders_[nbsIdx];
01495   //shift bin names by 1
01496   unsigned int xBinToFill=lsid;
01497   if (lsid>ROLL) {
01498     for (unsigned int i=1;i<=ROLL;i++) {
01499       for (unsigned int j=1;j<=MODNAMES;j++) {
01500         if (i<ROLL)
01501           me->setBinContent(i,j,me->getBinContent(i+1,j));
01502         else
01503           me->setBinContent(i,j,0);
01504       }
01505       std::ostringstream ostr;
01506       ostr << lsid-ROLL+i;
01507       me->setBinLabel(i,ostr.str(),1);
01508     }
01509     std::ostringstream ostr;
01510     ostr << lsid;
01511     xBinToFill=ROLL;
01512   }
01513   float nonIdleInv=0.;
01514   if (nonIdle>0)nonIdleInv=1./(double)nonIdle;
01515   //1st pass (there are free bins left)
01516   for (unsigned int i=0;i<offenders.size();i++) {
01517     unsigned int x=offenders[i].first;
01518     float percentageUsed=offenders[i].second*nonIdleInv;
01519     if (percentageUsed>0.02) {//2% threshold
01520       if (occupancyNameMap[nbsIdx].count(x)==0) {//new element
01521         unsigned int y=occupancyNameMap[nbsIdx].size();
01522         if (y<MODNAMES) {
01523           (occupancyNameMap[nbsIdx])[x]=y;
01524           me->setBinContent(xBinToFill,y+1,fround(percentageUsed,0.001f));
01525           me->setBinLabel(y+1,mapmod_[x],2);
01526         }
01527         else break;
01528       }
01529     }
01530   }
01531   //2nd pass (beyond available bins)
01532   for (unsigned int i=0;i<offenders.size();i++) {
01533     unsigned int x=offenders[i].first;
01534     float percentageUsed=offenders[i].second*nonIdleInv;
01535     if (percentageUsed>0.02) {//2% threshold
01536       if (occupancyNameMap[nbsIdx].count(x)==0) {
01537         unsigned int y=occupancyNameMap[nbsIdx].size();
01538         if (y>=MODNAMES && xBinToFill>1) {
01539           //filled up, replace another one
01540           float minbinval=1.;
01541           unsigned int toReplace=0;
01542           for (size_t j=1;j<=MODNAMES;j++) {
01543             //decide based on the smallest value
01544             float bin=me->getBinContent(xBinToFill,j);
01545             if (bin<minbinval) {toReplace=j;minbinval=bin;}
01546           }
01547           if (percentageUsed>minbinval && toReplace) {
01548             int key=-1;
01549             for (auto it = occupancyNameMap[nbsIdx].begin(); it != occupancyNameMap[nbsIdx].end(); ++it) {
01550               if (it->second == toReplace-1) {
01551                 key = it->first;
01552                 break;
01553               }
01554             }
01555             if (key>-1) {
01556               //erase old
01557               occupancyNameMap[nbsIdx].erase(key);
01558               //add new
01559               (occupancyNameMap[nbsIdx])[x]=toReplace-1;
01560               //fill histogram
01561               me->setBinContent(xBinToFill,toReplace,fround(percentageUsed,0.001f));
01562               me->setBinLabel(toReplace,mapmod_[x],2);
01563               //reset fields for previous lumis
01564               unsigned qsize = lsHistory[nbsIdx].size();
01565               for (size_t k=1;k<xBinToFill;k++) {
01566                 if (xBinToFill-k+1<qsize) {
01567                   float fr = (lsHistory[nbsIdx])[qsize-xBinToFill+k-1]->getOffenderFracAt(x);
01568                   if (fr>0.02) me->setBinContent(k,toReplace,fround(fr,0.001f));
01569                 }
01570                 else
01571                   me->setBinContent(k,toReplace,0);
01572               }
01573             }
01574           }
01575         }
01576       }
01577       else {
01578         unsigned int y=(occupancyNameMap[nbsIdx])[x];
01579         me->setBinContent(xBinToFill,y+1,fround(percentageUsed,0.001f));
01580       }
01581     }
01582   }
01583 }
01584 
01585 void iDie::doFlush() {
01586     if (dqmEnabled_.value_)
01587       dqmService_->flushStandalone();
01588 }
01589 
01590 void iDie::perLumiFileSaver(unsigned int lsid)
01591 {
01592 
01593   //make sure that run number is updated before saving
01594   if (lastRunNumberSet_<runNumber_) {
01595     if (meInitialized_) {
01596       std::ostringstream busySummaryTitle;
01597       busySummaryTitle << "DAQ HLT Farm busy (%) for run "<< runNumber_.value_;
01598       daqBusySummary_->setTitle(busySummaryTitle.str());
01599       lastRunNumberSet_ = runNumber_.value_;
01600     }
01601   }
01602 
01603   if (dqmSaveDir_.value_=="") return;
01604   //try to create directory if not there
01605 
01606   if (savedForLs_==0)
01607   {
01608     struct stat st;
01609     if (stat((dqmSaveDir_.value_+"/output").c_str(),&st) != 0) {
01610       if (mkdir((dqmSaveDir_.value_+"/output").c_str(), 0777) != 0) {
01611         LOG4CPLUS_ERROR(getApplicationLogger(),"iDie could not find nor create DQM \"output\" directory. DQM archiving -> Off.");
01612         dqmSaveDir_.value_="";//reset parameter
01613         return;
01614       }
01615     }
01616     if (stat((dqmSaveDir_.value_+"/done").c_str(),&st) != 0) {
01617       if (mkdir((dqmSaveDir_.value_+"/done").c_str(), 0777) != 0) {
01618         LOG4CPLUS_WARN(getApplicationLogger(),"iDie could not find nor create DQM \"done\" directory. DQM archiving might fail.");
01619       }
01620     }
01621     //static filename part
01622     char version[8];
01623     sprintf(version, "_V%04d_", int(1));
01624     version[7]='\0';
01625     std::string sDir = dqmSaveDir_.value_;
01626     if (sDir[sDir.size()-1]!='/') sDir+="/";
01627     sDir+="output/";
01628     fileBaseName_ = sDir + "DQM" + version;
01629 
01630     //checking if directory is there
01631     if ( access( sDir.c_str(), 0 ) == 0 )
01632     {
01633       struct stat status;
01634       stat( sDir.c_str(), &status );
01635 
01636       if ( status.st_mode & S_IFDIR ) writeDirectoryPresent_=true;
01637       else writeDirectoryPresent_=false;
01638     }
01639   }
01640 
01641   if (lsid > 0 && (lsid%saveLsInterval_.value_)==0  && lsid>savedForLs_ && writeDirectoryPresent_)
01642   {
01643     savedForLs_=lsid;
01644     char suffix[64];
01645     char rewrite[128];
01646     sprintf(suffix, "_R%09d_L%06d", runNumber_.value_, lsid);
01647     sprintf(rewrite, "\\1Run %d/\\2/By Lumi Section %d-%d", runNumber_.value_, ilumiprev_, lsid);
01648 
01649     std::vector<std::string> systems = {topLevelFolder_.value_};
01650 
01651     for (size_t i = 0, e = systems.size(); i != e; ++i) {
01652       std::string filename = fileBaseName_ + systems[i] + suffix + ".root";
01653       try {
01654         dqmStore_->save(filename, systems[i] , "^(Reference/)?([^/]+)",
01655             rewrite, (DQMStore::SaveReferenceTag) DQMStore::SaveWithReference, dqm::qstatus::STATUS_OK);
01656         pastSavedFiles_.push_back(filename);
01657         if (dqmFilesWritable_.value_)
01658           chmod(filename.c_str(),0777);//allow deletion by dqm script
01659         //if (pastSavedFiles_.size() > 500)
01660         //{
01661           //remove(pastSavedFiles_.front().c_str());
01662           //pastSavedFiles_.pop_front();
01663         //}
01664       }
01665       catch (...) {
01666         LOG4CPLUS_ERROR(getApplicationLogger(),"iDie could not create root file " << filename);
01667       }
01668     }
01669 
01670     ilumiprev_ = lsid;
01671 
01672     //cd() to micro report root file
01673     if (f_)
01674       f_->cd();
01675   }
01676 }
01677 
01678 
01679 
01680 void iDie::perTimeFileSaver()
01681 {
01682 
01683   //make sure that run number is updated before saving
01684   if (lastRunNumberSet_<runNumber_) {
01685     if (meInitialized_) {
01686       std::ostringstream busySummaryTitle;
01687       busySummaryTitle << "DAQ HLT Farm busy (%) for run "<< runNumber_.value_;
01688       daqBusySummary_->setTitle(busySummaryTitle.str());
01689       lastRunNumberSet_ = runNumber_.value_;
01690     }
01691   }
01692   
01693   if (dqmSaveDir_.value_=="") return;
01694 
01695   //save interval (+9 every minutes after initial)
01696   std::vector<unsigned int> minutes = {4,8,12,20};
01697   
01698   //directory should already be there
01699   //first invocation - just record time
01700   if (!reportingStart_) {
01701     reportingStart_ = new timeval;
01702     gettimeofday(reportingStart_,0);
01703     lastSavedForTime_=0;
01704     return;
01705   }
01706   timeval new_ts;
01707   gettimeofday(&new_ts,0);
01708 
01709   unsigned int dT = (new_ts.tv_sec - reportingStart_->tv_sec) / 60;
01710 
01711   unsigned int willSaveForTime = 0;
01712 
01713   for (size_t i=0;i<minutes.size();i++) {
01714     if (dT>=minutes[i]) {
01715       if (lastSavedForTime_ < minutes[i]) {
01716         willSaveForTime=dT;
01717         lastSavedForTime_=dT;
01718         break;
01719       }
01720     }
01721   }
01722 
01723   //in periodic part
01724   unsigned int lastMinutesTime = minutes[minutes.size()-1];
01725   if (!willSaveForTime && dT>lastMinutesTime)
01726   {
01727     if (lastSavedForTime_<lastMinutesTime || (dT-lastMinutesTime)/9 > (lastSavedForTime_-lastMinutesTime)/9) {
01728       willSaveForTime=dT;
01729       lastSavedForTime_=dT;
01730     }
01731   }
01732 
01733   if (willSaveForTime && writeDirectoryPresent_)
01734   {
01735     char suffix[64];
01736     char rewrite[128];
01737     sprintf(suffix, "_R%09d_T%08d", runNumber_.value_, willSaveForTime);
01738     sprintf(rewrite, "\\1Run %d/\\2/Run summary", runNumber_.value_);
01739 
01740     std::vector<std::string> systems = {topLevelFolder_.value_};
01741 
01742     for (size_t i = 0, e = systems.size(); i != e; ++i) {
01743       std::string filename = fileBaseName_ + systems[i] + suffix + ".root";
01744       try {
01745         dqmStore_->save(filename, systems[i] , "^(Reference/)?([^/]+)",
01746             rewrite, (DQMStore::SaveReferenceTag) DQMStore::SaveWithReference, dqm::qstatus::STATUS_OK);
01747         if (dqmFilesWritable_.value_)
01748           chmod(filename.c_str(),0777);//allow deletion by dqm script
01749       }
01750       catch (...) {
01751         LOG4CPLUS_ERROR(getApplicationLogger(),"iDie could not create root file " << filename);
01752       }
01753     }
01754 
01755     //cd() to micro report root file
01756     if (f_)
01757       f_->cd();
01758   }
01759 }
01760 
01761 
01762 
01763 
01764 
01766 // xdaq instantiator implementation macro
01768 
01769 XDAQ_INSTANTIATOR_IMPL(iDie)