62 lines
2.2 KiB
Python
62 lines
2.2 KiB
Python
"""Bound a CAD subprocess before it can exhaust the web host's memory."""
|
|
import os
|
|
import sys
|
|
import ctypes
|
|
import psutil
|
|
|
|
|
|
def memory_limits():
|
|
mb = 1024 * 1024
|
|
# Keep the original cap on small deployment hosts. Workstations with at
|
|
# least 16 GiB can accommodate compound geometry that exceeds 2 GiB.
|
|
total_mb = psutil.virtual_memory().total / mb
|
|
cap_mb = 4096 if total_mb >= 16384 else 2048
|
|
default = min(cap_mb, int(total_mb * .35))
|
|
resident = max(256, int(os.getenv('CADMIND_WORKER_MEMORY_MB', str(default)))) * mb
|
|
return resident
|
|
|
|
|
|
def process_footprint(process):
|
|
if sys.platform == 'darwin':
|
|
# macOS reserves hundreds of GB of address space on startup. VMS is
|
|
# not committed memory. libproc's footprint includes compressed pages.
|
|
class UsageV2(ctypes.Structure):
|
|
_fields_ = [('uuid', ctypes.c_uint8 * 16), ('values', ctypes.c_uint64 * 18)]
|
|
usage = UsageV2()
|
|
lib = ctypes.CDLL('/usr/lib/libproc.dylib')
|
|
lib.proc_pid_rusage.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_void_p]
|
|
lib.proc_pid_rusage.restype = ctypes.c_int
|
|
if lib.proc_pid_rusage(process.pid, 2, ctypes.byref(usage)) == 0:
|
|
return usage.values[7] # ri_phys_footprint, sys/resource.h
|
|
memory = process.memory_full_info()
|
|
return memory.rss + getattr(memory, 'swap', 0)
|
|
|
|
|
|
def memory_exceeded(pid, limit):
|
|
try:
|
|
root = psutil.Process(pid)
|
|
used = 0
|
|
for member in [root] + root.children(recursive=True):
|
|
try:
|
|
used += process_footprint(member)
|
|
except psutil.NoSuchProcess:
|
|
pass
|
|
if used > limit:
|
|
return f'CADMemoryLimit: 建模进程达到内存保护阈值({used//1048576}MB,上限{limit//1048576}MB),已停止当前运算并保留检查点'
|
|
except (psutil.NoSuchProcess, psutil.AccessDenied):
|
|
pass
|
|
return None
|
|
|
|
|
|
def kill_tree(process):
|
|
try:
|
|
for child in psutil.Process(process.pid).children(recursive=True):
|
|
try:
|
|
child.kill()
|
|
except psutil.NoSuchProcess:
|
|
pass
|
|
except psutil.NoSuchProcess:
|
|
pass
|
|
if process.is_alive():
|
|
process.kill()
|