|
| 1 | +#include <vcpkg/base/parse.h> |
| 2 | +#include <vcpkg/base/stringview.h> |
| 3 | +#include <vcpkg/base/system.debug.h> |
| 4 | +#include <vcpkg/base/util.h> |
| 5 | + |
| 6 | +#include <vcpkg/cgroup-parser.h> |
| 7 | + |
| 8 | +namespace vcpkg |
| 9 | +{ |
| 10 | + ControlGroup::ControlGroup(long id, StringView s, StringView c) |
| 11 | + : hierarchy_id(id), subsystems(s.data(), s.size()), control_group(c.data(), c.size()) |
| 12 | + { |
| 13 | + } |
| 14 | + |
| 15 | + // parses /proc/[pid]/cgroup file as specified in https://linux.die.net/man/5/proc |
| 16 | + // The file describes control groups to which the process/tasks belongs. |
| 17 | + // For each cgroup hierarchy there is one entry |
| 18 | + // containing colon-separated fields of the form: |
| 19 | + // 5:cpuacct,cpu,cpuset:/daemos |
| 20 | + // |
| 21 | + // The colon separated fields are, from left to right: |
| 22 | + // |
| 23 | + // 1. hierarchy ID number |
| 24 | + // 2. set of subsystems bound to the hierarchy |
| 25 | + // 3. control group in the hierarchy to which the process belongs |
| 26 | + std::vector<ControlGroup> parse_cgroup_file(StringView text, StringView origin) |
| 27 | + { |
| 28 | + using P = ParserBase; |
| 29 | + constexpr auto is_separator_or_lineend = [](auto ch) { return ch == ':' || P::is_lineend(ch); }; |
| 30 | + |
| 31 | + auto parser = ParserBase(text, origin); |
| 32 | + parser.skip_whitespace(); |
| 33 | + |
| 34 | + std::vector<ControlGroup> ret; |
| 35 | + while (!parser.at_eof()) |
| 36 | + { |
| 37 | + auto id = parser.match_until(is_separator_or_lineend); |
| 38 | + auto maybe_numeric_id = Strings::strto<long>(id); |
| 39 | + if (!maybe_numeric_id || P::is_lineend(parser.cur())) |
| 40 | + { |
| 41 | + ret.clear(); |
| 42 | + break; |
| 43 | + } |
| 44 | + |
| 45 | + parser.next(); |
| 46 | + auto subsystems = parser.match_until(is_separator_or_lineend); |
| 47 | + if (P::is_lineend(parser.cur())) |
| 48 | + { |
| 49 | + ret.clear(); |
| 50 | + break; |
| 51 | + } |
| 52 | + |
| 53 | + parser.next(); |
| 54 | + auto control_group = parser.match_until(P::is_lineend); |
| 55 | + parser.skip_whitespace(); |
| 56 | + |
| 57 | + ret.emplace_back(*maybe_numeric_id.get(), subsystems, control_group); |
| 58 | + } |
| 59 | + |
| 60 | + return ret; |
| 61 | + } |
| 62 | + |
| 63 | + bool detect_docker_in_cgroup_file(StringView text, StringView origin) |
| 64 | + { |
| 65 | + return Util::any_of(parse_cgroup_file(text, origin), [](auto&& cgroup) { |
| 66 | + return Strings::starts_with(cgroup.control_group, "/docker") || |
| 67 | + Strings::starts_with(cgroup.control_group, "/lxc"); |
| 68 | + }); |
| 69 | + } |
| 70 | +} |
0 commit comments