33#include < base/defines.h>
44
55#include < fstream>
6- #include < sstream >
6+ #include < string >
77
8+ namespace fs = std::filesystem;
89
910bool cgroupsV2Enabled ()
1011{
@@ -13,11 +14,11 @@ bool cgroupsV2Enabled()
1314 {
1415 // / This file exists iff the host has cgroups v2 enabled.
1516 auto controllers_file = default_cgroups_mount / " cgroup.controllers" ;
16- if (!std::filesystem ::exists (controllers_file))
17+ if (!fs ::exists (controllers_file))
1718 return false ;
1819 return true ;
1920 }
20- catch (const std::filesystem ::filesystem_error &) // / all "underlying OS API errors", typically: permission denied
21+ catch (const fs ::filesystem_error &) // / all "underlying OS API errors", typically: permission denied
2122 {
2223 return false ; // / not logging the exception as most callers fall back to cgroups v1
2324 }
@@ -33,8 +34,9 @@ bool cgroupsV2MemoryControllerEnabled()
3334 // / According to https://docs.kernel.org/admin-guide/cgroup-v2.html, file "cgroup.controllers" defines which controllers are available
3435 // / for the current + child cgroups. The set of available controllers can be restricted from level to level using file
3536 // / "cgroups.subtree_control". It is therefore sufficient to check the bottom-most nested "cgroup.controllers" file.
36- std::string cgroup = cgroupV2OfProcess ();
37- auto cgroup_dir = cgroup.empty () ? default_cgroups_mount : (default_cgroups_mount / cgroup);
37+ fs::path cgroup_dir = cgroupV2PathOfProcess ();
38+ if (cgroup_dir.empty ())
39+ return false ;
3840 std::ifstream controllers_file (cgroup_dir / " cgroup.controllers" );
3941 if (!controllers_file.is_open ())
4042 return false ;
@@ -46,25 +48,26 @@ bool cgroupsV2MemoryControllerEnabled()
4648#endif
4749}
4850
49- std::string cgroupV2OfProcess ()
51+ fs::path cgroupV2PathOfProcess ()
5052{
5153#if defined(OS_LINUX)
5254 chassert (cgroupsV2Enabled ());
5355 // / All PIDs assigned to a cgroup are in /sys/fs/cgroups/{cgroup_name}/cgroup.procs
5456 // / A simpler way to get the membership is:
5557 std::ifstream cgroup_name_file (" /proc/self/cgroup" );
5658 if (!cgroup_name_file.is_open ())
57- return " " ;
59+ return {} ;
5860 // / With cgroups v2, there will be a *single* line with prefix "0::/"
5961 // / (see https://docs.kernel.org/admin-guide/cgroup-v2.html)
6062 std::string cgroup;
6163 std::getline (cgroup_name_file, cgroup);
6264 static const std::string v2_prefix = " 0::/" ;
6365 if (!cgroup.starts_with (v2_prefix))
64- return " " ;
66+ return {} ;
6567 cgroup = cgroup.substr (v2_prefix.length ());
66- return cgroup;
68+ // / Note: The 'root' cgroup can have an empty cgroup name, this is valid
69+ return default_cgroups_mount / cgroup;
6770#else
68- return " " ;
71+ return {} ;
6972#endif
7073}
0 commit comments