okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6b63729a9
main
1"""The RAM this process gets on Linux, read the way the engine reads it. 2 3Inside a container /proc/meminfo shows the host's memory; the container's cgroup limit is the RAM there is. The limit is 4the smallest of cgroup v2 memory.max and memory.high from the process's group up to the mount root (cut at the deepest 5level that is visible: a container without its own cgroup namespace sees its host path, but only its own subtree), or of 6cgroup v1 memory.limit_in_bytes when there are no v2 memory files. 7 8Under a limit below MemTotal the available figure is the limit less the group's usage, with clean file cache on the 9active and inactive lists counted as free again (memory.stat: active_file + inactive_file, bounded by the usage, less 10dirty and writeback pages; shmem and locked pages are on other lists), as the engine's memory guard counts it. Without 11a limit, or with a limit at or above MemTotal, both figures are /proc/meminfo's, as before. 12""" 13from __future__import annotations 14 15import os 16 17SELF_CGROUP = "/proc/self/cgroup" 18CGROUP_ROOT = "/sys/fs/cgroup" 19MEMINFO = "/proc/meminfo" 20 21 22def _levels (root :str ,group :str )-> list [str ]: 23"""The cgroup directories from the mount `root` down to `group` ("/a/b"), cut at the first one that is not there.""" 24levels = [root ] 25at = root 26for part in [p for p in group .split ("/" )if p ]: 27if part in ("." ,".." ): 28return [] 29at = os .path .join (at ,part ) 30if not os .path .isdir (at ): 31break 32levels .append (at ) 33return levels if os .path .isdir (root )else [] 34 35 36def _number (path :str ,v1 :bool = False )-> int | None : 37"""A cgroup number file: its value, or None for "max", an absent or unreadable file, or v1's "unlimited".""" 38try : 39with open (path )as stream : 40text = stream .read ().strip () 41except OSError : 42return None 43if not text .isdigit (): 44return None 45value = int (text ) 46if v1 and value >= 1 << 62 : 47return None 48return value 49 50 51def limited_levels (self_cgroup :str = SELF_CGROUP ,root :str = CGROUP_ROOT )-> list [tuple [int ,str ,bool ]]: 52"""(limit in bytes, the level's directory, is cgroup v1) for every level of this process's cgroup that sets one.""" 53try : 54with open (self_cgroup )as stream : 55lines = stream .read ().splitlines () 56except OSError : 57lines = ["0::/" ] 58v2_group = v1_group = None 59for line in lines : 60parts = line .split (":" ,2 ) 61if len (parts )!= 3 : 62continue 63if parts [0 ]== "0" and parts [1 ]== "" : 64v2_group = parts [2 ] 65elif "memory" in parts [1 ].split ("," ): 66v1_group = parts [2 ] 67out :list [tuple [int ,str ,bool ]]= [] 68v2_files = False 69if v2_group is not None : 70for level in _levels (root ,v2_group ): 71if not os .path .exists (os .path .join (level ,"memory.current" )): 72continue 73v2_files = True 74values = [v for v in (_number (os .path .join (level ,n ))for n in ("memory.max" ,"memory.high" ))if v is not None ] 75if values : 76out .append ((min (values ),level ,False )) 77if not v2_files and v1_group is not None : 78for level in _levels (os .path .join (root ,"memory" ),v1_group ): 79value = _number (os .path .join (level ,"memory.limit_in_bytes" ),v1 = True ) 80if value is not None : 81out .append ((value ,level ,True )) 82return out 83 84 85def memory_limit (self_cgroup :str = SELF_CGROUP ,root :str = CGROUP_ROOT )-> int | None : 86"""The smallest memory limit (bytes) on this process's cgroup and its ancestors; None when no level sets one.""" 87limits = [limit for limit ,_ ,_ in limited_levels (self_cgroup ,root )] 88return min (limits )if limits else None 89 90 91def clean_file_cache (stat_text :str ,usage :int ,v1 :bool = False )-> int : 92"""Clean file cache on the active and inactive lists (bytes), bounded by the usage, from a memory.stat text. 930 when inactive_file is missing or unreadable; an active_file that cannot be read adds nothing.""" 94prefix = "total_" if v1 else "" 95keys = {"inactive" :prefix + "inactive_file" ,"active" :prefix + "active_file" , 96"dirty" :"total_dirty" if v1 else "file_dirty" ,"writeback" :"total_writeback" if v1 else "file_writeback" } 97seen :dict [str ,int ]= {} 98active_bad = False 99for line in stat_text .splitlines (): 100fields = line .split () 101if len (fields )!= 2 : 102continue 103key ,value = fields 104name = next ((k for k ,v in keys .items ()if v == key ),None ) 105if name is None : 106continue 107ok = value .isdigit () 108if name == "inactive" : 109if not ok or "inactive" in seen : 110return 0 111elif name == "active" : 112if not ok or "active" in seen : 113active_bad = True 114continue 115elif not ok : 116return 0 117seen [name ]= int (value ) 118if "inactive" not in seen : 119return 0 120cached = seen ["inactive" ]+ (seen ["active" ]if "active" in seen and not active_bad else 0 ) 121credit = min (cached ,usage ) 122for name in ("dirty" ,"writeback" ): 123credit = max (credit - seen .get (name ,0 ),0 ) 124return credit 125 126 127def _level_room (limit :int ,level :str ,v1 :bool )-> int : 128usage = _number (os .path .join (level ,"memory.usage_in_bytes" if v1 else "memory.current" )) 129if usage is None : 130return limit 131try : 132with open (os .path .join (level ,"memory.stat" ))as stream : 133stat_text = stream .read () 134except OSError : 135stat_text = "" 136used = usage - clean_file_cache (stat_text ,usage ,v1 ) 137return limit - used if used < limit else 0 138 139 140def ram_bytes (meminfo :str = MEMINFO ,self_cgroup :str = SELF_CGROUP ,root :str = CGROUP_ROOT )-> tuple [int | None ,int | None ]: 141"""(total, available) bytes of RAM for this process on Linux; None for a figure /proc/meminfo does not give (and 142both None where there is no /proc/meminfo).""" 143info :dict [str ,int ]= {} 144try : 145with open (meminfo ,encoding = "ascii" )as stream : 146for line in stream : 147key ,_ ,rest = line .partition (":" ) 148if key in ("MemTotal" ,"MemAvailable" ): 149info [key ]= int (rest .split ()[0 ])* 1024 150except (OSError ,ValueError ,IndexError ): 151return None ,None 152total ,available = info .get ("MemTotal" ),info .get ("MemAvailable" ) 153if total is None : 154return None ,available 155mem_total = total 156for limit ,level ,v1 in limited_levels (self_cgroup ,root ): 157if limit >= mem_total :# not a container's limit: /proc/meminfo's figures stand 158continue 159total = min (total ,limit ) 160if available is not None : 161available = min (available ,_level_room (limit ,level ,v1 )) 162return total ,available