Skip to content

Commit

Permalink
Improve process monitoring (#58)
Browse files Browse the repository at this point in the history
Read /proc file instead of using bash command when getting network stats
  • Loading branch information
awegrzyn authored Jun 29, 2018
1 parent 9975558 commit 808a618
Showing 1 changed file with 27 additions and 24 deletions.
51 changes: 27 additions & 24 deletions src/ProcessMonitor.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
#include <chrono>
#include <sstream>
#include <cmath>
#include <fstream>
#include <utility>

namespace o2
{
Expand All @@ -24,30 +26,6 @@ ProcessMonitor::ProcessMonitor()
mTimeLastRun = std::chrono::high_resolution_clock::now();
}

std::vector<Metric> ProcessMonitor::getNetworkUsage()
{
std::vector<Metric> metrics;
std::stringstream ss;
// get bytes received and transmitted per interface
ss << "cat /proc/" << mPid << "/net/dev | tail -n +3 | grep -v -e 'lo' -e 'virbr0' | awk ' {print $1 $2 \":\" $10}'";
std::string output = exec(ss.str().c_str());
// for each line (each network interfrace)
std::istringstream iss(output);
for (std::string line; std::getline(iss, line); ) {
auto position = line.find(":");
auto secondPosition = line.find(":", position + 1);
metrics.emplace_back(Metric{
static_cast<uint64_t>(std::stoull(line.substr(position + 1, secondPosition - position - 1))),
"bytesReceived"}.addTags({{"if", line.substr(0, position)}})
);
metrics.emplace_back(Metric{
static_cast<uint64_t>(std::stoull(line.substr(secondPosition + 1, line.size()))),
"bytesTransmitted"}.addTags({{"if", line.substr(0, position)}})
);
}
return metrics;
}

Metric ProcessMonitor::getMemoryUsage()
{
std::string command = "ps --no-headers -o pmem --pid " + std::to_string(mPid);
Expand Down Expand Up @@ -82,6 +60,31 @@ std::vector<Metric> ProcessMonitor::getCpuAndContexts() {
return metrics;
}

std::vector<Metric> ProcessMonitor::getNetworkUsage()
{
std::vector<Metric> metrics;
std::ifstream infile("/proc/" + std::to_string(mPid) + "/net/dev");
std::string line;
std::getline(infile, line);
std::getline(infile, line);
while (std::getline(infile, line)) {
if (line.find("virbr") != std::string::npos) continue;
if (line.find("lo") != std::string::npos) continue;
std::istringstream iss(line);
std::vector<std::string> tokens{std::istream_iterator<std::string>{iss},
std::istream_iterator<std::string>{}};
metrics.emplace_back(Metric{
static_cast<uint64_t>(std::stoull(tokens[1])),
"bytesReceived"}.addTags({{"if", tokens[0]}})
);
metrics.emplace_back(Metric{
static_cast<uint64_t>(std::stoull(tokens[9])),
"bytesTransmitted"}.addTags({{"if", tokens[0]}})
);
}
return metrics;
}

std::string ProcessMonitor::exec(const char* cmd)
{
char buffer[128];
Expand Down

0 comments on commit 808a618

Please sign in to comment.