folly::Optional findNonEmptySubsystem()

in bistro/processes/AsyncCGroupReaper.cpp [107:146]


  folly::Optional<std::string> findNonEmptySubsystem() noexcept {
    // While checking /cgroup.procs files, keep in mind that the kernel
    // `release_agent` can remove a cgroup from under us at any time.
    for (const auto& subsystem : *cgroupOpts_.subsystems_ref()) {
      auto dir = cgroupDir(subsystem);
      boost::system::error_code ec;
      if (!boost::filesystem::is_directory(dir, ec) || ec) {
        continue;  // cgroup was likely already reaped
      }
      // Don't trust `filesystem::is_empty` since sysfs metadata is bogus.
      try {
        folly::File procs_file(dir + "/cgroup.procs");
        char c;  // Reading one byte is enough to prove non-emptiness.
        ssize_t bytes_read = folly::readFull(procs_file.fd(), &c, 1);
        if (bytes_read == 1) {
          if (c < '0' || c > '9') {
            LOG(WARNING) << dir << "/cgroup.procs starts with bad char: " << c;
          }
          return subsystem;  // At least one cgroup contains data.
        } else if (bytes_read == -1) {
          PLOG(WARNING) << dir << "/cgroup.procs is unreadable";
        } else if (bytes_read == 0) {
          // Empty cgroup, but the directory still exists -- try to reap it.
          if (boost::filesystem::remove(dir, ec) && !ec) {
            LOG(INFO) << "Removed empty cgroup " << dir;
          } else if (ec) {
            LOG(WARNING) << "Failed to remove empty cgroup: " << dir
              << ": " << ec.message();
          }  // else: no file or directory existed at `dir`, no error occurred.
        } else {
          LOG(FATAL) << "read() returned bad value: " << bytes_read;
        }
      } catch (const std::exception& ex) {
        // Maybe we raced the system `release_agent` to reap the directory?
        LOG(WARNING) << dir << "/cgroup.procs is unreadable: " << ex.what();
      }
      // Either the cgroup is empty, or a read error made us assume it's gone.
    }
    return folly::none;
  }