AlCaRecoTriggerBitsRcdUpdate

Line Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
///////////////////////////////////////////////////////////////////////
///
/// Module to write trigger bit mappings (AlCaRecoTriggerBits) to DB.
/// Can be configured to read an old one and update this by
/// - removing old entries
/// - adding new ones
///
///////////////////////////////////////////////////////////////////////

#include <string>
#include <map>
#include <vector>
#include <algorithm>
#include <set>

// Framework
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/ServiceRegistry/interface/Service.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/Framework/interface/one/EDAnalyzer.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"

// Database
#include "CondCore/DBOutputService/interface/PoolDBOutputService.h"

// What I want to write:
#include "CondFormats/HLTObjects/interface/AlCaRecoTriggerBits.h"
// Rcd for reading old one:
#include "CondFormats/DataRecord/interface/AlCaRecoTriggerBitsRcd.h"

class AlCaRecoTriggerBitsRcdUpdate : public edm::one::EDAnalyzer<> {
public:
  explicit AlCaRecoTriggerBitsRcdUpdate(const edm::ParameterSet &cfg);
  ~AlCaRecoTriggerBitsRcdUpdate() override = default;

  void analyze(const edm::Event &evt, const edm::EventSetup &evtSetup) override;
  static void fillDescriptions(edm::ConfigurationDescriptions &descriptions);

private:
  typedef std::map<std::string, std::string> TriggerMap;
  bool removeKeysFromMap(const std::vector<std::string> &keys, TriggerMap &triggerMap) const;
  bool replaceKeysFromMap(const std::vector<edm::ParameterSet> &alcarecoReplace, TriggerMap &triggerMap) const;
  bool addTriggerLists(const std::vector<edm::ParameterSet> &triggerListsAdd, AlCaRecoTriggerBits &bits) const;
  bool addPathsFromMap(const std::vector<edm::ParameterSet> &pathsToAdd, AlCaRecoTriggerBits &bits) const;
  bool removePathsFromMap(const std::vector<edm::ParameterSet> &pathsToRemove, AlCaRecoTriggerBits &bits) const;
  void writeBitsToDB(const AlCaRecoTriggerBits &bitsToWrite) const;

  const edm::ESGetToken<AlCaRecoTriggerBits, AlCaRecoTriggerBitsRcd> triggerBitsToken_;
  unsigned int nEventCalls_;
  const unsigned int firstRunIOV_;
  const int lastRunIOV_;
  const bool startEmpty_;
  const std::vector<std::string> listNamesRemove_;
  const std::vector<edm::ParameterSet> triggerListsAdd_;
  const std::vector<edm::ParameterSet> alcarecoReplace_;
  const std::vector<edm::ParameterSet> pathsToAdd_;
  const std::vector<edm::ParameterSet> pathsToRemove_;
};

///////////////////////////////////////////////////////////////////////
void AlCaRecoTriggerBitsRcdUpdate::fillDescriptions(edm::ConfigurationDescriptions &descriptions) {
  edm::ParameterSetDescription desc;
  desc.setComment("Plugin to write payloads of type AlCaRecoTriggerBits");
  desc.add<unsigned int>("firstRunIOV", 1);
  desc.add<int>("lastRunIOV", -1);
  desc.add<bool>("startEmpty", true);
  desc.add<std::vector<std::string>>("listNamesRemove", {});

  edm::ParameterSetDescription desc_triggeListsToAdd;
  desc_triggeListsToAdd.add<std::string>("listName");
  desc_triggeListsToAdd.add<std::vector<std::string>>("hltPaths");
  std::vector<edm::ParameterSet> default_triggerListsToAdd;
  desc.addVPSet("triggerListsAdd", desc_triggeListsToAdd, default_triggerListsToAdd);

  edm::ParameterSetDescription desc_alcarecoToReplace;
  desc_alcarecoToReplace.add<std::string>("oldKey");
  desc_alcarecoToReplace.add<std::string>("newKey");
  std::vector<edm::ParameterSet> default_alcarecoToReplace;
  desc.addVPSet("alcarecoToReplace", desc_alcarecoToReplace, default_alcarecoToReplace);

  edm::ParameterSetDescription desc_pathsToAdd;
  desc_pathsToAdd.add<std::string>("listName");
  desc_pathsToAdd.add<std::vector<std::string>>("hltPaths");
  std::vector<edm::ParameterSet> default_pathsToAdd;
  desc.addVPSet("pathsToAdd", desc_pathsToAdd, default_pathsToAdd);

  edm::ParameterSetDescription desc_pathsToRemove;
  desc_pathsToRemove.add<std::string>("listName");
  desc_pathsToRemove.add<std::vector<std::string>>("hltPaths");
  std::vector<edm::ParameterSet> default_pathsToRemove;
  desc.addVPSet("pathsToRemove", desc_pathsToRemove, default_pathsToRemove);

  descriptions.addWithDefaultLabel(desc);
}

///////////////////////////////////////////////////////////////////////
AlCaRecoTriggerBitsRcdUpdate::AlCaRecoTriggerBitsRcdUpdate(const edm::ParameterSet &cfg)
    : triggerBitsToken_(esConsumes()),
      nEventCalls_(0),
      firstRunIOV_(cfg.getParameter<unsigned int>("firstRunIOV")),
      lastRunIOV_(cfg.getParameter<int>("lastRunIOV")),
      startEmpty_(cfg.getParameter<bool>("startEmpty")),
      listNamesRemove_(cfg.getParameter<std::vector<std::string>>("listNamesRemove")),
      triggerListsAdd_(cfg.getParameter<std::vector<edm::ParameterSet>>("triggerListsAdd")),
      alcarecoReplace_(cfg.getParameter<std::vector<edm::ParameterSet>>("alcarecoToReplace")),
      pathsToAdd_(cfg.getParameter<std::vector<edm::ParameterSet>>("pathsToAdd")),
      pathsToRemove_(cfg.getParameter<std::vector<edm::ParameterSet>>("pathsToRemove")) {}

///////////////////////////////////////////////////////////////////////
void AlCaRecoTriggerBitsRcdUpdate::analyze(const edm::Event &evt, const edm::EventSetup &iSetup) {
  if (nEventCalls_++ > 0) {  // postfix increment!
    edm::LogWarning("BadConfig") << "@SUB=analyze"
                                 << "Writing to DB to be done only once, set\n"
                                 << "'process.maxEvents = cms.untracked.PSet(input = cms.untracked.int32(1))'\n"
                                 << " next time. But your writing is fine.)";
    return;
  }

  // create what to write - starting from empty or existing list
  std::unique_ptr<AlCaRecoTriggerBits> bitsToWrite;
  if (startEmpty_) {
    bitsToWrite = std::make_unique<AlCaRecoTriggerBits>();
  } else {
    bitsToWrite = std::make_unique<AlCaRecoTriggerBits>(iSetup.getData(triggerBitsToken_));
  }

  // remove some existing entries in map
  this->removeKeysFromMap(listNamesRemove_, bitsToWrite->m_alcarecoToTrig);

  // now add new entries
  this->addTriggerLists(triggerListsAdd_, *bitsToWrite);

  // now replace keys
  this->replaceKeysFromMap(alcarecoReplace_, bitsToWrite->m_alcarecoToTrig);

  // add paths to the existing key
  this->addPathsFromMap(pathsToAdd_, *bitsToWrite);

  // remove paths from the existing key
  this->removePathsFromMap(pathsToRemove_, *bitsToWrite);

  // finally write to DB
  this->writeBitsToDB(*bitsToWrite);
}

///////////////////////////////////////////////////////////////////////
bool AlCaRecoTriggerBitsRcdUpdate::removeKeysFromMap(const std::vector<std::string> &keys,
                                                     TriggerMap &triggerMap) const {
  for (std::vector<std::string>::const_iterator iKey = keys.begin(), endKey = keys.end(); iKey != endKey; ++iKey) {
    if (triggerMap.find(*iKey) != triggerMap.end()) {
      triggerMap.erase(*iKey);
    } else {  // not in list ==> misconfiguartion!
      throw cms::Exception("BadConfig") << "[AlCaRecoTriggerBitsRcdUpdate::removeKeysFromMap] "
                                        << "Cannot remove key '" << *iKey << "' since not in "
                                        << "list - typo in configuration?\n";
      return false;
    }
  }
  return true;
}

///////////////////////////////////////////////////////////////////////
bool AlCaRecoTriggerBitsRcdUpdate::replaceKeysFromMap(const std::vector<edm::ParameterSet> &alcarecoReplace,
                                                      TriggerMap &triggerMap) const {
  std::vector<std::pair<std::string, std::string>> keyPairs;
  keyPairs.reserve(alcarecoReplace.size());

  for (auto &iSet : alcarecoReplace) {
    const std::string oldKey(iSet.getParameter<std::string>("oldKey"));
    const std::string newKey(iSet.getParameter<std::string>("newKey"));
    keyPairs.push_back(std::make_pair(oldKey, newKey));
  }

  for (auto &iKey : keyPairs) {
    if (triggerMap.find(iKey.first) != triggerMap.end()) {
      std::string bitsToReplace = triggerMap[iKey.first];
      triggerMap.erase(iKey.first);
      triggerMap[iKey.second] = bitsToReplace;
    } else {  // not in list ==> misconfiguration!
      edm::LogWarning("AlCaRecoTriggerBitsRcdUpdate")
          << "[AlCaRecoTriggerBitsRcdUpdate::replaceKeysFromMap] "
          << "Cannot replace key '" << iKey.first << "with " << iKey.second << " since not in "
          << "list - typo in configuration?\n";
      return false;
    }
  }
  return true;
}

///////////////////////////////////////////////////////////////////////
bool AlCaRecoTriggerBitsRcdUpdate::addTriggerLists(const std::vector<edm::ParameterSet> &triggerListsAdd,
                                                   AlCaRecoTriggerBits &bits) const {
  TriggerMap &triggerMap = bits.m_alcarecoToTrig;

  // loop on PSets, each containing the key (filter name) and a vstring with triggers
  for (const auto &iSet : triggerListsAdd) {
    const std::vector<std::string> paths(iSet.getParameter<std::vector<std::string>>("hltPaths"));
    // We must avoid a map<string,vector<string> > in DB for performance reason,
    // so we have to merge the paths into one string that will be decoded when needed:
    const std::string mergedPaths = bits.compose(paths);

    const std::string filter(iSet.getParameter<std::string>("listName"));
    if (triggerMap.find(filter) != triggerMap.end()) {
      throw cms::Exception("BadConfig") << "List name '" << filter << "' already in map, either "
                                        << "remove from 'triggerListsAdd' or "
                                        << " add to 'listNamesRemove'.\n";
    }
    triggerMap[filter] = mergedPaths;
  }

  return true;
}

///////////////////////////////////////////////////////////////////////
bool AlCaRecoTriggerBitsRcdUpdate::addPathsFromMap(const std::vector<edm::ParameterSet> &pathsToAdd,
                                                   AlCaRecoTriggerBits &bits) const {
  TriggerMap &triggerMap = bits.m_alcarecoToTrig;  //read from the condition tag

  // loop on PSets, each containing the key (filter name) and a vstring with triggers
  for (const auto &iSet : pathsToAdd) {
    const std::string filter(iSet.getParameter<std::string>("listName"));
    std::string mergedPathsInKey;

    for (const auto &imap : triggerMap) {
      if (imap.first == filter)
        mergedPathsInKey = imap.second;  //paths in the condition tag
    }

    if (mergedPathsInKey.empty()) {
      throw cms::Exception("BadConfig") << "List name '" << filter << "' not found in the map, "
                                        << "if you want to add new key/paths, please use 'addTriggerLists'.\n";
    }

    auto const &pathsInKey = bits.decompose(mergedPathsInKey);
    auto const &paths = iSet.getParameter<std::vector<std::string>>("hltPaths");  //paths to add; from the configuration

    if (paths.empty()) {  // nothing to add ==> misconfiguration!
      throw cms::Exception("BadConfig") << "Didn't set any path to add!";
    }

    std::set<std::string> pathsSet{pathsInKey.begin(), pathsInKey.end()};
    std::copy(paths.begin(), paths.end(), std::inserter(pathsSet, pathsSet.end()));
    std::vector<std::string> const newPathsInKey{pathsSet.begin(), pathsSet.end()};

    // We must avoid a map<string,vector<string> > in DB for performance reason,
    // so we have to merge the paths into one string that will be decoded when needed:
    triggerMap[filter] = bits.compose(newPathsInKey);
  }

  return true;
}

///////////////////////////////////////////////////////////////////////
bool AlCaRecoTriggerBitsRcdUpdate::removePathsFromMap(const std::vector<edm::ParameterSet> &pathsToRemove,
                                                      AlCaRecoTriggerBits &bits) const {
  TriggerMap &triggerMap = bits.m_alcarecoToTrig;  //read from the condition tag

  // loop on PSets, each containing the key (filter name) and a vstring with triggers
  for (const auto &iSet : pathsToRemove) {
    const std::string filter(iSet.getParameter<std::string>("listName"));
    std::string mergedPathsInKey;

    for (const auto &imap : triggerMap) {
      if (imap.first == filter)
        mergedPathsInKey = imap.second;  //paths in the condition tag
    }

    if (mergedPathsInKey.empty()) {
      throw cms::Exception("BadConfig") << "List name '" << filter << "' not found in the map";
    }

    auto PathsInKey = bits.decompose(mergedPathsInKey);
    auto const paths(
        iSet.getParameter<std::vector<std::string>>("hltPaths"));  //paths to remove; from the configuration

    if (paths.empty()) {  // nothing to remove ==> misconfiguration!
      throw cms::Exception("BadConfig") << "Didn't set any path to remove!";
    }

    for (auto const &path : paths) {
      PathsInKey.erase(std::remove(PathsInKey.begin(), PathsInKey.end(), path), PathsInKey.end());
    }

    // We must avoid a map<string,vector<string> > in DB for performance reason,
    // so we have to merge the paths into one string that will be decoded when needed:
    triggerMap[filter] = bits.compose(PathsInKey);
  }

  return true;
}

///////////////////////////////////////////////////////////////////////
void AlCaRecoTriggerBitsRcdUpdate::writeBitsToDB(const AlCaRecoTriggerBits &bitsToWrite) const {
  edm::LogInfo("AlCaRecoTriggerBitsRcdUpdate") << "Uploading to the database...";

  edm::Service<cond::service::PoolDBOutputService> poolDbService;
  if (!poolDbService.isAvailable()) {
    throw cms::Exception("NotAvailable") << "PoolDBOutputService not available.\n";
  }

  const std::string recordName("AlCaRecoTriggerBitsRcd");

  // when updating existing tag, compare payload hashs and skip appending new hash if it's same with last iov's
  poolDbService->startTransaction();
  auto newHash = poolDbService->session().storePayload(bitsToWrite);
  cond::TagInfo_t tag_info;

  if (poolDbService->tagInfo(recordName, tag_info)) {
    if (newHash != tag_info.lastInterval.payloadId) {
      edm::LogInfo("AlCaRecoTriggerBitsRcdUpdate") << "## Appending to existing tag...";
      poolDbService->forceInit();
      poolDbService->appendSinceTime(newHash, firstRunIOV_, recordName);
    } else {
      edm::LogInfo("AlCaRecoTriggerBitsRcdUpdate") << "## Skipping update since hash is the same...";
    }

  } else {
    edm::LogInfo("AlCaRecoTriggerBitsRcdUpdate") << "## Creating new tag...";
    poolDbService->forceInit();
    poolDbService->createNewIOV(newHash, firstRunIOV_, recordName);
  }
  poolDbService->commitTransaction();

  edm::LogInfo("AlCaRecoTriggerBitsRcdUpdate")
      << "...done for runs " << firstRunIOV_ << " to " << lastRunIOV_ << " (< 0 meaning infinity)!";
}

//define this as a plug-in
DEFINE_FWK_MODULE(AlCaRecoTriggerBitsRcdUpdate);