CMS 3D CMS Logo

/afs/cern.ch/work/a/aaltunda/public/www/CMSSW_6_2_5/src/FWCore/Services/src/InitRootHandlers.cc

Go to the documentation of this file.
00001 #include "FWCore/Services/src/InitRootHandlers.h"
00002 
00003 #include "DataFormats/Common/interface/RefCoreStreamer.h"
00004 #include "DataFormats/Streamer/interface/StreamedProductStreamer.h"
00005 #include "FWCore/MessageLogger/interface/ELseverityLevel.h"
00006 #include "FWCore/MessageLogger/interface/MessageLogger.h"
00007 #include "FWCore/ParameterSet/interface/ParameterSet.h"
00008 #include "FWCore/PluginManager/interface/PluginCapabilities.h"
00009 #include "FWCore/RootAutoLibraryLoader/interface/RootAutoLibraryLoader.h"
00010 #include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h"
00011 #include "FWCore/ParameterSet/interface/ParameterSetDescription.h"
00012 #include "FWCore/Utilities/interface/DictionaryTools.h"
00013 #include "FWCore/Utilities/interface/EDMException.h"
00014 #include "FWCore/Utilities/interface/TypeWithDict.h"
00015 #include "FWCore/Utilities/interface/UnixSignalHandlers.h"
00016 
00017 #include <sstream>
00018 #include <string.h>
00019 
00020 #include "Cintex/Cintex.h"
00021 #include "G__ci.h"
00022 #include "TROOT.h"
00023 #include "TError.h"
00024 #include "TFile.h"
00025 #include "TH1.h"
00026 #include "TSystem.h"
00027 #include "TUnixSystem.h"
00028 #include "TTree.h"
00029 
00030 namespace {
00031 
00032   void RootErrorHandlerImpl(int level, char const* location, char const* message, bool ignoreWarnings) {
00033 
00034   bool die = false;
00035 
00036   // Translate ROOT severity level to MessageLogger severity level
00037 
00038     edm::ELseverityLevel el_severity = edm::ELseverityLevel::ELsev_info;
00039 
00040     if (level >= kFatal) {
00041       el_severity = edm::ELseverityLevel::ELsev_fatal;
00042     } else if (level >= kSysError) {
00043       el_severity = edm::ELseverityLevel::ELsev_severe;
00044     } else if (level >= kError) {
00045       el_severity = edm::ELseverityLevel::ELsev_error;
00046     } else if (level >= kWarning) {
00047       el_severity = ignoreWarnings ? edm::ELseverityLevel::ELsev_info : edm::ELseverityLevel::ELsev_warning;
00048     }
00049 
00050   // Adapt C-strings to std::strings
00051   // Arrange to report the error location as furnished by Root
00052 
00053     std::string el_location = "@SUB=?";
00054     if (location != 0) el_location = std::string("@SUB=")+std::string(location);
00055 
00056     std::string el_message  = "?";
00057     if (message != 0) el_message  = message;
00058 
00059   // Try to create a meaningful id string using knowledge of ROOT error messages
00060   //
00061   // id ==     "ROOT-ClassName" where ClassName is the affected class
00062   //      else "ROOT/ClassName" where ClassName is the error-declaring class
00063   //      else "ROOT"
00064 
00065     std::string el_identifier = "ROOT";
00066 
00067     std::string precursor("class ");
00068     size_t index1 = el_message.find(precursor);
00069     if (index1 != std::string::npos) {
00070       size_t index2 = index1 + precursor.length();
00071       size_t index3 = el_message.find_first_of(" :", index2);
00072       if (index3 != std::string::npos) {
00073         size_t substrlen = index3-index2;
00074         el_identifier += "-";
00075         el_identifier += el_message.substr(index2,substrlen);
00076       }
00077     } else {
00078       index1 = el_location.find("::");
00079       if (index1 != std::string::npos) {
00080         el_identifier += "/";
00081         el_identifier += el_location.substr(0, index1);
00082       }
00083     }
00084 
00085   // Intercept some messages and upgrade the severity
00086 
00087       if ((el_location.find("TBranchElement::Fill") != std::string::npos)
00088        && (el_message.find("fill branch") != std::string::npos)
00089        && (el_message.find("address") != std::string::npos)
00090        && (el_message.find("not set") != std::string::npos)) {
00091         el_severity = edm::ELseverityLevel::ELsev_fatal;
00092       }
00093 
00094       if ((el_message.find("Tree branches") != std::string::npos)
00095        && (el_message.find("different numbers of entries") != std::string::npos)) {
00096         el_severity = edm::ELseverityLevel::ELsev_fatal;
00097       }
00098 
00099 
00100   // Intercept some messages and downgrade the severity
00101 
00102       if ((el_message.find("no dictionary for class") != std::string::npos) ||
00103           (el_message.find("already in TClassTable") != std::string::npos) ||
00104           (el_message.find("matrix not positive definite") != std::string::npos) ||
00105           (el_message.find("not a TStreamerInfo object") != std::string::npos) ||
00106           (el_location.find("Fit") != std::string::npos) ||
00107           (el_location.find("TDecompChol::Solve") != std::string::npos) ||
00108           (el_location.find("THistPainter::PaintInit") != std::string::npos) ||
00109           (el_location.find("TUnixSystem::SetDisplay") != std::string::npos) ||
00110           (el_location.find("TGClient::GetFontByName") != std::string::npos)) {
00111         el_severity = edm::ELseverityLevel::ELsev_info;
00112       }
00113 
00114     if (el_severity == edm::ELseverityLevel::ELsev_info) {
00115       // Don't throw if the message is just informational.
00116       die = false;
00117     } else {
00118       die = true;
00119     }
00120 
00121   // Feed the message to the MessageLogger and let it choose to suppress or not.
00122 
00123   // Root has declared a fatal error.  Throw an EDMException unless the
00124   // message corresponds to a pending signal. In that case, do not throw
00125   // but let the OS deal with the signal in the usual way.
00126     if (die && (el_location != std::string("@SUB=TUnixSystem::DispatchSignals"))) {
00127        std::ostringstream sstr;
00128        sstr << "Fatal Root Error: " << el_location << "\n" << el_message << '\n';
00129        edm::Exception except(edm::errors::FatalRootError, sstr.str());
00130        except.addAdditionalInfo(except.message());
00131        except.clearMessage();
00132        throw except;
00133      
00134     }
00135 
00136     // Typically, we get here only for informational messages,
00137     // but we leave the other code in just in case we change
00138     // the criteria for throwing.
00139     if (el_severity == edm::ELseverityLevel::ELsev_fatal) {
00140       edm::LogError("Root_Fatal") << el_location << el_message;
00141     } else if (el_severity == edm::ELseverityLevel::ELsev_severe) {
00142       edm::LogError("Root_Severe") << el_location << el_message;
00143     } else if (el_severity == edm::ELseverityLevel::ELsev_error) {
00144       edm::LogError("Root_Error") << el_location << el_message;
00145     } else if (el_severity == edm::ELseverityLevel::ELsev_warning) {
00146       edm::LogWarning("Root_Warning") << el_location << el_message ;
00147     } else if (el_severity == edm::ELseverityLevel::ELsev_info) {
00148       edm::LogInfo("Root_Information") << el_location << el_message ;
00149     }
00150   }
00151 
00152   void RootErrorHandler(int level, bool, char const* location, char const* message) {
00153     RootErrorHandlerImpl(level, location, message, false);
00154   }
00155 
00156   void RootErrorHandlerWithoutWarnings(int level, bool, char const* location, char const* message) {
00157     RootErrorHandlerImpl(level, location, message, true);
00158   }
00159 
00160   extern "C" {
00161     void sig_dostack_then_abort(int sig,siginfo_t*,void*) {
00162       if (gSystem) {
00163         const char* signalname = "unknown";
00164         switch (sig) {
00165           case SIGBUS:
00166             signalname = "bus error";
00167             break;
00168           case SIGSEGV:
00169             signalname = "segmentation violation";
00170             break;
00171           case SIGILL:
00172             signalname = "illegal instruction"; 
00173           default:
00174             break;
00175         }
00176         edm::LogError("FatalSystemSignal")<<"A fatal system signal has occurred: "<<signalname;
00177         std::cerr<< "\n\nA fatal system signal has occurred: "<<signalname<<"\n"
00178                  <<"The following is the call stack containing the origin of the signal.\n"
00179                  <<"NOTE:The first few functions on the stack are artifacts of processing the signal and can be ignored\n\n";
00180         
00181         gSystem->StackTrace();
00182         std::cerr<<"\nA fatal system signal has occurred: "<<signalname<<"\n";
00183       }
00184       ::abort();
00185     }
00186   }
00187 }  // end of unnamed namespace
00188 
00189 namespace edm {
00190   namespace service {
00191     InitRootHandlers::InitRootHandlers (ParameterSet const& pset)
00192       : RootHandlers(),
00193         unloadSigHandler_(pset.getUntrackedParameter<bool> ("UnloadRootSigHandler")),
00194         resetErrHandler_(pset.getUntrackedParameter<bool> ("ResetRootErrHandler")),
00195         autoLibraryLoader_(pset.getUntrackedParameter<bool> ("AutoLibraryLoader")) {
00196 
00197       if(unloadSigHandler_) {
00198       // Deactivate all the Root signal handlers and restore the system defaults
00199         gSystem->ResetSignal(kSigChild);
00200         gSystem->ResetSignal(kSigBus);
00201         gSystem->ResetSignal(kSigSegmentationViolation);
00202         gSystem->ResetSignal(kSigIllegalInstruction);
00203         gSystem->ResetSignal(kSigSystem);
00204         gSystem->ResetSignal(kSigPipe);
00205         gSystem->ResetSignal(kSigAlarm);
00206         gSystem->ResetSignal(kSigUrgent);
00207         gSystem->ResetSignal(kSigFloatingException);
00208         gSystem->ResetSignal(kSigWindowChanged);
00209       } else if(pset.getUntrackedParameter<bool>("AbortOnSignal")){
00210         //NOTE: ROOT can also be told to abort on these kinds of problems BUT
00211         // it requires an TApplication to be instantiated which causes problems
00212         gSystem->ResetSignal(kSigBus);
00213         gSystem->ResetSignal(kSigSegmentationViolation);
00214         gSystem->ResetSignal(kSigIllegalInstruction);
00215         installCustomHandler(SIGBUS,sig_dostack_then_abort);
00216         installCustomHandler(SIGSEGV,sig_dostack_then_abort);
00217         installCustomHandler(SIGILL,sig_dostack_then_abort);
00218       }
00219 
00220       if(resetErrHandler_) {
00221 
00222       // Replace the Root error handler with one that uses the MessageLogger
00223         SetErrorHandler(RootErrorHandler);
00224       }
00225 
00226       // Enable automatic Root library loading.
00227       if(autoLibraryLoader_) {
00228         RootAutoLibraryLoader::enable();
00229       }
00230 
00231       // Enable Cintex.
00232       ROOT::Cintex::Cintex::Enable();
00233 
00234       // Set ROOT parameters.
00235       TTree::SetMaxTreeSize(kMaxLong64);
00236       TH1::AddDirectory(kFALSE);
00237       G__SetCatchException(0);
00238 
00239       // Set custom streamers
00240       setRefCoreStreamer();
00241       setStreamedProductStreamer();
00242 
00243       // Load the library containing dictionaries for std:: classes, if not already loaded.
00244       if (!TypeWithDict(typeid(std::vector<std::vector<unsigned int> >)).hasDictionary()) {
00245          edmplugin::PluginCapabilities::get()->load(dictionaryPlugInPrefix() + "std::vector<std::vector<unsigned int> >");
00246       }
00247     }
00248 
00249     InitRootHandlers::~InitRootHandlers () {
00250       // close all open ROOT files
00251       // We get a new iterator each time,
00252       // because closing a file can invalidate the iterator
00253       while(gROOT->GetListOfFiles()->GetSize()) {
00254         TIter iter(gROOT->GetListOfFiles());
00255         TFile* f = dynamic_cast<TFile*>(iter.Next());
00256         if(f) f->Close();
00257       }
00258     }
00259 
00260     void InitRootHandlers::fillDescriptions(ConfigurationDescriptions& descriptions) {
00261       ParameterSetDescription desc;
00262       desc.setComment("Centralized interface to ROOT.");
00263       desc.addUntracked<bool>("UnloadRootSigHandler", false)
00264           ->setComment("If True, signals are handled by this service, rather than by ROOT.");
00265       desc.addUntracked<bool>("ResetRootErrHandler", true)
00266           ->setComment("If True, ROOT messages (e.g. errors, warnings) are handled by this service, rather than by ROOT.");
00267       desc.addUntracked<bool>("AutoLibraryLoader", true)
00268           ->setComment("If True, enables automatic loading of data dictionaries.");
00269       desc.addUntracked<bool>("AbortOnSignal",true)
00270       ->setComment("If True, do an abort when a signal occurs that causes a crash. If False, ROOT will do an exit which attempts to do a clean shutdown.");
00271       descriptions.add("InitRootHandlers", desc);
00272     }
00273 
00274     void
00275     InitRootHandlers::disableErrorHandler_() {
00276         SetErrorHandler(DefaultErrorHandler);
00277     }
00278 
00279     void
00280     InitRootHandlers::enableErrorHandler_() {
00281         SetErrorHandler(RootErrorHandler);
00282     }
00283 
00284     void
00285     InitRootHandlers::enableErrorHandlerWithoutWarnings_() {
00286         SetErrorHandler(RootErrorHandlerWithoutWarnings);
00287     }
00288 
00289   }  // end of namespace service
00290 }  // end of namespace edm