Skip to content

Instantly share code, notes, and snippets.

@crazyboycjr
Last active July 25, 2018 07:14
Show Gist options
  • Save crazyboycjr/3c4f702821bba1e10c6bfb3f60e7d017 to your computer and use it in GitHub Desktop.
Save crazyboycjr/3c4f702821bba1e10c6bfb3f60e7d017 to your computer and use it in GitHub Desktop.
netdev_to_ibdev
#include "prism/logging.h"
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <dirent.h>
#include <string>
#include <iostream>
#include <fstream>
#include <unordered_map>
std::unordered_map<std::string, std::string> eth_to_ib_;
std::unordered_map<std::string, std::string> ib_to_eth_;
void NetDevToIbDev() {
std::vector<std::string> eth_vec;
std::vector<std::string> ib_vec;
const std::string net_device_path = "/sys/class/net";
const std::string ib_device_path = "/sys/class/infiniband";
auto get_device_list = [](auto &vec, const char *path) {
DIR *dirp = opendir(path);
CHECK(dirp) << (perror("opendir"), path);
struct dirent *dp;
while (dp = readdir(dirp)) {
std::string dev = dp->d_name;
if (dev != "." && dev != "..")
vec.emplace_back(dp->d_name);
}
CHECK_EQ(0, closedir(dirp));
};
get_device_list(eth_vec, net_device_path.c_str());
get_device_list(ib_vec, ib_device_path.c_str());
auto get_dev_resource = [](const std::string &res_path) -> std::string {
std::string res;
std::ifstream res_file(res_path);
res_file >> res;
res_file.close();
return res;
};
for (const auto &eth : eth_vec) {
std::string eth_dev_path = net_device_path + "/" + eth + "/device/resource";
auto eth_resource = std::move(get_dev_resource(eth_dev_path));
for (const auto &ib : ib_vec) {
std::string ib_dev_path = ib_device_path + "/" + ib + "/device/resource";
auto ib_resource = std::move(get_dev_resource(ib_dev_path));
if (eth_resource == ib_resource) {
eth_to_ib_[eth] = ib;
ib_to_eth_[ib] = eth;
}
}
}
}
int main() {
NetDevToIbDev();
for (auto it : eth_to_ib_) {
auto eth = it.first;
std::cout << eth << " " << eth_to_ib_[eth] << std::endl;
}
int fd = open("/sys/class/net/eth5/carrier", O_RDONLY | O_CLOEXEC);
if (fd < 0) {
printf("err\n");
}
close(fd);
std::string value;
try {
std::ifstream ifile("/sys/class/net/eth5/carrier");
ifile >> value;
ifile.close();
} catch (const std::exception &e) {
std::cerr << e.what() << std::endl;
}
if (value.empty()) {
std::cout << "Down" << std::endl;
} else {
CHECK_EQ(value, "1");
std::cout << "Up" << std::endl;
}
std::string s = "";
bool f = s.empty();
std::cout << f << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment