Skip to content

Commit

Permalink
Remove usage metric in macOS and dry run functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
dormant-user committed Jan 3, 2025
1 parent e717b66 commit cd2a20c
Show file tree
Hide file tree
Showing 6 changed files with 18 additions and 111 deletions.
12 changes: 0 additions & 12 deletions pyudisk/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,10 +93,6 @@ class EnvConfig(BaseSettings):
"""

dry_run: bool = False
sample_partitions: str = "partitions.json"
sample_dump: str = "dump.txt"

smart_lib: FilePath = get_smart_lib()
disk_lib: FilePath = get_disk_lib()
metrics: Metric | List[Metric] = Field(default_factory=list)
Expand All @@ -122,14 +118,6 @@ class EnvConfig(BaseSettings):
report_dir: str | DirectoryPath = "report"
report_file: str = Field("disk_report_%m-%d-%Y_%I:%M_%p.html", pattern=r".*\.html$")

# noinspection PyMethodParameters
@field_validator("smart_lib", mode="before")
def validate_udisk_lib(cls, value: str) -> str:
"""Validates the disk library path only when DRY_RUN is set to false."""
if os.environ.get("DRY_RUN", "false") == "true":
return __file__
return value

# noinspection PyMethodParameters
@field_validator("metrics", mode="after")
def validate_metrics(cls, value: Metric | List[Metric]) -> List[Metric]:
Expand Down
53 changes: 18 additions & 35 deletions pyudisk/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
from .logger import LOGGER
from .models import SystemPartitions, darwin, linux
from .notification import notification_service, send_report
from .support import humanize_usage_metrics, load_dump, load_partitions
from .util import size_converter, standard


Expand All @@ -29,12 +28,8 @@ def get_partitions(env: EnvConfig) -> Generator[sdiskpart]:
sdiskpart:
Yields the partition datastructure.
"""
if env.dry_run:
partitions = load_partitions(filename=env.sample_partitions)
else:
partitions = psutil.disk_partitions()
system_partitions = SystemPartitions()
for partition in partitions:
for partition in psutil.disk_partitions():
if (
not any(
partition.mountpoint.startswith(mnt)
Expand All @@ -55,17 +50,13 @@ def get_smart_metrics(env: EnvConfig) -> str:
str:
Returns the output from disk util dump.
"""
if env.dry_run:
text = load_dump(filename=env.sample_dump)
else:
try:
output = subprocess.check_output(f"{env.smart_lib} dump", shell=True)
except subprocess.CalledProcessError as error:
result = error.output.decode(encoding="UTF-8").strip()
LOGGER.error(f"[{error.returncode}]: {result}\n")
return ""
text = output.decode(encoding="UTF-8")
return text
try:
output = subprocess.check_output(f"{env.smart_lib} dump", shell=True)
except subprocess.CalledProcessError as error:
result = error.output.decode(encoding="UTF-8").strip()
LOGGER.error(f"[{error.returncode}]: {result}\n")
return ""
return output.decode(encoding="UTF-8")


def parse_drives(input_data: str) -> Dict[str, Any]:
Expand Down Expand Up @@ -108,15 +99,15 @@ def parse_drives(input_data: str) -> Dict[str, Any]:

def parse_block_devices(
env: EnvConfig, input_data: str
) -> Dict[sdiskpart, Dict[str, str]]:
) -> Dict[str, List[Dict[str, str]]]:
"""Parses block_devices' information from the dump into a datastructure.
Args:
env: Environment variables configuration.
input_data: Smart metrics dump.
Returns:
Dict[sdiskpart, str]:
Dict[str, List[Dict[str, str]]]:
Returns a dictionary of block_devices' metrics as key-value pairs.
"""
block_devices = {}
Expand Down Expand Up @@ -184,10 +175,10 @@ def parse_block_devices(
block_devices[block][key] = val
block_devices_updated = {}
for _, value in block_devices.items():
if block_devices_updated.get(value['Drive']):
block_devices_updated[value['Drive']].append(value)
if block_devices_updated.get(value["Drive"]):
block_devices_updated[value["Drive"]].append(value)
else:
block_devices_updated[value['Drive']] = [value]
block_devices_updated[value["Drive"]] = [value]
return block_devices_updated


Expand Down Expand Up @@ -298,12 +289,6 @@ def get_smart_metrics_macos(
"device", darwin.Device(name=device_id, info_name=device_id).model_dump()
)
output["model_name"] = output.get("model_name", device_info.get("name"))
if len(mountpoints) == 1:
output["usage"] = humanize_usage_metrics(psutil.disk_usage(mountpoints[0]))
else:
# This will occur only when the disk retrieval falls back to partitions or the disk path itself
# In both cases, the mountpoint can be assumed as root (/)
output["usage"] = humanize_usage_metrics(psutil.disk_usage("/"))
output["mountpoints"] = mountpoints
return output
except ValidationError as error:
Expand Down Expand Up @@ -341,7 +326,7 @@ def smart_metrics(env: EnvConfig) -> Generator[linux.Disk | darwin.Disk]:
LOGGER.warning(
f"Number of block devices [{len(block_devices)}] is less than the number of drives [{len(drives)}]"
)
device_names = set(v["Drive"] for v in block_devices.values())
device_names = set(block_devices.keys())
drive_names = set(drives.keys())
diff = (
drive_names - device_names
Expand All @@ -362,11 +347,11 @@ def smart_metrics(env: EnvConfig) -> Generator[linux.Disk | darwin.Disk]:
for drive, data in drives.items():
if block_data := block_devices.get(drive):
data["Partition"] = block_data
yield linux.Disk(id=drive, model=data.get("Info", {}).get("Model", ""), **data)
else:
raise ValueError(
f"{drive} not found in {drives.keys()}"
yield linux.Disk(
id=drive, model=data.get("Info", {}).get("Model", ""), **data
)
else:
raise ValueError(f"{drive} not found in {drives.keys()}")


def generate_html(
Expand Down Expand Up @@ -434,8 +419,6 @@ def generate_report(**kwargs) -> str:
return report_file


# todo: Remove monitoring features all together

def monitor_disk(env: EnvConfig) -> Generator[linux.Disk]:
"""Monitors disk attributes based on the configuration.
Expand Down
9 changes: 0 additions & 9 deletions pyudisk/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,6 @@
from pydantic import BaseModel, Field


class Usage(BaseModel):
"""Disk partition's usage information."""

Total: str
Used: str
Free: str
Percent: int | float


class SystemPartitions(BaseModel):
"""System partitions' mountpoints and fstypes."""

Expand Down
4 changes: 0 additions & 4 deletions pyudisk/models/darwin.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

from pydantic import BaseModel

from . import Usage


class Message(BaseModel):
"""Log message with severity level.
Expand Down Expand Up @@ -470,8 +468,6 @@ class Disk(BaseModel):
ata_smart_error_log: Optional[ATASummary] = None
ata_smart_self_test_log: Optional[ATAStandard] = None
ata_smart_selective_self_test_log: Optional[ATASmartSelectiveSelfTestLog] = None
# todo: Remove usage for macOS - usage should be mountpoint specific (if mounted)
usage: Optional[Usage] = None
mountpoints: List[str] = None

class Config:
Expand Down
2 changes: 0 additions & 2 deletions pyudisk/models/linux.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@

from pydantic import BaseModel, field_validator

from . import Usage

try:
from enum import StrEnum
except ImportError:
Expand Down
49 changes: 0 additions & 49 deletions pyudisk/support.py

This file was deleted.

0 comments on commit cd2a20c

Please sign in to comment.