Returns (limit, available) in bytes for the cgroups that limit this process, or None. The limit is the smallest one from the process's cgroup up to the root. Available memory is the smallest headroom over every limited level, because a parent's limit also counts the usage of its other child
()
| 129 | |
| 130 | |
| 131 | def _cgroup_memory(): |
| 132 | """Returns (limit, available) in bytes for the cgroups that limit this process, or None. |
| 133 | |
| 134 | The limit is the smallest one from the process's cgroup up to the root. Available memory is the smallest headroom |
| 135 | over every limited level, because a parent's limit also counts the usage of its other children. Usage excludes the |
| 136 | inactive page cache, which the kernel can reclaim. Available is None when no limited level exposes its usage. |
| 137 | """ |
| 138 | override = os.environ.get("DS_CPU_RESPECT_CGROUP_MEMORY") |
| 139 | enabled = RESPECT_CGROUP_MEMORY_BY_DEFAULT if override is None else override.strip().lower() in ("1", "true") |
| 140 | if not enabled or not sys.platform.startswith("linux"): |
| 141 | return None |
| 142 | for controller, limit_file, usage_file, inactive_key in ( |
| 143 | (None, "memory.max", "memory.current", "inactive_file"), |
| 144 | ("memory", "memory.limit_in_bytes", "memory.usage_in_bytes", "total_inactive_file"), |
| 145 | ): |
| 146 | limit = None |
| 147 | available = None |
| 148 | for cgroup_dir in _cgroup_dirs(controller): |
| 149 | level_limit = _read_cgroup_int(os.path.join(cgroup_dir, limit_file)) |
| 150 | if level_limit is None or level_limit >= _CGROUP_UNLIMITED: |
| 151 | continue |
| 152 | limit = level_limit if limit is None else min(limit, level_limit) |
| 153 | usage = _read_cgroup_int(os.path.join(cgroup_dir, usage_file)) |
| 154 | if usage is None: |
| 155 | continue |
| 156 | inactive_file = _read_memory_stat(os.path.join(cgroup_dir, "memory.stat"), inactive_key) |
| 157 | headroom = max(0, level_limit - max(0, usage - inactive_file)) |
| 158 | available = headroom if available is None else min(available, headroom) |
| 159 | if limit is not None: |
| 160 | return limit, available |
| 161 | return None |
| 162 | |
| 163 | |
| 164 | # accelerator for Intel CPU |
no test coverage detected