|
| 1 | +# Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +"""Classes for querying guest stats inside microVMs. |
| 5 | +""" |
| 6 | + |
| 7 | + |
| 8 | +class ByteUnit: |
| 9 | + """Represents a byte unit that can be converted to other units.""" |
| 10 | + |
| 11 | + value_bytes: int |
| 12 | + |
| 13 | + def __init__(self, value_bytes: int): |
| 14 | + self.value_bytes = value_bytes |
| 15 | + |
| 16 | + @classmethod |
| 17 | + def from_kib(cls, value_kib: int): |
| 18 | + """Creates a ByteUnit from a value in KiB.""" |
| 19 | + if value_kib < 0: |
| 20 | + raise ValueError("value_kib must be non-negative") |
| 21 | + return ByteUnit(value_kib * 1024) |
| 22 | + |
| 23 | + def bytes(self) -> float: |
| 24 | + """Returns the value in B.""" |
| 25 | + return self.value_bytes |
| 26 | + |
| 27 | + def kib(self) -> float: |
| 28 | + """Returns the value in KiB.""" |
| 29 | + return self.value_bytes / 1024 |
| 30 | + |
| 31 | + def mib(self) -> float: |
| 32 | + """Returns the value in MiB.""" |
| 33 | + return self.value_bytes / (1 << 20) |
| 34 | + |
| 35 | + def gib(self) -> float: |
| 36 | + """Returns the value in GiB.""" |
| 37 | + return self.value_bytes / (1 << 30) |
| 38 | + |
| 39 | + |
| 40 | +class Meminfo: |
| 41 | + """Represents the contents of /proc/meminfo inside the guest""" |
| 42 | + |
| 43 | + mem_total: ByteUnit |
| 44 | + mem_free: ByteUnit |
| 45 | + mem_available: ByteUnit |
| 46 | + buffers: ByteUnit |
| 47 | + cached: ByteUnit |
| 48 | + |
| 49 | + def __init__(self): |
| 50 | + self.mem_total = ByteUnit(0) |
| 51 | + self.mem_free = ByteUnit(0) |
| 52 | + self.mem_available = ByteUnit(0) |
| 53 | + self.buffers = ByteUnit(0) |
| 54 | + self.cached = ByteUnit(0) |
| 55 | + |
| 56 | + |
| 57 | +class MeminfoGuest: |
| 58 | + """Queries /proc/meminfo inside the guest""" |
| 59 | + |
| 60 | + def __init__(self, vm): |
| 61 | + self.vm = vm |
| 62 | + |
| 63 | + def get(self) -> Meminfo: |
| 64 | + """Returns the contents of /proc/meminfo inside the guest""" |
| 65 | + meminfo = Meminfo() |
| 66 | + for line in self.vm.ssh.check_output("cat /proc/meminfo").stdout.splitlines(): |
| 67 | + parts = line.split() |
| 68 | + if parts[0] == "MemTotal:": |
| 69 | + meminfo.mem_total = ByteUnit.from_kib(int(parts[1])) |
| 70 | + elif parts[0] == "MemFree:": |
| 71 | + meminfo.mem_free = ByteUnit.from_kib(int(parts[1])) |
| 72 | + elif parts[0] == "MemAvailable:": |
| 73 | + meminfo.mem_available = ByteUnit.from_kib(int(parts[1])) |
| 74 | + elif parts[0] == "Buffers:": |
| 75 | + meminfo.buffers = ByteUnit.from_kib(int(parts[1])) |
| 76 | + elif parts[0] == "Cached:": |
| 77 | + meminfo.cached = ByteUnit.from_kib(int(parts[1])) |
| 78 | + |
| 79 | + return meminfo |
0 commit comments