1 /*
  2  * Copyright (c) 2019, 2025, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #include <string.h>
 26 #include <math.h>
 27 #include <errno.h>
 28 #include "cgroupV1Subsystem_linux.hpp"
 29 #include "cgroupUtil_linux.hpp"
 30 #include "logging/log.hpp"
 31 #include "memory/allocation.hpp"
 32 #include "runtime/globals.hpp"
 33 #include "runtime/os.hpp"
 34 #include "utilities/globalDefinitions.hpp"
 35 #include "os_linux.hpp"
 36 
 37 /*
 38  * Set directory to subsystem specific files based
 39  * on the contents of the mountinfo and cgroup files.
 40  *
 41  * The method determines whether it runs in
 42  * - host mode
 43  * - container mode
 44  *
 45  * In the host mode, _root is equal to "/" and
 46  * the subsystem path is equal to the _mount_point path
 47  * joined with cgroup_path.
 48  *
 49  * In the container mode, it can be two possibilities:
 50  * - private namespace (cgroupns=private)
 51  * - host namespace (cgroupns=host, default mode in cgroup V1 hosts)
 52  *
 53  * Private namespace is equivalent to the host mode, i.e.
 54  * the subsystem path is set by concatenating
 55  * _mount_point and cgroup_path.
 56  *
 57  * In the host namespace, _root is equal to host's cgroup path
 58  * of the control group to which the containerized process
 59  * belongs to at the moment of creation. The mountinfo and
 60  * cgroup files are mirrored from the host, while the subsystem
 61  * specific files are mapped directly at _mount_point, i.e.
 62  * at /sys/fs/cgroup/<controller>/, the subsystem path is
 63  * then set equal to _mount_point.
 64  *
 65  * A special case of the subsystem path is when a cgroup path
 66  * includes a subgroup, when a containerized process was associated
 67  * with an existing cgroup, that is different from cgroup
 68  * in which the process has been created.
 69  * Here, the _root is equal to the host's initial cgroup path,
 70  * cgroup_path will be equal to host's new cgroup path.
 71  * As host cgroup hierarchies are not accessible in the container,
 72  * it needs to be determined which part of cgroup path
 73  * is accessible inside container, i.e. mapped under
 74  * /sys/fs/cgroup/<controller>/<subgroup>.
 75  * In Docker default setup, host's cgroup path can be
 76  * of the form: /docker/<CONTAINER_ID>/<subgroup>,
 77  * from which only <subgroup> is mapped.
 78  * The method trims cgroup path from left, until the subgroup
 79  * component is found. The subsystem path will be set to
 80  * the _mount_point joined with the subgroup path.
 81  */
 82 void CgroupV1Controller::set_subsystem_path(const char* cgroup_path) {
 83   if (_cgroup_path != nullptr) {
 84     os::free(_cgroup_path);
 85   }
 86   if (_path != nullptr) {
 87     os::free(_path);
 88     _path = nullptr;
 89   }
 90   _cgroup_path = os::strdup(cgroup_path);
 91   stringStream ss;
 92   if (_root != nullptr && cgroup_path != nullptr) {
 93     ss.print_raw(_mount_point);
 94     if (strcmp(_root, "/") == 0) {
 95       // host processes and containers with cgroupns=private
 96       if (strcmp(cgroup_path,"/") != 0) {
 97         ss.print_raw(cgroup_path);
 98       }
 99     } else {
100       // containers with cgroupns=host, default setting is _root==cgroup_path
101       if (strcmp(_root, cgroup_path) != 0) {
102         if (*cgroup_path != '\0' && strcmp(cgroup_path, "/") != 0) {
103           // When moved to a subgroup, between subgroups, the path suffix will change.
104           const char *suffix = cgroup_path;
105           while (suffix != nullptr) {
106             stringStream pp;
107             pp.print_raw(_mount_point);
108             pp.print_raw(suffix);
109             if (os::file_exists(pp.base())) {
110               ss.print_raw(suffix);
111               if (suffix != cgroup_path) {
112                 log_trace(os, container)("set_subsystem_path: cgroup v1 path reduced to: %s.", suffix);
113               }
114               break;
115             }
116             log_trace(os, container)("set_subsystem_path: skipped non-existent directory: %s.", suffix);
117             suffix = strchr(suffix + 1, '/');
118           }
119         }
120       }
121     }
122     _path = os::strdup(ss.base());
123   }
124 }
125 
126 jlong CgroupV1MemoryController::uses_mem_hierarchy() {
127   julong use_hierarchy;
128   CONTAINER_READ_NUMBER_CHECKED(reader(), "/memory.use_hierarchy", "Use Hierarchy", use_hierarchy);
129   return (jlong)use_hierarchy;
130 }
131 
132 /*
133  * The common case, containers, we have _root == _cgroup_path, and thus set the
134  * controller path to the _mount_point. This is where the limits are exposed in
135  * the cgroup pseudo filesystem (at the leaf) and adjustment of the path won't
136  * be needed for that reason.
137  */
138 bool CgroupV1Controller::needs_hierarchy_adjustment() {
139   assert(_cgroup_path != nullptr, "sanity");
140   return strcmp(_root, _cgroup_path) != 0;
141 }
142 
143 static inline
144 void verbose_log(julong read_mem_limit, julong host_mem) {
145   if (log_is_enabled(Debug, os, container)) {
146     jlong mem_limit = (jlong)read_mem_limit; // account for negative values
147     if (mem_limit < 0 || read_mem_limit >= host_mem) {
148       const char *reason;
149       if (mem_limit == OSCONTAINER_ERROR) {
150         reason = "failed";
151       } else if (mem_limit == -1) {
152         reason = "unlimited";
153       } else {
154         assert(read_mem_limit >= host_mem, "Expected read value exceeding host_mem");
155         // Exceeding physical memory is treated as unlimited. This implementation
156         // caps it at host_mem since Cg v1 has no value to represent 'max'.
157         reason = "ignored";
158       }
159       log_debug(os, container)("container memory limit %s: " JLONG_FORMAT ", using host value " JLONG_FORMAT,
160                                reason, mem_limit, host_mem);
161     }
162   }
163 }
164 
165 jlong CgroupV1MemoryController::read_memory_limit_in_bytes(julong phys_mem) {
166   julong memlimit;
167   CONTAINER_READ_NUMBER_CHECKED(reader(), "/memory.limit_in_bytes", "Memory Limit", memlimit);
168   if (memlimit >= phys_mem && uses_mem_hierarchy()) {
169     CONTAINER_READ_NUMERICAL_KEY_VALUE_CHECKED(reader(), "/memory.stat",
170                                                "hierarchical_memory_limit", "Hierarchical Memory Limit",
171                                                memlimit);
172   }
173   verbose_log(memlimit, phys_mem);
174   return (jlong)((memlimit < phys_mem) ? memlimit : -1);
175 }
176 
177 /* read_mem_swap
178  *
179  * Determine the memory and swap limit metric. Returns a positive limit value strictly
180  * lower than the physical memory and swap limit iff there is a limit. Otherwise a
181  * negative value is returned indicating the determined status.
182  *
183  * returns:
184  *    * A number > 0 if the limit is available and lower than a physical upper bound.
185  *    * OSCONTAINER_ERROR if the limit cannot be retrieved (i.e. not supported) or
186  *    * -1 if there isn't any limit in place (note: includes values which exceed a physical
187  *      upper bound)
188  */
189 jlong CgroupV1MemoryController::read_mem_swap(julong host_total_memsw) {
190   julong memswlimit;
191   CONTAINER_READ_NUMBER_CHECKED(reader(), "/memory.memsw.limit_in_bytes", "Memory and Swap Limit", memswlimit);
192   if (memswlimit >= host_total_memsw && uses_mem_hierarchy()) {
193       CONTAINER_READ_NUMERICAL_KEY_VALUE_CHECKED(reader(), "/memory.stat",
194                                                  "hierarchical_memsw_limit", "Hierarchical Memory and Swap Limit",
195                                                  memswlimit);
196   }
197   verbose_log(memswlimit, host_total_memsw);
198   return (jlong)((memswlimit < host_total_memsw) ? memswlimit : -1);
199 }
200 
201 jlong CgroupV1MemoryController::memory_and_swap_limit_in_bytes(julong host_mem, julong host_swap) {
202   jlong memory_swap = read_mem_swap(host_mem + host_swap);
203   if (memory_swap == -1) {
204     return memory_swap;
205   }
206   // If there is a swap limit, but swappiness == 0, reset the limit
207   // to the memory limit. Do the same for cases where swap isn't
208   // supported.
209   jlong swappiness = read_mem_swappiness();
210   if (swappiness == 0 || memory_swap == OSCONTAINER_ERROR) {
211     jlong memlimit = read_memory_limit_in_bytes(host_mem);
212     if (memory_swap == OSCONTAINER_ERROR) {
213       log_trace(os, container)("Memory and Swap Limit has been reset to " JLONG_FORMAT " because swap is not supported", memlimit);
214     } else {
215       log_trace(os, container)("Memory and Swap Limit has been reset to " JLONG_FORMAT " because swappiness is 0", memlimit);
216     }
217     return memlimit;
218   }
219   return memory_swap;
220 }
221 
222 static inline
223 jlong memory_swap_usage_impl(CgroupController* ctrl) {
224   julong memory_swap_usage;
225   CONTAINER_READ_NUMBER_CHECKED(ctrl, "/memory.memsw.usage_in_bytes", "mem swap usage", memory_swap_usage);
226   return (jlong)memory_swap_usage;
227 }
228 
229 jlong CgroupV1MemoryController::memory_and_swap_usage_in_bytes(julong phys_mem, julong host_swap) {
230   jlong memory_sw_limit = memory_and_swap_limit_in_bytes(phys_mem, host_swap);
231   jlong memory_limit = read_memory_limit_in_bytes(phys_mem);
232   if (memory_sw_limit > 0 && memory_limit > 0) {
233     jlong delta_swap = memory_sw_limit - memory_limit;
234     if (delta_swap > 0) {
235       return memory_swap_usage_impl(reader());
236     }
237   }
238   return memory_usage_in_bytes();
239 }
240 
241 jlong CgroupV1MemoryController::read_mem_swappiness() {
242   julong swappiness;
243   CONTAINER_READ_NUMBER_CHECKED(reader(), "/memory.swappiness", "Swappiness", swappiness);
244   return (jlong)swappiness;
245 }
246 
247 jlong CgroupV1MemoryController::memory_soft_limit_in_bytes(julong phys_mem) {
248   julong memsoftlimit;
249   CONTAINER_READ_NUMBER_CHECKED(reader(), "/memory.soft_limit_in_bytes", "Memory Soft Limit", memsoftlimit);
250   if (memsoftlimit >= phys_mem) {
251     log_trace(os, container)("Memory Soft Limit is: Unlimited");
252     return (jlong)-1;
253   } else {
254     return (jlong)memsoftlimit;
255   }
256 }
257 
258 // Constructor
259 CgroupV1Subsystem::CgroupV1Subsystem(CgroupV1Controller* cpuset,
260                       CgroupV1CpuController* cpu,
261                       CgroupV1Controller* cpuacct,
262                       CgroupV1Controller* pids,
263                       CgroupV1MemoryController* memory) :
264     _cpuset(cpuset),
265     _cpuacct(cpuacct),
266     _pids(pids) {
267   CgroupUtil::adjust_controller(memory);
268   CgroupUtil::adjust_controller(cpu);
269   _memory = new CachingCgroupController<CgroupMemoryController>(memory);
270   _cpu = new CachingCgroupController<CgroupCpuController>(cpu);
271 }
272 
273 bool CgroupV1Subsystem::is_containerized() {
274   // containerized iff all required controllers are mounted
275   // read-only. See OSContainer::is_containerized() for
276   // the full logic.
277   //
278   return _memory->controller()->is_read_only() &&
279          _cpu->controller()->is_read_only() &&
280          _cpuacct->is_read_only() &&
281          _cpuset->is_read_only();
282 }
283 
284 /* memory_usage_in_bytes
285  *
286  * Return the amount of used memory for this process.
287  *
288  * return:
289  *    memory usage in bytes or
290  *    -1 for unlimited
291  *    OSCONTAINER_ERROR for not supported
292  */
293 jlong CgroupV1MemoryController::memory_usage_in_bytes() {
294   julong memusage;
295   CONTAINER_READ_NUMBER_CHECKED(reader(), "/memory.usage_in_bytes", "Memory Usage", memusage);
296   return (jlong)memusage;
297 }
298 
299 /* memory_max_usage_in_bytes
300  *
301  * Return the maximum amount of used memory for this process.
302  *
303  * return:
304  *    max memory usage in bytes or
305  *    OSCONTAINER_ERROR for not supported
306  */
307 jlong CgroupV1MemoryController::memory_max_usage_in_bytes() {
308   julong memmaxusage;
309   CONTAINER_READ_NUMBER_CHECKED(reader(), "/memory.max_usage_in_bytes", "Maximum Memory Usage", memmaxusage);
310   return (jlong)memmaxusage;
311 }
312 
313 jlong CgroupV1MemoryController::rss_usage_in_bytes() {
314   julong rss;
315   bool is_ok = reader()->read_numerical_key_value("/memory.stat", "rss", &rss);
316   if (!is_ok) {
317     return OSCONTAINER_ERROR;
318   }
319   log_trace(os, container)("RSS usage is: " JULONG_FORMAT, rss);
320   return (jlong)rss;
321 }
322 
323 jlong CgroupV1MemoryController::cache_usage_in_bytes() {
324   julong cache;
325   bool is_ok = reader()->read_numerical_key_value("/memory.stat", "cache", &cache);
326   if (!is_ok) {
327     return OSCONTAINER_ERROR;
328   }
329   log_trace(os, container)("Cache usage is: " JULONG_FORMAT, cache);
330   return cache;
331 }
332 
333 jlong CgroupV1MemoryController::kernel_memory_usage_in_bytes() {
334   julong kmem_usage;
335   CONTAINER_READ_NUMBER_CHECKED(reader(), "/memory.kmem.usage_in_bytes", "Kernel Memory Usage", kmem_usage);
336   return (jlong)kmem_usage;
337 }
338 
339 jlong CgroupV1MemoryController::kernel_memory_limit_in_bytes(julong phys_mem) {
340   julong kmem_limit;
341   CONTAINER_READ_NUMBER_CHECKED(reader(), "/memory.kmem.limit_in_bytes", "Kernel Memory Limit", kmem_limit);
342   if (kmem_limit >= phys_mem) {
343     return (jlong)-1;
344   }
345   return (jlong)kmem_limit;
346 }
347 
348 jlong CgroupV1MemoryController::kernel_memory_max_usage_in_bytes() {
349   julong kmem_max_usage;
350   CONTAINER_READ_NUMBER_CHECKED(reader(), "/memory.kmem.max_usage_in_bytes", "Maximum Kernel Memory Usage", kmem_max_usage);
351   return (jlong)kmem_max_usage;
352 }
353 
354 void CgroupV1MemoryController::print_version_specific_info(outputStream* st, julong phys_mem) {
355   jlong kmem_usage = kernel_memory_usage_in_bytes();
356   jlong kmem_limit = kernel_memory_limit_in_bytes(phys_mem);
357   jlong kmem_max_usage = kernel_memory_max_usage_in_bytes();
358 
359   OSContainer::print_container_helper(st, kmem_limit, "kernel_memory_limit_in_bytes");
360   OSContainer::print_container_helper(st, kmem_usage, "kernel_memory_usage_in_bytes");
361   OSContainer::print_container_helper(st, kmem_max_usage, "kernel_memory_max_usage_in_bytes");
362 }
363 
364 char* CgroupV1Subsystem::cpu_cpuset_cpus() {
365   char cpus[1024];
366   CONTAINER_READ_STRING_CHECKED(_cpuset, "/cpuset.cpus", "cpuset.cpus", cpus, 1024);
367   return os::strdup(cpus);
368 }
369 
370 char* CgroupV1Subsystem::cpu_cpuset_memory_nodes() {
371   char mems[1024];
372   CONTAINER_READ_STRING_CHECKED(_cpuset, "/cpuset.mems", "cpuset.mems", mems, 1024);
373   return os::strdup(mems);
374 }
375 
376 /* cpu_quota
377  *
378  * Return the number of microseconds per period
379  * process is guaranteed to run.
380  *
381  * return:
382  *    quota time in microseconds
383  *    -1 for no quota
384  *    OSCONTAINER_ERROR for not supported
385  */
386 int CgroupV1CpuController::cpu_quota() {
387   julong quota;
388   bool is_ok = reader()->read_number("/cpu.cfs_quota_us", &quota);
389   if (!is_ok) {
390     log_trace(os, container)("CPU Quota failed: %d", OSCONTAINER_ERROR);
391     return OSCONTAINER_ERROR;
392   }
393   // cast to int since the read value might be negative
394   // and we want to avoid logging -1 as a large unsigned value.
395   int quota_int = (int)quota;
396   log_trace(os, container)("CPU Quota is: %d", quota_int);
397   return quota_int;
398 }
399 
400 int CgroupV1CpuController::cpu_period() {
401   julong period;
402   CONTAINER_READ_NUMBER_CHECKED(reader(), "/cpu.cfs_period_us", "CPU Period", period);
403   return (int)period;
404 }
405 
406 /* cpu_shares
407  *
408  * Return the amount of cpu shares available to the process
409  *
410  * return:
411  *    Share number (typically a number relative to 1024)
412  *                 (2048 typically expresses 2 CPUs worth of processing)
413  *    -1 for no share setup
414  *    OSCONTAINER_ERROR for not supported
415  */
416 int CgroupV1CpuController::cpu_shares() {
417   julong shares;
418   CONTAINER_READ_NUMBER_CHECKED(reader(), "/cpu.shares", "CPU Shares", shares);
419   int shares_int = (int)shares;
420   // Convert 1024 to no shares setup
421   if (shares_int == 1024) return -1;
422 
423   return shares_int;
424 }
425 
426 /* pids_max
427  *
428  * Return the maximum number of tasks available to the process
429  *
430  * return:
431  *    maximum number of tasks
432  *    -1 for unlimited
433  *    OSCONTAINER_ERROR for not supported
434  */
435 jlong CgroupV1Subsystem::pids_max() {
436   if (_pids == nullptr) return OSCONTAINER_ERROR;
437   jlong pids_max;
438   CONTAINER_READ_NUMBER_CHECKED_MAX(_pids, "/pids.max", "Maximum number of tasks", pids_max);
439   return pids_max;
440 }
441 
442 /* pids_current
443  *
444  * The number of tasks currently in the cgroup (and its descendants) of the process
445  *
446  * return:
447  *    current number of tasks
448  *    OSCONTAINER_ERROR for not supported
449  */
450 jlong CgroupV1Subsystem::pids_current() {
451   if (_pids == nullptr) return OSCONTAINER_ERROR;
452   julong pids_current;
453   CONTAINER_READ_NUMBER_CHECKED(_pids, "/pids.current", "Current number of tasks", pids_current);
454   return (jlong)pids_current;
455 }