CMS 3D CMS Logo

SiStripPayloadHandler.cc
Go to the documentation of this file.
6 
7 #include <iostream>
8 #include <sstream>
9 #include <typeinfo>
10 #include <openssl/sha.h>
11 
13 
14 #include "RelationalAccess/ITransaction.h"
15 #include "RelationalAccess/ISessionProxy.h"
16 #include "RelationalAccess/ISchema.h"
17 #include "RelationalAccess/ITable.h"
18 #include "RelationalAccess/IQuery.h"
19 #include "RelationalAccess/ICursor.h"
20 #include "RelationalAccess/ITableDataEditor.h"
21 #include "RelationalAccess/TableDescription.h"
22 #include "CoralBase/Attribute.h"
23 #include "CoralBase/AttributeList.h"
24 #include "CoralBase/TimeStamp.h"
25 
27 
28 template <typename SiStripPayload>
30 public:
31  explicit SiStripPayloadHandler(const edm::ParameterSet& iConfig );
32  ~SiStripPayloadHandler() override;
33  void analyze( const edm::Event& evt, const edm::EventSetup& evtSetup) override;
34  void endJob() override;
35 
36 private:
39  void updateConfigMap(std::string configHash, std::string payloadHash);
40 
41 private:
50 
54 };
55 
56 
57 template<typename SiStripPayload>
60  m_cfgMapTableName( iConfig.getUntrackedParameter< std::string >("cfgMapTableName", "STRIP_CONFIG_TO_PAYLOAD_MAP") ),
61  m_condDb( iConfig.getParameter< std::string >("conditionDatabase") ),
62  m_localCondDbFile( iConfig.getParameter< std::string >("condDbFile") ),
63  m_targetTag( iConfig.getParameter< std::string >("targetTag") ),
64  m_since( iConfig.getParameter< uint32_t >("since") ),
65  p_type( cond::demangledName(typeid(SiStripPayload)) ),
66  p_cfgstr( condObjBuilder->getConfigString(typeid(SiStripPayload)) )
67 {
68  if (iConfig.exists("configMapDatabase"))
69  m_configMapDb = iConfig.getParameter< std::string >("configMapDatabase");
70  if (iConfig.exists("cfgMapDbFile"))
71  m_cfgMapDbFile = iConfig.getParameter< std::string >("cfgMapDbFile");
74 }
75 
76 template<typename SiStripPayload>
78 }
79 
80 template<typename SiStripPayload>
82 
83  // some extra work: Getting the payload hash of the last IOV from condDb
84  // Will be compared with the new payload and reported
86  condDbSession.transaction().start( true );
87  cond::persistency::IOVProxy iovProxy = condDbSession.readIov( m_targetTag );
88  cond::Hash last_hash = iovProxy.getLast().payloadId;
89 
90  // that's the final goal: obtain the payload to store into the sqlite file for the upload into the DB
91  std::shared_ptr<SiStripPayload> payloadToUpload;
92  // first compute the hash of the configuration
93  std::string configHash = makeConfigHash();
94  // query the configMap DB to find the corresponding payload hash
95  std::string mappedPayloadHash = queryConfigMap(configHash);
96  bool mapUpToDate = false;
97 
98  if ( !mappedPayloadHash.empty() ){
99  // the payload has been found ( fast O2O case )
100  // copy the payload from condtition database
101  mapUpToDate = true;
102  edm::LogInfo("SiStripPayloadHandler") << "[SiStripPayloadHandler::" << __func__ << "] "
103  << "Try retrieving payload from " << m_condDb;
104  payloadToUpload = condDbSession.fetchPayload<SiStripPayload>( mappedPayloadHash );
105  std::cout << "@@@[FastO2O:true]@@@" << std::endl;
106  edm::LogInfo("SiStripPayloadHandler") << "[SiStripPayloadHandler::" << __func__ << "] "
107  << " ... Payload is copied from offline condition database.";
108  }else {
109  // start the long O2O...
110  edm::LogInfo("SiStripPayloadHandler") << "[SiStripPayloadHandler::" << __func__ << "] "
111  << "NO mapping payload hash found. Will run the long O2O. ";
112  SiStripPayload *obj = nullptr;
113  if (typeid(SiStripPayload) == typeid(SiStripApvGain)){
114  // special treatment for ApvGain : provide last payload in DB
115  condObjBuilder->setLastIovGain(condDbSession.fetchPayload<SiStripApvGain>( last_hash ));
116  }
117  condObjBuilder->getValue(obj);
118  payloadToUpload = std::shared_ptr<SiStripPayload>(obj);
119  std::cout << "@@@[FastO2O:false]@@@" << std::endl;
120  edm::LogInfo("SiStripPayloadHandler") << "[SiStripPayloadHandler::" << __func__ << "] "
121  << " ... New payload has been created.";
122  }
123  condDbSession.transaction().commit();
124 
125  // write payload and iov in the local file
126  edm::LogInfo("SiStripPayloadHandler") << "[SiStripPayloadHandler::" << __func__ << "] "
127  << "Write payload to local sqlite file: " << m_localCondDbFile;
128  cond::persistency::Session localFileSession = m_connectionPool.createSession( m_localCondDbFile, true );
129  localFileSession.transaction().start( false );
130  // write the payload
131  cond::Hash thePayloadHash = localFileSession.storePayload<SiStripPayload>( *payloadToUpload );
132  cond::persistency::IOVEditor iovEditor = localFileSession.createIov<SiStripPayload>( m_targetTag, cond::runnumber );
133  iovEditor.setDescription( "New IOV" );
134  // inserting the iov
135  iovEditor.insert( m_since, thePayloadHash );
136  iovEditor.flush();
137  localFileSession.transaction().commit();
138  edm::LogInfo("SiStripPayloadHandler") << "[SiStripPayloadHandler::" << __func__ << "] "
139  << "Payload " << thePayloadHash << " inserted to sqlite with IOV " << m_since;
140 
141  // last step, update the configMap if required
142  if( !mapUpToDate ){
143  updateConfigMap(configHash, thePayloadHash);
144  }
145 
146  // finish the extra work: Compare the new payload with last IOV
147  if (last_hash == thePayloadHash){
148  std::cout << "@@@[PayloadChange:false]@@@" << last_hash << std::endl;
149  }else {
150  std::cout << "@@@[PayloadChange:true]@@@" << last_hash << " -> " << thePayloadHash << std::endl;
151  }
152 
153 }
154 
155 template<typename SiStripPayload>
157 }
158 
159 template<typename SiStripPayload>
161 
162  edm::LogInfo("SiStripPayloadHandler") << "[SiStripPayloadHandler::" << __func__ << "] "
163  << "Convert config string to SHA-1 hash for " << p_type
164  << "\n... config: " << p_cfgstr;
165 
166  // calcuate SHA-1 hash using openssl
167  // adapted from cond::persistency::makeHash() in CondCore/CondDB/src/IOVSchema.cc
168  SHA_CTX ctx;
169  if( !SHA1_Init( &ctx ) ){
170  throw cms::Exception("SHA1 initialization error.");
171  }
172  if( !SHA1_Update( &ctx, p_type.c_str(), p_type.size() ) ){
173  throw cms::Exception("SHA1 processing error (1).");
174  }
175  if( !SHA1_Update( &ctx, p_cfgstr.c_str(), p_cfgstr.size() ) ){
176  throw cms::Exception("SHA1 processing error (2).");
177  }
178  unsigned char hash[SHA_DIGEST_LENGTH];
179  if( !SHA1_Final(hash, &ctx) ){
180  throw cms::Exception("SHA1 finalization error.");
181  }
182 
183  char tmp[SHA_DIGEST_LENGTH*2+1];
184  // re-write bytes in hex
185  for (unsigned int i = 0; i < SHA_DIGEST_LENGTH; i++) {
186  ::sprintf(&tmp[i * 2], "%02x", hash[i]);
187  }
188  tmp[SHA_DIGEST_LENGTH*2] = 0;
189 
190  edm::LogInfo("SiStripPayloadHandler") << "[SiStripPayloadHandler::" << __func__ << "] "
191  "... hash: " << tmp;
192  return tmp;
193 
194 }
195 
196 template<typename SiStripPayload>
198  if (m_configMapDb.empty()) return ""; // return empty string if m_configMapDb is not specified
199 
200  edm::LogInfo("SiStripPayloadHandler") << "[SiStripPayloadHandler::" << __func__ << "] "
201  << "Query " << m_configMapDb << " to see if the payload is already in DB.";
202 
203  auto cmDbSession = m_connectionPool.createCoralSession( m_configMapDb );
204  // query the STRIP_CONFIG_TO_PAYLOAD_MAP table
205  cmDbSession->transaction().start( true );
206  coral::ITable& cmTable = cmDbSession->nominalSchema().tableHandle( m_cfgMapTableName );
207  std::unique_ptr<coral::IQuery> query( cmTable.newQuery() );
208  query->addToOutputList( "PAYLOAD_HASH" );
209  query->defineOutputType( "PAYLOAD_HASH", coral::AttributeSpecification::typeNameForType<std::string>() );
210  // also print these for debugging
211  query->addToOutputList( "PAYLOAD_TYPE" );
212  query->addToOutputList( "CONFIG_STRING" );
213  query->addToOutputList( "INSERTION_TIME" );
214  std::string whereClause( "CONFIG_HASH = :CONFIG_HASH" );
215  coral::AttributeList whereData;
216  whereData.extend<std::string>( "CONFIG_HASH" );
217  whereData.begin()->data< std::string >() = configHash;
218  query->setCondition( whereClause, whereData );
219  coral::ICursor& cursor = query->execute();
220  std::string p_hash;
221  if( cursor.next() ){
222  // the payload has been found ( fast O2O case )
223  p_hash = cursor.currentRow()["PAYLOAD_HASH"].data<std::string>();
224  edm::LogInfo("SiStripPayloadHandler") << "[SiStripPayloadHandler::" << __func__ << "] "
225  << "Found associated payload hash " << p_hash
226  << "\n... type=" << cursor.currentRow()["PAYLOAD_TYPE"].data<std::string>()
227  << "\n... config=" << cursor.currentRow()["CONFIG_STRING"].data<std::string>()
228  << "\n... insertion_time=" << cursor.currentRow()["INSERTION_TIME"].data<coral::TimeStamp>().toString();
229  }
230  cmDbSession->transaction().commit();
231 
232  return p_hash;
233 }
234 
235 template<typename SiStripPayload>
237  if (m_cfgMapDbFile.empty()) return; // skip this if m_cfgMapDbFile is not set
238 
239  edm::LogInfo("SiStripPayloadHandler") << "[SiStripPayloadHandler::" << __func__ << "] "
240  << "Updating the config to payload hash map to " << m_cfgMapDbFile;
241 
242  // create a writable transaction
243  auto cmSQLiteSession = m_connectionPool.createCoralSession( m_cfgMapDbFile, true );
244  cmSQLiteSession->transaction().start( false );
245 
246  if (!cmSQLiteSession->nominalSchema().existsTable( m_cfgMapTableName )){
247  // create the table if it does not exist
248  coral::TableDescription mapTable;
249  mapTable.setName(m_cfgMapTableName);
250  mapTable.insertColumn("CONFIG_HASH", coral::AttributeSpecification::typeNameForType<std::string>());
251  mapTable.insertColumn("PAYLOAD_HASH", coral::AttributeSpecification::typeNameForType<std::string>());
252  mapTable.insertColumn("PAYLOAD_TYPE", coral::AttributeSpecification::typeNameForType<std::string>());
253  mapTable.insertColumn("CONFIG_STRING", coral::AttributeSpecification::typeNameForType<std::string>());
254  mapTable.insertColumn("INSERTION_TIME", coral::AttributeSpecification::typeNameForType<coral::TimeStamp>());
255  mapTable.setPrimaryKey("CONFIG_HASH");
256  mapTable.setNotNullConstraint("CONFIG_HASH");
257  mapTable.setNotNullConstraint("PAYLOAD_HASH");
258  mapTable.setNotNullConstraint("PAYLOAD_TYPE");
259  mapTable.setNotNullConstraint("CONFIG_STRING");
260  mapTable.setNotNullConstraint("INSERTION_TIME");
261  cmSQLiteSession->nominalSchema().createTable(mapTable);
262  }
263 
264  coral::ITable& cmTable = cmSQLiteSession->nominalSchema().tableHandle( m_cfgMapTableName );
265  coral::AttributeList insertData;
266  insertData.extend<std::string>( "CONFIG_HASH" );
267  insertData.extend<std::string>( "PAYLOAD_HASH" );
268  // also insert these for bookkeeping
269  insertData.extend<std::string>( "PAYLOAD_TYPE" );
270  insertData.extend<std::string>( "CONFIG_STRING" );
271  insertData.extend<coral::TimeStamp>( "INSERTION_TIME" );
272  insertData["CONFIG_HASH"].data<std::string>() = configHash;
273  insertData["PAYLOAD_HASH"].data<std::string>() = payloadHash;
274  insertData["PAYLOAD_TYPE"].data<std::string>() = p_type;
275  insertData["CONFIG_STRING"].data<std::string>() = p_cfgstr;
276  insertData["INSERTION_TIME"].data<coral::TimeStamp>() = coral::TimeStamp::now(); // UTC time
277  cmTable.dataEditor().insertRow( insertData );
278  cmSQLiteSession->transaction().commit();
279  edm::LogInfo("SiStripPayloadHandler") << "[SiStripPayloadHandler::" << __func__ << "] "
280  << "Updated with mapping (configHash : payloadHash)" << configHash << " : " << payloadHash;
281 }
282 
283 // -------------------------------------------------------
284 
287 
290 
293 
296 
299 
302 
T getParameter(std::string const &) const
edm::Service< SiStripCondObjBuilderFromDb > condObjBuilder
SiStripPayloadHandler< SiStripNoises > SiStripO2ONoises
SiStripPayloadHandler< SiStripFedCabling > SiStripO2OFedCabling
std::string queryConfigMap(std::string configHash)
#define DEFINE_FWK_MODULE(type)
Definition: MakerMacros.h:17
void start(bool readOnly=true)
Definition: Session.cc:22
bool exists(std::string const &parameterName) const
checks if a parameter exists
void updateConfigMap(std::string configHash, std::string payloadHash)
IOVEditor createIov(const std::string &tag, cond::TimeType timeType, cond::SynchronizationType synchronizationType=cond::SYNCH_ANY)
Definition: Session.h:185
void setDescription(const std::string &description)
Definition: IOVEditor.cc:128
void analyze(const edm::Event &evt, const edm::EventSetup &evtSetup) override
Transaction & transaction()
Definition: Session.cc:66
def query(query_str, verbose=False)
Definition: das.py:5
SiStripPayloadHandler< SiStripPedestals > SiStripO2OPedestals
void setParameters(const edm::ParameterSet &connectionPset)
Definition: query.py:1
IOVProxy readIov(const std::string &tag, bool full=false)
Definition: Session.cc:81
SiStripPayloadHandler< SiStripBadStrip > SiStripO2OBadStrip
unsigned long long Time_t
Definition: Time.h:16
SiStripPayloadHandler< SiStripApvGain > SiStripO2OApvGain
std::string toString(const char *format,...)
Definition: xdaq_compat.cc:4
void getValue(SiStripFedCabling *&val)
Hash payloadId
Definition: Types.h:57
Session createSession(const std::string &connectionString, bool writeCapable=false)
void setLastIovGain(std::shared_ptr< SiStripApvGain > gain)
std::string Hash
Definition: Types.h:45
cond::persistency::ConnectionPool m_connectionPool
void insert(cond::Time_t since, const cond::Hash &payloadHash, bool checkType=false)
Definition: IOVEditor.cc:152
SiStripPayloadHandler(const edm::ParameterSet &iConfig)
cond::Hash storePayload(const T &payload, const boost::posix_time::ptime &creationTime=boost::posix_time::microsec_clock::universal_time())
Definition: Session.h:189
std::vector< std::vector< double > > tmp
Definition: MVATrainer.cc:100
Definition: plugin.cc:24
SiStripPayloadHandler< SiStripThreshold > SiStripO2OThreshold
SiStripPayloadHandler< SiStripLatency > SiStripO2OLatency
std::shared_ptr< coral::ISessionProxy > createCoralSession(const std::string &connectionString, bool writeCapable=false)
std::shared_ptr< T > fetchPayload(const cond::Hash &payloadHash)
Definition: Session.h:215