std::optional read_sysfs_cgroup_inode()

in xar/XarHelpers.cpp [95:128]


std::optional<ino_t> read_sysfs_cgroup_inode(const char* filename) {
  const auto maybe_contents = read_file_prefix(filename, 4096);
  if (!maybe_contents) {
    return std::nullopt;
  }
  const auto contents = *maybe_contents;
  if (contents.size() == 4096) {
    return std::nullopt;
  }

  // File contents are a colon-separated triplet.  We want the last
  // field, and to toss out the trailing newline.
  auto components = tools::xar::split(':', contents);
  if (components.size() < 3) {
    return std::nullopt;
  }
  auto newline_pos = components[2].find('\n');
  if (newline_pos != std::string::npos) {
    components[2].erase(newline_pos);
  }

  // /sys/fs/cgroup is the typical mount point for the cgroup2
  // filesystem, but it is not guaranteed.  In some FB environments
  // we've historically used /cgroup2 instead.
  for (auto& candidate : {"/sys/fs/cgroup", "/cgroup2"}) {
    auto path = std::string(candidate) + "/" + components[2];
    struct stat st;
    if (stat(path.c_str(), &st) == 0) {
      return st.st_ino;
    }
  }

  return std::nullopt;
}