Skip to content

Instantly share code, notes, and snippets.

@azat
Last active November 4, 2024 09:36
Show Gist options
  • Save azat/df9471e41cb4ead2bf32859c6947d0bc to your computer and use it in GitHub Desktop.
Save azat/df9471e41cb4ead2bf32859c6947d0bc to your computer and use it in GitHub Desktop.
import os
import pyinotify
def get_current_memory_cgroup_path():
try:
with open("/proc/self/cgroup", "r") as f:
for line in f:
parts = line.strip().split(":")
if len(parts) == 3 and parts[1] == "":
return os.path.join("/sys/fs/cgroup", parts[2].lstrip('/'), "memory.max")
except FileNotFoundError:
raise Exception("Could not find /proc/self/cgroup. Are you in a cgroup environment?")
print("Could not detect memory cgroup path in cgroupv2.")
class MemoryMaxEventHandler(pyinotify.ProcessEvent):
def __init__(self, memory_max_path):
self.memory_max_path = memory_max_path
def process_IN_MODIFY(self, event):
"""Handles the IN_MODIFY event."""
with open(self.memory_max_path, 'r') as f:
memory_max = f.read().strip()
print(f"Memory Max: {memory_max} bytes")
def poll_memory_max():
memory_max_path = get_current_memory_cgroup_path()
if not memory_max_path:
print("Memory cgroup path could not be determined.")
return
wm = pyinotify.WatchManager()
handler = MemoryMaxEventHandler(memory_max_path)
notifier = pyinotify.Notifier(wm, handler)
print(f"Watching memory.max at {memory_max_path}")
wm.add_watch(memory_max_path, pyinotify.IN_MODIFY)
try:
notifier.loop()
finally:
notifier.stop()
poll_memory_max()
@azat
Copy link
Author

azat commented Nov 4, 2024

$ python /tmp/inotify-cgroup-mem.py
Watching memory.max at /sys/fs/cgroup/user.slice/user-1000.slice/[email protected]/app.slice/tmux-spawn-27f038ab-a676-4225-b873-7e2c4a8d1508.scope/memory.max
Memory Max: max bytes
Memory Max: 107374182400 bytes
Memory Max: max bytes
# echo max >| /sys/fs/cgroup/user.slice/user-1000.slice/[email protected]/app.slice/tmux-spawn-27f038ab-a676-4225-b873-7e2c4a8d1508.scope/memory.max
# echo 100G >| /sys/fs/cgroup/user.slice/user-1000.slice/[email protected]/app.slice/tmux-spawn-27f038ab-a676-4225-b873-7e2c4a8d1508.scope/memory.max
# echo max >| /sys/fs/cgroup/user.slice/user-1000.slice/[email protected]/app.slice/tmux-spawn-27f038ab-a676-4225-b873-7e2c4a8d1508.scope/memory.max

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment