Last active
November 4, 2024 09:36
-
-
Save azat/df9471e41cb4ead2bf32859c6947d0bc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Author
azat
commented
Nov 4, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment