Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add WithHistory + fetching history for deleted objects #237

Merged
merged 3 commits into from
May 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 0 additions & 19 deletions mreg_cli/api/abstracts.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
from pydantic.fields import FieldInfo

from mreg_cli.api.endpoints import Endpoint
from mreg_cli.api.history import HistoryItem, HistoryResource
from mreg_cli.exceptions import (
CreateError,
EntityAlreadyExists,
Expand Down Expand Up @@ -508,21 +507,3 @@ def create(
raise CreateError(f"Failed to create {cls} with {params} @ {cls.endpoint()}.")

return None

def history(self, resource: HistoryResource) -> list[HistoryItem]:
"""Get the history of the object.

:param resource: The resource type to get the history for.

:returns: The history of the object.
"""
name = self.id_for_endpoint()
return HistoryItem.get(str(name), resource)

def output_history(self, resource: HistoryResource) -> None:
"""Output the history of the object.

:param resource: The resource type to get the history for.
"""
items = self.history(resource)
HistoryItem.output_multiple(str(self.id_for_endpoint()), items)
59 changes: 54 additions & 5 deletions mreg_cli/api/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,23 @@
import ipaddress
import re
from datetime import date, datetime
from typing import Any, Literal, Self, cast
from typing import Any, ClassVar, Literal, Self, cast

from pydantic import (
AliasChoices,
BaseModel,
ConfigDict,
Field,
computed_field,
field_validator,
model_validator,
)
from typing_extensions import Unpack

from mreg_cli.api.abstracts import APIMixin, FrozenModel, FrozenModelWithTimestamps
from mreg_cli.api.endpoints import Endpoint
from mreg_cli.api.fields import IPAddressField, MACAddressField, NameList
from mreg_cli.api.history import HistoryItem, HistoryResource
from mreg_cli.config import MregCliConfig
from mreg_cli.exceptions import (
CliWarning,
Expand Down Expand Up @@ -334,6 +337,44 @@ def rename(self, new_name: str) -> Self:
return self.patch({self.__name_field__: new_name})


ClassVarNotSet = object()


def AbstractClassVar() -> Any:
"""Hack to implement an abstract class variable on a Pydantic model."""
return ClassVarNotSet


class WithHistory(BaseModel, APIMixin):
"""Resource that supports history lookups.

Subclasses must implement the `history_resource` class variable.
"""

history_resource: ClassVar[HistoryResource] = AbstractClassVar()

def __init_subclass__(cls, **kwargs: Unpack[ConfigDict]):
"""Ensure that subclasses implement the history_resource class var."""
# NOTE: Only works for Pydantic model subclasses!
for attr in cls.__class_vars__:
if getattr(cls, attr) == ClassVarNotSet:
raise NotImplementedError(
f"Subclass {cls.__name__} must implement abstract class var `{attr}`."
)
return super().__init_subclass__(**kwargs)

@classmethod
def get_history(cls, name: str) -> list[HistoryItem]:
"""Get the history for the object."""
return HistoryItem.get(name, cls.history_resource)

@classmethod
def output_history(cls, name: str) -> None:
"""Output the history for the object."""
history = cls.get_history(name)
HistoryItem.output_multiple(name, history)


class NameServer(FrozenModelWithTimestamps, WithTTL):
"""Model for representing a nameserver within a DNS zone."""

Expand Down Expand Up @@ -1068,14 +1109,16 @@ def output(self, padding: int = 14) -> None:
output_manager.add_line(f"{'Description:':<{padding}}{self.description}")


class Role(HostPolicy):
class Role(HostPolicy, WithHistory):
"""Model for a role."""

id: int # noqa: A003
hosts: NameList
atoms: NameList
labels: list[int]

history_resource: ClassVar[HistoryResource] = HistoryResource.HostPolicy_Role

@classmethod
def endpoint(cls) -> Endpoint:
"""Return the endpoint for the class."""
Expand Down Expand Up @@ -1272,12 +1315,14 @@ def delete(self) -> bool:
return super().delete()


class Atom(HostPolicy):
class Atom(HostPolicy, WithHistory):
"""Model for an atom."""

id: int # noqa: A003
roles: NameList

history_resource: ClassVar[HistoryResource] = HistoryResource.HostPolicy_Atom

@classmethod
def endpoint(cls) -> Endpoint:
"""Return the endpoint for the class."""
Expand Down Expand Up @@ -2109,7 +2154,7 @@ def output(self, padding: int = 14):
OutputManager().add_line(f"{'LOC:':<{padding}}{self.loc}")


class Host(FrozenModelWithTimestamps, WithTTL, APIMixin):
class Host(FrozenModelWithTimestamps, WithTTL, WithHistory, APIMixin):
"""Model for an individual host."""

id: int # noqa: A003
Expand All @@ -2129,6 +2174,8 @@ class Host(FrozenModelWithTimestamps, WithTTL, APIMixin):
# Note, we do not use WithZone here as this is optional and we resolve it differently.
zone: int | None = None

history_resource: ClassVar[HistoryResource] = HistoryResource.Host

@field_validator("name", mode="before")
@classmethod
def validate_name(cls, value: str) -> HostT:
Expand Down Expand Up @@ -2819,7 +2866,7 @@ def _format(name: str, contact: str, comment: str) -> None:
_format(str(i.name), i.contact, i.comment or "")


class HostGroup(FrozenModelWithTimestamps, WithName, APIMixin):
class HostGroup(FrozenModelWithTimestamps, WithName, WithHistory, APIMixin):
"""Model for a hostgroup."""

id: int # noqa: A003
Expand All @@ -2830,6 +2877,8 @@ class HostGroup(FrozenModelWithTimestamps, WithName, APIMixin):
hosts: NameList
owners: NameList

history_resource: ClassVar[HistoryResource] = HistoryResource.Group

@classmethod
def endpoint(cls) -> Endpoint:
"""Return the endpoint for the class."""
Expand Down
3 changes: 1 addition & 2 deletions mreg_cli/commands/group.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import argparse
from typing import Any

from mreg_cli.api.history import HistoryResource
from mreg_cli.api.models import Host, HostGroup
from mreg_cli.commands.base import BaseCommand
from mreg_cli.commands.registry import CommandRegistry
Expand Down Expand Up @@ -323,4 +322,4 @@ def history(args: argparse.Namespace) -> None:

:param args: argparse.Namespace (name)
"""
HostGroup.get_by_name_or_raise(args.name).output_history(HistoryResource.Group)
HostGroup.output_history(args.name)
3 changes: 2 additions & 1 deletion mreg_cli/commands/host_submodules/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -494,4 +494,5 @@ def history(args: argparse.Namespace) -> None:

:param args: argparse.Namespace (name)
"""
Host.get_by_any_means_or_raise(args.name).output_history(HistoryResource.Host)
hostname = HostT(hostname=args.name)
pederhan marked this conversation as resolved.
Show resolved Hide resolved
Host.output_history(hostname.hostname)
6 changes: 2 additions & 4 deletions mreg_cli/commands/policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -466,8 +466,7 @@ def atom_history(args: argparse.Namespace) -> None:
"""
name: str = args.name

atom = Atom.get_by_name_or_raise(name)
atom.output_history(HistoryResource.HostPolicy_Atom)
Atom.output_history(name)


@command_registry.register_command(
Expand All @@ -485,5 +484,4 @@ def role_history(args: argparse.Namespace) -> None:
"""
name: str = args.name

role = Role.get_by_name_or_raise(name)
role.output_history(HistoryResource.HostPolicy_Role)
Role.output_history(name)
Loading