Skip to content

Instantly share code, notes, and snippets.

@tapionx
Created September 28, 2021 09:40
Show Gist options
  • Save tapionx/3f27b31a6501e343ad0cab7e0cd107bc to your computer and use it in GitHub Desktop.
Save tapionx/3f27b31a6501e343ad0cab7e0cd107bc to your computer and use it in GitHub Desktop.
get maximum docker containers memory usage
import subprocess
from decimal import Decimal
class DockerStatsParser():
def __init__(self):
self.max_memory = 0
def get_docker_stats(self):
process = subprocess.run(
["docker stats --no-stream --format '{{.MemUsage}}'"],
shell=True,
check=True,
stdout=subprocess.PIPE,
universal_newlines=True
)
return process.stdout
def get_GiB_from_memory_string(self, str):
if "GiB" in str:
return Decimal(str.replace("GiB", "").strip())
if "MiB" in str:
return Decimal(str.replace("MiB", "").strip()) / Decimal("1024")
def get_total_memory(self, stats_output):
total_memory = Decimal(0)
stats_lines = stats_output.splitlines()
for line in stats_lines:
memory_str = line.split("/")[0]
memory_GiB = self.get_GiB_from_memory_string(memory_str)
total_memory += memory_GiB
return total_memory
def run(self):
while True:
stats = self.get_docker_stats()
total_memory = self.get_total_memory(stats)
if total_memory > self.max_memory:
self.max_memory = total_memory
print(f"current: {total_memory} \t max: {self.max_memory}")
if __name__ == "__main__":
stats = DockerStatsParser()
stats.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment