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 secondUpdate();
55  void lastUpdate();
56  void updateImpl(time_t secsSinceLastUpdate);
57 
58  void preSourceConstruction(ModuleDescription const &md, int maxEvents, int maxLumis, int maxSecondsUntilRampdown);
59  void eventPost(StreamContext const &iContext);
60  void lumiPost(GlobalContext const &);
61  void runPost(GlobalContext const &);
62  void beginPre(PathsAndConsumesOfModulesBase const &, ProcessContext const &processContext);
63  void beginPost();
64  void endPost();
65  void filePost(std::string const &);
66 
67  bool m_debug;
68  std::atomic_flag m_shouldUpdate;
69  time_t m_beginJob = 0;
72  float m_rate = 0;
73  static constexpr float m_defaultEmaInterval = 15 * 60; // Time in seconds to average EMA over for event rate.
74  static constexpr unsigned int m_defaultUpdateInterval = 3 * 60;
75  std::atomic<time_t> m_lastUpdate;
76  std::atomic<std::uint_least64_t> m_events;
77  std::atomic<std::uint_least64_t> m_lumis;
78  std::atomic<std::uint_least64_t> m_runs;
79  std::atomic<std::uint_least64_t> m_files;
82 
83  std::uint_least64_t m_lastEventCount = 0;
84  };
85  inline bool isProcessWideService(CondorStatusService const *) { return true; }
86 
87  } // namespace service
88 
89 } // namespace edm
90 
91 using namespace edm::service;
92 
95 
97  : m_debug(pset.getUntrackedParameter("debug", false)),
98  m_lastUpdate(0),
99  m_events(0),
100  m_lumis(0),
101  m_runs(0),
102  m_files(0) {
103  m_shouldUpdate.clear();
104  if (not pset.getUntrackedParameter("enable", true)) {
105  return;
106  }
107  if (!isChirpSupported()) {
108  return;
109  }
110 
111  firstUpdate();
112 
120 
121  if (pset.exists("updateIntervalSeconds")) {
122  m_updateInterval = pset.getUntrackedParameter<unsigned int>("updateIntervalSeconds");
123  }
124  if (pset.exists("EMAInterval")) {
125  m_emaInterval = pset.getUntrackedParameter<double>("EMAInterval");
126  }
127  if (pset.exists("tag")) {
128  m_tag = pset.getUntrackedParameter<std::string>("tag");
129  }
130 }
131 
133  m_events++;
134  update();
135 }
136 
138  m_lumis++;
139  update();
140 }
141 
143  m_runs++;
144  update();
145 }
146 
148  m_files++;
149  update();
150 }
151 
153  secondUpdate();
155  m_processParameterSetID = processContext.parameterSetID();
156  }
157 }
158 
160  ParameterSet const &processParameterSet = edm::getParameterSet(m_processParameterSetID);
161  const edm::ParameterSet &pset = processParameterSet.getParameterSet("@main_input");
162  // PSet info from edm::ScheduleItems
163  int maxEvents =
164  processParameterSet.getUntrackedParameterSet("maxEvents", ParameterSet()).getUntrackedParameter<int>("input", -1);
165  int maxLumis = processParameterSet.getUntrackedParameterSet("maxLuminosityBlocks", ParameterSet())
166  .getUntrackedParameter<int>("input", -1);
167 
168  // lumisToProcess from EventSkipperByID (PoolSource and similar)
169  std::vector<edm::LuminosityBlockRange> toProcess = pset.getUntrackedParameter<std::vector<LuminosityBlockRange>>(
170  "lumisToProcess", std::vector<LuminosityBlockRange>());
171  edm::sortAndRemoveOverlaps(toProcess);
172  uint64_t lumiCount = 0;
173  for (auto const &range : toProcess) {
174  if (range.startRun() != range.endRun()) {
175  break;
176  }
178  break;
179  }
180  lumiCount += (range.endLumi() - range.startLumi());
181  }
182  // Handle sources deriving from ProducerSourceBase
183  unsigned int eventsPerLumi = pset.getUntrackedParameter<unsigned int>("numberEventsInLuminosityBlock", 0);
184  if ((lumiCount == 0) && (maxEvents > 0) && (eventsPerLumi > 0)) {
185  lumiCount = static_cast<unsigned int>(std::ceil(static_cast<float>(maxEvents) / static_cast<float>(eventsPerLumi)));
186  }
187 
188  std::vector<std::string> fileNames =
189  pset.getUntrackedParameter<std::vector<std::string>>("fileNames", std::vector<std::string>());
190  std::stringstream ss_max_files;
191  ss_max_files << fileNames.size();
192  updateChirp("MaxFiles", ss_max_files.str());
193 
194  if (lumiCount > 0) {
195  if (maxLumis < 0) {
196  maxLumis = lumiCount;
197  }
198  if (maxLumis > static_cast<int>(lumiCount)) {
199  maxLumis = lumiCount;
200  }
201  }
202  if (maxEvents > 0) {
203  std::stringstream ss_max_events;
204  ss_max_events << maxEvents;
205  updateChirp("MaxEvents", ss_max_events.str());
206  }
207  if (maxLumis > 0) {
208  std::stringstream ss_max_lumis;
209  ss_max_lumis << maxLumis;
210  updateChirp("MaxLumis", ss_max_lumis.str());
211  }
212 
213  m_beginJob = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
214  update();
215 }
216 
218 
220  if (m_debug) {
221  return true;
222  }
223 
224  return std::getenv("_CONDOR_CHIRP_CONFIG") && updateChirp("Elapsed", "0");
225 }
226 
228  // Note we always update all our statistics to 0 / false / -1
229  // This allows us to overwrite the activities of a previous cmsRun process
230  // within this HTCondor job.
231  updateImpl(0);
232  updateChirp("MaxFiles", "-1");
233  updateChirp("MaxEvents", "-1");
234  updateChirp("MaxLumis", "-1");
235  updateChirp("Done", "false");
237 }
238 
240  edm::Service<edm::ResourceInformation> resourceInformationService;
241  if (resourceInformationService.isAvailable()) {
242  std::string models = resourceInformationService->cpuModelsFormatted();
243  double avgSpeed = resourceInformationService->cpuAverageSpeed();
244  if (!models.empty()) {
245  updateChirpQuoted("CPUModels", models);
246  updateChirp("CPUSpeed", avgSpeed);
247  }
248  }
249 }
250 
252  time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
254  updateChirp("Done", "true");
255  edm::Service<edm::ResourceInformation> resourceInformationService;
256  if (!resourceInformationService.isAvailable()) {
257  edm::LogWarning("CondorStatusService") << "At post, ResourceInformationService is NOT available.\n";
258  }
259 }
260 
262  time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
263  if ((now - m_lastUpdate.load(std::memory_order_relaxed)) > m_updateInterval) {
264  if (!m_shouldUpdate.test_and_set(std::memory_order_acquire)) {
265  // Caught exception is rethrown
266  CMS_SA_ALLOW try {
267  time_t sinceLastUpdate = now - m_lastUpdate;
268  m_lastUpdate = now;
269  updateImpl(sinceLastUpdate);
270  m_shouldUpdate.clear(std::memory_order_release);
271  } catch (...) {
272  m_shouldUpdate.clear(std::memory_order_release);
273  throw;
274  }
275  }
276  }
277 }
278 
279 void CondorStatusService::updateImpl(time_t sinceLastUpdate) {
280  time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
281  time_t jobTime = now - m_beginJob;
282 
284  if (timingsvc.isAvailable()) {
285  updateChirp("TotalCPU", timingsvc->getTotalCPU());
286  }
287 
288  updateChirp("LastUpdate", now);
289 
290  if (!m_events || (m_events > m_lastEventCount)) {
291  updateChirp("Events", m_events);
292  }
293 
294  updateChirp("Lumis", m_lumis);
295 
296  updateChirp("Runs", m_runs);
297 
298  updateChirp("Files", m_files);
299 
300  float ema_coeff = 1 - std::exp(-static_cast<float>(sinceLastUpdate) /
301  std::max(std::min(m_emaInterval, static_cast<float>(jobTime)), 1.0f));
302  if (sinceLastUpdate > 0) {
303  updateChirp("Elapsed", jobTime);
304  m_rate = ema_coeff * static_cast<float>(m_events - m_lastEventCount) / static_cast<float>(sinceLastUpdate) +
305  (1.0 - ema_coeff) * m_rate;
307  updateChirp("EventRate", m_rate);
308  }
309 
310  // If Xrootd was used, pull the statistics from there.
312  if (xrdsvc.isAvailable()) {
313  for (auto const &iter : xrdsvc->condorUpdate()) {
314  std::string site = iter.first;
315  site.erase(std::remove_if(site.begin(), site.end(), [](char x) { return !isalnum(x) && (x != '_'); }),
316  site.end());
317  auto &iostats = iter.second;
318  updateChirp("IOSite_" + site + "_ReadBytes", iostats.bytesRead);
319  updateChirp("IOSite_" + site + "_ReadTimeMS",
320  std::chrono::duration_cast<std::chrono::milliseconds>(iostats.transferTime).count());
321  }
322  }
323 
324  using namespace edm::storage;
325  // Update storage account information
326  auto const &stats = StorageAccount::summary();
327  uint64_t readOps = 0;
328  uint64_t readVOps = 0;
329  uint64_t readSegs = 0;
330  uint64_t readBytes = 0;
331  uint64_t readTimeTotal = 0;
332  uint64_t writeBytes = 0;
333  uint64_t writeTimeTotal = 0;
334  const auto token = StorageAccount::tokenForStorageClassName("tstoragefile");
335  for (const auto &storage : stats) {
336  // StorageAccount records statistics for both the TFile layer and the
337  // StorageFactory layer. However, the StorageFactory statistics tend to
338  // be more accurate as various backends may alter the incoming read requests
339  // (such as when lazy-download is used).
340  if (storage.first == token.value()) {
341  continue;
342  }
343  for (const auto &counter : storage.second) {
344  if (counter.first == static_cast<int>(StorageAccount::Operation::read)) {
345  readOps += counter.second.successes;
346  readSegs++;
347  readBytes += counter.second.amount;
348  readTimeTotal += counter.second.timeTotal;
349  } else if (counter.first == static_cast<int>(StorageAccount::Operation::readv)) {
350  readVOps += counter.second.successes;
351  readSegs += counter.second.vector_count;
352  readBytes += counter.second.amount;
353  readTimeTotal += counter.second.timeTotal;
354  } else if ((counter.first == static_cast<int>(StorageAccount::Operation::write)) ||
355  (counter.first == static_cast<int>(StorageAccount::Operation::writev))) {
356  writeBytes += counter.second.amount;
357  writeTimeTotal += counter.second.timeTotal;
358  }
359  }
360  }
361  updateChirp("ReadOps", readOps);
362  updateChirp("ReadVOps", readVOps);
363  updateChirp("ReadSegments", readSegs);
364  updateChirp("ReadBytes", readBytes);
365  updateChirp("ReadTimeMsecs", readTimeTotal / (1000 * 1000));
366  updateChirp("WriteBytes", writeBytes);
367  updateChirp("WriteTimeMsecs", writeTimeTotal / (1000 * 1000));
368 }
369 
370 template <typename T>
371 bool CondorStatusService::updateChirp(const std::string &key_suffix, const T &value) {
372  std::stringstream ss;
373  ss << value;
374  return updateChirpImpl(key_suffix, ss.str());
375 }
376 
378  std::string value_copy = value;
379  // Remove double-quotes or the \ character (as it has special escaping semantics in ClassAds).
380  // Make sure we have ASCII characters.
381  // Otherwise, remainder is allowed (including tabs, newlines, single-quotes).
382  value_copy.erase(
383  remove_if(
384  value_copy.begin(), value_copy.end(), [](const char &c) { return !isascii(c) || (c == '"') || (c == '\\'); }),
385  value_copy.end());
386  return updateChirpImpl(key_suffix, "\"" + value_copy + "\"");
387 }
388 
390  std::stringstream ss;
391  ss << "ChirpCMSSW" << m_tag << key_suffix;
392  std::string key = ss.str();
393  if (m_debug) {
394  std::cout << "condor_chirp set_job_attr_delayed " << key << " " << value << std::endl;
395  }
396  int pid = 0;
397  posix_spawn_file_actions_t file_actions;
398  int devnull_fd = open("/dev/null", O_RDWR);
399  if (devnull_fd == -1) {
400  return false;
401  }
402  posix_spawn_file_actions_init(&file_actions);
403  posix_spawn_file_actions_adddup2(&file_actions, devnull_fd, 1);
404  posix_spawn_file_actions_adddup2(&file_actions, devnull_fd, 2);
405  const std::string chirp_name = "condor_chirp";
406  const std::string set_job_attr = "set_job_attr_delayed";
407  std::vector<const char *> argv;
408  argv.push_back(chirp_name.c_str());
409  argv.push_back(set_job_attr.c_str());
410  argv.push_back(key.c_str());
411  argv.push_back(value.c_str());
412  argv.push_back(nullptr);
413  int status = posix_spawnp(&pid, "condor_chirp", &file_actions, nullptr, const_cast<char *const *>(&argv[0]), environ);
414  close(devnull_fd);
415  posix_spawn_file_actions_destroy(&file_actions);
416  if (status) {
417  return false;
418  }
419  while ((waitpid(pid, &status, 0) == -1) && errno == -EINTR) {
420  }
421  return status == 0;
422 }
423 
426  desc.setComment("Service to update HTCondor with the current CMSSW status.");
427  desc.addOptionalUntracked<unsigned int>("updateIntervalSeconds", m_defaultUpdateInterval)
428  ->setComment("Interval, in seconds, for HTCondor updates");
429  desc.addOptionalUntracked<bool>("debug", false)->setComment("Enable debugging of this service");
430  desc.addOptionalUntracked<double>("EMAInterval", m_defaultEmaInterval)
431  ->setComment("Interval, in seconds, to calculate event rate over (using EMA)");
432  desc.addOptionalUntracked<std::string>("tag")->setComment(
433  "Identifier tag for this process (a value of 'Foo' results in ClassAd attributes of the form 'ChirpCMSSWFoo*')");
434  desc.addOptionalUntracked<bool>("enable", true)->setComment("Enable this service");
435  descriptions.add("CondorStatusService", desc);
436 }
437 
439 
bool updateChirpImpl(std::string const &key, std::string const &value)
constexpr int32_t ceil(float num)
CondorStatusService(ParameterSet const &pset, edm::ActivityRegistry &ar)
virtual double cpuAverageSpeed() const =0
#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)
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()
bool isProcessWideService(TFileService const *)
Definition: TFileService.h:98
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]
virtual std::string const & cpuModelsFormatted() const =0
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
Log< level::Warning, false > LogWarning
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