Source code for jcmsuite.daemon.resources

# SPDX-License-Identifier: MIT
# Copyright (c) 2001-{{ COPYRIGHT_END_YEAR }} JCMwave GmbH

"""Namespaced daemon resource management API."""

from __future__ import annotations

from collections.abc import Iterable
from typing import TYPE_CHECKING, Literal

from ..exceptions import InvalidConfigurationError
from .models import Cluster, DaemonResource, Queue, SlurmNodes, Workstation

if TYPE_CHECKING:
    from .handler import DaemonHandler

ResourceKind = Literal["workstation", "cluster", "queue", "slurm"]


[docs] class DaemonResources: """Resource namespace facade for daemon resource management. Parameters ---------- handler : DaemonHandler Owning daemon handler instance. """ def __init__(self, *, handler: DaemonHandler) -> None: self._handler: DaemonHandler = handler
[docs] def add(self, resource: DaemonResource) -> DaemonResource: """Add one compute resource to the daemon. Parameters ---------- resource : Workstation | Cluster | Queue | SlurmNodes Workstation, cluster, queue, or active SLURM allocation to add. Returns ------- Workstation | Cluster | Queue | SlurmNodes Added resource. Raises ------ InvalidConfigurationError If the resource settings are not valid. """ _validate_resource(resource) return self._handler._add_resource_internal(resource)
[docs] def list( self, *, kind: ResourceKind | None = None, hostname: str | None = None, ) -> tuple[DaemonResource, ...]: """Return registered resources that match the filters. Parameters ---------- kind : {"workstation", "cluster", "queue", "slurm"} | None, optional Resource type to select. If omitted, select all resource types. hostname : str | None, optional Hostname to select. If omitted, select all hostnames. Returns ------- tuple[Workstation | Cluster | Queue | SlurmNodes, ...] Matching resources in registration order. """ resources: tuple[DaemonResource, ...] = tuple(self._handler._resources) filtered_resources: list[DaemonResource] = [ resource for resource in resources if _matches_filters(resource, kind=kind, hostname=hostname) ] return tuple(filtered_resources)
[docs] def info( self, *, kind: ResourceKind | None = None, hostname: str | None = None, ) -> object: """Return information for resources that match the filters. Parameters ---------- kind : {"workstation", "cluster", "queue", "slurm"} | None, optional Resource type to select. If omitted, select all resource types. hostname : str | None, optional Hostname to select. If omitted, select all hostnames. Returns ------- object Information supplied by the daemon. If the handler is not connected, return the matching resource settings. """ resources: tuple[DaemonResource, ...] = tuple(self._handler._resources) matching_indices: list[int] = [ index for index, resource in enumerate(resources) if _matches_filters(resource, kind=kind, hostname=hostname) ] fallback_resources: tuple[DaemonResource, ...] = tuple( resources[index] for index in matching_indices ) return self._handler._resource_info_impl( resource_indices=matching_indices, fallback_resources=fallback_resources, )
[docs] def delete( self, *, kind: ResourceKind | None = None, hostname: str | None = None, allow_many: bool = False, ) -> tuple[DaemonResource, ...]: """Delete resources that match the filters. Parameters ---------- kind : {"workstation", "cluster", "queue", "slurm"} | None, optional Resource type to select. If omitted, select all resource types. hostname : str | None, optional Hostname to select. If omitted, select all hostnames. allow_many : bool, optional If `True`, allow the method to delete multiple matching resources. Returns ------- tuple[Workstation | Cluster | Queue | SlurmNodes, ...] Removed resources in the order in which they were added. Return an empty tuple if no resource matches. Raises ------ InvalidConfigurationError If multiple resources match and `allow_many` is `False`. """ matching_indices: list[int] = [ index for index, resource in enumerate(tuple(self._handler._resources)) if _matches_filters(resource, kind=kind, hostname=hostname) ] if not matching_indices: return () if not allow_many and len(matching_indices) > 1: raise InvalidConfigurationError( "delete() matched multiple resources; set allow_many=True to confirm." ) return self._handler._delete_resources_by_indices(matching_indices)
def _resource_kind(resource: DaemonResource) -> ResourceKind: """Infer the resource kind discriminator for a daemon resource model. Parameters ---------- resource : DaemonResource Resource declaration instance. Returns ------- ResourceKind Canonical kind label used by filtering and delete operations. Notes ----- Internal API: this helper is an implementation detail and may change without notice. """ if isinstance(resource, Workstation): return "workstation" if isinstance(resource, Cluster): return "cluster" if isinstance(resource, SlurmNodes): return "slurm" if isinstance(resource, Queue): return "queue" return "queue" def _resource_hostnames(resource: DaemonResource) -> tuple[str, ...]: """Extract and normalize hostname chains from a daemon resource model. Parameters ---------- resource : DaemonResource Resource declaration instance. Returns ------- tuple[str, ...] Trimmed hostname chain entries for the resource. Notes ----- Internal API: this helper is an implementation detail and may change without notice. """ hostname_value: str | Iterable[str] hostname_value = resource.hostname if isinstance(hostname_value, str): return _split_chain(hostname_value) return tuple(str(entry).strip() for entry in hostname_value if str(entry).strip()) def _matches_filters( resource: DaemonResource, *, kind: ResourceKind | None, hostname: str | None, ) -> bool: """Check whether a resource matches optional kind/hostname filters. Parameters ---------- resource : DaemonResource Resource declaration to evaluate. kind : ResourceKind | None Optional kind filter. hostname : str | None Optional hostname filter. Returns ------- bool True when the expected condition is satisfied. Notes ----- Internal API: this helper is an implementation detail and may change without notice. """ if kind is not None and _resource_kind(resource) != kind: return False if hostname is None: return True normalized_hostname: str = hostname.strip() if not normalized_hostname: return True return normalized_hostname in _resource_hostnames(resource) def _split_chain(value: str) -> tuple[str, ...]: """Split semicolon-separated host strings into normalized entries. Parameters ---------- value : str Raw chain string. Returns ------- tuple[str, ...] Non-empty hostname entries in order. Notes ----- Internal API: this helper is an implementation detail and may change without notice. """ entries: list[str] = [entry.strip() for entry in value.split(";")] non_empty_entries: list[str] = [entry for entry in entries if entry] return tuple(non_empty_entries) def _validate_resource(resource: DaemonResource) -> None: """Validate required invariants on one resource declaration. Parameters ---------- resource : DaemonResource Resource declaration to validate before daemon registration. Returns ------- None Raises when validation fails. Notes ----- Internal API: this helper is an implementation detail and may change without notice. """ hostnames: tuple[str, ...] = _resource_hostnames(resource) if not hostnames: raise InvalidConfigurationError("Resource hostname chain must not be empty.") if resource.multiplicity < 1: raise InvalidConfigurationError("Resource multiplicity must be >= 1.") if isinstance(resource, Workstation): if resource.n_threads < 1: raise InvalidConfigurationError("Workstation n_threads must be >= 1.") _validate_workstation_gpus(resource.gpus) return if isinstance(resource, Cluster): if resource.n_threads < 1: raise InvalidConfigurationError("Cluster n_threads must be >= 1.") if not tuple(resource.nodes): raise InvalidConfigurationError( "Cluster resource must define at least one node." ) for node in resource.nodes: if node.gpu is not None and node.gpu < 0: raise InvalidConfigurationError( "Cluster node gpu must be a non-negative integer." ) return if isinstance(resource, SlurmNodes): return if resource.n_threads < 1: raise InvalidConfigurationError("Queue n_threads must be >= 1.") if resource.queue_type != "slurm": raise InvalidConfigurationError("Only queue_type='slurm' is supported.") if resource.n_gpus is not None and resource.n_gpus < 1: raise InvalidConfigurationError("Queue n_gpus must be >= 1.") if resource.gpu_type is not None and not resource.gpu_type.strip(): raise InvalidConfigurationError("Queue gpu_type must not be blank.") if resource.gres is not None and not resource.gres.strip(): raise InvalidConfigurationError("Queue gres must not be blank.") if ( resource.node_list.strip() and resource.exclude_node.strip() and resource.node_list.strip() == resource.exclude_node.strip() ): raise InvalidConfigurationError( "Queue node_list and exclude_node cannot reference the same value." ) def _validate_workstation_gpus( gpu_value: object, ) -> None: """Validate workstation GPU selection declaration. Parameters ---------- gpu_value : object Raw GPU declaration from `Workstation.gpus`. Returns ------- None Raises when the GPU declaration is invalid. Notes ----- Internal API: this helper is an implementation detail and may change without notice. """ if gpu_value is None: return if isinstance(gpu_value, str): if gpu_value not in {"all", "no"}: raise InvalidConfigurationError( "Workstation gpus string value must be 'all' or 'no'." ) return if isinstance(gpu_value, int): if gpu_value < 0: raise InvalidConfigurationError( "Workstation gpus integer value must be non-negative." ) return if not isinstance(gpu_value, Iterable): raise InvalidConfigurationError( "Workstation gpus must be 'all', 'no', an integer, or a sequence of integers." ) try: gpu_sequence: tuple[object, ...] = tuple(gpu_value) except TypeError as error: raise InvalidConfigurationError( "Workstation gpus must be 'all', 'no', an integer, or a sequence of integers." ) from error if not gpu_sequence: raise InvalidConfigurationError( "Workstation gpus sequence must contain at least one entry." ) entry: object for entry in gpu_sequence: if not isinstance(entry, int) or entry < 0: raise InvalidConfigurationError( "Workstation gpus sequence entries must be non-negative integers." )