CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/scripts/memory_monitor.py
Views: 791
1
#!/usr/bin/env python3
2
3
import psutil
4
import time
5
import os
6
7
GB = 1024 * 1024 * 1024 # 1 GB in bytes
8
free = int(os.popen('free -g').read().splitlines()[1].split()[1])
9
THRESHOLD = (free - 3) * GB
10
11
while True:
12
print(
13
f"checking for processing using more than {THRESHOLD / GB:.2f} GB RAM")
14
for proc in psutil.process_iter(['pid', 'memory_info']):
15
try:
16
if proc.memory_info().rss > THRESHOLD:
17
print(
18
f"Killing process {proc.pid} using {proc.memory_info().rss / GB:.2f} GB RAM"
19
)
20
psutil.Process(proc.pid).kill()
21
except (psutil.NoSuchProcess, psutil.AccessDenied,
22
psutil.ZombieProcess):
23
pass
24
print("sleeping 3 seconds")
25
time.sleep(3) # Check every 5 seconds
26
27