CMS 3D CMS Logo

CondorStatusUpdater.cc
Go to the documentation of this file.
1 
18 
19 #include <fcntl.h>
20 #include <unistd.h>
21 #include <sys/wait.h>
22 #include <spawn.h>
23 #include <iostream>
24 #include <fstream>
25 #include <sstream>
26 #include <cmath>
27 #include <chrono>
28 #include <sstream>
29 #include <atomic>
30 #include <string>
31 #include <set>
32 
33 namespace edm {
34 
35  namespace service {
36 
38  public:
41  CondorStatusService(const CondorStatusService &) = delete;
43 
44  static void fillDescriptions(ConfigurationDescriptions &descriptions);
45 
46  private:
47  bool isChirpSupported();
48  template <typename T>
49  bool updateChirp(const std::string &key_suffix, const T &value);
50  bool updateChirpQuoted(const std::string &key_suffix, const std::string &value);
51  bool updateChirpImpl(std::string const &key, std::string const &value);
52  inline void update();
53  void firstUpdate();
54  void lastUpdate();
55  void updateImpl(time_t secsSinceLastUpdate);
56 
57  void preSourceConstruction(ModuleDescription const &md, int maxEvents, int maxLumis, int maxSecondsUntilRampdown);
58  void eventPost(StreamContext const &iContext);
59  void lumiPost(GlobalContext const &);
60  void runPost(GlobalContext const &);
61  void beginPre(PathsAndConsumesOfModulesBase const &, ProcessContext const &processContext);
62  void beginPost();
63  void endPost();
64  void filePost(std::string const &);
65 
66  bool m_debug;
67  std::atomic_flag m_shouldUpdate;
68  time_t m_beginJob = 0;
71  float m_rate = 0;
72  static constexpr float m_defaultEmaInterval = 15 * 60; // Time in seconds to average EMA over for event rate.
73  static constexpr unsigned int m_defaultUpdateInterval = 3 * 60;
74  std::atomic<time_t> m_lastUpdate;
75  std::atomic<std::uint_least64_t> m_events;
76  std::atomic<std::uint_least64_t> m_lumis;
77  std::atomic<std::uint_least64_t> m_runs;
78  std::atomic<std::uint_least64_t> m_files;
81 
82  std::uint_least64_t m_lastEventCount = 0;
83  };
84 
85  } // namespace service
86 
87 } // namespace edm
88 
89 using namespace edm::service;
90 
93 
95  : m_debug(pset.getUntrackedParameter("debug", false)),
96  m_lastUpdate(0),
97  m_events(0),
98  m_lumis(0),
99  m_runs(0),
100  m_files(0) {
101  m_shouldUpdate.clear();
102  if (not pset.getUntrackedParameter("enable", true)) {
103  return;
104  }
105  if (!isChirpSupported()) {
106  return;
107  }
108 
109  firstUpdate();
110 
118 
119  if (pset.exists("updateIntervalSeconds")) {
120  m_updateInterval = pset.getUntrackedParameter<unsigned int>("updateIntervalSeconds");
121  }
122  if (pset.exists("EMAInterval")) {
123  m_emaInterval = pset.getUntrackedParameter<double>("EMAInterval");
124  }
125  if (pset.exists("tag")) {
126  m_tag = pset.getUntrackedParameter<std::string>("tag");
127  }
128 }
129 
131  m_events++;
132  update();
133 }
134 
136  m_lumis++;
137  update();
138 }
139 
141  m_runs++;
142  update();
143 }
144 
146  m_files++;
147  update();
148 }
149 
152  m_processParameterSetID = processContext.parameterSetID();
153  }
154 }
155 
157  ParameterSet const &processParameterSet = edm::getParameterSet(m_processParameterSetID);
158  const edm::ParameterSet &pset = processParameterSet.getParameterSet("@main_input");
159  // PSet info from edm::ScheduleItems
160  int maxEvents =
161  processParameterSet.getUntrackedParameterSet("maxEvents", ParameterSet()).getUntrackedParameter<int>("input", -1);
162  int maxLumis = processParameterSet.getUntrackedParameterSet("maxLuminosityBlocks", ParameterSet())
163  .getUntrackedParameter<int>("input", -1);
164 
165  // lumisToProcess from EventSkipperByID (PoolSource and similar)
166  std::vector<edm::LuminosityBlockRange> toProcess = pset.getUntrackedParameter<std::vector<LuminosityBlockRange>>(
167  "lumisToProcess", std::vector<LuminosityBlockRange>());
168  edm::sortAndRemoveOverlaps(toProcess);
169  uint64_t lumiCount = 0;
170  for (auto const &range : toProcess) {
171  if (range.startRun() != range.endRun()) {
172  break;
173  }
175  break;
176  }
177  lumiCount += (range.endLumi() - range.startLumi());
178  }
179  // Handle sources deriving from ProducerSourceBase
180  unsigned int eventsPerLumi = pset.getUntrackedParameter<unsigned int>("numberEventsInLuminosityBlock", 0);
181  if ((lumiCount == 0) && (maxEvents > 0) && (eventsPerLumi > 0)) {
182  lumiCount = static_cast<unsigned int>(std::ceil(static_cast<float>(maxEvents) / static_cast<float>(eventsPerLumi)));
183  }
184 
185  std::vector<std::string> fileNames =
186  pset.getUntrackedParameter<std::vector<std::string>>("fileNames", std::vector<std::string>());
187  std::stringstream ss_max_files;
188  ss_max_files << fileNames.size();
189  updateChirp("MaxFiles", ss_max_files.str());
190 
191  if (lumiCount > 0) {
192  if (maxLumis < 0) {
193  maxLumis = lumiCount;
194  }
195  if (maxLumis > static_cast<int>(lumiCount)) {
196  maxLumis = lumiCount;
197  }
198  }
199  if (maxEvents > 0) {
200  std::stringstream ss_max_events;
201  ss_max_events << maxEvents;
202  updateChirp("MaxEvents", ss_max_events.str());
203  }
204  if (maxLumis > 0) {
205  std::stringstream ss_max_lumis;
206  ss_max_lumis << maxLumis;
207  updateChirp("MaxLumis", ss_max_lumis.str());
208  }
209 
210  m_beginJob = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
211  update();
212 }
213 
215 
217  if (m_debug) {
218  return true;
219  }
220 
221  return std::getenv("_CONDOR_CHIRP_CONFIG") && updateChirp("Elapsed", "0");
222 }
223 
225  // Note we always update all our statistics to 0 / false / -1
226  // This allows us to overwrite the activities of a previous cmsRun process
227  // within this HTCondor job.
228  updateImpl(0);
229  updateChirp("MaxFiles", "-1");
230  updateChirp("MaxEvents", "-1");
231  updateChirp("MaxLumis", "-1");
232  updateChirp("Done", "false");
234 
237  double avgSpeed;
238  if (cpusvc.isAvailable() && cpusvc->cpuInfo(models, avgSpeed)) {
239  updateChirpQuoted("CPUModels", models);
240  updateChirp("CPUSpeed", avgSpeed);
241  }
242 }
243 
245  time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
247  updateChirp("Done", "true");
249  if (!cpusvc.isAvailable()) {
250  std::cout << "At post, CPU service is NOT available.\n";
251  }
252 }
253 
255  time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
256  if ((now - m_lastUpdate.load(std::memory_order_relaxed)) > m_updateInterval) {
257  if (!m_shouldUpdate.test_and_set(std::memory_order_acquire)) {
258  // Caught exception is rethrown
259  CMS_SA_ALLOW try {
260  time_t sinceLastUpdate = now - m_lastUpdate;
261  m_lastUpdate = now;
262  updateImpl(sinceLastUpdate);
263  m_shouldUpdate.clear(std::memory_order_release);
264  } catch (...) {
265  m_shouldUpdate.clear(std::memory_order_release);
266  throw;
267  }
268  }
269  }
270 }
271 
272 void CondorStatusService::updateImpl(time_t sinceLastUpdate) {
273  time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
274  time_t jobTime = now - m_beginJob;
275 
277  if (timingsvc.isAvailable()) {
278  updateChirp("TotalCPU", timingsvc->getTotalCPU());
279  }
280 
281  updateChirp("LastUpdate", now);
282 
283  if (!m_events || (m_events > m_lastEventCount)) {
284  updateChirp("Events", m_events);
285  }
286 
287  updateChirp("Lumis", m_lumis);
288 
289  updateChirp("Runs", m_runs);
290 
291  updateChirp("Files", m_files);
292 
293  float ema_coeff = 1 - std::exp(-static_cast<float>(sinceLastUpdate) /
294  std::max(std::min(m_emaInterval, static_cast<float>(jobTime)), 1.0f));
295  if (sinceLastUpdate > 0) {
296  updateChirp("Elapsed", jobTime);
297  m_rate = ema_coeff * static_cast<float>(m_events - m_lastEventCount) / static_cast<float>(sinceLastUpdate) +
298  (1.0 - ema_coeff) * m_rate;
300  updateChirp("EventRate", m_rate);
301  }
302 
303  // If Xrootd was used, pull the statistics from there.
305  if (xrdsvc.isAvailable()) {
306  for (auto const &iter : xrdsvc->condorUpdate()) {
307  std::string site = iter.first;
308  site.erase(std::remove_if(site.begin(), site.end(), [](char x) { return !isalnum(x) && (x != '_'); }),
309  site.end());
310  auto &iostats = iter.second;
311  updateChirp("IOSite_" + site + "_ReadBytes", iostats.bytesRead);
312  updateChirp("IOSite_" + site + "_ReadTimeMS",
313  std::chrono::duration_cast<std::chrono::milliseconds>(iostats.transferTime).count());
314  }
315  }
316 
317  using namespace edm::storage;
318  // Update storage account information
319  auto const &stats = StorageAccount::summary();
320  uint64_t readOps = 0;
321  uint64_t readVOps = 0;
322  uint64_t readSegs = 0;
323  uint64_t readBytes = 0;
324  uint64_t readTimeTotal = 0;
325  uint64_t writeBytes = 0;
326  uint64_t writeTimeTotal = 0;
327  const auto token = StorageAccount::tokenForStorageClassName("tstoragefile");
328  for (const auto &storage : stats) {
329  // StorageAccount records statistics for both the TFile layer and the
330  // StorageFactory layer. However, the StorageFactory statistics tend to
331  // be more accurate as various backends may alter the incoming read requests
332  // (such as when lazy-download is used).
333  if (storage.first == token.value()) {
334  continue;
335  }
336  for (const auto &counter : storage.second) {
337  if (counter.first == static_cast<int>(StorageAccount::Operation::read)) {
338  readOps += counter.second.successes;
339  readSegs++;
340  readBytes += counter.second.amount;
341  readTimeTotal += counter.second.timeTotal;
342  } else if (counter.first == static_cast<int>(StorageAccount::Operation::readv)) {
343  readVOps += counter.second.successes;
344  readSegs += counter.second.vector_count;
345  readBytes += counter.second.amount;
346  readTimeTotal += counter.second.timeTotal;
347  } else if ((counter.first == static_cast<int>(StorageAccount::Operation::write)) ||
348  (counter.first == static_cast<int>(StorageAccount::Operation::writev))) {
349  writeBytes += counter.second.amount;
350  writeTimeTotal += counter.second.timeTotal;
351  }
352  }
353  }
354  updateChirp("ReadOps", readOps);
355  updateChirp("ReadVOps", readVOps);
356  updateChirp("ReadSegments", readSegs);
357  updateChirp("ReadBytes", readBytes);
358  updateChirp("ReadTimeMsecs", readTimeTotal / (1000 * 1000));
359  updateChirp("WriteBytes", writeBytes);
360  updateChirp("WriteTimeMsecs", writeTimeTotal / (1000 * 1000));
361 }
362 
363 template <typename T>
364 bool CondorStatusService::updateChirp(const std::string &key_suffix, const T &value) {
365  std::stringstream ss;
366  ss << value;
367  return updateChirpImpl(key_suffix, ss.str());
368 }
369 
371  std::string value_copy = value;
372  // Remove double-quotes or the \ character (as it has special escaping semantics in ClassAds).
373  // Make sure we have ASCII characters.
374  // Otherwise, remainder is allowed (including tabs, newlines, single-quotes).
375  value_copy.erase(
376  remove_if(
377  value_copy.begin(), value_copy.end(), [](const char &c) { return !isascii(c) || (c == '"') || (c == '\\'); }),
378  value_copy.end());
379  return updateChirpImpl(key_suffix, "\"" + value_copy + "\"");
380 }
381 
383  std::stringstream ss;
384  ss << "ChirpCMSSW" << m_tag << key_suffix;
385  std::string key = ss.str();
386  if (m_debug) {
387  std::cout << "condor_chirp set_job_attr_delayed " << key << " " << value << std::endl;
388  }
389  int pid = 0;
390  posix_spawn_file_actions_t file_actions;
391  int devnull_fd = open("/dev/null", O_RDWR);
392  if (devnull_fd == -1) {
393  return false;
394  }
395  posix_spawn_file_actions_init(&file_actions);
396  posix_spawn_file_actions_adddup2(&file_actions, devnull_fd, 1);
397  posix_spawn_file_actions_adddup2(&file_actions, devnull_fd, 2);
398  const std::string chirp_name = "condor_chirp";
399  const std::string set_job_attr = "set_job_attr_delayed";
400  std::vector<const char *> argv;
401  argv.push_back(chirp_name.c_str());
402  argv.push_back(set_job_attr.c_str());
403  argv.push_back(key.c_str());
404  argv.push_back(value.c_str());
405  argv.push_back(nullptr);
406  int status = posix_spawnp(&pid, "condor_chirp", &file_actions, nullptr, const_cast<char *const *>(&argv[0]), environ);
407  close(devnull_fd);
408  posix_spawn_file_actions_destroy(&file_actions);
409  if (status) {
410  return false;
411  }
412  while ((waitpid(pid, &status, 0) == -1) && errno == -EINTR) {
413  }
414  return status == 0;
415 }
416 
419  desc.setComment("Service to update HTCondor with the current CMSSW status.");
420  desc.addOptionalUntracked<unsigned int>("updateIntervalSeconds", m_defaultUpdateInterval)
421  ->setComment("Interval, in seconds, for HTCondor updates");
422  desc.addOptionalUntracked<bool>("debug", false)->setComment("Enable debugging of this service");
423  desc.addOptionalUntracked<double>("EMAInterval", m_defaultEmaInterval)
424  ->setComment("Interval, in seconds, to calculate event rate over (using EMA)");
425  desc.addOptionalUntracked<std::string>("tag")->setComment(
426  "Identifier tag for this process (a value of 'Foo' results in ClassAd attributes of the form 'ChirpCMSSWFoo*')");
427  desc.addOptionalUntracked<bool>("enable", true)->setComment("Enable this service");
428  descriptions.add("CondorStatusService", desc);
429 }
430 
bool updateChirpImpl(std::string const &key, std::string const &value)
constexpr int32_t ceil(float num)
CondorStatusService(ParameterSet const &pset, edm::ActivityRegistry &ar)
#define CMS_SA_ALLOW
void preSourceConstruction(ModuleDescription const &md, int maxEvents, int maxLumis, int maxSecondsUntilRampdown)
#define DEFINE_FWK_SERVICE_MAKER(concrete, maker)
Definition: ServiceMaker.h:102
void runPost(GlobalContext const &)
void watchPostEndJob(PostEndJob::slot_type const &iSlot)
void beginPre(PathsAndConsumesOfModulesBase const &, ProcessContext const &processContext)
virtual bool cpuInfo(std::string &models, double &avgSpeed)=0
CPU information - the models present and average speed.
void updateImpl(time_t secsSinceLastUpdate)
std::atomic< std::uint_least64_t > m_events
edm::serviceregistry::AllArgsMaker< edm::service::CondorStatusService > CondorStatusServiceMaker
void watchPostEvent(PostEvent::slot_type const &iSlot)
static LuminosityBlockNumber_t maxLuminosityBlockNumber()
ParameterSet const & getParameterSet(std::string const &) const
void lumiPost(GlobalContext const &)
ParameterSet getUntrackedParameterSet(std::string const &name, ParameterSet const &defaultValue) const
Definition: models.py:1
std::atomic< std::uint_least64_t > m_lumis
Guid const & processGUID()
Definition: processGUID.cc:4
bool isValid() const
Definition: Hash.h:141
T getUntrackedParameter(std::string const &, T const &) const
void watchPostCloseFile(PostCloseFile::slot_type const &iSlot)
bool updateChirpQuoted(const std::string &key_suffix, const std::string &value)
void filePost(std::string const &)
CondorStatusService & operator=(const CondorStatusService &)=delete
static constexpr float m_defaultEmaInterval
std::string toString(const char *format,...)
Definition: xdaq_compat.cc:4
std::atomic< std::uint_least64_t > m_runs
double f[11][100]
void watchPostGlobalEndLumi(PostGlobalEndLumi::slot_type const &iSlot)
Definition: value.py:1
virtual std::vector< std::pair< std::string, CondorIOStats > > condorUpdate()=0
void eventPost(StreamContext const &iContext)
unsigned long long uint64_t
Definition: Time.h:13
void watchPostGlobalEndRun(PostGlobalEndRun::slot_type const &iSlot)
void add(std::string const &label, ParameterSetDescription const &psetDescription)
void watchPreBeginJob(PreBeginJob::slot_type const &iSlot)
convenience function for attaching to signal
static constexpr unsigned int m_defaultUpdateInterval
ParameterSet const & getParameterSet(ParameterSetID const &id)
virtual double getTotalCPU() const =0
bool updateChirp(const std::string &key_suffix, const T &value)
HLT enums.
std::vector< EventRange > & sortAndRemoveOverlaps(std::vector< EventRange > &eventRange)
Definition: EventRange.cc:98
float x
bool isAvailable() const
Definition: Service.h:40
long double T
static void fillDescriptions(ConfigurationDescriptions &descriptions)
ParameterSetID const & parameterSetID() const
void watchPostBeginJob(PostBeginJob::slot_type const &iSlot)
convenience function for attaching to signal
std::atomic< std::uint_least64_t > m_files