Resource Monitor Core Documentation
- class bedrock_server_manager.core.system.base.ResourceMonitor(*args: Any, **kwargs: Any)
Bases:
object
A singleton class for monitoring process resource usage (CPU, memory, uptime).
This class provides a way to get resource statistics for a given
psutil.Process
object. It is implemented as a thread-safe singleton to ensure that the internal state required for calculating CPU percentage (which relies on comparing CPU times between calls) is maintained consistently across the application for each monitored process.The monitor stores the last CPU times and timestamp on a per-PID basis to correctly calculate CPU utilization for individual processes.
Requires the
psutil
library. Ifpsutil
is not available (indicated byPSUTIL_AVAILABLE
beingFalse
), methods likeget_stats()
will typically log a warning and returnNone
or raise an error.- _instance
The single instance of this class.
- Type:
Optional[ResourceMonitor]
- _lock
A lock to ensure thread-safe singleton creation and initialization.
- Type:
threading.Lock
- _last_readings
A dictionary storing the last CPU times (
psutil.cpu_times
result) and timestamp for each monitored PID. Keyed by PID.- Type:
Dict[int, Tuple[Any, float]]
- _initialized
A flag to ensure
__init__
logic runs only once.- Type:
bool
- __init__() None
Initializes the resource monitor’s state.
This constructor is called only once for the singleton instance. It sets up the _last_readings dictionary to store CPU time snapshots for different processes and an _initialized flag.
- get_stats(process: Process) Dict[str, Any] | None
Calculates and returns resource usage statistics for the given process.
If
psutil
is not available, this method logs a warning and returnsNone
.The CPU percentage is calculated based on the change in CPU times since the last call for the same process ID (PID). The first call for a PID will report 0% CPU usage as there’s no prior data for comparison.
- Parameters:
process (psutil.Process) – An instance of
psutil.Process
representing the process to monitor.- Returns:
A dictionary containing the statistics if successful, or
None
ifpsutil
is unavailable or the process is inaccessible (e.g.,psutil.NoSuchProcess
,psutil.AccessDenied
). The dictionary structure is:{ "pid": int, # Process ID "cpu_percent": float, # CPU usage percentage (e.g., 12.3) "memory_mb": float, # Resident Set Size (RSS) memory in megabytes "uptime": str # Process uptime formatted as "HH:MM:SS" }
- Return type:
Optional[Dict[str, Any]]
- Raises:
TypeError – If the input process is not a
psutil.Process
instance.SystemError – If an unexpected error occurs while fetching stats using
psutil
(other thanNoSuchProcess
orAccessDenied
).