]> git.proxmox.com Git - pve-container.git/blob - src/PVE/LXC/CGroup.pm
cgroup: use version returned from get_path()
[pve-container.git] / src / PVE / LXC / CGroup.pm
1 # cgroup handler
2 #
3 # This package should deal with figuring out the right cgroup path for a
4 # container (via the command socket), reading and writing cgroup values, and
5 # handling cgroup v1 & v2 differences.
6 #
7 # Note that the long term plan is to have resource manage functions instead of
8 # dealing with cgroup files on the outside.
9
10 package PVE::LXC::CGroup;
11
12 use strict;
13 use warnings;
14
15 use POSIX qw();
16
17 use PVE::ProcFSTools;
18 use PVE::Tools qw(
19 file_get_contents
20 file_read_firstline
21 );
22
23 use PVE::LXC::Command;
24
25 # We don't want to do a command socket round trip for every cgroup read/write,
26 # so any cgroup function needs to have the container's path cached, so this
27 # package has to be instantiated.
28 #
29 # LXC keeps separate paths by controller (although they're normally all the
30 # same, in our # case anyway), so we cache them by controller as well.
31 sub new {
32 my ($class, $vmid) = @_;
33
34 my $self = { vmid => $vmid };
35
36 return bless $self, $class;
37 }
38
39 # Get the v1 controller list.
40 #
41 # Returns a set (hash mapping names to `1`) of cgroupv1 controllers, and an
42 # optional boolean whether a unified (cgroupv2) hierarchy exists.
43 #
44 # Deprecated: Use `get_cgroup_controllers()` instead.
45 sub get_v1_controllers {
46 my $v1 = {};
47 my $v2 = 0;
48 my $data = PVE::Tools::file_get_contents('/proc/self/cgroup');
49 while ($data =~ /^\d+:([^:\n]*):.*$/gm) {
50 my $type = $1;
51 if (length($type)) {
52 $v1->{$_} = 1 foreach split(/,/, $type);
53 } else {
54 $v2 = 1;
55 }
56 }
57 return wantarray ? ($v1, $v2) : $v1;
58 }
59
60 # Get the set v2 controller list from the `cgroup.controllers` file.
61 my sub get_v2_controllers {
62 my $v2 = eval { file_get_contents('/sys/fs/cgroup/cgroup.controllers') }
63 || eval { file_get_contents('/sys/fs/cgroup/unified/cgroup.controllers') };
64 return undef if !defined $v2;
65
66 # It's a simple space separated list:
67 return { map { $_ => 1 } split(/\s+/, $v2) };
68 }
69
70 my $CGROUP_CONTROLLERS = undef;
71 # Get a list of controllers enabled in each cgroup subsystem.
72 #
73 # This is a more complete version of `PVE::LXC::get_cgroup_subsystems`.
74 #
75 # Returns 2 sets (hashes mapping controller names to `1`), one for each cgroup
76 # version.
77 sub get_cgroup_controllers() {
78 if (!defined($CGROUP_CONTROLLERS)) {
79 my ($v1, undef) = get_v1_controllers();
80 my $v2 = get_v2_controllers();
81
82 $CGROUP_CONTROLLERS = [$v1, $v2];
83 }
84
85 return $CGROUP_CONTROLLERS->@*;
86 }
87
88 my $CGROUP_MODE = undef;
89 # Figure out which cgroup mode we're operating under:
90 #
91 # Returns 1 if cgroupv1 controllers exist (hybrid or legacy mode), and 2 in a
92 # cgroupv2-only environment.
93 #
94 # NOTE: To fully support a hybrid layout it is better to use functions like
95 # `cpuset_controller_path`.
96 #
97 # This is a function, not a method!
98 sub cgroup_mode() {
99 if (!defined($CGROUP_MODE)) {
100 my ($v1, $v2) = get_cgroup_controllers();
101 if (keys %$v1) {
102 # hybrid or legacy mode
103 $CGROUP_MODE = 1;
104 } elsif ($v2) {
105 $CGROUP_MODE = 2;
106 }
107 }
108
109 die "unknown cgroup mode\n" if !defined($CGROUP_MODE);
110 return $CGROUP_MODE;
111 }
112
113 # Find a cgroup controller and return its path and version.
114 #
115 # LXC initializes the unified hierarchy first, so if a controller is
116 # available via both we favor cgroupv2 here as well.
117 #
118 # Returns nothing if the controller is not available.
119 sub find_cgroup_controller($) {
120 my ($controller) = @_;
121
122 my ($v1, $v2) = get_cgroup_controllers();
123
124 if (!defined($controller) || $v2->{$controller}) {
125 my $path;
126 if (cgroup_mode() == 2) {
127 $path = '/sys/fs/cgroup';
128 } else {
129 $path = '/sys/fs/cgroup/unified';
130 }
131 return wantarray ? ($path, 2) : $path;
132 }
133
134 if (defined($controller) && $v1->{$controller}) {
135 my $path = "/sys/fs/cgroup/$controller";
136 return wantarray ? ($path, 1) : $path;
137 }
138
139 return;
140 }
141
142 my $CG_PATH_CPUSET = undef;
143 my $CG_VER_CPUSET = undef;
144 # Find the cpuset cgroup controller.
145 #
146 # This is a function, not a method!
147 sub cpuset_controller_path() {
148 if (!defined($CG_PATH_CPUSET)) {
149 ($CG_PATH_CPUSET, $CG_VER_CPUSET) = find_cgroup_controller('cpuset')
150 or die "failed to find cpuset controller\n";
151 }
152
153 return wantarray ? ($CG_PATH_CPUSET, $CG_VER_CPUSET) : $CG_PATH_CPUSET;
154 }
155
156 # Get a subdirectory (without the cgroup mount point) for a controller.
157 #
158 # If `$controller` is `undef`, get the unified (cgroupv2) path.
159 #
160 # Note that in cgroup v2, lxc uses the activated controller names
161 # (`cgroup.controllers` file) as list of controllers for the unified hierarchy,
162 # so this returns a result when a `controller` is provided even when using
163 # a pure cgroupv2 setup.
164 my sub get_subdir {
165 my ($self, $controller, $limiting) = @_;
166
167 my $entry_name = $controller || 'unified';
168 my $entry = ($self->{controllers}->{$entry_name} //= {});
169
170 my $kind = $limiting ? 'limit' : 'ns';
171 my $path = $entry->{$kind};
172
173 return $path if defined $path;
174
175 $path = PVE::LXC::Command::get_cgroup_path(
176 $self->{vmid},
177 $controller,
178 $limiting,
179 ) or return undef;
180
181 # untaint:
182 if ($path =~ /\.\./) {
183 die "lxc returned suspicious path: '$path'\n";
184 }
185 ($path) = ($path =~ /^(.*)$/s);
186
187 $entry->{$kind} = $path;
188
189 return $path;
190 }
191
192 # Get path and version for a controller.
193 #
194 # `$controller` may be `undef`, see get_subdir above for details.
195 #
196 # Returns either just the path, or the path and cgroup version as a tuple.
197 sub get_path {
198 my ($self, $controller) = @_;
199
200 # Find the controller before querying the lxc monitor via a socket:
201 my ($cgpath, $ver) = find_cgroup_controller($controller)
202 or return undef;
203
204 my $path = get_subdir($self, $controller)
205 or return undef;
206
207 $path = "$cgpath/$path";
208 return wantarray ? ($path, $ver) : $path;
209 }
210
211 # Convenience method to get the path info if the first existing controller.
212 #
213 # Returns the same as `get_path`.
214 sub get_any_path {
215 my ($self, @controllers) = @_;
216
217 my ($path, $ver);
218 for my $c (@controllers) {
219 ($path, $ver) = $self->get_path($c);
220 last if defined $path;
221 }
222 return wantarray ? ($path, $ver) : $path;
223 }
224
225 # Parse a 'Nested keyed' file:
226 #
227 # See kernel documentation `admin-guide/cgroup-v2.rst` 4.1.
228 my sub parse_nested_keyed_file($) {
229 my ($data) = @_;
230 my $res = {};
231 foreach my $line (split(/\n/, $data)) {
232 my ($key, @values) = split(/\s+/, $line);
233
234 my $d = ($res->{$key} = {});
235
236 foreach my $value (@values) {
237 if (my ($key, $value) = ($value =~ /^([^=]+)=(.*)$/)) {
238 $d->{$key} = $value;
239 } else {
240 warn "bad key=value pair in nested keyed file\n";
241 }
242 }
243 }
244 return $res;
245 }
246
247 # Parse a 'Flat keyed' file:
248 #
249 # See kernel documentation `admin-guide/cgroup-v2.rst` 4.1.
250 my sub parse_flat_keyed_file($) {
251 my ($data) = @_;
252 my $res = {};
253 foreach my $line (split(/\n/, $data)) {
254 if (my ($key, $value) = ($line =~ /^(\S+)\s+(.*)$/)) {
255 $res->{$key} = $value;
256 } else {
257 warn "bad 'key value' pair in flat keyed file\n";
258 }
259 }
260 return $res;
261 }
262
263 # Parse out 'diskread' and 'diskwrite' values from I/O stats for this container.
264 sub get_io_stats {
265 my ($self) = @_;
266
267 my $res = {
268 diskread => 0,
269 diskwrite => 0,
270 };
271
272 # With cgroupv1 we have a 'blkio' controller, with cgroupv2 it's just 'io':
273 my ($path, $ver) = $self->get_any_path('io', 'blkio');
274 if (!defined($path)) {
275 # container not running
276 return undef;
277 } elsif ($ver == 2) {
278 # cgroupv2 environment, io controller enabled
279 my $io_stat = file_get_contents("$path/io.stat");
280
281 my $data = parse_nested_keyed_file($io_stat);
282 foreach my $dev (keys %$data) {
283 my $dev = $data->{$dev};
284 if (my $b = $dev->{rbytes}) {
285 $res->{diskread} += $b;
286 }
287 if (my $b = $dev->{wbytes}) {
288 $res->{diskread} += $b;
289 }
290 }
291
292 return $res;
293 } elsif ($ver == 1) {
294 # cgroupv1 environment:
295 my $io = file_get_contents("$path/blkio.throttle.io_service_bytes_recursive");
296 foreach my $line (split(/\n/, $io)) {
297 if (my ($type, $bytes) = ($line =~ /^\d+:\d+\s+(Read|Write)\s+(\d+)$/)) {
298 $res->{diskread} += $bytes if $type eq 'Read';
299 $res->{diskwrite} += $bytes if $type eq 'Write';
300 }
301 }
302
303 return $res;
304 } else {
305 die "bad cgroup version: $ver\n";
306 }
307
308 # container not running
309 return undef;
310 }
311
312 # Read utime and stime for this container from the cpuacct cgroup.
313 # Values are in milliseconds!
314 sub get_cpu_stat {
315 my ($self) = @_;
316
317 my $res = {
318 utime => 0,
319 stime => 0,
320 };
321
322 my ($path, $ver) = $self->get_any_path('cpuacct', 'cpu');
323 if (!defined($path)) {
324 # container not running
325 return undef;
326 } elsif ($ver == 2) {
327 my $data = eval { file_get_contents("$path/cpu.stat") };
328
329 # or no io controller available:
330 return undef if !defined($data);
331
332 $data = parse_flat_keyed_file($data);
333 $res->{utime} = int($data->{user_usec} / 1000);
334 $res->{stime} = int($data->{system_usec} / 1000);
335 } elsif ($ver == 1) {
336 # cgroupv1 environment:
337 my $clock_ticks = POSIX::sysconf(&POSIX::_SC_CLK_TCK);
338 my $clk_to_usec = 1000 / $clock_ticks;
339
340 my $data = parse_flat_keyed_file(file_get_contents("$path/cpuacct.stat"));
341 $res->{utime} = int($data->{user} * $clk_to_usec);
342 $res->{stime} = int($data->{system} * $clk_to_usec);
343 } else {
344 die "bad cgroup version: $ver\n";
345 }
346
347 return $res;
348 }
349
350 # Parse some memory data from `memory.stat`
351 sub get_memory_stat {
352 my ($self) = @_;
353
354 my $res = {
355 mem => 0,
356 swap => 0,
357 };
358
359 my ($path, $ver) = $self->get_path('memory');
360 if (!defined($path)) {
361 # container most likely isn't running
362 return undef;
363 } elsif ($ver == 2) {
364 my $mem = file_get_contents("$path/memory.current");
365 my $swap = file_get_contents("$path/memory.swap.current");
366
367 chomp ($mem, $swap);
368
369 # FIXME: For the cgv1 equivalent of `total_cache` we may need to sum up
370 # the values in `memory.stat`...
371
372 $res->{mem} = $mem;
373 $res->{swap} = $swap;
374 } elsif ($ver == 1) {
375 # cgroupv1 environment:
376 my $stat = parse_flat_keyed_file(file_get_contents("$path/memory.stat"));
377 my $mem = file_get_contents("$path/memory.usage_in_bytes");
378 my $memsw = file_get_contents("$path/memory.memsw.usage_in_bytes");
379 chomp ($mem, $memsw);
380
381 $res->{mem} = $mem - $stat->{total_cache};
382 $res->{swap} = $memsw - $mem;
383 } else {
384 die "bad cgroup version: $ver\n";
385 }
386
387 return $res;
388 }
389
390 # Change the memory limit for this container.
391 #
392 # Dies on error (including a not-running or currently-shutting-down guest).
393 sub change_memory_limit {
394 my ($self, $mem_bytes, $swap_bytes) = @_;
395
396 my ($path, $ver) = $self->get_path('memory');
397 if (!defined($path)) {
398 die "trying to change memory cgroup values: container not running\n";
399 } elsif ($ver == 2) {
400 PVE::ProcFSTools::write_proc_entry("$path/memory.swap.max", $swap_bytes)
401 if defined($swap_bytes);
402 PVE::ProcFSTools::write_proc_entry("$path/memory.max", $mem_bytes)
403 if defined($mem_bytes);
404 } elsif ($ver == 1) {
405 # With cgroupv1 we cannot control memory and swap limits separately.
406 # This also means that since the two values aren't independent, we need to handle
407 # growing and shrinking separately.
408 my $path_mem = "$path/memory.limit_in_bytes";
409 my $path_memsw = "$path/memory.memsw.limit_in_bytes";
410
411 my $old_mem_bytes = file_get_contents($path_mem);
412 my $old_memsw_bytes = file_get_contents($path_memsw);
413 chomp($old_mem_bytes, $old_memsw_bytes);
414
415 $mem_bytes //= $old_mem_bytes;
416 my $memsw_bytes = defined($swap_bytes) ? ($mem_bytes + $swap_bytes) : $old_memsw_bytes;
417
418 if ($memsw_bytes > $old_memsw_bytes) {
419 # Growing the limit means growing the combined limit first, then pulling the
420 # memory limitup.
421 PVE::ProcFSTools::write_proc_entry($path_memsw, $memsw_bytes);
422 PVE::ProcFSTools::write_proc_entry($path_mem, $mem_bytes);
423 } else {
424 # Shrinking means we first need to shrink the mem-only memsw cannot be
425 # shrunk below it.
426 PVE::ProcFSTools::write_proc_entry($path_mem, $mem_bytes);
427 PVE::ProcFSTools::write_proc_entry($path_memsw, $memsw_bytes);
428 }
429 } else {
430 die "bad cgroup version: $ver\n";
431 }
432
433 # return a truth value
434 return 1;
435 }
436
437 # Change the cpu quota for a container.
438 #
439 # Dies on error (including a not-running or currently-shutting-down guest).
440 sub change_cpu_quota {
441 my ($self, $quota, $period) = @_;
442
443 die "quota without period not allowed\n" if !defined($period) && defined($quota);
444
445 my ($path, $ver) = $self->get_path('memory');
446 if (!defined($path)) {
447 die "trying to change cpu quota cgroup values: container not running\n";
448 } elsif ($ver == 2) {
449 # cgroupv2 environment, an undefined (unlimited) quota is defined as "max"
450 # in this interface:
451 $quota //= 'max'; # unlimited
452 if (defined($quota)) {
453 PVE::ProcFSTools::write_proc_entry("$path/cpu.max", "$quota $period");
454 } else {
455 # we're allowed to only write the quota:
456 PVE::ProcFSTools::write_proc_entry("$path/cpu.max", 'max');
457 }
458 } elsif ($ver == 1) {
459 $quota //= -1; # unlimited
460 $period //= -1;
461 PVE::ProcFSTools::write_proc_entry("$path/cpu.cfs_period_us", $period);
462 PVE::ProcFSTools::write_proc_entry("$path/cpu.cfs_quota_us", $quota);
463 } else {
464 die "bad cgroup version: $ver\n";
465 }
466
467 # return a truth value
468 return 1;
469 }
470
471 # Change the cpu "shares" for a container.
472 #
473 # In cgroupv1 we used a value in `[0..500000]` with a default of 1024.
474 #
475 # In cgroupv2 we do not have "shares", we have "weights" in the range
476 # of `[1..10000]` with a default of 100.
477 #
478 # Since the default values don't match when scaling linearly, we use the
479 # values we get as-is and simply error for values >10000 in cgroupv2.
480 #
481 # It is left to the user to figure this out for now.
482 #
483 # Dies on error (including a not-running or currently-shutting-down guest).
484 sub change_cpu_shares {
485 my ($self, $shares, $cgroupv1_default) = @_;
486
487 my ($path, $ver) = $self->get_path('memory');
488 if (!defined($path)) {
489 die "trying to change cpu shares/weight cgroup values: container not running\n";
490 } elsif ($ver == 2) {
491 # the cgroupv2 documentation defines the default to 100
492 $shares //= 100;
493 die "cpu weight (shares) must be in range [1, 10000]\n" if $shares < 1 || $shares > 10000;
494 PVE::ProcFSTools::write_proc_entry("$path/cpu.weight", $shares);
495 } elsif (defined(my $path = $self->get_path('cpu'))) {
496 $shares //= 100;
497 PVE::ProcFSTools::write_proc_entry("$path/cpu.shares", $shares // $cgroupv1_default);
498 } else {
499 die "bad cgroup version: $ver\n";
500 }
501
502 # return a truth value
503 return 1;
504 }
505
506 1;