Skip to content

Commit

Permalink
[8.0.1] Fix parsing cpu.max file in cgroup v2 implementation (#24753)
Browse files Browse the repository at this point in the history
Fixes #24680

Closes #24714.

PiperOrigin-RevId: 707775390
Change-Id: I1a34c0917174aca3bbcfdec8668aef2d7e68ae6e

Commit
1c6aa50

Co-authored-by: Alessandro Patti <[email protected]>
  • Loading branch information
bazel-io and AlessandroPatti authored Dec 19, 2024
1 parent 9264ea1 commit d816b82
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public Path getPath() {
public void setCpus(double cpus) throws IOException {
long period;
try (Scanner scanner = new Scanner(Files.newBufferedReader(path.resolve("cpu.max")))) {
period = scanner.skip(".*\\s").nextInt();
period = scanner.skip("\\S+\\s").nextInt();
}
long quota = Math.round(period * cpus);
String limit = String.format("%d %d", quota, period);
Expand All @@ -52,6 +52,10 @@ public void setCpus(double cpus) throws IOException {
@Override
public long getCpus() throws IOException {
try (Scanner scanner = new Scanner(Files.newBufferedReader(path.resolve("cpu.max")))) {
if (!scanner.hasNextLong()) {
// Not a number, assume no limit and all processors available
return Runtime.getRuntime().availableProcessors();
}
long quota = scanner.nextLong();
long period = scanner.nextLong();
return quota / period;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,32 @@ public void setCpuLimit_v2() throws IOException {
assertThat(Files.asCharSource(limit, UTF_8).read()).isEqualTo("500000 100000");
}

@Test
public void setCpuLimitNewLine_v2() throws IOException {
File limit = scratch.file("cgroup/cpu/cpu.max", "-1 100000\n").getPathFile();
Cpu cpu = new UnifiedCpu(scratch.path("cgroup/cpu").getPathFile().toPath());
cpu.setCpus(5);
assertThat(Files.asCharSource(limit, UTF_8).read()).isEqualTo("500000 100000");
}

@Test
public void getCpuLimit_v2() throws IOException {
scratch.file("cgroup/cpu/cpu.max", "6000 1000");
Cpu memory = new UnifiedCpu(scratch.path("cgroup/cpu").getPathFile().toPath());
assertThat(memory.getCpus()).isEqualTo(6);
Cpu cpu = new UnifiedCpu(scratch.path("cgroup/cpu").getPathFile().toPath());
assertThat(cpu.getCpus()).isEqualTo(6);
}

@Test
public void getCpuLimitNewLine_v2() throws IOException {
scratch.file("cgroup/cpu/cpu.max", "6000 1000\n");
Cpu cpu = new UnifiedCpu(scratch.path("cgroup/cpu").getPathFile().toPath());
assertThat(cpu.getCpus()).isEqualTo(6);
}

@Test
public void getCpuLimitMax_v2() throws IOException {
scratch.file("cgroup/cpu/cpu.max", "max 1000\n");
Cpu cpu = new UnifiedCpu(scratch.path("cgroup/cpu").getPathFile().toPath());
assertThat(cpu.getCpus()).isEqualTo(Runtime.getRuntime().availableProcessors());
}
}

0 comments on commit d816b82

Please sign in to comment.