|
| 1 | +"""Operating-system and scheduler limits for host resources.""" |
| 2 | + |
| 3 | +import os |
| 4 | +import re |
| 5 | +from functools import partial |
| 6 | +from pathlib import Path |
| 7 | + |
| 8 | +from psutil import virtual_memory |
| 9 | + |
| 10 | +from devito.logger import is_log_enabled_for, perf |
| 11 | +from devito.tools import humanbytes |
| 12 | + |
| 13 | +__all__ = ['cgroup_memory_limit', 'host_memory_available'] |
| 14 | + |
| 15 | + |
| 16 | +def is_memory_mount(entry, groups): |
| 17 | + """Select valid mounts that expose the process's memory controller""" |
| 18 | + location, filesystem = entry |
| 19 | + # Check if the fields are valid |
| 20 | + if len(location) >= 5 and len(filesystem) >= 3: |
| 21 | + fstype, _, options = filesystem[:3] |
| 22 | + return fstype in groups and ( |
| 23 | + fstype == 'cgroup2' or 'memory' in options.split(',') |
| 24 | + ) |
| 25 | + return False |
| 26 | + |
| 27 | + |
| 28 | +def cgroup_memory_query(): |
| 29 | + """Estimate a host memory budget and usage in bytes for every known cgroup |
| 30 | +
|
| 31 | + Never change the `_proc_self` kwarg, it is only required for testing |
| 32 | + """ |
| 33 | + # Read physical capacity and process cgroup metadata |
| 34 | + try: |
| 35 | + memberships = Path('/proc/self/cgroup').read_text().splitlines() |
| 36 | + mounts = Path('/proc/self/mountinfo').read_text().splitlines() |
| 37 | + except OSError: |
| 38 | + memberships = mounts = [] |
| 39 | + |
| 40 | + # Identify membership in unified or v1 memory hierarchies |
| 41 | + groups = {} |
| 42 | + memberships = [line.split(':', 2) for line in memberships] |
| 43 | + for hierarchy, controllers, path in (i for i in memberships if len(i) == 3): |
| 44 | + if hierarchy == '0' and not controllers: |
| 45 | + groups['cgroup2'] = Path(path) |
| 46 | + elif 'memory' in controllers.split(','): |
| 47 | + groups['cgroup'] = Path(path) |
| 48 | + |
| 49 | + # Select the memory mounts |
| 50 | + mounts = filter( |
| 51 | + partial(is_memory_mount, groups=groups), [ |
| 52 | + (location.split(), filesystem.split()) |
| 53 | + for location, _, filesystem in (line.partition(' - ') for line in mounts) |
| 54 | + ] |
| 55 | + ) |
| 56 | + |
| 57 | + # Resolve escaped mount paths and enumerate visible cgroup ancestors |
| 58 | + limit_files = [] |
| 59 | + for location, filesystem in mounts: |
| 60 | + group = groups[filesystem[0]] |
| 61 | + root, mount = [ |
| 62 | + Path(re.sub(r'\\([0-7]{3})', lambda m: chr(int(m[1], 8)), i)) |
| 63 | + for i in location[3:5] |
| 64 | + ] |
| 65 | + valid_group = group.is_absolute() and '..' not in group.parts |
| 66 | + if valid_group and (group == Path('/') or group.is_relative_to(root)): |
| 67 | + if group == Path('/'): # noqa: SIM108 |
| 68 | + relative = Path('.') |
| 69 | + else: |
| 70 | + relative = group.relative_to(root) |
| 71 | + # NOTE: |
| 72 | + # Maximum memory allowed resides in memory.max or memory.limit_in_bytes |
| 73 | + # Current memory usage resides in memory.current or memory.usage_in_bytes |
| 74 | + if filesystem[0] == 'cgroup2': |
| 75 | + filename = ('memory.max', 'memory.current') |
| 76 | + else: |
| 77 | + filename = ('memory.limit_in_bytes', 'memory.usage_in_bytes') |
| 78 | + limit_files.extend( |
| 79 | + (mount / parent / filename[0], mount / parent / filename[1]) |
| 80 | + for parent in (relative, *relative.parents) |
| 81 | + ) |
| 82 | + |
| 83 | + # Read capacity limits and usage falling back to those reported psutil |
| 84 | + state = virtual_memory() |
| 85 | + result = [(state.total, state.used)] |
| 86 | + for path in limit_files: |
| 87 | + try: |
| 88 | + limit = path[0].read_text().strip() |
| 89 | + except OSError: |
| 90 | + limit = '' |
| 91 | + try: |
| 92 | + used = path[1].read_text().strip() |
| 93 | + except OSError: |
| 94 | + used = 0 |
| 95 | + if limit.isdecimal(): |
| 96 | + result.append((int(limit), int(used))) |
| 97 | + |
| 98 | + return result |
| 99 | + |
| 100 | + |
| 101 | +def cgroup_memory_limit(): |
| 102 | + """Return the lowest known cgroup memory ceiling in bytes""" |
| 103 | + return min(cgroup_memory_query())[0] |
| 104 | + |
| 105 | + |
| 106 | +def cgroup_memory_headroom(): |
| 107 | + """Return the smallest available cgroup memory headroom in bytes""" |
| 108 | + return min(limit - used for limit, used in cgroup_memory_query()) |
| 109 | + |
| 110 | + |
| 111 | +def slurm_integer(value): |
| 112 | + """Read a nonnegative Slurm memory size or resource count. |
| 113 | +
|
| 114 | + Zero represents an unset, invalid, or negative field. Callers treat zero |
| 115 | + as an unspecified budget or count. |
| 116 | + """ |
| 117 | + try: |
| 118 | + return max(0, int(value or '0')) |
| 119 | + except ValueError: |
| 120 | + return 0 |
| 121 | + |
| 122 | + |
| 123 | +def slurm_memory_bytes(memory, count='1', fallback_count=None): |
| 124 | + """Convert the selected Slurm memory request and local count to bytes.""" |
| 125 | + units = slurm_integer(count) or slurm_integer(fallback_count) |
| 126 | + budget = slurm_integer(memory) * units |
| 127 | + return budget * 2**20 if budget else None |
| 128 | + |
| 129 | + |
| 130 | +def slurm_memory_limit(): |
| 131 | + env = os.environ |
| 132 | + if not (env.get('SLURM_JOB_ID') or env.get('SLURM_JOBID')): |
| 133 | + return None |
| 134 | + |
| 135 | + if 'SLURM_MEM_PER_NODE' in env: |
| 136 | + return slurm_memory_bytes(env['SLURM_MEM_PER_NODE']) |
| 137 | + if 'SLURM_MEM_PER_CPU' in env: |
| 138 | + return slurm_memory_bytes( |
| 139 | + env['SLURM_MEM_PER_CPU'], env.get('SLURM_CPUS_ON_NODE') |
| 140 | + ) |
| 141 | + |
| 142 | + return slurm_memory_bytes( |
| 143 | + env.get('SLURM_MEM_PER_GPU'), env.get('SLURM_GPUS_ON_NODE'), |
| 144 | + env.get('SLURM_GPUS_PER_NODE') |
| 145 | + ) |
| 146 | + |
| 147 | + |
| 148 | +def host_memory_budget(node_available, cgroup, slurm): |
| 149 | + limits = ((cgroup, 'cgroup'), (slurm, 'slurm')) |
| 150 | + limits = tuple((limit, reason) for limit, reason in limits if limit is not None) |
| 151 | + available, reason = min( |
| 152 | + (*limits, (node_available, 'node')), key=lambda entry: entry[0] |
| 153 | + ) |
| 154 | + if limits and is_log_enabled_for('PERF'): |
| 155 | + perf(f'Host memory budget {humanbytes(available)} [{reason}]') |
| 156 | + |
| 157 | + return available |
| 158 | + |
| 159 | + |
| 160 | +def host_memory_available(): |
| 161 | + """ |
| 162 | + Return available host memory in bytes. |
| 163 | +
|
| 164 | + Cgroup headroom accounts for usage in the process's group and its |
| 165 | + visible ancestors. Slurm's `task/cgroup` plugin applies the job's RAM |
| 166 | + limit through cgroups when `ConstrainRAMSpace` is enabled. |
| 167 | +
|
| 168 | + Slurm can also enforce an allocation through job accounting |
| 169 | + (`OverMemoryKill`). A visible cgroup cap can come from a container or |
| 170 | + systemd scope, so also apply any local allocation reported in the |
| 171 | + Slurm environment. |
| 172 | + """ |
| 173 | + return host_memory_budget( |
| 174 | + virtual_memory().available, cgroup_memory_headroom(), slurm_memory_limit() |
| 175 | + ) |
0 commit comments