openstack-janitor 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ """openstack-janitor: audit an OpenStack cloud for orphaned and wasteful resources."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,42 @@
1
+ """Shared timestamp-age helper.
2
+
3
+ Used by age-based detectors (old snapshots, shutoff instances, ...) and will
4
+ also back the future min-age safety rail that gates any destructive "clean"
5
+ action behind a minimum resource age.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from datetime import UTC, datetime
11
+
12
+
13
+ def age_in_days(timestamp: str | None, *, now: datetime | None = None) -> float | None:
14
+ """Return the age of an ISO 8601 ``timestamp`` in days, or ``None``.
15
+
16
+ ``timestamp`` is expected in the form openstacksdk returns resource
17
+ timestamps in, e.g. ``"2026-06-01T12:00:00Z"``, with or without
18
+ microseconds, or with a ``+00:00``-style offset. Naive timestamps (no
19
+ offset at all) are treated as UTC, since openstacksdk sometimes returns
20
+ naive UTC strings.
21
+
22
+ Returns ``None`` if ``timestamp`` is ``None`` or cannot be parsed. Never
23
+ raises.
24
+
25
+ :param timestamp: ISO 8601 timestamp string, or ``None``.
26
+ :param now: Reference time to compute age against. Defaults to the
27
+ current UTC time; injectable for tests.
28
+ """
29
+ if timestamp is None:
30
+ return None
31
+
32
+ try:
33
+ parsed = datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
34
+ except ValueError:
35
+ return None
36
+
37
+ if parsed.tzinfo is None:
38
+ parsed = parsed.replace(tzinfo=UTC)
39
+
40
+ reference = now if now is not None else datetime.now(UTC)
41
+
42
+ return (reference - parsed).total_seconds() / 86400
@@ -0,0 +1,106 @@
1
+ """Command-line interface for openstack-janitor."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from enum import StrEnum
6
+
7
+ import typer
8
+ from openstack.exceptions import SDKException
9
+ from rich.console import Console
10
+
11
+ from openstack_janitor.connection import get_connection
12
+ from openstack_janitor.detectors import get_detectors
13
+ from openstack_janitor.reporting import print_findings, render_html, render_json
14
+
15
+ app = typer.Typer(
16
+ help="Audit an OpenStack cloud for orphaned and wasteful resources.",
17
+ no_args_is_help=True,
18
+ )
19
+ console = Console()
20
+ error_console = Console(stderr=True)
21
+
22
+
23
+ class OutputFormat(StrEnum):
24
+ """Supported `--format` values for `janitor audit`."""
25
+
26
+ table = "table"
27
+ json = "json"
28
+ html = "html"
29
+
30
+
31
+ @app.callback()
32
+ def callback() -> None:
33
+ """Audit an OpenStack cloud for orphaned and wasteful resources.
34
+
35
+ A no-op callback: its only purpose is to keep Typer in "subcommand" mode
36
+ (`janitor audit ...`) instead of collapsing to a single implicit command,
37
+ since there is currently only one subcommand registered.
38
+ """
39
+
40
+
41
+ @app.command()
42
+ def audit(
43
+ cloud: str | None = typer.Option(
44
+ None,
45
+ "--cloud",
46
+ help="Named cloud from clouds.yaml (default: resolved from OS_CLOUD / OS_* env vars).",
47
+ ),
48
+ detector: list[str] | None = typer.Option(
49
+ None,
50
+ "--detector",
51
+ help="Run only this detector (repeatable). Default: run all registered detectors.",
52
+ ),
53
+ output_format: OutputFormat = typer.Option(
54
+ OutputFormat.table,
55
+ "--format",
56
+ help="Output format: table for humans, json/html for reports or piping.",
57
+ ),
58
+ ) -> None:
59
+ """Scan the cloud and report orphaned/wasteful resources.
60
+
61
+ Exit codes: 0 = no findings, 1 = findings were reported (useful for cron
62
+ jobs), 2 = an unknown --detector name was given, 3 = connection or
63
+ authentication to the cloud failed. Exit-code behavior is the same for
64
+ every --format.
65
+ """
66
+ all_detectors = get_detectors()
67
+ selected = all_detectors
68
+ if detector:
69
+ by_name = {d.name: d for d in all_detectors}
70
+ unknown = [name for name in detector if name not in by_name]
71
+ if unknown:
72
+ valid = ", ".join(sorted(by_name)) or "(none registered)"
73
+ error_console.print(
74
+ f"[red]Unknown detector(s): {', '.join(unknown)}. Valid detectors: {valid}[/red]"
75
+ )
76
+ raise typer.Exit(code=2)
77
+ selected = [by_name[name] for name in detector]
78
+
79
+ try:
80
+ conn = get_connection(cloud)
81
+ findings = []
82
+ for det in selected:
83
+ findings.extend(det.detect(conn))
84
+ except SDKException as exc:
85
+ error_console.print(f"[red]Failed to connect to OpenStack cloud: {exc}[/red]")
86
+ raise typer.Exit(code=3) from exc
87
+
88
+ if output_format is OutputFormat.json:
89
+ # Machine-readable: use plain print(), never the rich console -- rich
90
+ # would wrap lines and inject markup, corrupting the JSON output.
91
+ print(render_json(findings))
92
+ elif output_format is OutputFormat.html:
93
+ print(render_html(findings))
94
+ else:
95
+ print_findings(findings, console)
96
+
97
+ raise typer.Exit(code=1 if findings else 0)
98
+
99
+
100
+ def main() -> None:
101
+ """Console-script entry point (typer's ``app`` is not itself callable-as-main)."""
102
+ app()
103
+
104
+
105
+ if __name__ == "__main__":
106
+ main()
@@ -0,0 +1,32 @@
1
+ """Connection helper: the single seam between openstack-janitor and openstacksdk.
2
+
3
+ Kept intentionally tiny so tests and the CLI have one place to mock instead of
4
+ reaching into openstacksdk internals.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import openstack
10
+ from openstack.connection import Connection
11
+
12
+
13
+ def get_connection(cloud: str | None = None) -> Connection:
14
+ """Return an authenticated openstacksdk Connection.
15
+
16
+ Resolution order follows openstacksdk's own rules:
17
+
18
+ 1. If ``cloud`` is given, it is looked up by name in ``clouds.yaml``
19
+ (searched in the current directory, ``~/.config/openstack/`` and
20
+ ``/etc/openstack/``), optionally layered with ``secure.yaml``.
21
+ 2. If ``cloud`` is ``None``, ``openstack.connect()`` is called with no
22
+ arguments and openstacksdk resolves the cloud itself: the ``OS_CLOUD``
23
+ environment variable (which behaves like passing ``cloud=...``), or
24
+ else the standard ``OS_*`` environment variables (``OS_AUTH_URL``,
25
+ ``OS_USERNAME``, ``OS_PASSWORD``, ``OS_PROJECT_NAME``, etc.).
26
+
27
+ No connection is made here -- openstacksdk connections are lazy, so this
28
+ only builds the ``Connection`` object.
29
+ """
30
+ if cloud is None:
31
+ return openstack.connect()
32
+ return openstack.connect(cloud=cloud)
@@ -0,0 +1,31 @@
1
+ """Detector registry.
2
+
3
+ This list is deliberately explicit and boring: to add a detector, write the
4
+ class and append it here. A config-driven enable/disable toggle (e.g. via
5
+ ``janitor.toml``) arrives in a later change.
6
+ """
7
+
8
+ from openstack_janitor.detectors.base import Detector, Finding
9
+ from openstack_janitor.detectors.floating_ips import UnassociatedFloatingIpsDetector
10
+ from openstack_janitor.detectors.instances import ShutoffInstancesDetector
11
+ from openstack_janitor.detectors.ports import OrphanedPortsDetector
12
+ from openstack_janitor.detectors.security_groups import UnusedSecurityGroupsDetector
13
+ from openstack_janitor.detectors.snapshots import OldSnapshotsDetector
14
+ from openstack_janitor.detectors.volumes import UnattachedVolumesDetector
15
+
16
+ ALL_DETECTORS: list[type[Detector]] = [
17
+ UnattachedVolumesDetector,
18
+ UnassociatedFloatingIpsDetector,
19
+ OrphanedPortsDetector,
20
+ OldSnapshotsDetector,
21
+ ShutoffInstancesDetector,
22
+ UnusedSecurityGroupsDetector,
23
+ ]
24
+
25
+
26
+ def get_detectors() -> list[Detector]:
27
+ """Instantiate every registered detector."""
28
+ return [detector_cls() for detector_cls in ALL_DETECTORS]
29
+
30
+
31
+ __all__ = ["ALL_DETECTORS", "Detector", "Finding", "get_detectors"]
@@ -0,0 +1,36 @@
1
+ """Base types shared by all detectors."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from abc import ABC, abstractmethod
6
+ from dataclasses import dataclass, field
7
+ from typing import ClassVar
8
+
9
+ from openstack.connection import Connection
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class Finding:
14
+ """A single flagged resource."""
15
+
16
+ resource_type: str
17
+ resource_id: str
18
+ resource_name: str
19
+ project_id: str
20
+ reason: str
21
+ extra: dict[str, str] = field(default_factory=dict)
22
+
23
+
24
+ class Detector(ABC):
25
+ """A check that scans a cloud for one category of orphaned/wasteful resource."""
26
+
27
+ name: ClassVar[str]
28
+ """Kebab-case identifier, e.g. "unattached-volumes"."""
29
+
30
+ description: ClassVar[str]
31
+ """Short human-readable description of what this detector looks for."""
32
+
33
+ @abstractmethod
34
+ def detect(self, conn: Connection) -> list[Finding]:
35
+ """Scan the cloud reachable via ``conn`` and return any findings."""
36
+ raise NotImplementedError
@@ -0,0 +1,42 @@
1
+ """Detector for unassociated floating IPs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import ClassVar
6
+
7
+ from openstack.connection import Connection
8
+
9
+ from openstack_janitor.detectors.base import Detector, Finding
10
+
11
+
12
+ class UnassociatedFloatingIpsDetector(Detector):
13
+ """Flags floating IPs that are not associated with any port."""
14
+
15
+ name: ClassVar[str] = "unassociated-floating-ips"
16
+ description: ClassVar[str] = "Floating IPs not associated with any port"
17
+
18
+ def detect(self, conn: Connection) -> list[Finding]:
19
+ # Unlike block storage, Neutron scopes list results by policy automatically
20
+ # (admins see all projects, non-admins see only their own), so there is no
21
+ # all_projects kwarg here and no ForbiddenException fallback is needed.
22
+ ips = list(conn.network.ips())
23
+
24
+ findings: list[Finding] = []
25
+ for ip in ips:
26
+ if ip.port_id:
27
+ continue
28
+ extra = {}
29
+ status = getattr(ip, "status", None)
30
+ if status:
31
+ extra["status"] = str(status)
32
+ findings.append(
33
+ Finding(
34
+ resource_type="floating-ip",
35
+ resource_id=ip.id,
36
+ resource_name=getattr(ip, "floating_ip_address", "") or "",
37
+ project_id=getattr(ip, "project_id", "") or "",
38
+ reason="floating IP is not associated with any port",
39
+ extra=extra,
40
+ )
41
+ )
42
+ return findings
@@ -0,0 +1,71 @@
1
+ """Detector for long-shutoff instances."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime
6
+ from typing import ClassVar
7
+
8
+ from openstack.connection import Connection
9
+ from openstack.exceptions import ForbiddenException
10
+
11
+ from openstack_janitor.age import age_in_days
12
+ from openstack_janitor.detectors.base import Detector, Finding
13
+
14
+
15
+ class ShutoffInstancesDetector(Detector):
16
+ """Flags instances that have been SHUTOFF for longer than a threshold.
17
+
18
+ There is no direct "shutoff since" field in the Compute API. Any status
19
+ transition bumps ``updated_at``, so an ``updated_at`` older than N days
20
+ on a currently-SHUTOFF server proves it has been off for at least N
21
+ days -- a conservative lower bound, not an exact shutoff duration.
22
+ Non-status mutations (metadata edits, resizes) also bump ``updated_at``,
23
+ which can reset the apparent age and hide a genuinely old instance: this
24
+ detector may under-report but never over-reports.
25
+ """
26
+
27
+ name: ClassVar[str] = "shutoff-instances"
28
+ description: ClassVar[str] = "Instances that have been SHUTOFF for longer than a threshold"
29
+
30
+ def __init__(self, max_age_days: float = 30.0, *, now: datetime | None = None) -> None:
31
+ self.max_age_days = max_age_days
32
+ self.now = now
33
+
34
+ def detect(self, conn: Connection) -> list[Finding]:
35
+ try:
36
+ servers = list(conn.compute.servers(details=True, all_projects=True))
37
+ except ForbiddenException:
38
+ # all_projects=True requires admin; fall back to the caller's own project.
39
+ servers = list(conn.compute.servers(details=True))
40
+
41
+ findings: list[Finding] = []
42
+ for server in servers:
43
+ if server.status != "SHUTOFF":
44
+ continue
45
+
46
+ age = age_in_days(getattr(server, "updated_at", None), now=self.now)
47
+ if age is None or age <= self.max_age_days:
48
+ continue
49
+
50
+ extra = {}
51
+ updated_at = getattr(server, "updated_at", None)
52
+ if updated_at:
53
+ extra["updated_at"] = str(updated_at)
54
+ status = getattr(server, "status", None)
55
+ if status:
56
+ extra["status"] = str(status)
57
+
58
+ findings.append(
59
+ Finding(
60
+ resource_type="instance",
61
+ resource_id=server.id,
62
+ resource_name=getattr(server, "name", "") or "",
63
+ project_id=getattr(server, "project_id", "") or "",
64
+ reason=(
65
+ f"instance has been shutoff for at least {age:.0f} days "
66
+ f"(threshold {self.max_age_days:.0f})"
67
+ ),
68
+ extra=extra,
69
+ )
70
+ )
71
+ return findings
@@ -0,0 +1,46 @@
1
+ """Detector for orphaned ports."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import ClassVar
6
+
7
+ from openstack.connection import Connection
8
+
9
+ from openstack_janitor.detectors.base import Detector, Finding
10
+
11
+
12
+ class OrphanedPortsDetector(Detector):
13
+ """Flags ports that have no device owner and no device id.
14
+
15
+ Infrastructure ports (DHCP, router interfaces, Octavia VIPs) always carry
16
+ a device owner or device id, so they are never flagged. Known false
17
+ positive: a manually pre-created port awaiting later attachment also has
18
+ both fields empty. That is fine for a read-only audit, but any future
19
+ clean action on ports must be gated behind age/tag safety rails rather
20
+ than this signal alone.
21
+ """
22
+
23
+ name: ClassVar[str] = "orphaned-ports"
24
+ description: ClassVar[str] = "Ports with no device owner and no device id"
25
+
26
+ def detect(self, conn: Connection) -> list[Finding]:
27
+ ports = list(conn.network.ports())
28
+
29
+ findings: list[Finding] = []
30
+ for port in ports:
31
+ if port.device_owner or port.device_id:
32
+ continue
33
+ extra = {}
34
+ if getattr(port, "network_id", None):
35
+ extra["network_id"] = str(port.network_id)
36
+ findings.append(
37
+ Finding(
38
+ resource_type="port",
39
+ resource_id=port.id,
40
+ resource_name=port.name or "",
41
+ project_id=getattr(port, "project_id", "") or "",
42
+ reason="port has no device owner or device id",
43
+ extra=extra,
44
+ )
45
+ )
46
+ return findings
@@ -0,0 +1,71 @@
1
+ """Detector for unused security groups."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import ClassVar
6
+
7
+ from openstack.connection import Connection
8
+
9
+ from openstack_janitor.detectors.base import Detector, Finding
10
+
11
+
12
+ class UnusedSecurityGroupsDetector(Detector):
13
+ """Flags security groups that are not in use.
14
+
15
+ A group is considered "in use" from two sources: it is attached to at
16
+ least one port (via that port's ``security_group_ids``), or it is named
17
+ as the ``remote_group_id`` of a rule on *any* security group -- a group
18
+ referenced that way is in use even if it has zero ports, because
19
+ deleting it would break the referencing rule. The auto-created "default"
20
+ group present in every project is undeletable and always skipped, since
21
+ flagging it would just be noise.
22
+
23
+ A self-referencing rule (remote_group_id pointing at its own group)
24
+ marks the group in-use — an under-report in the delete-safe direction.
25
+ Known false positive: a freshly created group awaiting its first port is
26
+ flagged. Fine for a read-only audit, but any future clean action must be
27
+ gated behind age/tag safety rails rather than this signal alone.
28
+ """
29
+
30
+ name: ClassVar[str] = "unused-security-groups"
31
+ description: ClassVar[str] = "Security groups not attached to any port or referenced by a rule"
32
+
33
+ def detect(self, conn: Connection) -> list[Finding]:
34
+ security_groups = list(conn.network.security_groups())
35
+ ports = list(conn.network.ports())
36
+
37
+ in_use_ids: set[str] = set()
38
+ for port in ports:
39
+ in_use_ids.update(getattr(port, "security_group_ids", []) or [])
40
+ for group in security_groups:
41
+ for rule in getattr(group, "security_group_rules", []) or []:
42
+ if isinstance(rule, dict):
43
+ remote_group_id = rule.get("remote_group_id")
44
+ else:
45
+ remote_group_id = getattr(rule, "remote_group_id", None)
46
+ if remote_group_id:
47
+ in_use_ids.add(remote_group_id)
48
+
49
+ findings: list[Finding] = []
50
+ for group in security_groups:
51
+ if group.id in in_use_ids:
52
+ continue
53
+ if (getattr(group, "name", None) or "") == "default":
54
+ continue
55
+
56
+ extra = {}
57
+ rules = getattr(group, "security_group_rules", None)
58
+ if rules is not None:
59
+ extra["rules_count"] = str(len(rules))
60
+
61
+ findings.append(
62
+ Finding(
63
+ resource_type="security-group",
64
+ resource_id=group.id,
65
+ resource_name=getattr(group, "name", "") or "",
66
+ project_id=getattr(group, "project_id", "") or "",
67
+ reason="security group is not attached to any port or referenced by any rule",
68
+ extra=extra,
69
+ )
70
+ )
71
+ return findings
@@ -0,0 +1,58 @@
1
+ """Detector for old block storage snapshots."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime
6
+ from typing import ClassVar
7
+
8
+ from openstack.connection import Connection
9
+ from openstack.exceptions import ForbiddenException
10
+
11
+ from openstack_janitor.age import age_in_days
12
+ from openstack_janitor.detectors.base import Detector, Finding
13
+
14
+
15
+ class OldSnapshotsDetector(Detector):
16
+ """Flags snapshots older than a configurable age threshold."""
17
+
18
+ name: ClassVar[str] = "old-snapshots"
19
+ description: ClassVar[str] = "Snapshots older than a configurable age threshold"
20
+
21
+ def __init__(self, max_age_days: float = 90.0, *, now: datetime | None = None) -> None:
22
+ self.max_age_days = max_age_days
23
+ self.now = now
24
+
25
+ def detect(self, conn: Connection) -> list[Finding]:
26
+ try:
27
+ snapshots = list(conn.block_storage.snapshots(details=True, all_projects=True))
28
+ except ForbiddenException:
29
+ # all_projects=True requires admin; fall back to the caller's own project.
30
+ snapshots = list(conn.block_storage.snapshots(details=True))
31
+
32
+ findings: list[Finding] = []
33
+ for snap in snapshots:
34
+ # Never flag what we can't date -- a missing/unparsable created_at
35
+ # is skipped silently rather than guessed at.
36
+ age = age_in_days(getattr(snap, "created_at", None), now=self.now)
37
+ if age is None or age <= self.max_age_days:
38
+ continue
39
+
40
+ extra = {}
41
+ created_at = getattr(snap, "created_at", None)
42
+ if created_at:
43
+ extra["created_at"] = str(created_at)
44
+ volume_id = getattr(snap, "volume_id", None)
45
+ if volume_id:
46
+ extra["volume_id"] = str(volume_id)
47
+
48
+ findings.append(
49
+ Finding(
50
+ resource_type="snapshot",
51
+ resource_id=snap.id,
52
+ resource_name=getattr(snap, "name", "") or "",
53
+ project_id=getattr(snap, "project_id", "") or "",
54
+ reason=(f"snapshot is {age:.0f} days old (threshold {self.max_age_days:.0f})"),
55
+ extra=extra,
56
+ )
57
+ )
58
+ return findings
@@ -0,0 +1,39 @@
1
+ """Detector for unattached (orphaned) block storage volumes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import ClassVar
6
+
7
+ from openstack.connection import Connection
8
+ from openstack.exceptions import ForbiddenException
9
+
10
+ from openstack_janitor.detectors.base import Detector, Finding
11
+
12
+
13
+ class UnattachedVolumesDetector(Detector):
14
+ """Flags volumes that are "available" (i.e. not attached to any server)."""
15
+
16
+ name: ClassVar[str] = "unattached-volumes"
17
+ description: ClassVar[str] = "Volumes in 'available' state with no attachments"
18
+
19
+ def detect(self, conn: Connection) -> list[Finding]:
20
+ try:
21
+ volumes = list(conn.block_storage.volumes(details=True, all_projects=True))
22
+ except ForbiddenException:
23
+ # all_projects=True requires admin; fall back to the caller's own project.
24
+ volumes = list(conn.block_storage.volumes(details=True))
25
+
26
+ findings: list[Finding] = []
27
+ for vol in volumes:
28
+ if vol.status != "available" or vol.attachments:
29
+ continue
30
+ findings.append(
31
+ Finding(
32
+ resource_type="volume",
33
+ resource_id=vol.id,
34
+ resource_name=vol.name or "",
35
+ project_id=getattr(vol, "project_id", "") or "",
36
+ reason="volume is unattached (status=available)",
37
+ )
38
+ )
39
+ return findings
@@ -0,0 +1,97 @@
1
+ """Rendering findings to the terminal, JSON, or HTML."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import dataclasses
6
+ import html
7
+ import json
8
+
9
+ from rich.console import Console
10
+ from rich.table import Table
11
+
12
+ from openstack_janitor.detectors.base import Finding
13
+
14
+
15
+ def render_table(findings: list[Finding]) -> Table:
16
+ """Build a rich Table summarizing the given findings."""
17
+ table = Table(title="openstack-janitor findings")
18
+ table.add_column("Type", style="cyan")
19
+ table.add_column("ID", style="dim")
20
+ table.add_column("Name")
21
+ table.add_column("Project")
22
+ table.add_column("Reason")
23
+
24
+ for finding in findings:
25
+ table.add_row(
26
+ finding.resource_type,
27
+ finding.resource_id,
28
+ finding.resource_name,
29
+ finding.project_id,
30
+ finding.reason,
31
+ )
32
+ return table
33
+
34
+
35
+ def print_findings(findings: list[Finding], console: Console) -> None:
36
+ """Print findings as a table, or a clean-cloud message if there are none."""
37
+ if not findings:
38
+ console.print("[green]No findings — cloud looks clean.[/green]")
39
+ return
40
+ console.print(render_table(findings))
41
+
42
+
43
+ def render_json(findings: list[Finding]) -> str:
44
+ """Render findings as an indented JSON array, for reports/piping."""
45
+ return json.dumps([dataclasses.asdict(f) for f in findings], indent=2, sort_keys=True)
46
+
47
+
48
+ def render_html(findings: list[Finding]) -> str:
49
+ """Render findings as a fully self-contained HTML document.
50
+
51
+ Every dynamic value is passed through ``html.escape`` -- findings come
52
+ from cloud-controlled resource names, which must never be trusted enough
53
+ to interpolate into HTML unescaped.
54
+ """
55
+ summary = f"{len(findings)} finding{'s' if len(findings) != 1 else ''}"
56
+
57
+ if not findings:
58
+ body = "<p>No findings — cloud looks clean.</p>"
59
+ else:
60
+ rows = []
61
+ for finding in findings:
62
+ extra = ", ".join(f"{k}={v}" for k, v in finding.extra.items())
63
+ cells = [
64
+ finding.resource_type,
65
+ finding.resource_id,
66
+ finding.resource_name,
67
+ finding.project_id,
68
+ finding.reason,
69
+ extra,
70
+ ]
71
+ row = "".join(f"<td>{html.escape(cell)}</td>" for cell in cells)
72
+ rows.append(f"<tr>{row}</tr>")
73
+ body = (
74
+ "<table>\n"
75
+ "<tr><th>Type</th><th>ID</th><th>Name</th><th>Project</th>"
76
+ "<th>Reason</th><th>Extra</th></tr>\n" + "\n".join(rows) + "\n</table>"
77
+ )
78
+
79
+ return f"""<!DOCTYPE html>
80
+ <html lang="en">
81
+ <head>
82
+ <meta charset="utf-8">
83
+ <title>openstack-janitor report</title>
84
+ <style>
85
+ body {{ font-family: sans-serif; margin: 2rem; }}
86
+ table {{ border-collapse: collapse; width: 100%; }}
87
+ th, td {{ border: 1px solid #ccc; padding: 0.4rem 0.6rem; text-align: left; }}
88
+ th {{ background: #eee; }}
89
+ </style>
90
+ </head>
91
+ <body>
92
+ <h1>openstack-janitor report</h1>
93
+ <p>{html.escape(summary)}</p>
94
+ {body}
95
+ </body>
96
+ </html>
97
+ """
@@ -0,0 +1,109 @@
1
+ Metadata-Version: 2.4
2
+ Name: openstack-janitor
3
+ Version: 0.1.0
4
+ Summary: Audit an OpenStack cloud for orphaned and wasteful resources
5
+ Author-email: Mohammad AbuNemeh <mabunemeh@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.11
9
+ Requires-Dist: openstacksdk>=3.0
10
+ Requires-Dist: rich>=13
11
+ Requires-Dist: typer>=0.12
12
+ Provides-Extra: dev
13
+ Requires-Dist: pytest; extra == 'dev'
14
+ Requires-Dist: pytest-cov; extra == 'dev'
15
+ Requires-Dist: ruff; extra == 'dev'
16
+ Description-Content-Type: text/markdown
17
+
18
+ # openstack-janitor
19
+
20
+ [![CI](https://github.com/mabunemeh/openstack-janitor/actions/workflows/ci.yml/badge.svg)](https://github.com/mabunemeh/openstack-janitor/actions/workflows/ci.yml)
21
+
22
+ A CLI that audits an OpenStack cloud for orphaned and wasteful resources.
23
+
24
+ **Status: early development.** Six detectors are working — see
25
+ [Detectors](#detectors); more detectors and a `clean` command are coming — see
26
+ [Roadmap](#roadmap).
27
+
28
+ ## Install
29
+
30
+ From source:
31
+
32
+ ```sh
33
+ git clone <this repo>
34
+ cd openstack-janitor
35
+ pip install -e .
36
+ ```
37
+
38
+ Publishing to PyPI (`pip install openstack-janitor`) and a `pipx`-friendly
39
+ release are planned once there's more than one detector.
40
+
41
+ ## Usage
42
+
43
+ ```sh
44
+ janitor audit
45
+ janitor audit --cloud my-cloud
46
+ janitor audit --detector unattached-volumes --detector orphaned-ports
47
+ janitor audit --format json > findings.json
48
+ janitor audit --format html > report.html
49
+ ```
50
+
51
+ `--format table` (the default) prints a rich table; `json` and `html` write
52
+ machine-readable / shareable reports to stdout.
53
+
54
+ Example output when orphaned volumes are found:
55
+
56
+ ```
57
+ $ janitor audit --cloud my-cloud
58
+ openstack-janitor findings
59
+ ┏━━━━━━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
60
+ ┃ Type ┃ ID ┃ Name ┃ Project ┃ Reason ┃
61
+ ┡━━━━━━━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
62
+ │ volume │ a1b2c3d4… │ old-db │ proj-1 │ volume is unattached │
63
+ │ │ │ │ │ (status=available) │
64
+ └───────────────┴───────────┴─────────┴─────────┴──────────────────────────────┘
65
+ $ echo $?
66
+ 1
67
+ ```
68
+
69
+ `janitor audit` exits `0` when nothing is found, `1` when findings were
70
+ reported (so it's safe to wire into a cron job or CI check), `2` if an
71
+ unknown `--detector` name is given, and `3` if connecting to the cloud
72
+ fails.
73
+
74
+ ## Detectors
75
+
76
+ | Name | Flags |
77
+ | --- | --- |
78
+ | `unattached-volumes` | Volumes in `available` status with no attachments. |
79
+ | `unassociated-floating-ips` | Floating IPs not associated with any port. |
80
+ | `orphaned-ports` | Ports with no device owner and no device id. Infrastructure ports (DHCP, routers, load balancer VIPs) always carry one of these, so they are never flagged; a pre-created port awaiting attachment will be. |
81
+ | `old-snapshots` | Volume snapshots older than a threshold (default 90 days). |
82
+ | `shutoff-instances` | Instances in `SHUTOFF` status whose last update is older than a threshold (default 30 days). There is no "shutoff since" field in the Compute API, so the age is a conservative lower bound — the detector may under-report but never over-reports. |
83
+ | `unused-security-groups` | Security groups not attached to any port and not referenced as a `remote_group_id` by any rule. The per-project `default` group is always skipped. |
84
+
85
+ All detectors are read-only. Resources without a parseable timestamp are never
86
+ flagged by the age-based detectors. Thresholds become configurable once
87
+ `janitor.toml` support lands (see [Roadmap](#roadmap)).
88
+
89
+ ## Authentication
90
+
91
+ `openstack-janitor` uses [openstacksdk](https://docs.openstack.org/openstacksdk/latest/)
92
+ for authentication, so anything openstacksdk understands works here too:
93
+
94
+ - A named cloud from `clouds.yaml` via `--cloud my-cloud` (or the `OS_CLOUD`
95
+ environment variable).
96
+ - The standard `OS_*` environment variables (`OS_AUTH_URL`, `OS_USERNAME`,
97
+ `OS_PASSWORD`, `OS_PROJECT_NAME`, etc.) if no cloud is specified.
98
+
99
+ See the openstacksdk
100
+ [configuration documentation](https://docs.openstack.org/openstacksdk/latest/user/config/configuration.html)
101
+ for the full resolution order and file locations.
102
+
103
+ ## Roadmap
104
+
105
+ - A `clean` command with a `--dry-run` default and explicit `--yes` to act.
106
+ - `janitor.toml` for per-cloud configuration (which detectors run, age
107
+ thresholds, exclusions).
108
+ - Safety rails: tagging/exclusion lists so resources can be marked "do not
109
+ touch" before `clean` ever deletes anything.
@@ -0,0 +1,18 @@
1
+ openstack_janitor/__init__.py,sha256=kBHapuL47sp1X-379YfqWxixUKYIlQjWwv_O6nFIhTs,110
2
+ openstack_janitor/age.py,sha256=AST-4kXMjBSaGHt-LMKFj66szmi_yFOM3i9XJy8F2b8,1425
3
+ openstack_janitor/cli.py,sha256=gsBvn3RRlSLD_Hpugm67c_gClGQWytnjHZ1L10ssWi4,3367
4
+ openstack_janitor/connection.py,sha256=jgI1OwTnLm8Lxpj_5ED6jw8NA5xH1OzOpg3Y-FP6u4s,1291
5
+ openstack_janitor/reporting.py,sha256=QCZzaX-PDV1jBF9pCVOITO7sBKDA53_uB0Pr0txueGQ,2992
6
+ openstack_janitor/detectors/__init__.py,sha256=egS-J4NMR13srWDNZB88UjPSPIWNiLKPVyRvKXuPY1Q,1194
7
+ openstack_janitor/detectors/base.py,sha256=1Bly8F8BYnbSZJjGccTZKX5Cavu2Y1w17BKcyKypUSg,957
8
+ openstack_janitor/detectors/floating_ips.py,sha256=r1fPMysSYVeHlibHvBA1faOrEf_AFQBOenszKFZOETM,1522
9
+ openstack_janitor/detectors/instances.py,sha256=Psz3i6kQ2YLTUc5AyCOCOzcnc6ob3PxIhmZBzWDYhbQ,2773
10
+ openstack_janitor/detectors/ports.py,sha256=8WpAi-W50N-q_dlzGCbGZDeuBBXK6qovdOvSGRqxbWE,1639
11
+ openstack_janitor/detectors/security_groups.py,sha256=3eSf_j8xn4DmwFx1ZbLBTK3fTZark2Y8aCenBX0w8VA,2933
12
+ openstack_janitor/detectors/snapshots.py,sha256=hXKnWkcK-VQEn7NN5ly47snS3dcbJKRZndjQ0q0O2Bw,2233
13
+ openstack_janitor/detectors/volumes.py,sha256=kVCtALXDBIk7bN96dED2WCyCLYe623ZENfjBh8TdBL0,1432
14
+ openstack_janitor-0.1.0.dist-info/METADATA,sha256=ycQ9HVOCO8JygF34Fetr8IZ_sc0xTzwvnIwXCYm-2kM,4982
15
+ openstack_janitor-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
16
+ openstack_janitor-0.1.0.dist-info/entry_points.txt,sha256=170MubAK5jENHIhjbKdlvefNl7AAI_d9vAGTZBGVLQE,55
17
+ openstack_janitor-0.1.0.dist-info/licenses/LICENSE,sha256=8qKQIlk_rsPJMoEo65z56KU2Njo98LuTfB-SFwSel4c,11347
18
+ openstack_janitor-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ janitor = openstack_janitor.cli:main
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing
141
+ the origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Mohammad AbuNemeh
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.