Skip to content

Commit bf47300

Browse files
laoarAlexei Starovoitov
authored and
Alexei Starovoitov
committed
selftests/bpf: Add a new cgroup helper get_cgroup_hierarchy_id()
A new cgroup helper function, get_cgroup1_hierarchy_id(), has been introduced to obtain the ID of a cgroup1 hierarchy based on the provided cgroup name. This cgroup name can be obtained from the /proc/self/cgroup file. Signed-off-by: Yafang Shao <[email protected]> Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Alexei Starovoitov <[email protected]>
1 parent c1dcc05 commit bf47300

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

tools/testing/selftests/bpf/cgroup_helpers.c

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -637,3 +637,55 @@ unsigned long long get_classid_cgroup_id(void)
637637
format_classid_path(cgroup_workdir);
638638
return get_cgroup_id_from_path(cgroup_workdir);
639639
}
640+
641+
/**
642+
* get_cgroup1_hierarchy_id - Retrieves the ID of a cgroup1 hierarchy from the cgroup1 subsys name.
643+
* @subsys_name: The cgroup1 subsys name, which can be retrieved from /proc/self/cgroup. It can be
644+
* a named cgroup like "name=systemd", a controller name like "net_cls", or multi-contollers like
645+
* "net_cls,net_prio".
646+
*/
647+
int get_cgroup1_hierarchy_id(const char *subsys_name)
648+
{
649+
char *c, *c2, *c3, *c4;
650+
bool found = false;
651+
char line[1024];
652+
FILE *file;
653+
int i, id;
654+
655+
if (!subsys_name)
656+
return -1;
657+
658+
file = fopen("/proc/self/cgroup", "r");
659+
if (!file) {
660+
log_err("fopen /proc/self/cgroup");
661+
return -1;
662+
}
663+
664+
while (fgets(line, 1024, file)) {
665+
i = 0;
666+
for (c = strtok_r(line, ":", &c2); c && i < 2; c = strtok_r(NULL, ":", &c2)) {
667+
if (i == 0) {
668+
id = strtol(c, NULL, 10);
669+
} else if (i == 1) {
670+
if (!strcmp(c, subsys_name)) {
671+
found = true;
672+
break;
673+
}
674+
675+
/* Multiple subsystems may share one single mount point */
676+
for (c3 = strtok_r(c, ",", &c4); c3;
677+
c3 = strtok_r(NULL, ",", &c4)) {
678+
if (!strcmp(c, subsys_name)) {
679+
found = true;
680+
break;
681+
}
682+
}
683+
}
684+
i++;
685+
}
686+
if (found)
687+
break;
688+
}
689+
fclose(file);
690+
return found ? id : -1;
691+
}

tools/testing/selftests/bpf/cgroup_helpers.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ int get_root_cgroup(void);
2020
int create_and_get_cgroup(const char *relative_path);
2121
void remove_cgroup(const char *relative_path);
2222
unsigned long long get_cgroup_id(const char *relative_path);
23+
int get_cgroup1_hierarchy_id(const char *subsys_name);
2324

2425
int join_cgroup(const char *relative_path);
2526
int join_root_cgroup(void);

0 commit comments

Comments
 (0)