| 1 |
# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 |
# |
| 3 |
# This source code is licensed under the MIT license found in the |
| 4 |
# LICENSE file in the root directory of this source tree. |
| 5 |
|
| 6 |
import os |
| 7 |
|
| 8 |
import platform |
| 9 |
import re |
| 10 |
import shlex |
| 11 |
import sys |
| 12 |
from typing import Optional, Tuple |
| 13 |
|
| 14 |
|
| 15 |
def is_windows() -> bool: |
| 16 |
"""Returns true if the system we are currently running on |
| 17 |
is a Windows system""" |
| 18 |
return sys.platform.startswith("win") |
| 19 |
|
| 20 |
|
| 21 |
def get_linux_type() -> Tuple[Optional[str], Optional[str], Optional[str]]: |
| 22 |
try: |
| 23 |
with open("/etc/os-release") as f: |
| 24 |
data = f.read() |
| 25 |
except EnvironmentError: |
| 26 |
return (None, None, None) |
| 27 |
|
| 28 |
os_vars = {} |
| 29 |
for line in data.splitlines(): |
| 30 |
parts = line.split("=", 1) |
| 31 |
if len(parts) != 2: |
| 32 |
continue |
| 33 |
key = parts[0].strip() |
| 34 |
value_parts = shlex.split(parts[1].strip()) |
| 35 |
if not value_parts: |
| 36 |
value = "" |
| 37 |
else: |
| 38 |
value = value_parts[0] |
| 39 |
os_vars[key] = value |
| 40 |
|
| 41 |
name = os_vars.get("NAME") |
| 42 |
if name: |
| 43 |
name = name.lower() |
| 44 |
name = re.sub("linux", "", name) |
| 45 |
name = name.strip().replace(" ", "_") |
| 46 |
|
| 47 |
version_id = os_vars.get("VERSION_ID") |
| 48 |
if version_id: |
| 49 |
version_id = version_id.lower() |
| 50 |
|
| 51 |
return "linux", name, version_id |
| 52 |
|
| 53 |
|
| 54 |
# Ideally we'd use a common library like `psutil` to read system information, |
| 55 |
# but getdeps can't take third-party dependencies. |
| 56 |
|
| 57 |
|
| 58 |
def _get_available_ram_linux() -> int: |
| 59 |
# TODO: Ideally, this function would inspect the current cgroup for any |
| 60 |
# limits, rather than solely relying on system RAM. |
| 61 |
|
| 62 |
meminfo_path = "/proc/meminfo" |
| 63 |
try: |
| 64 |
with open(meminfo_path) as f: |
| 65 |
for line in f: |
| 66 |
try: |
| 67 |
key, value = line.split(":", 1) |
| 68 |
except ValueError: |
| 69 |
continue |
| 70 |
suffix = " kB\n" |
| 71 |
if key == "MemAvailable" and value.endswith(suffix): |
| 72 |
value = value[: -len(suffix)] |
| 73 |
try: |
| 74 |
return int(value) // 1024 |
| 75 |
except ValueError: |
| 76 |
continue |
| 77 |
except OSError: |
| 78 |
print("error opening {}".format(meminfo_path), end="", file=sys.stderr) |
| 79 |
else: |
| 80 |
print( |
| 81 |
"{} had no valid MemAvailable".format(meminfo_path), end="", file=sys.stderr |
| 82 |
) |
| 83 |
|
| 84 |
guess = 8 |
| 85 |
print(", guessing {} GiB".format(guess), file=sys.stderr) |
| 86 |
return guess * 1024 |
| 87 |
|
| 88 |
|
| 89 |
def _get_available_ram_macos() -> int: |
| 90 |
import ctypes.util |
| 91 |
|
| 92 |
libc = ctypes.CDLL(ctypes.util.find_library("libc"), use_errno=True) |
| 93 |
sysctlbyname = libc.sysctlbyname |
| 94 |
sysctlbyname.restype = ctypes.c_int |
| 95 |
sysctlbyname.argtypes = [ |
| 96 |
ctypes.c_char_p, |
| 97 |
ctypes.c_void_p, |
| 98 |
ctypes.POINTER(ctypes.c_size_t), |
| 99 |
ctypes.c_void_p, |
| 100 |
ctypes.c_size_t, |
| 101 |
] |
| 102 |
# TODO: There may be some way to approximate an availability |
| 103 |
# metric, but just use total RAM for now. |
| 104 |
memsize = ctypes.c_int64() |
| 105 |
memsizesize = ctypes.c_size_t(8) |
| 106 |
res = sysctlbyname( |
| 107 |
b"hw.memsize", ctypes.byref(memsize), ctypes.byref(memsizesize), None, 0 |
| 108 |
) |
| 109 |
if res != 0: |
| 110 |
raise NotImplementedError( |
| 111 |
f"failed to retrieve hw.memsize sysctl: {ctypes.get_errno()}" |
| 112 |
) |
| 113 |
return memsize.value // (1024 * 1024) |
| 114 |
|
| 115 |
|
| 116 |
def _get_available_ram_windows() -> int: |
| 117 |
import ctypes |
| 118 |
|
| 119 |
DWORD = ctypes.c_uint32 |
| 120 |
QWORD = ctypes.c_uint64 |
| 121 |
|
| 122 |
class MEMORYSTATUSEX(ctypes.Structure): |
| 123 |
_fields_ = [ |
| 124 |
("dwLength", DWORD), |
| 125 |
("dwMemoryLoad", DWORD), |
| 126 |
("ullTotalPhys", QWORD), |
| 127 |
("ullAvailPhys", QWORD), |
| 128 |
("ullTotalPageFile", QWORD), |
| 129 |
("ullAvailPageFile", QWORD), |
| 130 |
("ullTotalVirtual", QWORD), |
| 131 |
("ullAvailVirtual", QWORD), |
| 132 |
("ullExtendedVirtual", QWORD), |
| 133 |
] |
| 134 |
|
| 135 |
ms = MEMORYSTATUSEX() |
| 136 |
ms.dwLength = ctypes.sizeof(ms) |
| 137 |
# pyre-ignore[16] |
| 138 |
res = ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(ms)) |
| 139 |
if res == 0: |
| 140 |
raise NotImplementedError("error calling GlobalMemoryStatusEx") |
| 141 |
|
| 142 |
# This is fuzzy, but AvailPhys is too conservative, and AvailTotal is too |
| 143 |
# aggressive, so average the two. It's okay for builds to use some swap. |
| 144 |
return (ms.ullAvailPhys + ms.ullTotalPhys) // (2 * 1024 * 1024) |
| 145 |
|
| 146 |
|
| 147 |
def _get_available_ram_freebsd() -> int: |
| 148 |
import ctypes.util |
| 149 |
|
| 150 |
libc = ctypes.CDLL(ctypes.util.find_library("libc"), use_errno=True) |
| 151 |
sysctlbyname = libc.sysctlbyname |
| 152 |
sysctlbyname.restype = ctypes.c_int |
| 153 |
sysctlbyname.argtypes = [ |
| 154 |
ctypes.c_char_p, |
| 155 |
ctypes.c_void_p, |
| 156 |
ctypes.POINTER(ctypes.c_size_t), |
| 157 |
ctypes.c_void_p, |
| 158 |
ctypes.c_size_t, |
| 159 |
] |
| 160 |
# hw.usermem is pretty close to what we want. |
| 161 |
memsize = ctypes.c_int64() |
| 162 |
memsizesize = ctypes.c_size_t(8) |
| 163 |
res = sysctlbyname( |
| 164 |
b"hw.usermem", ctypes.byref(memsize), ctypes.byref(memsizesize), None, 0 |
| 165 |
) |
| 166 |
if res != 0: |
| 167 |
raise NotImplementedError( |
| 168 |
f"failed to retrieve hw.memsize sysctl: {ctypes.get_errno()}" |
| 169 |
) |
| 170 |
return memsize.value // (1024 * 1024) |
| 171 |
|
| 172 |
|
| 173 |
def get_available_ram() -> int: |
| 174 |
""" |
| 175 |
Returns a platform-appropriate available RAM metric in MiB. |
| 176 |
""" |
| 177 |
if sys.platform == "linux": |
| 178 |
return _get_available_ram_linux() |
| 179 |
elif sys.platform == "darwin": |
| 180 |
return _get_available_ram_macos() |
| 181 |
elif sys.platform == "win32": |
| 182 |
return _get_available_ram_windows() |
| 183 |
elif sys.platform.startswith("freebsd"): |
| 184 |
return _get_available_ram_freebsd() |
| 185 |
else: |
| 186 |
raise NotImplementedError( |
| 187 |
f"platform {sys.platform} does not have an implementation of get_available_ram" |
| 188 |
) |
| 189 |
|
| 190 |
|
| 191 |
def is_current_host_arm() -> bool: |
| 192 |
if sys.platform.startswith("darwin"): |
| 193 |
# platform.machine() can be fooled by rosetta for python < 3.9.2 |
| 194 |
return "ARM64" in os.uname().version |
| 195 |
else: |
| 196 |
machine = platform.machine().lower() |
| 197 |
return "arm" in machine or "aarch" in machine |
| 198 |
|
| 199 |
|
| 200 |
class HostType(object): |
| 201 |
def __init__(self, ostype=None, distro=None, distrovers=None) -> None: |
| 202 |
# Maybe we should allow callers to indicate whether this machine uses |
| 203 |
# an ARM architecture, but we need to change HostType serialization |
| 204 |
# and deserialization in that case and hunt down anywhere that is |
| 205 |
# persisting that serialized data. |
| 206 |
isarm = False |
| 207 |
|
| 208 |
if ostype is None: |
| 209 |
distro = None |
| 210 |
distrovers = None |
| 211 |
if sys.platform.startswith("linux"): |
| 212 |
ostype, distro, distrovers = get_linux_type() |
| 213 |
elif sys.platform.startswith("darwin"): |
| 214 |
ostype = "darwin" |
| 215 |
elif is_windows(): |
| 216 |
ostype = "windows" |
| 217 |
# pyre-fixme[16]: Module `sys` has no attribute `getwindowsversion`. |
| 218 |
distrovers = str(sys.getwindowsversion().major) |
| 219 |
elif sys.platform.startswith("freebsd"): |
| 220 |
ostype = "freebsd" |
| 221 |
else: |
| 222 |
ostype = sys.platform |
| 223 |
|
| 224 |
isarm = is_current_host_arm() |
| 225 |
|
| 226 |
# The operating system type |
| 227 |
self.ostype = ostype |
| 228 |
# The distribution, if applicable |
| 229 |
self.distro = distro |
| 230 |
# The OS/distro version if known |
| 231 |
self.distrovers = distrovers |
| 232 |
# Does the CPU use an ARM architecture? ARM includes Apple Silicon |
| 233 |
# Macs as well as other ARM systems that might be running Linux or |
| 234 |
# something. |
| 235 |
self.isarm = isarm |
| 236 |
|
| 237 |
def is_windows(self): |
| 238 |
return self.ostype == "windows" |
| 239 |
|
| 240 |
# is_arm is kinda half implemented at the moment. This method is only |
| 241 |
# intended to be used when HostType represents information about the |
| 242 |
# current machine we are running on. |
| 243 |
# When HostType is being used to enumerate platform types (represent |
| 244 |
# information about machine types that we may or may not be running on) |
| 245 |
# the result could be nonsense (under the current implementation its always |
| 246 |
# false.) |
| 247 |
def is_arm(self): |
| 248 |
return self.isarm |
| 249 |
|
| 250 |
def is_darwin(self): |
| 251 |
return self.ostype == "darwin" |
| 252 |
|
| 253 |
def is_linux(self): |
| 254 |
return self.ostype == "linux" |
| 255 |
|
| 256 |
def is_freebsd(self): |
| 257 |
return self.ostype == "freebsd" |
| 258 |
|
| 259 |
def as_tuple_string(self) -> str: |
| 260 |
return "%s-%s-%s" % ( |
| 261 |
self.ostype, |
| 262 |
self.distro or "none", |
| 263 |
self.distrovers or "none", |
| 264 |
) |
| 265 |
|
| 266 |
def get_package_manager(self): |
| 267 |
if not self.is_linux() and not self.is_darwin(): |
| 268 |
return None |
| 269 |
if self.is_darwin(): |
| 270 |
return "homebrew" |
| 271 |
if self.distro in ("fedora", "centos", "centos_stream"): |
| 272 |
return "rpm" |
| 273 |
if self.distro.startswith(("debian", "ubuntu")): |
| 274 |
return "deb" |
| 275 |
return None |
| 276 |
|
| 277 |
@staticmethod |
| 278 |
def from_tuple_string(s) -> "HostType": |
| 279 |
ostype, distro, distrovers = s.split("-") |
| 280 |
return HostType(ostype=ostype, distro=distro, distrovers=distrovers) |
| 281 |
|
| 282 |
def __eq__(self, b): |
| 283 |
return ( |
| 284 |
self.ostype == b.ostype |
| 285 |
and self.distro == b.distro |
| 286 |
and self.distrovers == b.distrovers |
| 287 |
) |