33namespace {
44const size_t CONTAINER_ID_LENGTH = 64 ;
55const size_t REPORTED_CONTAINER_ID_LENGTH = 12 ;
6- const char *CONTAINER_ID_VALID_CHARACTERS = " 0123456789abcdefABCDEF" ;
76
87static_assert (REPORTED_CONTAINER_ID_LENGTH <= CONTAINER_ID_LENGTH,
98" Reported container ID length cannot be longer than actual length" );
@@ -13,6 +12,25 @@ static_assert(REPORTED_CONTAINER_ID_LENGTH <= CONTAINER_ID_LENGTH,
1312namespace libsinsp {
1413namespace runc {
1514
15+ inline static bool endswith (const std::string &s, const std::string &suffix) {
16+ return s.rfind (suffix) == (s.size () - suffix.size ());
17+ }
18+
19+ inline static bool is_host (const std::string &cgroup) {
20+ // A good approximation to minize false-positives is to exclude systemd suffixes.
21+ if (endswith (cgroup, " .slice" ) || endswith (cgroup, " .service" )) {
22+ return true ;
23+ } else if (endswith (cgroup, " .scope" )) {
24+ if (cgroup.find (" crio-" ) != std::string::npos ||
25+ cgroup.find (" docker-" ) != std::string::npos) {
26+ return false ;
27+ }
28+ return true ;
29+ }
30+
31+ return false ;
32+ }
33+
1634// check if cgroup ends with <prefix><container_id><suffix>
1735// If true, set <container_id> to a truncated version of the id and return true.
1836// Otherwise return false and leave container_id unchanged
@@ -31,16 +49,21 @@ bool match_one_container_id(const std::string &cgroup,
3149 return false ;
3250 }
3351
34- if (end_pos - start_pos != CONTAINER_ID_LENGTH) {
52+ // In some container runtimes the container id is not
53+ // necessarly CONTAINER_ID_LENGTH long and can be arbitrarly defined.
54+ // To keep it simple we only discard the container id > of CONTAINER_ID_LENGTH.
55+ if (end_pos - start_pos > CONTAINER_ID_LENGTH || end_pos - start_pos == 0 ) {
3556 return false ;
3657 }
3758
38- size_t invalid_ch_pos = cgroup.find_first_not_of (CONTAINER_ID_VALID_CHARACTERS, start_pos);
39- if (invalid_ch_pos < CONTAINER_ID_LENGTH) {
59+ if (is_host (cgroup)) {
4060 return false ;
4161 }
4262
43- container_id = cgroup.substr (start_pos, REPORTED_CONTAINER_ID_LENGTH);
63+ size_t reported_len = end_pos - start_pos >= REPORTED_CONTAINER_ID_LENGTH
64+ ? REPORTED_CONTAINER_ID_LENGTH
65+ : end_pos;
66+ container_id = cgroup.substr (start_pos, reported_len);
4467 return true ;
4568}
4669
@@ -52,7 +75,6 @@ bool matches_runc_cgroup(const std::string &cgroup,
5275 return true ;
5376 }
5477 }
55-
5678 return false ;
5779}
5880} // namespace runc
0 commit comments