Kagome
Polkadot Runtime Engine in C++17
fd_limit.cpp
Go to the documentation of this file.
1 
6 #include "common/fd_limit.hpp"
7 
8 #include <sys/resource.h>
9 #include <algorithm>
10 #include <boost/iterator/counting_iterator.hpp>
11 
12 #include "log/logger.hpp"
13 
14 namespace kagome::common {
15  namespace {
16  inline auto log() {
17  return log::createLogger("FdLimit", log::defaultGroupName);
18  }
19 
20  bool getFdLimit(rlimit &r) {
21  if (getrlimit(RLIMIT_NOFILE, &r) != 0) {
22  SL_WARN(log(),
23  "Error: getrlimit(RLIMIT_NOFILE) errno={} {}",
24  errno,
25  strerror(errno));
26  return false;
27  }
28  return true;
29  }
30 
31  bool setFdLimit(const rlimit &r) {
32  return setrlimit(RLIMIT_NOFILE, &r) == 0;
33  }
34  } // namespace
35 
36  std::optional<size_t> getFdLimit() {
37  rlimit r{};
38  if (!getFdLimit(r)) {
39  return std::nullopt;
40  }
41  return r.rlim_cur;
42  }
43 
44  void setFdLimit(size_t limit) {
45  rlimit r{};
46  if (!getFdLimit(r)) {
47  return;
48  }
49  if (r.rlim_max == RLIM_INFINITY) {
50  SL_VERBOSE(log(), "current={} max=unlimited", r.rlim_cur);
51  } else {
52  SL_VERBOSE(log(), "current={} max={}", r.rlim_cur, r.rlim_max);
53  }
54  const rlim_t current = r.rlim_cur;
55  if (limit == current) {
56  return;
57  }
58  r.rlim_cur = limit;
59  if (limit < current) {
60  SL_WARN(log(), "requested limit is lower than system allowed limit");
61  setFdLimit(r);
62  } else if (!setFdLimit(r)) {
63  std::upper_bound(boost::counting_iterator{current},
64  boost::counting_iterator{rlim_t{limit}},
65  nullptr,
66  [&](std::nullptr_t, rlim_t current) {
67  r.rlim_cur = current;
68  return !setFdLimit(r);
69  });
70  }
71  if (!getFdLimit(r)) {
72  return;
73  }
74  if (r.rlim_cur != current) {
75  SL_VERBOSE(log(), "changed current={}", r.rlim_cur);
76  }
77  }
78 } // namespace kagome::common
void setFdLimit(size_t limit)
Definition: fd_limit.cpp:44
static const std::string defaultGroupName("kagome")
Logger createLogger(const std::string &tag)
Definition: logger.cpp:112
std::optional< size_t > getFdLimit()
Definition: fd_limit.cpp:36