From 826149c823c235f2420b64b5a5ad6cdd558af991 Mon Sep 17 00:00:00 2001 From: michael Date: Fri, 20 Nov 2026 10:45:22 +0100 Subject: [PATCH 1/4] feat(credentials): KMS-backed credential store for external systems Groundwork for storage-array plugins (provision/resize/delete LUNs): plugins hold a credential reference and resolve it at call time; secrets never sit in FoundationDB in clear. - KMS: generic secret wrap/unwrap (wrap_secret/unwrap_secret) on all three backends, with a context binding (array identity + endpoint) and an embedded SHA-256 digest -- KMIP wraps with AES-CBC, so the digest is what catches tampering there. ensure_key_encryption_key never replaces an existing KEK (KMIP create was not idempotent). - Vault: read_kv_secret for customer-managed KV v2 secrets; optional credentials_cert_role so a separate Vault policy can cover credentials. - KMIP: get_secret_data for customer-managed SecretData objects. - simplyblock_core.credentials: CredentialProvider with managed refs (wrapped under a per-cluster KEK) and external refs (Vault KV path, KMIP SecretData UID), in-memory TTL cache, invalidate-on-auth-failure. - LocalKMS (no external KMS) only encodes, so credentials are refused unless the cluster opts in via allow_local_kms_credentials. - cluster set: parse bool attributes explicitly; bool("false") was True. Co-Authored-By: Claude Opus 5.5 --- simplyblock_core/cluster_ops.py | 13 +- simplyblock_core/credentials.py | 311 +++++++++++++ simplyblock_core/kms/__init__.py | 12 +- simplyblock_core/kms/_base.py | 87 ++++ simplyblock_core/kms/_fdb.py | 19 + simplyblock_core/kms/_hcp.py | 52 +++ simplyblock_core/kms/_kmip.py | 46 +- simplyblock_core/kms/_settings.py | 5 + simplyblock_core/models/cluster.py | 6 + tests/integration/kms/test_kmip_client.py | 66 +++ tests/unit/test_credentials.py | 516 ++++++++++++++++++++++ 11 files changed, 1128 insertions(+), 5 deletions(-) create mode 100644 simplyblock_core/credentials.py create mode 100644 tests/unit/test_credentials.py diff --git a/simplyblock_core/cluster_ops.py b/simplyblock_core/cluster_ops.py index 0972bbbb5a..8413e2bdc5 100644 --- a/simplyblock_core/cluster_ops.py +++ b/simplyblock_core/cluster_ops.py @@ -4680,7 +4680,18 @@ def set_(cl_id, attr, value) -> bool: cluster.write_to_db() return True else: - value = cluster.get_attrs_map()[attr]['type'](value) + attr_type = cluster.get_attrs_map()[attr]['type'] + if attr_type is bool and isinstance(value, str): + # bool("false") is True; parse the CLI's string form explicitly. + lowered = value.strip().lower() + if lowered in ("1", "true", "yes", "on"): + value = True + elif lowered in ("0", "false", "no", "off"): + value = False + else: + raise ValueError(f"Not a boolean value for {attr}: {value!r}") + else: + value = attr_type(value) logger.info(f"Setting {attr} to {value}") if attr == "two_node_arbitration": set_two_node_arbitration(cl_id, value) diff --git a/simplyblock_core/credentials.py b/simplyblock_core/credentials.py new file mode 100644 index 0000000000..b65103acf2 --- /dev/null +++ b/simplyblock_core/credentials.py @@ -0,0 +1,311 @@ +"""Credentials for external systems (storage arrays, ...), kept out of the database. + +Plugins that drive an external system (provision/resize/delete a LUN on a +storage array, ...) never store or fetch secrets themselves. Their records +hold a :data:`CredentialRef`; at call time they ask a +:class:`CredentialProvider` to resolve it into a :class:`Credential`, which +exists only in memory. + +Two kinds of reference: + +*Managed* (:class:`ManagedCredentialRef`) + simplyblock received the secret (CLI/API) and keeps it wrapped under a + cluster KEK in the cluster's KMS: Vault Transit or a KMIP appliance. Only + the ciphertext is stored, inside the ref. Revoking the KEK in the KMS + makes every managed credential of the cluster unreadable at once. + +*External* (:class:`VaultKVCredentialRef`, :class:`KMIPSecretCredentialRef`) + The customer owns and rotates the secret in their own Vault KV v2 mount or + as a KMIP ``SecretData`` object; simplyblock stores only the pointer. + +Every resolution is bound to a *context* string naming what the credential is +for (e.g. ``"array//https://pure01.example:443"``). A managed credential +carries its context inside the wrapped payload and is refused for any other, +so rewriting an array's endpoint in the database cannot redirect the +credential to another host. An external secret may opt into the same check by +holding a ``_context`` field. + +With no external KMS configured the cluster falls back to ``LocalKMS``, which +only encodes. Managed credentials are then refused unless the cluster has +explicitly opted in via ``Cluster.allow_local_kms_credentials``. + +Resolved credentials are cached in memory for ``ttl_s``. On an authentication +failure from the external system the caller invalidates the ref and resolves +again once, which picks up a rotated external secret without a restart. +""" +from __future__ import annotations + +import json +import logging +import threading +import time +from collections.abc import Callable, Mapping +from typing import TYPE_CHECKING, Annotated, Literal, Union + +from pydantic import BaseModel, ConfigDict, Field, SecretStr, TypeAdapter + +from simplyblock_core.kms import ( + KMS, + HCPClient, + KMIPClient, + KMIPKMSSettings, + KMSException, + VaultKMSSettings, + create_kms_connection, +) + +if TYPE_CHECKING: + from simplyblock_core.models.cluster import Cluster + +logger = logging.getLogger(__name__) + +#: Field an external secret may hold to bind itself to one context. +CONTEXT_FIELD = "_context" + +Backend = Literal["vault", "kmip", "local"] + + +class CredentialError(Exception): + """A credential could not be stored or resolved. Never carries secret values.""" + + +class ManagedCredentialRef(BaseModel): + model_config = ConfigDict(frozen=True, extra="forbid") + + kind: Literal["managed"] = "managed" + #: The KMS backend that wrapped it; a different backend cannot unwrap it. + backend: Backend + kek_name: str = Field(min_length=1) + wrapped: str = Field(min_length=1) + + +class VaultKVCredentialRef(BaseModel): + model_config = ConfigDict(frozen=True, extra="forbid") + + kind: Literal["vault-kv"] = "vault-kv" + mount: str = Field(min_length=1) + path: str = Field(min_length=1) + #: Pin a KV version; ``None`` follows the latest (i.e. picks up rotation). + version: int | None = Field(default=None, ge=1) + + +class KMIPSecretCredentialRef(BaseModel): + model_config = ConfigDict(frozen=True, extra="forbid") + + kind: Literal["kmip-secret"] = "kmip-secret" + uid: str = Field(min_length=1) + #: ``None``: the object's value is a JSON object of string fields. + #: Set: the raw value (UTF-8) is that single field, e.g. ``"password"``. + field: str | None = Field(default=None, min_length=1) + + +CredentialRef = Annotated[ + Union[ManagedCredentialRef, VaultKVCredentialRef, KMIPSecretCredentialRef], + Field(discriminator="kind"), +] +CREDENTIAL_REF_ADAPTER: TypeAdapter[CredentialRef] = TypeAdapter(CredentialRef) + + +class Credential: + """Resolved secret fields, in memory only. ``repr`` shows field names only.""" + + __slots__ = ("_fields",) + + def __init__(self, fields: Mapping[str, SecretStr]): + self._fields = dict(fields) + + @property + def field_names(self) -> frozenset[str]: + return frozenset(self._fields) + + def get(self, name: str) -> SecretStr: + try: + return self._fields[name] + except KeyError: + raise CredentialError( + f"Credential has no field {name!r} (has: {', '.join(sorted(self._fields))})" + ) from None + + def get_optional(self, name: str) -> SecretStr | None: + return self._fields.get(name) + + def __repr__(self) -> str: + return f"Credential(fields={sorted(self._fields)})" + + +def kek_name_for(cluster_id: str) -> str: + """The cluster KEK that wraps managed credentials.""" + return f"credentials-{cluster_id}" + + +def _backend_of(cluster: Cluster) -> Backend: + settings = cluster.get_kms_settings() + if settings is None: + return "local" + if isinstance(settings, VaultKMSSettings): + return "vault" + if isinstance(settings, KMIPKMSSettings): + return "kmip" + raise CredentialError(f"Unsupported KMS settings: {type(settings).__name__}") + + +class CredentialProvider: + """Stores and resolves credentials for one cluster. Thread-safe.""" + + def __init__( + self, + cluster: Cluster, + *, + ttl_s: float = 300.0, + clock: Callable[[], float] = time.monotonic, + kms_factory: Callable[..., KMS] = create_kms_connection, + ): + self._cluster = cluster + self._ttl_s = ttl_s + self._clock = clock + self._kms_factory = kms_factory + self._lock = threading.Lock() + self._cache: dict[tuple[str, str], tuple[float, Credential]] = {} + + # -- KMS access --------------------------------------------------------- + + def _open_kms(self) -> KMS: + backend = _backend_of(self._cluster) + if backend == "local" and not self._cluster.allow_local_kms_credentials: + raise CredentialError( + "No external KMS (Vault or KMIP) is configured for this cluster. " + "Configure one, or explicitly opt in to keeping credentials in the " + "cluster database (effectively unencrypted) by setting " + "allow_local_kms_credentials on the cluster." + ) + cert_role = None + settings = self._cluster.get_kms_settings() + if isinstance(settings, VaultKMSSettings): + cert_role = settings.credentials_cert_role + try: + return self._kms_factory(self._cluster, cert_role=cert_role) + except KMSException as e: + raise CredentialError(f"Cannot connect to the KMS: {e.message}") from e + + # -- Store -------------------------------------------------------------- + + def store( + self, fields: Mapping[str, SecretStr | str], context: str, + ) -> ManagedCredentialRef: + """Wrap ``fields`` under the cluster's credentials KEK, bound to + ``context``. Persist the returned ref; the plaintext is not kept.""" + if not context: + raise CredentialError("A credential needs a non-empty context") + if not fields: + raise CredentialError("Refusing to store an empty credential") + secret_fields = { + name: value if isinstance(value, SecretStr) else SecretStr(value) + for name, value in fields.items() + } + backend = _backend_of(self._cluster) + kek_name = kek_name_for(self._cluster.get_id()) + try: + with self._open_kms() as kms: + kms.ensure_key_encryption_key(kek_name) + wrapped = kms.wrap_secret(kek_name, secret_fields, context) + except KMSException as e: + raise CredentialError(f"Storing credential failed: {e.message}") from e + logger.info("Stored managed credential (backend=%s, fields=%s, context=%s)", + backend, sorted(secret_fields), context) + return ManagedCredentialRef(backend=backend, kek_name=kek_name, wrapped=wrapped) + + # -- Resolve ------------------------------------------------------------ + + @staticmethod + def _cache_key(ref: CredentialRef, context: str) -> tuple[str, str]: + return ref.model_dump_json(), context + + def resolve(self, ref: CredentialRef | Mapping, context: str) -> Credential: + """Return the credential for ``ref``, bound to ``context``.""" + if isinstance(ref, Mapping): + ref = CREDENTIAL_REF_ADAPTER.validate_python(ref) + key = self._cache_key(ref, context) + now = self._clock() + with self._lock: + hit = self._cache.get(key) + if hit is not None and hit[0] > now: + return hit[1] + + credential = self._fetch(ref, context) + + with self._lock: + self._cache[key] = (self._clock() + self._ttl_s, credential) + return credential + + def invalidate(self, ref: CredentialRef | None = None) -> None: + """Drop cached resolutions of ``ref`` (all, if ``None``). Call after + the external system rejected the credential, then resolve once more.""" + with self._lock: + if ref is None: + self._cache.clear() + return + dumped = ref.model_dump_json() + for key in [k for k in self._cache if k[0] == dumped]: + del self._cache[key] + + def _fetch(self, ref: CredentialRef, context: str) -> Credential: + if isinstance(ref, ManagedCredentialRef): + backend = _backend_of(self._cluster) + if ref.backend != backend: + raise CredentialError( + f"Credential was stored with the {ref.backend} KMS backend, but the " + f"cluster now uses {backend}; store it again" + ) + try: + with self._open_kms() as kms: + if isinstance(ref, ManagedCredentialRef): + return Credential(kms.unwrap_secret(ref.kek_name, ref.wrapped, context)) + if isinstance(ref, VaultKVCredentialRef): + if not isinstance(kms, HCPClient): + raise CredentialError( + "A Vault KV credential needs the cluster KMS to be Vault") + fields = kms.read_kv_secret(ref.mount, ref.path, ref.version) + where = f"Vault {ref.mount}/{ref.path}" + else: + if not isinstance(kms, KMIPClient): + raise CredentialError( + "A KMIP secret credential needs the cluster KMS to be KMIP") + fields = self._parse_secret_data(kms.get_secret_data(ref.uid), ref) + where = f"KMIP object {ref.uid}" + except KMSException as e: + raise CredentialError(f"Resolving credential failed: {e.message}") from e + return Credential(self._check_external_context(fields, context, where)) + + @staticmethod + def _parse_secret_data( + raw: bytes, ref: KMIPSecretCredentialRef, + ) -> dict[str, SecretStr]: + try: + text = raw.decode("utf-8") + except UnicodeDecodeError as e: + raise CredentialError(f"KMIP object {ref.uid} is not UTF-8 text") from e + if ref.field is not None: + return {ref.field: SecretStr(text)} + try: + data = json.loads(text) + except ValueError: + data = None + if not isinstance(data, dict) or not data or not all( + isinstance(k, str) and isinstance(v, str) for k, v in data.items() + ): + raise CredentialError( + f"KMIP object {ref.uid} is not a JSON object of string fields; " + "set 'field' on the reference to use its raw value as one field" + ) + return {name: SecretStr(value) for name, value in data.items()} + + @staticmethod + def _check_external_context( + fields: dict[str, SecretStr], context: str, where: str, + ) -> dict[str, SecretStr]: + bound = fields.pop(CONTEXT_FIELD, None) + if bound is not None and bound.get_secret_value() != context: + raise CredentialError(f"Secret at {where} is bound to a different context") + if not fields: + raise CredentialError(f"Secret at {where} has no credential fields") + return fields diff --git a/simplyblock_core/kms/__init__.py b/simplyblock_core/kms/__init__.py index 95b424ffca..f366d00819 100644 --- a/simplyblock_core/kms/__init__.py +++ b/simplyblock_core/kms/__init__.py @@ -17,9 +17,12 @@ __all__ = [ "KMS", + "HCPClient", + "KMIPClient", "KMIPKMSSettings", "KMSException", "KMSSettings", + "LocalKMS", "VaultKMSSettings", "backup_dek_path", "backup_kek_name", @@ -55,7 +58,12 @@ def backup_kek_name(backup_id: str) -> str: return f"backup-{backup_id}" -def create_kms_connection(cluster: "Cluster") -> KMS: +def create_kms_connection(cluster: "Cluster", *, cert_role: str | None = None) -> KMS: + """Open the cluster's KMS backend. + + ``cert_role`` overrides the configured Vault cert-auth role; the other + backends ignore it. + """ kms_settings = cluster.get_kms_settings() if kms_settings is None: return LocalKMS(cluster) @@ -81,7 +89,7 @@ def create_kms_connection(cluster: "Cluster") -> KMS: settings.tls_key, transit_mount=kms_settings.transit_mount, kv_mount=kms_settings.kv_mount, - cert_role=kms_settings.cert_role, + cert_role=cert_role or kms_settings.cert_role, ) return KMIPClient( diff --git a/simplyblock_core/kms/_base.py b/simplyblock_core/kms/_base.py index 1bc6126b9a..93dcbfa4e5 100644 --- a/simplyblock_core/kms/_base.py +++ b/simplyblock_core/kms/_base.py @@ -1,11 +1,22 @@ from __future__ import annotations +import hashlib +import hmac +import json from abc import abstractmethod +from collections.abc import Mapping from contextlib import AbstractContextManager from types import TracebackType from pydantic import SecretStr +from ._exceptions import KMSException + +#: Version of the envelope ``wrap_secret`` produces. Bump on any change to the +#: payload layout; ``unwrap_secret`` refuses versions it does not know. +_SECRET_ENVELOPE_VERSION = 1 +_DIGEST_LEN = hashlib.sha256().digest_size + class KMS(AbstractContextManager): def __exit__( # Has to be defined to make the type-checker happy @@ -49,6 +60,82 @@ def create_key_encryption_key(self, name: str) -> None: ... @abstractmethod def delete_key_encryption_key(self, name: str) -> None: ... + def ensure_key_encryption_key(self, name: str) -> None: + """Create the KEK ``name`` unless it already exists. + + Must never replace an existing key: everything wrapped under it would + become unreadable. Backends whose ``create_key_encryption_key`` is not + already idempotent override this. + """ + self.create_key_encryption_key(name) + + # -- Opaque secrets (credentials for external systems) ------------------ + # + # Unlike data encryption keys these are not random key material but small + # sets of named string fields (username/password, API token, PEM client + # certificate, ...). Only the wrapped form is ever persisted. + + def _wrap_bytes(self, kek_name: str, plaintext: bytes) -> str: + """Encrypt ``plaintext`` under the KEK, returning a storable string.""" + raise NotImplementedError(f"{type(self).__name__} cannot wrap secrets") + + def _unwrap_bytes(self, kek_name: str, wrapped: str) -> bytes: + """Inverse of :meth:`_wrap_bytes`.""" + raise NotImplementedError(f"{type(self).__name__} cannot unwrap secrets") + + def wrap_secret( + self, kek_name: str, fields: Mapping[str, SecretStr], context: str, + ) -> str: + """Wrap ``fields`` under ``kek_name``, bound to ``context``. + + ``context`` names what the secret is *for* (e.g. the external system's + identity and endpoint). :meth:`unwrap_secret` refuses to return the + secret for any other context, so a record whose endpoint was rewritten + in the database cannot be used to send the credential elsewhere. + + A SHA-256 digest of the payload is wrapped together with it. Vault + Transit (AES-GCM) already authenticates its ciphertext; the KMIP + backend wraps with AES-CBC (see ``_kmip.py``), which does not, and the + embedded digest turns blind tampering with that ciphertext into a + refusal instead of a silently altered secret or context. + """ + if not fields: + raise KMSException("Refusing to wrap an empty secret") + payload = json.dumps( + { + "v": _SECRET_ENVELOPE_VERSION, + "ctx": context, + "fields": {name: value.get_secret_value() for name, value in fields.items()}, + }, + sort_keys=True, separators=(",", ":"), + ).encode() + return self._wrap_bytes(kek_name, hashlib.sha256(payload).digest() + payload) + + def unwrap_secret( + self, kek_name: str, wrapped: str, context: str, + ) -> dict[str, SecretStr]: + """Inverse of :meth:`wrap_secret`; ``context`` must match exactly.""" + blob = self._unwrap_bytes(kek_name, wrapped) + digest, payload = blob[:_DIGEST_LEN], blob[_DIGEST_LEN:] + if len(digest) != _DIGEST_LEN or not hmac.compare_digest( + digest, hashlib.sha256(payload).digest(), + ): + raise KMSException("Wrapped secret failed its integrity check") + try: + data = json.loads(payload) + except ValueError as e: + raise KMSException("Wrapped secret is not valid") from e + if not isinstance(data, dict) or data.get("v") != _SECRET_ENVELOPE_VERSION: + raise KMSException("Wrapped secret has an unsupported format") + if not hmac.compare_digest(str(data.get("ctx", "")).encode(), context.encode()): + raise KMSException("Wrapped secret is bound to a different context") + fields = data.get("fields") + if not isinstance(fields, dict) or not fields or not all( + isinstance(k, str) and isinstance(v, str) for k, v in fields.items() + ): + raise KMSException("Wrapped secret is not valid") + return {name: SecretStr(value) for name, value in fields.items()} + # Generic secrets: a flat ``{name: value}`` dict stored at ``path`` (array # credentials, see simplyblock_core.array). Values go in as ``SecretStr`` # (plain strings are wrapped) and come back as ``SecretStr``; only the diff --git a/simplyblock_core/kms/_fdb.py b/simplyblock_core/kms/_fdb.py index 99bc1f362f..f2b94c07e0 100644 --- a/simplyblock_core/kms/_fdb.py +++ b/simplyblock_core/kms/_fdb.py @@ -1,3 +1,5 @@ +import base64 +import binascii import json from typing import TYPE_CHECKING @@ -79,3 +81,20 @@ def get_secret(self, path: str) -> dict: def delete_secret(self, path: str) -> None: self._kv_store.clear(self._secret_key(path)) + + # There is no KEK here: the "wrapped" form is only encoded, not encrypted, + # so a secret wrapped by LocalKMS is effectively plaintext in FoundationDB. + # Credential storage gates this behind an explicit per-cluster opt-in + # (see simplyblock_core.credentials). + _LOCAL_PREFIX = "local:" + + def _wrap_bytes(self, kek_name: str, plaintext: bytes) -> str: + return self._LOCAL_PREFIX + base64.b64encode(plaintext).decode() + + def _unwrap_bytes(self, kek_name: str, wrapped: str) -> bytes: + if not wrapped.startswith(self._LOCAL_PREFIX): + raise KMSException("Wrapped secret was not produced by the local KMS") + try: + return base64.b64decode(wrapped[len(self._LOCAL_PREFIX):], validate=True) + except binascii.Error as e: + raise KMSException("Wrapped secret is not valid") from e diff --git a/simplyblock_core/kms/_hcp.py b/simplyblock_core/kms/_hcp.py index eada641254..593b22b918 100644 --- a/simplyblock_core/kms/_hcp.py +++ b/simplyblock_core/kms/_hcp.py @@ -170,3 +170,55 @@ def delete_secret(self, path: str) -> None: return except hvac.exceptions.VaultError as e: raise KMSException("Request failed") from e + + def ensure_key_encryption_key(self, name: str) -> None: + try: + self.client.secrets.transit.read_key(name=name, mount_point=self.transit_mount) + return + except hvac.exceptions.InvalidPath: + pass + except hvac.exceptions.VaultError as e: + raise KMSException("Request failed") from e + self.create_key_encryption_key(name) + + def _wrap_bytes(self, kek_name: str, plaintext: bytes) -> str: + try: + return self.client.secrets.transit.encrypt_data( + name=kek_name, plaintext=base64.b64encode(plaintext).decode(), + mount_point=self.transit_mount, + )['data']['ciphertext'] + except hvac.exceptions.VaultError as e: + raise KMSException("Request failed") from e + + def _unwrap_bytes(self, kek_name: str, wrapped: str) -> bytes: + try: + plaintext_b64 = self.client.secrets.transit.decrypt_data( + name=kek_name, ciphertext=wrapped, mount_point=self.transit_mount, + )['data']['plaintext'] + except hvac.exceptions.VaultError as e: + raise KMSException("Request failed") from e + return base64.b64decode(plaintext_b64) + + def read_kv_secret( + self, mount: str, path: str, version: int | None = None, + ) -> dict[str, SecretStr]: + """Read a customer-managed KV v2 secret as named string fields. + + Errors name the path and field names, never values. + """ + try: + data = self.client.secrets.kv.v2.read_secret_version( + path=path, mount_point=mount, version=version, + raise_on_deleted_version=True, + )['data']['data'] + except hvac.exceptions.InvalidPath as e: + raise KMSException(f"No secret at {mount}/{path}") from e + except hvac.exceptions.VaultError as e: + raise KMSException("Request failed") from e + if not isinstance(data, dict) or not data: + raise KMSException(f"Secret at {mount}/{path} is empty") + bad = sorted(name for name, value in data.items() if not isinstance(value, str)) + if bad: + raise KMSException( + f"Secret at {mount}/{path} has non-string fields: {', '.join(bad)}") + return {name: SecretStr(value) for name, value in data.items()} diff --git a/simplyblock_core/kms/_kmip.py b/simplyblock_core/kms/_kmip.py index cf1d472300..ffa0bb3d4a 100644 --- a/simplyblock_core/kms/_kmip.py +++ b/simplyblock_core/kms/_kmip.py @@ -3,6 +3,7 @@ from kmip.core import enums from kmip.pie import exceptions as kmip_exceptions +from kmip.pie import objects as kmip_objects from kmip.pie.client import ProxyKmipClient from pydantic import SecretStr @@ -133,9 +134,12 @@ def delete_key_encryption_key(self, name: str) -> None: kv_store.clear(self._kek_key(name)) def _encrypt(self, kek_uid: str, plaintext_hex: SecretStr) -> dict: + return self._encrypt_bytes(kek_uid, bytes.fromhex(plaintext_hex.get_secret_value())) + + def _encrypt_bytes(self, kek_uid: str, plaintext: bytes) -> dict: try: ciphertext, iv_counter_nonce = self.client.encrypt( - bytes.fromhex(plaintext_hex.get_secret_value()), + plaintext, uid=kek_uid, cryptographic_parameters=dict(_CRYPTOGRAPHIC_PARAMETERS), ) @@ -147,6 +151,9 @@ def _encrypt(self, kek_uid: str, plaintext_hex: SecretStr) -> dict: } def _decrypt(self, kek_uid: str, wrapped: dict) -> SecretStr: + return SecretStr(self._decrypt_bytes(kek_uid, wrapped).hex()) + + def _decrypt_bytes(self, kek_uid: str, wrapped: dict) -> bytes: try: plaintext = self.client.decrypt( bytes.fromhex(wrapped["ciphertext"]), @@ -156,7 +163,7 @@ def _decrypt(self, kek_uid: str, wrapped: dict) -> SecretStr: ) except _KMIP_ERRORS as e: raise KMSException("Request failed") from e - return SecretStr(plaintext.hex()) + return plaintext def create_data_encryption_keys(self, path: str, kek_name: str) -> None: self.import_data_encryption_keys( @@ -200,3 +207,38 @@ def get_secret(self, path: str) -> dict: def delete_secret(self, path: str) -> None: raise KMSException(self._NO_SECRETS) + + def ensure_key_encryption_key(self, name: str) -> None: + # create_key_encryption_key always mints a new appliance key and + # repoints the name at it, which would orphan everything already + # wrapped under the old one. + if self._kv_store().get(self._kek_key(name)): + return + self.create_key_encryption_key(name) + + def _wrap_bytes(self, kek_name: str, plaintext: bytes) -> str: + return json.dumps(self._encrypt_bytes(self._kek_uid(kek_name), plaintext)) + + def _unwrap_bytes(self, kek_name: str, wrapped: str) -> bytes: + try: + parsed = json.loads(wrapped) + if not isinstance(parsed, dict) or "ciphertext" not in parsed: + raise ValueError("not a wrapped KMIP record") + return self._decrypt_bytes(self._kek_uid(kek_name), parsed) + except ValueError as e: # bad JSON, or bytes.fromhex on a corrupted record + raise KMSException("Wrapped secret is not valid") from e + + def get_secret_data(self, uid: str) -> bytes: + """Fetch a customer-managed KMIP ``SecretData`` object's raw value. + + Support for ``SecretData`` varies between appliances (some only manage + keys); a server that refuses it surfaces as ``KMSException``. + """ + try: + obj = self.client.get(uid) + except _KMIP_ERRORS as e: + raise KMSException(f"Could not fetch KMIP object {uid}") from e + if not isinstance(obj, kmip_objects.SecretData): + raise KMSException( + f"KMIP object {uid} is a {type(obj).__name__}, not SecretData") + return bytes(obj.value) diff --git a/simplyblock_core/kms/_settings.py b/simplyblock_core/kms/_settings.py index ca1c92d992..fa9ebf21d9 100644 --- a/simplyblock_core/kms/_settings.py +++ b/simplyblock_core/kms/_settings.py @@ -29,6 +29,11 @@ class VaultKMSSettings(BaseModel): transit_mount: str = "simplyblock/transit" kv_mount: str = "simplyblock/kv" cert_role: str = "simplyblock-webappapi" + #: Vault cert-auth role used for credentials of external systems (storage + #: arrays, ...) instead of ``cert_role``, so a Vault policy can grant those + #: paths separately from volume encryption keys. ``None`` reuses + #: ``cert_role``. + credentials_cert_role: str | None = None #: Same convention as BackupLocation._serialize_endpoint: the field owns #: its own JSON-safety, so plain model_dump() is enough here too. diff --git a/simplyblock_core/models/cluster.py b/simplyblock_core/models/cluster.py index 283a3fda6b..ae0c5f40a5 100644 --- a/simplyblock_core/models/cluster.py +++ b/simplyblock_core/models/cluster.py @@ -463,6 +463,12 @@ def is_topology_owned(self) -> bool: # migration for every create/update. Empty dict = no external KMS (LocalKMS). kms_settings: dict = default_factory(dict) hashicorp_vault_settings: HashicorpVaultSettings | None = None + # Explicit opt-in to keep credentials for external systems (storage + # arrays, ...) with no external KMS configured. LocalKMS only encodes, so + # such credentials would sit effectively in plaintext in FoundationDB; + # without this flag simplyblock_core.credentials refuses to store or read + # them unless a Vault or KMIP backend is configured. + allow_local_kms_credentials: bool = False # Single-node-expansion resumability cursor. Empty dict means no expansion # is in flight. Populated/advanced/cleared via the helpers in diff --git a/tests/integration/kms/test_kmip_client.py b/tests/integration/kms/test_kmip_client.py index e37470362a..e817737659 100644 --- a/tests/integration/kms/test_kmip_client.py +++ b/tests/integration/kms/test_kmip_client.py @@ -114,3 +114,69 @@ def test_rekey_moves_keys_to_a_new_kek_and_path(kmip_client): def test_delete_key_encryption_key_of_an_unknown_name_is_a_no_op(kmip_client): kmip_client.delete_key_encryption_key(_unique("kek")) + + +# -- Opaque secrets (credentials for external systems) ---------------------- + +_CTX = "array/a1/https://pure01.example:443" + + +def test_wrap_secret_round_trip(kmip_client): + kek_name = _unique("kek") + kmip_client.ensure_key_encryption_key(kek_name) + try: + wrapped = kmip_client.wrap_secret( + kek_name, {"username": SecretStr("u"), "password": SecretStr("p")}, _CTX) + fields = kmip_client.unwrap_secret(kek_name, wrapped, _CTX) + assert {k: v.get_secret_value() for k, v in fields.items()} == { + "username": "u", "password": "p"} + with pytest.raises(KMSException, match="different context"): + kmip_client.unwrap_secret(kek_name, wrapped, "array/a1/https://evil.example:443") + finally: + kmip_client.delete_key_encryption_key(kek_name) + + +def test_ensure_key_encryption_key_keeps_existing_key(kmip_client): + kek_name = _unique("kek") + kmip_client.ensure_key_encryption_key(kek_name) + try: + wrapped = kmip_client.wrap_secret(kek_name, {"a": SecretStr("b")}, _CTX) + kmip_client.ensure_key_encryption_key(kek_name) + assert kmip_client.unwrap_secret(kek_name, wrapped, _CTX)["a"].get_secret_value() == "b" + finally: + kmip_client.delete_key_encryption_key(kek_name) + + +@pytest.fixture() +def kmip_client_no_fdb(pykmip_server): + """SecretData Get never touches FoundationDB.""" + client = KMIPClient( + pykmip_server.server_url, + pykmip_server.ca, pykmip_server.certificate, pykmip_server.key, + ) + with client: + yield client + + +def test_get_secret_data_returns_customer_secret(kmip_client_no_fdb): + from kmip.core import enums + from kmip.pie import objects + + value = b'{"username": "u", "password": "p"}' + uid = kmip_client_no_fdb.client.register( + objects.SecretData(value, enums.SecretDataType.PASSWORD)) + try: + assert kmip_client_no_fdb.get_secret_data(uid) == value + finally: + kmip_client_no_fdb.client.destroy(uid) + + +def test_get_secret_data_refuses_a_key_object(kmip_client_no_fdb): + from kmip.core import enums + + uid = kmip_client_no_fdb.client.create(enums.CryptographicAlgorithm.AES, 256) + try: + with pytest.raises(KMSException, match="not SecretData"): + kmip_client_no_fdb.get_secret_data(uid) + finally: + kmip_client_no_fdb.client.destroy(uid) diff --git a/tests/unit/test_credentials.py b/tests/unit/test_credentials.py new file mode 100644 index 0000000000..5761f9920e --- /dev/null +++ b/tests/unit/test_credentials.py @@ -0,0 +1,516 @@ +"""Credentials for external systems: KMS secret envelope + CredentialProvider.""" +import base64 +import json +from unittest.mock import MagicMock + +import hvac.exceptions +import pytest +from kmip.core import enums +from kmip.pie import objects as kmip_objects +from pydantic import SecretStr + +from simplyblock_core.credentials import ( + CONTEXT_FIELD, + Credential, + CredentialError, + CredentialProvider, + KMIPSecretCredentialRef, + ManagedCredentialRef, + VaultKVCredentialRef, + kek_name_for, +) +from simplyblock_core.kms import KMS, HCPClient, KMIPClient, KMSException, LocalKMS +from simplyblock_core.models.cluster import Cluster + +CTX = "array/a1/https://pure01.example:443" + + +class FakeKMS(KMS): + """Reversible, keyed 'encryption' so tests can see wrong-key failures.""" + + def __init__(self): + self.keks: set[str] = set() + self.created: list[str] = [] + + def create_data_encryption_keys(self, path, kek_name): ... + def import_data_encryption_keys(self, path, kek_name, keys): ... + def get_data_encryption_keys(self, path, kek_name): ... + def delete_data_encryption_keys(self, path): ... + + def create_key_encryption_key(self, name): + self.created.append(name) + self.keks.add(name) + + def delete_key_encryption_key(self, name): + self.keks.discard(name) + + def ensure_key_encryption_key(self, name): + if name not in self.keks: + self.create_key_encryption_key(name) + + def _wrap_bytes(self, kek_name, plaintext): + if kek_name not in self.keks: + raise KMSException("no such KEK") + return base64.b64encode(kek_name.encode() + b"|" + plaintext).decode() + + def _unwrap_bytes(self, kek_name, wrapped): + if kek_name not in self.keks: + raise KMSException("no such KEK") + prefix, _, plaintext = base64.b64decode(wrapped).partition(b"|") + if prefix != kek_name.encode(): + raise KMSException("wrong KEK") + return plaintext + + +def _fields(**kw): + return {k: SecretStr(v) for k, v in kw.items()} + + +def _plain(fields): + return {k: v.get_secret_value() for k, v in fields.items()} + + +# -- Envelope (KMS.wrap_secret / unwrap_secret) ----------------------------- + +class TestEnvelope: + + def setup_method(self): + self.kms = FakeKMS() + self.kms.create_key_encryption_key("k") + + def test_round_trip(self): + wrapped = self.kms.wrap_secret("k", _fields(username="u", password="p"), CTX) + assert _plain(self.kms.unwrap_secret("k", wrapped, CTX)) == { + "username": "u", "password": "p"} + + def test_other_context_is_refused(self): + wrapped = self.kms.wrap_secret("k", _fields(password="p"), CTX) + with pytest.raises(KMSException, match="different context"): + self.kms.unwrap_secret("k", wrapped, "array/a1/https://evil.example:443") + + def test_tampered_payload_is_refused(self): + wrapped = self.kms.wrap_secret("k", _fields(password="p"), CTX) + raw = bytearray(base64.b64decode(wrapped)) + raw[-3] ^= 0x01 # inside the JSON payload, after the digest + with pytest.raises(KMSException, match="integrity"): + self.kms.unwrap_secret("k", base64.b64encode(bytes(raw)).decode(), CTX) + + def test_truncated_blob_is_refused(self): + wrapped = base64.b64encode(b"k|short").decode() + with pytest.raises(KMSException, match="integrity"): + self.kms.unwrap_secret("k", wrapped, CTX) + + def test_unknown_version_is_refused(self): + import hashlib + payload = json.dumps({"v": 99, "ctx": CTX, "fields": {"a": "b"}}).encode() + wrapped = self.kms._wrap_bytes("k", hashlib.sha256(payload).digest() + payload) + with pytest.raises(KMSException, match="unsupported format"): + self.kms.unwrap_secret("k", wrapped, CTX) + + def test_empty_secret_is_refused(self): + with pytest.raises(KMSException): + self.kms.wrap_secret("k", {}, CTX) + + def test_backend_without_wrap_support_says_so(self): + class NoWrap(FakeKMS): + _wrap_bytes = KMS._wrap_bytes + with pytest.raises(NotImplementedError, match="cannot wrap"): + NoWrap().wrap_secret("k", _fields(a="b"), CTX) + + +# -- Backends --------------------------------------------------------------- + +class TestLocalKMSWrapping: + + def _kms(self): + return object.__new__(LocalKMS) # no FDB needed for wrap/unwrap + + def test_round_trip(self): + kms = self._kms() + wrapped = kms.wrap_secret("ignored", _fields(token="t"), CTX) + assert wrapped.startswith("local:") + assert _plain(kms.unwrap_secret("ignored", wrapped, CTX)) == {"token": "t"} + + def test_foreign_ciphertext_is_refused(self): + with pytest.raises(KMSException, match="local KMS"): + self._kms().unwrap_secret("k", "vault:v1:abc", CTX) + + def test_corrupt_encoding_is_refused(self): + with pytest.raises(KMSException): + self._kms().unwrap_secret("k", "local:!!!", CTX) + + +class _FakeKVStore: + def __init__(self): + self.data = {} + + def get(self, key): + return self.data.get(key) + + def set(self, key, value): + self.data[key] = value + + def clear(self, key): + self.data.pop(key, None) + + +@pytest.fixture() +def kmip(monkeypatch): + client = object.__new__(KMIPClient) + client.client = MagicMock() + kv = _FakeKVStore() + monkeypatch.setattr(KMIPClient, "_kv_store", staticmethod(lambda: kv)) + uids = iter(f"uid-{i}" for i in range(100)) + client.client.create.side_effect = lambda *a, **k: next(uids) + client.client.encrypt.side_effect = lambda data, **k: (bytes(b ^ 0x5A for b in data), b"\x01" * 16) + client.client.decrypt.side_effect = lambda data, **k: bytes(b ^ 0x5A for b in data) + return client, kv + + +class TestKMIPWrapping: + + def test_round_trip(self, kmip): + client, _ = kmip + client.ensure_key_encryption_key("k") + wrapped = client.wrap_secret("k", _fields(password="p"), CTX) + assert json.loads(wrapped)["iv"] == "01" * 16 + assert _plain(client.unwrap_secret("k", wrapped, CTX)) == {"password": "p"} + + def test_ensure_does_not_replace_existing_kek(self, kmip): + client, kv = kmip + client.ensure_key_encryption_key("k") + client.ensure_key_encryption_key("k") + assert client.client.create.call_count == 1 + assert kv.get(b"kms/kmip/kek/k") == b"uid-0" + + def test_cbc_bit_flip_is_caught_by_digest(self, kmip): + client, _ = kmip + client.ensure_key_encryption_key("k") + record = json.loads(client.wrap_secret("k", _fields(password="p"), CTX)) + ct = bytearray.fromhex(record["ciphertext"]) + ct[40] ^= 0x01 + record["ciphertext"] = ct.hex() + with pytest.raises(KMSException, match="integrity"): + client.unwrap_secret("k", json.dumps(record), CTX) + + def test_garbage_record_is_refused(self, kmip): + client, _ = kmip + client.ensure_key_encryption_key("k") + for bad in ("not json", "[]", '{"ciphertext": "zz"}'): + with pytest.raises(KMSException, match="not valid"): + client.unwrap_secret("k", bad, CTX) + + def test_get_secret_data(self, kmip): + client, _ = kmip + client.client.get.return_value = kmip_objects.SecretData( + b'{"password": "p"}', enums.SecretDataType.PASSWORD) + assert client.get_secret_data("u1") == b'{"password": "p"}' + + def test_get_secret_data_refuses_keys(self, kmip): + client, _ = kmip + client.client.get.return_value = kmip_objects.SymmetricKey( + enums.CryptographicAlgorithm.AES, 128, b"\x00" * 16) + with pytest.raises(KMSException, match="not SecretData"): + client.get_secret_data("u1") + + +@pytest.fixture() +def vault(): + client = object.__new__(HCPClient) + client.client = MagicMock() + client.transit_mount = "t" + client.kv_mount = "kv" + return client + + +class TestVault: + + def test_ensure_creates_only_when_missing(self, vault): + transit = vault.client.secrets.transit + transit.read_key.side_effect = hvac.exceptions.InvalidPath() + vault.ensure_key_encryption_key("k") + transit.create_key.assert_called_once() + + transit.reset_mock() + transit.read_key.side_effect = None + vault.ensure_key_encryption_key("k") + transit.create_key.assert_not_called() + + def test_wrap_uses_transit(self, vault): + transit = vault.client.secrets.transit + store = {} + transit.encrypt_data.side_effect = lambda name, plaintext, mount_point: ( + store.setdefault("pt", plaintext), {"data": {"ciphertext": "vault:v1:x"}})[1] + transit.decrypt_data.side_effect = lambda name, ciphertext, mount_point: { + "data": {"plaintext": store["pt"]}} + wrapped = vault.wrap_secret("k", _fields(password="p"), CTX) + assert wrapped == "vault:v1:x" + assert _plain(vault.unwrap_secret("k", wrapped, CTX)) == {"password": "p"} + + def test_read_kv_secret(self, vault): + vault.client.secrets.kv.v2.read_secret_version.return_value = { + "data": {"data": {"username": "u", "password": "p"}}} + assert _plain(vault.read_kv_secret("arrays", "pure01")) == { + "username": "u", "password": "p"} + + def test_read_kv_secret_refuses_non_string_fields_without_values(self, vault): + vault.client.secrets.kv.v2.read_secret_version.return_value = { + "data": {"data": {"password": "hunter2", "port": 443}}} + with pytest.raises(KMSException) as e: + vault.read_kv_secret("arrays", "pure01") + assert "port" in e.value.message and "hunter2" not in e.value.message + + def test_read_kv_secret_missing(self, vault): + vault.client.secrets.kv.v2.read_secret_version.side_effect = hvac.exceptions.InvalidPath() + with pytest.raises(KMSException, match="No secret"): + vault.read_kv_secret("arrays", "nope") + + +# -- CredentialProvider ----------------------------------------------------- + +def _cluster(kms_settings=None, allow_local=False): + cluster = Cluster() + cluster.uuid = "c1" + cluster.set_kms_settings(kms_settings) + cluster.allow_local_kms_credentials = allow_local + return cluster + + +VAULT = {"provider": "vault", "base_url": "https://vault.example:8200"} +KMIP = {"provider": "kmip", "server_url": "kmip.example:5696"} + + +class Clock: + def __init__(self): + self.t = 1000.0 + + def __call__(self): + return self.t + + +def _provider(cluster, kms, clock=None): + factory = MagicMock(return_value=kms) + provider = CredentialProvider(cluster, kms_factory=factory, clock=clock or Clock()) + return provider, factory + + +class TestOptIn: + + def test_local_kms_is_refused_without_opt_in(self): + provider, factory = _provider(_cluster(), FakeKMS()) + with pytest.raises(CredentialError, match="opt in"): + provider.store({"password": "p"}, CTX) + factory.assert_not_called() + + def test_local_kms_refuses_resolve_after_opt_in_is_withdrawn(self): + cluster = _cluster(allow_local=True) + provider, _ = _provider(cluster, FakeKMS()) + ref = provider.store({"password": "p"}, CTX) + cluster.allow_local_kms_credentials = False + with pytest.raises(CredentialError, match="opt in"): + CredentialProvider(cluster, kms_factory=MagicMock(return_value=FakeKMS())).resolve(ref, CTX) + + def test_local_kms_works_with_opt_in(self): + provider, _ = _provider(_cluster(allow_local=True), FakeKMS()) + ref = provider.store({"password": "p"}, CTX) + assert ref.backend == "local" + assert provider.resolve(ref, CTX).get("password").get_secret_value() == "p" + + def test_cluster_default_is_no_opt_in(self): + assert Cluster().allow_local_kms_credentials is False + + +class TestManaged: + + def test_store_and_resolve_round_trip(self): + kms = FakeKMS() + provider, factory = _provider(_cluster(VAULT), kms) + ref = provider.store({"username": "u", "password": SecretStr("hunter2")}, CTX) + assert ref == ManagedCredentialRef( + backend="vault", kek_name=kek_name_for("c1"), wrapped=ref.wrapped) + assert kms.created == ["credentials-c1"] + cred = provider.resolve(ref.model_dump(), CTX) # dict form, as stored in FDB + assert cred.get("password").get_secret_value() == "hunter2" + assert "hunter2" not in repr(cred) + + def test_kek_is_reused(self): + kms = FakeKMS() + provider, _ = _provider(_cluster(VAULT), kms) + provider.store({"a": "1"}, CTX) + provider.store({"a": "2"}, CTX) + assert kms.created == ["credentials-c1"] + + def test_other_context_is_refused(self): + provider, _ = _provider(_cluster(KMIP), FakeKMS()) + ref = provider.store({"password": "p"}, CTX) + with pytest.raises(CredentialError, match="different context"): + provider.resolve(ref, "array/a1/https://evil.example:443") + + def test_backend_change_is_reported(self): + kms = FakeKMS() + provider, _ = _provider(_cluster(VAULT), kms) + ref = provider.store({"password": "p"}, CTX) + provider2, _ = _provider(_cluster(KMIP), kms) + with pytest.raises(CredentialError, match="stored with the vault"): + provider2.resolve(ref, CTX) + + def test_empty_inputs_are_refused(self): + provider, _ = _provider(_cluster(VAULT), FakeKMS()) + with pytest.raises(CredentialError): + provider.store({}, CTX) + with pytest.raises(CredentialError): + provider.store({"a": "b"}, "") + + def test_credentials_cert_role_is_used(self): + settings = dict(VAULT, credentials_cert_role="simplyblock-credentials") + provider, factory = _provider(_cluster(settings), FakeKMS()) + provider.store({"a": "b"}, CTX) + assert factory.call_args.kwargs == {"cert_role": "simplyblock-credentials"} + + def test_kms_connection_failure_is_wrapped(self): + provider = CredentialProvider( + _cluster(VAULT), kms_factory=MagicMock(side_effect=KMSException("Authentication failed"))) + with pytest.raises(CredentialError, match="Authentication failed"): + provider.store({"a": "b"}, CTX) + + +class TestCache: + + def test_ttl_and_invalidate(self): + kms = FakeKMS() + clock = Clock() + provider, factory = _provider(_cluster(VAULT), kms, clock) + ref = provider.store({"a": "b"}, CTX) + factory.reset_mock() + + provider.resolve(ref, CTX) + provider.resolve(ref, CTX) + assert factory.call_count == 1 + + clock.t += 301 + provider.resolve(ref, CTX) + assert factory.call_count == 2 + + provider.invalidate(ref) + provider.resolve(ref, CTX) + assert factory.call_count == 3 + + provider.invalidate() + provider.resolve(ref, CTX) + assert factory.call_count == 4 + + def test_cache_is_per_context(self): + provider, _ = _provider(_cluster(VAULT), FakeKMS()) + ref = provider.store({"a": "b"}, CTX) + provider.resolve(ref, CTX) + with pytest.raises(CredentialError): + provider.resolve(ref, "other") + + +class TestExternal: + + def _vault_kms(self, data): + kms = MagicMock(spec=HCPClient) + kms.__enter__.return_value = kms + kms.read_kv_secret.return_value = {k: SecretStr(v) for k, v in data.items()} + return kms + + def _kmip_kms(self, raw): + kms = MagicMock(spec=KMIPClient) + kms.__enter__.return_value = kms + kms.get_secret_data.return_value = raw + return kms + + def test_vault_kv(self): + kms = self._vault_kms({"username": "u", "password": "p"}) + provider, _ = _provider(_cluster(VAULT), kms) + ref = VaultKVCredentialRef(mount="customer-kv", path="arrays/pure01", version=3) + cred = provider.resolve(ref, CTX) + assert cred.field_names == {"username", "password"} + kms.read_kv_secret.assert_called_once_with("customer-kv", "arrays/pure01", 3) + + def test_vault_kv_context_field(self): + provider, _ = _provider( + _cluster(VAULT), self._vault_kms({"password": "p", CONTEXT_FIELD: CTX})) + assert provider.resolve( + VaultKVCredentialRef(mount="m", path="p"), CTX).field_names == {"password"} + + provider, _ = _provider( + _cluster(VAULT), self._vault_kms({"password": "p", CONTEXT_FIELD: "other"})) + with pytest.raises(CredentialError, match="different context"): + provider.resolve(VaultKVCredentialRef(mount="m", path="p"), CTX) + + def test_vault_kv_needs_vault(self): + provider, _ = _provider(_cluster(KMIP), self._kmip_kms(b"{}")) + with pytest.raises(CredentialError, match="needs the cluster KMS to be Vault"): + provider.resolve(VaultKVCredentialRef(mount="m", path="p"), CTX) + + def test_kmip_json_object(self): + provider, _ = _provider( + _cluster(KMIP), self._kmip_kms(b'{"username": "u", "password": "p"}')) + cred = provider.resolve({"kind": "kmip-secret", "uid": "42"}, CTX) + assert cred.get("password").get_secret_value() == "p" + + def test_kmip_raw_value_as_field(self): + provider, _ = _provider(_cluster(KMIP), self._kmip_kms(b"s3cr3t")) + cred = provider.resolve(KMIPSecretCredentialRef(uid="42", field="api_token"), CTX) + assert cred.get("api_token").get_secret_value() == "s3cr3t" + + def test_kmip_raw_value_without_field_is_refused(self): + provider, _ = _provider(_cluster(KMIP), self._kmip_kms(b"s3cr3t")) + with pytest.raises(CredentialError, match="set 'field'") as e: + provider.resolve(KMIPSecretCredentialRef(uid="42"), CTX) + assert "s3cr3t" not in str(e.value) + + def test_kmip_needs_kmip(self): + provider, _ = _provider(_cluster(VAULT), self._vault_kms({"a": "b"})) + with pytest.raises(CredentialError, match="needs the cluster KMS to be KMIP"): + provider.resolve(KMIPSecretCredentialRef(uid="42"), CTX) + + def test_external_refs_refused_under_local_kms_without_opt_in(self): + provider, _ = _provider(_cluster(), FakeKMS()) + with pytest.raises(CredentialError, match="opt in"): + provider.resolve(VaultKVCredentialRef(mount="m", path="p"), CTX) + + +def test_credential_missing_field_names_fields_not_values(): + cred = Credential(_fields(username="u", password="hunter2")) + with pytest.raises(CredentialError) as e: + cred.get("token") + assert "password" in str(e.value) and "hunter2" not in str(e.value) + + +# -- cluster set: bool parsing --------------------------------------------- + +@pytest.mark.parametrize("raw, expected", [ + ("true", True), ("True", True), ("1", True), ("yes", True), + ("false", False), ("False", False), ("0", False), ("off", False), +]) +def test_cluster_set_parses_bools(monkeypatch, raw, expected): + from simplyblock_core import cluster_ops + + cluster = Cluster() + cluster.allow_local_kms_credentials = not expected + cluster.write_to_db = MagicMock() + db = MagicMock() + db.get_cluster_by_id.return_value = cluster + monkeypatch.setattr(cluster_ops, "db_controller", db) + + cluster_ops.set_("c1", "allow_local_kms_credentials", raw) + + assert cluster.allow_local_kms_credentials is expected + cluster.write_to_db.assert_called_once() + + +def test_cluster_set_rejects_non_bool(monkeypatch): + from simplyblock_core import cluster_ops + + cluster = Cluster() + cluster.write_to_db = MagicMock() + db = MagicMock() + db.get_cluster_by_id.return_value = cluster + monkeypatch.setattr(cluster_ops, "db_controller", db) + + with pytest.raises(ValueError): + cluster_ops.set_("c1", "allow_local_kms_credentials", "maybe") + cluster.write_to_db.assert_not_called() From 00b47151e262c1484dd307b68bbe90fae6f11731 Mon Sep 17 00:00:00 2001 From: michael Date: Fri, 20 Nov 2026 13:56:51 +0100 Subject: [PATCH 2/4] feat(storage_arrays): adapter framework, fake-array test harness, Pure FlashArray adapter ArrayClient (credential resolution + re-auth retry, sb- naming, size rounding, idempotent create/map/unmap/delete, ownership + WWN checks), RestSession (TLS/CA bundle, retries, error mapping), lazy vendor registry, in-process vendor fakes + HTTPS mock server, shared contract suite with a live tier (SB_ARRAY_LIVE_CONFIG). Co-Authored-By: Claude Opus 5.5 --- simplyblock_core/storage_arrays/__init__.py | 44 +++ .../storage_arrays/adapters/__init__.py | 1 + .../storage_arrays/adapters/pure.py | 224 +++++++++++ simplyblock_core/storage_arrays/base.py | 354 ++++++++++++++++++ simplyblock_core/storage_arrays/client.py | 268 +++++++++++++ simplyblock_core/storage_arrays/http.py | 198 ++++++++++ simplyblock_core/storage_arrays/registry.py | 61 +++ .../storage_arrays/testing/__init__.py | 314 ++++++++++++++++ .../storage_arrays/testing/__main__.py | 48 +++ .../storage_arrays/testing/pure.py | 270 +++++++++++++ tests/unit/storage_arrays/__init__.py | 0 tests/unit/storage_arrays/conftest.py | 115 ++++++ tests/unit/storage_arrays/test_contract.py | 270 +++++++++++++ 13 files changed, 2167 insertions(+) create mode 100644 simplyblock_core/storage_arrays/__init__.py create mode 100644 simplyblock_core/storage_arrays/adapters/__init__.py create mode 100644 simplyblock_core/storage_arrays/adapters/pure.py create mode 100644 simplyblock_core/storage_arrays/base.py create mode 100644 simplyblock_core/storage_arrays/client.py create mode 100644 simplyblock_core/storage_arrays/http.py create mode 100644 simplyblock_core/storage_arrays/registry.py create mode 100644 simplyblock_core/storage_arrays/testing/__init__.py create mode 100644 simplyblock_core/storage_arrays/testing/__main__.py create mode 100644 simplyblock_core/storage_arrays/testing/pure.py create mode 100644 tests/unit/storage_arrays/__init__.py create mode 100644 tests/unit/storage_arrays/conftest.py create mode 100644 tests/unit/storage_arrays/test_contract.py diff --git a/simplyblock_core/storage_arrays/__init__.py b/simplyblock_core/storage_arrays/__init__.py new file mode 100644 index 0000000000..d0ada602c8 --- /dev/null +++ b/simplyblock_core/storage_arrays/__init__.py @@ -0,0 +1,44 @@ +"""External storage arrays: vendor adapters behind one contract. + +Entry point: :class:`simplyblock_core.storage_arrays.client.ArrayClient`. +""" +from .base import ( + ArrayAdapter, + ArrayAuthError, + ArrayConfig, + ArrayConflictError, + ArrayError, + ArrayInfo, + ArrayNotFoundError, + ArrayRequestError, + ArrayUnsupportedError, + Capabilities, + HostSpec, + Initiator, + Mapping, + Protocol, + Volume, +) +from .registry import ADAPTERS, ALIASES, adapter_class, canonical_vendor + +__all__ = [ + "ADAPTERS", + "ALIASES", + "ArrayAdapter", + "ArrayAuthError", + "ArrayConfig", + "ArrayConflictError", + "ArrayError", + "ArrayInfo", + "ArrayNotFoundError", + "ArrayRequestError", + "ArrayUnsupportedError", + "Capabilities", + "HostSpec", + "Initiator", + "Mapping", + "Protocol", + "Volume", + "adapter_class", + "canonical_vendor", +] diff --git a/simplyblock_core/storage_arrays/adapters/__init__.py b/simplyblock_core/storage_arrays/adapters/__init__.py new file mode 100644 index 0000000000..9763b23894 --- /dev/null +++ b/simplyblock_core/storage_arrays/adapters/__init__.py @@ -0,0 +1 @@ +"""Vendor adapters; see ..registry for the vendor keys.""" diff --git a/simplyblock_core/storage_arrays/adapters/pure.py b/simplyblock_core/storage_arrays/adapters/pure.py new file mode 100644 index 0000000000..5c2ed4864e --- /dev/null +++ b/simplyblock_core/storage_arrays/adapters/pure.py @@ -0,0 +1,224 @@ +"""Pure Storage FlashArray, REST API 2.x (Purity//FA 6.x and later). + +Auth: an API token (``api_token`` credential field) exchanged for a session +token via ``POST /api/2.x/login`` (``api-token`` header -> ``x-auth-token``). + +Objects are addressed by name (hosts) and id (volumes). Pure "destroys" +volumes into a recycle bin (recoverable for the eradication delay, 24 h by +default) before eradication; ``eradicate=true`` removes them at once. + +Volume identity: SCSI ``naa.624a9370``; NVMe NGUID +``eui.0024a937``. +""" +from __future__ import annotations + +from typing import Any + +from ..base import ( + ArrayAdapter, + ArrayConflictError, + ArrayInfo, + ArrayNotFoundError, + ArrayRequestError, + Capabilities, + HostSpec, + Mapping, + OptionDoc, + Protocol, + Volume, +) +from ..http import json_of + +_SUPPORTED_MAX = (2, 36) # newest 2.x minor this adapter was written against +_MIN_VERSION = (2, 4) + + +def _ver(v: str) -> tuple[int, int]: + major, _, minor = v.partition(".") + return int(major), int(minor or 0) + + +def pure_wwn(serial: str) -> str: + return "naa.624a9370" + serial.lower() + + +def pure_nguid(serial: str) -> str: + s = serial.lower() + return "eui.00" + s[:14] + "24a937" + s[14:] + + +class PureFlashArrayAdapter(ArrayAdapter): + vendor = "pure-flasharray" + display_name = "Pure Storage FlashArray" + capabilities = Capabilities( + protocols=frozenset({Protocol.ISCSI, Protocol.FC, Protocol.NVME_TCP, + Protocol.NVME_RDMA, Protocol.NVME_FC}), + size_granularity_bytes=512, + min_size_bytes=1 << 20, + max_name_len=63, + ) + credential_fields = (frozenset({"api_token"}),) + option_docs = ( + OptionDoc("eradicate", "Eradicate deleted volumes immediately instead of " + "leaving them recoverable for the eradication delay.", default=False), + OptionDoc("api_version", "Pin the REST 2.x version (e.g. '2.21'); " + "default: newest supported by both sides."), + ) + + def __init__(self, ctx): + super().__init__(ctx) + self._api = "" + + # -- session ------------------------------------------------------------ + + def login(self) -> None: + version = self.option("api_version") + if not version: + offered = json_of(self.session.get("/api/api_version")).get("version", []) + usable = [v for v in offered + if v.startswith("2.") and _MIN_VERSION <= _ver(v) <= _SUPPORTED_MAX] + if not usable: + raise ArrayRequestError( + f"FlashArray offers no REST 2.x version in " + f"{'.'.join(map(str, _MIN_VERSION))}..{'.'.join(map(str, _SUPPORTED_MAX))}: " + f"{offered}") + version = max(usable, key=_ver) + self._api = f"/api/{version}" + self.session.headers.pop("x-auth-token", None) + resp = self.session.post(f"{self._api}/login", + headers={"api-token": self.secret("api_token")}) + token = resp.headers.get("x-auth-token") + if not token: + raise ArrayRequestError("FlashArray login returned no x-auth-token") + self.session.headers["x-auth-token"] = token + + def close(self) -> None: + if self._api and "x-auth-token" in self.session.headers: + try: + self.session.post(f"{self._api}/logout") + except Exception: + pass + + # -- request helpers ----------------------------------------------------- + + def _items(self, method: str, path: str, *, params=None, json=None, + missing_ok: bool = False) -> list[dict[str, Any]]: + resp = self.session.request(method, f"{self._api}{path}", params=params, json=json, + ok=(400,)) + body = json_of(resp) or {} + if resp.status_code == 400: + messages = " ".join( + str(e.get("message", "")) for e in body.get("errors", [])) + lowered = messages.lower() + if "does not exist" in lowered or "not found" in lowered: + if missing_ok: + return [] + raise ArrayNotFoundError(f"{method} {path}: {messages}") + if "already" in lowered or "in use" in lowered or "exists" in lowered: + raise ArrayConflictError(f"{method} {path}: {messages}") + raise ArrayRequestError(f"{method} {path}: {messages}", status=400) + return list(body.get("items", [])) + + @staticmethod + def _volume(item: dict[str, Any]) -> Volume: + serial = item.get("serial") or "" + return Volume( + id=item["id"], name=item["name"], size_bytes=int(item["provisioned"]), + wwn=pure_wwn(serial) if serial else None, + nguid=pure_nguid(serial) if serial else None, + ) + + # -- contract ------------------------------------------------------------- + + def get_info(self) -> ArrayInfo: + arr = self._items("GET", "/arrays")[0] + model = "" + try: + controllers = self._items("GET", "/controllers") + model = next((c.get("model", "") for c in controllers if c.get("model")), "") + except ArrayRequestError: + pass + return ArrayInfo(vendor=self.vendor, model=model, + version=f"{arr.get('os', 'Purity//FA')} {arr.get('version', '')}".strip(), + serial=arr.get("id", "")) + + def create_volume(self, name: str, size_bytes: int) -> Volume: + items = self._items("POST", "/volumes", params={"names": name}, + json={"provisioned": size_bytes}) + return self._volume(items[0]) + + def _live(self, items: list[dict[str, Any]]) -> Volume | None: + live = [i for i in items if not i.get("destroyed")] + return self._volume(live[0]) if live else None + + def get_volume(self, volume_id: str) -> Volume | None: + return self._live(self._items("GET", "/volumes", params={"ids": volume_id}, + missing_ok=True)) + + def find_volume(self, name: str) -> Volume | None: + return self._live(self._items("GET", "/volumes", params={"names": name}, + missing_ok=True)) + + def resize_volume(self, volume_id: str, size_bytes: int) -> Volume: + items = self._items("PATCH", "/volumes", params={"ids": volume_id}, + json={"provisioned": size_bytes}) + return self._volume(items[0]) + + def delete_volume(self, volume_id: str) -> None: + self._items("PATCH", "/volumes", params={"ids": volume_id}, json={"destroyed": True}) + if self.option("eradicate"): + self._items("DELETE", "/volumes", params={"ids": volume_id}) + + def _host(self, name: str) -> dict[str, Any] | None: + items = self._items("GET", "/hosts", params={"names": name}, missing_ok=True) + return items[0] if items else None + + def ensure_host(self, spec: HostSpec) -> str: + wanted = { + "iqns": spec.addresses(Protocol.ISCSI), + "wwns": [a.upper() for a in spec.addresses(Protocol.FC)], + "nqns": spec.addresses(Protocol.NVME_TCP, Protocol.NVME_RDMA, Protocol.NVME_FC), + } + wanted = {k: v for k, v in wanted.items() if v} + host = self._host(spec.name) + if host is None: + self._items("POST", "/hosts", params={"names": spec.name}, json=wanted) + return spec.name + add: dict[str, list[str]] = {} + for key, values in wanted.items(): + have = {str(v).lower() for v in host.get(key, [])} + missing = [v for v in values if v.lower() not in have] + if missing: + add[f"add_{key}"] = missing + if add: + self._items("PATCH", "/hosts", params={"names": spec.name}, json=add) + return spec.name + + def delete_host(self, host_id: str) -> None: + self._items("DELETE", "/hosts", params={"names": host_id}, missing_ok=True) + + def _connections(self, volume_id: str, host_id: str | None = None) -> list[Mapping]: + params: dict[str, str] = {"volume_ids": volume_id} + if host_id is not None: + params["host_names"] = host_id + items = self._items("GET", "/connections", params=params, missing_ok=True) + return [Mapping(volume_id=i["volume"]["id"], host_id=i["host"]["name"], + lun=i.get("lun")) for i in items if i.get("host")] + + def map_volume(self, volume_id: str, host_id: str) -> Mapping: + existing = self._connections(volume_id, host_id) + if existing: + return existing[0] + items = self._items("POST", "/connections", + params={"host_names": host_id, "volume_ids": volume_id}) + i = items[0] + return Mapping(volume_id=i["volume"]["id"], host_id=i["host"]["name"], lun=i.get("lun")) + + def unmap_volume(self, volume_id: str, host_id: str) -> None: + if not self._connections(volume_id, host_id): + return + self._items("DELETE", "/connections", + params={"host_names": host_id, "volume_ids": volume_id}, missing_ok=True) + + def list_mappings(self, volume_id: str) -> list[Mapping]: + return self._connections(volume_id) diff --git a/simplyblock_core/storage_arrays/base.py b/simplyblock_core/storage_arrays/base.py new file mode 100644 index 0000000000..0619d402e6 --- /dev/null +++ b/simplyblock_core/storage_arrays/base.py @@ -0,0 +1,354 @@ +"""Vendor-neutral model and adapter contract for external storage arrays. + +An adapter translates five operations -- volume create/resize/delete, host +(initiator group) management and volume-to-host mapping -- into one vendor's +management API. Everything vendor-neutral (credential resolution, +re-authentication, size rounding, idempotence, delete/resize safety checks) +lives in :class:`simplyblock_core.storage_arrays.client.ArrayClient`, so +adapters stay thin and are tested against one shared contract suite +(``tests/unit/storage_arrays/test_contract.py``). +""" +from __future__ import annotations + +import re +from abc import ABC, abstractmethod +from collections.abc import Mapping as MappingABC +from dataclasses import dataclass, field +from enum import Enum +from typing import Any, ClassVar + +from pydantic import BaseModel, ConfigDict, Field, field_validator + +from simplyblock_core.credentials import Credential + +# -- Errors ----------------------------------------------------------------- + + +class ArrayError(Exception): + """Base class. Messages never contain credential values.""" + + +class ArrayAuthError(ArrayError): + """The array rejected the credential or the session expired.""" + + +class ArrayNotFoundError(ArrayError): + """The addressed object does not exist.""" + + +class ArrayConflictError(ArrayError): + """The request conflicts with array state (name taken, initiator owned + by another host, volume still mapped, ...).""" + + +class ArrayUnsupportedError(ArrayError): + """The adapter or array does not support the requested operation.""" + + +class ArrayRequestError(ArrayError): + """Any other failed request.""" + + def __init__(self, message: str, status: int | None = None): + super().__init__(message) + self.status = status + + +# -- Model ------------------------------------------------------------------ + + +class Protocol(str, Enum): + ISCSI = "iscsi" + FC = "fc" + NVME_TCP = "nvme-tcp" + NVME_RDMA = "nvme-rdma" + NVME_FC = "nvme-fc" + #: Dell PowerFlex native client (SDC); the initiator address is the SDC GUID. + SDC = "sdc" + + @property + def is_nvme(self) -> bool: + return self in (Protocol.NVME_TCP, Protocol.NVME_RDMA, Protocol.NVME_FC) + + @property + def is_scsi(self) -> bool: + return self in (Protocol.ISCSI, Protocol.FC) + + +_WWPN_RE = re.compile(r"^[0-9a-f]{16}$") + + +def normalize_wwpn(value: str) -> str: + """``21:00:00:24:FF:4C:1A:2B`` / ``0x2100...`` -> ``21000024ff4c1a2b``.""" + v = value.strip().lower().removeprefix("0x").replace(":", "").replace("-", "") + if not _WWPN_RE.match(v): + raise ValueError(f"Not a WWPN: {value!r}") + return v + + +def colon_wwpn(value: str) -> str: + """``21000024ff4c1a2b`` -> ``21:00:00:24:ff:4c:1a:2b``.""" + v = normalize_wwpn(value) + return ":".join(v[i:i + 2] for i in range(0, 16, 2)) + + +class Initiator(BaseModel): + """One host port: an iSCSI IQN, an FC WWPN, an NVMe host NQN or an SDC GUID.""" + + model_config = ConfigDict(frozen=True, extra="forbid") + + protocol: Protocol + address: str = Field(min_length=1) + + @field_validator("address") + @classmethod + def _strip(cls, v: str) -> str: + return v.strip() + + def normalized(self) -> str: + if self.protocol in (Protocol.FC, Protocol.NVME_FC): + return normalize_wwpn(self.address) + if self.protocol == Protocol.ISCSI: + return self.address.lower() + return self.address + + +class HostSpec(BaseModel): + """A host as the array should know it. All initiators share one protocol + family (SCSI or NVMe); a host using both is registered twice.""" + + model_config = ConfigDict(frozen=True, extra="forbid") + + name: str = Field(min_length=1, max_length=255) + initiators: tuple[Initiator, ...] = Field(min_length=1) + + @field_validator("initiators") + @classmethod + def _one_family(cls, v: tuple[Initiator, ...]) -> tuple[Initiator, ...]: + protocols = {i.protocol for i in v} + if len(protocols) > 1 and not ( + all(p.is_scsi for p in protocols) or all(p.is_nvme for p in protocols) + ): + raise ValueError("A host's initiators must all be SCSI or all be NVMe") + return v + + @property + def protocols(self) -> frozenset[Protocol]: + return frozenset(i.protocol for i in self.initiators) + + def addresses(self, *protocols: Protocol) -> list[str]: + return [i.normalized() for i in self.initiators if i.protocol in protocols] + + +class Volume(BaseModel): + model_config = ConfigDict(frozen=True, extra="forbid") + + #: The array's own handle for the volume (id, uuid, device number, name). + id: str + name: str + size_bytes: int + #: SCSI identity as the host sees it, ``naa.`` (lowercase). This is + #: what matches the array volume to ``/dev/disk/by-id`` on the host. + wwn: str | None = None + #: NVMe identity, ``eui.<32 hex>`` (NGUID) where the array exposes one. + nguid: str | None = None + + @property + def identifier(self) -> str: + """Stable identity used for safety checks: WWN, else NGUID, else id.""" + return self.wwn or self.nguid or f"id.{self.id}" + + +class Mapping(BaseModel): + model_config = ConfigDict(frozen=True, extra="forbid") + + volume_id: str + host_id: str + #: SCSI LUN or NVMe namespace ID as presented to the host; ``None`` where + #: the protocol has no such number (PowerFlex SDC). + lun: int | None = None + + +class ArrayInfo(BaseModel): + model_config = ConfigDict(frozen=True, extra="forbid") + + vendor: str + model: str = "" + version: str = "" + serial: str = "" + + +class ArrayConfig(BaseModel): + """One registered array. Holds no secret: ``credential_ref`` is resolved + through :class:`simplyblock_core.credentials.CredentialProvider`.""" + + model_config = ConfigDict(frozen=True, extra="forbid") + + id: str = Field(min_length=1) + vendor: str = Field(min_length=1) + #: Management endpoint, e.g. ``https://pure01.example.com`` or + #: ``https://unisphere.example.com:8443``. Path prefixes are kept. + endpoint: str = Field(min_length=1) + credential_ref: dict[str, Any] + #: PEM CA bundle (or pinned self-signed certificate) for the endpoint. + ca_bundle: str | None = None + #: Must stay True outside of labs; ``False`` disables TLS verification. + verify_tls: bool = True + timeout_s: float = Field(default=60.0, gt=0) + #: Vendor-specific settings (pool, SVM, CPG, storage group, ...); each + #: adapter documents what it reads in ``option_docs``. + options: dict[str, Any] = Field(default_factory=dict) + + @field_validator("endpoint") + @classmethod + def _https_only(cls, v: str) -> str: + v = v.strip().rstrip("/") + if not v.lower().startswith("https://"): + raise ValueError("Array endpoint must be https://") + return v + + +@dataclass(frozen=True) +class Capabilities: + protocols: frozenset[Protocol] + #: Volume sizes are rounded up to a multiple of this. + size_granularity_bytes: int = 512 + min_size_bytes: int = 1 << 20 + #: Longest volume / host name the array accepts. + max_name_len: int = 63 + #: Whether resize can only grow (true for every supported array today). + grow_only: bool = True + + +@dataclass +class OptionDoc: + name: str + help: str + required: bool = False + default: Any = None + + +@dataclass +class AdapterContext: + """What an adapter is constructed with.""" + + config: ArrayConfig + credential: Credential + session: Any # simplyblock_core.storage_arrays.http.RestSession + extra: dict[str, Any] = field(default_factory=dict) + + +class ArrayAdapter(ABC): + """One vendor's implementation of the contract. + + Rules every adapter follows (the contract suite checks them): + + * ``create_volume`` receives a name that is already unique and short + enough, and a size already rounded to ``capabilities``. + * ``get_volume``/``find_volume`` return ``None`` for a missing volume; + every other method raises :class:`ArrayNotFoundError` for one. + * ``ensure_host`` is idempotent: an existing host of that name gets any + missing initiators added; an initiator registered to a *different* host + raises :class:`ArrayConflictError`. + * ``map_volume`` is idempotent and returns the existing mapping if there is + one; ``unmap_volume`` of an absent mapping is a no-op. + * ``delete_volume`` is only called with no mappings left. + * Errors never include credential values. + """ + + vendor: ClassVar[str] + display_name: ClassVar[str] + capabilities: ClassVar[Capabilities] + #: Accepted credential shapes, as alternatives of required field names, + #: e.g. ``({"api_token"}, {"username", "password"})``. + credential_fields: ClassVar[tuple[frozenset[str], ...]] = ( + frozenset({"username", "password"}), + ) + option_docs: ClassVar[tuple[OptionDoc, ...]] = () + + def __init__(self, ctx: AdapterContext): + self.config = ctx.config + self.credential = ctx.credential + self.session = ctx.session + self.options: MappingABC[str, Any] = ctx.config.options + self._check_credential_shape() + self._check_options() + + # -- helpers ------------------------------------------------------------ + + def _check_credential_shape(self) -> None: + have = self.credential.field_names + if not any(shape <= have for shape in self.credential_fields): + wanted = " or ".join("+".join(sorted(s)) for s in self.credential_fields) + raise ArrayAuthError( + f"{self.display_name} needs credential fields {wanted}; " + f"got {', '.join(sorted(have)) or 'none'}") + + def _check_options(self) -> None: + missing = [o.name for o in self.option_docs if o.required and o.name not in self.options] + if missing: + raise ArrayError(f"{self.display_name} array {self.config.id} needs options: " + + ", ".join(missing)) + known = {o.name for o in self.option_docs} + unknown = sorted(set(self.options) - known) + if unknown: + raise ArrayError(f"Unknown {self.display_name} options: {', '.join(unknown)}") + + def option(self, name: str) -> Any: + if name in self.options: + return self.options[name] + for o in self.option_docs: + if o.name == name: + return o.default + raise KeyError(name) + + def secret(self, name: str) -> str: + return self.credential.get(name).get_secret_value() + + def has_secret(self, name: str) -> bool: + return name in self.credential.field_names + + # -- lifecycle ---------------------------------------------------------- + + def login(self) -> None: + """Establish a session. Called lazily by the client and again after + an :class:`ArrayAuthError`. Basic-auth adapters may leave this empty.""" + + def close(self) -> None: + """Release the session (best effort, never raises).""" + + # -- contract ----------------------------------------------------------- + + @abstractmethod + def get_info(self) -> ArrayInfo: ... + + @abstractmethod + def create_volume(self, name: str, size_bytes: int) -> Volume: ... + + @abstractmethod + def get_volume(self, volume_id: str) -> Volume | None: ... + + @abstractmethod + def find_volume(self, name: str) -> Volume | None: ... + + @abstractmethod + def resize_volume(self, volume_id: str, size_bytes: int) -> Volume: ... + + @abstractmethod + def delete_volume(self, volume_id: str) -> None: ... + + @abstractmethod + def ensure_host(self, spec: HostSpec) -> str: + """Return the host id.""" + + @abstractmethod + def delete_host(self, host_id: str) -> None: + """Delete a host that has no mappings left (no-op if absent).""" + + @abstractmethod + def map_volume(self, volume_id: str, host_id: str) -> Mapping: ... + + @abstractmethod + def unmap_volume(self, volume_id: str, host_id: str) -> None: ... + + @abstractmethod + def list_mappings(self, volume_id: str) -> list[Mapping]: ... diff --git a/simplyblock_core/storage_arrays/client.py b/simplyblock_core/storage_arrays/client.py new file mode 100644 index 0000000000..e5bb928eab --- /dev/null +++ b/simplyblock_core/storage_arrays/client.py @@ -0,0 +1,268 @@ +"""Vendor-neutral front end for array adapters. + +:class:`ArrayClient` is what the rest of simplyblock calls. It + +* resolves the array's credential through the cluster's + :class:`~simplyblock_core.credentials.CredentialProvider`, bound to the + array's id and endpoint (so a rewritten endpoint cannot receive it); +* builds the adapter lazily and, when the array rejects the session or the + credential, invalidates the cached credential, logs in again and retries + the operation once (this is how rotated secrets are picked up); +* names volumes ``sb-`` from the simplyblock volume UUID, so names are + unique, fit every array's length limit, and mark ownership; +* rounds sizes up to the array's granularity; +* makes create/map/unmap/delete idempotent so an interrupted task can be + re-run; +* refuses to resize, unmap or delete a volume that is not simplyblock-owned + (name prefix) or whose WWN/NGUID differs from the one simplyblock recorded. +""" +from __future__ import annotations + +import logging +import threading +import uuid as uuid_mod +from collections.abc import Callable +from typing import Any, Self, TypeVar +from urllib.parse import urlsplit + +from requests.adapters import BaseAdapter + +from simplyblock_core.credentials import ( + CREDENTIAL_REF_ADAPTER, + Credential, + CredentialProvider, +) + +from .base import ( + AdapterContext, + ArrayAdapter, + ArrayAuthError, + ArrayConfig, + ArrayConflictError, + ArrayError, + ArrayInfo, + HostSpec, + Mapping, + Volume, +) +from .http import RestSession +from .registry import adapter_class, canonical_vendor + +logger = logging.getLogger(__name__) + +MANAGED_PREFIX = "sb-" +_NAME_HEX_LEN = 24 # 96 bits of the volume UUID: ample, and fits 31-char limits + +T = TypeVar("T") + + +def credential_context(config: ArrayConfig) -> str: + """The context an array's credential is bound to: id + scheme/host/port.""" + parts = urlsplit(config.endpoint) + port = parts.port or 443 + return f"array/{config.id}/{parts.scheme}://{(parts.hostname or '').lower()}:{port}" + + +def managed_name(volume_uuid: str, max_len: int, prefix: str = MANAGED_PREFIX) -> str: + hex_id = uuid_mod.UUID(str(volume_uuid)).hex + return (prefix + hex_id[:_NAME_HEX_LEN])[:max_len] + + +def round_size(size_bytes: int, granularity: int, minimum: int) -> int: + size = max(int(size_bytes), minimum) + return -(-size // granularity) * granularity + + +class ArrayClient: + """Thread-safe: operations on one array are serialized.""" + + def __init__( + self, + config: ArrayConfig, + credentials: CredentialProvider, + *, + transport: BaseAdapter | None = None, + session_kwargs: dict[str, Any] | None = None, + ): + self.config = config + self.vendor = canonical_vendor(config.vendor) + self.adapter_cls = adapter_class(self.vendor) + self._credentials = credentials + self._ref = CREDENTIAL_REF_ADAPTER.validate_python(config.credential_ref) + self._context = credential_context(config) + self._transport = transport + self._session_kwargs = session_kwargs or {} + self._adapter: ArrayAdapter | None = None + self._lock = threading.RLock() + + @property + def capabilities(self): + return self.adapter_cls.capabilities + + # -- adapter lifecycle ---------------------------------------------------- + + def _build(self) -> ArrayAdapter: + credential: Credential = self._credentials.resolve(self._ref, self._context) + session = RestSession.for_config(self.config, transport=self._transport, + **self._session_kwargs) + adapter = self.adapter_cls(AdapterContext(self.config, credential, session)) + try: + adapter.login() + except BaseException: + adapter.close() + session.close() + raise + return adapter + + def _drop(self) -> None: + if self._adapter is not None: + try: + self._adapter.close() + except Exception: # pragma: no cover - best effort + logger.debug("adapter close failed", exc_info=True) + try: + self._adapter.session.close() + except Exception: # pragma: no cover + pass + self._adapter = None + + def close(self) -> None: + with self._lock: + self._drop() + + def __enter__(self) -> Self: + return self + + def __exit__(self, *exc: object) -> None: + self.close() + + def _call(self, op: str, fn: Callable[[ArrayAdapter], T]) -> T: + with self._lock: + for attempt in (1, 2): + try: + if self._adapter is None: + self._adapter = self._build() + return fn(self._adapter) + except ArrayAuthError: + self._drop() + if attempt == 2: + raise + logger.info("Array %s rejected the session during %s; re-authenticating", + self.config.id, op) + self._credentials.invalidate(self._ref) + raise AssertionError("unreachable") # pragma: no cover + + # -- checks ----------------------------------------------------------------- + + def _owned(self, vol: Volume, expected_identifier: str | None, action: str) -> None: + if not vol.name.startswith(MANAGED_PREFIX): + raise ArrayConflictError( + f"Refusing to {action} volume {vol.name!r} on array {self.config.id}: " + "not created by simplyblock") + if expected_identifier is not None and vol.identifier.lower() != expected_identifier.lower(): + raise ArrayConflictError( + f"Refusing to {action} volume {vol.name!r} on array {self.config.id}: " + f"identifier {vol.identifier} does not match recorded {expected_identifier}") + + # -- operations ------------------------------------------------------------- + + def get_info(self) -> ArrayInfo: + return self._call("get_info", lambda a: a.get_info()) + + def volume_name(self, volume_uuid: str) -> str: + return managed_name(volume_uuid, self.capabilities.max_name_len) + + def create_volume(self, volume_uuid: str, size_bytes: int) -> Volume: + """Create (or, on re-run, return) the array volume for a simplyblock + volume. An existing volume of that name smaller than requested is grown.""" + name = self.volume_name(volume_uuid) + caps = self.capabilities + size = round_size(size_bytes, caps.size_granularity_bytes, caps.min_size_bytes) + + def op(a: ArrayAdapter) -> Volume: + existing = a.find_volume(name) + if existing is not None: + if existing.size_bytes < size: + return a.resize_volume(existing.id, size) + return existing + vol = a.create_volume(name, size) + logger.info("Array %s: created volume %s (%s, %d bytes)", + self.config.id, vol.name, vol.identifier, vol.size_bytes) + return vol + + return self._call("create_volume", op) + + def get_volume(self, volume_id: str) -> Volume | None: + return self._call("get_volume", lambda a: a.get_volume(volume_id)) + + def find_volume(self, volume_uuid: str) -> Volume | None: + name = self.volume_name(volume_uuid) + return self._call("find_volume", lambda a: a.find_volume(name)) + + def resize_volume(self, volume_id: str, size_bytes: int, + expected_identifier: str | None = None) -> Volume: + caps = self.capabilities + size = round_size(size_bytes, caps.size_granularity_bytes, caps.min_size_bytes) + + def op(a: ArrayAdapter) -> Volume: + vol = a.get_volume(volume_id) + if vol is None: + raise ArrayError(f"Volume {volume_id} not found on array {self.config.id}") + self._owned(vol, expected_identifier, "resize") + if size == vol.size_bytes: + return vol + if size < vol.size_bytes and caps.grow_only: + raise ArrayConflictError( + f"Refusing to shrink volume {vol.name} from {vol.size_bytes} to {size} bytes") + new = a.resize_volume(vol.id, size) + logger.info("Array %s: resized volume %s %d -> %d bytes", + self.config.id, vol.name, vol.size_bytes, new.size_bytes) + return new + + return self._call("resize_volume", op) + + def delete_volume(self, volume_id: str, expected_identifier: str | None = None) -> bool: + """Unmap from every host and delete. Returns False if already gone.""" + def op(a: ArrayAdapter) -> bool: + vol = a.get_volume(volume_id) + if vol is None: + return False + self._owned(vol, expected_identifier, "delete") + for m in a.list_mappings(vol.id): + a.unmap_volume(vol.id, m.host_id) + a.delete_volume(vol.id) + logger.info("Array %s: deleted volume %s (%s)", self.config.id, vol.name, vol.identifier) + return True + + return self._call("delete_volume", op) + + def ensure_host(self, spec: HostSpec) -> str: + unsupported = spec.protocols - self.capabilities.protocols + if unsupported: + raise ArrayError( + f"{self.adapter_cls.display_name} adapter does not support " + + ", ".join(sorted(p.value for p in unsupported))) + if len(spec.name) > self.capabilities.max_name_len: + raise ArrayError(f"Host name {spec.name!r} exceeds " + f"{self.capabilities.max_name_len} characters") + return self._call("ensure_host", lambda a: a.ensure_host(spec)) + + def delete_host(self, host_id: str) -> None: + self._call("delete_host", lambda a: a.delete_host(host_id)) + + def map_volume(self, volume_id: str, host_id: str, + expected_identifier: str | None = None) -> Mapping: + def op(a: ArrayAdapter) -> Mapping: + vol = a.get_volume(volume_id) + if vol is None: + raise ArrayError(f"Volume {volume_id} not found on array {self.config.id}") + self._owned(vol, expected_identifier, "map") + return a.map_volume(vol.id, host_id) + + return self._call("map_volume", op) + + def unmap_volume(self, volume_id: str, host_id: str) -> None: + self._call("unmap_volume", lambda a: a.unmap_volume(volume_id, host_id)) + + def list_mappings(self, volume_id: str) -> list[Mapping]: + return self._call("list_mappings", lambda a: a.list_mappings(volume_id)) diff --git a/simplyblock_core/storage_arrays/http.py b/simplyblock_core/storage_arrays/http.py new file mode 100644 index 0000000000..71c29fdc30 --- /dev/null +++ b/simplyblock_core/storage_arrays/http.py @@ -0,0 +1,198 @@ +"""Small HTTPS/JSON session shared by all array adapters. + +Adapters never build ``requests`` sessions themselves, so TLS verification, +timeouts, retries and error mapping are uniform, and tests can swap the +transport for an in-process fake (see ``storage_arrays.testing``). +""" +from __future__ import annotations + +import logging +import os +import tempfile +import time +from collections.abc import Callable, Iterable +from typing import Any + +import requests +from requests.adapters import BaseAdapter + +from .base import ( + ArrayAuthError, + ArrayConfig, + ArrayConflictError, + ArrayNotFoundError, + ArrayRequestError, +) + +logger = logging.getLogger(__name__) + +_IDEMPOTENT = frozenset({"GET", "HEAD", "OPTIONS"}) +_RETRY_STATUSES = frozenset({502, 503, 504}) +_MAX_ERROR_BODY = 600 + + +class RestSession: + """``requests`` wrapper bound to one array endpoint. + + * ``verify``: ``True`` (system CAs), a CA bundle path, or ``False``. + * Non-2xx responses raise: 401/403 -> :class:`ArrayAuthError`, 404 -> + :class:`ArrayNotFoundError`, 409 -> :class:`ArrayConflictError`, other -> + :class:`ArrayRequestError`. Pass ``ok=`` to accept extra statuses. + * Idempotent requests are retried on connection errors and 502/503/504. + """ + + def __init__( + self, + base_url: str, + *, + verify: bool | str = True, + timeout_s: float = 60.0, + retries: int = 2, + backoff_s: float = 0.5, + transport: BaseAdapter | None = None, + sleep: Callable[[float], None] = time.sleep, + ): + self.base_url = base_url.rstrip("/") + self.timeout_s = timeout_s + self.retries = retries + self.backoff_s = backoff_s + self._sleep = sleep + self.http = requests.Session() + self.http.verify = verify + self.http.headers.update({"Accept": "application/json"}) + if transport is not None: + self.http.mount("https://", transport) + self.http.mount("http://", transport) + self._ca_file: str | None = None + + @classmethod + def for_config(cls, config: ArrayConfig, *, transport: BaseAdapter | None = None, + base_url: str | None = None, **kw: Any) -> RestSession: + verify: bool | str = config.verify_tls + ca_file = None + if config.verify_tls and config.ca_bundle: + fd, ca_file = tempfile.mkstemp(prefix="sb-array-ca-", suffix=".pem") + with os.fdopen(fd, "w") as f: + f.write(config.ca_bundle) + verify = ca_file + session = cls(base_url or config.endpoint, verify=verify, timeout_s=config.timeout_s, + transport=transport, **kw) + session._ca_file = ca_file + return session + + # -- auth helpers --------------------------------------------------------- + + @property + def headers(self) -> Any: + return self.http.headers + + def set_basic_auth(self, username: str, password: str) -> None: + self.http.auth = (username, password) + + def clear_auth(self) -> None: + self.http.auth = None + + # -- requests ------------------------------------------------------------- + + def url(self, path: str) -> str: + if path.startswith(("http://", "https://")): + return path + return f"{self.base_url}/{path.lstrip('/')}" + + def request( + self, + method: str, + path: str, + *, + params: Any = None, + json: Any = None, + data: Any = None, + headers: dict[str, str] | None = None, + ok: Iterable[int] = (), + auth: Any = None, + ) -> requests.Response: + method = method.upper() + attempts = 1 + (self.retries if method in _IDEMPOTENT else 0) + ok_extra = frozenset(ok) + last_exc: Exception | None = None + for attempt in range(attempts): + try: + kwargs: dict[str, Any] = dict(params=params, json=json, data=data, + headers=headers, timeout=self.timeout_s) + if auth is not None: + kwargs["auth"] = auth + resp = self.http.request(method, self.url(path), **kwargs) + except requests.RequestException as e: + last_exc = e + if attempt + 1 < attempts: + self._sleep(self.backoff_s * (attempt + 1)) + continue + raise ArrayRequestError( + f"{method} {path}: {type(e).__name__}: {_safe(str(e))}") from e + if resp.status_code in _RETRY_STATUSES and attempt + 1 < attempts: + self._sleep(self.backoff_s * (attempt + 1)) + continue + if 200 <= resp.status_code < 300 or resp.status_code in ok_extra: + return resp + raise error_for(method, path, resp) + raise ArrayRequestError(f"{method} {path}: giving up") from last_exc # pragma: no cover + + def get(self, path: str, **kw: Any) -> requests.Response: + return self.request("GET", path, **kw) + + def post(self, path: str, **kw: Any) -> requests.Response: + return self.request("POST", path, **kw) + + def put(self, path: str, **kw: Any) -> requests.Response: + return self.request("PUT", path, **kw) + + def patch(self, path: str, **kw: Any) -> requests.Response: + return self.request("PATCH", path, **kw) + + def delete(self, path: str, **kw: Any) -> requests.Response: + return self.request("DELETE", path, **kw) + + def close(self) -> None: + try: + self.http.close() + finally: + if self._ca_file: + try: + os.unlink(self._ca_file) + except OSError: + pass + self._ca_file = None + + +def _safe(text: str) -> str: + return text[:_MAX_ERROR_BODY] + + +def body_text(resp: requests.Response) -> str: + try: + return _safe(resp.text or "") + except Exception: # pragma: no cover - decoding issues + return "" + + +def error_for(method: str, path: str, resp: requests.Response) -> Exception: + msg = f"{method} {path} -> HTTP {resp.status_code}: {body_text(resp)}" + if resp.status_code in (401, 403): + return ArrayAuthError(msg) + if resp.status_code == 404: + return ArrayNotFoundError(msg) + if resp.status_code == 409: + return ArrayConflictError(msg) + return ArrayRequestError(msg, status=resp.status_code) + + +def json_of(resp: requests.Response) -> Any: + """Response body as JSON (``None`` for an empty body).""" + if not resp.content: + return None + try: + return resp.json() + except ValueError as e: + raise ArrayRequestError( + f"Expected JSON from {resp.request.method} {resp.url}, got: {body_text(resp)}", + status=resp.status_code) from e diff --git a/simplyblock_core/storage_arrays/registry.py b/simplyblock_core/storage_arrays/registry.py new file mode 100644 index 0000000000..b868b75571 --- /dev/null +++ b/simplyblock_core/storage_arrays/registry.py @@ -0,0 +1,61 @@ +"""Vendor key -> adapter class. Adapters are imported lazily, on first use.""" +from __future__ import annotations + +import importlib + +from .base import ArrayAdapter, ArrayUnsupportedError + +#: vendor key -> "module:Class" (module relative to this package) +ADAPTERS: dict[str, str] = { + "pure-flasharray": "adapters.pure:PureFlashArrayAdapter", + "netapp-ontap": "adapters.netapp_ontap:NetAppOntapAdapter", + "dell-powerstore": "adapters.dell_powerstore:DellPowerStoreAdapter", + "dell-powermax": "adapters.dell_powermax:DellPowerMaxAdapter", + "dell-powerflex": "adapters.dell_powerflex:DellPowerFlexAdapter", + "hpe-wsapi": "adapters.hpe_wsapi:HpeWsapiAdapter", + "hpe-nimble": "adapters.hpe_nimble:HpeNimbleAdapter", + "ibm-flashsystem": "adapters.ibm_flashsystem:IbmFlashSystemAdapter", + "hitachi-vsp": "adapters.hitachi_vsp:HitachiVspAdapter", + "huawei-dorado": "adapters.huawei_dorado:HuaweiDoradoAdapter", + "infinidat-infinibox": "adapters.infinidat:InfinidatAdapter", +} + +#: Other names customers use for the same API. +ALIASES: dict[str, str] = { + "pure": "pure-flasharray", + "netapp": "netapp-ontap", + "netapp-asa": "netapp-ontap", + "lenovo-thinksystem-dm": "netapp-ontap", + "powerstore": "dell-powerstore", + "powermax": "dell-powermax", + "powerflex": "dell-powerflex", + "hpe-alletra-mp": "hpe-wsapi", + "hpe-primera": "hpe-wsapi", + "hpe-3par": "hpe-wsapi", + "hpe-alletra-6000": "hpe-nimble", + "hpe-alletra-5000": "hpe-nimble", + "ibm-storage-virtualize": "ibm-flashsystem", + "ibm-svc": "ibm-flashsystem", + "hitachi": "hitachi-vsp", + "huawei-oceanstor": "huawei-dorado", + "infinidat": "infinidat-infinibox", +} + + +def canonical_vendor(vendor: str) -> str: + key = vendor.strip().lower() + key = ALIASES.get(key, key) + if key not in ADAPTERS: + raise ArrayUnsupportedError( + f"Unknown array vendor {vendor!r}; supported: {', '.join(sorted(ADAPTERS))}") + return key + + +def adapter_class(vendor: str) -> type[ArrayAdapter]: + target = ADAPTERS[canonical_vendor(vendor)] + module_name, _, class_name = target.partition(":") + module = importlib.import_module(f"{__package__}.{module_name}") + cls = getattr(module, class_name) + if not (isinstance(cls, type) and issubclass(cls, ArrayAdapter)): + raise TypeError(f"{target} is not an ArrayAdapter") + return cls diff --git a/simplyblock_core/storage_arrays/testing/__init__.py b/simplyblock_core/storage_arrays/testing/__init__.py new file mode 100644 index 0000000000..b295365650 --- /dev/null +++ b/simplyblock_core/storage_arrays/testing/__init__.py @@ -0,0 +1,314 @@ +"""Stateful fakes of each vendor's management REST API. + +Each ``testing/.py`` module provides + +* a :class:`FakeArray` subclass that keeps volumes/hosts/mappings in memory + and answers the subset of the vendor API its adapter uses, with the + vendor's status codes, error bodies and quirks (async jobs, session + tokens, size units); and +* ``contract_setup()`` returning a :class:`ContractSetup` for the shared + contract suite. + +Fakes plug into ``requests`` in-process through :class:`FakeTransport` (no +sockets), or run as a real HTTPS server with :func:`serve` / ``python -m +simplyblock_core.storage_arrays.testing`` for end-to-end and UI testing. + +A fake encodes our reading of the vendor API. Passing the contract suite +proves the adapter logic; it does not prove API fidelity -- that needs the +same suite against a vendor simulator or a real array (``live`` tier). +""" +from __future__ import annotations + +import base64 +import io +import json +import re +import threading +from collections.abc import Callable +from dataclasses import dataclass, field +from typing import Any +from urllib.parse import parse_qs, urlsplit + +import requests +from requests.adapters import BaseAdapter +from requests.structures import CaseInsensitiveDict + +from simplyblock_core.credentials import Credential + +from ..base import ArrayConfig, Initiator, Protocol + +Handler = Callable[..., "Reply"] + + +@dataclass +class Request: + method: str + path: str + query: dict[str, list[str]] + headers: CaseInsensitiveDict + body: bytes + + def json(self) -> Any: + return json.loads(self.body) if self.body else None + + def q(self, name: str, default: str | None = None) -> str | None: + values = self.query.get(name) + return values[0] if values else default + + def basic_auth(self) -> tuple[str, str] | None: + header = self.headers.get("Authorization", "") + if not header.lower().startswith("basic "): + return None + user, _, pw = base64.b64decode(header[6:]).decode().partition(":") + return user, pw + + +@dataclass +class Reply: + status: int = 200 + body: Any = None + headers: dict[str, str] = field(default_factory=dict) + + +def route(method: str, pattern: str): + """Decorate a FakeArray method as the handler of ``method`` + path regex. + Named groups are passed as keyword arguments.""" + def deco(fn): + fn._route = (method.upper(), re.compile(f"^{pattern}$")) + return fn + return deco + + +class FakeArray: + """Base class: routing, fault injection, request log, thread safety.""" + + vendor: str = "" + + def __init__(self) -> None: + self.lock = threading.RLock() + self.requests: list[tuple[str, str]] = [] + self._faults: list[tuple[re.Pattern[str] | None, Reply, int]] = [] + self._routes: list[tuple[str, re.Pattern[str], Handler]] = [] + for name in dir(type(self)): + fn = getattr(type(self), name) + r = getattr(fn, "_route", None) + if r: + self._routes.append((r[0], r[1], getattr(self, name))) + self._id = 0 + + # -- helpers for subclasses ---------------------------------------------- + + def next_id(self) -> int: + self._id += 1 + return self._id + + # -- fault injection -------------------------------------------------------- + + def fail_next(self, status: int, body: Any = None, *, path: str | None = None, + times: int = 1) -> None: + """Answer the next ``times`` requests (optionally only those whose path + matches ``path`` regex) with ``status`` and ``body``.""" + with self.lock: + self._faults.append((re.compile(path) if path else None, Reply(status, body), times)) + + def expire_sessions(self) -> None: + """Invalidate every session token, as an array restart or timeout would. + Basic-auth fakes have nothing to expire.""" + + def set_credential(self, **fields: str) -> None: + """Change the credential the fake accepts (simulates rotation).""" + raise NotImplementedError + + # -- dispatch --------------------------------------------------------------- + + def handle(self, req: Request) -> Reply: + with self.lock: + self.requests.append((req.method, req.path)) + for i, (pattern, reply, times) in enumerate(self._faults): + if pattern is None or pattern.search(req.path): + if times <= 1: + del self._faults[i] + else: + self._faults[i] = (pattern, reply, times - 1) + return reply + for method, pattern, handler in self._routes: + if method != req.method: + continue + m = pattern.match(req.path) + if m: + try: + return handler(req, **m.groupdict()) + except FakeError as e: + return e.reply + return self.not_routed(req) + + def not_routed(self, req: Request) -> Reply: + return Reply(404, {"error": f"fake: no route for {req.method} {req.path}"}) + + +class FakeError(Exception): + """Raise inside a handler to answer with ``reply``.""" + + def __init__(self, status: int, body: Any = None, headers: dict[str, str] | None = None): + super().__init__(status) + self.reply = Reply(status, body, headers or {}) + + +class FakeTransport(BaseAdapter): + """A ``requests`` transport adapter answering from a :class:`FakeArray`.""" + + def __init__(self, fake: FakeArray): + super().__init__() + self.fake = fake + + def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None): + parts = urlsplit(request.url) + body = request.body or b"" + if isinstance(body, str): + body = body.encode() + req = Request( + method=request.method.upper(), + path=parts.path, + query=parse_qs(parts.query, keep_blank_values=True), + headers=CaseInsensitiveDict(request.headers), + body=body, + ) + reply = self.fake.handle(req) + return _to_response(request, reply) + + def close(self): + pass + + +def _encode(reply: Reply) -> tuple[bytes, dict[str, str]]: + headers = dict(reply.headers) + if reply.body is None: + return b"", headers + if isinstance(reply.body, bytes): + return reply.body, headers + if isinstance(reply.body, str): + headers.setdefault("Content-Type", "text/plain") + return reply.body.encode(), headers + headers.setdefault("Content-Type", "application/json") + return json.dumps(reply.body).encode(), headers + + +def _to_response(request, reply: Reply) -> requests.Response: + content, headers = _encode(reply) + resp = requests.Response() + resp.status_code = reply.status + resp.headers = CaseInsensitiveDict(headers) + resp.raw = io.BytesIO(content) + resp._content = content + resp.url = request.url + resp.request = request + resp.encoding = "utf-8" + resp.reason = "" + return resp + + +@dataclass +class ContractSetup: + """What the shared contract suite needs from a vendor fake.""" + + fake: FakeArray + config: ArrayConfig + credential: Credential + #: Credential the fake rejects. + bad_credential: Credential + #: Two distinct initiator sets per supported protocol, for two hosts. + initiators: dict[Protocol, tuple[tuple[Initiator, ...], tuple[Initiator, ...]]] + #: Create a volume directly on the fake (bypassing the client), for the + #: "not simplyblock-owned" checks. Returns the array's volume id. + create_foreign_volume: Callable[[str, int], str] + #: Whether mapping yields a LUN/NSID number. + has_lun_numbers: bool = True + + +def make_config(vendor: str, endpoint: str, **options: Any) -> ArrayConfig: + return ArrayConfig( + id=f"fake-{vendor}", + vendor=vendor, + endpoint=endpoint, + credential_ref={"kind": "vault-kv", "mount": "m", "path": f"arrays/{vendor}"}, + options=options, + ) + + +# -- standalone HTTPS mock server ------------------------------------------------ + + +def serve(fake: FakeArray, host: str = "127.0.0.1", port: int = 8443, + certfile: str | None = None, keyfile: str | None = None): + """Serve ``fake`` over HTTPS (a throwaway self-signed certificate is + generated unless ``certfile``/``keyfile`` are given). Returns the server; + call ``serve_forever()`` on it.""" + import ssl + import tempfile + from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + + class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def _do(self): + parts = urlsplit(self.path) + length = int(self.headers.get("Content-Length") or 0) + body = self.rfile.read(length) if length else b"" + reply = fake.handle(Request( + method=self.command, path=parts.path, + query=parse_qs(parts.query, keep_blank_values=True), + headers=CaseInsensitiveDict(dict(self.headers.items())), body=body)) + content, headers = _encode(reply) + self.send_response(reply.status) + for k, v in headers.items(): + self.send_header(k, v) + self.send_header("Content-Length", str(len(content))) + self.end_headers() + self.wfile.write(content) + + do_GET = do_POST = do_PUT = do_PATCH = do_DELETE = _do + + def log_message(self, fmt, *args): # quieter default logging + pass + + server = ThreadingHTTPServer((host, port), Handler) + if certfile is None: + tmp = tempfile.mkdtemp(prefix="sb-array-mock-") + certfile, keyfile = f"{tmp}/cert.pem", f"{tmp}/key.pem" + _self_signed(host, certfile, keyfile) + ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + ctx.load_cert_chain(certfile, keyfile) + server.socket = ctx.wrap_socket(server.socket, server_side=True) + server.certfile = certfile # type: ignore[attr-defined] + return server + + +def _self_signed(host: str, certfile: str, keyfile: str) -> None: + import datetime + import ipaddress + + from cryptography import x509 + from cryptography.hazmat.primitives import hashes, serialization + from cryptography.hazmat.primitives.asymmetric import ec + from cryptography.x509.oid import NameOID + + key = ec.generate_private_key(ec.SECP256R1()) + name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, host)]) + try: + san: x509.GeneralName = x509.IPAddress(ipaddress.ip_address(host)) + except ValueError: + san = x509.DNSName(host) + now = datetime.datetime.now(datetime.UTC) + cert = (x509.CertificateBuilder().subject_name(name).issuer_name(name) + .public_key(key.public_key()).serial_number(x509.random_serial_number()) + .not_valid_before(now - datetime.timedelta(minutes=5)) + .not_valid_after(now + datetime.timedelta(days=30)) + .add_extension(x509.SubjectAlternativeName([san]), critical=False) + .add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True) + .sign(key, hashes.SHA256())) + with open(certfile, "wb") as f: + f.write(cert.public_bytes(serialization.Encoding.PEM)) + with open(keyfile, "wb") as f: + f.write(key.private_bytes(serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption())) diff --git a/simplyblock_core/storage_arrays/testing/__main__.py b/simplyblock_core/storage_arrays/testing/__main__.py new file mode 100644 index 0000000000..6eee1688aa --- /dev/null +++ b/simplyblock_core/storage_arrays/testing/__main__.py @@ -0,0 +1,48 @@ +"""Run a vendor fake as an HTTPS mock server. + + python -m simplyblock_core.storage_arrays.testing --vendor pure-flasharray --port 8443 + +Prints the accepted credential, the CA certificate path (pass its content as +the array's ``ca_bundle``) and the options to register the array with. +""" +import argparse +import importlib +import json + +from ..registry import ADAPTERS, canonical_vendor + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--vendor", required=True, help=", ".join(sorted(ADAPTERS))) + parser.add_argument("--host", default="127.0.0.1") + parser.add_argument("--port", type=int, default=8443) + args = parser.parse_args() + + vendor = canonical_vendor(args.vendor) + module = importlib.import_module( + f"{__package__}.{ADAPTERS[vendor].split(':')[0].split('.')[-1]}") + setup = module.contract_setup() + server = serve_fake(setup.fake, args.host, args.port) + print(json.dumps({ + "vendor": vendor, + "endpoint": f"https://{args.host}:{args.port}", + "ca_bundle_file": server.certfile, + "credential_fields": sorted(setup.credential.field_names), + "credential": {k: setup.credential.get(k).get_secret_value() + for k in setup.credential.field_names}, + "options": setup.config.options, + }, indent=2)) + try: + server.serve_forever() + except KeyboardInterrupt: + pass + + +def serve_fake(fake, host, port): + from . import serve + return serve(fake, host, port) + + +if __name__ == "__main__": + main() diff --git a/simplyblock_core/storage_arrays/testing/pure.py b/simplyblock_core/storage_arrays/testing/pure.py new file mode 100644 index 0000000000..dd611d6bb0 --- /dev/null +++ b/simplyblock_core/storage_arrays/testing/pure.py @@ -0,0 +1,270 @@ +"""Fake Pure FlashArray REST 2.x (the subset the adapter uses).""" +from __future__ import annotations + +import secrets +from typing import Any, ClassVar + +from pydantic import SecretStr + +from simplyblock_core.credentials import Credential + +from ..base import Initiator, Protocol +from . import ContractSetup, FakeArray, FakeError, Reply, Request, make_config, route + +_V = r"/api/(?P2\.\d+)" + + +def _err(msg: str, status: int = 400) -> FakeError: + return FakeError(status, {"errors": [{"message": msg, "context": ""}]}) + + +class FakePureFlashArray(FakeArray): + vendor = "pure-flasharray" + versions: ClassVar[list[str]] = ["1.19", "2.0", "2.4", "2.17", "2.21"] + + def __init__(self, api_token: str = "pure-token"): + super().__init__() + self.api_token = api_token + self.sessions: set[str] = set() + self.volumes: dict[str, dict[str, Any]] = {} # id -> volume + self.hosts: dict[str, dict[str, Any]] = {} # name -> host + self.connections: list[dict[str, Any]] = [] # {host, volume_id, lun} + + # -- fake controls ------------------------------------------------------ + + def expire_sessions(self) -> None: + self.sessions.clear() + + def set_credential(self, **fields: str) -> None: + self.api_token = fields["api_token"] + + def add_volume(self, name: str, size: int) -> str: + vid = f"{secrets.token_hex(4)}-{self.next_id()}" + self.volumes[vid] = {"id": vid, "name": name, "provisioned": size, + "serial": secrets.token_hex(12).upper(), "destroyed": False} + return vid + + # -- auth --------------------------------------------------------------- + + def _auth(self, req: Request) -> None: + if req.headers.get("x-auth-token") not in self.sessions: + raise _err("Authentication failed.", 401) + + @route("GET", "/api/api_version") + def api_version(self, req): + return Reply(200, {"version": self.versions}) + + @route("POST", _V + "/login") + def login(self, req, ver): + if req.headers.get("api-token") != self.api_token: + raise _err("Invalid API token.", 401) + token = secrets.token_hex(8) + self.sessions.add(token) + return Reply(200, {"items": [{"username": "sb"}]}, {"x-auth-token": token}) + + @route("POST", _V + "/logout") + def logout(self, req, ver): + self.sessions.discard(req.headers.get("x-auth-token")) + return Reply(200, {}) + + @route("GET", _V + "/arrays") + def arrays(self, req, ver): + self._auth(req) + return Reply(200, {"items": [{"id": "fake-array-id", "name": "fake-fa", + "os": "Purity//FA", "version": "6.5.0"}]}) + + @route("GET", _V + "/controllers") + def controllers(self, req, ver): + self._auth(req) + return Reply(200, {"items": [{"name": "CT0", "model": "FA-X70R4"}]}) + + # -- volumes ------------------------------------------------------------- + + def _select(self, req) -> list[dict[str, Any]]: + if req.q("ids"): + ids = req.q("ids").split(",") + missing = [i for i in ids if i not in self.volumes] + if missing: + raise _err("Volume does not exist.") + return [self.volumes[i] for i in ids] + names = (req.q("names") or "").split(",") + found = [v for v in self.volumes.values() if v["name"] in names] + if len(found) < len(names): + raise _err("Volume does not exist.") + return found + + @route("GET", _V + "/volumes") + def get_volumes(self, req, ver): + self._auth(req) + return Reply(200, {"items": self._select(req)}) + + @route("POST", _V + "/volumes") + def post_volumes(self, req, ver): + self._auth(req) + name = req.q("names") + body = req.json() + if any(v["name"] == name for v in self.volumes.values()): + raise _err("Volume already exists.") + size = int(body["provisioned"]) + if size % 512: + raise _err("Volume size must be a multiple of 512.") + vid = self.add_volume(name, size) + return Reply(200, {"items": [self.volumes[vid]]}) + + @route("PATCH", _V + "/volumes") + def patch_volumes(self, req, ver): + self._auth(req) + body = req.json() + vols = self._select(req) + for v in vols: + if "provisioned" in body: + size = int(body["provisioned"]) + if size < v["provisioned"] and not body.get("truncate"): + raise _err("Implicit truncation is not permitted.") + v["provisioned"] = size + if body.get("destroyed"): + if any(c["volume_id"] == v["id"] for c in self.connections): + raise _err("Volume has host connections.") + v["destroyed"] = True + return Reply(200, {"items": vols}) + + @route("DELETE", _V + "/volumes") + def delete_volumes(self, req, ver): + self._auth(req) + for v in self._select(req): + if not v["destroyed"]: + raise _err("Volume must be destroyed before eradication.") + del self.volumes[v["id"]] + return Reply(200, {}) + + # -- hosts ---------------------------------------------------------------- + + def _owner(self, key: str, value: str) -> str | None: + for h in self.hosts.values(): + if value.lower() in (x.lower() for x in h[key]): + return h["name"] + return None + + @route("GET", _V + "/hosts") + def get_hosts(self, req, ver): + self._auth(req) + name = req.q("names") + if name not in self.hosts: + raise _err("Host does not exist.") + return Reply(200, {"items": [self.hosts[name]]}) + + def _claim(self, host: str, body: dict[str, Any], prefix: str = "") -> None: + for key in ("iqns", "wwns", "nqns"): + for value in body.get(prefix + key, []): + owner = self._owner(key, value) + if owner and owner != host: + raise _err(f"{value} is already in use by host {owner}.") + if key == "wwns" and len(value.replace(":", "")) != 16: + raise _err("Invalid WWN.") + if value.lower() not in (x.lower() for x in self.hosts[host][key]): + self.hosts[host][key].append(value) + + @route("POST", _V + "/hosts") + def post_hosts(self, req, ver): + self._auth(req) + name = req.q("names") + if name in self.hosts: + raise _err("Host already exists.") + self.hosts[name] = {"name": name, "iqns": [], "wwns": [], "nqns": []} + try: + self._claim(name, req.json() or {}) + except FakeError: + del self.hosts[name] + raise + return Reply(200, {"items": [self.hosts[name]]}) + + @route("PATCH", _V + "/hosts") + def patch_hosts(self, req, ver): + self._auth(req) + name = req.q("names") + if name not in self.hosts: + raise _err("Host does not exist.") + self._claim(name, req.json() or {}, prefix="add_") + return Reply(200, {"items": [self.hosts[name]]}) + + @route("DELETE", _V + "/hosts") + def delete_hosts(self, req, ver): + self._auth(req) + name = req.q("names") + if name not in self.hosts: + raise _err("Host does not exist.") + if any(c["host"] == name for c in self.connections): + raise _err("Host has volume connections.") + del self.hosts[name] + return Reply(200, {}) + + # -- connections ------------------------------------------------------------ + + def _conn_item(self, c): + v = self.volumes[c["volume_id"]] + return {"host": {"name": c["host"]}, "volume": {"id": v["id"], "name": v["name"]}, + "lun": c["lun"]} + + @route("GET", _V + "/connections") + def get_connections(self, req, ver): + self._auth(req) + vid, host = req.q("volume_ids"), req.q("host_names") + if vid and vid not in self.volumes: + raise _err("Volume does not exist.") + items = [self._conn_item(c) for c in self.connections + if (not vid or c["volume_id"] == vid) and (not host or c["host"] == host)] + return Reply(200, {"items": items}) + + @route("POST", _V + "/connections") + def post_connections(self, req, ver): + self._auth(req) + vid, host = req.q("volume_ids"), req.q("host_names") + if vid not in self.volumes or self.volumes[vid]["destroyed"]: + raise _err("Volume does not exist.") + if host not in self.hosts: + raise _err("Host does not exist.") + if any(c["volume_id"] == vid and c["host"] == host for c in self.connections): + raise _err("Connection already exists.") + used = {c["lun"] for c in self.connections if c["host"] == host} + lun = next(n for n in range(1, 4096) if n not in used) + c = {"host": host, "volume_id": vid, "lun": lun} + self.connections.append(c) + return Reply(200, {"items": [self._conn_item(c)]}) + + @route("DELETE", _V + "/connections") + def delete_connections(self, req, ver): + self._auth(req) + vid, host = req.q("volume_ids"), req.q("host_names") + before = len(self.connections) + self.connections = [c for c in self.connections + if not (c["volume_id"] == vid and c["host"] == host)] + if len(self.connections) == before: + raise _err("Connection does not exist.") + return Reply(200, {}) + + +def contract_setup() -> ContractSetup: + fake = FakePureFlashArray(api_token="pure-token") + return ContractSetup( + fake=fake, + config=make_config("pure-flasharray", "https://pure.fake.example"), + credential=Credential({"api_token": SecretStr("pure-token")}), + bad_credential=Credential({"api_token": SecretStr("wrong")}), + initiators={ + Protocol.ISCSI: ( + (Initiator(protocol=Protocol.ISCSI, address="iqn.2026-01.io.sb:host-a"),), + (Initiator(protocol=Protocol.ISCSI, address="iqn.2026-01.io.sb:host-b"),), + ), + Protocol.FC: ( + (Initiator(protocol=Protocol.FC, address="21:00:00:24:ff:4c:1a:2b"),), + (Initiator(protocol=Protocol.FC, address="21:00:00:24:ff:4c:1a:2c"),), + ), + Protocol.NVME_TCP: ( + (Initiator(protocol=Protocol.NVME_TCP, + address="nqn.2014-08.org.nvmexpress:uuid:host-a"),), + (Initiator(protocol=Protocol.NVME_TCP, + address="nqn.2014-08.org.nvmexpress:uuid:host-b"),), + ), + }, + create_foreign_volume=lambda name, size: fake.add_volume(name, size), + ) diff --git a/tests/unit/storage_arrays/__init__.py b/tests/unit/storage_arrays/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/storage_arrays/conftest.py b/tests/unit/storage_arrays/conftest.py new file mode 100644 index 0000000000..44d8985189 --- /dev/null +++ b/tests/unit/storage_arrays/conftest.py @@ -0,0 +1,115 @@ +"""Shared fixtures: run ArrayClient against a vendor fake (in-process) or, +with ``SB_ARRAY_LIVE_CONFIG=``, against a real array/simulator. + +Live config file:: + + {"vendor": "netapp-ontap", "endpoint": "https://cluster1.lab:443", + "credential": {"username": "...", "password": "..."}, + "ca_bundle": "-----BEGIN CERTIFICATE-----...", "verify_tls": true, + "options": {"svm": "svm1"}, + "initiators": {"iscsi": [["iqn...a"], ["iqn...b"]]}} + +The live tier creates and deletes only ``sb-`` volumes and ``sbtest-`` hosts. +""" +from __future__ import annotations + +import importlib +import json +import os + +import pytest +from pydantic import SecretStr + +from simplyblock_core.credentials import Credential +from simplyblock_core.storage_arrays.base import ArrayConfig, Initiator, Protocol +from simplyblock_core.storage_arrays.client import ArrayClient +from simplyblock_core.storage_arrays.registry import ADAPTERS +from simplyblock_core.storage_arrays.testing import ContractSetup, FakeTransport + +VENDORS = sorted(ADAPTERS) + + +class StaticProvider: + """Stands in for CredentialProvider: returns ``credential`` and counts + invalidations. Tests flip ``credential`` to simulate rotation.""" + + def __init__(self, credential: Credential): + self.credential = credential + self.resolved: list[str] = [] + self.invalidated = 0 + + def resolve(self, ref, context): + self.resolved.append(context) + return self.credential + + def invalidate(self, ref=None): + self.invalidated += 1 + + +def fake_module(vendor: str): + tail = ADAPTERS[vendor].split(":")[0].split(".")[-1] + try: + return importlib.import_module(f"simplyblock_core.storage_arrays.testing.{tail}") + except ModuleNotFoundError as e: + if e.name and e.name.endswith(tail): + pytest.skip(f"no fake for {vendor} yet") + raise + + +class Harness: + def __init__(self, setup: ContractSetup, live: bool = False): + self.setup = setup + self.live = live + self.provider = StaticProvider(setup.credential) + self.client = ArrayClient( + setup.config, self.provider, # type: ignore[arg-type] + transport=None if live else FakeTransport(setup.fake), + session_kwargs={"sleep": lambda s: None}, + ) + + @property + def fake(self): + return self.setup.fake + + +def _live_setup(path: str) -> ContractSetup: + with open(path) as f: + cfg = json.load(f) + initiators = { + Protocol(proto): tuple( + tuple(Initiator(protocol=Protocol(proto), address=a) for a in group) + for group in groups) + for proto, groups in cfg["initiators"].items() + } + return ContractSetup( + fake=None, # type: ignore[arg-type] + config=ArrayConfig(id="live", vendor=cfg["vendor"], endpoint=cfg["endpoint"], + credential_ref={"kind": "vault-kv", "mount": "m", "path": "p"}, + ca_bundle=cfg.get("ca_bundle"), + verify_tls=cfg.get("verify_tls", True), + options=cfg.get("options", {})), + credential=Credential({k: SecretStr(v) for k, v in cfg["credential"].items()}), + bad_credential=Credential({k: SecretStr("wrong-" + v) + for k, v in cfg["credential"].items()}), + initiators=initiators, + create_foreign_volume=None, # type: ignore[arg-type] + has_lun_numbers=cfg.get("has_lun_numbers", True), + ) + + +def _params(): + live = os.environ.get("SB_ARRAY_LIVE_CONFIG") + if live: + return [pytest.param(("live", live), id="live")] + return [pytest.param(("fake", v), id=v) for v in VENDORS] + + +@pytest.fixture(params=_params()) +def harness(request) -> Harness: + kind, value = request.param + if kind == "live": + h = Harness(_live_setup(value), live=True) + else: + h = Harness(fake_module(value).contract_setup()) + yield h + h.client.close() diff --git a/tests/unit/storage_arrays/test_contract.py b/tests/unit/storage_arrays/test_contract.py new file mode 100644 index 0000000000..6e36507a59 --- /dev/null +++ b/tests/unit/storage_arrays/test_contract.py @@ -0,0 +1,270 @@ +"""The contract every array adapter must meet, run against each vendor fake +(and, with SB_ARRAY_LIVE_CONFIG, against one real array or simulator).""" +from __future__ import annotations + +import uuid + +import pytest + +from simplyblock_core.storage_arrays.base import ( + ArrayAuthError, + ArrayConflictError, + ArrayError, + ArrayRequestError, + HostSpec, + Protocol, +) +from simplyblock_core.storage_arrays.client import MANAGED_PREFIX, round_size + +GIB = 1 << 30 + + +def _uuid() -> str: + return str(uuid.uuid4()) + + +def _protocols(h): + return [p for p in h.setup.initiators if p in h.client.capabilities.protocols] + + +def _host(h, protocol, which=0, name=None): + return HostSpec(name=name or f"sbtest-{protocol.value}-{which}-{uuid.uuid4().hex[:6]}", + initiators=h.setup.initiators[protocol][which]) + + +@pytest.fixture() +def cleanup(harness): + volumes, hosts = [], [] + yield volumes, hosts + for vid in volumes: + try: + harness.client.delete_volume(vid) + except ArrayError: + pass + for host in hosts: + try: + harness.client.delete_host(host) + except ArrayError: + pass + + +def test_adapter_declares_itself(harness): + cls = harness.client.adapter_cls + assert cls.vendor == harness.client.vendor + assert cls.display_name + caps = cls.capabilities + assert caps.protocols + assert caps.size_granularity_bytes > 0 and caps.min_size_bytes > 0 + assert caps.max_name_len >= len(MANAGED_PREFIX) + 16 + assert set(_protocols(harness)), "fake provides no initiators for a supported protocol" + + +def test_get_info(harness): + info = harness.client.get_info() + assert info.vendor == harness.client.vendor + assert harness.provider.resolved[0].startswith("array/") + + +def test_create_get_find(harness, cleanup): + vol_uuid = _uuid() + vol = harness.client.create_volume(vol_uuid, 10 * GIB + 1) + cleanup[0].append(vol.id) + caps = harness.client.capabilities + assert vol.name == harness.client.volume_name(vol_uuid) + assert vol.name.startswith(MANAGED_PREFIX) + assert len(vol.name) <= caps.max_name_len + assert vol.size_bytes == round_size(10 * GIB + 1, caps.size_granularity_bytes, + caps.min_size_bytes) + assert vol.identifier and vol.identifier == vol.identifier.lower() + assert vol.wwn is None or vol.wwn.startswith("naa.") + assert vol.nguid is None or vol.nguid.startswith("eui.") + + got = harness.client.get_volume(vol.id) + assert got == vol + assert harness.client.find_volume(vol_uuid) == vol + + +def test_missing_volume_is_none(harness): + assert harness.client.find_volume(_uuid()) is None + + +def test_get_volume_of_deleted_is_none(harness, cleanup): + vol = harness.client.create_volume(_uuid(), GIB) + assert harness.client.delete_volume(vol.id) is True + assert harness.client.get_volume(vol.id) is None + assert harness.client.delete_volume(vol.id) is False + + +def test_create_is_idempotent(harness, cleanup): + vol_uuid = _uuid() + first = harness.client.create_volume(vol_uuid, 4 * GIB) + cleanup[0].append(first.id) + again = harness.client.create_volume(vol_uuid, 4 * GIB) + assert again.id == first.id and again.identifier == first.identifier + + +def test_create_rerun_with_larger_size_grows(harness, cleanup): + vol_uuid = _uuid() + first = harness.client.create_volume(vol_uuid, 8 * GIB) + cleanup[0].append(first.id) + again = harness.client.create_volume(vol_uuid, 16 * GIB) + assert again.id == first.id and again.size_bytes >= 16 * GIB + + +def test_resize(harness, cleanup): + vol = harness.client.create_volume(_uuid(), 8 * GIB) + cleanup[0].append(vol.id) + grown = harness.client.resize_volume(vol.id, 24 * GIB, expected_identifier=vol.identifier) + assert grown.size_bytes >= 24 * GIB + assert grown.identifier == vol.identifier + assert harness.client.get_volume(vol.id).size_bytes == grown.size_bytes + # same size: no-op + assert harness.client.resize_volume(vol.id, grown.size_bytes) == grown + with pytest.raises(ArrayConflictError, match="shrink"): + harness.client.resize_volume(vol.id, 8 * GIB) + + +def test_host_and_mapping_lifecycle(harness, cleanup): + for protocol in _protocols(harness): + vol = harness.client.create_volume(_uuid(), GIB * 8) + cleanup[0].append(vol.id) + spec_a = _host(harness, protocol, 0) + spec_b = _host(harness, protocol, 1) + host_a = harness.client.ensure_host(spec_a) + cleanup[1].append(host_a) + assert harness.client.ensure_host(spec_a) == host_a, "ensure_host not idempotent" + host_b = harness.client.ensure_host(spec_b) + cleanup[1].append(host_b) + assert host_a != host_b + + m_a = harness.client.map_volume(vol.id, host_a, expected_identifier=vol.identifier) + assert m_a.host_id == host_a and m_a.volume_id == vol.id + if harness.setup.has_lun_numbers: + assert isinstance(m_a.lun, int) and m_a.lun >= 0 + assert harness.client.map_volume(vol.id, host_a) == m_a, "map not idempotent" + m_b = harness.client.map_volume(vol.id, host_b) # multi-attach + + hosts = {m.host_id for m in harness.client.list_mappings(vol.id)} + assert hosts == {host_a, host_b} + + harness.client.unmap_volume(vol.id, host_a) + harness.client.unmap_volume(vol.id, host_a) # idempotent + assert [m.host_id for m in harness.client.list_mappings(vol.id)] == [m_b.host_id] + + # delete unmaps the remaining host first + assert harness.client.delete_volume(vol.id, expected_identifier=vol.identifier) + cleanup[0].remove(vol.id) + assert harness.client.get_volume(vol.id) is None + + harness.client.delete_host(host_a) + harness.client.delete_host(host_a) # absent: no-op + harness.client.delete_host(host_b) + cleanup[1].clear() + + +def test_initiator_owned_by_another_host_conflicts(harness, cleanup): + protocol = _protocols(harness)[0] + first = _host(harness, protocol, 0) + cleanup[1].append(harness.client.ensure_host(first)) + other = HostSpec(name=f"sbtest-other-{uuid.uuid4().hex[:6]}", initiators=first.initiators) + with pytest.raises(ArrayConflictError): + cleanup[1].append(harness.client.ensure_host(other)) + + +def test_existing_host_gets_missing_initiators(harness, cleanup): + protocol = _protocols(harness)[0] + a, b = harness.setup.initiators[protocol] + name = f"sbtest-grow-{uuid.uuid4().hex[:6]}" + host = harness.client.ensure_host(HostSpec(name=name, initiators=a)) + cleanup[1].append(host) + assert harness.client.ensure_host(HostSpec(name=name, initiators=a + b)) == host + # b's initiators now belong to that host: claiming them elsewhere conflicts + with pytest.raises(ArrayConflictError): + cleanup[1].append(harness.client.ensure_host( + HostSpec(name=f"sbtest-x-{uuid.uuid4().hex[:6]}", initiators=b))) + + +def test_wrong_identifier_is_refused(harness, cleanup): + vol = harness.client.create_volume(_uuid(), GIB) + cleanup[0].append(vol.id) + for action in ( + lambda: harness.client.delete_volume(vol.id, expected_identifier="naa.600000000000"), + lambda: harness.client.resize_volume(vol.id, 4 * GIB, expected_identifier="naa.6000"), + ): + with pytest.raises(ArrayConflictError, match="does not match"): + action() + assert harness.client.get_volume(vol.id) is not None + + +def test_foreign_volume_is_refused(harness): + if harness.live: + pytest.skip("live tier never touches foreign volumes") + vid = harness.setup.create_foreign_volume("customer-db01", 4 * GIB) + for action in (lambda: harness.client.delete_volume(vid), + lambda: harness.client.resize_volume(vid, 8 * GIB)): + with pytest.raises(ArrayConflictError, match="not created by simplyblock"): + action() + assert harness.client.get_volume(vid) is not None + + +def test_session_expiry_is_transparent(harness, cleanup): + if harness.live: + pytest.skip("cannot expire a real array's sessions") + harness.client.get_info() + harness.fake.expire_sessions() + vol = harness.client.create_volume(_uuid(), GIB) + cleanup[0].append(vol.id) + assert harness.client.get_volume(vol.id) == vol + + +def test_bad_credential_raises_auth_error_after_one_retry(harness): + harness.provider.credential = harness.setup.bad_credential + with pytest.raises(ArrayAuthError): + harness.client.get_info() + assert harness.provider.invalidated == 1 + assert len(harness.provider.resolved) == 2 + + +def test_rotated_credential_is_picked_up(harness): + if harness.live: + pytest.skip("needs control of the array's credential") + harness.client.get_info() + new = {k: "rotated-" + harness.setup.credential.get(k).get_secret_value() + for k in harness.setup.credential.field_names} + harness.fake.set_credential(**new) + harness.fake.expire_sessions() + from pydantic import SecretStr + + from simplyblock_core.credentials import Credential + old_secret_values = {harness.setup.credential.get(k).get_secret_value() + for k in harness.setup.credential.field_names} + harness.provider.credential = Credential({k: SecretStr(v) for k, v in new.items()}) + # A basic-auth adapter keeps the old password in its session until it is + # rejected; either way the client must recover with one invalidation. + harness.client.get_info() + assert harness.provider.invalidated <= 1 + assert old_secret_values # silence unused + + +def test_server_error_does_not_leak_credentials(harness): + if harness.live: + pytest.skip("fault injection needs the fake") + harness.client.get_info() + harness.fake.fail_next(500, {"error": "internal"}, times=50) + with pytest.raises(ArrayRequestError) as e: + harness.client.create_volume(_uuid(), GIB) + text = str(e.value) + for name in harness.setup.credential.field_names: + assert harness.setup.credential.get(name).get_secret_value() not in text + + +def test_unsupported_protocol_is_refused_before_calling_the_array(harness): + unsupported = [p for p in Protocol if p not in harness.client.capabilities.protocols] + if not unsupported: + pytest.skip("adapter supports every protocol") + from simplyblock_core.storage_arrays.base import Initiator + p = unsupported[0] + address = "21:00:00:24:ff:4c:1a:99" if p in (Protocol.FC, Protocol.NVME_FC) else "x" + with pytest.raises(ArrayError, match="does not support"): + harness.client.ensure_host(HostSpec(name="sbtest-unsup", + initiators=(Initiator(protocol=p, address=address),))) From e90d205ddd41f3718eaa66dd1df9b052274dc71e Mon Sep 17 00:00:00 2001 From: michael Date: Fri, 20 Nov 2026 14:15:06 +0100 Subject: [PATCH 3/4] feat(storage_arrays): adapters for all supported array families Ten more adapters behind the ArrayAdapter contract, each with a stateful fake of the vendor REST API and vendor-specific tests: NetApp ONTAP, Dell PowerStore / PowerMax / PowerFlex, HPE WSAPI (Alletra MP, Primera, 3PAR), HPE Nimble (Alletra 5000/6000), IBM FlashSystem, Hitachi VSP, Huawei OceanStor Dorado, Infinidat InfiniBox. Framework follow-ups from integrating them: - Volume.wwn holds any SCSI designator (naa. or eui. for Nimble). - NVMe/FC initiators are NQNs, not WWPNs. - Capabilities.max_initiators_per_host (PowerFlex SDC hosts = 1). - Client pins resize/map/delete to the name derived from the recorded volume UUID (array ids and WWNs can be reused after delete, e.g. VSP). - RestSession.sleep is public (async job polling without real waits). - Fake transport fills the cookie jar like a real response. - Contract: delete_host must not drop live mappings (Pure now checks). Each adapter lists unverified API details under "Verify against a real system"; nothing has run against real hardware yet. Co-Authored-By: Claude Opus 5.5 --- simplyblock_core/storage_arrays/README.md | 69 ++ .../storage_arrays/adapters/dell_powerflex.py | 351 ++++++++ .../storage_arrays/adapters/dell_powermax.py | 434 +++++++++ .../adapters/dell_powerstore.py | 332 +++++++ .../storage_arrays/adapters/hitachi_vsp.py | 570 ++++++++++++ .../storage_arrays/adapters/hpe_nimble.py | 321 +++++++ .../storage_arrays/adapters/hpe_wsapi.py | 317 +++++++ .../storage_arrays/adapters/huawei_dorado.py | 426 +++++++++ .../adapters/ibm_flashsystem.py | 378 ++++++++ .../storage_arrays/adapters/infinidat.py | 290 ++++++ .../storage_arrays/adapters/netapp_ontap.py | 799 +++++++++++++++++ .../storage_arrays/adapters/pure.py | 4 + simplyblock_core/storage_arrays/base.py | 13 +- simplyblock_core/storage_arrays/client.py | 36 +- simplyblock_core/storage_arrays/http.py | 8 +- .../storage_arrays/testing/__init__.py | 17 +- .../storage_arrays/testing/dell_powerflex.py | 289 ++++++ .../storage_arrays/testing/dell_powermax.py | 593 +++++++++++++ .../storage_arrays/testing/dell_powerstore.py | 426 +++++++++ .../storage_arrays/testing/hitachi_vsp.py | 616 +++++++++++++ .../storage_arrays/testing/hpe_nimble.py | 363 ++++++++ .../storage_arrays/testing/hpe_wsapi.py | 321 +++++++ .../storage_arrays/testing/huawei_dorado.py | 589 +++++++++++++ .../storage_arrays/testing/ibm_flashsystem.py | 395 +++++++++ .../storage_arrays/testing/infinidat.py | 315 +++++++ .../storage_arrays/testing/netapp_ontap.py | 832 ++++++++++++++++++ tests/unit/storage_arrays/test_contract.py | 46 +- .../storage_arrays/test_dell_powerflex.py | 189 ++++ .../unit/storage_arrays/test_dell_powermax.py | 256 ++++++ .../storage_arrays/test_dell_powerstore.py | 212 +++++ tests/unit/storage_arrays/test_framework.py | 223 +++++ tests/unit/storage_arrays/test_hitachi_vsp.py | 360 ++++++++ tests/unit/storage_arrays/test_hpe_nimble.py | 188 ++++ tests/unit/storage_arrays/test_hpe_wsapi.py | 188 ++++ .../unit/storage_arrays/test_huawei_dorado.py | 172 ++++ .../storage_arrays/test_ibm_flashsystem.py | 187 ++++ tests/unit/storage_arrays/test_infinidat.py | 147 ++++ .../unit/storage_arrays/test_netapp_ontap.py | 430 +++++++++ 38 files changed, 11680 insertions(+), 22 deletions(-) create mode 100644 simplyblock_core/storage_arrays/README.md create mode 100644 simplyblock_core/storage_arrays/adapters/dell_powerflex.py create mode 100644 simplyblock_core/storage_arrays/adapters/dell_powermax.py create mode 100644 simplyblock_core/storage_arrays/adapters/dell_powerstore.py create mode 100644 simplyblock_core/storage_arrays/adapters/hitachi_vsp.py create mode 100644 simplyblock_core/storage_arrays/adapters/hpe_nimble.py create mode 100644 simplyblock_core/storage_arrays/adapters/hpe_wsapi.py create mode 100644 simplyblock_core/storage_arrays/adapters/huawei_dorado.py create mode 100644 simplyblock_core/storage_arrays/adapters/ibm_flashsystem.py create mode 100644 simplyblock_core/storage_arrays/adapters/infinidat.py create mode 100644 simplyblock_core/storage_arrays/adapters/netapp_ontap.py create mode 100644 simplyblock_core/storage_arrays/testing/dell_powerflex.py create mode 100644 simplyblock_core/storage_arrays/testing/dell_powermax.py create mode 100644 simplyblock_core/storage_arrays/testing/dell_powerstore.py create mode 100644 simplyblock_core/storage_arrays/testing/hitachi_vsp.py create mode 100644 simplyblock_core/storage_arrays/testing/hpe_nimble.py create mode 100644 simplyblock_core/storage_arrays/testing/hpe_wsapi.py create mode 100644 simplyblock_core/storage_arrays/testing/huawei_dorado.py create mode 100644 simplyblock_core/storage_arrays/testing/ibm_flashsystem.py create mode 100644 simplyblock_core/storage_arrays/testing/infinidat.py create mode 100644 simplyblock_core/storage_arrays/testing/netapp_ontap.py create mode 100644 tests/unit/storage_arrays/test_dell_powerflex.py create mode 100644 tests/unit/storage_arrays/test_dell_powermax.py create mode 100644 tests/unit/storage_arrays/test_dell_powerstore.py create mode 100644 tests/unit/storage_arrays/test_framework.py create mode 100644 tests/unit/storage_arrays/test_hitachi_vsp.py create mode 100644 tests/unit/storage_arrays/test_hpe_nimble.py create mode 100644 tests/unit/storage_arrays/test_hpe_wsapi.py create mode 100644 tests/unit/storage_arrays/test_huawei_dorado.py create mode 100644 tests/unit/storage_arrays/test_ibm_flashsystem.py create mode 100644 tests/unit/storage_arrays/test_infinidat.py create mode 100644 tests/unit/storage_arrays/test_netapp_ontap.py diff --git a/simplyblock_core/storage_arrays/README.md b/simplyblock_core/storage_arrays/README.md new file mode 100644 index 0000000000..83bbbd7696 --- /dev/null +++ b/simplyblock_core/storage_arrays/README.md @@ -0,0 +1,69 @@ +# External storage arrays + +Provision, resize and delete volumes (LUNs and NVMe namespaces) on enterprise arrays, and map them to hosts. +There is no usable cross-vendor standard, so each array has its own adapter. SMI-S is deprecated, Swordfish has almost no array support, and CSI drivers depend on Kubernetes. + +## Supported systems + +| Key | Systems | API | Protocols | +|---|---|---|---| +| `pure-flasharray` | Pure FlashArray //X, //C, //XL, //E | REST 2.x, API token | iSCSI, FC, NVMe/TCP, /RoCE, /FC | +| `netapp-ontap` | NetApp AFF/FAS/ASA (not ASA r2), Lenovo DM | ONTAP REST | iSCSI, FC, NVMe/TCP, /FC (`protocol_family`) | +| `dell-powerstore` | Dell PowerStore | REST | iSCSI, FC, NVMe/TCP, /FC | +| `dell-powermax` | Dell PowerMax | Unisphere REST | iSCSI, FC, NVMe (port-group per protocol) | +| `dell-powerflex` | Dell PowerFlex 3.6 / 4.x | Gateway REST / PFxM OAuth | SDC | +| `hpe-wsapi` | HPE Alletra Storage MP B10000, Primera, 3PAR | WSAPI | iSCSI, FC | +| `hpe-nimble` | HPE Alletra 5000/6000, Nimble | NimbleOS REST | iSCSI, FC | +| `ibm-flashsystem` | IBM FlashSystem, Storage Virtualize/SVC | REST (port 7443) | iSCSI, FC, NVMe/TCP, /RDMA | +| `hitachi-vsp` | Hitachi VSP One Block, VSP E, VSP 5000 | Configuration Manager REST | iSCSI, FC | +| `huawei-dorado` | Huawei OceanStor Dorado | DeviceManager REST | iSCSI, FC | +| `infinidat-infinibox` | Infinidat InfiniBox | REST | iSCSI, FC | + +Each adapter's module docstring lists the options it reads, the credential fields it needs, and a section called **"Verify against a real system"**. +That section names every API detail its author was unsure of. Work through it before the adapter is first used against a real array. + +## Layers + +- `base.py`: the adapter contract (`ArrayAdapter`) and the shared model. +- `client.py`: `ArrayClient`, the only entry point for the rest of simplyblock. It handles: + - credentials through `simplyblock_core.credentials`, bound to the array id and endpoint, with re-authentication and one retry on auth failure; + - `sb-` volume names and rounding sizes to the array's granularity; + - making create, map, unmap and delete safe to re-run; + - safety checks before resize, map or delete: the `sb-` name prefix, the name derived from the recorded volume UUID, and the recorded WWN/NGUID; + - refusing to shrink a volume. +- `http.py`: TLS (pinned CA bundle per array), timeouts, retries, error mapping. +- `registry.py`: maps vendor keys and aliases to adapters, loading each adapter on first use. + +## Testing + +1. **Contract suite against fakes** (`tests/unit/storage_arrays/test_contract.py`). + `testing/.py` is a stateful in-memory fake of the vendor's REST API: paths, JSON shapes, status codes, error bodies, async jobs, session tokens. + Every adapter runs the same suite against its fake, through a `requests` transport, with no network. + This shows the adapter's logic is right. It does **not** show the fake matches the real API; the fakes encode our reading of each vendor's API. +2. **Vendor unit tests** (`test_.py`): unit conversions, identifier derivation, job polling and failures, error mapping, options. +3. **HTTPS mock server**, for end-to-end and UI work: + ``` + python -m simplyblock_core.storage_arrays.testing --vendor netapp-ontap --port 8443 + ``` + It prints the endpoint, the CA file, the credential and the options to register. +4. **Live tier**: the same contract suite against a simulator or a real array: + ``` + SB_ARRAY_LIVE_CONFIG=lab-array.json python -m pytest tests/unit/storage_arrays/test_contract.py --timeout-method=thread + ``` + See `tests/unit/storage_arrays/conftest.py` for the file format. The live tier only creates and deletes `sb-` volumes and `sbtest-` hosts. + +### Where to get something real to test against + +These are partly from memory; check availability with each vendor. + +- **NetApp:** ONTAP Select evaluation, and the ONTAP simulator (support-site login). Both have the full REST API. A Lab on Demand is also an option. +- **Pure:** Pure Test Drive labs. There is no downloadable FlashArray simulator. +- **Dell:** PowerFlex can be installed on 3 VMs. Dell demo labs cover PowerStore and PowerMax. PowerStore has a virtual edition for partners. +- **HPE:** the 3PAR StoreServ simulator (older WSAPI). Alletra through HPE demo and partner labs. +- **IBM:** Storage Virtualize for Public Cloud, plus IBM Technology Zone labs. +- **Hitachi, Huawei:** partner and demo labs only. +- **Infinidat:** `infinisim`, an open-source Python simulator of the InfiniBox API. + +Vendor SDKs make good reference code for API details: `py-pure-client`, `netapp-ontap`, `PyPowerStore`, `PyU4V`, `PyPowerFlex`, `hpe3parclient`, `nimble-sdk`, `infinisdk`. +The same goes for each vendor's Ansible collection, CSI driver and OpenStack Cinder driver. +This package uses plain `requests` and does not depend on any of them. diff --git a/simplyblock_core/storage_arrays/adapters/dell_powerflex.py b/simplyblock_core/storage_arrays/adapters/dell_powerflex.py new file mode 100644 index 0000000000..12e017bb2f --- /dev/null +++ b/simplyblock_core/storage_arrays/adapters/dell_powerflex.py @@ -0,0 +1,351 @@ +"""Dell PowerFlex (formerly ScaleIO / VxFlex OS), REST gateway API, PowerFlex +3.6 and 4.x. + +Auth (option ``auth``): + +* ``token`` (3.x gateway): ``GET /api/login`` with HTTP basic + ``username:password`` returns a session token as a JSON *string*; every + later request uses basic auth ``username:``. The token expires after + 8 h, or 10 min idle (-> 401; the client logs in again). + ``GET /api/logout`` invalidates it. +* ``oauth`` (4.x, PowerFlex Manager gateway): ``POST /rest/auth/login`` + ``{"username", "password"}`` returns ``{"access_token", "refresh_token", + ...}``; requests carry ``Authorization: Bearer ``. The + ``/api/...`` paths below are unchanged behind the 4.x gateway. + ``POST /rest/auth/logout {"refresh_token"}`` ends the session. The access + token is short-lived (minutes); rather than refreshing it, the adapter + logs in again on the 401 (``ArrayClient`` does this transparently). +* ``auto`` (default): try ``oauth``; a 404/405 from ``/rest/auth/login`` + means a 3.x gateway, so fall back to ``token``. + +Volumes are addressed by their 16-hex-digit id (``Volume::``). Sizes +are in KiB on create and GiB on resize and are rounded up by the array to a +multiple of 8 GiB, so the adapter declares 8 GiB granularity and minimum. +Names are at most 31 characters. Volumes are created thin +(``ThinProvisioned``) in the ``storage_pool_id`` option's pool. + +Hosts: PowerFlex's native protocol is the SDC (storage data client) kernel +driver, which registers itself with the MDM when installed on the host. The +adapter never creates SDCs: ``ensure_host`` looks the SDC up by its GUID +(the initiator address, ``drv_cfg --query_guid`` on the host) and returns +its id as the host id. An SDC is one OS instance, so a host has exactly one +SDC GUID; specs with more are refused (:class:`ArrayUnsupportedError`). + +SDC names stand in for host ownership (option ``sdc_naming``): + +* ``claim`` (default): an unnamed SDC is named after the host + (``setSdcName``); an SDC already carrying the *same* name is that host; + an SDC carrying a *different* name belongs to another host and raises + :class:`ArrayConflictError` (an admin-named SDC must therefore be + registered under its PowerFlex name). +* ``ignore``: names are neither read nor written; any host name maps to the + SDC with the given GUID (no ownership conflict detection). + +``delete_host`` is a no-op for SDCs: the SDC belongs to the host's PowerFlex +installation (removing it is ``removeSdc``, an admin decision) and keeps the +name ``claim`` gave it. + +Mappings are SDC mappings (``addMappedSdc`` / ``removeMappedSdc``); the +volume's ``mappedSdcInfo`` lists them (``null``, not ``[]``, when there are +none). Mapping a volume to a second SDC needs ``allowMultipleMappings``. +SDC mappings have no LUN number (``Mapping.lun`` is ``None``) and SDC +volumes no NAA WWN or NGUID, so ``Volume.identifier`` is ``id.``. + +NVMe/TCP (4.x NVMe hosts, ``/api/types/Host/instances``) is not +implemented: a 4.x NVMe host has exactly one NQN, and the mapping actions +for NVMe hosts could not be verified against documentation (see below). + +Errors: the gateway answers ``{"message", "httpStatusCode", "errorCode"}``, +and reports "not found" as HTTP **500** (sometimes 400) rather than 404, so +missing objects are recognised by message text; any other 500 stays an +:class:`ArrayRequestError`. Booleans and numbers in action bodies are sent as +strings (``"TRUE"``, ``"8388608"``), as the REST reference shows them. + +Verify against a real system: + +* ``auto`` detection: that a 3.x gateway answers ``POST /rest/auth/login`` + with 404/405 (not 401), and whether a 4.x gateway still serves + ``GET /api/login``. +* 4.x token lifetime and whether a refresh-token grant would be preferable + to re-login; the 4.x logout body. +* Exact error texts/codes: volume not found (``"Could not find the + volume"``, errorCode 79?), ``queryIdByKey`` for a missing name, name in + use, "already mapped", "not mapped", SDC name in use. +* That ``setVolumeSize`` rounds a non-multiple of 8 up rather than + rejecting it (the adapter always sends multiples of 8, so this only + matters for volumes created outside simplyblock). +* ``accessMode: ReadWrite`` accepted by ``addMappedSdc`` on 3.6 and 4.x; + ``allowMultipleMappings`` spelling/value ``"TRUE"``. +* Field names ``sdcGuid`` and ``name`` on ``Sdc`` and ``mappedSdcInfo[].sdcId`` + on ``Volume``; ``systemVersionName`` on ``System``. +* Whether SDC names are unique system-wide (the fake assumes so). +""" +from __future__ import annotations + +from typing import Any + +from ..base import ( + ArrayAdapter, + ArrayConflictError, + ArrayError, + ArrayInfo, + ArrayNotFoundError, + ArrayRequestError, + ArrayUnsupportedError, + Capabilities, + HostSpec, + Mapping, + OptionDoc, + Protocol, + Volume, +) +from ..http import body_text, json_of + +GIB = 1 << 30 +KIB = 1 << 10 + +_AUTH_MODES = ("auto", "token", "oauth") +_NAMING_MODES = ("claim", "ignore") +_NOT_FOUND = ("could not find", "not found", "does not exist", "no such") +_CONFLICT = ("already in use", "already exists", "already mapped", "is mapped", + "name in use") +_NOT_MAPPED = ("not mapped",) + + +def _message(body: Any, fallback: str) -> str: + if isinstance(body, dict) and body.get("message"): + msg = str(body["message"]) + code = body.get("errorCode") + return f"{msg} (errorCode {code})" if code is not None else msg + return fallback + + +class DellPowerFlexAdapter(ArrayAdapter): + vendor = "dell-powerflex" + display_name = "Dell PowerFlex" + capabilities = Capabilities( + protocols=frozenset({Protocol.SDC}), + size_granularity_bytes=8 * GIB, + min_size_bytes=8 * GIB, + max_name_len=31, + max_initiators_per_host=1, + ) + option_docs = ( + OptionDoc("storage_pool_id", "Id of the storage pool new volumes are created in.", + required=True), + OptionDoc("protection_domain_id", "Protection domain of the storage pool " + "(sent on create; only needed where the gateway asks for it)."), + OptionDoc("auth", "'token' (3.x /api/login), 'oauth' (4.x /rest/auth/login) " + "or 'auto' (try oauth, fall back to token).", default="auto"), + OptionDoc("sdc_naming", "'claim': name unnamed SDCs after the host and treat an " + "SDC named differently as another host's; 'ignore': never read or " + "write SDC names.", default="claim"), + ) + + def __init__(self, ctx): + super().__init__(ctx) + if self.option("auth") not in _AUTH_MODES: + raise ArrayError(f"PowerFlex option auth must be one of {', '.join(_AUTH_MODES)}") + if self.option("sdc_naming") not in _NAMING_MODES: + raise ArrayError( + f"PowerFlex option sdc_naming must be one of {', '.join(_NAMING_MODES)}") + self._mode = "" + self._refresh_token = "" + + # -- session ------------------------------------------------------------ + + def _reset_auth(self) -> None: + self.session.clear_auth() + self.session.headers.pop("Authorization", None) + self._mode = "" + self._refresh_token = "" + + def login(self) -> None: + self._reset_auth() + mode = self.option("auth") + user, password = self.secret("username"), self.secret("password") + if mode in ("auto", "oauth"): + resp = self.session.post("/rest/auth/login", + json={"username": user, "password": password}, + ok=(404, 405) if mode == "auto" else ()) + if resp.status_code < 300: + body = json_of(resp) or {} + token = body.get("access_token") if isinstance(body, dict) else None + if not token: + raise ArrayRequestError("PowerFlex /rest/auth/login returned no access_token") + self.session.headers["Authorization"] = f"Bearer {token}" + self._refresh_token = str(body.get("refresh_token") or "") + self._mode = "oauth" + return + # 404/405 under "auto": a 3.x gateway without PowerFlex Manager. + resp = self.session.get("/api/login", auth=(user, password)) + token = (resp.text or "").strip().strip('"') + if not token: + raise ArrayRequestError("PowerFlex /api/login returned no token") + self.session.set_basic_auth(user, token) + self._mode = "token" + + def close(self) -> None: + try: + if self._mode == "token": + self.session.get("/api/logout") + elif self._mode == "oauth": + self.session.post("/rest/auth/logout", + json={"refresh_token": self._refresh_token}) + except Exception: + pass + self._mode = "" + + # -- request helpers ----------------------------------------------------- + + def _req(self, method: str, path: str, *, json: Any = None, + missing_ok: bool = False) -> Any: + """Issue a request; returns the decoded body, or ``None`` for a + missing object when ``missing_ok``.""" + resp = self.session.request(method, path, json=json, ok=(400, 404, 500)) + if resp.status_code < 300: + if not resp.content: + return None + try: + return resp.json() + except ValueError: + return resp.text + try: + body = resp.json() + except ValueError: + body = None + msg = _message(body, body_text(resp)) + lowered = msg.lower() + if resp.status_code == 404 or any(s in lowered for s in _NOT_FOUND): + if missing_ok: + return None + raise ArrayNotFoundError(f"{method} {path}: {msg}") + if any(s in lowered for s in _CONFLICT): + raise ArrayConflictError(f"{method} {path}: {msg}") + raise ArrayRequestError(f"{method} {path} -> HTTP {resp.status_code}: {msg}", + status=resp.status_code) + + def _raw_volume(self, volume_id: str, missing_ok: bool = False) -> dict[str, Any] | None: + body = self._req("GET", f"/api/instances/Volume::{volume_id}", missing_ok=missing_ok) + if body is None: + return None + if not isinstance(body, dict): + raise ArrayRequestError(f"PowerFlex returned no volume for {volume_id}") + return body + + @staticmethod + def _volume(v: dict[str, Any]) -> Volume: + return Volume(id=str(v["id"]), name=v.get("name") or "", + size_bytes=int(v["sizeInKb"]) * KIB) + + def _action(self, volume_id: str, action: str, body: dict[str, Any]) -> Any: + return self._req("POST", f"/api/instances/Volume::{volume_id}/action/{action}", + json=body) + + # -- contract ------------------------------------------------------------- + + def get_info(self) -> ArrayInfo: + systems = self._req("GET", "/api/types/System/instances") or [] + system = systems[0] if isinstance(systems, list) and systems else {} + return ArrayInfo(vendor=self.vendor, model="PowerFlex", + version=str(system.get("systemVersionName") or ""), + serial=str(system.get("id") or "")) + + def create_volume(self, name: str, size_bytes: int) -> Volume: + body: dict[str, Any] = { + "name": name, + "volumeSizeInKb": str(size_bytes // KIB), + "storagePoolId": self.option("storage_pool_id"), + "volumeType": "ThinProvisioned", + } + if self.option("protection_domain_id"): + body["protectionDomainId"] = self.option("protection_domain_id") + created = self._req("POST", "/api/types/Volume/instances", json=body) + vid = created.get("id") if isinstance(created, dict) else None + if not vid: + raise ArrayRequestError("PowerFlex volume create returned no id") + raw = self._raw_volume(vid) + assert raw is not None + return self._volume(raw) + + def get_volume(self, volume_id: str) -> Volume | None: + raw = self._raw_volume(volume_id, missing_ok=True) + return self._volume(raw) if raw else None + + def find_volume(self, name: str) -> Volume | None: + vid = self._req("POST", "/api/types/Volume/instances/action/queryIdByKey", + json={"name": name}, missing_ok=True) + if not vid or not isinstance(vid, str): + return None + return self.get_volume(vid) + + def resize_volume(self, volume_id: str, size_bytes: int) -> Volume: + size_gb = -(-size_bytes // GIB) + self._action(volume_id, "setVolumeSize", {"sizeInGB": str(size_gb)}) + raw = self._raw_volume(volume_id) + assert raw is not None + return self._volume(raw) + + def delete_volume(self, volume_id: str) -> None: + self._action(volume_id, "removeVolume", {"removeMode": "ONLY_ME"}) + + # -- hosts (SDCs) ----------------------------------------------------------- + + def _sdcs(self) -> list[dict[str, Any]]: + body = self._req("GET", "/api/types/Sdc/instances") + return list(body) if isinstance(body, list) else [] + + def ensure_host(self, spec: HostSpec) -> str: + guids = spec.addresses(Protocol.SDC) + if len(guids) != 1 or len(spec.initiators) != 1: + raise ArrayUnsupportedError( + "A PowerFlex host is one SDC: give exactly one SDC GUID per host") + guid = guids[0] + sdc = next((s for s in self._sdcs() + if str(s.get("sdcGuid") or "").lower() == guid.lower()), None) + if sdc is None: + raise ArrayNotFoundError( + f"No SDC with GUID {guid} is registered with PowerFlex; install the SDC " + "on the host and connect it to the MDM first") + sdc_id = str(sdc["id"]) + if self.option("sdc_naming") == "claim": + current = sdc.get("name") or "" + if current and current != spec.name: + raise ArrayConflictError( + f"SDC {guid} is registered as host {current!r}, not {spec.name!r}") + if not current: + self._req("POST", f"/api/instances/Sdc::{sdc_id}/action/setSdcName", + json={"sdcName": spec.name}) + return sdc_id + + def delete_host(self, host_id: str) -> None: + """No-op: SDCs belong to the host's PowerFlex installation.""" + + # -- mappings --------------------------------------------------------------- + + def list_mappings(self, volume_id: str) -> list[Mapping]: + raw = self._raw_volume(volume_id) + assert raw is not None + info = raw.get("mappedSdcInfo") or [] # null when unmapped + return [Mapping(volume_id=volume_id, host_id=str(m["sdcId"]), lun=None) + for m in info if m.get("sdcId")] + + def map_volume(self, volume_id: str, host_id: str) -> Mapping: + for m in self.list_mappings(volume_id): + if m.host_id == host_id: + return m + self._action(volume_id, "addMappedSdc", { + "sdcId": host_id, "allowMultipleMappings": "TRUE", "accessMode": "ReadWrite"}) + return Mapping(volume_id=volume_id, host_id=host_id, lun=None) + + def unmap_volume(self, volume_id: str, host_id: str) -> None: + raw = self._raw_volume(volume_id, missing_ok=True) + if raw is None: + return + if not any(str(m.get("sdcId")) == host_id for m in raw.get("mappedSdcInfo") or []): + return + try: + self._action(volume_id, "removeMappedSdc", {"sdcId": host_id}) + except ArrayRequestError as e: + if not any(s in str(e).lower() for s in _NOT_MAPPED): + raise diff --git a/simplyblock_core/storage_arrays/adapters/dell_powermax.py b/simplyblock_core/storage_arrays/adapters/dell_powermax.py new file mode 100644 index 0000000000..a05fbbd1fd --- /dev/null +++ b/simplyblock_core/storage_arrays/adapters/dell_powermax.py @@ -0,0 +1,434 @@ +"""Dell PowerMax, Unisphere for PowerMax REST API (10.x). + +Auth: HTTP basic on every request (no session). Provisioning lives under +``/univmax/restapi/{api_version}/sloprovisioning/symmetrix/{symmetrix_id}``. +Errors are ``{"message": "..."}``, mostly with status 400; 404 for missing +objects; 401 for a rejected credential. + +Layout (one object set per simplyblock volume): + +* storage group ```` (``sb-``) in the configured SRP / + service level, holding exactly one device; +* the device's ``volume_identifier`` is the same name; +* one masking view per (storage group, host): ``_`` (or + ``_`` when that exceeds 64 characters), joining the storage + group, the host (initiator group) and the port group configured for the + host's protocol. + +A storage group per volume keeps map/unmap/delete independent per volume +(PowerMax maps storage groups, not devices), at the cost of one SG and one +masking view per mapping; arrays allow tens of thousands of each. + +``Volume.id`` is the 5-hex-digit device id (``0012A``). ``Volume.wwn`` is +``naa.`` + the device's ``effective_wwn`` (falls back to ``wwn``). Volume +identifiers are *not* unique on PowerMax; lookups by name prefer the device +in the storage group of that name and refuse to guess between several. + +Sizes: devices are allocated in cylinders; on PowerMaxOS (FBA) one cylinder +is 15 tracks x 128 KiB = 1920 KiB, so the size granularity is 1 966 080 +bytes and all sizes are sent as ``capacityUnit: "CYL"`` (exact, no GB/MB +rounding). ``cap_cyl`` is read back. + +Async jobs: with ``async_jobs`` the adapter sends +``executionOption: ASYNCHRONOUS`` and polls ``/{ver}/system/job/{jobId}`` on +``202 Accepted``; otherwise it sends ``SYNCHRONOUS`` but still follows a 202 +should the server answer with a job. + +Verify against a real system +---------------------------- +* Whether ``sloId: "None"`` (no service level) is accepted on 10.x, and that + ``workloadSelection`` may be omitted. +* The empty answer of ``GET .../volume?volume_identifier=x`` (assumed: + ``count: 0`` with no ``resultList``) and whether the filter is exact or + case-insensitive; iterator paging (``/common/Iterator``) is not followed -- + fine for name lookups that match one device. +* The ``storageGroupId`` filter on ``GET .../volume``. +* Status codes and wording for: SG / host / masking view name already in use, + initiator already in another initiator group (classified by "already" / + "in use" / "exist" / "member of"), removing the last device of a masked SG, + deleting a device still in an SG, shrink. +* Whether a device must be removed from its SG before ``DELETE volume`` (done + here) and whether 10.x still needs a deallocation step first (not done). +* Whether iSCSI IQNs / NVMe host NQNs must already be logged in to the array + before ``POST host`` accepts them (FC WWNs need not be). +* NVMe/TCP: initiator ids for NVMe hosts (assumed: the host NQN) and whether + the volume object carries an ``nguid`` field (read if present). +* ``GET maskingview/{mv}/connections?volume_id=`` returns rows only for + initiator/port pairs (assumed: one row per initiator x port, logged in or + not); ``host_lun_address`` is hex. With no rows the mapping's LUN is None. +* Job states (``SUCCEEDED`` / ``FAILED`` / ``VALIDATE_FAILED``; others are + in progress) and that the failure text is in ``result``. +""" +from __future__ import annotations + +import hashlib +import math +from collections.abc import Callable +from typing import Any + +import requests + +from ..base import ( + ArrayAdapter, + ArrayConflictError, + ArrayError, + ArrayInfo, + ArrayNotFoundError, + ArrayRequestError, + ArrayUnsupportedError, + Capabilities, + HostSpec, + Mapping, + OptionDoc, + Protocol, + Volume, +) +from ..http import json_of + +CYLINDER_BYTES = 1920 * 1024 +MAX_NAME = 64 +_JOB_DONE = "SUCCEEDED" +_JOB_FAILED = frozenset({"FAILED", "VALIDATE_FAILED"}) +_JOB_POLL_S = 2.0 + +_NOT_FOUND = ("cannot find", "not found", "does not exist", "no such") +_CONFLICT = ("already", "in use", "exists", "member of", "is part of", "masking view") + + +def _message(resp: requests.Response) -> str: + try: + body = json_of(resp) + except ArrayRequestError: + body = None + if isinstance(body, dict) and body.get("message"): + return str(body["message"]) + return (resp.text or "")[:600] or f"HTTP {resp.status_code}" + + +def _classify(what: str, text: str, status: int | None = None) -> ArrayError: + lowered = text.lower() + msg = f"{what}: {text}" + if status == 404 or any(k in lowered for k in _NOT_FOUND): + return ArrayNotFoundError(msg) + if any(k in lowered for k in _CONFLICT): + return ArrayConflictError(msg) + return ArrayRequestError(msg, status=status) + + +def powermax_wwn(item: dict[str, Any]) -> str | None: + v = str(item.get("effective_wwn") or item.get("wwn") or "").strip().lower() + v = v.removeprefix("naa.") + return f"naa.{v}" if v else None + + +def initiator_protocol(initiator_id: str) -> Protocol: + """Protocol of an initiator-group member as Unisphere lists it.""" + v = initiator_id.lower() + if v.startswith(("iqn.", "eui.")): + return Protocol.ISCSI + if v.startswith("nqn."): + return Protocol.NVME_TCP + return Protocol.FC + + +class DellPowerMaxAdapter(ArrayAdapter): + vendor = "dell-powermax" + display_name = "Dell PowerMax" + capabilities = Capabilities( + protocols=frozenset({Protocol.ISCSI, Protocol.FC, Protocol.NVME_TCP}), + size_granularity_bytes=CYLINDER_BYTES, + min_size_bytes=CYLINDER_BYTES, + max_name_len=MAX_NAME, + ) + credential_fields = (frozenset({"username", "password"}),) + option_docs = ( + OptionDoc("symmetrix_id", "12-digit array serial (symmetrix id), e.g. '000197900123'.", + required=True), + OptionDoc("srp", "Storage resource pool for new storage groups.", default="SRP_1"), + OptionDoc("service_level", "Service level (e.g. 'Diamond'); default: none."), + OptionDoc("port_group", "Port group for masking views: a name, or a map from " + "protocol ('iscsi', 'fc', 'nvme-tcp') to name. Needed to map volumes."), + OptionDoc("api_version", "Unisphere REST version in the URL ('100' = 10.0, " + "'101' = 10.1, ...).", default="100"), + OptionDoc("async_jobs", "Run modifying calls as Unisphere jobs and poll them " + "(recommended for large arrays where synchronous calls time out).", + default=False), + OptionDoc("job_timeout_s", "How long to wait for an asynchronous job.", default=600), + ) + + def __init__(self, ctx): + super().__init__(ctx) + self._base = f"/univmax/restapi/{self.option('api_version')}" + self._sym = str(self.option("symmetrix_id")) + self._slo = f"{self._base}/sloprovisioning/symmetrix/{self._sym}" + self._sleep: Callable[[float], None] = self.session.sleep + + # -- session ------------------------------------------------------------ + + def login(self) -> None: + self.session.set_basic_auth(self.secret("username"), self.secret("password")) + + def close(self) -> None: + self.session.clear_auth() + + # -- request helpers ----------------------------------------------------- + + def _exec(self) -> str: + return "ASYNCHRONOUS" if self.option("async_jobs") else "SYNCHRONOUS" + + def _call(self, method: str, path: str, *, params: dict[str, Any] | None = None, + json: Any = None, missing_ok: bool = False) -> Any: + resp = self.session.request(method, path, params=params, json=json, ok=(400, 404)) + if resp.status_code in (400, 404): + err = _classify(f"{method} {path} -> HTTP {resp.status_code}", _message(resp), + resp.status_code) + if missing_ok and isinstance(err, ArrayNotFoundError): + return None + raise err + body = json_of(resp) + if resp.status_code == 202 and isinstance(body, dict) and body.get("jobId"): + return self._wait_job(str(body["jobId"]), f"{method} {path}") + return body + + def _wait_job(self, job_id: str, what: str) -> dict[str, Any]: + polls = max(1, math.ceil(float(self.option("job_timeout_s")) / _JOB_POLL_S)) + for _ in range(polls): + job = json_of(self.session.get(f"{self._base}/system/job/{job_id}")) or {} + status = str(job.get("status", "")).upper() + if status == _JOB_DONE: + return job + if status in _JOB_FAILED: + raise _classify(f"{what} (job {job_id} {status})", + str(job.get("result") or "no result")) + self._sleep(_JOB_POLL_S) + raise ArrayRequestError(f"{what}: job {job_id} did not finish within " + f"{self.option('job_timeout_s')} s") + + @staticmethod + def _volume(item: dict[str, Any]) -> Volume: + nguid = str(item.get("nguid") or "").strip().lower().removeprefix("eui.") + return Volume(id=item["volumeId"], name=item.get("volume_identifier") or "", + size_bytes=int(item["cap_cyl"]) * CYLINDER_BYTES, + wwn=powermax_wwn(item), nguid=f"eui.{nguid}" if nguid else None) + + def _volume_item(self, device_id: str) -> dict[str, Any] | None: + return self._call("GET", f"{self._slo}/volume/{device_id}", missing_ok=True) + + def _require_item(self, device_id: str) -> dict[str, Any]: + item = self._volume_item(device_id) + if item is None: + raise ArrayNotFoundError(f"PowerMax device {device_id} not found") + return item + + def _device_ids(self, **filters: str) -> list[str]: + body = self._call("GET", f"{self._slo}/volume", params=filters) or {} + rows = (body.get("resultList") or {}).get("result") or [] + return [r["volumeId"] for r in rows if r.get("volumeId")] + + @staticmethod + def _cyl(size_bytes: int) -> int: + return -(-int(size_bytes) // CYLINDER_BYTES) + + def _attrs(self, name: str, size_bytes: int) -> dict[str, Any]: + return {"num_of_vols": 1, "volume_size": str(self._cyl(size_bytes)), + "capacityUnit": "CYL", + "volumeIdentifier": {"identifier_name": name, + "volumeIdentifierChoice": "identifier_name"}} + + # -- contract ------------------------------------------------------------- + + def get_info(self) -> ArrayInfo: + about = self._call("GET", "/univmax/restapi/version") or {} + supported = about.get("supported_api_versions") + if supported and str(self.option("api_version")) not in [str(v) for v in supported]: + raise ArrayUnsupportedError( + f"Unisphere {about.get('version', '')} does not serve REST version " + f"{self.option('api_version')} (supported: {', '.join(map(str, supported))})") + sym = self._call("GET", f"{self._base}/system/symmetrix/{self._sym}") or {} + version = sym.get("ucode") or "" + unisphere = about.get("version") or "" + return ArrayInfo(vendor=self.vendor, model=sym.get("model", ""), + version=f"PowerMaxOS {version} (Unisphere {unisphere})".strip(), + serial=sym.get("symmetrixId", self._sym)) + + def create_volume(self, name: str, size_bytes: int) -> Volume: + attrs = self._attrs(name, size_bytes) + payload: dict[str, Any] = { + "srpId": self.option("srp"), + "storageGroupId": name, + "emulation": "FBA", + "sloBasedStorageGroupParam": [{ + "sloId": self.option("service_level") or "None", + "volumeAttributes": [attrs], + }], + "executionOption": self._exec(), + } + try: + self._call("POST", f"{self._slo}/storagegroup", json=payload) + except ArrayConflictError: + # Left over from an interrupted create or delete: reuse it if empty. + sg = self._call("GET", f"{self._slo}/storagegroup/{name}", missing_ok=True) + if sg is None or int(sg.get("num_of_vols") or 0): + raise + self._call("PUT", f"{self._slo}/storagegroup/{name}", json={ + "editStorageGroupActionParam": {"expandStorageGroupParam": {"addVolumeParam": { + "create_new_volumes": True, "emulation": "FBA", + "volumeAttributes": [attrs]}}}, + "executionOption": self._exec()}) + devices = self._device_ids(storageGroupId=name) + if len(devices) != 1: + raise ArrayRequestError( + f"PowerMax storage group {name} holds {len(devices)} devices after create") + return self._volume(self._require_item(devices[0])) + + def get_volume(self, volume_id: str) -> Volume | None: + item = self._volume_item(volume_id) + return self._volume(item) if item else None + + def find_volume(self, name: str) -> Volume | None: + items = [i for i in (self._volume_item(d) for d in self._device_ids(volume_identifier=name)) + if i and i.get("volume_identifier") == name] + if len(items) > 1: + own = [i for i in items if name in (i.get("storageGroupId") or [])] + if len(own) != 1: + raise ArrayConflictError( + f"{len(items)} PowerMax devices are named {name}: " + + ", ".join(i["volumeId"] for i in items)) + items = own + return self._volume(items[0]) if items else None + + def resize_volume(self, volume_id: str, size_bytes: int) -> Volume: + self._call("PUT", f"{self._slo}/volume/{volume_id}", json={ + "editVolumeActionParam": {"expandVolumeParam": {"volumeAttribute": { + "volume_size": str(self._cyl(size_bytes)), "capacityUnit": "CYL"}}}, + "executionOption": self._exec()}) + return self._volume(self._require_item(volume_id)) + + def delete_volume(self, volume_id: str) -> None: + item = self._require_item(volume_id) + name = item.get("volume_identifier") or "" + for sg in item.get("storageGroupId") or []: + self._call("PUT", f"{self._slo}/storagegroup/{sg}", json={ + "editStorageGroupActionParam": {"removeVolumeParam": {"volumeId": [volume_id]}}, + "executionOption": self._exec()}) + if sg == name: + self._call("DELETE", f"{self._slo}/storagegroup/{sg}", missing_ok=True) + self._call("DELETE", f"{self._slo}/volume/{volume_id}") + + # -- hosts ------------------------------------------------------------------ + + def ensure_host(self, spec: HostSpec) -> str: + wanted = [i.normalized() for i in spec.initiators] + host = self._call("GET", f"{self._slo}/host/{spec.name}", missing_ok=True) + if host is None: + self._call("POST", f"{self._slo}/host", json={ + "hostId": spec.name, "initiatorId": wanted, "executionOption": self._exec()}) + return spec.name + have = {str(i).lower() for i in host.get("initiator") or []} + missing = [w for w in wanted if w.lower() not in have] + if missing: + self._call("PUT", f"{self._slo}/host/{spec.name}", json={ + "editHostActionParam": {"addInitiatorParam": {"initiator": missing}}, + "executionOption": self._exec()}) + return spec.name + + def delete_host(self, host_id: str) -> None: + self._call("DELETE", f"{self._slo}/host/{host_id}", missing_ok=True) + + # -- mappings ------------------------------------------------------------------ + + @staticmethod + def view_name(sg: str, host: str) -> str: + name = f"{sg}_{host}" + if len(name) <= MAX_NAME: + return name + return f"{sg}_{hashlib.sha256(host.encode()).hexdigest()[:16]}" + + def _port_group(self, host_id: str) -> str: + option = self.option("port_group") + if not option: + raise ArrayError(f"{self.display_name} array {self.config.id} needs the " + "'port_group' option to map volumes") + if isinstance(option, str): + return option + host = self._call("GET", f"{self._slo}/host/{host_id}") + protocols = {initiator_protocol(str(i)) for i in host.get("initiator") or []} + if len(protocols) != 1: + raise ArrayError(f"Cannot tell the protocol of PowerMax host {host_id}") + protocol = protocols.pop() + pg = option.get(protocol.value) + if not pg: + raise ArrayError(f"No PowerMax port group configured for {protocol.value} " + f"(option 'port_group')") + return str(pg) + + def _views(self, item: dict[str, Any]) -> list[tuple[str, str, str]]: + """(masking view, host or host group, storage group) for a device.""" + out = [] + for sg in item.get("storageGroupId") or []: + sg_item = self._call("GET", f"{self._slo}/storagegroup/{sg}", missing_ok=True) + for mv in (sg_item or {}).get("maskingview") or []: + mv_item = self._call("GET", f"{self._slo}/maskingview/{mv}", missing_ok=True) + if mv_item: + host = mv_item.get("hostId") or mv_item.get("hostGroupId") + if host: + out.append((mv, str(host), sg)) + return out + + def _lun(self, view: str, device_id: str) -> int | None: + body = self._call("GET", f"{self._slo}/maskingview/{view}/connections", + params={"volume_id": device_id}, missing_ok=True) or {} + for row in body.get("maskingViewConnection") or []: + if row.get("volumeId") == device_id and row.get("host_lun_address"): + return int(str(row["host_lun_address"]), 16) + return None + + def _mappings(self, item: dict[str, Any]) -> list[Mapping]: + seen: dict[str, Mapping] = {} + for view, host, _sg in self._views(item): + if host not in seen: + seen[host] = Mapping(volume_id=item["volumeId"], host_id=host, + lun=self._lun(view, item["volumeId"])) + return list(seen.values()) + + def map_volume(self, volume_id: str, host_id: str) -> Mapping: + item = self._require_item(volume_id) + for m in self._mappings(item): + if m.host_id == host_id: + return m + sg = item.get("volume_identifier") or "" + if sg not in (item.get("storageGroupId") or []): + raise ArrayConflictError( + f"PowerMax device {volume_id} is not in its own storage group {sg!r}") + if self._call("GET", f"{self._slo}/host/{host_id}", missing_ok=True) is None: + raise ArrayNotFoundError(f"PowerMax host {host_id} not found") + self._call("POST", f"{self._slo}/maskingview", json={ + "maskingViewId": self.view_name(sg, host_id), + "hostOrHostGroupSelection": {"useExistingHostParam": {"hostId": host_id}}, + "portGroupSelection": {"useExistingPortGroupParam": { + "portGroupId": self._port_group(host_id)}}, + "storageGroupSelection": {"useExistingStorageGroupParam": {"storageGroupId": sg}}, + "executionOption": self._exec()}) + for m in self._mappings(self._require_item(volume_id)): + if m.host_id == host_id: + return m + raise ArrayRequestError( + f"PowerMax masked device {volume_id} to host {host_id} but lists no mapping") + + def unmap_volume(self, volume_id: str, host_id: str) -> None: + item = self._volume_item(volume_id) + if item is None: + return + own = item.get("volume_identifier") or "" + for view, host, sg in self._views(item): + if host != host_id: + continue + if sg != own: + raise ArrayConflictError( + f"PowerMax device {volume_id} is mapped to {host_id} through shared " + f"storage group {sg} (masking view {view}); unmap it on the array") + self._call("DELETE", f"{self._slo}/maskingview/{view}", missing_ok=True) + + def list_mappings(self, volume_id: str) -> list[Mapping]: + item = self._volume_item(volume_id) + return self._mappings(item) if item else [] diff --git a/simplyblock_core/storage_arrays/adapters/dell_powerstore.py b/simplyblock_core/storage_arrays/adapters/dell_powerstore.py new file mode 100644 index 0000000000..4a480d92e4 --- /dev/null +++ b/simplyblock_core/storage_arrays/adapters/dell_powerstore.py @@ -0,0 +1,332 @@ +"""Dell PowerStore, REST API (PowerStoreOS 3.x / 4.x). + +Auth: HTTP basic on ``GET /api/rest/login_session`` opens a session. The +response carries the session cookie (``auth_cookie``) and a CSRF token in the +``DELL-EMC-TOKEN`` header; every later request sends the cookie, and every +non-GET request must also send the token header (the array answers 403 +without it). Basic auth is *not* kept on the session afterwards, so an expired +session surfaces as 401 and :class:`ArrayClient` logs in again. + +Queries use the PostgREST-style syntax: ``select=a,b`` picks fields, +``name=eq.x`` filters, ``limit``/``offset`` page; a partial page is answered +with ``206 Partial Content`` and a ``Content-Range`` header. + +Errors: ``{"messages": [{"code": "0x...", "severity": "Error", +"message_l10n": "...", "arguments": [...]}]}``. Semantic failures (name in +use, initiator owned by another host, volume still attached, shrink) come +back as ``422 Unprocessable Entity``; malformed requests as 400. + +Objects are addressed by id (UUID) for volumes and hosts. Volume identity: +``wwn`` is returned as ``naa.``, ``nguid`` as ``nguid.<32 hex>``; this +adapter reports them as ``naa.`` / ``eui.`` (lowercase). + +Sizes are bytes; PowerStore requires a multiple of 8 KiB (8192) and at least +1 MiB. + +Verify against a real system +---------------------------- +* The session cookie name (``auth_cookie``) and that the CSRF header is + exactly ``DELL-EMC-TOKEN`` on both the login response and requests. +* That ``POST /volume`` and ``POST /host`` answer ``201 {"id": ...}`` and that + PATCH/DELETE/attach/detach answer ``204`` with an empty body. +* The status code (422 assumed) and ``message_l10n`` wording for: duplicate + name, initiator already registered to another host, delete of an attached + volume/host, shrink, detach of a non-attached volume. Classification below + is by wording ("already", "in use", "attached", "mapped", "not found"). +* The host field holding initiators on GET is ``host_initiators`` + (create uses ``initiators``, modify ``add_initiators``), each + ``{"port_name", "port_type"}``; ``port_type`` values ``iSCSI``/``FC``/ + ``NVMe`` (NVMe/TCP and NVMe/FC both ``NVMe``), and that FC ``port_name`` is + accepted/returned colon-separated lowercase (``21:00:...``). +* That ``logical_unit_number`` in ``host_volume_mapping`` is the NVMe NSID for + NVMe hosts, and which LUN the array picks first (fake: 1). +* That a ``name=eq.`` filter needs no quoting for host names containing + dots or commas. +* That the size multiple is 8192 bytes on 4.x as on 3.x. +""" +from __future__ import annotations + +from http.cookies import CookieError, SimpleCookie +from typing import Any + +import requests + +from ..base import ( + ArrayAdapter, + ArrayConflictError, + ArrayError, + ArrayInfo, + ArrayNotFoundError, + ArrayRequestError, + Capabilities, + HostSpec, + Mapping, + OptionDoc, + Protocol, + Volume, + colon_wwpn, + normalize_wwpn, +) +from ..http import json_of + +API = "/api/rest" +TOKEN_HEADER = "DELL-EMC-TOKEN" +VOLUME_FIELDS = "id,name,size,wwn,nguid" +HOST_FIELDS = "id,name,host_initiators" +MAPPING_FIELDS = "id,host_id,host_group_id,volume_id,logical_unit_number" +_PAGE = 1000 + +_NOT_FOUND = ("not found", "does not exist", "not exist", "no such") +_CONFLICT = ("already", "in use", "exists", "attached", "mapped", "is used", "duplicate") + + +def _messages(resp: requests.Response) -> str: + try: + body = json_of(resp) or {} + except ArrayRequestError: + return "" + if not isinstance(body, dict): + return "" + return " ".join(str(m.get("message_l10n") or m.get("code") or "") + for m in body.get("messages", []) if isinstance(m, dict)) + + +def _classify(method: str, path: str, resp: requests.Response) -> ArrayError: + text = _messages(resp) or f"HTTP {resp.status_code}" + lowered = text.lower() + msg = f"{method} {path} -> HTTP {resp.status_code}: {text}" + if resp.status_code == 404 or any(k in lowered for k in _NOT_FOUND): + return ArrayNotFoundError(msg) + if any(k in lowered for k in _CONFLICT): + return ArrayConflictError(msg) + return ArrayRequestError(msg, status=resp.status_code) + + +def powerstore_wwn(value: str | None) -> str | None: + v = (value or "").strip().lower().removeprefix("naa.") + return f"naa.{v}" if v else None + + +def powerstore_nguid(value: str | None) -> str | None: + v = (value or "").strip().lower().removeprefix("nguid.").removeprefix("eui.") + return f"eui.{v}" if v else None + + +_PORT_TYPE = { + Protocol.ISCSI: "iSCSI", + Protocol.FC: "FC", + Protocol.NVME_TCP: "NVMe", + Protocol.NVME_FC: "NVMe", +} + + +def _port_key(port_type: str, port_name: str) -> str: + """Comparable form of an initiator as the array reports it.""" + if port_type == "FC": + try: + return normalize_wwpn(port_name) + except ValueError: + return port_name.lower() + if port_type == "iSCSI": + return port_name.lower() + return port_name + + +class DellPowerStoreAdapter(ArrayAdapter): + vendor = "dell-powerstore" + display_name = "Dell PowerStore" + capabilities = Capabilities( + protocols=frozenset({Protocol.ISCSI, Protocol.FC, Protocol.NVME_TCP, Protocol.NVME_FC}), + size_granularity_bytes=8192, + min_size_bytes=1 << 20, + max_name_len=128, + ) + credential_fields = (frozenset({"username", "password"}),) + option_docs = ( + OptionDoc("os_type", "os_type of hosts simplyblock creates.", default="Linux"), + OptionDoc("appliance_id", "Create volumes on this appliance of a multi-appliance " + "cluster (e.g. 'A1'); default: the array places them."), + ) + + # -- session ------------------------------------------------------------ + + def login(self) -> None: + self.session.headers.pop(TOKEN_HEADER, None) + self.session.http.cookies.clear() + resp = self.session.get(f"{API}/login_session", + auth=(self.secret("username"), self.secret("password"))) + token = resp.headers.get(TOKEN_HEADER) + if not token: + raise ArrayRequestError(f"PowerStore login returned no {TOKEN_HEADER} header") + self.session.headers[TOKEN_HEADER] = token + self._adopt_cookies(resp) + + def _adopt_cookies(self, resp: requests.Response) -> None: + """Keep the session cookie. ``requests`` normally stores it already; + this also covers transports that do not populate the cookie jar.""" + raw = resp.headers.get("Set-Cookie") + if not raw: + return + jar = self.session.http.cookies + try: + parsed = SimpleCookie() + parsed.load(raw) + except CookieError: + return + for name, morsel in parsed.items(): + if name not in jar: + jar.set(name, morsel.value, path=morsel["path"] or "/") + + def close(self) -> None: + if TOKEN_HEADER in self.session.headers: + try: + self.session.post(f"{API}/logout", ok=(401, 403)) + except Exception: + pass + self.session.headers.pop(TOKEN_HEADER, None) + + # -- request helpers ----------------------------------------------------- + + def _call(self, method: str, path: str, *, params: dict[str, Any] | None = None, + json: Any = None, missing_ok: bool = False) -> requests.Response | None: + resp = self.session.request(method, f"{API}{path}", params=params, json=json, + ok=(400, 404, 422)) + if resp.status_code in (400, 404, 422): + err = _classify(method, path, resp) + if missing_ok and isinstance(err, ArrayNotFoundError): + return None + raise err + return resp + + def _one(self, path: str, select: str) -> dict[str, Any] | None: + resp = self._call("GET", path, params={"select": select}, missing_ok=True) + return json_of(resp) if resp is not None else None + + def _list(self, path: str, select: str, **filters: str) -> list[dict[str, Any]]: + out: list[dict[str, Any]] = [] + offset = 0 + while True: + params: dict[str, Any] = {"select": select, **{k: f"eq.{v}" for k, v in filters.items()}, + "limit": _PAGE, "offset": offset} + resp = self.session.request("GET", f"{API}{path}", params=params, + ok=(206, 400, 422)) + if resp.status_code in (400, 422): + raise _classify("GET", path, resp) + items = json_of(resp) or [] + out.extend(items) + if resp.status_code != 206 or not items: + return out + offset += len(items) + + @staticmethod + def _volume(item: dict[str, Any]) -> Volume: + return Volume(id=item["id"], name=item["name"], size_bytes=int(item["size"]), + wwn=powerstore_wwn(item.get("wwn")), + nguid=powerstore_nguid(item.get("nguid"))) + + def _require_volume(self, volume_id: str) -> Volume: + vol = self.get_volume(volume_id) + if vol is None: + raise ArrayNotFoundError(f"PowerStore volume {volume_id} not found") + return vol + + # -- contract ------------------------------------------------------------- + + def get_info(self) -> ArrayInfo: + clusters = self._list("/cluster", "id,name,global_id") + cluster = clusters[0] if clusters else {} + model = version = "" + try: + appliances = self._list("/appliance", "id,name,model") + model = next((a.get("model", "") for a in appliances if a.get("model")), "") + software = self._list("/software_installed", "id,release_version,is_cluster", + is_cluster="true") + version = next((s.get("release_version", "") for s in software), "") + except (ArrayRequestError, ArrayNotFoundError): + pass + return ArrayInfo(vendor=self.vendor, model=model, + version=f"PowerStoreOS {version}".strip(), + serial=cluster.get("global_id") or cluster.get("id", "")) + + def create_volume(self, name: str, size_bytes: int) -> Volume: + body: dict[str, Any] = {"name": name, "size": size_bytes} + if self.option("appliance_id"): + body["appliance_id"] = self.option("appliance_id") + resp = self._call("POST", "/volume", json=body) + created = json_of(resp) if resp is not None else None + if not created or "id" not in created: + raise ArrayRequestError(f"PowerStore volume create for {name} returned no id") + return self._require_volume(created["id"]) + + def get_volume(self, volume_id: str) -> Volume | None: + item = self._one(f"/volume/{volume_id}", VOLUME_FIELDS) + return self._volume(item) if item else None + + def find_volume(self, name: str) -> Volume | None: + items = self._list("/volume", VOLUME_FIELDS, name=name) + return self._volume(items[0]) if items else None + + def resize_volume(self, volume_id: str, size_bytes: int) -> Volume: + self._call("PATCH", f"/volume/{volume_id}", json={"size": size_bytes}) + return self._require_volume(volume_id) + + def delete_volume(self, volume_id: str) -> None: + self._call("DELETE", f"/volume/{volume_id}") + + def _host_by_name(self, name: str) -> dict[str, Any] | None: + items = self._list("/host", HOST_FIELDS, name=name) + return items[0] if items else None + + def ensure_host(self, spec: HostSpec) -> str: + wanted: list[dict[str, str]] = [] + for i in spec.initiators: + port_name = colon_wwpn(i.address) if i.protocol == Protocol.FC else i.normalized() + wanted.append({"port_name": port_name, "port_type": _PORT_TYPE[i.protocol]}) + host = self._host_by_name(spec.name) + if host is None: + resp = self._call("POST", "/host", json={ + "name": spec.name, "os_type": self.option("os_type"), "initiators": wanted}) + created = json_of(resp) if resp is not None else None + if not created or "id" not in created: + raise ArrayRequestError(f"PowerStore host create for {spec.name} returned no id") + return str(created["id"]) + have = {_port_key(p.get("port_type", ""), p.get("port_name", "")) + for p in host.get("host_initiators") or []} + missing = [w for w in wanted if _port_key(w["port_type"], w["port_name"]) not in have] + if missing: + self._call("PATCH", f"/host/{host['id']}", json={"add_initiators": missing}) + return str(host["id"]) + + def delete_host(self, host_id: str) -> None: + self._call("DELETE", f"/host/{host_id}", missing_ok=True) + + def _mappings(self, volume_id: str) -> list[Mapping]: + items = self._list("/host_volume_mapping", MAPPING_FIELDS, volume_id=volume_id) + out = [] + for i in items: + host = i.get("host_id") or i.get("host_group_id") + if host: + lun = i.get("logical_unit_number") + out.append(Mapping(volume_id=i["volume_id"], host_id=host, + lun=int(lun) if lun is not None else None)) + return out + + def map_volume(self, volume_id: str, host_id: str) -> Mapping: + for m in self._mappings(volume_id): + if m.host_id == host_id: + return m + self._call("POST", f"/volume/{volume_id}/attach", json={"host_id": host_id}) + for m in self._mappings(volume_id): + if m.host_id == host_id: + return m + raise ArrayRequestError( + f"PowerStore attached volume {volume_id} to host {host_id} but lists no mapping") + + def unmap_volume(self, volume_id: str, host_id: str) -> None: + if not any(m.host_id == host_id for m in self._mappings(volume_id)): + return + self._call("POST", f"/volume/{volume_id}/detach", json={"host_id": host_id}, + missing_ok=True) + + def list_mappings(self, volume_id: str) -> list[Mapping]: + return self._mappings(volume_id) diff --git a/simplyblock_core/storage_arrays/adapters/hitachi_vsp.py b/simplyblock_core/storage_arrays/adapters/hitachi_vsp.py new file mode 100644 index 0000000000..29cead34cd --- /dev/null +++ b/simplyblock_core/storage_arrays/adapters/hitachi_vsp.py @@ -0,0 +1,570 @@ +"""Hitachi VSP (VSP One Block, VSP E series, VSP 5000, VSP G/F) through the +Configuration Manager REST API. + +Deployment modes (option ``storage_device_id``): + +* embedded (option absent): the API runs on the SVP / controller and objects + live under ``/ConfigurationManager/v1/objects/...``; +* REST API server (Ops Center API Configuration Manager): the storage system + must already be registered on the server; objects live under + ``/ConfigurationManager/v1/objects/storages/{storageDeviceId}/...``. + +Auth: ``POST .../sessions`` with HTTP basic auth (a storage-system user) +returns ``{"token", "sessionId"}``; later requests send ``Authorization: +Session ``; ``DELETE .../sessions/{sessionId}`` discards it. An expired +session answers 401, which the client turns into one re-login. + +Asynchronous jobs: create/modify/delete requests answer ``202`` with a job +object (``jobId``, ``status``, ``state``, ``affectedResources``, ``error``). +The adapter polls ``GET .../jobs/{jobId}`` until ``status == "Completed"``; +``state`` is then ``Succeeded`` or ``Failed`` (``error`` carries the usual +error body). Polling gives up after ``job_timeout_s``; the job may still +finish on the array, and every operation is safe to re-run. + +Object model: + +* volume = DP-VOL LDEV in pool ``pool_id``; ``Volume.id`` is the decimal LDEV + number, ``Volume.name`` the LDEV label (max 32 characters, not unique on the + array). A deleted LDEV still answers ``GET /ldevs/{id}`` with + ``emulationType == "NOT DEFINED"``, which reads as "missing". +* host = one host group (FC) / iSCSI target (iSCSI) of the same name on every + configured port of the matching type; the host id is that name. Initiators + are ``host-wwns`` / ``host-iscsis`` of each of those groups. +* mapping = one LU path per port (``POST /luns``); the adapter uses the same + LUN number on every port and reports the LUN of the first configured port. + +Volume identity: SCSI ``naa.`` (lowercase). + +Verify against a real system: + +* ``POST /ldevs`` without ``ldevId`` auto-assigns a free LDEV number (newer + API versions); older microcode may require ``ldevId`` or a + ``startLdevId``/``endLdevId`` range -- set ``ldev_range`` there. +* The label is set in a second request (``PUT /ldevs/{id}``); a crash between + the two leaves an unlabeled LDEV the client cannot find (a label failure + is cleaned up here, a crash is not). +* ``find_volume`` lists DP-VOLs of the pool (``ldevOption=dpVolume&poolId=``, + paged by ``headLdevId``/``count``) and matches labels client-side: one or a + few requests per 16k LDEVs. The API has no label filter that we know of. +* ``naaId`` is derived from the serial and LDEV number, so a deleted LDEV's + number reused by a later volume has the same WWN; ownership then rests on + the ``sb-`` label. +* DP-VOL capacity: the adapter rounds to 1 MiB (safe for data-reduction + volumes, which need MiB alignment) and creates at least 64 MiB (DP-VOLs + have a ~47 MB floor on some models). +* ``GET /ldevs/{id}`` lists its LU paths under ``ports`` (``portId``, + ``hostGroupNumber``, ``hostGroupName``, ``lun``); mappings are read from + there. +* ``GET /host-wwns`` and ``/host-iscsis`` need ``portId`` and + ``hostGroupNumber``, so detecting an initiator owned by another host lists + every host group on each configured port (one request per group). + FC rejects a WWN registered to two host groups of one port; iSCSI allows + the same initiator in several targets, so the scan is what enforces + ownership there. +* Some models / configurations require the resource-group lock + (``services/resource-group-service/actions/lock/invoke``) around changes; + enable with ``use_lock``. +* Error ``messageId``s: storage-side failures mostly arrive as + ``KART30000-E`` with SSB codes in ``errorCode``; errors are classified by + HTTP status first, then by message text (see ``_classify``). +* NVMe-oF (``/nvm-subsystems``) is not implemented: only FC and iSCSI. +""" +from __future__ import annotations + +import re +import time +from collections.abc import Iterator +from contextlib import contextmanager +from typing import Any + +from ..base import ( + ArrayAdapter, + ArrayConflictError, + ArrayError, + ArrayInfo, + ArrayNotFoundError, + ArrayRequestError, + Capabilities, + HostSpec, + Mapping, + OptionDoc, + Protocol, + Volume, +) +from ..http import json_of + +ROOT = "/ConfigurationManager/v1/objects" +BLOCK = 512 +NOT_DEFINED = "NOT DEFINED" +MAX_LUN = 2047 +#: ``count`` per ``GET /ldevs`` page (the API maximum). +PAGE_SIZE = 16384 + +_PORT_RE = re.compile(r"^CL[0-9A-Z]+-[A-Z0-9]+$") +_RANGE_RE = re.compile(r"^\s*(\d+)\s*-\s*(\d+)\s*$") +_PORT_TYPES = {"FIBRE": Protocol.FC, "ISCSI": Protocol.ISCSI} +#: HTTP statuses whose Hitachi error body the adapter classifies itself +#: (401/403 stay with RestSession -> ArrayAuthError). +_OWN_STATUSES = (400, 404, 405, 409, 412, 500, 502, 503, 504) + +_CONFLICT_TEXT = ("already", "in use", "is used", "registered", "duplicat", + "lu path is defined", "lu paths are defined", "locked") +_MISSING_TEXT = ("does not exist", "not found", "not defined", "not exist") + + +def _monotonic() -> float: + return time.monotonic() + + +def _classify(where: str, status: int | None, body: Any) -> ArrayError: + """Map a Hitachi error body (``errorSource``, ``message``, ``solution``, + ``messageId``, ``errorCode``) to an ArrayError.""" + if isinstance(body, dict): + message = str(body.get("message") or body.get("error") or "") + msg_id = str(body.get("messageId") or "") + codes = body.get("errorCode") + ssb = "" + if isinstance(codes, dict) and codes: + ssb = " (" + ", ".join(f"{k}={v}" for k, v in sorted(codes.items())) + ")" + text = f"{where}: {msg_id + ' ' if msg_id else ''}{message}{ssb}".strip() + else: + message = str(body or "") + text = f"{where}: {message}" + if status: + text += f" [HTTP {status}]" + lowered = message.lower() + if status == 404: + return ArrayNotFoundError(text) + if status in (409, 412): + return ArrayConflictError(text) + if status is None or status in (400, 500): + if any(t in lowered for t in _MISSING_TEXT): + return ArrayNotFoundError(text) + if any(t in lowered for t in _CONFLICT_TEXT): + return ArrayConflictError(text) + return ArrayRequestError(text, status=status) + + +def _tail(resource: str) -> str: + """``/ConfigurationManager/v1/objects/ldevs/123`` -> ``123``.""" + return resource.rstrip("/").rsplit("/", 1)[-1] + + +class HitachiVspAdapter(ArrayAdapter): + vendor = "hitachi-vsp" + display_name = "Hitachi VSP" + capabilities = Capabilities( + protocols=frozenset({Protocol.FC, Protocol.ISCSI}), + size_granularity_bytes=1 << 20, + min_size_bytes=64 << 20, + # LDEV labels and iSCSI target names: 32 characters. + max_name_len=32, + ) + option_docs = ( + OptionDoc("pool_id", "DP (HDP/HDT) pool number volumes are created in.", + required=True), + OptionDoc("ports", "Target ports hosts are presented on, e.g. " + "['CL1-A', 'CL2-A']. FC and iSCSI ports may be mixed; a host " + "uses the ports of its initiators' protocol.", required=True), + OptionDoc("storage_device_id", "storageDeviceId (e.g. '886000123456') when " + "the endpoint is an Ops Center API Configuration Manager server; " + "leave unset for the API embedded on the SVP/controller."), + OptionDoc("ldev_range", "Restrict new LDEV numbers (and volume lookups) " + "to 'start-end' (decimal LDEV ids)."), + OptionDoc("host_mode", "hostMode of new host groups.", default="LINUX/IRIX"), + OptionDoc("host_mode_options", "hostModeOptions numbers for new host groups.", + default=()), + OptionDoc("job_timeout_s", "Seconds to wait for an asynchronous job.", + default=300), + OptionDoc("use_lock", "Take the resource-group lock around configuration " + "changes (needed on some models/configurations).", default=False), + OptionDoc("lock_wait_s", "waitTime for the resource-group lock.", default=30), + ) + + def __init__(self, ctx): + super().__init__(ctx) + ports = self.option("ports") + if isinstance(ports, str): + ports = [p for p in ports.replace(",", " ").split() if p] + if not ports or not all(isinstance(p, str) and _PORT_RE.match(p.upper()) + for p in ports): + raise ArrayError(f"Hitachi VSP option 'ports' must list port ids like " + f"'CL1-A'; got {self.option('ports')!r}") + self._ports: list[str] = list(dict.fromkeys(p.upper() for p in ports)) + try: + self._pool = int(self.option("pool_id")) + except (TypeError, ValueError) as e: + raise ArrayError("Hitachi VSP option 'pool_id' must be a number") from e + self._range: tuple[int, int] | None = None + rng = self.option("ldev_range") + if rng: + m = _RANGE_RE.match(str(rng)) + if not m or int(m.group(1)) > int(m.group(2)): + raise ArrayError(f"Hitachi VSP option 'ldev_range' must be 'start-end'; " + f"got {rng!r}") + self._range = (int(m.group(1)), int(m.group(2))) + sdid = self.option("storage_device_id") + self._base = f"{ROOT}/storages/{sdid}" if sdid else ROOT + self._session_id: Any = None + self._port_types: dict[str, Protocol | None] = {} + + # -- session ------------------------------------------------------------ + + def login(self) -> None: + self.session.headers.pop("Authorization", None) + self._session_id = None + resp = self.session.post(f"{self._base}/sessions", + auth=(self.secret("username"), self.secret("password"))) + body = json_of(resp) or {} + token = body.get("token") + if not token: + raise ArrayRequestError("Hitachi VSP session request returned no token") + self._session_id = body.get("sessionId") + self.session.headers["Authorization"] = f"Session {token}" + + def close(self) -> None: + if self._session_id is not None and "Authorization" in self.session.headers: + try: + self.session.delete(f"{self._base}/sessions/{self._session_id}") + except Exception: + pass + self.session.headers.pop("Authorization", None) + self._session_id = None + + # -- request helpers ----------------------------------------------------- + + def _req(self, method: str, path: str, *, params: Any = None, + json: Any = None) -> tuple[int, Any]: + full = path if path.startswith(ROOT) else f"{self._base}{path}" + resp = self.session.request(method, full, params=params, json=json, + ok=_OWN_STATUSES) + try: + body = json_of(resp) + except ArrayRequestError: + body = resp.text + if resp.status_code >= 400: + raise _classify(f"{method} {path}", resp.status_code, body) + return resp.status_code, body + + def _get(self, path: str, **params: Any) -> Any: + return self._req("GET", path, params=params or None)[1] + + def _data(self, path: str, **params: Any) -> list[dict[str, Any]]: + return list((self._get(path, **params) or {}).get("data", [])) + + def _run(self, method: str, path: str, json: Any = None) -> list[str]: + """Issue a change request, wait for its job and return the job's + ``affectedResources``.""" + status, body = self._req(method, path, json=json) + if not isinstance(body, dict) or "jobId" not in body: + return [] + job = self._wait(body) + if job.get("state") != "Succeeded": + raise _classify(f"{method} {path} (job {job.get('jobId')} {job.get('state')})", + None, job.get("error") or {"message": "job did not succeed"}) + return [str(r) for r in job.get("affectedResources") or []] + + def _wait(self, job: dict[str, Any]) -> dict[str, Any]: + timeout = float(self.option("job_timeout_s")) + sleep = self.session.sleep + deadline = _monotonic() + timeout + interval, waited = 0.5, 0.0 + job_id = job["jobId"] + while job.get("status") != "Completed": + if waited >= timeout or _monotonic() > deadline: + raise ArrayRequestError( + f"Hitachi VSP job {job_id} not completed after {timeout:g}s " + f"(status {job.get('status')}, state {job.get('state')}); " + "it may still finish on the array") + sleep(interval) + waited += interval + interval = min(interval * 2, 5.0) + job = self._get(f"/jobs/{job_id}") or {} + return job + + @contextmanager + def _change(self) -> Iterator[None]: + """Resource-group lock around a configuration change (``use_lock``).""" + if not self.option("use_lock"): + yield + return + svc = "/services/resource-group-service/actions" + self._run("POST", f"{svc}/lock/invoke", + {"parameters": {"waitTime": int(self.option("lock_wait_s"))}}) + try: + yield + finally: + try: + self._run("POST", f"{svc}/unlock/invoke", {}) + except ArrayError: + pass + + # -- volumes -------------------------------------------------------------- + + @staticmethod + def _defined(ldev: dict[str, Any] | None) -> bool: + return bool(ldev) and (ldev or {}).get("emulationType", NOT_DEFINED) != NOT_DEFINED + + @staticmethod + def _volume(ldev: dict[str, Any]) -> Volume: + naa = str(ldev.get("naaId") or "").lower() + return Volume(id=str(ldev["ldevId"]), name=str(ldev.get("label") or ""), + size_bytes=int(ldev["blockCapacity"]) * BLOCK, + wwn=f"naa.{naa}" if naa else None) + + def _ldev(self, volume_id: str) -> dict[str, Any] | None: + if not str(volume_id).isdigit(): + return None + try: + ldev = self._get(f"/ldevs/{int(volume_id)}") + except ArrayNotFoundError: + return None + return ldev if self._defined(ldev) else None + + def _require(self, volume_id: str) -> dict[str, Any]: + ldev = self._ldev(volume_id) + if ldev is None: + raise ArrayNotFoundError(f"LDEV {volume_id} is not defined") + return ldev + + def get_info(self) -> ArrayInfo: + sdid = self.option("storage_device_id") + info = self._get(f"{ROOT}/storages/{sdid}" if sdid else f"{ROOT}/storages/instance") + info = info or {} + return ArrayInfo(vendor=self.vendor, model=str(info.get("model", "")), + version=str(info.get("dkcMicroVersion", "")), + serial=str(info.get("serialNumber", ""))) + + def create_volume(self, name: str, size_bytes: int) -> Volume: + body: dict[str, Any] = {"poolId": self._pool, "blockCapacity": size_bytes // BLOCK} + if self._range: + body["startLdevId"], body["endLdevId"] = self._range + with self._change(): + affected = self._run("POST", "/ldevs", body) + ldev_ids = [_tail(r) for r in affected if "/ldevs/" in r] + if not ldev_ids: + raise ArrayRequestError(f"Hitachi VSP LDEV create for {name} reported no LDEV") + ldev_id = ldev_ids[0] + try: + self._run("PUT", f"/ldevs/{ldev_id}", {"label": name}) + except ArrayError: + # An unlabeled LDEV cannot be found again; do not leak it. + try: + self._run("DELETE", f"/ldevs/{ldev_id}") + except ArrayError: + pass + raise + return self._volume(self._require(ldev_id)) + + def get_volume(self, volume_id: str) -> Volume | None: + ldev = self._ldev(volume_id) + return self._volume(ldev) if ldev else None + + def find_volume(self, name: str) -> Volume | None: + head, end = self._range if self._range else (0, None) + found: list[dict[str, Any]] = [] + while True: + page = self._data("/ldevs", ldevOption="dpVolume", poolId=self._pool, + headLdevId=head, count=PAGE_SIZE) + for ldev in page: + if end is not None and int(ldev["ldevId"]) > end: + break + if ldev.get("label") == name and self._defined(ldev): + found.append(ldev) + if len(page) < PAGE_SIZE: + break + head = int(page[-1]["ldevId"]) + 1 + if end is not None and head > end: + break + if len(found) > 1: + raise ArrayConflictError( + f"Several LDEVs labeled {name!r}: " + + ", ".join(str(f["ldevId"]) for f in found)) + if not found: + return None + # List entries may omit fields; read the LDEV itself. + return self.get_volume(str(found[0]["ldevId"])) + + def resize_volume(self, volume_id: str, size_bytes: int) -> Volume: + ldev = self._require(volume_id) + add = size_bytes // BLOCK - int(ldev["blockCapacity"]) + if add > 0: + with self._change(): + self._run("POST", f"/ldevs/{ldev['ldevId']}/actions/expand/invoke", + {"parameters": {"additionalBlockCapacity": add}}) + return self._volume(self._require(volume_id)) + + def delete_volume(self, volume_id: str) -> None: + ldev = self._require(volume_id) + with self._change(): + self._run("DELETE", f"/ldevs/{ldev['ldevId']}") + + # -- ports and host groups ------------------------------------------------------ + + def _port_protocol(self, port: str) -> Protocol | None: + if port not in self._port_types: + info = self._get(f"/ports/{port}") or {} + self._port_types[port] = _PORT_TYPES.get(str(info.get("portType", "")).upper()) + return self._port_types[port] + + def _ports_for(self, protocol: Protocol) -> list[str]: + return [p for p in self._ports if self._port_protocol(p) == protocol] + + def _groups(self, port: str) -> list[dict[str, Any]]: + return self._data("/host-groups", portId=port) + + @staticmethod + def _by_name(groups: list[dict[str, Any]], name: str) -> dict[str, Any] | None: + return next((g for g in groups if g.get("hostGroupName") == name), None) + + def _host_groups(self, name: str) -> list[tuple[str, int]]: + """(port, hostGroupNumber) of host ``name`` on every configured port.""" + out = [] + for port in self._ports: + g = self._by_name(self._groups(port), name) + if g is not None: + out.append((port, int(g["hostGroupNumber"]))) + return out + + def _members(self, protocol: Protocol, port: str, number: int) -> set[str]: + if protocol == Protocol.FC: + items = self._data("/host-wwns", portId=port, hostGroupNumber=number) + return {str(i.get("hostWwn", "")).lower() for i in items} + items = self._data("/host-iscsis", portId=port, hostGroupNumber=number) + return {str(i.get("iscsiName", "")).lower() for i in items} + + def _add_member(self, protocol: Protocol, port: str, number: int, address: str) -> None: + if protocol == Protocol.FC: + self._run("POST", "/host-wwns", + {"hostWwn": address, "portId": port, "hostGroupNumber": number}) + else: + self._run("POST", "/host-iscsis", + {"iscsiName": address, "portId": port, "hostGroupNumber": number}) + + def ensure_host(self, spec: HostSpec) -> str: + wanted = {p: spec.addresses(p) for p in (Protocol.FC, Protocol.ISCSI)} + wanted = {p: a for p, a in wanted.items() if a} + plan: list[tuple[Protocol, str, list[dict[str, Any]]]] = [] + for protocol, addresses in wanted.items(): + ports = self._ports_for(protocol) + if not ports: + raise ArrayError(f"Hitachi VSP array {self.config.id} has no configured " + f"{protocol.value} port (option 'ports': {self._ports})") + for port in ports: + groups = self._groups(port) + # Ownership check before any change: FC refuses a WWN in two + # host groups of a port, iSCSI does not, so scan both. + for g in groups: + if g.get("hostGroupName") == spec.name: + continue + taken = self._members(protocol, port, int(g["hostGroupNumber"])) + clash = sorted(set(addresses) & taken) + if clash: + raise ArrayConflictError( + f"Initiator {clash[0]} is registered to host group " + f"{g.get('hostGroupName')!r} ({g.get('hostGroupId')}) " + f"on port {port}") + plan.append((protocol, port, groups)) + with self._change(): + for protocol, port, groups in plan: + current = self._by_name(groups, spec.name) + if current is None: + body: dict[str, Any] = {"portId": port, "hostGroupName": spec.name, + "hostMode": self.option("host_mode")} + if self.option("host_mode_options"): + body["hostModeOptions"] = [int(o) for o in + self.option("host_mode_options")] + affected = self._run("POST", "/host-groups", body) + ids = [_tail(r) for r in affected if "/host-groups/" in r] + if ids: + number = int(ids[0].split(",")[1]) + else: + found = self._by_name(self._groups(port), spec.name) + if found is None: + raise ArrayRequestError( + f"Host group {spec.name} not found on {port} after create") + number = int(found["hostGroupNumber"]) + have: set[str] = set() + else: + number = int(current["hostGroupNumber"]) + have = self._members(protocol, port, number) + for address in wanted[protocol]: + if address.lower() not in have: + self._add_member(protocol, port, number, address) + return spec.name + + def delete_host(self, host_id: str) -> None: + targets = [(p, n) for p, n in self._host_groups(host_id) if n != 0] + if not targets: + return + with self._change(): + for port, number in targets: + try: + self._run("DELETE", f"/host-groups/{port},{number}") + except ArrayNotFoundError: + pass + + # -- mappings -------------------------------------------------------------------- + + def _paths(self, ldev: dict[str, Any], host_id: str | None = None + ) -> list[dict[str, Any]]: + order = {p: i for i, p in enumerate(self._ports)} + paths = [p for p in ldev.get("ports") or [] + if p.get("portId") in order + and (host_id is None or p.get("hostGroupName") == host_id)] + return sorted(paths, key=lambda p: order[p["portId"]]) + + def _mappings(self, ldev: dict[str, Any], host_id: str | None = None) -> list[Mapping]: + out: dict[str, Mapping] = {} + for p in self._paths(ldev, host_id): + name = str(p.get("hostGroupName")) + out.setdefault(name, Mapping(volume_id=str(ldev["ldevId"]), host_id=name, + lun=int(p["lun"]))) + return list(out.values()) + + def map_volume(self, volume_id: str, host_id: str) -> Mapping: + ldev = self._require(volume_id) + groups = self._host_groups(host_id) + if not groups: + raise ArrayNotFoundError(f"Host {host_id} has no host group on " + f"ports {', '.join(self._ports)}") + present = {(p["portId"], int(p["hostGroupNumber"])): int(p["lun"]) + for p in self._paths(ldev, host_id)} + missing = [g for g in groups if g not in present] + if missing: + used: set[int] = set() + for port, number in missing: + used |= {int(lu["lun"]) for lu in + self._data("/luns", portId=port, hostGroupNumber=number)} + preferred = next(iter(present.values()), None) + lun = preferred if preferred is not None and preferred not in used else next( + (n for n in range(MAX_LUN + 1) if n not in used), None) + if lun is None: + raise ArrayConflictError(f"Host {host_id} has no free LUN") + with self._change(): + for port, number in missing: + self._run("POST", "/luns", {"portId": port, "hostGroupNumber": number, + "ldevId": int(ldev["ldevId"]), "lun": lun}) + ldev = self._require(volume_id) + mappings = self._mappings(ldev, host_id) + if not mappings: + raise ArrayRequestError(f"LDEV {volume_id} shows no path to {host_id} after mapping") + return mappings[0] + + def unmap_volume(self, volume_id: str, host_id: str) -> None: + ldev = self._ldev(volume_id) + if ldev is None: + return + paths = self._paths(ldev, host_id) + if not paths: + return + with self._change(): + for p in paths: + try: + self._run("DELETE", + f"/luns/{p['portId']},{p['hostGroupNumber']},{p['lun']}") + except ArrayNotFoundError: + pass + + def list_mappings(self, volume_id: str) -> list[Mapping]: + return self._mappings(self._require(volume_id)) diff --git a/simplyblock_core/storage_arrays/adapters/hpe_nimble.py b/simplyblock_core/storage_arrays/adapters/hpe_nimble.py new file mode 100644 index 0000000000..35cd1583ea --- /dev/null +++ b/simplyblock_core/storage_arrays/adapters/hpe_nimble.py @@ -0,0 +1,321 @@ +"""HPE Alletra 5000/6000 and Nimble Storage, NimbleOS REST API v1. + +The endpoint normally includes the API port: ``https://array:5392``. + +Auth: ``POST /v1/tokens {"data": {"username", "password"}}`` returns +``data.session_token`` (sent as ``X-Auth-Token``) and ``data.id`` (used to +release the token with ``DELETE /v1/tokens/``). Every request and +response body is wrapped in ``{"data": ...}``; errors are +``{"messages": [{"code": "SM_...", "severity": "error", "text": "..."}]}``. + +Volumes: sizes are in MiB. ``Volume.id`` is the NimbleOS object id. A volume +must be taken offline (``PUT {"data": {"online": false}}``) before it can be +deleted. + +Hosts are *initiator groups* (``access_protocol`` ``iscsi`` or ``fc``); the +host id is the group id. Initiators are added one by one with ``POST +/v1/initiators``; FC WWPNs use the colon form. Before adding, the adapter +looks each initiator up and raises :class:`ArrayConflictError` if another +group owns it (whether NimbleOS itself forbids an initiator in two groups is +not relied on). Mappings are *access control records* (ACRs) with +``apply_to: "both"`` (volume and its snapshots); the array assigns the LUN. + +Volume identity: NimbleOS volumes report a 32-hex ``serial_number`` and +present it to hosts as a 16-byte **EUI-64** designator (multipath WWID +``2``, sysfs ``wwid`` ``eui.``), not an NAA. The adapter +reports it as ``wwn="eui."`` (``Volume.wwn`` holds the SCSI +designator, NAA or EUI-64), so the identifier equals the host's sysfs wwid. + +Verify against a real system +---------------------------- +* The EUI-64 derivation above (``eui.`` + ``serial_number`` lowercase), both + for iSCSI and FC, on NimbleOS 5.x/6.x. +* Error codes: ``SM_http_unauthorized`` (401) for bad login and expired + tokens; ``SM_eexist`` (409) for duplicate names and ACRs; + ``SM_http_not_found``/``SM_enoent`` (404) for unknown ids; ``SM_vol_online`` + (409, deleting an online volume); ``SM_vol_has_acl`` / ACR-related refusal + when offlining a connected volume; ``SM_invalid_arg`` (400). The adapter + keys on HTTP status, and treats 400 + ``SM_enoent`` / "not found" as + not-found. +* Whether ``GET /v1/volumes/`` for a malformed id answers 400 or 404 + (both are treated as "missing" by ``get_volume``). +* Query filtering on any attribute (``/v1/initiators/detail?iqn=...``, + ``/v1/access_control_records/detail?vol_id=...``) and that a filtered list + with no hits returns ``data: []`` rather than 404. +* LUN assignment: with volume-scoped iSCSI targets (the default on recent + NimbleOS) every iSCSI ACR shows ``lun`` 0; group-scoped targets and FC get + distinct LUNs per initiator group. +* That ``label`` is required for iSCSI initiators (max 64 chars) and is + unique only within its group. +* Shrinking (``PUT size`` below current) is refused; we never request it. +""" +from __future__ import annotations + +import hashlib +from typing import Any +from urllib.parse import quote + +import requests + +from ..base import ( + ArrayAdapter, + ArrayAuthError, + ArrayConflictError, + ArrayError, + ArrayInfo, + ArrayNotFoundError, + ArrayRequestError, + Capabilities, + HostSpec, + Mapping, + OptionDoc, + Protocol, + Volume, + colon_wwpn, + normalize_wwpn, +) +from ..http import body_text, json_of + +MIB = 1 << 20 +_NOT_FOUND_CODES = frozenset({"SM_enoent", "SM_http_not_found", "SM_no_such_object"}) + + +def nimble_eui(serial: str) -> str: + return "eui." + serial.lower() + + +class HpeNimbleAdapter(ArrayAdapter): + vendor = "hpe-nimble" + display_name = "HPE Alletra 5000/6000 / Nimble" + capabilities = Capabilities( + protocols=frozenset({Protocol.ISCSI, Protocol.FC}), + size_granularity_bytes=MIB, + min_size_bytes=MIB, + max_name_len=63, + ) + credential_fields = (frozenset({"username", "password"}),) + option_docs = ( + OptionDoc("pool", "Pool name new volumes are created in (default: the " + "array's default pool)."), + OptionDoc("performance_policy", "Performance policy name for new volumes " + "(default: the array default)."), + ) + + def __init__(self, ctx): + super().__init__(ctx) + self._token_id: str | None = None + self._create_extra: dict[str, str] | None = None + + # -- session ------------------------------------------------------------ + + def login(self) -> None: + self.session.headers.pop("X-Auth-Token", None) + data = self._data("POST", "/v1/tokens", + json={"data": {"username": self.secret("username"), + "password": self.secret("password")}}) + token = (data or {}).get("session_token") + if not token: + raise ArrayRequestError("NimbleOS login returned no session_token") + self._token_id = data.get("id") + self.session.headers["X-Auth-Token"] = token + + def close(self) -> None: + token_id, self._token_id = self._token_id, None + if token_id and "X-Auth-Token" in self.session.headers: + try: + self.session.delete(f"/v1/tokens/{quote(token_id, safe='')}", + ok=(401, 404)) + except Exception: + pass + self.session.headers.pop("X-Auth-Token", None) + + # -- request helpers ----------------------------------------------------- + + def _request(self, method: str, path: str, *, params: Any = None, json: Any = None, + missing_ok: bool = False) -> requests.Response | None: + resp = self.session.request(method, path, params=params, json=json, + ok=(400, 401, 403, 404, 409)) + status = resp.status_code + if status < 400: + return resp + codes: list[str] = [] + text = body_text(resp) + try: + messages = (resp.json() or {}).get("messages") or [] + codes = [str(m.get("code", "")) for m in messages] + text = "; ".join(f"{m.get('code', '')}: {m.get('text', '')}" for m in messages) or text + except (ValueError, AttributeError): + pass + msg = f"{method} {path} -> HTTP {status}: {text}" + if status in (401, 403): + raise ArrayAuthError(msg) + if status == 404 or any(c in _NOT_FOUND_CODES for c in codes): + if missing_ok: + return None + raise ArrayNotFoundError(msg) + if status == 409 or "SM_eexist" in codes: + raise ArrayConflictError(msg) + raise ArrayRequestError(msg, status=status) + + def _data(self, method: str, path: str, **kw: Any) -> Any: + resp = self._request(method, path, **kw) + if resp is None: + return None + return (json_of(resp) or {}).get("data") + + def _list(self, path: str, **filters: str) -> list[dict[str, Any]]: + return list(self._data("GET", path, params=filters) or []) + + @staticmethod + def _volume(item: dict[str, Any]) -> Volume: + serial = item.get("serial_number") or "" + return Volume(id=item["id"], name=item["name"], size_bytes=int(item["size"]) * MIB, + wwn=nimble_eui(serial) if serial else None) + + def _lookup_id(self, path: str, name: str, what: str) -> str: + items = self._list(path, name=name) + if not items: + raise ArrayError(f"{self.display_name} array {self.config.id}: " + f"{what} {name!r} not found") + return str(items[0]["id"]) + + def _volume_extra(self) -> dict[str, str]: + if self._create_extra is None: + extra: dict[str, str] = {} + if self.option("pool"): + extra["pool_id"] = self._lookup_id("/v1/pools/detail", self.option("pool"), + "pool") + if self.option("performance_policy"): + extra["perfpolicy_id"] = self._lookup_id( + "/v1/performance_policies/detail", self.option("performance_policy"), + "performance policy") + self._create_extra = extra + return self._create_extra + + # -- contract ------------------------------------------------------------- + + def get_info(self) -> ArrayInfo: + arrays = self._list("/v1/arrays/detail") + arr = arrays[0] if arrays else {} + return ArrayInfo(vendor=self.vendor, model=str(arr.get("model", "")), + version=str(arr.get("version", "")), + serial=str(arr.get("serial", ""))) + + def create_volume(self, name: str, size_bytes: int) -> Volume: + body = {"name": name, "size": -(-size_bytes // MIB), **self._volume_extra()} + return self._volume(self._data("POST", "/v1/volumes", json={"data": body})) + + def get_volume(self, volume_id: str) -> Volume | None: + try: + data = self._data("GET", f"/v1/volumes/{quote(volume_id, safe='')}", + missing_ok=True) + except ArrayRequestError as e: + if e.status == 400: # malformed id: cannot exist + return None + raise + return self._volume(data) if data else None + + def find_volume(self, name: str) -> Volume | None: + items = [i for i in self._list("/v1/volumes/detail", name=name) if i.get("name") == name] + return self._volume(items[0]) if items else None + + def resize_volume(self, volume_id: str, size_bytes: int) -> Volume: + data = self._data("PUT", f"/v1/volumes/{quote(volume_id, safe='')}", + json={"data": {"size": -(-size_bytes // MIB)}}) + return self._volume(data) + + def delete_volume(self, volume_id: str) -> None: + path = f"/v1/volumes/{quote(volume_id, safe='')}" + self._data("PUT", path, json={"data": {"online": False}}) + self._request("DELETE", path) + + # -- hosts (initiator groups) ------------------------------------------- + + def _group(self, name: str) -> dict[str, Any] | None: + items = [g for g in self._list("/v1/initiator_groups/detail", name=name) + if g.get("name") == name] + return items[0] if items else None + + def _owner(self, protocol: str, key: str, value: str) -> str | None: + """Name of the initiator group that owns ``value`` (iqn or wwpn).""" + for i in self._list("/v1/initiators/detail", access_protocol=protocol, **{key: value}): + have = str(i.get(key, "")) + same = (normalize_wwpn(have) == normalize_wwpn(value) if key == "wwpn" + else have.lower() == value.lower()) + if same: + return str(i.get("initiator_group_name") or i.get("initiator_group_id")) + return None + + def ensure_host(self, spec: HostSpec) -> str: + unsupported = [p for p in spec.protocols if not p.is_scsi] + if unsupported: + raise ArrayError(f"{self.display_name} adapter does not support " + + ", ".join(sorted(p.value for p in unsupported))) + iqns = spec.addresses(Protocol.ISCSI) + wwpns = [colon_wwpn(w) for w in spec.addresses(Protocol.FC)] + if iqns and wwpns: + raise ArrayError(f"{self.display_name}: an initiator group is either iSCSI or " + "FC; register the host once per protocol") + protocol, key, wanted = ("iscsi", "iqn", iqns) if iqns else ("fc", "wwpn", wwpns) + + group = self._group(spec.name) + if group is not None and group.get("access_protocol") != protocol: + raise ArrayConflictError( + f"Initiator group {spec.name} exists with access_protocol " + f"{group.get('access_protocol')}, not {protocol}") + if group is not None: + list_key = "iscsi_initiators" if protocol == "iscsi" else "fc_initiators" + have = {str(i.get(key, "")).lower() for i in group.get(list_key) or []} + wanted = [w for w in wanted if w.lower() not in have] + for value in wanted: + owner = self._owner(protocol, key, value) + if owner is not None and owner != spec.name: + raise ArrayConflictError( + f"Initiator {value} already belongs to initiator group {owner}") + if group is None: + group = self._data("POST", "/v1/initiator_groups", + json={"data": {"name": spec.name, "access_protocol": protocol, + "description": "simplyblock"}}) + group_id = str(group["id"]) + for value in wanted: + body: dict[str, Any] = {"initiator_group_id": group_id, + "access_protocol": protocol, key: value} + if protocol == "iscsi": + body["label"] = f"sb-{hashlib.sha1(value.encode()).hexdigest()[:12]}" + self._data("POST", "/v1/initiators", json={"data": body}) + return group_id + + def delete_host(self, host_id: str) -> None: + self._request("DELETE", f"/v1/initiator_groups/{quote(host_id, safe='')}", + missing_ok=True) + + # -- mappings (access control records) ----------------------------------- + + def _acrs(self, volume_id: str, host_id: str | None = None) -> list[dict[str, Any]]: + items = self._list("/v1/access_control_records/detail", vol_id=volume_id) + return [a for a in items if a.get("vol_id") == volume_id and a.get("initiator_group_id") + and (host_id is None or a.get("initiator_group_id") == host_id)] + + @staticmethod + def _mapping(acr: dict[str, Any]) -> Mapping: + lun = acr.get("lun") + return Mapping(volume_id=acr["vol_id"], host_id=acr["initiator_group_id"], + lun=int(lun) if lun is not None else None) + + def map_volume(self, volume_id: str, host_id: str) -> Mapping: + existing = self._acrs(volume_id, host_id) + if existing: + return self._mapping(existing[0]) + acr = self._data("POST", "/v1/access_control_records", + json={"data": {"vol_id": volume_id, "initiator_group_id": host_id, + "apply_to": "both"}}) + return self._mapping(acr) + + def unmap_volume(self, volume_id: str, host_id: str) -> None: + for acr in self._acrs(volume_id, host_id): + self._request("DELETE", + f"/v1/access_control_records/{quote(str(acr['id']), safe='')}", + missing_ok=True) + + def list_mappings(self, volume_id: str) -> list[Mapping]: + return [self._mapping(a) for a in self._acrs(volume_id)] diff --git a/simplyblock_core/storage_arrays/adapters/hpe_wsapi.py b/simplyblock_core/storage_arrays/adapters/hpe_wsapi.py new file mode 100644 index 0000000000..9642886ec8 --- /dev/null +++ b/simplyblock_core/storage_arrays/adapters/hpe_wsapi.py @@ -0,0 +1,317 @@ +"""HPE WSAPI: Alletra Storage MP B10000, Primera and 3PAR StoreServ. + +Auth: ``POST /api/v1/credentials {"user", "password"}`` returns ``{"key"}``, +sent as the ``X-HP3PAR-WSAPI-SessionKey`` header on every later request and +released with ``DELETE /api/v1/credentials/``. An expired or unknown key +is answered with HTTP 401/403 (mapped to :class:`ArrayAuthError`, so the client +logs in again). + +Objects are addressed by name: ``Volume.id`` is the volume name and the host +id is the host name. Errors carry ``{"code": , "desc": "..."}``. + +Volumes: ``POST /api/v1/volumes {name, cpg, sizeMiB, tpvv|reduce}``; grow is +``PUT /api/v1/volumes/ {"action": 3, "sizeMiB": }`` -- GROW +takes the *delta*, not the new size. SCSI identity: ``naa.`` from the +volume's ``wwn`` field (``60002AC...``). + +Hosts: ``POST /api/v1/hosts {name, persona, iSCSINames|FCWWNs}``; paths are +added with ``PUT /api/v1/hosts/ {"pathOperation": 1, ...}``. Note the +asymmetry: requests use ``iSCSINames``/``FCWWNs``, responses report +``iSCSIPaths[].name``/``FCPaths[].wwn``. + +VLUNs (mappings): ``POST /api/v1/vluns {volumeName, hostname, lun, autoLun, +maxAutoLun}`` answers 201 with an empty body and a ``Location`` header +``/api/v1/vluns/,,``. ``GET /api/v1/vluns?query="volumeName EQ +"`` lists both the VLUN *template* and one *active* VLUN per host path, +so entries are de-duplicated by (volume, host). + +Only iSCSI and FC hosts are supported: NVMe/TCP and NVMe/FC hosts exist on +Alletra MP and Primera but their WSAPI host fields (``NVMETCPPaths``/NQN +attributes) are not verified, so NVMe is refused up front. + +Verify against a real system +---------------------------- +* Error codes (taken from python-3parclient / Cinder usage, not from a + spec): 23 NON_EXISTENT_VOL (404), 22 EXISTENT_VOL (409), 17 + NON_EXISTENT_HOST (404), 16 EXISTENT_HOST (409), 73 EXISTENT_PATH -- WWN/IQN + already owned by another host (409), 19 NON_EXISTENT_VLUN (404), 29 + EXISTENT_VLUN (409), 34 VOLUME_HAS_VLUNS / 26 HOST_IN_USE (409), 5 invalid + login (403), 6 invalid/expired session key (401). The adapter keys its + behaviour on HTTP status first and on codes only where listed in + ``_NOT_FOUND_CODES`` / ``_CONFLICT_CODES``. +* Whether a 403 is ever returned for a non-auth reason (it would trigger a + pointless re-login before failing). +* Size granularity: 3PAR/Primera allocate in 256 MiB units and report the + rounded ``sizeMiB``; we therefore round to 256 MiB (min 256 MiB) so the + requested and reported sizes agree. Alletra MP may accept 1 MiB units. +* ``reduce: true`` (dedup + compression) as the Alletra MP create flag, versus + ``tdvv``/``compression`` on Primera; ``tpvv: true`` for thin on 3PAR/Primera. +* Whether one host may carry both iSCSI and FC paths (passed through as given). +* The exact ``query`` syntax (``"volumeName EQ x"``, double quotes included) + and that it returns ``{"total", "members"}`` with an empty list (not 404) + when nothing matches; whether active VLUN entries carry ``active: true``. +* Persona 2 = "Generic-ALUA" (persona 1 = Generic, 11 = VMware). +* Max session count per user (stale keys from crashed processes may exhaust + it); we always ``DELETE`` the key on close. +""" +from __future__ import annotations + +import re +from typing import Any +from urllib.parse import quote, unquote + +import requests + +from ..base import ( + ArrayAdapter, + ArrayAuthError, + ArrayConflictError, + ArrayError, + ArrayInfo, + ArrayNotFoundError, + ArrayRequestError, + Capabilities, + HostSpec, + Mapping, + OptionDoc, + Protocol, + Volume, +) +from ..http import body_text, json_of + +MIB = 1 << 20 +_GRANULARITY = 256 * MIB + +SESSION_HEADER = "X-HP3PAR-WSAPI-SessionKey" +_API = "/api/v1" + +GROW_VOLUME = 3 +PATH_ADD = 1 + +_NOT_FOUND_CODES = frozenset({17, 19, 23}) +_CONFLICT_CODES = frozenset({16, 22, 26, 29, 34, 73}) + +_LOCATION_RE = re.compile(r"/api/v1/vluns/(?P[^,]+),(?P\d+),(?P[^,/]*)") + + +def wsapi_wwn(wwn: str) -> str: + return "naa." + wwn.lower() + + +class HpeWsapiAdapter(ArrayAdapter): + vendor = "hpe-wsapi" + display_name = "HPE Alletra MP / Primera / 3PAR" + capabilities = Capabilities( + protocols=frozenset({Protocol.ISCSI, Protocol.FC}), + size_granularity_bytes=_GRANULARITY, + min_size_bytes=_GRANULARITY, + max_name_len=31, + ) + credential_fields = (frozenset({"username", "password"}),) + option_docs = ( + OptionDoc("cpg", "Common Provisioning Group new volumes are created in.", + required=True), + OptionDoc("provisioning", "'tpvv' (thin, 3PAR/Primera) or 'reduce' " + "(thin + dedup + compression, Alletra MP).", default="tpvv"), + OptionDoc("persona", "Host persona id for new hosts (2 = Generic-ALUA).", + default=2), + ) + + def __init__(self, ctx): + super().__init__(ctx) + self._key: str | None = None + provisioning = str(self.option("provisioning")).lower() + if provisioning not in ("tpvv", "reduce"): + raise ArrayError(f"{self.display_name}: provisioning must be 'tpvv' or " + f"'reduce', not {provisioning!r}") + self._provisioning = provisioning + + # -- session ------------------------------------------------------------ + + def login(self) -> None: + self.session.headers.pop(SESSION_HEADER, None) + resp = self._call("POST", "/credentials", + json={"user": self.secret("username"), + "password": self.secret("password")}) + key = (json_of(resp) or {}).get("key") + if not key: + raise ArrayRequestError("WSAPI login returned no session key") + self._key = key + self.session.headers[SESSION_HEADER] = key + + def close(self) -> None: + key, self._key = self._key, None + self.session.headers.pop(SESSION_HEADER, None) + if key: + try: + self.session.delete(f"{_API}/credentials/{quote(key, safe='')}", + headers={SESSION_HEADER: key}, ok=(401, 403, 404)) + except Exception: + pass + + # -- request helpers ----------------------------------------------------- + + def _call(self, method: str, path: str, *, params: Any = None, json: Any = None, + missing_ok: bool = False) -> requests.Response: + """One WSAPI request; maps ``{"code", "desc"}`` errors to ArrayErrors. + With ``missing_ok`` a not-found answer is returned instead of raised.""" + resp = self.session.request(method, f"{_API}{path}", params=params, json=json, + ok=(400, 401, 403, 404, 409)) + status = resp.status_code + if status < 400: + return resp + code: int | None = None + desc = body_text(resp) + try: + body = resp.json() + if isinstance(body, dict): + code = int(body["code"]) if body.get("code") is not None else None + desc = str(body.get("desc", desc)) + except (ValueError, TypeError, KeyError): + pass + msg = f"{method} {path} -> HTTP {status}" + (f" code {code}" if code is not None else "") \ + + f": {desc}" + if status in (401, 403): + raise ArrayAuthError(msg) + if status == 404 or code in _NOT_FOUND_CODES: + if missing_ok: + return resp + raise ArrayNotFoundError(msg) + if status == 409 or code in _CONFLICT_CODES: + raise ArrayConflictError(msg) + raise ArrayRequestError(msg, status=status) + + @staticmethod + def _found(resp: requests.Response) -> bool: + return resp.status_code < 400 + + @staticmethod + def _volume(item: dict[str, Any]) -> Volume: + wwn = item.get("wwn") or "" + return Volume(id=item["name"], name=item["name"], + size_bytes=int(item["sizeMiB"]) * MIB, + wwn=wsapi_wwn(wwn) if wwn else None) + + # -- contract ------------------------------------------------------------- + + def get_info(self) -> ArrayInfo: + system = json_of(self._call("GET", "/system")) or {} + return ArrayInfo(vendor=self.vendor, model=str(system.get("model", "")), + version=str(system.get("systemVersion", "")), + serial=str(system.get("serialNumber", ""))) + + def create_volume(self, name: str, size_bytes: int) -> Volume: + body: dict[str, Any] = {"name": name, "cpg": self.option("cpg"), + "sizeMiB": -(-size_bytes // MIB)} + body["reduce" if self._provisioning == "reduce" else "tpvv"] = True + self._call("POST", "/volumes", json=body) + vol = self.get_volume(name) + if vol is None: + raise ArrayRequestError(f"Volume {name} not found right after creation") + return vol + + def get_volume(self, volume_id: str) -> Volume | None: + resp = self._call("GET", f"/volumes/{quote(volume_id, safe='')}", missing_ok=True) + return self._volume(json_of(resp)) if self._found(resp) else None + + def find_volume(self, name: str) -> Volume | None: + return self.get_volume(name) + + def resize_volume(self, volume_id: str, size_bytes: int) -> Volume: + vol = self.get_volume(volume_id) + if vol is None: + raise ArrayNotFoundError(f"Volume {volume_id} does not exist") + delta = -(-size_bytes // MIB) - vol.size_bytes // MIB + if delta > 0: + self._call("PUT", f"/volumes/{quote(volume_id, safe='')}", + json={"action": GROW_VOLUME, "sizeMiB": delta}) + elif delta < 0: + raise ArrayConflictError(f"WSAPI cannot shrink volume {volume_id}") + new = self.get_volume(volume_id) + if new is None: + raise ArrayNotFoundError(f"Volume {volume_id} vanished during resize") + return new + + def delete_volume(self, volume_id: str) -> None: + self._call("DELETE", f"/volumes/{quote(volume_id, safe='')}") + + def _host(self, name: str) -> dict[str, Any] | None: + resp = self._call("GET", f"/hosts/{quote(name, safe='')}", missing_ok=True) + return json_of(resp) if self._found(resp) else None + + def ensure_host(self, spec: HostSpec) -> str: + unsupported = [p for p in spec.protocols if not p.is_scsi] + if unsupported: + raise ArrayError(f"{self.display_name} adapter does not support " + + ", ".join(sorted(p.value for p in unsupported))) + iqns = spec.addresses(Protocol.ISCSI) + wwns = [w.upper() for w in spec.addresses(Protocol.FC)] + host = self._host(spec.name) + if host is None: + # Create with one path type; any second type is added below + # (whether WSAPI accepts both in one request is unverified). + body: dict[str, Any] = {"name": spec.name, "persona": int(self.option("persona"))} + if iqns: + body["iSCSINames"] = iqns + else: + body["FCWWNs"] = wwns + self._call("POST", "/hosts", json=body) + if not (iqns and wwns): + return spec.name + host = {"iSCSIPaths": [{"name": i} for i in iqns], "FCPaths": []} + have_iqns = {str(p.get("name", "")).lower() for p in host.get("iSCSIPaths") or []} + have_wwns = {str(p.get("wwn", "")).upper() for p in host.get("FCPaths") or []} + add_iqns = [i for i in iqns if i.lower() not in have_iqns] + add_wwns = [w for w in wwns if w not in have_wwns] + # One path type per request (whether WSAPI accepts both in one + # modify is unverified; separate requests are always valid). + if add_iqns: + self._call("PUT", f"/hosts/{quote(spec.name, safe='')}", + json={"pathOperation": PATH_ADD, "iSCSINames": add_iqns}) + if add_wwns: + self._call("PUT", f"/hosts/{quote(spec.name, safe='')}", + json={"pathOperation": PATH_ADD, "FCWWNs": add_wwns}) + return spec.name + + def delete_host(self, host_id: str) -> None: + self._call("DELETE", f"/hosts/{quote(host_id, safe='')}", missing_ok=True) + + def _vluns(self, volume_id: str, host_id: str | None = None) -> list[Mapping]: + resp = self._call("GET", "/vluns", params={"query": f'"volumeName EQ {volume_id}"'}, + missing_ok=True) + if not self._found(resp): + return [] + seen: dict[tuple[str, str], Mapping] = {} + for m in (json_of(resp) or {}).get("members", []): + host = m.get("hostname") + if not host or m.get("volumeName") != volume_id: + continue + if host_id is not None and host != host_id: + continue + # The template and every active per-path VLUN share (vol, lun, host). + seen.setdefault((volume_id, host), + Mapping(volume_id=volume_id, host_id=host, lun=int(m["lun"]))) + return list(seen.values()) + + def map_volume(self, volume_id: str, host_id: str) -> Mapping: + existing = self._vluns(volume_id, host_id) + if existing: + return existing[0] + resp = self._call("POST", "/vluns", + json={"volumeName": volume_id, "hostname": host_id, "lun": 0, + "autoLun": True, "maxAutoLun": 0}) + m = _LOCATION_RE.search(unquote(resp.headers.get("Location", ""))) + if m: + return Mapping(volume_id=volume_id, host_id=host_id, lun=int(m["lun"])) + existing = self._vluns(volume_id, host_id) + if not existing: + raise ArrayRequestError(f"VLUN {volume_id} -> {host_id} not found after creation") + return existing[0] + + def unmap_volume(self, volume_id: str, host_id: str) -> None: + for m in self._vluns(volume_id, host_id): + self._call("DELETE", "/vluns/" + quote(f"{volume_id},{m.lun},{host_id}", safe=","), + missing_ok=True) + + def list_mappings(self, volume_id: str) -> list[Mapping]: + return self._vluns(volume_id) diff --git a/simplyblock_core/storage_arrays/adapters/huawei_dorado.py b/simplyblock_core/storage_arrays/adapters/huawei_dorado.py new file mode 100644 index 0000000000..9c97615739 --- /dev/null +++ b/simplyblock_core/storage_arrays/adapters/huawei_dorado.py @@ -0,0 +1,426 @@ +"""Huawei OceanStor Dorado (V6 / OceanStor 6.x) DeviceManager REST API. + +Auth: ``POST /deviceManager/rest/xx/sessions`` with ``{username, password, +scope: "0"}`` (scope 0 = local user) returns ``data.deviceid`` and +``data.iBaseToken`` (plus a session cookie, kept by the ``requests`` +session). Every later call goes to ``/deviceManager/rest//...`` +with the ``iBaseToken`` header. Logout is ``DELETE .../sessions``. + +Envelope: answers are HTTP 200 even on failure, with ``{"data": ..., +"error": {"code": , "description": "..."}}``; code 0 is success. A +query that matches nothing omits ``data``. All values are strings. Codes +mapped here (from Huawei's own CSI driver, eSDK_K8S_Plugin): + +* auth: -401 (not logged in / session expired), 1077949069 (user offline), + 1077987870 / 1077949081 / 1077949061 (bad user or password), + 1077949070 / 1077987871 (account locked), 1077949071 (IP locked) +* not found: 1077948996 (object), 1077936859 (LUN), 1077937498 (host), + 1077937500 (host group), 1077951819 (mapping view) +* conflict: 1077948993 (name exists), 1077948997 (id not unique) +* tolerated as "already done": 1077936862 (LUN already in LUN group), + 1077937501 (host already in host group), 1073745412 (host not in host + group), 1073804556 / 1073804560 (host/LUN group already in mapping view), + 1073804552 / 1073804554 (host/LUN group not in mapping view) + +LUNs: ``POST /lun {NAME, PARENTID: , CAPACITY: <512-byte sectors>, +ALLOCTYPE: 1}`` (thin; Dorado LUNs are always thin), ``PUT /lun/expand {ID, +CAPACITY}``, ``DELETE /lun/``. Identity: ``WWN`` -> ``naa.``. +The ``storage_pool`` option is a pool *name*, resolved once per session via +``GET /storagepool?filter=NAME::``. + +Hosts and initiators: ``POST /host {NAME, OPERATIONSYSTEM: 0}`` (Linux). +iSCSI/FC initiators are objects of their own (``/iscsi_initiator/``, +``/fc_initiator/``) with ``ISFREE`` / ``PARENTID``; one is created if +the array does not know it yet, then bound with ``PUT ... {PARENTTYPE: 21, +PARENTID: }``. An initiator whose ``ISFREE`` is ``"false"`` and +``PARENTID`` is another host raises :class:`ArrayConflictError`. Hosts are +addressed by id (``ensure_host`` returns it). + +Mapping: the classic host group + LUN group + mapping view triple, one per +host, as Huawei's CSI driver does: ``sb_hg_`` holds the host, +``sb_lg_`` holds the LUNs mapped to it, ``sb_mv_`` joins them. +Map/unmap add/remove the LUN to/from the host's LUN group; ``delete_host`` +tears the triple down, unbinds the initiators and deletes the host. The +host LUN id comes from ``GET /lun/associate?TYPE=11&ASSOCIATEOBJTYPE=21& +ASSOCIATEOBJID=`` (``HostLUNID`` inside the ``ASSOCIATEMETADATA`` JSON +string). ``list_mappings`` reports only mappings made through ``sb_lg_`` +groups; a LUN in a customer's LUN group is never touched (deleting it then +fails on the array). + +NVMe hosts are not supported by this adapter (iSCSI and FC only). + +Verify against a real system +---------------------------- +* Size granularity: CAPACITY is in 512-byte sectors, but whether Dorado + accepts any sector count is unverified; we round sizes to 1 MiB to be safe. + Whether CAPACITY stays in 512-byte units for 4K-sector LUNs (``SECTORSIZE``). +* Name limits: LUN names and host names assumed <= 31 characters. +* ``filter=NAME::x`` is assumed to be an exact match (results are + re-filtered by exact name anyway); query values are sent URL-encoded. +* Creating an FC initiator object for a WWPN that has never logged in + (``POST /fc_initiator {ID, TYPE: "223"}``). +* Unbinding initiators: ``PUT /iscsi_initiator/remove_iscsi_from_host`` and + ``PUT /fc_initiator/remove_fc_from_host`` with ``{ID, TYPE}`` (from the + OpenStack Cinder Huawei driver), and listing them with ``?PARENTID=``. +* ``DELETE`` requests carry a JSON body (``/lungroup/associate``, + ``/host/associate``) as the CSI driver sends them. +* Error codes for: deleting a LUN that is still in a LUN group, deleting a + host that still has initiators or group membership, binding an initiator + that is bound elsewhere, and a host already in another host group (a host + can belong to one host group only; the adapter checks this itself and + raises :class:`ArrayConflictError`). +* ``GET /system/`` fields used for ``get_info``: ``ID`` (serial), + ``productModeString`` or ``PRODUCTMODE`` (model code), ``pointRelease`` or + ``PRODUCTVERSION``. +* Some firmware may answer an expired session with HTTP 401 instead of the + -401 envelope; both are treated as an auth error. +""" +from __future__ import annotations + +import json +from typing import Any + +from ..base import ( + ArrayAdapter, + ArrayAuthError, + ArrayConflictError, + ArrayError, + ArrayInfo, + ArrayNotFoundError, + ArrayRequestError, + Capabilities, + HostSpec, + Mapping, + OptionDoc, + Protocol, + Volume, +) +from ..http import json_of + +SECTOR = 512 +REST = "/deviceManager/rest" + +AUTH_CODES = frozenset({-401, 1077949069, 1077987870, 1077949081, 1077949061, + 1077949070, 1077987871, 1077949071}) +NOT_FOUND_CODES = frozenset({1077948996, 1077936859, 1077937498, 1077937500, 1077951819}) +CONFLICT_CODES = frozenset({1077948993, 1077948997}) + +LUN_ALREADY_IN_GROUP = 1077936862 +HOST_ALREADY_IN_GROUP = 1077937501 +HOST_NOT_IN_GROUP = 1073745412 +GROUP_ALREADY_IN_VIEW = frozenset({1073804556, 1073804560}) +GROUP_NOT_IN_VIEW = frozenset({1073804552, 1073804554}) + +OBJ_HOST = 21 +OBJ_HOSTGROUP = 14 +OBJ_LUN = 11 +OBJ_LUNGROUP = 256 +OBJ_MAPPINGVIEW = 245 +TYPE_ISCSI_INITIATOR = "222" +TYPE_FC_INITIATOR = "223" + +_LG, _HG, _MV = "sb_lg_", "sb_hg_", "sb_mv_" + + +def huawei_wwn(wwn: str) -> str: + return "naa." + wwn.lower() + + +class HuaweiDoradoAdapter(ArrayAdapter): + vendor = "huawei-dorado" + display_name = "Huawei OceanStor Dorado" + capabilities = Capabilities( + protocols=frozenset({Protocol.ISCSI, Protocol.FC}), + size_granularity_bytes=1 << 20, + min_size_bytes=1 << 20, + max_name_len=31, + ) + credential_fields = (frozenset({"username", "password"}),) + option_docs = ( + OptionDoc("storage_pool", "Name of the storage pool new LUNs are created in.", + required=True), + OptionDoc("scope", "Login scope: '0' local user, '1' LDAP user.", default="0"), + ) + + def __init__(self, ctx): + super().__init__(ctx) + self._base = "" + self._pool_id: str | None = None + + # -- session ----------------------------------------------------------------- + + def login(self) -> None: + self.session.headers.pop("iBaseToken", None) + self._base = "" + resp = self.session.post(f"{REST}/xx/sessions", json={ + "username": self.secret("username"), "password": self.secret("password"), + "scope": str(self.option("scope"))}) + data = self._unwrap("POST", "/xx/sessions", resp) + if not isinstance(data, dict) or not data.get("deviceid") or not data.get("iBaseToken"): + raise ArrayRequestError("OceanStor login returned no deviceid/iBaseToken") + self.session.headers["iBaseToken"] = data["iBaseToken"] + self._base = f"{REST}/{data['deviceid']}" + + def close(self) -> None: + if self._base and "iBaseToken" in self.session.headers: + try: + self.session.delete(f"{self._base}/sessions") + except Exception: + pass + + # -- request helpers ------------------------------------------------------------ + + @staticmethod + def _unwrap(method: str, path: str, resp, tolerate: frozenset[int] = frozenset(), + missing_ok: bool = False) -> Any: + body = json_of(resp) or {} + err = body.get("error") or {} + try: + code = int(err.get("code", 0)) + except (TypeError, ValueError): + code = -1 + if code == 0 or code in tolerate: + return body.get("data") + msg = f"{method} {path}: error {code}: {err.get('description', '')}".rstrip() + if err.get("suggestion"): + msg += f" ({err['suggestion']})" + if code in AUTH_CODES: + raise ArrayAuthError(msg) + if code in NOT_FOUND_CODES: + if missing_ok: + return None + raise ArrayNotFoundError(msg) + if code in CONFLICT_CODES: + raise ArrayConflictError(msg) + raise ArrayRequestError(msg) + + def _call(self, method: str, path: str, *, params: dict[str, Any] | None = None, + body: Any = None, tolerate: frozenset[int] = frozenset(), + missing_ok: bool = False) -> Any: + if not self._base: + raise ArrayAuthError("OceanStor session not established") + resp = self.session.request(method, f"{self._base}{path}", params=params, json=body) + return self._unwrap(method, path, resp, tolerate, missing_ok) + + def _list(self, path: str, params: dict[str, Any] | None = None) -> list[dict[str, Any]]: + data = self._call("GET", path, params=params) + return [d for d in data if isinstance(d, dict)] if isinstance(data, list) else [] + + def _by_name(self, path: str, name: str) -> dict[str, Any] | None: + rows = self._list(path, {"filter": f"NAME::{name}", "range": "[0-100]"}) + return next((r for r in rows if r.get("NAME") == name), None) + + # -- info / pool ------------------------------------------------------------------ + + def get_info(self) -> ArrayInfo: + s = self._call("GET", "/system/") or {} + return ArrayInfo( + vendor=self.vendor, + model=str(s.get("productModeString") or s.get("PRODUCTMODE") or ""), + version=str(s.get("pointRelease") or s.get("PRODUCTVERSION") or ""), + serial=str(s.get("ID", ""))) + + def _pool(self) -> str: + if self._pool_id is None: + name = str(self.option("storage_pool")) + pool = self._by_name("/storagepool", name) + if pool is None: + raise ArrayError(f"OceanStor storage pool {name!r} not found") + self._pool_id = str(pool["ID"]) + return self._pool_id + + # -- LUNs ----------------------------------------------------------------------------- + + @staticmethod + def _volume(lun: dict[str, Any]) -> Volume: + wwn = str(lun.get("WWN") or "") + return Volume(id=str(lun["ID"]), name=lun["NAME"], + size_bytes=int(lun["CAPACITY"]) * SECTOR, + wwn=huawei_wwn(wwn) if wwn else None) + + def create_volume(self, name: str, size_bytes: int) -> Volume: + lun = self._call("POST", "/lun", body={ + "NAME": name, "PARENTID": self._pool(), "CAPACITY": size_bytes // SECTOR, + "ALLOCTYPE": 1, "DESCRIPTION": "simplyblock"}) + return self._volume(lun) + + def get_volume(self, volume_id: str) -> Volume | None: + lun = self._call("GET", f"/lun/{volume_id}", missing_ok=True) + return self._volume(lun) if lun else None + + def find_volume(self, name: str) -> Volume | None: + lun = self._by_name("/lun", name) + return self._volume(lun) if lun else None + + def resize_volume(self, volume_id: str, size_bytes: int) -> Volume: + self._call("PUT", "/lun/expand", body={"ID": volume_id, + "CAPACITY": size_bytes // SECTOR}) + vol = self.get_volume(volume_id) + if vol is None: + raise ArrayNotFoundError(f"LUN {volume_id} does not exist") + return vol + + def delete_volume(self, volume_id: str) -> None: + self._call("DELETE", f"/lun/{volume_id}") + + # -- hosts and initiators --------------------------------------------------------------- + + @staticmethod + def _initiator_kinds(spec: HostSpec) -> list[tuple[str, str, str]]: + """(collection, TYPE, address) for each initiator.""" + out = [("iscsi_initiator", TYPE_ISCSI_INITIATOR, a) + for a in spec.addresses(Protocol.ISCSI)] + out += [("fc_initiator", TYPE_FC_INITIATOR, a) for a in spec.addresses(Protocol.FC)] + return out + + def _initiator(self, collection: str, address: str) -> dict[str, Any] | None: + data = self._call("GET", f"/{collection}/{address}", missing_ok=True) + return data if isinstance(data, dict) and data else None + + def ensure_host(self, spec: HostSpec) -> str: + host = self._by_name("/host", spec.name) + host_id = str(host["ID"]) if host else None + # Check ownership before creating anything. + pending: list[tuple[str, str, str, bool]] = [] # collection, type, address, exists + for collection, itype, address in self._initiator_kinds(spec): + ini = self._initiator(collection, address) + if ini is not None and str(ini.get("ISFREE", "true")).lower() == "false": + parent = str(ini.get("PARENTID") or "") + if parent and parent != host_id: + raise ArrayConflictError( + f"Initiator {address} is registered to another host " + f"({ini.get('PARENTNAME') or parent})") + continue # already ours + pending.append((collection, itype, address, ini is not None)) + if host_id is None: + created = self._call("POST", "/host", body={ + "NAME": spec.name, "TYPE": OBJ_HOST, "OPERATIONSYSTEM": 0, + "DESCRIPTION": "simplyblock"}) + host_id = str(created["ID"]) + for collection, itype, address, exists in pending: + if not exists: + self._call("POST", f"/{collection}", body={"ID": address, "TYPE": itype}, + tolerate=frozenset({1077948997})) + self._call("PUT", f"/{collection}/{address}", + body={"TYPE": itype, "ID": address, + "PARENTTYPE": OBJ_HOST, "PARENTID": host_id}) + return host_id + + def delete_host(self, host_id: str) -> None: + host = self._call("GET", f"/host/{host_id}", missing_ok=True) + if not host: + return + if self._host_luns(host_id): + raise ArrayConflictError(f"Host {host_id} still has LUNs mapped") + view = self._by_name("/mappingview", _MV + host_id) + hg = self._by_name("/hostgroup", _HG + host_id) + lg = self._by_name("/lungroup", _LG + host_id) + if view is not None: + for obj_type, group in ((OBJ_HOSTGROUP, hg), (OBJ_LUNGROUP, lg)): + if group is not None: + self._call("PUT", "/mappingview/remove_associate", body={ + "ID": view["ID"], "ASSOCIATEOBJTYPE": obj_type, + "ASSOCIATEOBJID": group["ID"]}, tolerate=GROUP_NOT_IN_VIEW) + self._call("DELETE", f"/mappingview/{view['ID']}", missing_ok=True) + if hg is not None: + self._call("DELETE", "/host/associate", body={ + "ID": hg["ID"], "ASSOCIATEOBJTYPE": OBJ_HOST, "ASSOCIATEOBJID": host_id}, + tolerate=frozenset({HOST_NOT_IN_GROUP})) + self._call("DELETE", f"/hostgroup/{hg['ID']}", missing_ok=True) + if lg is not None: + self._call("DELETE", f"/lungroup/{lg['ID']}", missing_ok=True) + for collection, itype, action in ( + ("iscsi_initiator", TYPE_ISCSI_INITIATOR, "remove_iscsi_from_host"), + ("fc_initiator", TYPE_FC_INITIATOR, "remove_fc_from_host")): + for ini in self._list(f"/{collection}", {"PARENTID": host_id}): + self._call("PUT", f"/{collection}/{action}", + body={"ID": ini["ID"], "TYPE": itype}) + self._call("DELETE", f"/host/{host_id}", missing_ok=True) + + # -- mapping ------------------------------------------------------------------------------ + + def _host_luns(self, host_id: str) -> dict[str, int | None]: + """LUN id -> host LUN id for every LUN the host sees.""" + rows = self._list("/lun/associate", {"TYPE": OBJ_LUN, "ASSOCIATEOBJTYPE": OBJ_HOST, + "ASSOCIATEOBJID": host_id}) + out: dict[str, int | None] = {} + for r in rows: + lun_no: int | None = None + try: + meta = json.loads(r.get("ASSOCIATEMETADATA") or "{}") + if meta.get("HostLUNID") is not None: + lun_no = int(meta["HostLUNID"]) + except (TypeError, ValueError): + pass + out[str(r["ID"])] = lun_no + return out + + def _ensure_group(self, path: str, name: str, extra: dict[str, Any]) -> str: + found = self._by_name(path, name) + if found is None: + try: + found = self._call("POST", path, body={"NAME": name, **extra}) + except ArrayConflictError: # created concurrently + found = self._by_name(path, name) + if not found: + raise ArrayRequestError(f"Could not create {path[1:]} {name}") + return str(found["ID"]) + + def _ensure_view(self, host_id: str) -> str: + """Create (or complete) the host's group triple; returns the LUN group id.""" + if self._call("GET", f"/host/{host_id}", missing_ok=True) is None: + raise ArrayNotFoundError(f"Host {host_id} does not exist") + lg = self._ensure_group("/lungroup", _LG + host_id, {"APPTYPE": 0}) + hg = self._ensure_group("/hostgroup", _HG + host_id, {}) + groups = self._list("/hostgroup/associate", {"ASSOCIATEOBJTYPE": OBJ_HOST, + "ASSOCIATEOBJID": host_id}) + others = [g for g in groups if str(g.get("ID")) != hg] + if others: + raise ArrayConflictError( + f"Host {host_id} already belongs to host group " + f"{others[0].get('NAME') or others[0].get('ID')}; an OceanStor host can be " + "in one host group only") + if not groups: + self._call("POST", "/hostgroup/associate", body={ + "ID": hg, "ASSOCIATEOBJTYPE": OBJ_HOST, "ASSOCIATEOBJID": host_id}, + tolerate=frozenset({HOST_ALREADY_IN_GROUP})) + mv = self._ensure_group("/mappingview", _MV + host_id, {}) + for obj_type, group in ((OBJ_HOSTGROUP, hg), (OBJ_LUNGROUP, lg)): + self._call("PUT", "/mappingview/create_associate", body={ + "ID": mv, "ASSOCIATEOBJTYPE": obj_type, "ASSOCIATEOBJID": group}, + tolerate=GROUP_ALREADY_IN_VIEW) + return lg + + def map_volume(self, volume_id: str, host_id: str) -> Mapping: + seen = self._host_luns(host_id) + if volume_id in seen: + return Mapping(volume_id=volume_id, host_id=host_id, lun=seen[volume_id]) + lg = self._ensure_view(host_id) + self._call("POST", "/lungroup/associate", body={ + "ID": lg, "ASSOCIATEOBJTYPE": OBJ_LUN, "ASSOCIATEOBJID": volume_id}, + tolerate=frozenset({LUN_ALREADY_IN_GROUP, 1077948997})) + seen = self._host_luns(host_id) + if volume_id not in seen: + raise ArrayError(f"LUN {volume_id} not visible to host {host_id} after mapping") + return Mapping(volume_id=volume_id, host_id=host_id, lun=seen[volume_id]) + + def unmap_volume(self, volume_id: str, host_id: str) -> None: + lg = self._by_name("/lungroup", _LG + host_id) + if lg is None: + return + self._call("DELETE", "/lungroup/associate", body={ + "ID": lg["ID"], "ASSOCIATEOBJTYPE": OBJ_LUN, "ASSOCIATEOBJID": volume_id}, + missing_ok=True) + + def list_mappings(self, volume_id: str) -> list[Mapping]: + groups = self._list("/lungroup/associate", {"ASSOCIATEOBJTYPE": OBJ_LUN, + "ASSOCIATEOBJID": volume_id}) + out = [] + for g in groups: + name = str(g.get("NAME", "")) + if not name.startswith(_LG): + continue + host_id = name[len(_LG):] + out.append(Mapping(volume_id=volume_id, host_id=host_id, + lun=self._host_luns(host_id).get(volume_id))) + return out diff --git a/simplyblock_core/storage_arrays/adapters/ibm_flashsystem.py b/simplyblock_core/storage_arrays/adapters/ibm_flashsystem.py new file mode 100644 index 0000000000..fe18364fb1 --- /dev/null +++ b/simplyblock_core/storage_arrays/adapters/ibm_flashsystem.py @@ -0,0 +1,378 @@ +"""IBM FlashSystem / SAN Volume Controller (IBM Storage Virtualize) REST API. + +The Storage Virtualize REST API (port 7443) is a thin wrapper around the CLI: +every command is ``POST /rest/[/]`` with the command's +flags as a JSON object (``-unit b`` -> ``{"unit": "b"}``, ``-thin`` -> +``{"thin": true}``). Positional arguments go into the path. + +Auth: ``POST /rest/auth`` with headers ``X-Auth-Username`` / +``X-Auth-Password`` returns ``{"token": ...}``; every later call carries +``X-Auth-Token``. Tokens expire after an idle period (one hour by default) +and the array then answers 403, which the client turns into a re-login. + +Errors: a failed command answers HTTP 500 with the CLI's message, e.g. +``CMMVC5753E The specified object does not exist or is not a suitable +candidate.`` The ``CMMVCnnnnE`` code is mapped as follows (anything else is +an :class:`ArrayRequestError`): + +* not found: CMMVC5753E, CMMVC5754E, CMMVC5804E, CMMVC5842E +* conflict: CMMVC6035E (name exists), CMMVC6581E (IQN/NQN already assigned + or invalid), CMMVC5867E (WWPN already assigned or invalid), CMMVC5878E + (volume already mapped to that host), CMMVC6071E (mapped to another host, + needs ``force``), CMMVC5840E (volume still mapped), CMMVC5871E (host + still has mappings) + +Objects: volumes are addressed by their numeric id (``Volume.id``), hosts by +name (``ensure_host`` returns the host name). Note that the array reuses the +lowest free id after a deletion, so a stale volume id can address a +different volume later -- callers pass ``expected_identifier`` (the WWN) to +the client, which then refuses to act on the wrong volume. + +Volumes are created with ``mkvolume`` (``-thin`` unless ``thin`` is False); +the virtual capacity has 512-byte granularity (extents only govern the real +allocation). Resizing grows with ``expandvdisksize`` (a delta). Deletion uses +``rmvolume``. Volume identity: ``vdisk_UID`` (32 hex) -> ``naa.``. + +Initiator ownership: ``mkhost``/``addhostport`` fail with CMMVC6581E / +CMMVC5867E when a port already belongs to another host; the adapter first +reads its own host (``lshost ``, ports in the ``nodes`` list) so ports +it already owns are never re-added, and treats those codes as +:class:`ArrayConflictError`. + +Verify against a real system +---------------------------- +* REST root: ``/rest`` (as used by IBM's Ansible collection). Code level + 8.5+ documents ``/rest/v1``; set the ``rest_root`` option if ``/rest`` is + rejected. +* HTTP status on an expired token (assumed 403, 401 handled the same) and on + bad credentials at ``/rest/auth`` (assumed 403). +* Error body format: plain text with the CMMVC message (JSON bodies are also + parsed). Codes CMMVC5804E, CMMVC5840E (rmvolume of a mapped volume; newer + levels may answer with a different code), CMMVC5871E (rmhost with + mappings) and the NQN-already-assigned code (assumed CMMVC6581E as for + IQNs) are from memory of the CLI reference. +* ``mkhost -protocol`` values for NVMe hosts (``tcpnvme``, ``rdmanvme`` on + 8.6+; older levels only knew ``nvme``) -- set ``nvme_protocol_value`` if + the array rejects them. SCSI hosts are created without ``-protocol``. +* Detail views (``lsvdisk ``, ``lshost ``) may come back as a list + of dicts (object, then copies) or one dict; ``lsvdiskhostmap`` with a + single row may come back as a dict instead of a one-element list. Both + shapes are accepted. +* ``mkvolume -unit b`` with a size that is not a 512-byte multiple (we never + send one). +* ``mkhost -force`` for FC WWPNs that are not logged in (we always pass it). +""" +from __future__ import annotations + +import re +from typing import Any +from urllib.parse import quote + +from ..base import ( + ArrayAdapter, + ArrayConflictError, + ArrayError, + ArrayInfo, + ArrayNotFoundError, + ArrayRequestError, + ArrayUnsupportedError, + Capabilities, + HostSpec, + Mapping, + OptionDoc, + Protocol, + Volume, +) +from ..http import body_text, json_of + +_CODE_RE = re.compile(r"CMMVC\d{4}[EW]") + +NOT_FOUND_CODES = frozenset({"CMMVC5753E", "CMMVC5754E", "CMMVC5804E", "CMMVC5842E"}) +CONFLICT_CODES = frozenset({ + "CMMVC6035E", # object already exists + "CMMVC6581E", # IQN (and, we assume, NQN) already assigned or not valid + "CMMVC5867E", # WWPN already assigned or not valid + "CMMVC5878E", # volume already mapped to this host + "CMMVC6071E", # volume mapped to another host; needs -force + "CMMVC5840E", # volume not deleted: still mapped + "CMMVC5871E", # host has mappings +}) +#: Codes meaning "this port is owned by another host" on mkhost/addhostport. +PORT_TAKEN_CODES = frozenset({"CMMVC6581E", "CMMVC5867E"}) + +_NVME_PROTOCOL = {Protocol.NVME_TCP: "tcpnvme", Protocol.NVME_RDMA: "rdmanvme"} + + +def ibm_wwn(vdisk_uid: str) -> str: + return "naa." + vdisk_uid.lower() + + +def _rows(data: Any) -> list[dict[str, Any]]: + """List views can come back as a bare dict when there is one row.""" + if data is None: + return [] + if isinstance(data, dict): + return [data] + return [d for d in data if isinstance(d, dict)] + + +def _detail(data: Any) -> dict[str, Any]: + """Detail views: a dict, or a list (object first, then e.g. copies).""" + rows = _rows(data) + return rows[0] if rows else {} + + +class IbmFlashSystemAdapter(ArrayAdapter): + vendor = "ibm-flashsystem" + display_name = "IBM FlashSystem / Storage Virtualize" + capabilities = Capabilities( + protocols=frozenset({Protocol.ISCSI, Protocol.FC, Protocol.NVME_TCP, + Protocol.NVME_RDMA}), + size_granularity_bytes=512, + min_size_bytes=1 << 20, + max_name_len=63, + ) + credential_fields = (frozenset({"username", "password"}),) + option_docs = ( + OptionDoc("pool", "Storage pool (mdisk group) name or id for new volumes.", + required=True), + OptionDoc("thin", "Create thin-provisioned volumes (mkvolume -thin). In a " + "data reduction pool this is a DRP thin volume.", default=True), + OptionDoc("io_group", "I/O group (name or id) that owns new volumes; " + "default: chosen by the array."), + OptionDoc("rest_root", "REST path root; '/rest/v1' on code levels that " + "reject '/rest'.", default="/rest"), + OptionDoc("nvme_protocol_value", "Override the mkhost -protocol value used " + "for NVMe hosts (default: tcpnvme / rdmanvme by transport)."), + ) + + def __init__(self, ctx): + super().__init__(ctx) + self._root = "/" + str(self.option("rest_root")).strip("/") + + # -- session -------------------------------------------------------------- + + def login(self) -> None: + self.session.headers.pop("X-Auth-Token", None) + resp = self.session.post(f"{self._root}/auth", headers={ + "X-Auth-Username": self.secret("username"), + "X-Auth-Password": self.secret("password"), + }) + token = (json_of(resp) or {}).get("token") + if not token: + raise ArrayRequestError("Storage Virtualize /auth returned no token") + self.session.headers["X-Auth-Token"] = token + + def close(self) -> None: + # There is no logout command; tokens lapse on their own. + self.session.headers.pop("X-Auth-Token", None) + + # -- request helper --------------------------------------------------------- + + def _cmd(self, command: str, obj: str | None = None, *, missing_ok: bool = False, + **opts: Any) -> Any: + """Run one CLI command. Returns the decoded JSON (``None`` on an empty + body, or when ``missing_ok`` and the object does not exist).""" + path = f"{self._root}/{command}" + if obj is not None: + path += "/" + quote(str(obj), safe="") + resp = self.session.post(path, json=opts, ok=(500,)) + if resp.status_code == 500: + text = body_text(resp) + m = _CODE_RE.search(text) + code = m.group(0) if m else "" + msg = f"{command}{' ' + str(obj) if obj is not None else ''}: {text.strip()}" + if code in NOT_FOUND_CODES: + if missing_ok: + return None + raise ArrayNotFoundError(msg) + if code in CONFLICT_CODES: + raise ArrayConflictError(msg) + raise ArrayRequestError(msg, status=500) + if not resp.content: + return None + try: + return resp.json() + except ValueError as e: + raise ArrayRequestError(f"{command}: expected JSON, got {body_text(resp)}") from e + + # -- volumes ---------------------------------------------------------------- + + @staticmethod + def _volume(row: dict[str, Any]) -> Volume: + uid = str(row.get("vdisk_UID") or "") + return Volume(id=str(row["id"]), name=row["name"], size_bytes=int(row["capacity"]), + wwn=ibm_wwn(uid) if uid else None) + + def get_info(self) -> ArrayInfo: + s = _detail(self._cmd("lssystem")) + return ArrayInfo(vendor=self.vendor, model=str(s.get("product_name", "")), + version=str(s.get("code_level", "")).split(" ")[0], + serial=str(s.get("id", ""))) + + def create_volume(self, name: str, size_bytes: int) -> Volume: + opts: dict[str, Any] = {"name": name, "pool": str(self.option("pool")), + "size": size_bytes, "unit": "b"} + if self.option("thin"): + opts["thin"] = True + if self.option("io_group") not in (None, ""): + opts["iogrp"] = str(self.option("io_group")) + out = self._cmd("mkvolume", **opts) or {} + vid = out.get("id") + vol = self.get_volume(str(vid)) if vid is not None else self.find_volume(name) + if vol is None: + raise ArrayRequestError(f"mkvolume {name} reported success but the volume " + "cannot be read back") + return vol + + def get_volume(self, volume_id: str) -> Volume | None: + row = _detail(self._cmd("lsvdisk", volume_id, missing_ok=True, bytes=True)) + return self._volume(row) if row else None + + def find_volume(self, name: str) -> Volume | None: + rows = _rows(self._cmd("lsvdisk", filtervalue=f"name={name}", bytes=True)) + rows = [r for r in rows if r.get("name") == name] + return self._volume(rows[0]) if rows else None + + def _require(self, volume_id: str) -> Volume: + vol = self.get_volume(volume_id) + if vol is None: + raise ArrayNotFoundError(f"Volume {volume_id} does not exist") + return vol + + def resize_volume(self, volume_id: str, size_bytes: int) -> Volume: + vol = self._require(volume_id) + delta = size_bytes - vol.size_bytes + if delta < 0: + raise ArrayConflictError( + f"Refusing to shrink volume {vol.name} ({vol.size_bytes} -> {size_bytes})") + if delta: + self._cmd("expandvdisksize", vol.id, size=delta, unit="b") + return self._require(vol.id) + + def delete_volume(self, volume_id: str) -> None: + self._cmd("rmvolume", volume_id) + + # -- hosts ------------------------------------------------------------------- + + def _host(self, name: str) -> dict[str, Any] | None: + data = self._cmd("lshost", name, missing_ok=True) + if data is None: + return None + merged: dict[str, Any] = {} + nodes: list[dict[str, Any]] = [] + for row in _rows(data): + nodes.extend(n for n in row.get("nodes", []) if isinstance(n, dict)) + merged.update({k: v for k, v in row.items() if k != "nodes"}) + merged["nodes"] = nodes + return merged + + @staticmethod + def _ports(host: dict[str, Any]) -> dict[str, set[str]]: + ports: dict[str, set[str]] = {"iscsiname": set(), "fcwwpn": set(), "nqn": set()} + for n in host.get("nodes", []): + if n.get("WWPN"): + ports["fcwwpn"].add(str(n["WWPN"]).lower()) + if n.get("iscsi_name"): + ports["iscsiname"].add(str(n["iscsi_name"]).lower()) + if n.get("nqn"): + ports["nqn"].add(str(n["nqn"])) + return ports + + def _nvme_protocol(self, spec: HostSpec) -> str | None: + nvme = {p for p in spec.protocols if p.is_nvme} + if not nvme: + return None + if len(nvme) > 1: + raise ArrayUnsupportedError( + "A Storage Virtualize NVMe host has one transport; register " + f"{', '.join(sorted(p.value for p in nvme))} initiators as separate hosts") + override = self.option("nvme_protocol_value") + return str(override) if override else _NVME_PROTOCOL[next(iter(nvme))] + + def ensure_host(self, spec: HostSpec) -> str: + wanted = { + "iscsiname": spec.addresses(Protocol.ISCSI), + "fcwwpn": [a.upper() for a in spec.addresses(Protocol.FC)], + "nqn": spec.addresses(Protocol.NVME_TCP, Protocol.NVME_RDMA), + } + protocol = self._nvme_protocol(spec) + host = self._host(spec.name) + try: + if host is None: + opts: dict[str, Any] = {"name": spec.name} + if wanted["iscsiname"]: + opts["iscsiname"] = ",".join(wanted["iscsiname"]) + if wanted["fcwwpn"]: + opts["fcwwpn"] = ":".join(wanted["fcwwpn"]) + opts["force"] = True + if wanted["nqn"]: + opts["nqn"] = ",".join(wanted["nqn"]) + if protocol: + opts["protocol"] = protocol + self._cmd("mkhost", **opts) + return spec.name + have = self._ports(host) + for key, values in wanted.items(): + missing = [v for v in values if v.lower() not in have[key] + and v not in have[key]] + if not missing: + continue + sep = ":" if key == "fcwwpn" else "," + opts = {key: sep.join(missing)} + if key == "fcwwpn": + opts["force"] = True + self._cmd("addhostport", spec.name, **opts) + except ArrayConflictError as e: + code = _CODE_RE.search(str(e)) + if code and code.group(0) in PORT_TAKEN_CODES: + raise ArrayConflictError( + f"An initiator of host {spec.name} is registered to another host " + f"(or is invalid): {e}") from e + raise + return spec.name + + def delete_host(self, host_id: str) -> None: + try: + self._cmd("rmhost", host_id) + except ArrayNotFoundError: + pass + + # -- mappings ------------------------------------------------------------------- + + def _maps(self, volume_id: str) -> list[dict[str, Any]]: + data = self._cmd("lsvdiskhostmap", volume_id, missing_ok=True) + if data is None: + raise ArrayNotFoundError(f"Volume {volume_id} does not exist") + return _rows(data) + + @staticmethod + def _mapping(volume_id: str, row: dict[str, Any]) -> Mapping: + scsi = str(row.get("SCSI_id") or "") + return Mapping(volume_id=volume_id, host_id=str(row["host_name"]), + lun=int(scsi) if scsi.isdigit() else None) + + def list_mappings(self, volume_id: str) -> list[Mapping]: + return [self._mapping(volume_id, r) for r in self._maps(volume_id) + if r.get("host_name")] + + def map_volume(self, volume_id: str, host_id: str) -> Mapping: + for m in self.list_mappings(volume_id): + if m.host_id == host_id: + return m + try: + # force: allow the volume to be mapped to more than one host. + self._cmd("mkvdiskhostmap", volume_id, host=host_id, force=True) + except ArrayConflictError as e: + if "CMMVC5878E" not in str(e): # raced with another mapper: fine + raise + for m in self.list_mappings(volume_id): + if m.host_id == host_id: + return m + raise ArrayError(f"Mapping of volume {volume_id} to host {host_id} not found " + "after mkvdiskhostmap") + + def unmap_volume(self, volume_id: str, host_id: str) -> None: + if not any(m.host_id == host_id for m in self.list_mappings(volume_id)): + return + self._cmd("rmvdiskhostmap", volume_id, missing_ok=True, host=host_id) diff --git a/simplyblock_core/storage_arrays/adapters/infinidat.py b/simplyblock_core/storage_arrays/adapters/infinidat.py new file mode 100644 index 0000000000..b87c427806 --- /dev/null +++ b/simplyblock_core/storage_arrays/adapters/infinidat.py @@ -0,0 +1,290 @@ +"""Infinidat InfiniBox, REST API ``/api/rest`` (InfiniBox 7.x). + +Auth: HTTP basic on every request (``username`` / ``password`` credential). +The array also sets a session cookie, which ``requests`` keeps; basic auth +is still sent, so an expired cookie never matters and a rotated password +surfaces as a 401 (``ArrayClient`` then re-resolves the credential). + +Every response is an envelope ``{"result": ..., "error": ..., "metadata": +{...}}``; errors carry ``error.code`` (e.g. ``VOLUME_NOT_FOUND``) and +``error.message``. Lists are paged (``page``, ``page_size`` up to 1000; +``metadata.pages_total``) and filtered with ``field=eq:value``. + +Destructive requests (delete volume/host, unmap, shrink) need +``?approved=true``; without it the array answers **403** +``APPROVAL_REQUIRED``, which must not be mistaken for an auth failure, so +the adapter always sends the flag and maps that code to +:class:`ArrayRequestError`. + +Objects have integer ids, returned here as strings. Volumes are created in +the pool named by the ``pool`` option (resolved to its id once per session), +thin by default. Sizes are bytes; see granularity below. + +Volume identity: ``serial`` is the SCSI NAA-6 identifier without the +leading ``6`` (``742b0f...``, 31 hex digits, IEEE company id 0x742B0F); +``wwn = "naa.6" + serial``. A 32-digit serial already starting with ``6`` is +used as-is. + +Hosts: ``POST /hosts {name}`` then one ``POST /hosts/{id}/ports +{type, address}`` per initiator (``ISCSI`` IQN; ``FC`` WWPN as 16 lowercase +hex digits). A port owned by another host is refused by the array; when that +happens on a host ``ensure_host`` just created, the empty host is deleted +again. Mappings: ``POST /hosts/{id}/luns {volume_id}`` -> ``{lun, ...}``; +``GET /volumes/{id}/luns`` lists them; ``DELETE +/hosts/{id}/luns/volume_id/{vid}?approved=true`` unmaps. Mappings made +through a host *cluster* (``clustered: true``) are not listed by this adapter +(it never creates them), so ``delete_volume`` on such a volume fails. + +Higher-fidelity testing: Infinidat publishes ``infinisim`` (a Python +InfiniBox simulator serving this REST API) and ``infinisdk`` (the official +SDK). Running the contract suite's live tier against infinisim would check +this adapter's API reading; neither is a dependency here. + +Verify against a real system: + +* Size granularity/minimum: the adapter rounds to 1 MiB (minimum 1 MiB) + because InfiniBox may round byte sizes up to its own allocation unit; if + the array rounds to a coarser unit, raise ``size_granularity_bytes`` (a + silent round-up would make later resizes look like shrinks). +* ``serial`` format (with or without the leading ``6``). +* Error codes and statuses: ``VOLUME_NOT_FOUND``/``HOST_NOT_FOUND``/ + ``POOL_NOT_FOUND`` (404?), name conflict (409 ``*_NAME_CONFLICT``?), + port owned by another host (409 ``PORT_ALREADY_BELONGS_TO_HOST``?), + volume still mapped on delete, ``APPROVAL_REQUIRED`` on unmap/delete. +* FC port address format accepted/returned (colons or not) -- both are + normalised on read. +* That LUN numbers start at 1 and ``GET /volumes/{id}/luns`` includes + ``host_id``. +* ``GET /system`` field names ``serial_number``, ``model_name``, ``version``. +* NVMe/TCP (``NVMEOF`` port type?) is not implemented. +* Name limit (adapter declares 63 characters). +""" +from __future__ import annotations + +from typing import Any + +from ..base import ( + ArrayAdapter, + ArrayAuthError, + ArrayConflictError, + ArrayError, + ArrayInfo, + ArrayNotFoundError, + ArrayRequestError, + Capabilities, + HostSpec, + Mapping, + OptionDoc, + Protocol, + Volume, + normalize_wwpn, +) +from ..http import body_text + +_API = "/api/rest" +_PAGE_SIZE = 1000 +_APPROVED = {"approved": "true"} + + +def infinibox_wwn(serial: str) -> str: + s = serial.strip().lower() + if len(s) == 32 and s.startswith("6"): + return "naa." + s + return "naa.6" + s + + +def _port_key(ptype: str, address: str) -> tuple[str, str]: + ptype = ptype.upper() + if ptype == "FC": + try: + return ptype, normalize_wwpn(address) + except ValueError: + pass + return ptype, address.strip().lower() + + +class InfinidatAdapter(ArrayAdapter): + vendor = "infinidat-infinibox" + display_name = "Infinidat InfiniBox" + capabilities = Capabilities( + protocols=frozenset({Protocol.ISCSI, Protocol.FC}), + size_granularity_bytes=1 << 20, + min_size_bytes=1 << 20, + max_name_len=63, + ) + option_docs = ( + OptionDoc("pool", "Name of the pool new volumes are created in.", required=True), + OptionDoc("provtype", "Provisioning type of new volumes: THIN or THICK.", + default="THIN"), + ) + + def __init__(self, ctx): + super().__init__(ctx) + if str(self.option("provtype")).upper() not in ("THIN", "THICK"): + raise ArrayError("InfiniBox option provtype must be THIN or THICK") + self._pool_id: int | None = None + + # -- session ------------------------------------------------------------ + + def login(self) -> None: + self.session.http.cookies.clear() + self.session.set_basic_auth(self.secret("username"), self.secret("password")) + self._pool_id = None + + # -- request helpers ----------------------------------------------------- + + def _send(self, method: str, path: str, *, params: dict[str, Any] | None = None, + json: Any = None, missing_ok: bool = False) -> dict[str, Any] | None: + """Return the response envelope, or ``None`` for a missing object when + ``missing_ok``; map envelope errors to :class:`ArrayError` types.""" + resp = self.session.request(method, _API + path, params=params, json=json, + ok=(400, 403, 404, 409, 500)) + try: + body = resp.json() if resp.content else None + except ValueError: + body = None + env: dict[str, Any] = body if isinstance(body, dict) else {} + err = env.get("error") + status = resp.status_code + if status < 300 and not err: + return env + err = err if isinstance(err, dict) else {} + code = str(err.get("code") or "") + msg = str(err.get("message") or "") or body_text(resp) + text = f"{method} {path} -> HTTP {status}: {code} {msg}".strip() + if status == 403 and code == "APPROVAL_REQUIRED": + raise ArrayRequestError(text, status=status) + if status == 403: + raise ArrayAuthError(text) + if status == 404 or code.endswith("NOT_FOUND"): + if missing_ok: + return None + raise ArrayNotFoundError(text) + if status == 409 or "CONFLICT" in code or "ALREADY" in code: + raise ArrayConflictError(text) + raise ArrayRequestError(text, status=status) + + def _call(self, method: str, path: str, *, params: dict[str, Any] | None = None, + json: Any = None, missing_ok: bool = False) -> Any: + env = self._send(method, path, params=params, json=json, missing_ok=missing_ok) + return None if env is None else env.get("result") + + def _list(self, path: str, **filters: str) -> list[dict[str, Any]]: + out: list[dict[str, Any]] = [] + page = 1 + while True: + params: dict[str, Any] = {k: f"eq:{v}" for k, v in filters.items()} + params.update(page=page, page_size=_PAGE_SIZE) + env = self._send("GET", path, params=params) or {} + out.extend(env.get("result") or []) + pages = int((env.get("metadata") or {}).get("pages_total") or 1) + if page >= pages: + return out + page += 1 + + @staticmethod + def _volume(v: dict[str, Any]) -> Volume: + serial = str(v.get("serial") or "") + return Volume(id=str(v["id"]), name=v["name"], size_bytes=int(v["size"]), + wwn=infinibox_wwn(serial) if serial else None) + + @staticmethod + def _int_id(object_id: str) -> int | None: + try: + return int(object_id) + except (TypeError, ValueError): + return None + + def _pool(self) -> int: + if self._pool_id is None: + name = self.option("pool") + pools = self._list("/pools", name=name) + if not pools: + raise ArrayNotFoundError(f"InfiniBox pool {name!r} not found") + self._pool_id = int(pools[0]["id"]) + return self._pool_id + + # -- contract ------------------------------------------------------------- + + def get_info(self) -> ArrayInfo: + system = self._call("GET", "/system") or {} + return ArrayInfo(vendor=self.vendor, model=str(system.get("model_name") or "InfiniBox"), + version=str(system.get("version") or ""), + serial=str(system.get("serial_number") or "")) + + def create_volume(self, name: str, size_bytes: int) -> Volume: + result = self._call("POST", "/volumes", json={ + "name": name, "size": size_bytes, "pool_id": self._pool(), + "provtype": str(self.option("provtype")).upper()}) + return self._volume(result) + + def get_volume(self, volume_id: str) -> Volume | None: + if self._int_id(volume_id) is None: + return None + result = self._call("GET", f"/volumes/{volume_id}", missing_ok=True) + return self._volume(result) if result else None + + def find_volume(self, name: str) -> Volume | None: + items = self._list("/volumes", name=name) + return self._volume(items[0]) if items else None + + def resize_volume(self, volume_id: str, size_bytes: int) -> Volume: + result = self._call("PUT", f"/volumes/{volume_id}", json={"size": size_bytes}) + return self._volume(result) + + def delete_volume(self, volume_id: str) -> None: + self._call("DELETE", f"/volumes/{volume_id}", params=_APPROVED) + + # -- hosts ---------------------------------------------------------------- + + def ensure_host(self, spec: HostSpec) -> str: + wanted = ([("ISCSI", a) for a in spec.addresses(Protocol.ISCSI)] + + [("FC", a) for a in spec.addresses(Protocol.FC)]) + hosts = self._list("/hosts", name=spec.name) + created = not hosts + host = hosts[0] if hosts else self._call("POST", "/hosts", json={"name": spec.name}) + host_id = int(host["id"]) + have = {_port_key(str(p.get("type", "")), str(p.get("address", ""))) + for p in host.get("ports") or []} + try: + for ptype, address in wanted: + if _port_key(ptype, address) in have: + continue + self._call("POST", f"/hosts/{host_id}/ports", + json={"type": ptype, "address": address}) + except ArrayError: + if created: + try: + self._call("DELETE", f"/hosts/{host_id}", params=_APPROVED, + missing_ok=True) + except ArrayError: + pass + raise + return str(host_id) + + def delete_host(self, host_id: str) -> None: + if self._int_id(host_id) is None: + return + self._call("DELETE", f"/hosts/{host_id}", params=_APPROVED, missing_ok=True) + + # -- mappings --------------------------------------------------------------- + + def list_mappings(self, volume_id: str) -> list[Mapping]: + luns = self._call("GET", f"/volumes/{volume_id}/luns") or [] + return [Mapping(volume_id=str(volume_id), host_id=str(m["host_id"]), lun=int(m["lun"])) + for m in luns if m.get("host_id") and not m.get("clustered")] + + def map_volume(self, volume_id: str, host_id: str) -> Mapping: + for m in self.list_mappings(volume_id): + if m.host_id == host_id: + return m + result = self._call("POST", f"/hosts/{host_id}/luns", + json={"volume_id": self._int_id(volume_id)}) + return Mapping(volume_id=str(volume_id), host_id=str(host_id), lun=int(result["lun"])) + + def unmap_volume(self, volume_id: str, host_id: str) -> None: + luns = self._call("GET", f"/volumes/{volume_id}/luns", missing_ok=True) or [] + if not any(str(m.get("host_id")) == str(host_id) for m in luns): + return + self._call("DELETE", f"/hosts/{host_id}/luns/volume_id/{volume_id}", + params=_APPROVED, missing_ok=True) diff --git a/simplyblock_core/storage_arrays/adapters/netapp_ontap.py b/simplyblock_core/storage_arrays/adapters/netapp_ontap.py new file mode 100644 index 0000000000..6f9587f867 --- /dev/null +++ b/simplyblock_core/storage_arrays/adapters/netapp_ontap.py @@ -0,0 +1,799 @@ +"""NetApp ONTAP 9.x REST API (AFF/FAS/ASA; also Lenovo ThinkSystem DM). + +Auth: HTTP basic (``username``/``password``) on every request; there is no +session to establish. ``login`` checks that the configured SVM exists. + +Layout (``volume_per_lun``, the default): every simplyblock volume is its +own FlexVol ``sb_`` (FlexVol names cannot contain ``-``) holding one +LUN or NVMe namespace ``sb-``. The FlexVol is thin (``guarantee none``), +has no snapshot reserve and no snapshot policy, and is sized +``flexvol_headroom_percent`` above the LUN so a fully written thin LUN does +not run its volume out of space. With ``volume_per_lun: false`` LUNs are +placed in one existing FlexVol (``flexvol``) that the operator sizes. + +Protocol family. ``create_volume`` has no protocol argument, so the option +``protocol_family`` (``scsi`` default, or ``nvme``) decides whether new +volumes are LUNs (``/api/storage/luns``) or namespaces +(``/api/storage/namespaces``). Existing volumes of either kind are always +found, mapped and deleted correctly. ``capabilities.protocols`` is a class +attribute, so it lists every protocol ONTAP serves; mapping a LUN to an NVMe +host (or a namespace to a SCSI host) raises :class:`ArrayUnsupportedError`. + +SCSI hosts are igroups (``protocol mixed``, ``os_type linux``); the host id +is the igroup name; volumes are mapped with ``lun-maps`` and the mapping's +``lun`` is the ``logical_unit_number``. Volume identity: ``naa.600a0980`` + +hex of the 12-character ASCII LUN serial number. + +NVMe hosts. ONTAP maps a namespace to exactly one subsystem, so a subsystem +cannot stand for a host if a volume is to be attached to several hosts. +Instead: + +* ``ensure_host`` creates a *host subsystem* named after the host holding + the host NQNs (and nothing else). The host id is its name. +* ``map_volume`` maps the namespace to its own *volume subsystem* + (``sb_``, comment :data:`VOLUME_SUBSYSTEM_COMMENT`, created on first + map) and adds the host's NQNs to it; ``unmap_volume`` removes them. +* The mapping's ``lun`` is the namespace's NSID in the volume subsystem. + +Volume subsystems are recognised by their comment and never count as hosts. +Namespaces carry no serial-derived identity in the REST API, so their +:attr:`Volume.identifier` is ``id.`` (the same UUID the host +sees as ``/dev/disk/by-id/nvme-uuid.``); ``nguid`` is left empty. + +ONTAP lets an initiator / host NQN sit in several igroups / subsystems. The +contract does not: before adding one, the adapter looks it up and raises +:class:`ArrayConflictError` if another host (igroup or host subsystem) has it. + +Asynchronous calls (FlexVol create/resize/delete) answer ``202`` with a job +link; the adapter polls ``/api/cluster/jobs/{uuid}`` until ``success`` or +``failure``, at most ``job_timeout_s`` seconds. + +Verify against a real system +---------------------------- +* FlexVol ``DELETE`` of an online volume without a junction path succeeds + without first taking it offline (the adapter does not offline it). +* A thin LUN/namespace may not be larger than its FlexVol (the fake + enforces this; it is why resize grows the FlexVol first). +* ``aggregates`` omitted on FlexVol ``POST`` lets ONTAP place the volume + (9.8+); with several ``aggregates`` configured the adapter picks the one + with the most ``space.block_storage.available`` (needs read access to + ``/api/storage/aggregates``, which SVM-scoped accounts may lack). +* Name/duplicate errors: HTTP 409 vs 400, and the numeric ONTAP error codes + (the adapter classifies by status and message text, not by code). +* FlexVol duplicate name surfaces as a failed job rather than a synchronous + error. +* ``PATCH`` of an igroup's ``protocol`` to ``mixed`` (only needed for igroups + not created by this adapter). +* ``nsid`` in subsystem-maps is a hex string such as ``"00000001h"``; the + subsystem-map ``DELETE`` path is + ``/subsystem-maps/{subsystem.uuid}/{namespace.uuid}``. +* ``allow_delete_with_hosts`` on subsystem ``DELETE``. +* Namespace resize via ``PATCH space.size`` (grow only). +* Whether query values match case-insensitively (WWPNs are always written in + lowercase colon form, IQNs in lowercase). +* ASA r2 systems (ONTAP 9.16+ "ASA r2") hide FlexVols; this adapter targets + the classic unified/ASA personality. +* NVMe/FC hosts are identified by NQN, not WWPN (see :meth:`_nqn`). +""" +from __future__ import annotations + +from collections.abc import Callable +from typing import Any +from urllib.parse import quote + +import requests + +from ..base import ( + ArrayAdapter, + ArrayConflictError, + ArrayError, + ArrayInfo, + ArrayNotFoundError, + ArrayRequestError, + ArrayUnsupportedError, + Capabilities, + HostSpec, + Initiator, + Mapping, + OptionDoc, + Protocol, + Volume, + colon_wwpn, +) +from ..http import json_of + +NETAPP_NAA_PREFIX = "naa.600a0980" +VOLUME_SUBSYSTEM_COMMENT = "simplyblock volume subsystem" +FLEXVOL_COMMENT = "simplyblock" +MIN_FLEXVOL_BYTES = 20 << 20 +_FAMILIES = ("scsi", "nvme") +_GUARANTEES = ("none", "volume") +_LUN = "lun" +_NS = "namespace" + +_LUN_FIELDS = "uuid,name,serial_number,space.size,location.logical_unit,location.volume,svm" +_NS_FIELDS = "uuid,name,space.size,location.namespace,location.volume,svm" + + +def ontap_wwn(serial: str) -> str: + """``naa.600a0980`` + hex of the 12-character ASCII LUN serial.""" + return NETAPP_NAA_PREFIX + serial.encode("ascii").hex() + + +def flexvol_name(name: str) -> str: + """FlexVol names allow letters, digits and ``_`` only.""" + return name.replace("-", "_") + + +def parse_nsid(value: Any) -> int | None: + """``"00000001h"`` (ONTAP's NSID format) or an int -> ``1``.""" + if value is None: + return None + if isinstance(value, int): + return value + text = str(value).strip().lower().removesuffix("h") + try: + return int(text, 16) + except ValueError: + return None + + +def _as_bool(value: Any) -> bool: + if isinstance(value, str): + return value.strip().lower() in ("1", "true", "yes", "on") + return bool(value) + + +class NetAppOntapAdapter(ArrayAdapter): + vendor = "netapp-ontap" + display_name = "NetApp ONTAP" + capabilities = Capabilities( + protocols=frozenset({Protocol.ISCSI, Protocol.FC, Protocol.NVME_TCP, Protocol.NVME_FC}), + size_granularity_bytes=4096, + min_size_bytes=1 << 20, + max_name_len=96, + ) + credential_fields = (frozenset({"username", "password"}),) + option_docs = ( + OptionDoc("svm", "Storage VM (vserver) that owns the volumes, igroups and " + "subsystems.", required=True), + OptionDoc("protocol_family", "'scsi' (LUNs, for iSCSI/FC hosts) or 'nvme' " + "(namespaces, for NVMe/TCP and NVMe/FC hosts): what new volumes " + "are created as.", default="scsi"), + OptionDoc("aggregates", "Aggregate name(s) for new FlexVols (list or comma " + "separated); with several, the one with most free space is used. " + "Default: ONTAP chooses."), + OptionDoc("volume_per_lun", "Create one FlexVol per LUN/namespace.", default=True), + OptionDoc("flexvol", "Existing FlexVol for all LUNs/namespaces; required when " + "volume_per_lun is false."), + OptionDoc("space_guarantee", "FlexVol space guarantee: 'none' (thin) or " + "'volume'.", default="none"), + OptionDoc("snapshot_reserve_percent", "FlexVol snapshot reserve (0-90).", default=0), + OptionDoc("snapshot_policy", "FlexVol snapshot policy.", default="none"), + OptionDoc("flexvol_headroom_percent", "FlexVol size above the LUN/namespace size, " + "for metadata.", default=5), + OptionDoc("os_type", "os_type of LUNs, namespaces, igroups and subsystems.", + default="linux"), + OptionDoc("namespace_block_size", "NVMe namespace block size (512 or 4096).", + default=4096), + OptionDoc("job_timeout_s", "How long to wait for an asynchronous ONTAP job.", + default=300), + ) + + def __init__(self, ctx): + super().__init__(ctx) + self._sleep: Callable[[float], None] = self.session.sleep + self.svm = str(self.option("svm")).strip() + if not self.svm: + raise ArrayError("NetApp ONTAP option svm must not be empty") + self.family = str(self.option("protocol_family")).strip().lower() + if self.family not in _FAMILIES: + raise ArrayError(f"NetApp ONTAP protocol_family must be one of {_FAMILIES}, " + f"got {self.family!r}") + self.volume_per_lun = _as_bool(self.option("volume_per_lun")) + self.shared_flexvol = self.option("flexvol") + if not self.volume_per_lun and not self.shared_flexvol: + raise ArrayError("NetApp ONTAP option flexvol is required when volume_per_lun " + "is false") + aggr = self.option("aggregates") or [] + if isinstance(aggr, str): + aggr = [a for a in (x.strip() for x in aggr.split(",")) if a] + self.aggregates: list[str] = [str(a) for a in aggr] + self.guarantee = str(self.option("space_guarantee")) + if self.guarantee not in _GUARANTEES: + raise ArrayError(f"NetApp ONTAP space_guarantee must be one of {_GUARANTEES}") + self.snapshot_reserve = self._int_option("snapshot_reserve_percent", 0, 90) + self.headroom = self._int_option("flexvol_headroom_percent", 0, 100) + self.block_size = self._int_option("namespace_block_size", 512, 4096) + if self.block_size not in (512, 4096): + raise ArrayError("NetApp ONTAP namespace_block_size must be 512 or 4096") + self.job_timeout_s = float(self._int_option("job_timeout_s", 1, 86400)) + self.os_type = str(self.option("os_type")) + + def _int_option(self, name: str, lo: int, hi: int) -> int: + raw = self.option(name) + try: + value = int(raw) + except (TypeError, ValueError): + raise ArrayError(f"NetApp ONTAP option {name} must be an integer") from None + if not lo <= value <= hi: + raise ArrayError(f"NetApp ONTAP option {name} must be in {lo}..{hi}") + return value + + # -- session ------------------------------------------------------------ + + def login(self) -> None: + self.session.set_basic_auth(self.secret("username"), self.secret("password")) + if not self._records("/api/svm/svms", {"name": self.svm, "fields": "uuid,name"}): + raise ArrayNotFoundError(f"SVM {self.svm!r} not found on array {self.config.id}") + + def close(self) -> None: + self.session.clear_auth() + + # -- request helpers ----------------------------------------------------- + + def _call(self, method: str, path: str, *, params: dict[str, Any] | None = None, + json: Any = None) -> requests.Response: + """One request; ONTAP 400 errors are classified by message.""" + resp = self.session.request(method, path, params=params, json=json, ok=(400,)) + if resp.status_code == 400: + raise self._error(method, path, json_of(resp) or {}) + return resp + + @staticmethod + def _error(method: str, path: str, body: dict[str, Any]) -> ArrayError: + err = body.get("error") or {} + message = str(err.get("message", "")) or "request failed" + code = err.get("code", "") + text = f"{method} {path}: {message} (ONTAP error {code})" + lowered = message.lower() + if "doesn't exist" in lowered or "does not exist" in lowered or "not found" in lowered: + return ArrayNotFoundError(text) + if any(w in lowered for w in ("already", "duplicate", "in use", "is mapped")): + return ArrayConflictError(text) + return ArrayRequestError(text, status=400) + + def _records(self, path: str, params: dict[str, Any]) -> list[dict[str, Any]]: + """GET a collection, following ``_links.next``.""" + out: list[dict[str, Any]] = [] + next_path: str | None = path + query: dict[str, Any] | None = params + while next_path: + body = json_of(self._call("GET", next_path, params=query)) or {} + out.extend(body.get("records", [])) + next_path = ((body.get("_links") or {}).get("next") or {}).get("href") + query = None + return out + + def _one(self, path: str, params: dict[str, Any]) -> dict[str, Any] | None: + records = self._records(path, params) + return records[0] if records else None + + def _async(self, method: str, path: str, *, params: dict[str, Any] | None = None, + json: Any = None) -> dict[str, Any]: + """Issue a request that may answer 202 + job, and wait for the job.""" + resp = self._call(method, path, params=params, json=json) + body = json_of(resp) or {} + job = body.get("job") + if job: + self._wait_job(job, f"{method} {path}") + return body + + def _wait_job(self, job: dict[str, Any], what: str) -> None: + href = ((job.get("_links") or {}).get("self") or {}).get("href") \ + or f"/api/cluster/jobs/{job['uuid']}" + waited = 0.0 + interval = 0.5 + while True: + state = json_of(self._call("GET", href, + params={"fields": "uuid,state,message,code"})) or {} + status = state.get("state") + if status == "success": + return + if status == "failure": + raise self._error_from_job(what, state) + if waited >= self.job_timeout_s: + raise ArrayRequestError( + f"{what}: ONTAP job {job.get('uuid')} still {status} after " + f"{self.job_timeout_s:.0f}s") + self._sleep(interval) + waited += interval + interval = min(interval * 2, 5.0) + + def _error_from_job(self, what: str, state: dict[str, Any]) -> ArrayError: + method, _, path = what.partition(" ") + message = f"{state.get('message') or 'job failed'} [job {state.get('uuid', '')}]" + return self._error(method, path, {"error": {"message": message, + "code": state.get("code", "")}}) + + @staticmethod + def _created(resp_body: dict[str, Any]) -> dict[str, Any] | None: + records = resp_body.get("records") or [] + return records[0] if records else None + + def _svm_ref(self) -> dict[str, str]: + return {"name": self.svm} + + # -- volumes: lookup ----------------------------------------------------- + + def _volume_from_lun(self, rec: dict[str, Any]) -> Volume: + serial = rec.get("serial_number") or "" + loc = rec.get("location") or {} + name = loc.get("logical_unit") or str(rec.get("name", "")).rsplit("/", 1)[-1] + return Volume(id=rec["uuid"], name=name, size_bytes=int(rec["space"]["size"]), + wwn=ontap_wwn(serial) if serial else None) + + @staticmethod + def _volume_from_ns(rec: dict[str, Any]) -> Volume: + loc = rec.get("location") or {} + name = loc.get("namespace") or str(rec.get("name", "")).rsplit("/", 1)[-1] + return Volume(id=rec["uuid"], name=name, size_bytes=int(rec["space"]["size"])) + + def _kinds(self) -> tuple[str, str]: + return (_LUN, _NS) if self.family == "scsi" else (_NS, _LUN) + + def _lookup(self, kind: str, params: dict[str, Any]) -> dict[str, Any] | None: + if kind == _LUN: + return self._one("/api/storage/luns", {**params, "svm.name": self.svm, + "fields": _LUN_FIELDS}) + return self._one("/api/storage/namespaces", {**params, "svm.name": self.svm, + "fields": _NS_FIELDS}) + + def _locate(self, volume_id: str) -> tuple[str, dict[str, Any]] | None: + for kind in self._kinds(): + rec = self._lookup(kind, {"uuid": volume_id}) + if rec is not None: + return kind, rec + return None + + def _require(self, volume_id: str) -> tuple[str, dict[str, Any]]: + found = self._locate(volume_id) + if found is None: + raise ArrayNotFoundError( + f"Volume {volume_id} not found in SVM {self.svm} on array {self.config.id}") + return found + + def _to_volume(self, kind: str, rec: dict[str, Any]) -> Volume: + return self._volume_from_lun(rec) if kind == _LUN else self._volume_from_ns(rec) + + def _flexvol_for(self, name: str) -> str: + return flexvol_name(name) if self.volume_per_lun else str(self.shared_flexvol) + + # -- contract ------------------------------------------------------------- + + def get_info(self) -> ArrayInfo: + cluster = json_of(self._call("GET", "/api/cluster", + params={"fields": "name,uuid,version"})) or {} + model = "" + try: + nodes = self._records("/api/cluster/nodes", {"fields": "name,model,serial_number"}) + model = next((n["model"] for n in nodes if n.get("model")), "") + except (ArrayRequestError, ArrayNotFoundError): + pass + version = (cluster.get("version") or {}).get("full", "") + return ArrayInfo(vendor=self.vendor, model=model, version=version, + serial=cluster.get("uuid", "")) + + def get_volume(self, volume_id: str) -> Volume | None: + found = self._locate(volume_id) + return self._to_volume(*found) if found else None + + def find_volume(self, name: str) -> Volume | None: + path = f"/vol/{self._flexvol_for(name)}/{name}" + for kind in self._kinds(): + rec = self._lookup(kind, {"name": path}) + if rec is not None: + return self._to_volume(kind, rec) + return None + + def _flexvol_bytes(self, size_bytes: int) -> int: + usable = -(-size_bytes * (100 + self.headroom) // 100) + total = -(-usable * 100 // (100 - self.snapshot_reserve)) + total = -(-total // 4096) * 4096 + return max(total, MIN_FLEXVOL_BYTES) + + def _get_flexvol(self, name: str) -> dict[str, Any] | None: + return self._one("/api/storage/volumes", + {"name": name, "svm.name": self.svm, "fields": "uuid,name,size"}) + + def _pick_aggregate(self) -> list[dict[str, str]]: + if not self.aggregates: + return [] + if len(self.aggregates) == 1: + return [{"name": self.aggregates[0]}] + # More than one aggregate in the POST would make a FlexGroup: choose one. + recs = self._records("/api/storage/aggregates", + {"name": "|".join(self.aggregates), + "fields": "name,space.block_storage.available"}) + if not recs: + raise ArrayNotFoundError(f"None of the aggregates {self.aggregates} exist") + best = max(recs, key=lambda r: int( + ((r.get("space") or {}).get("block_storage") or {}).get("available", 0))) + return [{"name": best["name"]}] + + def _create_flexvol(self, name: str, size_bytes: int) -> None: + body: dict[str, Any] = { + "name": name, + "svm": self._svm_ref(), + "size": size_bytes, + "type": "rw", + "guarantee": {"type": self.guarantee}, + "space": {"snapshot": {"reserve_percent": self.snapshot_reserve}}, + "snapshot_policy": {"name": str(self.option("snapshot_policy"))}, + "comment": FLEXVOL_COMMENT, + } + aggrs = self._pick_aggregate() + if aggrs: + body["aggregates"] = aggrs + self._async("POST", "/api/storage/volumes", json=body) + + def _grow_flexvol(self, vol: dict[str, Any], size_bytes: int) -> None: + if int(vol.get("size", 0)) < size_bytes: + self._async("PATCH", f"/api/storage/volumes/{vol['uuid']}", + json={"size": size_bytes}) + + def _delete_flexvol(self, uuid: str) -> None: + try: + self._async("DELETE", f"/api/storage/volumes/{uuid}") + except ArrayNotFoundError: + pass + + def create_volume(self, name: str, size_bytes: int) -> Volume: + flex = self._flexvol_for(name) + created_flexvol: str | None = None + if self.volume_per_lun: + want = self._flexvol_bytes(size_bytes) + vol = self._get_flexvol(flex) + if vol is None: # a re-run may find the FlexVol of an interrupted create + self._create_flexvol(flex, want) + vol = self._get_flexvol(flex) + if vol is None: + raise ArrayRequestError(f"FlexVol {flex} missing after create") + created_flexvol = vol["uuid"] + else: + self._grow_flexvol(vol, want) + path = f"/vol/{flex}/{name}" + kind = _LUN if self.family == "scsi" else _NS + try: + if kind == _LUN: + self._call("POST", "/api/storage/luns", params={"return_records": "true"}, json={ + "svm": self._svm_ref(), "name": path, "os_type": self.os_type, + "space": {"size": size_bytes, "guarantee": {"requested": False}}, + }) + else: + self._call("POST", "/api/storage/namespaces", params={"return_records": "true"}, + json={"svm": self._svm_ref(), "name": path, "os_type": self.os_type, + "space": {"size": size_bytes, + "block_size": self.block_size}}) + except ArrayError: + if created_flexvol: + try: + self._delete_flexvol(created_flexvol) + except ArrayError: + pass + raise + rec = self._lookup(kind, {"name": path}) + if rec is None: + raise ArrayRequestError(f"{kind} {path} missing after create") + return self._to_volume(kind, rec) + + def _owns_flexvol(self, kind: str, rec: dict[str, Any]) -> bool: + """True when the LUN/namespace sits in its own per-volume FlexVol.""" + flex = ((rec.get("location") or {}).get("volume") or {}).get("name", "") + name = self._to_volume(kind, rec).name + return bool(flex) and flex != self.shared_flexvol and flex == flexvol_name(name) + + def resize_volume(self, volume_id: str, size_bytes: int) -> Volume: + kind, rec = self._require(volume_id) + loc_vol = (rec.get("location") or {}).get("volume") or {} + if self._owns_flexvol(kind, rec): + vol = self._get_flexvol(loc_vol.get("name", "")) + if vol is None: + raise ArrayNotFoundError(f"FlexVol of volume {volume_id} not found") + self._grow_flexvol(vol, self._flexvol_bytes(size_bytes)) + base = "/api/storage/luns" if kind == _LUN else "/api/storage/namespaces" + self._call("PATCH", f"{base}/{volume_id}", json={"space": {"size": size_bytes}}) + kind, rec = self._require(volume_id) + return self._to_volume(kind, rec) + + def delete_volume(self, volume_id: str) -> None: + kind, rec = self._require(volume_id) + loc_vol = (rec.get("location") or {}).get("volume") or {} + if kind == _LUN: + self._call("DELETE", f"/api/storage/luns/{volume_id}") + else: + smap = self._subsystem_map(volume_id) + if smap is not None: + sub = smap["subsystem"] + self._call("DELETE", + f"/api/protocols/nvme/subsystem-maps/{sub['uuid']}/{volume_id}") + self._delete_subsystem(sub["uuid"]) + self._call("DELETE", f"/api/storage/namespaces/{volume_id}") + # Only a FlexVol of our own (one per LUN) is removed; never the shared one. + flex = loc_vol.get("name", "") + if self._owns_flexvol(kind, rec): + uuid = loc_vol.get("uuid") or (self._get_flexvol(flex) or {}).get("uuid") + if uuid: + self._delete_flexvol(uuid) + + # -- hosts ---------------------------------------------------------------- + + @staticmethod + def _nqn(i: Initiator) -> str: + if i.protocol == Protocol.NVME_FC and ":" in i.address and not i.address.startswith( + "nqn."): + raise ArrayUnsupportedError( + "ONTAP identifies NVMe/FC hosts by host NQN, not by WWPN: " + f"{i.address!r}") + return i.address + + def ensure_host(self, spec: HostSpec) -> str: + if all(i.protocol.is_nvme for i in spec.initiators): + return self._ensure_nvme_host(spec) + if all(i.protocol.is_scsi for i in spec.initiators): + return self._ensure_igroup(spec) + raise ArrayUnsupportedError( + f"NetApp ONTAP adapter does not support {sorted(p.value for p in spec.protocols)}") + + # SCSI: igroups + + @staticmethod + def _igroup_initiator(i: Initiator) -> str: + return colon_wwpn(i.address) if i.protocol == Protocol.FC else i.normalized() + + @staticmethod + def _norm_initiator(value: str) -> str: + v = value.strip().lower() + if v.startswith(("iqn.", "eui.", "naa.")): + return v + return v.replace(":", "").replace("-", "").removeprefix("0x") + + def _igroup(self, name: str) -> dict[str, Any] | None: + return self._one("/api/protocols/san/igroups", + {"name": name, "svm.name": self.svm, + "fields": "uuid,name,protocol,os_type,initiators.name"}) + + def _ensure_igroup(self, spec: HostSpec) -> str: + wanted = [self._igroup_initiator(i) for i in spec.initiators] + owners = self._records("/api/protocols/san/igroups", + {"svm.name": self.svm, "initiators.name": "|".join(wanted), + "fields": "uuid,name,initiators.name"}) + want_norm = {self._norm_initiator(w) for w in wanted} + for g in owners: + if g["name"] == spec.name: + continue + taken = want_norm & {self._norm_initiator(i["name"]) + for i in g.get("initiators") or []} + if taken: + raise ArrayConflictError( + f"Initiator(s) {', '.join(sorted(taken))} already belong to igroup " + f"{g['name']!r} in SVM {self.svm}") + group = self._igroup(spec.name) + if group is None: + self._call("POST", "/api/protocols/san/igroups", + params={"return_records": "true"}, + json={"svm": self._svm_ref(), "name": spec.name, "os_type": self.os_type, + "protocol": "mixed", + "initiators": [{"name": w} for w in wanted]}) + return spec.name + have = {self._norm_initiator(i["name"]) for i in group.get("initiators") or []} + missing = [w for w in wanted if self._norm_initiator(w) not in have] + if missing: + needs = {"iscsi" if i.protocol == Protocol.ISCSI else "fcp" + for i in spec.initiators + if self._norm_initiator(self._igroup_initiator(i)) not in have} + if group.get("protocol") not in ("mixed", *needs) or len(needs) > 1: + self._call("PATCH", f"/api/protocols/san/igroups/{group['uuid']}", + json={"protocol": "mixed"}) + self._call("POST", f"/api/protocols/san/igroups/{group['uuid']}/initiators", + json={"records": [{"name": m} for m in missing]}) + return spec.name + + # NVMe: host subsystems + + def _subsystems(self, params: dict[str, Any]) -> list[dict[str, Any]]: + return self._records("/api/protocols/nvme/subsystems", + {**params, "svm.name": self.svm, + "fields": "uuid,name,comment,os_type,hosts.nqn"}) + + @staticmethod + def _is_volume_subsystem(sub: dict[str, Any]) -> bool: + return sub.get("comment") == VOLUME_SUBSYSTEM_COMMENT + + def _host_subsystem(self, name: str) -> dict[str, Any] | None: + subs = [s for s in self._subsystems({"name": name}) if not self._is_volume_subsystem(s)] + return subs[0] if subs else None + + def _ensure_nvme_host(self, spec: HostSpec) -> str: + wanted = [self._nqn(i) for i in spec.initiators] + for other in self._subsystems({"hosts.nqn": "|".join(wanted)}): + if other["name"] == spec.name or self._is_volume_subsystem(other): + continue + taken = set(wanted) & {h["nqn"] for h in other.get("hosts") or []} + if taken: + raise ArrayConflictError( + f"Host NQN(s) {', '.join(sorted(taken))} already belong to subsystem " + f"{other['name']!r} in SVM {self.svm}") + sub = self._host_subsystem(spec.name) + if sub is None: + self._call("POST", "/api/protocols/nvme/subsystems", + params={"return_records": "true"}, + json={"svm": self._svm_ref(), "name": spec.name, "os_type": self.os_type, + "hosts": [{"nqn": n} for n in wanted]}) + return spec.name + have = {h["nqn"] for h in sub.get("hosts") or []} + missing = [n for n in wanted if n not in have] + if missing: + self._add_subsystem_hosts(sub["uuid"], missing) + return spec.name + + def _add_subsystem_hosts(self, sub_uuid: str, nqns: list[str]) -> None: + self._call("POST", f"/api/protocols/nvme/subsystems/{sub_uuid}/hosts", + json={"records": [{"nqn": n} for n in nqns]}) + + def _delete_subsystem(self, sub_uuid: str) -> None: + try: + self._call("DELETE", f"/api/protocols/nvme/subsystems/{sub_uuid}", + params={"allow_delete_with_hosts": "true"}) + except ArrayNotFoundError: + pass + + def delete_host(self, host_id: str) -> None: + group = self._igroup(host_id) + if group is not None: + try: + self._call("DELETE", f"/api/protocols/san/igroups/{group['uuid']}") + except ArrayNotFoundError: + pass + sub = self._host_subsystem(host_id) + if sub is not None: + self._delete_subsystem(sub["uuid"]) + + # -- mappings ------------------------------------------------------------- + + def _lun_maps(self, lun_uuid: str, igroup: str | None = None) -> list[dict[str, Any]]: + params: dict[str, Any] = {"lun.uuid": lun_uuid, "svm.name": self.svm, + "fields": "lun.uuid,igroup.uuid,igroup.name," + "logical_unit_number"} + if igroup is not None: + params["igroup.name"] = igroup + return self._records("/api/protocols/san/lun-maps", params) + + @staticmethod + def _lun_mapping(rec: dict[str, Any]) -> Mapping: + return Mapping(volume_id=rec["lun"]["uuid"], host_id=rec["igroup"]["name"], + lun=rec.get("logical_unit_number")) + + def _subsystem_map(self, ns_uuid: str) -> dict[str, Any] | None: + return self._one("/api/protocols/nvme/subsystem-maps", + {"namespace.uuid": ns_uuid, "svm.name": self.svm, + "fields": "namespace.uuid,subsystem.uuid,subsystem.name,nsid"}) + + def _volume_subsystem_hosts(self, smap: dict[str, Any]) -> dict[str, Any]: + sub = smap["subsystem"] + recs = self._subsystems({"uuid": sub["uuid"]}) + if not recs: + raise ArrayNotFoundError(f"Subsystem {sub.get('name')} not found") + return recs[0] + + def _nvme_mappings(self, ns_uuid: str) -> list[Mapping]: + smap = self._subsystem_map(ns_uuid) + if smap is None: + return [] + vsub = self._volume_subsystem_hosts(smap) + nqns = {h["nqn"] for h in vsub.get("hosts") or []} + if not nqns: + return [] + nsid = parse_nsid(smap.get("nsid")) + out: list[Mapping] = [] + for sub in self._subsystems({"hosts.nqn": "|".join(sorted(nqns))}): + if self._is_volume_subsystem(sub): + continue + if nqns & {h["nqn"] for h in sub.get("hosts") or []}: + out.append(Mapping(volume_id=ns_uuid, host_id=sub["name"], lun=nsid)) + return out + + def map_volume(self, volume_id: str, host_id: str) -> Mapping: + kind, rec = self._require(volume_id) + if kind == _LUN: + return self._map_lun(volume_id, host_id) + return self._map_namespace(volume_id, rec, host_id) + + def _map_lun(self, lun_uuid: str, host_id: str) -> Mapping: + if self._igroup(host_id) is None: + if self._host_subsystem(host_id) is not None: + raise ArrayUnsupportedError( + f"Host {host_id} is an NVMe host; volume {lun_uuid} is a SCSI LUN " + "(protocol_family scsi)") + raise ArrayNotFoundError(f"igroup {host_id} not found in SVM {self.svm}") + existing = self._lun_maps(lun_uuid, host_id) + if existing: + return self._lun_mapping(existing[0]) + self._call("POST", "/api/protocols/san/lun-maps", params={"return_records": "true"}, + json={"svm": self._svm_ref(), "lun": {"uuid": lun_uuid}, + "igroup": {"name": host_id}}) + created = self._lun_maps(lun_uuid, host_id) + if not created: + raise ArrayRequestError(f"lun-map {lun_uuid} -> {host_id} missing after create") + return self._lun_mapping(created[0]) + + def _map_namespace(self, ns_uuid: str, rec: dict[str, Any], host_id: str) -> Mapping: + host = self._host_subsystem(host_id) + if host is None: + if self._igroup(host_id) is not None: + raise ArrayUnsupportedError( + f"Host {host_id} is a SCSI host; volume {ns_uuid} is an NVMe namespace " + "(protocol_family nvme)") + raise ArrayNotFoundError(f"NVMe host subsystem {host_id} not found in SVM {self.svm}") + host_nqns = [h["nqn"] for h in host.get("hosts") or []] + smap = self._subsystem_map(ns_uuid) + if smap is None: + sub_name = flexvol_name(self._volume_from_ns(rec).name) + vsubs = [s for s in self._subsystems({"name": sub_name}) + if self._is_volume_subsystem(s)] + if vsubs: + sub_uuid = vsubs[0]["uuid"] + else: + body = json_of(self._call( + "POST", "/api/protocols/nvme/subsystems", params={"return_records": "true"}, + json={"svm": self._svm_ref(), "name": sub_name, "os_type": self.os_type, + "comment": VOLUME_SUBSYSTEM_COMMENT})) or {} + created = self._created(body) + if created is None: + created = next(iter(s for s in self._subsystems({"name": sub_name}) + if self._is_volume_subsystem(s)), None) + if created is None: + raise ArrayRequestError(f"Subsystem {sub_name} missing after create") + sub_uuid = created["uuid"] + self._call("POST", "/api/protocols/nvme/subsystem-maps", + params={"return_records": "true"}, + json={"svm": self._svm_ref(), "namespace": {"uuid": ns_uuid}, + "subsystem": {"uuid": sub_uuid}}) + smap = self._subsystem_map(ns_uuid) + if smap is None: + raise ArrayRequestError(f"subsystem-map of {ns_uuid} missing after create") + vsub = self._volume_subsystem_hosts(smap) + if not self._is_volume_subsystem(vsub): + raise ArrayConflictError( + f"Namespace {ns_uuid} is mapped to subsystem {vsub['name']!r}, which " + "simplyblock does not manage") + have = {h["nqn"] for h in vsub.get("hosts") or []} + missing = [n for n in host_nqns if n not in have] + if missing: + self._add_subsystem_hosts(vsub["uuid"], missing) + return Mapping(volume_id=ns_uuid, host_id=host_id, lun=parse_nsid(smap.get("nsid"))) + + def unmap_volume(self, volume_id: str, host_id: str) -> None: + found = self._locate(volume_id) + if found is None: + return + kind, _ = found + if kind == _LUN: + for m in self._lun_maps(volume_id, host_id): + try: + self._call("DELETE", f"/api/protocols/san/lun-maps/{volume_id}/" + f"{m['igroup']['uuid']}") + except ArrayNotFoundError: + pass + return + smap = self._subsystem_map(volume_id) + host = self._host_subsystem(host_id) + if smap is None or host is None: + return + vsub = self._volume_subsystem_hosts(smap) + if not self._is_volume_subsystem(vsub): + return + have = {h["nqn"] for h in vsub.get("hosts") or []} + for h in host.get("hosts") or []: + if h["nqn"] in have: + try: + self._call("DELETE", f"/api/protocols/nvme/subsystems/{vsub['uuid']}/hosts/" + f"{quote(h['nqn'], safe='')}") + except ArrayNotFoundError: + pass + + def list_mappings(self, volume_id: str) -> list[Mapping]: + kind, _ = self._require(volume_id) + if kind == _LUN: + return [self._lun_mapping(r) for r in self._lun_maps(volume_id)] + return self._nvme_mappings(volume_id) diff --git a/simplyblock_core/storage_arrays/adapters/pure.py b/simplyblock_core/storage_arrays/adapters/pure.py index 5c2ed4864e..866d3894da 100644 --- a/simplyblock_core/storage_arrays/adapters/pure.py +++ b/simplyblock_core/storage_arrays/adapters/pure.py @@ -195,6 +195,10 @@ def ensure_host(self, spec: HostSpec) -> str: return spec.name def delete_host(self, host_id: str) -> None: + if self._host(host_id) is None: + return + if self._items("GET", "/connections", params={"host_names": host_id}, missing_ok=True): + raise ArrayConflictError(f"Host {host_id} still has volume connections") self._items("DELETE", "/hosts", params={"names": host_id}, missing_ok=True) def _connections(self, volume_id: str, host_id: str | None = None) -> list[Mapping]: diff --git a/simplyblock_core/storage_arrays/base.py b/simplyblock_core/storage_arrays/base.py index 0619d402e6..8d2a6b927e 100644 --- a/simplyblock_core/storage_arrays/base.py +++ b/simplyblock_core/storage_arrays/base.py @@ -105,7 +105,9 @@ def _strip(cls, v: str) -> str: return v.strip() def normalized(self) -> str: - if self.protocol in (Protocol.FC, Protocol.NVME_FC): + # NVMe/FC hosts are identified by their host NQN like every NVMe + # transport; only SCSI over FC uses WWPNs. + if self.protocol == Protocol.FC: return normalize_wwpn(self.address) if self.protocol == Protocol.ISCSI: return self.address.lower() @@ -146,8 +148,10 @@ class Volume(BaseModel): id: str name: str size_bytes: int - #: SCSI identity as the host sees it, ``naa.`` (lowercase). This is - #: what matches the array volume to ``/dev/disk/by-id`` on the host. + #: SCSI identity (VPD page 0x83 designator) as the host sees it: + #: ``naa.`` for most arrays, ``eui.`` where the array presents an + #: EUI-64 designator (HPE Nimble). Lowercase. This matches the array volume + #: to ``/dev/disk/by-id`` / the multipath WWID on the host. wwn: str | None = None #: NVMe identity, ``eui.<32 hex>`` (NGUID) where the array exposes one. nguid: str | None = None @@ -217,6 +221,9 @@ class Capabilities: max_name_len: int = 63 #: Whether resize can only grow (true for every supported array today). grow_only: bool = True + #: Most initiators one host may have; ``None`` = unlimited. PowerFlex SDC + #: hosts are exactly one client, so 1 there. + max_initiators_per_host: int | None = None @dataclass diff --git a/simplyblock_core/storage_arrays/client.py b/simplyblock_core/storage_arrays/client.py index e5bb928eab..cccef18751 100644 --- a/simplyblock_core/storage_arrays/client.py +++ b/simplyblock_core/storage_arrays/client.py @@ -154,11 +154,20 @@ def _call(self, op: str, fn: Callable[[ArrayAdapter], T]) -> T: # -- checks ----------------------------------------------------------------- - def _owned(self, vol: Volume, expected_identifier: str | None, action: str) -> None: + def _owned(self, vol: Volume, expected_identifier: str | None, action: str, + volume_uuid: str | None = None) -> None: + """Refuse to touch a volume simplyblock did not create, or that is not + the one it recorded. The name check matters where the array reuses + identities: an LDEV number / volume id (and the WWN derived from it) + can come back after a delete, the name derived from our UUID cannot.""" if not vol.name.startswith(MANAGED_PREFIX): raise ArrayConflictError( f"Refusing to {action} volume {vol.name!r} on array {self.config.id}: " "not created by simplyblock") + if volume_uuid is not None and vol.name != self.volume_name(volume_uuid): + raise ArrayConflictError( + f"Refusing to {action} volume {vol.name!r} on array {self.config.id}: " + f"name does not match recorded volume {volume_uuid}") if expected_identifier is not None and vol.identifier.lower() != expected_identifier.lower(): raise ArrayConflictError( f"Refusing to {action} volume {vol.name!r} on array {self.config.id}: " @@ -200,7 +209,8 @@ def find_volume(self, volume_uuid: str) -> Volume | None: return self._call("find_volume", lambda a: a.find_volume(name)) def resize_volume(self, volume_id: str, size_bytes: int, - expected_identifier: str | None = None) -> Volume: + expected_identifier: str | None = None, + volume_uuid: str | None = None) -> Volume: caps = self.capabilities size = round_size(size_bytes, caps.size_granularity_bytes, caps.min_size_bytes) @@ -208,7 +218,7 @@ def op(a: ArrayAdapter) -> Volume: vol = a.get_volume(volume_id) if vol is None: raise ArrayError(f"Volume {volume_id} not found on array {self.config.id}") - self._owned(vol, expected_identifier, "resize") + self._owned(vol, expected_identifier, "resize", volume_uuid) if size == vol.size_bytes: return vol if size < vol.size_bytes and caps.grow_only: @@ -221,13 +231,17 @@ def op(a: ArrayAdapter) -> Volume: return self._call("resize_volume", op) - def delete_volume(self, volume_id: str, expected_identifier: str | None = None) -> bool: - """Unmap from every host and delete. Returns False if already gone.""" + def delete_volume(self, volume_id: str, expected_identifier: str | None = None, + volume_uuid: str | None = None) -> bool: + """Unmap from every host and delete. Returns False if already gone. + + Callers should pass both ``expected_identifier`` and ``volume_uuid`` + from their record; together they pin the exact volume.""" def op(a: ArrayAdapter) -> bool: vol = a.get_volume(volume_id) if vol is None: return False - self._owned(vol, expected_identifier, "delete") + self._owned(vol, expected_identifier, "delete", volume_uuid) for m in a.list_mappings(vol.id): a.unmap_volume(vol.id, m.host_id) a.delete_volume(vol.id) @@ -242,6 +256,11 @@ def ensure_host(self, spec: HostSpec) -> str: raise ArrayError( f"{self.adapter_cls.display_name} adapter does not support " + ", ".join(sorted(p.value for p in unsupported))) + limit = self.capabilities.max_initiators_per_host + if limit is not None and len(spec.initiators) > limit: + raise ArrayError( + f"{self.adapter_cls.display_name} hosts take at most {limit} initiator(s); " + f"got {len(spec.initiators)}") if len(spec.name) > self.capabilities.max_name_len: raise ArrayError(f"Host name {spec.name!r} exceeds " f"{self.capabilities.max_name_len} characters") @@ -251,12 +270,13 @@ def delete_host(self, host_id: str) -> None: self._call("delete_host", lambda a: a.delete_host(host_id)) def map_volume(self, volume_id: str, host_id: str, - expected_identifier: str | None = None) -> Mapping: + expected_identifier: str | None = None, + volume_uuid: str | None = None) -> Mapping: def op(a: ArrayAdapter) -> Mapping: vol = a.get_volume(volume_id) if vol is None: raise ArrayError(f"Volume {volume_id} not found on array {self.config.id}") - self._owned(vol, expected_identifier, "map") + self._owned(vol, expected_identifier, "map", volume_uuid) return a.map_volume(vol.id, host_id) return self._call("map_volume", op) diff --git a/simplyblock_core/storage_arrays/http.py b/simplyblock_core/storage_arrays/http.py index 71c29fdc30..0f4e0819d9 100644 --- a/simplyblock_core/storage_arrays/http.py +++ b/simplyblock_core/storage_arrays/http.py @@ -56,7 +56,9 @@ def __init__( self.timeout_s = timeout_s self.retries = retries self.backoff_s = backoff_s - self._sleep = sleep + #: Used for retry backoff and by adapters that poll async jobs, so + #: tests can make all waiting instant. + self.sleep = sleep self.http = requests.Session() self.http.verify = verify self.http.headers.update({"Accept": "application/json"}) @@ -125,12 +127,12 @@ def request( except requests.RequestException as e: last_exc = e if attempt + 1 < attempts: - self._sleep(self.backoff_s * (attempt + 1)) + self.sleep(self.backoff_s * (attempt + 1)) continue raise ArrayRequestError( f"{method} {path}: {type(e).__name__}: {_safe(str(e))}") from e if resp.status_code in _RETRY_STATUSES and attempt + 1 < attempts: - self._sleep(self.backoff_s * (attempt + 1)) + self.sleep(self.backoff_s * (attempt + 1)) continue if 200 <= resp.status_code < 300 or resp.status_code in ok_extra: return resp diff --git a/simplyblock_core/storage_arrays/testing/__init__.py b/simplyblock_core/storage_arrays/testing/__init__.py index b295365650..67f49ad7e2 100644 --- a/simplyblock_core/storage_arrays/testing/__init__.py +++ b/simplyblock_core/storage_arrays/testing/__init__.py @@ -20,10 +20,12 @@ from __future__ import annotations import base64 +import http.client import io import json import re import threading +import types from collections.abc import Callable from dataclasses import dataclass, field from typing import Any @@ -193,12 +195,25 @@ def _encode(reply: Reply) -> tuple[bytes, dict[str, str]]: return json.dumps(reply.body).encode(), headers +class _Raw(io.BytesIO): + """Body stream that also carries the headers the way urllib3 does, so + ``requests`` stores Set-Cookie values in the session's cookie jar exactly + as it would for a real response.""" + + def __init__(self, content: bytes, headers: dict[str, str]): + super().__init__(content) + msg = http.client.HTTPMessage() + for k, v in headers.items(): + msg[k] = v + self._original_response = types.SimpleNamespace(msg=msg) + + def _to_response(request, reply: Reply) -> requests.Response: content, headers = _encode(reply) resp = requests.Response() resp.status_code = reply.status resp.headers = CaseInsensitiveDict(headers) - resp.raw = io.BytesIO(content) + resp.raw = _Raw(content, headers) resp._content = content resp.url = request.url resp.request = request diff --git a/simplyblock_core/storage_arrays/testing/dell_powerflex.py b/simplyblock_core/storage_arrays/testing/dell_powerflex.py new file mode 100644 index 0000000000..d1266297df --- /dev/null +++ b/simplyblock_core/storage_arrays/testing/dell_powerflex.py @@ -0,0 +1,289 @@ +"""Fake Dell PowerFlex REST gateway (3.6 ``/api/login`` token auth, 4.x +``/rest/auth/login`` OAuth), the subset the adapter uses. + +Quirks reproduced: the 3.x login token is a JSON *string*; "not found" is +HTTP 500 with ``{"message", "httpStatusCode", "errorCode"}``; sizes round up +to 8 GiB; ``mappedSdcInfo`` is ``null`` when unmapped; a second SDC mapping +needs ``allowMultipleMappings``; SDCs exist before (and independently of) +any host registration. Error codes are placeholders, not PowerFlex's. +""" +from __future__ import annotations + +import json +import secrets +import uuid +from typing import Any + +from pydantic import SecretStr + +from simplyblock_core.credentials import Credential + +from ..base import Initiator, Protocol +from . import ContractSetup, FakeArray, FakeError, Reply, Request, make_config, route + +GIB = 1 << 30 +_KB_PER_8GIB = 8 * 1024 * 1024 +_VOL = r"/api/instances/Volume::(?P[0-9a-zA-Z]+)" + + +def _err(msg: str, status: int = 500, code: int = 0) -> FakeError: + return FakeError(status, {"message": msg, "httpStatusCode": status, "errorCode": code}) + + +def _bool(v: Any) -> bool: + return str(v).upper() == "TRUE" + + +class FakePowerFlex(FakeArray): + vendor = "dell-powerflex" + + def __init__(self, username: str = "admin", password: str = "pf-pass", + generation: int = 4): + super().__init__() + if generation not in (3, 4): + raise ValueError("generation must be 3 or 4") + self.generation = generation + self.username = username + self.password = password + self.tokens: set[str] = set() # 3.x session tokens + self.access_tokens: set[str] = set() # 4.x bearer tokens + self.system_id = "4a54e5c8a1b2c3d4" + self.pools = {"7d2e1c5b00000001": {"id": "7d2e1c5b00000001", "name": "sb-pool", + "protectionDomainId": "e1f2a3b400000000"}} + self.volumes: dict[str, dict[str, Any]] = {} + self.sdcs: dict[str, dict[str, Any]] = {} + + # -- fake controls ------------------------------------------------------ + + @property + def pool_id(self) -> str: + return next(iter(self.pools)) + + def _new_id(self) -> str: + return f"{secrets.token_hex(4)}{self.next_id():08x}" + + def expire_sessions(self) -> None: + self.tokens.clear() + self.access_tokens.clear() + + def set_credential(self, **fields: str) -> None: + self.username = fields.get("username", self.username) + self.password = fields["password"] + + def add_sdc(self, guid: str, name: str | None = None) -> str: + sid = self._new_id() + self.sdcs[sid] = {"id": sid, "sdcGuid": guid, "name": name, + "sdcIp": f"10.0.0.{len(self.sdcs) + 10}", "sdcApproved": True, + "mdmConnectionState": "Connected", + "links": [{"rel": "self", "href": f"/api/instances/Sdc::{sid}"}]} + return sid + + def add_volume(self, name: str | None, size_bytes: int, pool_id: str | None = None) -> str: + vid = self._new_id() + kb = -(-max(size_bytes // 1024, 1) // _KB_PER_8GIB) * _KB_PER_8GIB + self.volumes[vid] = { + "id": vid, "name": name, "sizeInKb": kb, + "storagePoolId": pool_id or self.pool_id, "volumeType": "ThinProvisioned", + "vtreeId": self._new_id(), "ancestorVolumeId": None, "mappedSdcInfo": None, + "creationTime": 1763600000, "isObfuscated": False, + "links": [{"rel": "self", "href": f"/api/instances/Volume::{vid}"}], + } + return vid + + # -- auth --------------------------------------------------------------- + + def _auth(self, req: Request) -> None: + if self.generation == 3: + creds = req.basic_auth() + if creds and creds[1] in self.tokens: + return + else: + header = req.headers.get("Authorization", "") + if header.startswith("Bearer ") and header[7:] in self.access_tokens: + return + raise _err("Unauthorized", 401) + + @route("GET", "/api/login") + def api_login(self, req): + if self.generation != 3: + raise _err("Not found", 404) + if req.basic_auth() != (self.username, self.password): + raise _err("Unauthorized", 401) + token = secrets.token_urlsafe(24) + self.tokens.add(token) + # The 3.x gateway returns the token as a JSON string literal. + return Reply(200, json.dumps(token).encode(), {"Content-Type": "application/json"}) + + @route("GET", "/api/logout") + def api_logout(self, req): + creds = req.basic_auth() + if creds: + self.tokens.discard(creds[1]) + return Reply(200, None) + + @route("POST", "/rest/auth/login") + def rest_login(self, req): + if self.generation != 4: + return Reply(404, b"HTTP Status 404 - Not Found", + {"Content-Type": "text/html"}) + body = req.json() or {} + if (body.get("username"), body.get("password")) != (self.username, self.password): + raise FakeError(401, {"error": "invalid_grant", + "error_description": "Invalid user credentials"}) + token = secrets.token_urlsafe(32) + self.access_tokens.add(token) + return Reply(200, {"access_token": token, "expires_in": 300, + "refresh_token": secrets.token_urlsafe(32), + "refresh_expires_in": 1800, "token_type": "Bearer", + "scope": "openid profile email"}) + + @route("POST", "/rest/auth/logout") + def rest_logout(self, req): + header = req.headers.get("Authorization", "") + self.access_tokens.discard(header[7:]) + return Reply(204, None) + + # -- system ----------------------------------------------------------------- + + @route("GET", "/api/types/System/instances") + def systems(self, req): + self._auth(req) + version = "R3_6.0.0" if self.generation == 3 else "R4_5.0.0" + return Reply(200, [{"id": self.system_id, "name": "fake-pflex", + "systemVersionName": f"DellEMC PowerFlex Version: {version}", + "mdmClusterState": "ClusteredNormal"}]) + + # -- volumes ------------------------------------------------------------- + + def _vol(self, vid: str) -> dict[str, Any]: + if vid not in self.volumes: + raise _err("Could not find the volume", 500, 79) + return self.volumes[vid] + + @route("POST", "/api/types/Volume/instances") + def create_volume(self, req): + self._auth(req) + body = req.json() or {} + name = body.get("name") + if name and len(name) > 31: + raise _err("Name is too long", 500, 7) + if name and any(v["name"] == name for v in self.volumes.values()): + raise _err("Volume name already in use", 500, 6) + pool = body.get("storagePoolId") + if pool not in self.pools: + raise _err("Could not find the Storage Pool", 500, 61) + if body.get("volumeType") not in ("ThinProvisioned", "ThickProvisioned"): + raise _err("Invalid volume type", 400, 1) + try: + kb = int(body["volumeSizeInKb"]) + except (KeyError, TypeError, ValueError): + raise _err("Invalid volume size", 400, 1) from None + vid = self.add_volume(name, kb * 1024, pool) + return Reply(200, {"id": vid}) + + @route("GET", _VOL) + def get_volume(self, req, vid): + self._auth(req) + return Reply(200, self._vol(vid)) + + @route("POST", "/api/types/Volume/instances/action/queryIdByKey") + def query_id(self, req): + self._auth(req) + name = (req.json() or {}).get("name") + for v in self.volumes.values(): + if v["name"] == name: + return Reply(200, v["id"]) + raise _err("Could not find the volume", 500, 79) + + @route("POST", _VOL + "/action/(?P[A-Za-z]+)") + def volume_action(self, req, vid, action): + self._auth(req) + v = self._vol(vid) + body = req.json() or {} + mapped = v["mappedSdcInfo"] or [] + if action == "setVolumeSize": + gb = int(body["sizeInGB"]) + kb = -(-gb // 8) * 8 * 1024 * 1024 + if kb < v["sizeInKb"]: + raise _err("Volume size cannot be decreased", 500, 76) + v["sizeInKb"] = kb + return Reply(200, {}) + if action == "removeVolume": + if body.get("removeMode") not in ("ONLY_ME", "INCLUDING_DESCENDANTS", + "DESCENDANTS_ONLY", "WHOLE_VTREE"): + raise _err("Invalid remove mode", 400, 1) + if mapped: + raise _err("The volume is mapped to an SDC; unmap it first", 500, 80) + del self.volumes[vid] + return Reply(200, {}) + if action == "addMappedSdc": + sid = body.get("sdcId") + if sid not in self.sdcs: + raise _err("Could not find the SDC", 500, 100) + if any(m["sdcId"] == sid for m in mapped): + raise _err("The volume is already mapped to this SDC", 500, 81) + if mapped and not _bool(body.get("allowMultipleMappings")): + raise _err("The volume is already mapped to another SDC; " + "set allowMultipleMappings", 500, 82) + sdc = self.sdcs[sid] + v["mappedSdcInfo"] = mapped + [{ + "sdcId": sid, "sdcIp": sdc["sdcIp"], "sdcName": sdc["name"], + "limitIops": 0, "limitBwInMbps": 0, + "accessMode": body.get("accessMode", "ReadWrite")}] + return Reply(200, {}) + if action == "removeMappedSdc": + sid = body.get("sdcId") + rest = [m for m in mapped if m["sdcId"] != sid] + if len(rest) == len(mapped): + raise _err("The volume is not mapped to SDC", 500, 83) + v["mappedSdcInfo"] = rest or None + return Reply(200, {}) + raise _err(f"Unknown action {action}", 400, 1) + + # -- SDCs ----------------------------------------------------------------- + + @route("GET", "/api/types/Sdc/instances") + def list_sdcs(self, req): + self._auth(req) + return Reply(200, list(self.sdcs.values())) + + @route("POST", r"/api/instances/Sdc::(?P[0-9a-zA-Z]+)/action/setSdcName") + def set_sdc_name(self, req, sid): + self._auth(req) + if sid not in self.sdcs: + raise _err("Could not find the SDC", 500, 100) + name = (req.json() or {}).get("sdcName") + if any(s["name"] == name and s["id"] != sid for s in self.sdcs.values()): + raise _err("SDC name already in use", 500, 6) + self.sdcs[sid]["name"] = name + return Reply(200, {}) + + +def _guid() -> str: + return str(uuid.uuid4()).upper() + + +def contract_setup(generation: int = 4) -> ContractSetup: + fake = FakePowerFlex(username="admin", password="pf-pass", generation=generation) + guid_a, guid_b = _guid(), _guid() + # SDCs register themselves with the MDM when installed on a host; the + # adapter only finds them, so the fake starts with both hosts' SDCs. + fake.add_sdc(guid_a) + fake.add_sdc(guid_b) + return ContractSetup( + fake=fake, + config=make_config("dell-powerflex", "https://powerflex.fake.example", + storage_pool_id=fake.pool_id), + credential=Credential({"username": SecretStr("admin"), + "password": SecretStr("pf-pass")}), + bad_credential=Credential({"username": SecretStr("admin"), + "password": SecretStr("wrong")}), + initiators={ + Protocol.SDC: ( + (Initiator(protocol=Protocol.SDC, address=guid_a),), + (Initiator(protocol=Protocol.SDC, address=guid_b),), + ), + }, + create_foreign_volume=lambda name, size: fake.add_volume(name, size), + has_lun_numbers=False, + ) diff --git a/simplyblock_core/storage_arrays/testing/dell_powermax.py b/simplyblock_core/storage_arrays/testing/dell_powermax.py new file mode 100644 index 0000000000..5c3e59f406 --- /dev/null +++ b/simplyblock_core/storage_arrays/testing/dell_powermax.py @@ -0,0 +1,593 @@ +"""Fake Dell PowerMax Unisphere REST API 10.x (the subset the adapter uses). + +Quirks reproduced: basic auth on every request (401 plain-text body); +``{"message": "..."}`` error bodies, 400 for most failures and 404 for +missing objects; versioned paths (``/univmax/restapi/{ver}/...``) with +unknown versions refused; sizes in cylinders (1 CYL = 1920 KiB), also +accepting MB/GB/TB; ``executionOption: ASYNCHRONOUS`` answered with +``202`` + job that runs on the second poll of ``/{ver}/system/job/{id}`` +(``SCHEDULED`` -> ``RUNNING`` -> ``SUCCEEDED``/``FAILED`` with the error in +``result``); volume listing as an iterator (``count``/``resultList``, no +``resultList`` when empty); non-unique volume identifiers; masked storage +groups cannot lose their last device; host LUN addresses in hex; port groups +bound to one protocol. +""" +from __future__ import annotations + +import math +import re +import secrets +from collections.abc import Callable +from typing import Any + +from pydantic import SecretStr + +from simplyblock_core.credentials import Credential + +from ..base import Initiator, Protocol +from . import ContractSetup, FakeArray, FakeError, Reply, Request, make_config, route + +SYMMETRIX_ID = "000197900123" +CYL_BYTES = 1920 * 1024 +_ROOT = "/univmax/restapi" +_V = _ROOT + r"/(?P\d+)" +_SLO = _V + r"/sloprovisioning/symmetrix/(?P\d{12})" +_NAME_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$") +_UNIT_MB = {"MB": 1, "GB": 1024, "TB": 1024 * 1024} + + +def _err(status: int, message: str) -> FakeError: + return FakeError(status, {"message": message}) + + +def _bad(message: str) -> FakeError: + return _err(400, message) + + +def _proto_of(initiator: str) -> str: + v = initiator.lower() + if v.startswith(("iqn.", "eui.")): + return "iscsi" + if v.startswith("nqn."): + return "nvme-tcp" + return "fc" + + +class FakeDellPowerMax(FakeArray): + vendor = "dell-powermax" + api_versions = ("100", "101") + + def __init__(self, username: str = "smc", password: str = "pmax-pass", + symmetrix_id: str = SYMMETRIX_ID): + super().__init__() + self.username = username + self.password = password + self.symmetrix_id = symmetrix_id + self.volumes: dict[str, dict[str, Any]] = {} # device id -> volume + self.storage_groups: dict[str, dict[str, Any]] = {} # name -> sg + self.hosts: dict[str, dict[str, Any]] = {} # name -> host + self.port_groups: dict[str, dict[str, Any]] = { + "sb_pg_iscsi": {"protocol": "iscsi", "ports": ["SE-1E:0", "SE-2E:0"]}, + "sb_pg_fc": {"protocol": "fc", "ports": ["FA-1D:4", "FA-2D:4"]}, + "sb_pg_nvme": {"protocol": "nvme-tcp", "ports": ["OR-1C:2", "OR-2C:2"]}, + } + self.views: dict[str, dict[str, Any]] = {} # name -> masking view + self.jobs: dict[str, dict[str, Any]] = {} + self._job_fns: dict[str, Callable[[], Reply]] = {} + self.first_lun = 1 + self._dev = 0x00100 + + # -- fake controls ------------------------------------------------------ + + def set_credential(self, **fields: str) -> None: + self.username = fields.get("username", self.username) + self.password = fields.get("password", self.password) + + def _new_device(self, identifier: str, cyl: int) -> str: + self._dev += 1 + dev = f"{self._dev:05X}" + wwn = ("6000097000" + self.symmetrix_id[-12:] + dev.encode().hex()).upper() + self.volumes[dev] = { + "volumeId": dev, "type": "TDEV", "emulation": "FBA", "ssid": "FFFFFFFF", + "status": "Ready", "reserved": False, "pinned": False, + "volume_identifier": identifier, "cap_cyl": cyl, "wwn": wwn, + "effective_wwn": wwn, "has_effective_wwn": False, "encapsulated": False, + "storageGroupId": [], "snapvx_source": False, "snapvx_target": False, + "mobility_id_enabled": False, + } + return dev + + def add_volume(self, name: str, size: int, storage_group: str | None = None) -> str: + """Create a device directly (optionally inside a storage group).""" + dev = self._new_device(name, math.ceil(size / CYL_BYTES)) + if storage_group: + sg = self.storage_groups.setdefault(storage_group, self._sg_record( + storage_group, "SRP_1", None)) + sg["volumes"].append(dev) + self.volumes[dev]["storageGroupId"].append(storage_group) + return dev + + # -- dispatch helpers ---------------------------------------------------------- + + def _auth(self, req: Request) -> None: + if req.basic_auth() != (self.username, self.password): + raise FakeError(401, "Unauthorized", {"WWW-Authenticate": 'Basic realm="Unisphere"'}) + + def _check(self, req: Request, ver: str, sym: str | None = None) -> None: + self._auth(req) + if ver not in self.api_versions: + raise _err(404, f"Unsupported REST API version {ver}") + if sym is not None and sym != self.symmetrix_id: + raise _err(404, f"Cannot find Symmetrix {sym}") + + def _run(self, req: Request, fn: Callable[[], Reply]) -> Reply: + """Honour ``executionOption``: run now, or queue as a job.""" + body = req.json() or {} + option = body.get("executionOption", "SYNCHRONOUS") + if option not in ("SYNCHRONOUS", "ASYNCHRONOUS"): + raise _bad(f"Invalid executionOption {option}") + if option == "SYNCHRONOUS": + return fn() + job_id = str(1_000_000 + self.next_id()) + self.jobs[job_id] = { + "jobId": job_id, "name": f"{req.method} {req.path}", "status": "SCHEDULED", + "username": self.username, "result": None, + "last_modified_date": "Nov-20-2026 00:00:00.000", + "resourceLink": f"https://unisphere.fake.example{req.path}", + "task": [{"execution_order": 1, "description": f"{req.method} {req.path}"}], + "_polls": 0, + } + self._job_fns[job_id] = fn + return Reply(202, self._public_job(job_id)) + + def _public_job(self, job_id: str) -> dict[str, Any]: + return {k: v for k, v in self.jobs[job_id].items() if not k.startswith("_")} + + @route("GET", _V + r"/system/job/(?P\d+)") + def get_job(self, req, ver, job_id): + self._check(req, ver) + job = self.jobs.get(job_id) + if job is None: + raise _err(404, f"Cannot find job {job_id}") + job["_polls"] += 1 + if job["status"] == "SCHEDULED": + job["status"] = "RUNNING" + elif job["status"] == "RUNNING": + fn = self._job_fns.pop(job_id) + try: + fn() + job["status"], job["result"] = "SUCCEEDED", "Succeeded" + except FakeError as e: + body = e.reply.body if isinstance(e.reply.body, dict) else {} + job["status"] = "FAILED" + job["result"] = f"Failed : {body.get('message', e.reply.status)}" + return Reply(200, self._public_job(job_id)) + + # -- system ------------------------------------------------------------------------- + + @route("GET", _ROOT + "/version") + def version(self, req): + self._auth(req) + return Reply(200, {"version": "T10.1.0.0", "api_version": "101", + "supported_api_versions": list(self.api_versions)}) + + @route("GET", _V + r"/system/symmetrix/(?P\d{12})") + def get_symmetrix(self, req, ver, sym): + self._check(req, ver, sym) + return Reply(200, {"symmetrixId": sym, "device_count": len(self.volumes), + "ucode": "6079.225.0", "model": "PowerMax_8500", + "local": True, "default_fba_srp": "SRP_1"}) + + # -- volumes ------------------------------------------------------------------------ + + def _vol(self, dev: str) -> dict[str, Any]: + if dev not in self.volumes: + raise _err(404, f"Cannot find Volume {dev}") + return self.volumes[dev] + + def _vol_view(self, v: dict[str, Any]) -> dict[str, Any]: + cyl = v["cap_cyl"] + mapped = any(v["volumeId"] in self.storage_groups[sg]["volumes"] + and self.storage_groups[sg]["maskingview"] for sg in v["storageGroupId"]) + return {**v, + "cap_gb": round(cyl * 1920 / 1024 / 1024, 2), + "cap_mb": round(cyl * 1.875, 2), + "num_of_storage_groups": len(v["storageGroupId"]), + "num_of_front_end_paths": 0, "mapped": mapped, + "allocated_percent": 0} + + @staticmethod + def _cylinders(attrs: dict[str, Any]) -> int: + unit = attrs.get("capacityUnit", "GB") + try: + size = float(attrs["volume_size"]) + except (KeyError, TypeError, ValueError) as e: + raise _bad("Invalid volume_size") from e + if size <= 0: + raise _bad("volume_size must be positive") + if unit == "CYL": + if size != int(size): + raise _bad("volume_size in CYL must be a whole number") + return int(size) + if unit not in _UNIT_MB: + raise _bad(f"Invalid capacityUnit {unit}") + return math.ceil(size * _UNIT_MB[unit] / 1.875) + + def _identifier(self, attrs: dict[str, Any]) -> str: + ident = attrs.get("volumeIdentifier") or {} + if not ident: + return "" + if ident.get("volumeIdentifierChoice") != "identifier_name": + raise _bad("Unsupported volumeIdentifierChoice") + name = ident.get("identifier_name") or "" + if len(name) > 64: + raise _bad("The volume identifier must not exceed 64 characters") + return name + + @route("GET", _SLO + "/volume") + def list_volumes(self, req, ver, sym): + self._check(req, ver, sym) + rows = list(self.volumes.values()) + if req.q("volume_identifier") is not None: + want = req.q("volume_identifier") or "" + if want.startswith(""): + rows = [v for v in rows if want[6:] in v["volume_identifier"]] + else: + rows = [v for v in rows if v["volume_identifier"] == want] + if req.q("storageGroupId") is not None: + sg = req.q("storageGroupId") + rows = [v for v in rows if sg in v["storageGroupId"]] + body: dict[str, Any] = {"count": len(rows), "maxPageSize": 1000, + "expirationTime": 1_900_000_000_000} + if rows: + body["id"] = f"{secrets.token_hex(4)}-iterator" + body["resultList"] = {"result": [{"volumeId": v["volumeId"]} for v in rows], + "from": 1, "to": len(rows)} + return Reply(200, body) + + @route("GET", _SLO + r"/volume/(?P[0-9A-Fa-f]+)") + def get_volume(self, req, ver, sym, dev): + self._check(req, ver, sym) + return Reply(200, self._vol_view(self._vol(dev))) + + @route("PUT", _SLO + r"/volume/(?P[0-9A-Fa-f]+)") + def put_volume(self, req, ver, sym, dev): + self._check(req, ver, sym) + vol = self._vol(dev) + body = req.json() or {} + expand = ((body.get("editVolumeActionParam") or {}).get("expandVolumeParam") or {}) + if not expand: + raise _bad("Unsupported editVolumeActionParam") + cyl = self._cylinders(expand.get("volumeAttribute") or {}) + + def do() -> Reply: + if cyl < vol["cap_cyl"]: + raise _bad(f"The new size of volume {dev} must be larger than the " + "current size") + vol["cap_cyl"] = cyl + return Reply(200, self._vol_view(vol)) + return self._run(req, do) + + @route("DELETE", _SLO + r"/volume/(?P[0-9A-Fa-f]+)") + def delete_volume(self, req, ver, sym, dev): + self._check(req, ver, sym) + vol = self._vol(dev) + if vol["storageGroupId"]: + raise _bad(f"A problem occurred deleting the volume {dev}: the device is a " + f"member of storage group {vol['storageGroupId'][0]}") + del self.volumes[dev] + return Reply(204) + + # -- storage groups ------------------------------------------------------------------ + + @staticmethod + def _sg_record(name: str, srp: str, slo: str | None) -> dict[str, Any]: + return {"storageGroupId": name, "srp": srp, "slo": slo or "NONE", + "volumes": [], "maskingview": []} + + def _sg(self, name: str) -> dict[str, Any]: + if name not in self.storage_groups: + raise _err(404, f"Cannot find Storage Group {name}") + return self.storage_groups[name] + + def _sg_view(self, sg: dict[str, Any]) -> dict[str, Any]: + cyl = sum(self.volumes[d]["cap_cyl"] for d in sg["volumes"]) + out = {"storageGroupId": sg["storageGroupId"], "srp": sg["srp"], "slo": sg["slo"], + "num_of_vols": len(sg["volumes"]), "num_of_child_sgs": 0, + "num_of_parent_sgs": 0, "num_of_masking_views": len(sg["maskingview"]), + "num_of_snapshots": 0, "cap_gb": round(cyl * 1920 / 1024 / 1024, 2), + "device_emulation": "FBA", "type": "Standalone", "unprotected": True, + "compression": True} + if sg["maskingview"]: + out["maskingview"] = list(sg["maskingview"]) + return out + + def _add_devices(self, sg: dict[str, Any], attrs_list: list[dict[str, Any]]) -> None: + for attrs in attrs_list: + cyl = self._cylinders(attrs) + ident = self._identifier(attrs) + for _ in range(int(attrs.get("num_of_vols", 1))): + dev = self._new_device(ident, cyl) + sg["volumes"].append(dev) + self.volumes[dev]["storageGroupId"].append(sg["storageGroupId"]) + + @route("POST", _SLO + "/storagegroup") + def post_sg(self, req, ver, sym): + self._check(req, ver, sym) + body = req.json() or {} + name = body.get("storageGroupId") or "" + if not _NAME_RE.match(name): + raise _bad(f"Invalid storage group name {name!r}") + srp = body.get("srpId", "None") + if srp not in ("SRP_1", "None"): + raise _err(404, f"Cannot find SRP {srp}") + params = body.get("sloBasedStorageGroupParam") or [] + for p in params: + if p.get("sloId", "None") not in ("None", "Diamond", "Platinum", "Gold", + "Silver", "Bronze", "Optimized"): + raise _bad(f"Invalid sloId {p.get('sloId')}") + if "workloadSelection" in p and p["workloadSelection"] not in ("None", None): + raise _bad("workloadSelection is not supported on this array") + + def do() -> Reply: + if name in self.storage_groups: + raise _bad(f"Storage Group {name} already exists") + slo = next((p.get("sloId") for p in params if p.get("sloId") != "None"), None) + sg = self._sg_record(name, srp, slo) + self.storage_groups[name] = sg + try: + for p in params: + self._add_devices(sg, p.get("volumeAttributes") or []) + except FakeError: + del self.storage_groups[name] + raise + return Reply(200, self._sg_view(sg)) + return self._run(req, do) + + @route("GET", _SLO + r"/storagegroup/(?P[^/]+)") + def get_sg(self, req, ver, sym, name): + self._check(req, ver, sym) + return Reply(200, self._sg_view(self._sg(name))) + + @route("PUT", _SLO + r"/storagegroup/(?P[^/]+)") + def put_sg(self, req, ver, sym, name): + self._check(req, ver, sym) + sg = self._sg(name) + edit = (req.json() or {}).get("editStorageGroupActionParam") or {} + if "removeVolumeParam" in edit: + devs = edit["removeVolumeParam"].get("volumeId") or [] + + def remove() -> Reply: + for d in devs: + if d not in sg["volumes"]: + raise _bad(f"Volume {d} is not in Storage Group {name}") + if sg["maskingview"] and len(set(sg["volumes"]) - set(devs)) == 0: + raise _bad(f"Cannot remove the last volume from Storage Group {name} " + "because it is part of a masking view") + for d in devs: + sg["volumes"].remove(d) + self.volumes[d]["storageGroupId"].remove(name) + return Reply(200, self._sg_view(sg)) + return self._run(req, remove) + expand = edit.get("expandStorageGroupParam") or {} + add = expand.get("addVolumeParam") + if add is not None: + if not add.get("create_new_volumes", False): + raise _bad("Only create_new_volumes is supported by the fake") + + def grow() -> Reply: + self._add_devices(sg, add.get("volumeAttributes") or []) + return Reply(200, self._sg_view(sg)) + return self._run(req, grow) + raise _bad("Unsupported editStorageGroupActionParam") + + @route("DELETE", _SLO + r"/storagegroup/(?P[^/]+)") + def delete_sg(self, req, ver, sym, name): + self._check(req, ver, sym) + sg = self._sg(name) + if sg["maskingview"]: + raise _bad(f"Storage Group {name} is part of masking view {sg['maskingview'][0]}") + if sg["volumes"]: + raise _bad(f"Storage Group {name} is not empty") + del self.storage_groups[name] + return Reply(204) + + # -- hosts ------------------------------------------------------------------------------- + + def _host(self, name: str) -> dict[str, Any]: + if name not in self.hosts: + raise _err(404, f"Cannot find Host {name}") + return self.hosts[name] + + def _host_view(self, h: dict[str, Any]) -> dict[str, Any]: + return {"hostId": h["hostId"], "num_of_masking_views": len(h["maskingview"]), + "num_of_initiators": len(h["initiator"]), "num_of_host_groups": 0, + "port_flags_override": False, "consistent_lun": False, + "initiator": list(h["initiator"]), "maskingview": list(h["maskingview"]), + "type": {"fc": "Fibre", "iscsi": "iSCSI", "nvme-tcp": "NVMe/TCP"}.get( + _proto_of(h["initiator"][0]) if h["initiator"] else "", "")} + + def _claim(self, host: str, initiators: list[str]) -> list[str]: + out = [] + for i in initiators: + proto = _proto_of(i) + if proto == "fc" and not re.match(r"^[0-9a-f]{16}$", i): + raise _bad(f"Invalid initiator {i}: expected a 16-digit WWN") + for other in self.hosts.values(): + if i.lower() in (x.lower() for x in other["initiator"]): + if other["hostId"] == host: + raise _bad(f"Initiator {i} is already in Host {host}") + raise _bad(f"Initiator {i} is already in use by Host {other['hostId']}") + out.append(i) + protos = {_proto_of(x) for x in out + (self.hosts[host]["initiator"] + if host in self.hosts else [])} + if len(protos) > 1: + raise _bad("A host cannot mix initiator types") + return out + + @route("POST", _SLO + "/host") + def post_host(self, req, ver, sym): + self._check(req, ver, sym) + body = req.json() or {} + name = body.get("hostId") or "" + if not _NAME_RE.match(name): + raise _bad(f"Invalid host name {name!r}") + initiators = body.get("initiatorId") or [] + + def do() -> Reply: + if name in self.hosts: + raise _bad(f"Host {name} already exists") + claimed = self._claim(name, initiators) + self.hosts[name] = {"hostId": name, "initiator": claimed, "maskingview": []} + return Reply(200, self._host_view(self.hosts[name])) + return self._run(req, do) + + @route("GET", _SLO + r"/host/(?P[^/]+)") + def get_host(self, req, ver, sym, name): + self._check(req, ver, sym) + return Reply(200, self._host_view(self._host(name))) + + @route("PUT", _SLO + r"/host/(?P[^/]+)") + def put_host(self, req, ver, sym, name): + self._check(req, ver, sym) + host = self._host(name) + edit = (req.json() or {}).get("editHostActionParam") or {} + add = (edit.get("addInitiatorParam") or {}).get("initiator") + if add is None: + raise _bad("Unsupported editHostActionParam") + + def do() -> Reply: + host["initiator"].extend(self._claim(name, add)) + return Reply(200, self._host_view(host)) + return self._run(req, do) + + @route("DELETE", _SLO + r"/host/(?P[^/]+)") + def delete_host(self, req, ver, sym, name): + self._check(req, ver, sym) + host = self._host(name) + if host["maskingview"]: + raise _bad(f"Host {name} is part of masking view {host['maskingview'][0]}") + del self.hosts[name] + return Reply(204) + + # -- masking views --------------------------------------------------------------- + + def _view(self, name: str) -> dict[str, Any]: + if name not in self.views: + raise _err(404, f"Cannot find Masking View {name}") + return self.views[name] + + @route("POST", _SLO + "/maskingview") + def post_view(self, req, ver, sym): + self._check(req, ver, sym) + body = req.json() or {} + name = body.get("maskingViewId") or "" + if not _NAME_RE.match(name): + raise _bad(f"Invalid masking view name {name!r}") + host = ((body.get("hostOrHostGroupSelection") or {}) + .get("useExistingHostParam") or {}).get("hostId") + pg = ((body.get("portGroupSelection") or {}) + .get("useExistingPortGroupParam") or {}).get("portGroupId") + sg = ((body.get("storageGroupSelection") or {}) + .get("useExistingStorageGroupParam") or {}).get("storageGroupId") + if not (host and pg and sg): + raise _bad("A masking view needs an existing host, port group and storage group") + + def do() -> Reply: + if name in self.views: + raise _bad(f"Masking View {name} already exists") + h, s = self._host(host), self._sg(sg) + if pg not in self.port_groups: + raise _err(404, f"Cannot find Port Group {pg}") + if not s["volumes"]: + raise _bad(f"Storage Group {sg} is empty") + protos = {_proto_of(i) for i in h["initiator"]} + if protos and protos != {self.port_groups[pg]["protocol"]}: + raise _bad(f"Port Group {pg} does not match the protocol of Host {host}") + used = {lun for v in self.views.values() if v["host"] == host + for lun in v["luns"].values()} + luns = {} + for dev in s["volumes"]: + lun = next(n for n in range(self.first_lun, 4096) if n not in used) + used.add(lun) + luns[dev] = lun + self.views[name] = {"maskingViewId": name, "host": host, "pg": pg, "sg": sg, + "luns": luns} + h["maskingview"].append(name) + s["maskingview"].append(name) + return Reply(200, self._view_view(self.views[name])) + return self._run(req, do) + + @staticmethod + def _view_view(v: dict[str, Any]) -> dict[str, Any]: + return {"maskingViewId": v["maskingViewId"], "hostId": v["host"], + "portGroupId": v["pg"], "storageGroupId": v["sg"]} + + @route("GET", _SLO + r"/maskingview/(?P[^/]+)") + def get_view(self, req, ver, sym, name): + self._check(req, ver, sym) + return Reply(200, self._view_view(self._view(name))) + + @route("GET", _SLO + r"/maskingview/(?P[^/]+)/connections") + def get_connections(self, req, ver, sym, name): + self._check(req, ver, sym) + v = self._view(name) + want = req.q("volume_id") + rows = [] + for dev in self.storage_groups[v["sg"]]["volumes"]: + if want and dev != want: + continue + lun = v["luns"].get(dev) + if lun is None: # device added after the view was created + continue + for initiator in self.hosts[v["host"]]["initiator"]: + for port in self.port_groups[v["pg"]]["ports"]: + rows.append({"volumeId": dev, "host_lun_address": f"{lun:04X}", + "cap_gb": round(self.volumes[dev]["cap_cyl"] * 1920 + / 1024 / 1024, 2), + "initiatorId": initiator, "alias": initiator, + "dir_port": port, "logged_in": False, "on_fabric": False}) + return Reply(200, {"maskingViewConnection": rows}) + + @route("DELETE", _SLO + r"/maskingview/(?P[^/]+)") + def delete_view(self, req, ver, sym, name): + self._check(req, ver, sym) + v = self._view(name) + self.hosts[v["host"]]["maskingview"].remove(name) + self.storage_groups[v["sg"]]["maskingview"].remove(name) + del self.views[name] + return Reply(204) + + +def contract_setup(**options: Any) -> ContractSetup: + fake = FakeDellPowerMax(username="smc", password="pmax-pass") + opts: dict[str, Any] = { + "symmetrix_id": SYMMETRIX_ID, + "port_group": {"iscsi": "sb_pg_iscsi", "fc": "sb_pg_fc", "nvme-tcp": "sb_pg_nvme"}, + } + opts.update(options) + return ContractSetup( + fake=fake, + config=make_config("dell-powermax", "https://unisphere.fake.example:8443", **opts), + credential=Credential({"username": SecretStr("smc"), + "password": SecretStr("pmax-pass")}), + bad_credential=Credential({"username": SecretStr("smc"), + "password": SecretStr("wrong")}), + initiators={ + Protocol.ISCSI: ( + (Initiator(protocol=Protocol.ISCSI, address="iqn.2026-01.io.sb:host-a"),), + (Initiator(protocol=Protocol.ISCSI, address="iqn.2026-01.io.sb:host-b"),), + ), + Protocol.FC: ( + (Initiator(protocol=Protocol.FC, address="21:00:00:24:ff:4c:1a:2b"),), + (Initiator(protocol=Protocol.FC, address="21:00:00:24:ff:4c:1a:2c"),), + ), + Protocol.NVME_TCP: ( + (Initiator(protocol=Protocol.NVME_TCP, + address="nqn.2014-08.org.nvmexpress:uuid:host-a"),), + (Initiator(protocol=Protocol.NVME_TCP, + address="nqn.2014-08.org.nvmexpress:uuid:host-b"),), + ), + }, + create_foreign_volume=lambda name, size: fake.add_volume(name, size, "customer_sg"), + ) diff --git a/simplyblock_core/storage_arrays/testing/dell_powerstore.py b/simplyblock_core/storage_arrays/testing/dell_powerstore.py new file mode 100644 index 0000000000..0855735314 --- /dev/null +++ b/simplyblock_core/storage_arrays/testing/dell_powerstore.py @@ -0,0 +1,426 @@ +"""Fake Dell PowerStore REST API (the subset the adapter uses). + +Quirks reproduced: basic auth only on ``login_session``; session cookie +``auth_cookie`` plus ``DELL-EMC-TOKEN`` CSRF header required on non-GET +requests (403 without it); PostgREST-style ``select``/``eq.`` filters with +400 on unknown fields; ``limit``/``offset`` paging answered with 206 and +``Content-Range``; 201 ``{"id"}`` on create, 204 on modify/delete/attach; +422 with ``{"messages": [...]}`` for semantic errors; sizes in bytes, a +multiple of 8192; ``wwn``/``nguid`` prefixed ``naa.``/``nguid.``. +""" +from __future__ import annotations + +import re +import secrets +import uuid +from http.cookies import CookieError, SimpleCookie +from typing import Any + +from pydantic import SecretStr + +from simplyblock_core.credentials import Credential + +from ..base import Initiator, Protocol +from . import ContractSetup, FakeArray, FakeError, Reply, Request, make_config, route + +API = "/api/rest" +_ID = r"(?P[^/]+)" +_FC_RE = re.compile(r"^([0-9a-f]{2}:){7}[0-9a-f]{2}$", re.IGNORECASE) +MIN_SIZE = 1 << 20 +MAX_SIZE = 256 << 40 +GRANULARITY = 8192 + +_FIELDS = { + "volume": {"id", "name", "description", "type", "wwn", "nguid", "size", "state", + "appliance_id", "creation_timestamp", "is_replication_destination", + "performance_policy_id", "protection_policy_id"}, + "host": {"id", "name", "description", "os_type", "host_group_id", "host_initiators", + "host_connectivity"}, + "host_volume_mapping": {"id", "host_id", "host_group_id", "volume_id", + "logical_unit_number"}, + "cluster": {"id", "global_id", "name", "management_address", "state", + "appliance_count"}, + "appliance": {"id", "name", "model", "service_tag", "express_service_code"}, + "software_installed": {"id", "release_version", "build_version", "is_cluster", + "release_timestamp"}, +} + + +def _err(status: int, message: str, code: str = "0xE04040010005") -> FakeError: + return FakeError(status, {"messages": [{"code": code, "severity": "Error", + "message_l10n": message, "arguments": []}]}) + + +def _not_found(kind: str, oid: str) -> FakeError: + return _err(404, f"The {kind} {oid} was not found.", "0xE04040010005") + + +def _unprocessable(message: str) -> FakeError: + return _err(422, message, "0xE0A07001000C") + + +class FakeDellPowerStore(FakeArray): + vendor = "dell-powerstore" + + def __init__(self, username: str = "admin", password: str = "ps-pass"): + super().__init__() + self.username = username + self.password = password + self.sessions: dict[str, str] = {} # auth_cookie -> CSRF token + self.volumes: dict[str, dict[str, Any]] = {} # id -> volume + self.hosts: dict[str, dict[str, Any]] = {} # id -> host + self.mappings: list[dict[str, Any]] = [] + self.page_limit = 2000 # array-side default/max page size + self.first_lun = 1 + + # -- fake controls ------------------------------------------------------ + + def expire_sessions(self) -> None: + self.sessions.clear() + + def set_credential(self, **fields: str) -> None: + self.username = fields.get("username", self.username) + self.password = fields.get("password", self.password) + + def add_volume(self, name: str, size: int) -> str: + vid = str(uuid.uuid4()) + self.volumes[vid] = { + "id": vid, "name": name, "description": None, "type": "Primary", + "wwn": "naa.68ccf098" + secrets.token_hex(12), + "nguid": "nguid." + secrets.token_hex(16), + "size": size, "state": "Ready", "appliance_id": "A1", + "creation_timestamp": "2026-11-20T00:00:00+00:00", + "is_replication_destination": False, "performance_policy_id": "default_medium", + "protection_policy_id": None, + } + return vid + + # -- auth --------------------------------------------------------------- + + def _session(self, req: Request) -> None: + cookie: str | None = None + try: + jar = SimpleCookie() + jar.load(req.headers.get("Cookie", "")) + if "auth_cookie" in jar: + cookie = jar["auth_cookie"].value + except CookieError: + pass + if cookie is None or cookie not in self.sessions: + raise _err(401, "Unauthorized: the session is invalid or expired.", + "0xE09040010001") + if req.method != "GET" and req.headers.get("DELL-EMC-TOKEN") != self.sessions[cookie]: + raise _err(403, "Forbidden: missing or invalid DELL-EMC-TOKEN.", "0xE09040010003") + + @route("GET", API + "/login_session") + def login_session(self, req): + if req.basic_auth() != (self.username, self.password): + raise _err(401, "Unauthorized: invalid credentials.", "0xE09040010001") + cookie, token = secrets.token_hex(16), secrets.token_hex(16) + self.sessions[cookie] = token + return Reply(200, [{"id": secrets.token_hex(8), "user": self.username, + "role_ids": ["1"], "idle_timeout": 3600, + "is_password_change_required": False, + "is_built_in_user": True}], + {"DELL-EMC-TOKEN": token, + "Set-Cookie": f"auth_cookie={cookie}; Path=/; Secure; HttpOnly"}) + + @route("POST", API + "/logout") + def logout(self, req): + self._session(req) + jar = SimpleCookie() + jar.load(req.headers.get("Cookie", "")) + self.sessions.pop(jar["auth_cookie"].value, None) + return Reply(204) + + # -- query engine ------------------------------------------------------------ + + def _query(self, req: Request, kind: str, rows: list[dict[str, Any]]) -> Reply: + fields = _FIELDS[kind] + for key, values in req.query.items(): + if key in ("select", "limit", "offset", "order"): + continue + if key not in fields: + raise _err(400, f"Invalid filter field: {key}.", "0xE04040020009") + m = re.match(r"^eq\.(.*)$", values[0], re.DOTALL) + if not m: + raise _err(400, f"Unsupported filter operator in {key}={values[0]}.", + "0xE04040020009") + want = m.group(1) + rows = [r for r in rows if _as_filter(r.get(key)) == want] + select = req.q("select") + if select: + names = select.split(",") + bad = [n for n in names if n not in fields] + if bad: + raise _err(400, f"Invalid select field: {','.join(bad)}.", "0xE04040020009") + else: + names = ["id"] + offset = int(req.q("offset", "0") or 0) + limit = min(int(req.q("limit", str(self.page_limit)) or self.page_limit), + self.page_limit) + total = len(rows) + page = rows[offset:offset + limit] + body = [{n: r.get(n) for n in names} for r in page] + if offset + len(page) < total: + end = offset + len(page) - 1 + return Reply(206, body, {"Content-Range": f"{offset}-{end}/{total}"}) + return Reply(200, body) + + def _project(self, req: Request, kind: str, row: dict[str, Any]) -> Reply: + select = req.q("select") + names = select.split(",") if select else sorted(_FIELDS[kind]) + bad = [n for n in names if n not in _FIELDS[kind]] + if bad: + raise _err(400, f"Invalid select field: {','.join(bad)}.", "0xE04040020009") + return Reply(200, {n: row.get(n) for n in names}) + + # -- system ------------------------------------------------------------------ + + @route("GET", API + "/cluster") + def get_cluster(self, req): + self._session(req) + return self._query(req, "cluster", [{ + "id": "0", "global_id": "PS4a7b5c3e9f01", "name": "fake-powerstore", + "management_address": "10.0.0.10", "state": "Configured", "appliance_count": 1}]) + + @route("GET", API + "/appliance") + def get_appliance(self, req): + self._session(req) + return self._query(req, "appliance", [{ + "id": "A1", "name": "fake-powerstore-appliance-1", "model": "PowerStore 1200T", + "service_tag": "FAKE123", "express_service_code": "0"}]) + + @route("GET", API + "/software_installed") + def get_software(self, req): + self._session(req) + return self._query(req, "software_installed", [ + {"id": "c1", "release_version": "4.0.0.0", "build_version": "4.0.0.0.5.123", + "is_cluster": True, "release_timestamp": "2026-01-01T00:00:00Z"}, + {"id": "a1", "release_version": "4.0.0.0", "build_version": "4.0.0.0.5.123", + "is_cluster": False, "release_timestamp": "2026-01-01T00:00:00Z"}, + ]) + + # -- volumes ----------------------------------------------------------------- + + def _vol(self, oid: str) -> dict[str, Any]: + if oid not in self.volumes: + raise _not_found("volume", oid) + return self.volumes[oid] + + @staticmethod + def _check_size(size: Any) -> int: + if not isinstance(size, int) or isinstance(size, bool): + raise _err(400, "Invalid value for size.", "0xE04040020009") + if size < MIN_SIZE or size > MAX_SIZE: + raise _err(400, f"Size {size} is out of range ({MIN_SIZE}..{MAX_SIZE}).", + "0xE04040020009") + if size % GRANULARITY: + raise _err(400, f"Size {size} must be a multiple of {GRANULARITY}.", + "0xE04040020009") + return size + + @route("GET", API + "/volume") + def list_volumes(self, req): + self._session(req) + return self._query(req, "volume", list(self.volumes.values())) + + @route("GET", API + "/volume/" + _ID) + def get_volume(self, req, oid): + self._session(req) + return self._project(req, "volume", self._vol(oid)) + + @route("POST", API + "/volume") + def post_volume(self, req): + self._session(req) + body = req.json() or {} + name = body.get("name") + if not name or len(name) > 128: + raise _err(400, "Invalid value for name.", "0xE04040020009") + size = self._check_size(body.get("size")) + if any(v["name"] == name for v in self.volumes.values()): + raise _unprocessable(f"The name {name} is already in use by another volume.") + vid = self.add_volume(name, size) + if body.get("appliance_id"): + self.volumes[vid]["appliance_id"] = body["appliance_id"] + return Reply(201, {"id": vid}) + + @route("PATCH", API + "/volume/" + _ID) + def patch_volume(self, req, oid): + self._session(req) + vol = self._vol(oid) + body = req.json() or {} + if "size" in body: + size = self._check_size(body["size"]) + if size < vol["size"]: + raise _unprocessable("The new size must be greater than the current size " + "of the volume.") + vol["size"] = size + return Reply(204) + + @route("DELETE", API + "/volume/" + _ID) + def delete_volume(self, req, oid): + self._session(req) + self._vol(oid) + if any(m["volume_id"] == oid for m in self.mappings): + raise _unprocessable(f"Volume {oid} cannot be deleted because it is attached " + "to one or more hosts.") + del self.volumes[oid] + return Reply(204) + + @route("POST", API + "/volume/" + _ID + "/attach") + def attach(self, req, oid): + self._session(req) + self._vol(oid) + body = req.json() or {} + host_id = body.get("host_id") + if not host_id or host_id not in self.hosts: + raise _not_found("host", str(host_id)) + if any(m["volume_id"] == oid and m["host_id"] == host_id for m in self.mappings): + raise _unprocessable(f"Volume {oid} is already attached to host {host_id}.") + used = {m["logical_unit_number"] for m in self.mappings if m["host_id"] == host_id} + lun = body.get("logical_unit_number") + if lun is None: + lun = next(n for n in range(self.first_lun, 16384) if n not in used) + elif lun in used: + raise _unprocessable(f"Logical unit number {lun} is already in use on the host.") + self.mappings.append({"id": str(uuid.uuid4()), "host_id": host_id, + "host_group_id": None, "volume_id": oid, + "logical_unit_number": lun}) + return Reply(204) + + @route("POST", API + "/volume/" + _ID + "/detach") + def detach(self, req, oid): + self._session(req) + self._vol(oid) + host_id = (req.json() or {}).get("host_id") + before = len(self.mappings) + self.mappings = [m for m in self.mappings + if not (m["volume_id"] == oid and m["host_id"] == host_id)] + if len(self.mappings) == before: + raise _unprocessable(f"Volume {oid} is not attached to host {host_id}.") + return Reply(204) + + @route("GET", API + "/host_volume_mapping") + def list_mappings(self, req): + self._session(req) + return self._query(req, "host_volume_mapping", list(self.mappings)) + + # -- hosts ---------------------------------------------------------------------- + + def _host(self, oid: str) -> dict[str, Any]: + if oid not in self.hosts: + raise _not_found("host", oid) + return self.hosts[oid] + + def _claim(self, host_id: str, initiators: Any) -> list[dict[str, Any]]: + if not isinstance(initiators, list): + raise _err(400, "Invalid value for initiators.", "0xE04040020009") + out = [] + for i in initiators: + port_name, port_type = i.get("port_name"), i.get("port_type") + if port_type not in ("iSCSI", "FC", "NVMe"): + raise _err(400, f"Invalid port_type {port_type}.", "0xE04040020009") + if not port_name: + raise _err(400, "Invalid value for port_name.", "0xE04040020009") + if port_type == "FC" and not _FC_RE.match(port_name): + raise _err(400, f"Invalid FC port_name {port_name}.", "0xE04040020009") + for other in self.hosts.values(): + for p in other["host_initiators"]: + if p["port_name"].lower() == port_name.lower(): + if other["id"] == host_id: + raise _unprocessable( + f"The initiator {port_name} is already added to this host.") + raise _unprocessable( + f"The initiator {port_name} is already registered to host " + f"{other['name']}.") + out.append({"port_name": port_name, "port_type": port_type, + "active_sessions": [], "chap_single_username": None, + "chap_mutual_username": None}) + return out + + @route("GET", API + "/host") + def list_hosts(self, req): + self._session(req) + return self._query(req, "host", list(self.hosts.values())) + + @route("GET", API + "/host/" + _ID) + def get_host(self, req, oid): + self._session(req) + return self._project(req, "host", self._host(oid)) + + @route("POST", API + "/host") + def post_host(self, req): + self._session(req) + body = req.json() or {} + name = body.get("name") + if not name or len(name) > 128: + raise _err(400, "Invalid value for name.", "0xE04040020009") + if body.get("os_type") not in ("Windows", "Linux", "ESXi", "AIX", "HP-UX", "Solaris"): + raise _err(400, f"Invalid os_type {body.get('os_type')}.", "0xE04040020009") + if any(h["name"] == name for h in self.hosts.values()): + raise _unprocessable(f"The name {name} is already in use by another host.") + hid = str(uuid.uuid4()) + initiators = self._claim(hid, body.get("initiators") or []) + self.hosts[hid] = {"id": hid, "name": name, "description": None, + "os_type": body["os_type"], "host_group_id": None, + "host_initiators": initiators, + "host_connectivity": "Local_Only"} + return Reply(201, {"id": hid}) + + @route("PATCH", API + "/host/" + _ID) + def patch_host(self, req, oid): + self._session(req) + host = self._host(oid) + body = req.json() or {} + if "initiators" in body: + raise _err(400, "Use add_initiators/remove_initiators to modify initiators.", + "0xE04040020009") + added = self._claim(oid, body.get("add_initiators") or []) + host["host_initiators"].extend(added) + return Reply(204) + + @route("DELETE", API + "/host/" + _ID) + def delete_host(self, req, oid): + self._session(req) + self._host(oid) + if any(m["host_id"] == oid for m in self.mappings): + raise _unprocessable(f"Host {oid} cannot be deleted because it has volumes " + "attached.") + del self.hosts[oid] + return Reply(204) + + +def _as_filter(value: Any) -> str: + if isinstance(value, bool): + return "true" if value else "false" + return "" if value is None else str(value) + + +def contract_setup() -> ContractSetup: + fake = FakeDellPowerStore(username="admin", password="ps-pass") + return ContractSetup( + fake=fake, + config=make_config("dell-powerstore", "https://powerstore.fake.example"), + credential=Credential({"username": SecretStr("admin"), + "password": SecretStr("ps-pass")}), + bad_credential=Credential({"username": SecretStr("admin"), + "password": SecretStr("wrong")}), + initiators={ + Protocol.ISCSI: ( + (Initiator(protocol=Protocol.ISCSI, address="iqn.2026-01.io.sb:host-a"),), + (Initiator(protocol=Protocol.ISCSI, address="iqn.2026-01.io.sb:host-b"),), + ), + Protocol.FC: ( + (Initiator(protocol=Protocol.FC, address="21:00:00:24:ff:4c:1a:2b"),), + (Initiator(protocol=Protocol.FC, address="21:00:00:24:FF:4C:1A:2C"),), + ), + Protocol.NVME_TCP: ( + (Initiator(protocol=Protocol.NVME_TCP, + address="nqn.2014-08.org.nvmexpress:uuid:host-a"),), + (Initiator(protocol=Protocol.NVME_TCP, + address="nqn.2014-08.org.nvmexpress:uuid:host-b"),), + ), + }, + create_foreign_volume=lambda name, size: fake.add_volume(name, size), + ) diff --git a/simplyblock_core/storage_arrays/testing/hitachi_vsp.py b/simplyblock_core/storage_arrays/testing/hitachi_vsp.py new file mode 100644 index 0000000000..cc09025c60 --- /dev/null +++ b/simplyblock_core/storage_arrays/testing/hitachi_vsp.py @@ -0,0 +1,616 @@ +"""Fake Hitachi VSP Configuration Manager REST API (the subset the adapter uses). + +Reproduces: both path layouts (embedded ``/ConfigurationManager/v1/objects`` +and server ``.../objects/storages/{storageDeviceId}``), basic-auth sessions +with ``Authorization: Session ``, ``202`` + job objects for every +change with the change applied only when the job runs (after ``job_polls`` +"Running" polls), job failures carrying the Hitachi error body, LDEVs that +read back as ``NOT DEFINED`` after deletion, per-port host groups with +default group 0, FC WWN uniqueness per port (iSCSI names may repeat across +targets, as on the array), LU paths listed on the LDEV, the resource-group +lock, and ``{"errorSource", "message", "solution", "messageId"}`` errors. +""" +from __future__ import annotations + +import re +import secrets +from collections.abc import Callable +from typing import Any + +from pydantic import SecretStr + +from simplyblock_core.credentials import Credential + +from ..base import Initiator, Protocol +from . import ContractSetup, FakeArray, FakeError, Reply, Request, make_config, route + +_ROOT = "/ConfigurationManager/v1/objects" +_P = _ROOT + r"(?:/storages/(?P\d{12}))?" +_MAX_LDEV = 65279 +NOT_DEFINED = "NOT DEFINED" +_UNITS = {"K": 1 << 10, "M": 1 << 20, "G": 1 << 30, "T": 1 << 40} + + +def _body(msg: str, msg_id: str, source: str = "", solution: str = "") -> dict[str, Any]: + return {"errorSource": source, "message": msg, "solution": solution or + "Check the request and the storage system configuration.", + "messageId": msg_id} + + +def _err(status: int, msg: str, msg_id: str = "KART40040-E", source: str = "") -> FakeError: + return FakeError(status, _body(msg, msg_id, source)) + + +def _storage_err(msg: str, ssb1: str = "2E11", ssb2: str = "0001") -> FakeError: + """A failure inside the storage system: in a job's ``error``.""" + body = _body(msg, "KART30000-E") + body["errorCode"] = {"SSB1": ssb1, "SSB2": ssb2} + return FakeError(400, body) + + +class FakeHitachiVsp(FakeArray): + vendor = "hitachi-vsp" + + def __init__(self, username: str = "sbadmin", password: str = "vsp-secret", + serial: int = 451234, model: str = "VSP E990", + ports: dict[str, str] | None = None, pools: tuple[int, ...] = (0,)): + super().__init__() + self.username, self.password = username, password + self.serial = serial + self.model = model + self.storage_device_id = f"{938000000000 + serial}" + self.sessions: dict[str, int] = {} # token -> sessionId + self.pools = set(pools) + self.ldevs: dict[int, dict[str, Any]] = {} # defined LDEVs only + self.ports = ports or {"CL1-A": "FIBRE", "CL2-A": "FIBRE", + "CL1-B": "ISCSI", "CL2-B": "ISCSI"} + #: (port, number) -> {"name", "mode", "wwns": [], "iscsis": [], "luns": {lun: ldev}} + self.groups: dict[tuple[str, int], dict[str, Any]] = {} + for port in self.ports: + self.groups[(port, 0)] = self._group(f"{port[2:].replace('-', '')}-G00", + "LINUX/IRIX") + self.jobs: dict[int, dict[str, Any]] = {} + self._pending: dict[int, Callable[[], list[str]]] = {} + self._polls_left: dict[int, int] = {} + #: "Running" answers before a job executes. + self.job_polls = 1 + #: Model requires the resource-group lock for changes. + self.require_lock = False + self.lock_owner: str | None = None + self.max_count = 16384 + + @staticmethod + def _group(name: str, mode: str) -> dict[str, Any]: + return {"name": name, "mode": mode, "modeOptions": [], "wwns": [], "iscsis": [], + "luns": {}} + + # -- fake controls ------------------------------------------------------ + + def expire_sessions(self) -> None: + self.sessions.clear() + self.lock_owner = None + + def set_credential(self, **fields: str) -> None: + self.username = fields.get("username", self.username) + self.password = fields["password"] + + def add_ldev(self, label: str, size: int, ldev_id: int | None = None) -> str: + lid = ldev_id if ldev_id is not None else self._free_ldev(0, _MAX_LDEV) + self.ldevs[lid] = {"pool": min(self.pools), "blocks": size // 512, "label": label} + return str(lid) + + def _free_ldev(self, start: int, end: int) -> int: + lid = next((i for i in range(start, end + 1) if i not in self.ldevs), None) + if lid is None: + raise _storage_err("No free LDEV number in the specified range.", "2E11", "0012") + return lid + + def naa(self, lid: int) -> str: + s = f"{self.serial:06X}" + return f"60060E80{s}0030{s}0000{lid:04X}" + + # -- auth / prefix ------------------------------------------------------- + + def _prefix(self, sdid: str | None) -> str: + if sdid is None: + return _ROOT + if sdid != self.storage_device_id: + raise _err(404, f"The storage system {sdid} is not registered.", "KART40053-E") + return f"{_ROOT}/storages/{sdid}" + + def _token(self, req: Request) -> str: + header = req.headers.get("Authorization", "") + token = header[8:] if header.startswith("Session ") else "" + if token not in self.sessions: + raise _err(401, "The session is invalid or has timed out.", "KART40047-E", + req.path) + return token + + def _auth(self, req: Request, sdid: str | None) -> str: + self._prefix(sdid) + return self._token(req) + + @route("POST", _P + "/sessions") + def post_session(self, req, sdid): + self._prefix(sdid) + if req.basic_auth() != (self.username, self.password): + raise _err(401, "Authentication failed.", "KART40046-E", req.path) + token = secrets.token_hex(16) + self.sessions[token] = self.next_id() + return Reply(200, {"token": token, "sessionId": self.sessions[token]}) + + @route("DELETE", _P + r"/sessions/(?P\d+)") + def delete_session(self, req, sdid, sid): + token = self._auth(req, sdid) + if self.sessions.get(token) != int(sid): + raise _err(404, f"Session {sid} does not exist.", "KART40050-E") + del self.sessions[token] + if self.lock_owner == token: + self.lock_owner = None + return Reply(200, {"sessionId": int(sid)}) + + @route("GET", _ROOT + r"/storages/(?Pinstance|\d{12})") + def get_storage(self, req, which): + self._auth(req, None if which == "instance" else which) + return Reply(200, {"storageDeviceId": self.storage_device_id, "model": self.model, + "serialNumber": self.serial, "svpIp": "192.0.2.10", + "dkcMicroVersion": "93-07-23-80/00", "communicationModes": [ + {"communicationMode": "lanConnectionMode"}]}) + + # -- jobs ----------------------------------------------------------------- + + def _job(self, req: Request, sdid: str | None, token: str, + execute: Callable[[], list[str]], *, lock_request: bool = False) -> Reply: + if not lock_request: + if self.lock_owner and self.lock_owner != token: + raise _err(409, "The resource group is locked by another user.", + "KART40049-E") + if self.require_lock and self.lock_owner != token: + raise _storage_err("The resource group is not locked.", "2E10", "A001") + jid = self.next_id() + prefix = self._prefix(sdid) + self.jobs[jid] = { + "jobId": jid, "self": f"{prefix}/jobs/{jid}", "userId": self.username, + "status": "Initializing", "state": "Queued", + "createdTime": "2026-11-20T10:00:00Z", "updatedTime": "2026-11-20T10:00:00Z", + "request": {"requestUrl": f"https://vsp.fake{req.path}", + "requestMethod": req.method, + "requestBody": req.body.decode() if req.body else ""}, + "affectedResources": [], + } + self._pending[jid] = execute + self._polls_left[jid] = self.job_polls + return Reply(202, dict(self.jobs[jid])) + + @route("GET", _P + r"/jobs/(?P\d+)") + def get_job(self, req, sdid, jid): + self._auth(req, sdid) + job = self.jobs.get(int(jid)) + if job is None: + raise _err(404, f"Job {jid} does not exist.", "KART40050-E") + jid_i = int(jid) + if jid_i in self._pending: + if self._polls_left[jid_i] > 0: + self._polls_left[jid_i] -= 1 + job.update(status="Running", state="Started") + else: + execute = self._pending.pop(jid_i) + try: + job.update(status="Completed", state="Succeeded", + affectedResources=execute(), + completedTime="2026-11-20T10:00:05Z") + except FakeError as e: + job.update(status="Completed", state="Failed", + error=e.reply.body, completedTime="2026-11-20T10:00:05Z") + return Reply(200, dict(job)) + + # -- resource-group lock ------------------------------------------------------- + + @route("POST", _P + r"/services/resource-group-service/actions/(?Plock|unlock)/invoke") + def rg_lock(self, req, sdid, act): + token = self._auth(req, sdid) + prefix = self._prefix(sdid) + + def run() -> list[str]: + if act == "lock": + if self.lock_owner not in (None, token): + raise _storage_err("The resource group is locked by another user.", + "2E10", "A002") + self.lock_owner = token + elif self.lock_owner == token: + self.lock_owner = None + return [f"{prefix}/services/resource-group-service"] + + return self._job(req, sdid, token, run, lock_request=True) + + # -- LDEVs ------------------------------------------------------------------ + + def _ldev_view(self, lid: int) -> dict[str, Any]: + ldev = self.ldevs.get(lid) + if ldev is None: + return {"ldevId": lid, "emulationType": NOT_DEFINED, "ssid": "0004", + "resourceGroupId": 0} + paths = [{"portId": port, "hostGroupNumber": num, "hostGroupName": g["name"], + "lun": lun} + for (port, num), g in sorted(self.groups.items()) + for lun, target in sorted(g["luns"].items()) if target == lid] + view = { + "ldevId": lid, "clprId": 0, "emulationType": "OPEN-V-CVS", + "byteFormatCapacity": f"{ldev['blocks'] * 512 / (1 << 30):.2f} G", + "blockCapacity": ldev["blocks"], "numOfPorts": len(paths), + "attributes": ["CVS", "HDP"], "label": ldev["label"], "status": "NML", + "mpBladeId": 0, "ssid": "0004", "poolId": ldev["pool"], + "numOfUsedBlock": 0, "isFullAllocationEnabled": False, + "resourceGroupId": 0, "dataReductionStatus": "DISABLED", + "dataReductionMode": "disabled", "isAluaEnabled": False, + "naaId": self.naa(lid), + } + if paths: + view["ports"] = paths + return view + + def _ldev_id(self, raw: str) -> int: + lid = int(raw) + if lid > _MAX_LDEV: + raise _err(400, f"The value of ldevId ({lid}) is out of range.", "KART40042-E") + return lid + + @route("GET", _P + r"/ldevs/(?P\d+)") + def get_ldev(self, req, sdid, lid): + self._auth(req, sdid) + return Reply(200, self._ldev_view(self._ldev_id(lid))) + + @route("GET", _P + r"/ldevs") + def list_ldevs(self, req, sdid): + self._auth(req, sdid) + option = req.q("ldevOption") + pool = req.q("poolId") + if pool is not None and option != "dpVolume": + raise _err(400, "poolId can be specified only with ldevOption=dpVolume.", + "KART40044-E") + if option not in (None, "defined", "dpVolume"): + raise _err(400, f"fake: ldevOption={option} not implemented", "KART40044-E") + count = int(req.q("count", "100") or 100) + if not 1 <= count <= self.max_count: + raise _err(400, f"The value of count ({count}) is out of range.", "KART40042-E") + head = int(req.q("headLdevId", "0") or 0) + data = [self._ldev_view(lid) for lid in sorted(self.ldevs) + if lid >= head and (pool is None or self.ldevs[lid]["pool"] == int(pool))] + return Reply(200, {"data": data[:count]}) + + @staticmethod + def _blocks(body: dict[str, Any]) -> int: + if "blockCapacity" in body: + return int(body["blockCapacity"]) + m = re.match(r"^(\d+)([KMGT])$", str(body.get("byteFormatCapacity", ""))) + if not m: + raise _err(400, "Specify blockCapacity or byteFormatCapacity.", "KART40041-E") + return int(m.group(1)) * _UNITS[m.group(2)] // 512 + + @route("POST", _P + r"/ldevs") + def post_ldev(self, req, sdid): + token = self._auth(req, sdid) + body = req.json() or {} + prefix = self._prefix(sdid) + if int(body.get("poolId", -1)) not in self.pools: + raise _err(400, f"The specified pool ({body.get('poolId')}) does not exist.", + "KART40045-E") + blocks = self._blocks(body) + if blocks <= 0: + raise _err(400, "The capacity is invalid.", "KART40042-E") + if ("startLdevId" in body) != ("endLdevId" in body): + raise _err(400, "Specify both startLdevId and endLdevId.", "KART40041-E") + + def run() -> list[str]: + if "ldevId" in body: + lid = int(body["ldevId"]) + if lid in self.ldevs: + raise _storage_err(f"LDEV {lid} is already defined.", "2E11", "0011") + else: + lid = self._free_ldev(int(body.get("startLdevId", 0)), + int(body.get("endLdevId", _MAX_LDEV))) + self.ldevs[lid] = {"pool": int(body["poolId"]), "blocks": blocks, "label": ""} + return [f"{prefix}/ldevs/{lid}"] + + return self._job(req, sdid, token, run) + + @route("PUT", _P + r"/ldevs/(?P\d+)") + def put_ldev(self, req, sdid, lid): + token = self._auth(req, sdid) + body = req.json() or {} + lid_i = self._ldev_id(lid) + prefix = self._prefix(sdid) + label = body.get("label") + if label is None: + raise _err(400, "fake: only label changes are implemented", "KART40041-E") + if len(label) > 32: + raise _err(400, "The label must be 32 characters or fewer.", "KART40042-E") + + def run() -> list[str]: + if lid_i not in self.ldevs: + raise _storage_err(f"LDEV {lid_i} is not defined.", "2E10", "0000") + self.ldevs[lid_i]["label"] = label + return [f"{prefix}/ldevs/{lid_i}"] + + return self._job(req, sdid, token, run) + + @route("POST", _P + r"/ldevs/(?P\d+)/actions/expand/invoke") + def expand_ldev(self, req, sdid, lid): + token = self._auth(req, sdid) + lid_i = self._ldev_id(lid) + params = (req.json() or {}).get("parameters") or {} + prefix = self._prefix(sdid) + add = int(params.get("additionalBlockCapacity", 0)) + if add <= 0: + raise _err(400, "additionalBlockCapacity must be positive.", "KART40042-E") + + def run() -> list[str]: + if lid_i not in self.ldevs: + raise _storage_err(f"LDEV {lid_i} is not defined.", "2E10", "0000") + self.ldevs[lid_i]["blocks"] += add + return [f"{prefix}/ldevs/{lid_i}"] + + return self._job(req, sdid, token, run) + + def _paths_of(self, lid: int) -> int: + return sum(1 for g in self.groups.values() for t in g["luns"].values() if t == lid) + + @route("DELETE", _P + r"/ldevs/(?P\d+)") + def delete_ldev(self, req, sdid, lid): + token = self._auth(req, sdid) + lid_i = self._ldev_id(lid) + prefix = self._prefix(sdid) + + def run() -> list[str]: + if lid_i not in self.ldevs: + raise _storage_err(f"LDEV {lid_i} is not defined.", "2E10", "0000") + if self._paths_of(lid_i): + raise _storage_err(f"LU paths are defined for LDEV {lid_i}.", "2E11", "0007") + del self.ldevs[lid_i] + return [f"{prefix}/ldevs/{lid_i}"] + + return self._job(req, sdid, token, run) + + # -- ports and host groups ------------------------------------------------------- + + def _port(self, port: str | None) -> str: + if port not in self.ports: + raise _err(404, f"The specified port ({port}) does not exist.", "KART40050-E") + return port # type: ignore[return-value] + + @route("GET", _P + r"/ports/(?P[^/]+)") + def get_port(self, req, sdid, port): + self._auth(req, sdid) + self._port(port) + info: dict[str, Any] = {"portId": port, "portType": self.ports[port], + "portAttributes": ["TAR"], "portSpeed": "AUT", + "lunSecuritySetting": True} + if self.ports[port] == "FIBRE": + info.update(loopId="EF", fabricMode=True, portConnection="PtoP", + wwn=f"50060e80{self.serial:06x}{list(self.ports).index(port):02x}") + else: + info.update(ipv4Address="192.0.2.20", tcpPort="3260") + return Reply(200, info) + + def _group_view(self, port: str, num: int) -> dict[str, Any]: + g = self.groups[(port, num)] + view: dict[str, Any] = {"hostGroupId": f"{port},{num}", "portId": port, + "hostGroupNumber": num, "hostGroupName": g["name"], + "hostMode": g["mode"], "resourceGroupId": 0} + if g["modeOptions"]: + view["hostModeOptions"] = list(g["modeOptions"]) + if self.ports[port] == "ISCSI": + view["iscsiName"] = f"iqn.1994-04.jp.co.hitachi:rsd.h8m.t.{self.serial:05d}." \ + f"{port[2:].replace('-', '')}{num:03x}" + return view + + def _existing_group(self, port: str | None, num: Any) -> tuple[str, int]: + port = self._port(port) + try: + key = (port, int(num)) + except (TypeError, ValueError) as e: + raise _err(400, "hostGroupNumber is required.", "KART40041-E") from e + if key not in self.groups: + raise _err(404, f"Host group {port},{num} does not exist.", "KART40050-E") + return key + + @route("GET", _P + r"/host-groups") + def list_groups(self, req, sdid): + self._auth(req, sdid) + port = self._port(req.q("portId")) + return Reply(200, {"data": [self._group_view(p, n) for (p, n) in sorted(self.groups) + if p == port]}) + + @route("POST", _P + r"/host-groups") + def post_group(self, req, sdid): + token = self._auth(req, sdid) + body = req.json() or {} + port = self._port(body.get("portId")) + name = str(body.get("hostGroupName") or "") + prefix = self._prefix(sdid) + limit = 32 if self.ports[port] == "ISCSI" else 64 + if not name or len(name) > limit: + raise _err(400, f"hostGroupName must be 1-{limit} characters.", "KART40042-E") + mode = body.get("hostMode", "LINUX/IRIX") + if mode not in ("LINUX/IRIX", "VMWARE_EX", "WIN_EX", "AIX", "HP-UX", "SOLARIS"): + raise _err(400, f"The hostMode ({mode}) is invalid.", "KART40042-E") + + def run() -> list[str]: + if any(p == port and g["name"] == name for (p, _), g in self.groups.items()): + raise _storage_err(f"The host group name {name} is already used on {port}.", + "2E11", "4E00") + num = body.get("hostGroupNumber") + if num is None: + num = next(n for n in range(1, 255) if (port, n) not in self.groups) + self.groups[(port, int(num))] = self._group(name, mode) + self.groups[(port, int(num))]["modeOptions"] = list(body.get("hostModeOptions", [])) + return [f"{prefix}/host-groups/{port},{num}"] + + return self._job(req, sdid, token, run) + + @route("DELETE", _P + r"/host-groups/(?P[^/,]+),(?P\d+)") + def delete_group(self, req, sdid, port, num): + token = self._auth(req, sdid) + key = self._existing_group(port, num) + prefix = self._prefix(sdid) + if key[1] == 0: + raise _err(400, "Host group 0 cannot be deleted.", "KART40042-E") + + def run() -> list[str]: + if self.groups[key]["luns"]: + raise _storage_err(f"LU paths are defined in host group {port},{num}.", + "2E11", "0007") + del self.groups[key] + return [f"{prefix}/host-groups/{port},{num}"] + + return self._job(req, sdid, token, run) + + # -- initiators -------------------------------------------------------------------- + + @route("GET", _P + r"/host-wwns") + def list_wwns(self, req, sdid): + self._auth(req, sdid) + port, num = self._existing_group(req.q("portId"), req.q("hostGroupNumber")) + g = self.groups[(port, num)] + return Reply(200, {"data": [ + {"hostWwnId": f"{port},{num},{w}", "portId": port, "hostGroupNumber": num, + "hostGroupName": g["name"], "hostWwn": w, "wwnNickname": "-"} + for w in g["wwns"]]}) + + @route("POST", _P + r"/host-wwns") + def post_wwn(self, req, sdid): + token = self._auth(req, sdid) + body = req.json() or {} + port, num = self._existing_group(body.get("portId"), body.get("hostGroupNumber")) + wwn = str(body.get("hostWwn", "")).lower() + prefix = self._prefix(sdid) + if self.ports[port] != "FIBRE": + raise _err(400, f"Port {port} is not a Fibre Channel port.", "KART40042-E") + if not re.match(r"^[0-9a-f]{16}$", wwn): + raise _err(400, f"The hostWwn ({wwn}) is invalid.", "KART40042-E") + + def run() -> list[str]: + for (p, n), g in self.groups.items(): + if p == port and wwn in g["wwns"]: + raise _storage_err( + f"The WWN {wwn} is already registered in host group {p},{n}.", + "B957", "4184") + self.groups[(port, num)]["wwns"].append(wwn) + return [f"{prefix}/host-wwns/{port},{num},{wwn}"] + + return self._job(req, sdid, token, run) + + @route("GET", _P + r"/host-iscsis") + def list_iscsis(self, req, sdid): + self._auth(req, sdid) + port, num = self._existing_group(req.q("portId"), req.q("hostGroupNumber")) + g = self.groups[(port, num)] + return Reply(200, {"data": [ + {"hostIscsiId": f"{port},{num},{n}", "portId": port, "hostGroupNumber": num, + "hostGroupName": g["name"], "iscsiName": n, "iscsiNickname": "-"} + for n in g["iscsis"]]}) + + @route("POST", _P + r"/host-iscsis") + def post_iscsi(self, req, sdid): + token = self._auth(req, sdid) + body = req.json() or {} + port, num = self._existing_group(body.get("portId"), body.get("hostGroupNumber")) + name = str(body.get("iscsiName", "")) + prefix = self._prefix(sdid) + if self.ports[port] != "ISCSI": + raise _err(400, f"Port {port} is not an iSCSI port.", "KART40042-E") + if not name.startswith(("iqn.", "eui.")): + raise _err(400, f"The iscsiName ({name}) is invalid.", "KART40042-E") + + def run() -> list[str]: + g = self.groups[(port, num)] + # The same initiator may log in to several targets of a port; only + # a duplicate within one target is refused. + if name.lower() in (n.lower() for n in g["iscsis"]): + raise _storage_err(f"The iSCSI name {name} is already registered.", + "B957", "4185") + g["iscsis"].append(name) + return [f"{prefix}/host-iscsis/{port},{num},{name}"] + + return self._job(req, sdid, token, run) + + # -- LU paths --------------------------------------------------------------------- + + @route("GET", _P + r"/luns") + def list_luns(self, req, sdid): + self._auth(req, sdid) + port, num = self._existing_group(req.q("portId"), req.q("hostGroupNumber")) + g = self.groups[(port, num)] + return Reply(200, {"data": [ + {"lunId": f"{port},{num},{lun}", "portId": port, "hostGroupNumber": num, + "hostMode": g["mode"], "lun": lun, "ldevId": lid, "isCommandDevice": False, + "luHostReserve": {"openSystem": False, "persistent": False, + "pgrKey": False, "mainframe": False, "acaReserve": False}} + for lun, lid in sorted(g["luns"].items())]}) + + @route("POST", _P + r"/luns") + def post_lun(self, req, sdid): + token = self._auth(req, sdid) + body = req.json() or {} + port, num = self._existing_group(body.get("portId"), body.get("hostGroupNumber")) + lid = int(body.get("ldevId", -1)) + prefix = self._prefix(sdid) + lun = body.get("lun") + if lun is not None and not 0 <= int(lun) <= 2047: + raise _err(400, f"The value of lun ({lun}) is out of range.", "KART40042-E") + + def run() -> list[str]: + g = self.groups[(port, num)] + if lid not in self.ldevs: + raise _storage_err(f"LDEV {lid} is not defined.", "2E10", "0000") + if lid in g["luns"].values(): + raise _storage_err(f"LDEV {lid} is already mapped in host group " + f"{port},{num}.", "B958", "0233") + n = int(lun) if lun is not None else next( + i for i in range(2048) if i not in g["luns"]) + if n in g["luns"]: + raise _storage_err(f"LUN {n} is already in use in host group " + f"{port},{num}.", "B958", "0234") + g["luns"][n] = lid + return [f"{prefix}/luns/{port},{num},{n}"] + + return self._job(req, sdid, token, run) + + @route("DELETE", _P + r"/luns/(?P[^/,]+),(?P\d+),(?P\d+)") + def delete_lun(self, req, sdid, port, num, lun): + token = self._auth(req, sdid) + key = self._existing_group(port, num) + prefix = self._prefix(sdid) + if int(lun) not in self.groups[key]["luns"]: + raise _err(404, f"LU path {port},{num},{lun} does not exist.", "KART40050-E") + + def run() -> list[str]: + self.groups[key]["luns"].pop(int(lun), None) + return [f"{prefix}/luns/{port},{num},{lun}"] + + return self._job(req, sdid, token, run) + + +def contract_setup(**options: Any) -> ContractSetup: + fake = FakeHitachiVsp(username="sbadmin", password="vsp-secret") + opts: dict[str, Any] = {"pool_id": 0, "ports": ["CL1-A", "CL2-A", "CL1-B", "CL2-B"]} + opts.update(options) + return ContractSetup( + fake=fake, + config=make_config("hitachi-vsp", "https://vsp.fake.example", **opts), + credential=Credential({"username": SecretStr("sbadmin"), + "password": SecretStr("vsp-secret")}), + bad_credential=Credential({"username": SecretStr("sbadmin"), + "password": SecretStr("wrong")}), + initiators={ + Protocol.ISCSI: ( + (Initiator(protocol=Protocol.ISCSI, address="iqn.2026-01.io.sb:host-a"),), + (Initiator(protocol=Protocol.ISCSI, address="iqn.2026-01.io.sb:host-b"),), + ), + Protocol.FC: ( + (Initiator(protocol=Protocol.FC, address="21:00:00:24:ff:4c:1a:2b"),), + (Initiator(protocol=Protocol.FC, address="21:00:00:24:ff:4c:1a:2c"),), + ), + }, + create_foreign_volume=lambda name, size: fake.add_ldev(name, size), + ) diff --git a/simplyblock_core/storage_arrays/testing/hpe_nimble.py b/simplyblock_core/storage_arrays/testing/hpe_nimble.py new file mode 100644 index 0000000000..f02e5a9728 --- /dev/null +++ b/simplyblock_core/storage_arrays/testing/hpe_nimble.py @@ -0,0 +1,363 @@ +"""Fake HPE Alletra 5000/6000 / Nimble, NimbleOS REST v1 (subset the adapter uses). + +Quirks reproduced: tokens from ``POST /v1/tokens`` checked on ``X-Auth-Token`` +and released by token *id*; ``{"data": ...}`` envelopes on requests and +responses; ``{"messages": [{"code": "SM_...", ...}]}`` errors; 42-hex object +ids; sizes in MiB; volumes that must be offline before deletion and cannot be +offlined or deleted while ACRs exist; FC WWPNs in colon form; and LUN 0 for +every iSCSI ACR with volume-scoped targets. +""" +from __future__ import annotations + +import re +import secrets +from typing import Any + +from pydantic import SecretStr + +from simplyblock_core.credentials import Credential + +from ..base import Initiator, Protocol +from . import ContractSetup, FakeArray, FakeError, Reply, Request, make_config, route + +_ID = r"(?P(?!detail$)[^/]+)" +_ID_RE = re.compile(r"^[0-9a-f]{42}$") +_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9.:\-]{0,214}$") +_WWPN_RE = re.compile(r"^([0-9a-f]{2}:){7}[0-9a-f]{2}$") +_NG_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9.:\-]{0,63}$") + + +def _err(status: int, code: str, text: str) -> FakeError: + return FakeError(status, {"messages": [{"code": code, "severity": "error", "text": text}]}) + + +class FakeHpeNimble(FakeArray): + vendor = "hpe-nimble" + + def __init__(self, username: str = "admin", password: str = "admin", + volume_scoped_targets: bool = True): + super().__init__() + self.username = username + self.password = password + self.volume_scoped_targets = volume_scoped_targets + self.tokens: dict[str, str] = {} # token id -> session_token + self.pools = {self._new_id(0x0a): "default", self._new_id(0x0a): "fast"} + self.perfpolicies = {self._new_id(0x03): "default", self._new_id(0x03): "Oracle OLTP"} + self.volumes: dict[str, dict[str, Any]] = {} # id -> volume + self.groups: dict[str, dict[str, Any]] = {} # id -> initiator group + self.initiators: dict[str, dict[str, Any]] = {} + self.acrs: dict[str, dict[str, Any]] = {} + + def _new_id(self, kind: int) -> str: + # NimbleOS ids: 42 hex chars, group-unique prefix + object type + counter. + return f"06{secrets.token_hex(9)}{kind:02x}{self.next_id():020x}"[:42] + + # -- fake controls ------------------------------------------------------ + + def expire_sessions(self) -> None: + self.tokens.clear() + + def set_credential(self, **fields: str) -> None: + self.username = fields.get("username", self.username) + self.password = fields["password"] + + def add_volume(self, name: str, size: int, pool_id: str | None = None, + perfpolicy_id: str | None = None) -> str: + vid = self._new_id(0x2a) + pool_id = pool_id or next(iter(self.pools)) + perfpolicy_id = perfpolicy_id or next(iter(self.perfpolicies)) + self.volumes[vid] = { + "id": vid, "name": name, "size": -(-size // (1 << 20)), + "serial_number": secrets.token_hex(8) + "6c9ce900" + secrets.token_hex(4), + "target_name": f"iqn.2007-11.com.nimblestorage:{name}-v{secrets.token_hex(8)}", + "online": True, "vol_state": "online", "pool_id": pool_id, + "pool_name": self.pools[pool_id], "perfpolicy_id": perfpolicy_id, + "perfpolicy_name": self.perfpolicies[perfpolicy_id], "access_control_records": [], + } + return vid + + # -- envelope helpers ----------------------------------------------------- + + def _auth(self, req: Request) -> None: + if req.headers.get("X-Auth-Token") not in self.tokens.values(): + raise _err(401, "SM_http_unauthorized", "Unauthorized: session token invalid") + + @staticmethod + def _body(req: Request) -> dict[str, Any]: + body = req.json() + if not isinstance(body, dict) or not isinstance(body.get("data"), dict): + raise _err(400, "SM_missing_arg", "Missing data envelope") + return body["data"] + + @staticmethod + def _page(items: list[dict[str, Any]]) -> Reply: + return Reply(200, {"startRow": 0, "endRow": len(items), "totalRows": len(items), + "data": items}) + + @staticmethod + def _filter(req: Request, items: list[dict[str, Any]]) -> list[dict[str, Any]]: + out = items + for key, values in req.query.items(): + if key in ("startRow", "endRow", "pageSize", "fields", "sortBy"): + continue + out = [i for i in out if str(i.get(key, "")).lower() == values[0].lower()] + return out + + def _get(self, table: dict[str, dict[str, Any]], obj_id: str, what: str) -> dict[str, Any]: + if not _ID_RE.match(obj_id): + raise _err(400, "SM_invalid_arg", f"Invalid {what} id: {obj_id}") + if obj_id not in table: + raise _err(404, "SM_http_not_found", f"Object not found: {what} {obj_id}") + return table[obj_id] + + # -- auth / info ---------------------------------------------------------- + + @route("POST", "/v1/tokens") + def login(self, req): + data = self._body(req) + if data.get("username") != self.username or data.get("password") != self.password: + raise _err(401, "SM_http_unauthorized", "Unauthorized: invalid credentials") + tid, token = self._new_id(0x1f), secrets.token_hex(16) + self.tokens[tid] = token + return Reply(201, {"data": {"id": tid, "session_token": token, + "username": self.username, "app_name": "", + "source_ip": "192.0.2.1"}}) + + @route("DELETE", "/v1/tokens/" + _ID) + def logout(self, req, obj_id): + self._auth(req) + self._get(self.tokens, obj_id, "token") # type: ignore[arg-type] + del self.tokens[obj_id] + return Reply(200, {}) + + @route("GET", "/v1/arrays/detail") + def arrays(self, req): + self._auth(req) + return self._page([{"id": "0906b8bc6e4a3c2a7f000000000000000000000001", + "name": "fake-af40", "model": "AF40", "serial": "AF-123456", + "version": "6.1.2.100-1010", "status": "reachable"}]) + + @route("GET", "/v1/pools/detail") + def pools_detail(self, req): + self._auth(req) + return self._page(self._filter(req, [{"id": k, "name": v} + for k, v in self.pools.items()])) + + @route("GET", "/v1/performance_policies/detail") + def perfpolicies_detail(self, req): + self._auth(req) + return self._page(self._filter(req, [{"id": k, "name": v} + for k, v in self.perfpolicies.items()])) + + # -- volumes ------------------------------------------------------------- + + @route("POST", "/v1/volumes") + def post_volumes(self, req): + self._auth(req) + data = self._body(req) + name, size = data.get("name"), data.get("size") + if not isinstance(name, str) or not _NAME_RE.match(name): + raise _err(400, "SM_invalid_arg", "Invalid argument: name") + if not isinstance(size, int) or size < 1: + raise _err(400, "SM_invalid_arg", "Invalid argument: size (MiB)") + if any(v["name"] == name for v in self.volumes.values()): + raise _err(409, "SM_eexist", f"Object exists: volume {name}") + pool_id, pp_id = data.get("pool_id"), data.get("perfpolicy_id") + if pool_id is not None and pool_id not in self.pools: + raise _err(404, "SM_http_not_found", f"Object not found: pool {pool_id}") + if pp_id is not None and pp_id not in self.perfpolicies: + raise _err(404, "SM_http_not_found", f"Object not found: perfpolicy {pp_id}") + vid = self.add_volume(name, size << 20, pool_id, pp_id) + return Reply(201, {"data": self.volumes[vid]}) + + @route("GET", "/v1/volumes/detail") + def volumes_detail(self, req): + self._auth(req) + return self._page(self._filter(req, list(self.volumes.values()))) + + @route("GET", "/v1/volumes/" + _ID) + def get_volume(self, req, obj_id): + self._auth(req) + return Reply(200, {"data": self._get(self.volumes, obj_id, "volume")}) + + @route("PUT", "/v1/volumes/" + _ID) + def put_volume(self, req, obj_id): + self._auth(req) + vol = self._get(self.volumes, obj_id, "volume") + data = self._body(req) + if "size" in data: + size = data["size"] + if not isinstance(size, int) or size < vol["size"]: + raise _err(400, "SM_vol_size_decreased", + "Volume size cannot be decreased") + vol["size"] = size + if "online" in data: + if not data["online"] and self._vol_acrs(obj_id) and not data.get("force"): + raise _err(409, "SM_vol_has_connections", + "Volume has access control records; cannot offline") + vol["online"] = bool(data["online"]) + vol["vol_state"] = "online" if vol["online"] else "offline" + return Reply(200, {"data": vol}) + + @route("DELETE", "/v1/volumes/" + _ID) + def delete_volume(self, req, obj_id): + self._auth(req) + vol = self._get(self.volumes, obj_id, "volume") + if vol["online"]: + raise _err(409, "SM_vol_online", "Volume must be offline before it can be deleted") + if self._vol_acrs(obj_id): + raise _err(409, "SM_vol_has_acl", "Volume has access control records") + del self.volumes[obj_id] + return Reply(200, {}) + + # -- initiator groups / initiators ---------------------------------------------- + + def _group_view(self, g: dict[str, Any]) -> dict[str, Any]: + members = [i for i in self.initiators.values() if i["initiator_group_id"] == g["id"]] + view = dict(g) + if g["access_protocol"] == "iscsi": + view["iscsi_initiators"] = [{"id": i["id"], "label": i["label"], "iqn": i["iqn"], + "ip_address": "*"} for i in members] + view["fc_initiators"] = None + else: + view["fc_initiators"] = [{"wwpn": i["wwpn"], "alias": ""} for i in members] + view["iscsi_initiators"] = None + return view + + @route("GET", "/v1/initiator_groups/detail") + def groups_detail(self, req): + self._auth(req) + return self._page(self._filter(req, [self._group_view(g) + for g in self.groups.values()])) + + @route("GET", "/v1/initiator_groups/" + _ID) + def get_group(self, req, obj_id): + self._auth(req) + return Reply(200, {"data": self._group_view(self._get(self.groups, obj_id, "group"))}) + + @route("POST", "/v1/initiator_groups") + def post_group(self, req): + self._auth(req) + data = self._body(req) + name, proto = data.get("name"), data.get("access_protocol") + if not isinstance(name, str) or not _NG_NAME_RE.match(name): + raise _err(400, "SM_invalid_arg", "Invalid argument: name") + if proto not in ("iscsi", "fc"): + raise _err(400, "SM_invalid_arg", "Invalid argument: access_protocol") + if any(g["name"] == name for g in self.groups.values()): + raise _err(409, "SM_eexist", f"Object exists: initiator group {name}") + gid = self._new_id(0x02) + self.groups[gid] = {"id": gid, "name": name, "access_protocol": proto, + "description": data.get("description", ""), + "target_subnets": [], "host_type": "auto"} + return Reply(201, {"data": self._group_view(self.groups[gid])}) + + @route("DELETE", "/v1/initiator_groups/" + _ID) + def delete_group(self, req, obj_id): + self._auth(req) + self._get(self.groups, obj_id, "group") + if any(a["initiator_group_id"] == obj_id for a in self.acrs.values()): + raise _err(409, "SM_igrp_has_acl", + "Initiator group is in use by access control records") + for iid in [i for i, v in self.initiators.items() if v["initiator_group_id"] == obj_id]: + del self.initiators[iid] + del self.groups[obj_id] + return Reply(200, {}) + + @route("GET", "/v1/initiators/detail") + def initiators_detail(self, req): + self._auth(req) + return self._page(self._filter(req, list(self.initiators.values()))) + + @route("POST", "/v1/initiators") + def post_initiator(self, req): + self._auth(req) + data = self._body(req) + gid, proto = data.get("initiator_group_id"), data.get("access_protocol") + group = self._get(self.groups, str(gid), "group") + if proto != group["access_protocol"]: + raise _err(400, "SM_invalid_arg", "access_protocol does not match initiator group") + item = {"id": self._new_id(0x04), "access_protocol": proto, + "initiator_group_id": gid, "initiator_group_name": group["name"], + "label": "", "iqn": "", "ip_address": "", "wwpn": "", "alias": ""} + if proto == "iscsi": + iqn, label = data.get("iqn"), data.get("label") + if not iqn or not label or len(label) > 64: + raise _err(400, "SM_missing_arg", "iqn and label are required") + if any(i["iqn"].lower() == iqn.lower() for i in self.initiators.values()): + raise _err(409, "SM_eexist", f"Object exists: initiator {iqn}") + item.update(iqn=iqn, label=label, ip_address=data.get("ip_address", "*")) + else: + wwpn = str(data.get("wwpn", "")) + if not _WWPN_RE.match(wwpn): + raise _err(400, "SM_invalid_arg", "Invalid argument: wwpn (colon form)") + if any(i["wwpn"] == wwpn for i in self.initiators.values()): + raise _err(409, "SM_eexist", f"Object exists: initiator {wwpn}") + item.update(wwpn=wwpn, alias=data.get("alias", "")) + self.initiators[item["id"]] = item + return Reply(201, {"data": item}) + + # -- access control records ------------------------------------------------ + + def _vol_acrs(self, vol_id: str) -> list[dict[str, Any]]: + return [a for a in self.acrs.values() if a["vol_id"] == vol_id] + + @route("GET", "/v1/access_control_records/detail") + def acrs_detail(self, req): + self._auth(req) + return self._page(self._filter(req, list(self.acrs.values()))) + + @route("POST", "/v1/access_control_records") + def post_acr(self, req): + self._auth(req) + data = self._body(req) + vol = self._get(self.volumes, str(data.get("vol_id")), "volume") + group = self._get(self.groups, str(data.get("initiator_group_id")), "group") + if data.get("apply_to", "both") not in ("volume", "snapshot", "both", "pe", "vvol_volume", + "vvol_snapshot"): + raise _err(400, "SM_invalid_arg", "Invalid argument: apply_to") + if any(a["initiator_group_id"] == group["id"] for a in self._vol_acrs(vol["id"])): + raise _err(409, "SM_eexist", "Object exists: access control record") + if group["access_protocol"] == "iscsi" and self.volume_scoped_targets: + lun = 0 + else: + used = {a["lun"] for a in self.acrs.values() + if a["initiator_group_id"] == group["id"]} + lun = next(n for n in range(2048) if n not in used) + aid = self._new_id(0x0d) + self.acrs[aid] = {"id": aid, "vol_id": vol["id"], "vol_name": vol["name"], + "initiator_group_id": group["id"], + "initiator_group_name": group["name"], + "apply_to": data.get("apply_to", "both"), "lun": lun, + "chap_user_id": "", "pe_id": "", "snap_id": ""} + return Reply(201, {"data": self.acrs[aid]}) + + @route("DELETE", "/v1/access_control_records/" + _ID) + def delete_acr(self, req, obj_id): + self._auth(req) + self._get(self.acrs, obj_id, "access control record") + del self.acrs[obj_id] + return Reply(200, {}) + + +def contract_setup() -> ContractSetup: + fake = FakeHpeNimble(username="admin", password="nimble-pw") + return ContractSetup( + fake=fake, + config=make_config("hpe-nimble", "https://nimble.fake.example:5392"), + credential=Credential({"username": SecretStr("admin"), + "password": SecretStr("nimble-pw")}), + bad_credential=Credential({"username": SecretStr("admin"), + "password": SecretStr("wrong")}), + initiators={ + Protocol.ISCSI: ( + (Initiator(protocol=Protocol.ISCSI, address="iqn.2026-01.io.sb:host-a"),), + (Initiator(protocol=Protocol.ISCSI, address="iqn.2026-01.io.sb:host-b"),), + ), + Protocol.FC: ( + (Initiator(protocol=Protocol.FC, address="21:00:00:24:ff:4c:1a:2b"),), + (Initiator(protocol=Protocol.FC, address="21:00:00:24:ff:4c:1a:2c"),), + ), + }, + create_foreign_volume=lambda name, size: fake.add_volume(name, size), + ) diff --git a/simplyblock_core/storage_arrays/testing/hpe_wsapi.py b/simplyblock_core/storage_arrays/testing/hpe_wsapi.py new file mode 100644 index 0000000000..9b93d51bf3 --- /dev/null +++ b/simplyblock_core/storage_arrays/testing/hpe_wsapi.py @@ -0,0 +1,321 @@ +"""Fake HPE WSAPI (Alletra MP / Primera / 3PAR), the subset the adapter uses. + +Quirks reproduced: session keys created with ``POST /api/v1/credentials`` and +checked on ``X-HP3PAR-WSAPI-SessionKey``; ``{"code", "desc"}`` error bodies; +volumes addressed by name with sizes in MiB rounded up to 256 MiB; GROW +taking an increment; host requests using ``iSCSINames``/``FCWWNs`` while +responses report ``iSCSIPaths``/``FCPaths``; VLUN creation answering 201 +with an empty body and a ``Location`` header; and VLUN listings that contain +the template plus one active VLUN per host path. +""" +from __future__ import annotations + +import re +import secrets +from typing import Any +from urllib.parse import unquote + +from pydantic import SecretStr + +from simplyblock_core.credentials import Credential + +from ..base import Initiator, Protocol +from . import ContractSetup, FakeArray, FakeError, Reply, Request, make_config, route + +_A = "/api/v1" +_UNIT_MIB = 256 +_MAX_NAME = 31 +_QUERY_RE = re.compile(r'^"?\s*volumeName\s+EQ\s+(?P\S+?)\s*"?$') + + +def _err(status: int, code: int, desc: str) -> FakeError: + return FakeError(status, {"code": code, "desc": desc}) + + +class FakeHpeWsapi(FakeArray): + vendor = "hpe-wsapi" + + def __init__(self, username: str = "3paradm", password: str = "3pardata", + cpgs: tuple[str, ...] = ("SSD_r6",), paths_per_host: int = 2): + super().__init__() + self.username = username + self.password = password + self.cpgs = set(cpgs) + #: active VLUN entries listed per mapping (one per host port path) + self.paths_per_host = paths_per_host + self.sessions: set[str] = set() + self.volumes: dict[str, dict[str, Any]] = {} # name -> volume + self.hosts: dict[str, dict[str, Any]] = {} # name -> host + self.vluns: list[dict[str, Any]] = [] # templates {volumeName, hostname, lun} + self.created_bodies: list[dict[str, Any]] = [] + + # -- fake controls ------------------------------------------------------ + + def expire_sessions(self) -> None: + self.sessions.clear() + + def set_credential(self, **fields: str) -> None: + self.username = fields.get("username", self.username) + self.password = fields["password"] + + def add_volume(self, name: str, size: int) -> str: + mib = -(-size // (1 << 20)) + mib = -(-mib // _UNIT_MIB) * _UNIT_MIB + self.volumes[name] = { + "id": self.next_id(), "name": name, "sizeMiB": mib, + "wwn": "60002AC" + secrets.token_hex(13).upper()[:25], + "provisioningType": 2, "userCPG": next(iter(self.cpgs)), "state": 1, + "uuid": secrets.token_hex(16), + } + return name + + # -- auth --------------------------------------------------------------- + + def _auth(self, req: Request) -> None: + if req.headers.get("X-HP3PAR-WSAPI-SessionKey") not in self.sessions: + raise _err(401, 6, "invalid session key") + + @route("POST", _A + "/credentials") + def login(self, req): + body = req.json() or {} + if body.get("user") != self.username or body.get("password") != self.password: + raise _err(403, 5, "invalid username or password") + key = "0-" + secrets.token_hex(16) + "-" + secrets.token_hex(4) + self.sessions.add(key) + return Reply(201, {"key": key}) + + @route("DELETE", _A + "/credentials/(?P[^/]+)") + def logout(self, req, key): + key = unquote(key) + if key not in self.sessions: + raise _err(404, 6, "invalid session key") + self.sessions.discard(key) + return Reply(200) + + @route("GET", _A + "/system") + def system(self, req): + self._auth(req) + return Reply(200, {"id": 412345, "name": "fake-b10000", "systemVersion": "10.4.0.123", + "model": "HPE Alletra Storage MP B10000", + "serialNumber": "CZ12345678", "IPv4Addr": "192.0.2.10"}) + + # -- volumes ------------------------------------------------------------- + + def _vol(self, name: str) -> dict[str, Any]: + name = unquote(name) + if name not in self.volumes: + raise _err(404, 23, "volume does not exist") + return self.volumes[name] + + @route("POST", _A + "/volumes") + def post_volumes(self, req): + self._auth(req) + body = req.json() or {} + self.created_bodies.append(body) + name, cpg, size = body.get("name"), body.get("cpg"), body.get("sizeMiB") + if not name or not cpg or not isinstance(size, int): + raise _err(400, 15, "missing required field") + if len(name) > _MAX_NAME: + raise _err(400, 21, "invalid input: string length exceeds limit") + if cpg not in self.cpgs: + raise _err(404, 15, "CPG does not exist") + if name in self.volumes: + raise _err(409, 22, "volume exists") + if size < 1: + raise _err(400, 40, "invalid input: number exceeds expected range") + self.add_volume(name, size << 20) + return Reply(201, None, {"Location": f"{_A}/volumes/{name}"}) + + @route("GET", _A + "/volumes/(?P[^/]+)") + def get_volume(self, req, name): + self._auth(req) + return Reply(200, self._vol(name)) + + @route("PUT", _A + "/volumes/(?P[^/]+)") + def put_volume(self, req, name): + self._auth(req) + vol = self._vol(name) + body = req.json() or {} + if body.get("action") == 3: + delta = body.get("sizeMiB") + if not isinstance(delta, int) or delta <= 0: + raise _err(400, 40, "invalid input: number exceeds expected range") + vol["sizeMiB"] = -(-(vol["sizeMiB"] + delta) // _UNIT_MIB) * _UNIT_MIB + return Reply(200) + raise _err(400, 29, "invalid input: unsupported action") + + @route("DELETE", _A + "/volumes/(?P[^/]+)") + def delete_volume(self, req, name): + self._auth(req) + vol = self._vol(name) + if any(v["volumeName"] == vol["name"] for v in self.vluns): + raise _err(409, 34, "volume is exported (has VLUNs)") + del self.volumes[vol["name"]] + return Reply(200) + + # -- hosts ---------------------------------------------------------------- + + def _host(self, name: str) -> dict[str, Any]: + name = unquote(name) + if name not in self.hosts: + raise _err(404, 17, "host does not exist") + return self.hosts[name] + + def _claim(self, host: str, body: dict[str, Any]) -> None: + iqns = [str(i) for i in body.get("iSCSINames") or []] + wwns = [str(w).upper().replace(":", "") for w in body.get("FCWWNs") or []] + for w in wwns: + if not re.fullmatch(r"[0-9A-F]{16}", w): + raise _err(400, 32, "invalid WWN") + for other in self.hosts.values(): + if other["name"] == host: + continue + taken = ({p["name"].lower() for p in other["iSCSIPaths"]} & {i.lower() for i in iqns} + or {p["wwn"] for p in other["FCPaths"]} & set(wwns)) + if taken: + raise _err(409, 73, f"path {min(taken)} is already used by " + f"host {other['name']}") + h = self.hosts[host] + for i in iqns: + if i.lower() not in {p["name"].lower() for p in h["iSCSIPaths"]}: + h["iSCSIPaths"].append({"name": i, "IPAddr": "0.0.0.0", "hostSpeed": 0}) + for w in wwns: + if w not in {p["wwn"] for p in h["FCPaths"]}: + h["FCPaths"].append({"wwn": w, "hostSpeed": 0}) + + @route("POST", _A + "/hosts") + def post_hosts(self, req): + self._auth(req) + body = req.json() or {} + name = body.get("name") + if not name: + raise _err(400, 15, "missing required field") + if len(name) > _MAX_NAME: + raise _err(400, 21, "invalid input: string length exceeds limit") + if name in self.hosts: + raise _err(409, 16, "host exists") + if body.get("iSCSINames") and body.get("FCWWNs"): + # Mirrors the adapter's conservative reading: one path type per request. + raise _err(400, 28, "invalid input: iSCSINames and FCWWNs are exclusive") + self.hosts[name] = {"id": self.next_id(), "name": name, + "persona": body.get("persona", 2), + "iSCSIPaths": [], "FCPaths": [], "descriptors": {}} + try: + self._claim(name, body) + except FakeError: + del self.hosts[name] + raise + return Reply(201, None, {"Location": f"{_A}/hosts/{name}"}) + + @route("GET", _A + "/hosts/(?P[^/]+)") + def get_host(self, req, name): + self._auth(req) + return Reply(200, self._host(name)) + + @route("PUT", _A + "/hosts/(?P[^/]+)") + def put_host(self, req, name): + self._auth(req) + host = self._host(name) + body = req.json() or {} + if body.get("pathOperation") != 1: + raise _err(400, 29, "invalid input: unsupported pathOperation") + if body.get("iSCSINames") and body.get("FCWWNs"): + raise _err(400, 28, "invalid input: iSCSINames and FCWWNs are exclusive") + self._claim(host["name"], body) + return Reply(200) + + @route("DELETE", _A + "/hosts/(?P[^/]+)") + def delete_host(self, req, name): + self._auth(req) + host = self._host(name) + if any(v["hostname"] == host["name"] for v in self.vluns): + raise _err(409, 26, "host has exported VLUNs") + del self.hosts[host["name"]] + return Reply(200) + + # -- VLUNs ------------------------------------------------------------------ + + def _vlun_members(self, vol: str | None) -> list[dict[str, Any]]: + out = [] + for t in self.vluns: + if vol is not None and t["volumeName"] != vol: + continue + v = self.volumes[t["volumeName"]] + base = {"lun": t["lun"], "volumeName": t["volumeName"], "hostname": t["hostname"], + "volumeWWN": v["wwn"], "type": 4} + out.append({**base, "active": False}) + for port in range(self.paths_per_host): + out.append({**base, "active": True, "remoteName": f"path{port}", + "portPos": {"node": port, "slot": 2, "cardPort": 1}}) + return out + + @route("GET", _A + "/vluns") + def get_vluns(self, req): + self._auth(req) + query = req.q("query") + vol = None + if query is not None: + m = _QUERY_RE.match(query) + if not m: + raise _err(400, 92, "invalid query") + vol = m["vol"] + members = self._vlun_members(vol) + return Reply(200, {"total": len(members), "members": members}) + + @route("POST", _A + "/vluns") + def post_vluns(self, req): + self._auth(req) + body = req.json() or {} + vol, host = body.get("volumeName"), body.get("hostname") + if vol not in self.volumes: + raise _err(404, 23, "volume does not exist") + if host not in self.hosts: + raise _err(404, 17, "host does not exist") + if any(t["volumeName"] == vol and t["hostname"] == host for t in self.vluns): + raise _err(409, 29, "VLUN exists") + used = {t["lun"] for t in self.vluns if t["hostname"] == host} + start = int(body.get("lun", 0)) + if body.get("autoLun"): + lun = next(n for n in range(start, 16384) if n not in used) + elif start in used: + raise _err(409, 29, "LUN already in use") + else: + lun = start + self.vluns.append({"volumeName": vol, "hostname": host, "lun": lun}) + return Reply(201, None, {"Location": f"{_A}/vluns/{vol},{lun},{host}"}) + + @route("DELETE", _A + "/vluns/(?P[^/]+)") + def delete_vlun(self, req, spec): + self._auth(req) + parts = unquote(spec).split(",") + if len(parts) != 3 or not parts[1].isdigit(): + raise _err(400, 28, "invalid VLUN id") + vol, lun, host = parts[0], int(parts[1]), parts[2] + for t in self.vluns: + if t["volumeName"] == vol and t["lun"] == lun and t["hostname"] == host: + self.vluns.remove(t) + return Reply(200) + raise _err(404, 19, "VLUN does not exist") + + +def contract_setup() -> ContractSetup: + fake = FakeHpeWsapi(username="3paradm", password="wsapi-pw") + return ContractSetup( + fake=fake, + config=make_config("hpe-wsapi", "https://wsapi.fake.example:443", cpg="SSD_r6"), + credential=Credential({"username": SecretStr("3paradm"), + "password": SecretStr("wsapi-pw")}), + bad_credential=Credential({"username": SecretStr("3paradm"), + "password": SecretStr("wrong")}), + initiators={ + Protocol.ISCSI: ( + (Initiator(protocol=Protocol.ISCSI, address="iqn.2026-01.io.sb:host-a"),), + (Initiator(protocol=Protocol.ISCSI, address="iqn.2026-01.io.sb:host-b"),), + ), + Protocol.FC: ( + (Initiator(protocol=Protocol.FC, address="21:00:00:24:ff:4c:1a:2b"),), + (Initiator(protocol=Protocol.FC, address="21:00:00:24:ff:4c:1a:2c"),), + ), + }, + create_foreign_volume=lambda name, size: fake.add_volume(name, size), + ) diff --git a/simplyblock_core/storage_arrays/testing/huawei_dorado.py b/simplyblock_core/storage_arrays/testing/huawei_dorado.py new file mode 100644 index 0000000000..408f6d22f5 --- /dev/null +++ b/simplyblock_core/storage_arrays/testing/huawei_dorado.py @@ -0,0 +1,589 @@ +"""Fake Huawei OceanStor Dorado DeviceManager REST API (the subset the adapter uses). + +Quirks reproduced: + +* every answer is HTTP 200 with ``{"data": ..., "error": {"code", "description"}}``; + failures only show in ``error.code``; a query matching nothing omits ``data``; +* login at ``/deviceManager/rest/xx/sessions`` returns ``deviceid`` + + ``iBaseToken``; later calls must use ``/deviceManager/rest//`` and + the ``iBaseToken`` header, else ``-401``; wrong password is 1077987870; +* every value is a string; LUN ``CAPACITY`` is in 512-byte sectors; +* initiators are free-standing objects bound to a host via ``PARENTID``; +* mapping is host group + LUN group + mapping view; a host can be in one host + group only; host LUN ids are assigned when a LUN becomes visible to a host + and reported inside the ``ASSOCIATEMETADATA`` JSON string. + +Codes marked "unverified" below are stand-ins: the real array refuses those +operations, but we do not know with which code. The adapter must not depend +on them. +""" +from __future__ import annotations + +import json +import secrets +from typing import Any + +from pydantic import SecretStr + +from simplyblock_core.credentials import Credential + +from ..base import Initiator, Protocol +from . import ContractSetup, FakeArray, FakeError, Reply, Request, make_config, route + +_D = r"/deviceManager/rest/(?P[^/]+)" + +UNAUTHORIZED = -401 +WRONG_PASSWORD = 1077987870 +OBJECT_NOT_EXIST = 1077948996 +OBJECT_NAME_EXISTS = 1077948993 +OBJECT_ID_NOT_UNIQUE = 1077948997 +LUN_NOT_EXIST = 1077936859 +LUN_ALREADY_IN_GROUP = 1077936862 +HOST_NOT_EXIST = 1077937498 +HOSTGROUP_NOT_EXIST = 1077937500 +HOST_ALREADY_IN_GROUP = 1077937501 +HOST_NOT_IN_GROUP = 1073745412 +HOSTGROUP_NOT_IN_VIEW = 1073804552 +LUNGROUP_NOT_IN_VIEW = 1073804554 +HOSTGROUP_ALREADY_IN_VIEW = 1073804556 +LUNGROUP_ALREADY_IN_VIEW = 1073804560 +MAPPINGVIEW_NOT_EXIST = 1077951819 +PARAMETER_INCORRECT = 50331651 +#: unverified: object still in use (LUN in a group, host with initiators, ...) +IN_USE = 1077949000 +#: unverified: host already in another host group / initiator bound elsewhere +ALREADY_ASSOCIATED = 1077949002 + + +def _fail(code: int, description: str) -> FakeError: + return FakeError(200, {"data": {}, "error": {"code": code, "description": description, + "suggestion": ""}}) + + +def _ok(data: Any = None) -> Reply: + body: dict[str, Any] = {"error": {"code": 0, "description": "0"}} + if data is not None and data != []: + body["data"] = data + return Reply(200, body) + + +def _filter_name(req: Request) -> str | None: + f = req.q("filter") + if not f: + return None + key, _, value = f.partition("::") + if key != "NAME": + raise _fail(PARAMETER_INCORRECT, "The entered parameter is incorrect.") + return value + + +class FakeHuaweiDorado(FakeArray): + vendor = "huawei-dorado" + + def __init__(self, username: str = "admin", password: str = "Admin@storage1", + pools: tuple[str, ...] = ("StoragePool001",)): + super().__init__() + self.username = username + self.password = password + self.device_id = "2102353GTH10L8000008" + self.tokens: set[str] = set() + self.pools = {str(i): {"ID": str(i), "NAME": n, "USAGETYPE": "1"} + for i, n in enumerate(pools)} + self.luns: dict[str, dict[str, Any]] = {} + self.hosts: dict[str, dict[str, Any]] = {} + self.hostgroups: dict[str, dict[str, Any]] = {} # + "hosts": set + self.lungroups: dict[str, dict[str, Any]] = {} # + "luns": set + self.views: dict[str, dict[str, Any]] = {} # + "hostgroups", "lungroups" + self.initiators: dict[str, dict[str, dict[str, Any]]] = { + "iscsi_initiator": {}, "fc_initiator": {}} + self.host_lun_ids: dict[tuple[str, str], int] = {} + + # -- fake controls ------------------------------------------------------------- + + def expire_sessions(self) -> None: + self.tokens.clear() + + def set_credential(self, **fields: str) -> None: + self.username = fields["username"] + self.password = fields["password"] + + def add_volume(self, name: str, size: int) -> str: + lid = str(self.next_id()) + pool = next(iter(self.pools.values())) + self.luns[lid] = { + "ID": lid, "NAME": name, "TYPE": "11", "PARENTID": pool["ID"], + "PARENTNAME": pool["NAME"], "CAPACITY": str(size // 512), "ALLOCTYPE": "1", + "SECTORSIZE": "512", "HEALTHSTATUS": "1", "RUNNINGSTATUS": "27", + "WWN": "6" + secrets.token_hex(4) + "1001f4e7d" + secrets.token_hex(5) + + f"{int(lid):08x}"[:4], + "DESCRIPTION": "", "ISADD2LUNGROUP": "false"} + return lid + + # -- auth ---------------------------------------------------------------------- + + def _auth(self, req: Request, dev: str) -> None: + if dev != self.device_id or req.headers.get("iBaseToken") not in self.tokens: + raise _fail(UNAUTHORIZED, "The user is not logged in or the session has expired.") + + @route("POST", r"/deviceManager/rest/xx/sessions") + def login(self, req): + body = req.json() or {} + if body.get("username") != self.username or body.get("password") != self.password: + raise _fail(WRONG_PASSWORD, "The user name or password is incorrect.") + if str(body.get("scope")) not in ("0", "1"): + raise _fail(PARAMETER_INCORRECT, "The entered parameter is incorrect.") + token = secrets.token_hex(16) + self.tokens.add(token) + reply = _ok({"deviceid": self.device_id, "iBaseToken": token, "accountstate": 1, + "lastloginip": "10.0.0.1", "level": 2, "pwdchangetime": -1, + "usergroup": "", "userid": body["username"], "username": body["username"], + "userscope": "0"}) + reply.headers["Set-Cookie"] = f"session={secrets.token_hex(8)}; Secure; HttpOnly" + return reply + + @route("DELETE", _D + "/sessions") + def logout(self, req, dev): + self.tokens.discard(req.headers.get("iBaseToken")) + return _ok() + + @route("GET", _D + "/system/") + def system(self, req, dev): + self._auth(req, dev) + return _ok({"ID": self.device_id, "NAME": "fake-dorado", "TYPE": "201", + "PRODUCTMODE": "811", "productModeString": "OceanStor Dorado 5000 V6", + "PRODUCTVERSION": "V600R005C20", "pointRelease": "6.1.5", + "HEALTHSTATUS": "1", "RUNNINGSTATUS": "1"}) + + @route("GET", _D + "/storagepool") + def storagepool(self, req, dev): + self._auth(req, dev) + name = _filter_name(req) + return _ok([p for p in self.pools.values() if name is None or p["NAME"] == name]) + + # -- LUNs -------------------------------------------------------------------------- + + def _lun(self, lid: str) -> dict[str, Any]: + if lid not in self.luns: + raise _fail(LUN_NOT_EXIST, "The LUN does not exist.") + return self.luns[lid] + + @route("GET", _D + "/lun") + def get_luns(self, req, dev): + self._auth(req, dev) + name = _filter_name(req) + return _ok([lun for lun in self.luns.values() if name is None or lun["NAME"] == name]) + + @route("POST", _D + "/lun") + def post_lun(self, req, dev): + self._auth(req, dev) + b = req.json() or {} + name, cap = b.get("NAME"), b.get("CAPACITY") + if not name or len(name) > 31 or not isinstance(cap, int) or cap <= 0: + raise _fail(PARAMETER_INCORRECT, "The entered parameter is incorrect.") + if str(b.get("PARENTID")) not in self.pools: + raise _fail(OBJECT_NOT_EXIST, "The specified storage pool does not exist.") + if any(lun["NAME"] == name for lun in self.luns.values()): + raise _fail(OBJECT_NAME_EXISTS, "The name already exists.") + lid = self.add_volume(name, cap * 512) + self.luns[lid]["PARENTID"] = str(b["PARENTID"]) + self.luns[lid]["PARENTNAME"] = self.pools[str(b["PARENTID"])]["NAME"] + self.luns[lid]["ALLOCTYPE"] = str(b.get("ALLOCTYPE", 1)) + return _ok(self.luns[lid]) + + @route("GET", _D + r"/lun/(?P\d+)") + def get_lun(self, req, dev, lid): + self._auth(req, dev) + return _ok(self._lun(lid)) + + @route("PUT", _D + "/lun/expand") + def expand_lun(self, req, dev): + self._auth(req, dev) + b = req.json() or {} + lun = self._lun(str(b.get("ID"))) + cap = b.get("CAPACITY") + if not isinstance(cap, int) or cap < int(lun["CAPACITY"]): + raise _fail(PARAMETER_INCORRECT, "The entered parameter is incorrect.") + lun["CAPACITY"] = str(cap) + return _ok() + + @route("DELETE", _D + r"/lun/(?P\d+)") + def delete_lun(self, req, dev, lid): + self._auth(req, dev) + self._lun(lid) + if any(lid in g["luns"] for g in self.lungroups.values()): + raise _fail(IN_USE, "The LUN is in a LUN group.") + del self.luns[lid] + return _ok() + + @route("GET", _D + "/lun/associate") + def lun_associate(self, req, dev): + self._auth(req, dev) + if req.q("ASSOCIATEOBJTYPE") != "21": + raise _fail(PARAMETER_INCORRECT, "The entered parameter is incorrect.") + hid = req.q("ASSOCIATEOBJID") or "" + if hid not in self.hosts: + raise _fail(HOST_NOT_EXIST, "The host does not exist.") + rows = [] + for (h, lid), n in sorted(self.host_lun_ids.items()): + if h == hid: + row = dict(self.luns[lid]) + row["ASSOCIATEMETADATA"] = json.dumps({"HostLUNID": n, + "mappingviewId": self._view_of(hid)}) + rows.append(row) + return _ok(rows) + + # -- hosts ---------------------------------------------------------------------------- + + def _host(self, hid: str) -> dict[str, Any]: + if hid not in self.hosts: + raise _fail(OBJECT_NOT_EXIST, "The object does not exist.") + return self.hosts[hid] + + @route("GET", _D + "/host") + def get_hosts(self, req, dev): + self._auth(req, dev) + name = _filter_name(req) + return _ok([h for h in self.hosts.values() if name is None or h["NAME"] == name]) + + @route("POST", _D + "/host") + def post_host(self, req, dev): + self._auth(req, dev) + b = req.json() or {} + name = b.get("NAME") + if not name or len(name) > 31: + raise _fail(PARAMETER_INCORRECT, "The entered parameter is incorrect.") + if any(h["NAME"] == name for h in self.hosts.values()): + raise _fail(OBJECT_NAME_EXISTS, "The name already exists.") + hid = str(self.next_id()) + self.hosts[hid] = {"ID": hid, "NAME": name, "TYPE": "21", + "OPERATIONSYSTEM": str(b.get("OPERATIONSYSTEM", 0)), + "ISADD2HOSTGROUP": "false", "HEALTHSTATUS": "1", + "RUNNINGSTATUS": "1", "DESCRIPTION": b.get("DESCRIPTION", "")} + return _ok(self.hosts[hid]) + + @route("GET", _D + r"/host/(?P\d+)") + def get_host(self, req, dev, hid): + self._auth(req, dev) + return _ok(self._host(hid)) + + @route("DELETE", _D + r"/host/(?P\d+)") + def delete_host(self, req, dev, hid): + self._auth(req, dev) + if hid not in self.hosts: + raise _fail(HOST_NOT_EXIST, "The host does not exist.") + if any(hid in g["hosts"] for g in self.hostgroups.values()): + raise _fail(IN_USE, "The host is in a host group.") + if any(i["PARENTID"] == hid for c in self.initiators.values() for i in c.values()): + raise _fail(IN_USE, "The host has initiators.") + del self.hosts[hid] + return _ok() + + @route("DELETE", _D + "/host/associate") + def host_leave_group(self, req, dev): + self._auth(req, dev) + b = req.json() or {} + g = self.hostgroups.get(str(b.get("ID"))) + if g is None: + raise _fail(HOSTGROUP_NOT_EXIST, "The host group does not exist.") + hid = str(b.get("ASSOCIATEOBJID")) + if hid not in g["hosts"]: + raise _fail(HOST_NOT_IN_GROUP, "The host is not in the host group.") + g["hosts"].discard(hid) + self.hosts[hid]["ISADD2HOSTGROUP"] = "false" + self._refresh() + return _ok() + + # -- initiators ------------------------------------------------------------------------- + + def _ini_lookup(self, coll: str, iid: str) -> dict[str, Any] | None: + for k, v in self.initiators[coll].items(): + if k.lower() == iid.lower(): + return v + return None + + @route("GET", _D + r"/(?Piscsi_initiator|fc_initiator)") + def list_initiators(self, req, dev, coll): + self._auth(req, dev) + parent = req.q("PARENTID") + return _ok([i for i in self.initiators[coll].values() + if parent is None or i["PARENTID"] == parent]) + + @route("POST", _D + r"/(?Piscsi_initiator|fc_initiator)") + def add_initiator(self, req, dev, coll): + self._auth(req, dev) + b = req.json() or {} + iid = str(b.get("ID") or "") + if coll == "fc_initiator" and (len(iid) != 16 or any( + c not in "0123456789abcdef" for c in iid)): + raise _fail(PARAMETER_INCORRECT, "The entered parameter is incorrect.") + if not iid: + raise _fail(PARAMETER_INCORRECT, "The entered parameter is incorrect.") + if self._ini_lookup(coll, iid) is not None: + raise _fail(OBJECT_ID_NOT_UNIQUE, "The ID already exists.") + self.initiators[coll][iid] = { + "ID": iid, "TYPE": "222" if coll == "iscsi_initiator" else "223", + "ISFREE": "true", "PARENTID": "", "PARENTNAME": "", "PARENTTYPE": "", + "RUNNINGSTATUS": "28", "HEALTHSTATUS": "1", "MULTIPATHTYPE": "0"} + return _ok(self.initiators[coll][iid]) + + @route("GET", _D + r"/(?Piscsi_initiator|fc_initiator)/(?P[^/]+)") + def get_initiator(self, req, dev, coll, iid): + self._auth(req, dev) + ini = self._ini_lookup(coll, iid) + if ini is None: + raise _fail(OBJECT_NOT_EXIST, "The object does not exist.") + return _ok(ini) + + @route("PUT", _D + r"/(?Piscsi_initiator|fc_initiator)/(?P[^/]+)") + def put_initiator(self, req, dev, coll, iid): + self._auth(req, dev) + b = req.json() or {} + if iid in ("remove_iscsi_from_host", "remove_fc_from_host"): + ini = self._ini_lookup(coll, str(b.get("ID") or "")) + if ini is None: + raise _fail(OBJECT_NOT_EXIST, "The object does not exist.") + ini.update(ISFREE="true", PARENTID="", PARENTNAME="", PARENTTYPE="") + return _ok() + ini = self._ini_lookup(coll, iid) + if ini is None: + raise _fail(OBJECT_NOT_EXIST, "The object does not exist.") + if "PARENTID" in b: + hid = str(b["PARENTID"]) + host = self._host(hid) + if str(b.get("PARENTTYPE")) != "21": + raise _fail(PARAMETER_INCORRECT, "The entered parameter is incorrect.") + if ini["ISFREE"] == "false" and ini["PARENTID"] != hid: + raise _fail(ALREADY_ASSOCIATED, "The initiator has been added to another host.") + ini.update(ISFREE="false", PARENTID=hid, PARENTNAME=host["NAME"], PARENTTYPE="21") + return _ok() + + # -- groups and views --------------------------------------------------------------------- + + def _create_named(self, store: dict[str, dict[str, Any]], req: Request, + obj_type: str, **sets: set) -> Reply: + b = req.json() or {} + name = b.get("NAME") + if not name or len(name) > 31: + raise _fail(PARAMETER_INCORRECT, "The entered parameter is incorrect.") + if any(o["NAME"] == name for o in store.values()): + raise _fail(OBJECT_NAME_EXISTS, "The name already exists.") + oid = str(self.next_id()) + store[oid] = {"ID": oid, "NAME": name, "TYPE": obj_type, "DESCRIPTION": "", **sets} + return _ok(self._public(store[oid])) + + @staticmethod + def _public(obj: dict[str, Any]) -> dict[str, Any]: + return {k: v for k, v in obj.items() if not isinstance(v, set)} + + def _list_named(self, store, req) -> Reply: + name = _filter_name(req) + return _ok([self._public(o) for o in store.values() if name is None or o["NAME"] == name]) + + @route("GET", _D + "/hostgroup") + def get_hostgroups(self, req, dev): + self._auth(req, dev) + return self._list_named(self.hostgroups, req) + + @route("POST", _D + "/hostgroup") + def post_hostgroup(self, req, dev): + self._auth(req, dev) + return self._create_named(self.hostgroups, req, "14", hosts=set()) + + @route("DELETE", _D + r"/hostgroup/(?P\d+)") + def delete_hostgroup(self, req, dev, gid): + self._auth(req, dev) + g = self.hostgroups.get(gid) + if g is None: + raise _fail(HOSTGROUP_NOT_EXIST, "The host group does not exist.") + if g["hosts"] or any(gid in v["hostgroups"] for v in self.views.values()): + raise _fail(IN_USE, "The host group is in use.") + del self.hostgroups[gid] + return _ok() + + @route("POST", _D + "/hostgroup/associate") + def hostgroup_add_host(self, req, dev): + self._auth(req, dev) + b = req.json() or {} + g = self.hostgroups.get(str(b.get("ID"))) + if g is None: + raise _fail(HOSTGROUP_NOT_EXIST, "The host group does not exist.") + hid = str(b.get("ASSOCIATEOBJID")) + if hid not in self.hosts: + raise _fail(HOST_NOT_EXIST, "The host does not exist.") + if hid in g["hosts"]: + raise _fail(HOST_ALREADY_IN_GROUP, "The host already exists in the host group.") + if any(hid in o["hosts"] for o in self.hostgroups.values()): + raise _fail(ALREADY_ASSOCIATED, "The host already belongs to another host group.") + g["hosts"].add(hid) + self.hosts[hid]["ISADD2HOSTGROUP"] = "true" + self._refresh() + return _ok() + + @route("GET", _D + "/hostgroup/associate") + def hostgroups_of(self, req, dev): + self._auth(req, dev) + t, oid = req.q("ASSOCIATEOBJTYPE"), req.q("ASSOCIATEOBJID") or "" + if t == "21": + return _ok([self._public(g) for g in self.hostgroups.values() if oid in g["hosts"]]) + if t == "245": + v = self.views.get(oid) + return _ok([self._public(self.hostgroups[g]) for g in v["hostgroups"]] if v else []) + raise _fail(PARAMETER_INCORRECT, "The entered parameter is incorrect.") + + @route("GET", _D + "/lungroup") + def get_lungroups(self, req, dev): + self._auth(req, dev) + return self._list_named(self.lungroups, req) + + @route("POST", _D + "/lungroup") + def post_lungroup(self, req, dev): + self._auth(req, dev) + return self._create_named(self.lungroups, req, "256", luns=set()) + + @route("DELETE", _D + r"/lungroup/(?P\d+)") + def delete_lungroup(self, req, dev, gid): + self._auth(req, dev) + g = self.lungroups.get(gid) + if g is None: + raise _fail(OBJECT_NOT_EXIST, "The object does not exist.") + if g["luns"] or any(gid in v["lungroups"] for v in self.views.values()): + raise _fail(IN_USE, "The LUN group is in use.") + del self.lungroups[gid] + return _ok() + + @route("POST", _D + "/lungroup/associate") + def lungroup_add_lun(self, req, dev): + self._auth(req, dev) + b = req.json() or {} + g = self.lungroups.get(str(b.get("ID"))) + if g is None: + raise _fail(OBJECT_NOT_EXIST, "The object does not exist.") + if str(b.get("ASSOCIATEOBJTYPE")) != "11": + raise _fail(PARAMETER_INCORRECT, "The entered parameter is incorrect.") + lid = str(b.get("ASSOCIATEOBJID")) + self._lun(lid) + if lid in g["luns"]: + raise _fail(LUN_ALREADY_IN_GROUP, "The LUN is already in the LUN group.") + g["luns"].add(lid) + self.luns[lid]["ISADD2LUNGROUP"] = "true" + self._refresh() + return _ok() + + @route("DELETE", _D + "/lungroup/associate") + def lungroup_remove_lun(self, req, dev): + self._auth(req, dev) + b = req.json() or {} + g = self.lungroups.get(str(b.get("ID"))) + lid = str(b.get("ASSOCIATEOBJID")) + if g is None or lid not in g["luns"]: + raise _fail(OBJECT_NOT_EXIST, "The object does not exist.") + g["luns"].discard(lid) + if lid in self.luns and not any(lid in o["luns"] for o in self.lungroups.values()): + self.luns[lid]["ISADD2LUNGROUP"] = "false" + self._refresh() + return _ok() + + @route("GET", _D + "/lungroup/associate") + def lungroups_of(self, req, dev): + self._auth(req, dev) + if req.q("ASSOCIATEOBJTYPE") != "11": + raise _fail(PARAMETER_INCORRECT, "The entered parameter is incorrect.") + lid = req.q("ASSOCIATEOBJID") or "" + self._lun(lid) + return _ok([self._public(g) for g in self.lungroups.values() if lid in g["luns"]]) + + @route("GET", _D + "/mappingview") + def get_views(self, req, dev): + self._auth(req, dev) + return self._list_named(self.views, req) + + @route("POST", _D + "/mappingview") + def post_view(self, req, dev): + self._auth(req, dev) + return self._create_named(self.views, req, "245", hostgroups=set(), lungroups=set()) + + @route("DELETE", _D + r"/mappingview/(?P\d+)") + def delete_view(self, req, dev, vid): + self._auth(req, dev) + v = self.views.get(vid) + if v is None: + raise _fail(MAPPINGVIEW_NOT_EXIST, "The mapping view does not exist.") + if v["hostgroups"] or v["lungroups"]: + raise _fail(IN_USE, "The mapping view is in use.") + del self.views[vid] + return _ok() + + @route("PUT", _D + r"/mappingview/(?Pcreate_associate|remove_associate)") + def view_associate(self, req, dev, action): + self._auth(req, dev) + b = req.json() or {} + v = self.views.get(str(b.get("ID"))) + if v is None: + raise _fail(MAPPINGVIEW_NOT_EXIST, "The mapping view does not exist.") + t, oid = str(b.get("ASSOCIATEOBJTYPE")), str(b.get("ASSOCIATEOBJID")) + if t == "14": + key, store, already, missing = ("hostgroups", self.hostgroups, + HOSTGROUP_ALREADY_IN_VIEW, HOSTGROUP_NOT_IN_VIEW) + elif t == "256": + key, store, already, missing = ("lungroups", self.lungroups, + LUNGROUP_ALREADY_IN_VIEW, LUNGROUP_NOT_IN_VIEW) + else: + raise _fail(PARAMETER_INCORRECT, "The entered parameter is incorrect.") + if oid not in store: + raise _fail(OBJECT_NOT_EXIST, "The object does not exist.") + if action == "create_associate": + if oid in v[key]: + raise _fail(already, "The group is already in the mapping view.") + if v[key]: + raise _fail(PARAMETER_INCORRECT, "A mapping view holds one group of each kind.") + v[key].add(oid) + else: + if oid not in v[key]: + raise _fail(missing, "The group is not in the mapping view.") + v[key].discard(oid) + self._refresh() + return _ok() + + # -- visibility ------------------------------------------------------------------------------- + + def _view_of(self, hid: str) -> str: + for v in self.views.values(): + if any(hid in self.hostgroups[g]["hosts"] for g in v["hostgroups"]): + return v["ID"] + return "" + + def _refresh(self) -> None: + """Recompute which LUNs each host sees; keep existing host LUN ids.""" + visible: set[tuple[str, str]] = set() + for v in self.views.values(): + hosts = {h for g in v["hostgroups"] for h in self.hostgroups[g]["hosts"]} + luns = {lun for g in v["lungroups"] for lun in self.lungroups[g]["luns"]} + visible |= {(h, lun) for h in hosts for lun in luns} + self.host_lun_ids = {k: n for k, n in self.host_lun_ids.items() if k in visible} + for h, lun in sorted(visible - set(self.host_lun_ids)): + used = {n for (hh, _), n in self.host_lun_ids.items() if hh == h} + self.host_lun_ids[(h, lun)] = next(n for n in range(1, 4096) if n not in used) + + +def contract_setup() -> ContractSetup: + fake = FakeHuaweiDorado(username="admin", password="Admin@storage1") + return ContractSetup( + fake=fake, + config=make_config("huawei-dorado", "https://dorado.fake.example:8088", + storage_pool="StoragePool001"), + credential=Credential({"username": SecretStr("admin"), + "password": SecretStr("Admin@storage1")}), + bad_credential=Credential({"username": SecretStr("admin"), + "password": SecretStr("wrong")}), + initiators={ + Protocol.ISCSI: ( + (Initiator(protocol=Protocol.ISCSI, address="iqn.2026-01.io.sb:host-a"),), + (Initiator(protocol=Protocol.ISCSI, address="iqn.2026-01.io.sb:host-b"),), + ), + Protocol.FC: ( + (Initiator(protocol=Protocol.FC, address="21:00:00:24:ff:4c:1a:2b"),), + (Initiator(protocol=Protocol.FC, address="21:00:00:24:ff:4c:1a:2c"),), + ), + }, + create_foreign_volume=lambda name, size: fake.add_volume(name, size), + ) diff --git a/simplyblock_core/storage_arrays/testing/ibm_flashsystem.py b/simplyblock_core/storage_arrays/testing/ibm_flashsystem.py new file mode 100644 index 0000000000..609726468c --- /dev/null +++ b/simplyblock_core/storage_arrays/testing/ibm_flashsystem.py @@ -0,0 +1,395 @@ +"""Fake IBM Storage Virtualize REST API (the subset the adapter uses). + +Mirrors the real API's shape: every command is ``POST /rest[/v1]/[/]`` +with CLI flags as JSON; failures are HTTP 500 with the CLI's ``CMMVCnnnnE`` +message as plain text; an unknown/expired token is HTTP 403. Quirks kept: + +* values are strings (ids, capacities, SCSI ids); +* ``capacity`` is human-readable (``10.00GB``) unless ``bytes`` is passed; +* detail views (``lsvdisk ``) are a list: the volume, then its copies; +* a one-row ``lsvdiskhostmap`` comes back as a bare dict; +* object ids are the lowest free integer, so a deleted volume's id is reused; +* ``mkvdiskhostmap`` to a second host needs ``force`` (CMMVC6071E); +* FC WWPNs that are not logged in need ``force`` on mkhost/addhostport. +""" +from __future__ import annotations + +import secrets +from typing import Any + +from pydantic import SecretStr + +from simplyblock_core.credentials import Credential + +from ..base import Initiator, Protocol +from . import ContractSetup, FakeArray, FakeError, Reply, Request, make_config, route + +_ROOT = r"/rest(?:/v1)?" + +E_NOT_EXIST = "CMMVC5753E The specified object does not exist or is not a suitable candidate." +E_NAME_RULES = ("CMMVC5754E The specified object does not exist, or the name supplied " + "does not meet the naming rules.") +E_IN_REQUEST = "CMMVC5842E The action failed because an object that was in the request does not exist." +E_EXISTS = "CMMVC6035E The action failed as the object already exists." +E_IQN = ("CMMVC6581E The command has failed because the maximum number of allowed iSCSI " + "qualified names (IQNs) has been reached, or the IQN is already assigned or is not valid.") +E_WWPN = ("CMMVC5867E The action failed because the worldwide port name is already " + "assigned or is not valid.") +E_ALREADY_MAPPED = ("CMMVC5878E The virtual disk (VDisk)-to-host mapping was not created " + "because this VDisk is already mapped to this host.") +E_MULTI_HOST = ("CMMVC6071E The VDisk-to-host mapping was not created because the VDisk is " + "already mapped to a host.") +E_VDISK_MAPPED = ("CMMVC5840E The virtual disk (VDisk) was not deleted because it is mapped " + "to a host or because it is part of a FlashCopy or Remote Copy mapping, " + "or is involved in an image mode migrate.") +E_HOST_MAPPED = ("CMMVC5871E The action failed because one or more of the configured port " + "names is in a mapping.") +E_BAD_NAME = ("CMMVC6527E The name that you have entered is not valid. The name can contain " + "letters, numbers, spaces, periods, dashes, and underscores. The name must " + "begin with a letter or an underscore.") +E_PARAM = "CMMVC5707E Required parameters are missing." +E_SHRINK = "CMMVC5709E [-size] is not a supported parameter." + + +def _cli_error(text: str) -> FakeError: + return FakeError(500, text.encode(), {"Content-Type": "text/plain"}) + + +def _human(size: int) -> str: + for unit, div in (("TB", 1 << 40), ("GB", 1 << 30), ("MB", 1 << 20)): + if size >= div: + return f"{size / div:.2f}{unit}" + return f"{size}B" + + +def _units(unit: str | None) -> int: + return 1 << (10 * ["b", "kb", "mb", "gb", "tb", "pb"].index((unit or "mb").lower())) + + +def _valid_name(name: str) -> bool: + return bool(name) and len(name) <= 63 and (name[0].isalpha() or name[0] == "_") and all( + c.isalnum() or c in "._- " for c in name) + + +class FakeIbmFlashSystem(FakeArray): + vendor = "ibm-flashsystem" + + def __init__(self, username: str = "superuser", password: str = "passw0rd", + pools: tuple[str, ...] = ("Pool0",)): + super().__init__() + self.username = username + self.password = password + self.pools = {name: str(i) for i, name in enumerate(pools)} + self.tokens: set[str] = set() + self.vdisks: dict[str, dict[str, Any]] = {} # id -> vdisk + self.hosts: dict[str, dict[str, Any]] = {} # name -> host + self.maps: list[dict[str, Any]] = [] # {vdisk_id, host, scsi} + self.commands: list[tuple[str, str | None, dict[str, Any]]] = [] + + # -- fake controls ------------------------------------------------------------ + + def expire_sessions(self) -> None: + self.tokens.clear() + + def set_credential(self, **fields: str) -> None: + self.username = fields["username"] + self.password = fields["password"] + + @staticmethod + def _free_id(used) -> str: + n = 0 + while str(n) in used: + n += 1 + return str(n) + + def add_volume(self, name: str, size: int, thin: bool = False) -> str: + vid = self._free_id(self.vdisks) + self.vdisks[vid] = {"id": vid, "name": name, "capacity": size, + "vdisk_UID": "600507680C8" + secrets.token_hex(11).upper()[:21], + "mdisk_grp_name": next(iter(self.pools)), "IO_group_name": "io_grp0", + "thin": thin} + return vid + + # -- dispatch ------------------------------------------------------------------- + + @route("POST", _ROOT + "/auth") + def auth(self, req: Request): + if (req.headers.get("X-Auth-Username") != self.username + or req.headers.get("X-Auth-Password") != self.password): + raise FakeError(403, {"code": 403, "message": "Forbidden"}) + token = secrets.token_hex(16) + self.tokens.add(token) + return Reply(200, {"token": token}) + + @route("POST", _ROOT + r"/(?P[a-z]+)(?:/(?P[^/]+))?") + def command(self, req: Request, cmd: str, obj: str | None = None): + if cmd == "auth": # pragma: no cover - matched above + return self.auth(req) + if req.headers.get("X-Auth-Token") not in self.tokens: + raise FakeError(403, {"code": 403, "message": "Forbidden"}) + opts = req.json() or {} + self.commands.append((cmd, obj, opts)) + handler = getattr(self, f"_c_{cmd}", None) + if handler is None: + raise FakeError(404, "Not Found") + result = handler(obj, opts) + return Reply(200, result) + + # -- lookups ---------------------------------------------------------------------- + + def _vdisk(self, ref: str | None) -> dict[str, Any]: + if ref in self.vdisks: + return self.vdisks[ref] + for v in self.vdisks.values(): + if v["name"] == ref: + return v + raise _cli_error(E_NOT_EXIST) + + def _host(self, ref: str | None) -> dict[str, Any]: + if ref in self.hosts: + return self.hosts[ref] + for h in self.hosts.values(): + if h["id"] == ref: + return h + raise _cli_error(E_NOT_EXIST) + + def _vdisk_row(self, v: dict[str, Any], opts: dict[str, Any]) -> dict[str, Any]: + cap = str(v["capacity"]) if opts.get("bytes") else _human(v["capacity"]) + return {"id": v["id"], "name": v["name"], "IO_group_id": "0", + "IO_group_name": v["IO_group_name"], "status": "online", + "mdisk_grp_id": self.pools[v["mdisk_grp_name"]], + "mdisk_grp_name": v["mdisk_grp_name"], "capacity": cap, "type": "striped", + "FC_id": "", "FC_name": "", "RC_id": "", "RC_name": "", + "vdisk_UID": v["vdisk_UID"], "fc_map_count": "0", "copy_count": "1", + "fast_write_state": "empty", "se_copy_count": "1" if v["thin"] else "0", + "RC_change": "no", "compressed_copy_count": "0", "parent_mdisk_grp_id": "0", + "parent_mdisk_grp_name": v["mdisk_grp_name"], "formatting": "no", + "encrypt": "no", "volume_id": v["id"], "volume_name": v["name"], + "function": ""} + + # -- system ------------------------------------------------------------------------- + + def _c_lssystem(self, obj, opts): + return {"id": "000002042140A0B2", "name": "fake-fs7300", "location": "local", + "code_level": "8.6.0.4 (build 169.12.2403211122000)", + "product_name": "IBM FlashSystem 7300"} + + # -- volumes -------------------------------------------------------------------------- + + def _c_lsvdisk(self, obj, opts): + if obj is not None: + v = self._vdisk(obj) + row = self._vdisk_row(v, opts) + cap = row["capacity"] + copy = {"copy_id": "0", "status": "online", "sync": "yes", "primary": "yes", + "mdisk_grp_name": v["mdisk_grp_name"], "type": "striped", + "capacity": cap, "real_capacity": cap if not v["thin"] else "0.00MB", + "autoexpand": "on" if v["thin"] else "", "se_copy": "yes" if v["thin"] else "no"} + return [row, copy] + rows = [self._vdisk_row(v, opts) for v in self.vdisks.values()] + fv = opts.get("filtervalue") + if fv: + key, _, value = str(fv).partition("=") + rows = [r for r in rows if str(r.get(key)) == value] + return rows + + def _c_mkvolume(self, obj, opts): + name, pool = opts.get("name"), opts.get("pool") + if "size" not in opts or not pool: + raise _cli_error(E_PARAM) + if pool not in self.pools and pool not in self.pools.values(): + raise _cli_error(E_NAME_RULES) + if name is not None and not _valid_name(name): + raise _cli_error(E_BAD_NAME) + if any(v["name"] == name for v in self.vdisks.values()): + raise _cli_error(E_EXISTS) + size = int(opts["size"]) * _units(opts.get("unit")) + size = -(-size // 512) * 512 + vid = self.add_volume(name or "", size, thin=bool(opts.get("thin"))) + v = self.vdisks[vid] + if not name: + v["name"] = f"volume{vid}" + if pool in self.pools: + v["mdisk_grp_name"] = pool + if opts.get("iogrp") is not None: + v["IO_group_name"] = str(opts["iogrp"]) + return {"id": vid, "message": f"Volume, id [{vid}], successfully created"} + + def _c_expandvdisksize(self, obj, opts): + v = self._vdisk(obj) + if "size" not in opts: + raise _cli_error(E_PARAM) + delta = int(opts["size"]) * _units(opts.get("unit")) + if delta <= 0: + raise _cli_error(E_SHRINK) + v["capacity"] += -(-delta // 512) * 512 + + def _c_rmvolume(self, obj, opts): + v = self._vdisk(obj) + if any(m["vdisk_id"] == v["id"] for m in self.maps) and not opts.get("removehostmappings"): + raise _cli_error(E_VDISK_MAPPED) + self.maps = [m for m in self.maps if m["vdisk_id"] != v["id"]] + del self.vdisks[v["id"]] + + # -- hosts ------------------------------------------------------------------------------ + + def _owner(self, kind: str, value: str) -> str | None: + for h in self.hosts.values(): + if value.lower() in (p.lower() for p in h[kind]): + return h["name"] + return None + + def _parse_ports(self, opts: dict[str, Any]) -> dict[str, list[str]]: + ports: dict[str, list[str]] = {"iscsiname": [], "fcwwpn": [], "nqn": []} + if opts.get("iscsiname"): + ports["iscsiname"] = [p for p in str(opts["iscsiname"]).split(",") if p] + if opts.get("fcwwpn"): + wwpns = [p for p in str(opts["fcwwpn"]).split(":") if p] + for w in wwpns: + if len(w) != 16 or any(c not in "0123456789abcdefABCDEF" for c in w): + raise _cli_error(E_WWPN) + if not opts.get("force"): + # The fake has no fabric: no WWPN is ever logged in. + raise _cli_error(E_WWPN) + ports["fcwwpn"] = [w.upper() for w in wwpns] + if opts.get("nqn"): + ports["nqn"] = [p for p in str(opts["nqn"]).split(",") if p] + return ports + + def _claim(self, host: str | None, ports: dict[str, list[str]]) -> None: + errors = {"iscsiname": E_IQN, "fcwwpn": E_WWPN, "nqn": E_IQN} + for kind, values in ports.items(): + for value in values: + if self._owner(kind, value) is not None: # even when it is this host + raise _cli_error(errors[kind]) + + def _c_mkhost(self, obj, opts): + name = opts.get("name") + if not name: + raise _cli_error(E_PARAM) + if not _valid_name(name): + raise _cli_error(E_BAD_NAME) + if name in self.hosts: + raise _cli_error(E_EXISTS) + protocol = opts.get("protocol", "scsi") + if protocol not in ("scsi", "iscsi", "fcscsi", "tcpnvme", "rdmanvme", "fcnvme", "nvme"): + raise _cli_error(E_PARAM) + ports = self._parse_ports(opts) + if not any(ports.values()): + raise _cli_error(E_PARAM) + if ports["nqn"] and protocol not in ("tcpnvme", "rdmanvme", "fcnvme", "nvme"): + raise _cli_error(E_PARAM) + self._claim(None, ports) + hid = self._free_id({h["id"] for h in self.hosts.values()}) + self.hosts[name] = {"id": hid, "name": name, "protocol": protocol, + "iscsiname": ports["iscsiname"], "fcwwpn": ports["fcwwpn"], + "nqn": ports["nqn"]} + return {"id": hid, "message": f"Host, id [{hid}], successfully created"} + + def _c_addhostport(self, obj, opts): + h = self._host(obj) + ports = self._parse_ports(opts) + if not any(ports.values()): + raise _cli_error(E_PARAM) + self._claim(h["name"], ports) + for kind, values in ports.items(): + h[kind].extend(values) + + def _c_lshost(self, obj, opts): + if obj is None: + return [{"id": h["id"], "name": h["name"], "port_count": str( + len(h["iscsiname"]) + len(h["fcwwpn"]) + len(h["nqn"])), + "iogrp_count": "4", "status": "online", "protocol": h["protocol"]} + for h in self.hosts.values()] + h = self._host(obj) + nodes = ([{"WWPN": w, "node_logged_in_count": "0", "state": "offline"} + for w in h["fcwwpn"]] + + [{"iscsi_name": i, "node_logged_in_count": "0", "state": "offline"} + for i in h["iscsiname"]] + + [{"nqn": n, "node_logged_in_count": "0", "state": "offline"} + for n in h["nqn"]]) + return {"id": h["id"], "name": h["name"], "port_count": str(len(nodes)), + "type": "generic", "iogrp_count": "4", "status": "offline", + "protocol": h["protocol"], "host_cluster_id": "", "host_cluster_name": "", + "mapping_count": str(sum(1 for m in self.maps if m["host"] == h["name"])), + "nodes": nodes} + + def _c_rmhost(self, obj, opts): + h = self._host(obj) + if any(m["host"] == h["name"] for m in self.maps) and not opts.get("force"): + raise _cli_error(E_HOST_MAPPED) + self.maps = [m for m in self.maps if m["host"] != h["name"]] + del self.hosts[h["name"]] + + # -- mappings ------------------------------------------------------------------------------- + + def _map_row(self, m: dict[str, Any]) -> dict[str, Any]: + v, h = self.vdisks[m["vdisk_id"]], self.hosts[m["host"]] + return {"id": v["id"], "name": v["name"], "SCSI_id": str(m["scsi"]), + "host_id": h["id"], "host_name": h["name"], "vdisk_UID": v["vdisk_UID"], + "IO_group_id": "0", "IO_group_name": v["IO_group_name"], + "mapping_type": "private", "host_cluster_id": "", "host_cluster_name": "", + "protocol": h["protocol"]} + + def _c_lsvdiskhostmap(self, obj, opts): + v = self._vdisk(obj) + rows = [self._map_row(m) for m in self.maps if m["vdisk_id"] == v["id"]] + return rows[0] if len(rows) == 1 else rows # quirk: one row -> bare dict + + def _c_mkvdiskhostmap(self, obj, opts): + v = self._vdisk(obj) + if not opts.get("host"): + raise _cli_error(E_PARAM) + h = self._host(opts["host"]) + mine = [m for m in self.maps if m["vdisk_id"] == v["id"]] + if any(m["host"] == h["name"] for m in mine): + raise _cli_error(E_ALREADY_MAPPED) + if mine and not opts.get("force"): + raise _cli_error(E_MULTI_HOST) + used = {m["scsi"] for m in self.maps if m["host"] == h["name"]} + scsi = int(opts["scsi"]) if opts.get("scsi") is not None else next( + n for n in range(4096) if n not in used) + self.maps.append({"vdisk_id": v["id"], "host": h["name"], "scsi": scsi}) + return {"id": str(scsi), + "message": f"Virtual Disk to Host map, id [{scsi}], successfully created"} + + def _c_rmvdiskhostmap(self, obj, opts): + v = self._vdisk(obj) + if not opts.get("host"): + raise _cli_error(E_PARAM) + h = self._host(opts["host"]) + before = len(self.maps) + self.maps = [m for m in self.maps + if not (m["vdisk_id"] == v["id"] and m["host"] == h["name"])] + if len(self.maps) == before: + raise _cli_error(E_IN_REQUEST) + + +def contract_setup() -> ContractSetup: + fake = FakeIbmFlashSystem(username="superuser", password="passw0rd") + return ContractSetup( + fake=fake, + config=make_config("ibm-flashsystem", "https://flashsystem.fake.example:7443", + pool="Pool0"), + credential=Credential({"username": SecretStr("superuser"), + "password": SecretStr("passw0rd")}), + bad_credential=Credential({"username": SecretStr("superuser"), + "password": SecretStr("wrong")}), + initiators={ + Protocol.ISCSI: ( + (Initiator(protocol=Protocol.ISCSI, address="iqn.2026-01.io.sb:host-a"),), + (Initiator(protocol=Protocol.ISCSI, address="iqn.2026-01.io.sb:host-b"),), + ), + Protocol.FC: ( + (Initiator(protocol=Protocol.FC, address="21:00:00:24:ff:4c:1a:2b"),), + (Initiator(protocol=Protocol.FC, address="21:00:00:24:ff:4c:1a:2c"),), + ), + Protocol.NVME_TCP: ( + (Initiator(protocol=Protocol.NVME_TCP, + address="nqn.2014-08.org.nvmexpress:uuid:host-a"),), + (Initiator(protocol=Protocol.NVME_TCP, + address="nqn.2014-08.org.nvmexpress:uuid:host-b"),), + ), + }, + create_foreign_volume=lambda name, size: fake.add_volume(name, size), + ) diff --git a/simplyblock_core/storage_arrays/testing/infinidat.py b/simplyblock_core/storage_arrays/testing/infinidat.py new file mode 100644 index 0000000000..595b75cab6 --- /dev/null +++ b/simplyblock_core/storage_arrays/testing/infinidat.py @@ -0,0 +1,315 @@ +"""Fake Infinidat InfiniBox REST API (``/api/rest``), the subset the adapter +uses. + +Quirks reproduced: every reply is a ``{"result", "error", "metadata"}`` +envelope; lists are paged and filtered with ``field=eq:value``; destructive +requests without ``?approved=true`` get **403** ``APPROVAL_REQUIRED``; +object ids are integers; volume ``serial`` is the NAA-6 identifier without +its leading ``6``; LUN numbers start at 1 per host. Error codes follow the +``OBJECT_NOT_FOUND`` / ``*_CONFLICT`` style of the real API but are our +reading of it, not a verified list. For higher fidelity run the contract +suite's live tier against Infinidat's ``infinisim``. +""" +from __future__ import annotations + +from typing import Any + +from pydantic import SecretStr + +from simplyblock_core.credentials import Credential + +from ..base import Initiator, Protocol, normalize_wwpn +from . import ContractSetup, FakeArray, FakeError, Reply, Request, make_config, route + +_R = "/api/rest" +_ID = r"(?P\d+)" +_SYSTEM_ID = "000004e2" + + +def _err(status: int, code: str, message: str) -> FakeError: + return FakeError(status, { + "result": None, + "error": {"code": code, "message": message, "is_remote": False, "data": None, + "reasons": [], "severity": "ERROR"}, + "metadata": {"ready": True}}) + + +def _ok(result: Any, status: int = 200, metadata: dict[str, Any] | None = None) -> Reply: + return Reply(status, {"result": result, "error": None, + "metadata": metadata or {"ready": True}}) + + +def _port_address(ptype: str, address: str) -> str: + if ptype == "FC": + try: + return normalize_wwpn(address) + except ValueError: + raise _err(400, "INVALID_PORT_ADDRESS", f"Invalid FC address {address}") from None + return address.lower() + + +class FakeInfiniBox(FakeArray): + vendor = "infinidat-infinibox" + + def __init__(self, username: str = "admin", password: str = "ibox-pass"): + super().__init__() + self.username = username + self.password = password + self.pools: dict[int, dict[str, Any]] = {} + self.volumes: dict[int, dict[str, Any]] = {} + self.hosts: dict[int, dict[str, Any]] = {} + self.luns: list[dict[str, Any]] = [] # {host_id, volume_id, lun, id} + self.add_pool("sb-pool") + + # -- fake controls ------------------------------------------------------ + + def set_credential(self, **fields: str) -> None: + self.username = fields.get("username", self.username) + self.password = fields["password"] + + def add_pool(self, name: str) -> int: + pid = self.next_id() + self.pools[pid] = {"id": pid, "name": name, "physical_capacity": 1 << 50, + "virtual_capacity": 1 << 52, "state": "NORMAL"} + return pid + + def add_volume(self, name: str, size: int, pool_id: int | None = None) -> int: + vid = self.next_id() + self.volumes[vid] = { + "id": vid, "name": name, "size": size, "used": 0, "allocated": 0, + "pool_id": pool_id or next(iter(self.pools)), "provtype": "THIN", + "type": "MASTER", "mapped": False, "write_protected": False, + "serial": f"742b0f{_SYSTEM_ID}{vid:017x}", "created_at": 1763600000000, + "parent_id": 0, "family_id": vid, "rmr_source": False, "rmr_target": False, + } + return vid + + # -- dispatch helpers --------------------------------------------------------- + + def _auth(self, req: Request) -> None: + if req.basic_auth() != (self.username, self.password): + raise _err(401, "UNAUTHORIZED", "Invalid credentials") + + @staticmethod + def _approved(req: Request, what: str) -> None: + if (req.q("approved") or "").lower() != "true": + raise _err(403, "APPROVAL_REQUIRED", f"{what} requires approval") + + def _page(self, req: Request, items: list[dict[str, Any]]) -> Reply: + for key, values in req.query.items(): + if key in ("page", "page_size", "approved", "fields", "sort"): + continue + raw = values[0] + op, _, value = raw.partition(":") if ":" in raw else ("eq", "", raw) + if op != "eq": + raise _err(400, "UNSUPPORTED_FILTER", f"fake: filter op {op}") + items = [i for i in items if str(i.get(key)) == value] + page = int(req.q("page") or 1) + size = int(req.q("page_size") or 50) + if not 1 <= size <= 1000: + raise _err(400, "BAD_PAGE_SIZE", "page_size must be 1..1000") + total = len(items) + pages = max(1, -(-total // size)) + chunk = items[(page - 1) * size: page * size] + return _ok(chunk, metadata={"ready": True, "number_of_objects": total, + "page_size": size, "pages_total": pages, "page": page}) + + def _vol(self, vid: int) -> dict[str, Any]: + if vid not in self.volumes: + raise _err(404, "VOLUME_NOT_FOUND", f"Volume {vid} not found") + return self.volumes[vid] + + def _host(self, hid: int) -> dict[str, Any]: + if hid not in self.hosts: + raise _err(404, "HOST_NOT_FOUND", f"Host {hid} not found") + return self.hosts[hid] + + def _host_view(self, h: dict[str, Any]) -> dict[str, Any]: + luns = [self._lun_view(m) for m in self.luns if m["host_id"] == h["id"]] + return {**h, "ports": [dict(p) for p in h["ports"]], "luns": luns} + + def _lun_view(self, m: dict[str, Any]) -> dict[str, Any]: + return {"id": m["id"], "lun": m["lun"], "volume_id": m["volume_id"], + "host_id": m["host_id"], "host_cluster_id": 0, "clustered": False} + + # -- system / pools -------------------------------------------------------------- + + @route("GET", _R + "/system") + def system(self, req): + self._auth(req) + return _ok({"name": "ibox-fake", "serial_number": 1250, "model_name": "F4304", + "version": "7.3.10.0", "system_type": "INFINIBOX"}) + + @route("GET", _R + "/pools") + def list_pools(self, req): + self._auth(req) + return self._page(req, list(self.pools.values())) + + # -- volumes -------------------------------------------------------------------- + + @route("GET", _R + "/volumes") + def list_volumes(self, req): + self._auth(req) + return self._page(req, list(self.volumes.values())) + + @route("POST", _R + "/volumes") + def create_volume(self, req): + self._auth(req) + body = req.json() or {} + name, size, pool_id = str(body.get("name") or ""), body.get("size"), body.get("pool_id") + if not isinstance(size, int) or size <= 0 or size % 512: + raise _err(400, "BAD_REQUEST", "size must be a positive multiple of 512 bytes") + if pool_id not in self.pools: + raise _err(404, "POOL_NOT_FOUND", f"Pool {pool_id} not found") + if body.get("provtype", "THIN") not in ("THIN", "THICK"): + raise _err(400, "BAD_REQUEST", "provtype must be THIN or THICK") + if any(v["name"] == name for v in self.volumes.values()): + raise _err(409, "VOLUME_NAME_CONFLICT", f"Volume name {name} already exists") + vid = self.add_volume(name, size, pool_id) + self.volumes[vid]["provtype"] = body.get("provtype", "THIN") + return _ok(self.volumes[vid], 201) + + @route("GET", _R + "/volumes/" + _ID) + def get_volume(self, req, oid): + self._auth(req) + return _ok(self._vol(int(oid))) + + @route("PUT", _R + "/volumes/" + _ID) + def update_volume(self, req, oid): + self._auth(req) + v = self._vol(int(oid)) + body = req.json() or {} + if "size" in body: + size = body["size"] + if not isinstance(size, int) or size <= 0 or size % 512: + raise _err(400, "BAD_REQUEST", "size must be a positive multiple of 512 bytes") + if size < v["size"]: + self._approved(req, "Shrinking a volume") + v["size"] = size + return _ok(v) + + @route("DELETE", _R + "/volumes/" + _ID) + def delete_volume(self, req, oid): + self._auth(req) + v = self._vol(int(oid)) + self._approved(req, "Deleting a volume") + if any(m["volume_id"] == v["id"] for m in self.luns): + raise _err(409, "VOLUME_IS_MAPPED", "Volume is mapped; unmap it first") + del self.volumes[v["id"]] + return _ok(v) + + @route("GET", _R + "/volumes/" + _ID + "/luns") + def volume_luns(self, req, oid): + self._auth(req) + vid = self._vol(int(oid))["id"] + return _ok([self._lun_view(m) for m in self.luns if m["volume_id"] == vid]) + + # -- hosts ------------------------------------------------------------------------ + + @route("GET", _R + "/hosts") + def list_hosts(self, req): + self._auth(req) + return self._page(req, [self._host_view(h) for h in self.hosts.values()]) + + @route("POST", _R + "/hosts") + def create_host(self, req): + self._auth(req) + name = (req.json() or {}).get("name") + if not name: + raise _err(400, "BAD_REQUEST", "name is required") + if any(h["name"] == name for h in self.hosts.values()): + raise _err(409, "HOST_NAME_CONFLICT", f"Host name {name} already exists") + hid = self.next_id() + self.hosts[hid] = {"id": hid, "name": name, "ports": [], "security_method": "NONE", + "host_type": "LINUX", "host_cluster_id": 0} + return _ok(self._host_view(self.hosts[hid]), 201) + + @route("DELETE", _R + "/hosts/" + _ID) + def delete_host(self, req, oid): + self._auth(req) + h = self._host(int(oid)) + self._approved(req, "Deleting a host") + if any(m["host_id"] == h["id"] for m in self.luns): + raise _err(409, "HOST_HAS_LUNS", "Host has mapped volumes") + del self.hosts[h["id"]] + return _ok(self._host_view(h)) + + @route("POST", _R + "/hosts/" + _ID + "/ports") + def add_port(self, req, oid): + self._auth(req) + h = self._host(int(oid)) + body = req.json() or {} + ptype = str(body.get("type", "")).upper() + if ptype not in ("ISCSI", "FC"): + raise _err(400, "BAD_REQUEST", f"Unsupported port type {ptype}") + address = _port_address(ptype, str(body.get("address", ""))) + for other in self.hosts.values(): + for p in other["ports"]: + if p["type"] == ptype and p["address"] == address: + if other["id"] == h["id"]: + raise _err(409, "PORT_ALREADY_EXISTS", + f"Port {address} already belongs to this host") + raise _err(409, "PORT_ALREADY_BELONGS_TO_HOST", + f"Port {address} belongs to host {other['name']}") + port = {"type": ptype, "address": address, "host_id": h["id"]} + h["ports"].append(port) + return _ok(port, 201) + + @route("POST", _R + "/hosts/" + _ID + "/luns") + def map_lun(self, req, oid): + self._auth(req) + h = self._host(int(oid)) + vid = (req.json() or {}).get("volume_id") + if not isinstance(vid, int): + raise _err(400, "BAD_REQUEST", "volume_id must be an integer") + self._vol(vid) + if any(m["host_id"] == h["id"] and m["volume_id"] == vid for m in self.luns): + raise _err(409, "MAPPING_ALREADY_EXISTS", "Volume already mapped to host") + used = {m["lun"] for m in self.luns if m["host_id"] == h["id"]} + lun = next(n for n in range(1, 4096) if n not in used) + m = {"id": self.next_id(), "host_id": h["id"], "volume_id": vid, "lun": lun} + self.luns.append(m) + self.volumes[vid]["mapped"] = True + return _ok(self._lun_view(m), 201) + + @route("DELETE", _R + "/hosts/" + _ID + r"/luns/volume_id/(?P\d+)") + def unmap_lun(self, req, oid, vid): + self._auth(req) + h = self._host(int(oid)) + self._approved(req, "Unmapping a volume") + match = [m for m in self.luns if m["host_id"] == h["id"] and m["volume_id"] == int(vid)] + if not match: + raise _err(404, "LUN_NOT_FOUND", f"Volume {vid} is not mapped to host {h['id']}") + self.luns.remove(match[0]) + if int(vid) in self.volumes: + self.volumes[int(vid)]["mapped"] = any( + m["volume_id"] == int(vid) for m in self.luns) + return _ok(self._lun_view(match[0])) + + def not_routed(self, req: Request) -> Reply: + return Reply(404, {"result": None, "error": { + "code": "NOT_FOUND", "message": f"fake: no route for {req.method} {req.path}"}, + "metadata": {"ready": True}}) + + +def contract_setup() -> ContractSetup: + fake = FakeInfiniBox(username="admin", password="ibox-pass") + return ContractSetup( + fake=fake, + config=make_config("infinidat-infinibox", "https://ibox.fake.example", pool="sb-pool"), + credential=Credential({"username": SecretStr("admin"), + "password": SecretStr("ibox-pass")}), + bad_credential=Credential({"username": SecretStr("admin"), + "password": SecretStr("wrong")}), + initiators={ + Protocol.ISCSI: ( + (Initiator(protocol=Protocol.ISCSI, address="iqn.2026-01.io.sb:host-a"),), + (Initiator(protocol=Protocol.ISCSI, address="iqn.2026-01.io.sb:host-b"),), + ), + Protocol.FC: ( + (Initiator(protocol=Protocol.FC, address="21:00:00:24:ff:4c:1a:2b"),), + (Initiator(protocol=Protocol.FC, address="21:00:00:24:ff:4c:1a:2c"),), + ), + }, + create_foreign_volume=lambda name, size: str(fake.add_volume(name, size)), + ) diff --git a/simplyblock_core/storage_arrays/testing/netapp_ontap.py b/simplyblock_core/storage_arrays/testing/netapp_ontap.py new file mode 100644 index 0000000000..2ccc0b52c8 --- /dev/null +++ b/simplyblock_core/storage_arrays/testing/netapp_ontap.py @@ -0,0 +1,832 @@ +"""Fake NetApp ONTAP 9.x REST API (the subset the adapter uses). + +Modelled behaviour: + +* HTTP basic auth on every request (``401`` + ONTAP error body otherwise). +* Collections answer ``{"records": [...], "num_records": n}``; query + parameters filter on (dotted, array-flattening) fields with ``|`` for OR + and ``*`` wildcards; ``fields=`` projects the records (key fields ``uuid`` + and ``name`` are always returned), so an adapter that forgets to ask for a + field does not get it. +* Errors: ``{"error": {"message": ..., "code": ...}}``; ``404`` for unknown + objects, ``409`` for duplicates, ``400`` for everything else. Numeric + codes are illustrative. +* FlexVol create/resize/delete are asynchronous: ``202`` with a job link; + the effect happens when the job runs, after ``job_polls`` polls of + ``/api/cluster/jobs/{uuid}``. +* Size rules: FlexVol >= 20 MiB (rounded up to 4 KiB); LUN/namespace must fit + in its FlexVol (usable = size minus snapshot reserve), cannot shrink, and a + namespace is a multiple of its block size. +* Name rules: FlexVol ``[A-Za-z_][A-Za-z0-9_]*``; LUN/namespace path + ``/vol//``. +* An initiator / host NQN may be in several igroups / subsystems (as on + ONTAP); a namespace can be mapped to one subsystem only; mapped + LUNs/namespaces/igroups/subsystems cannot be deleted. +""" +from __future__ import annotations + +import copy +import fnmatch +import re +import secrets +import string +import uuid as uuid_mod +from collections.abc import Callable +from typing import Any +from urllib.parse import unquote + +from pydantic import SecretStr + +from simplyblock_core.credentials import Credential + +from ..base import Initiator, Protocol +from . import ContractSetup, FakeArray, FakeError, Reply, Request, make_config, route + +_U = r"(?P[0-9a-fA-F-]{36})" +_RESERVED = frozenset({"fields", "return_records", "return_timeout", "max_records", "order_by", + "allow_delete_while_mapped", "allow_delete_with_hosts"}) +_FLEXVOL_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,202}$") +_PATH_RE = re.compile(r"^/vol/(?P[^/]+)/(?P[A-Za-z0-9_.\-{}]{1,255})$") +_IGROUP_RE = re.compile(r"^[A-Za-z0-9_.:\-]{1,96}$") +_SUBSYS_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_.\-]{0,95}$") +_WWPN_RE = re.compile(r"^([0-9a-f]{2}:){7}[0-9a-f]{2}$", re.IGNORECASE) +_SERIAL_CHARS = string.ascii_letters + string.digits + "-]?$" +MIN_VOLUME = 20 << 20 +MAX_LUN = 128 << 40 + + +def _err(status: int, message: str, code: str = "1", target: str | None = None) -> FakeError: + body: dict[str, Any] = {"error": {"message": message, "code": code}} + if target: + body["error"]["target"] = target + return FakeError(status, body) + + +def _not_found(what: str = "entry") -> FakeError: + return _err(404, f"{what} doesn't exist", "4") + + +def _resolve(obj: Any, parts: list[str]) -> list[Any]: + if not parts: + return obj if isinstance(obj, list) else [obj] + if isinstance(obj, list): + return [v for e in obj for v in _resolve(e, parts)] + if isinstance(obj, dict) and parts[0] in obj: + return _resolve(obj[parts[0]], parts[1:]) + return [] + + +def _matches(rec: dict[str, Any], key: str, pattern: str) -> bool: + values = _resolve(rec, key.split(".")) + texts = [str(v).lower() for v in values] # True -> "true", as in ONTAP queries + for p in pattern.split("|"): + if any(fnmatch.fnmatchcase(t, p.lower()) for t in texts): + return True + return False + + +def _project(obj: Any, paths: list[list[str]]) -> Any: + if any(not p for p in paths): + return copy.deepcopy(obj) + if isinstance(obj, list): + return [_project(e, paths) for e in obj] + if not isinstance(obj, dict): + return copy.deepcopy(obj) + out: dict[str, Any] = {} + groups: dict[str, list[list[str]]] = {} + for p in paths: + groups.setdefault(p[0], []).append(p[1:]) + for key, sub in groups.items(): + if key in obj: + out[key] = _project(obj[key], sub) + return out + + +class FakeNetAppOntap(FakeArray): + vendor = "netapp-ontap" + + def __init__(self, username: str = "admin", password: str = "netapp1!", + svm: str = "svm1"): + super().__init__() + self.username = username + self.password = password + self.svms: dict[str, str] = {svm: str(uuid_mod.uuid4())} + self.aggregates: list[dict[str, Any]] = [ + {"uuid": str(uuid_mod.uuid4()), "name": "aggr1", + "space": {"block_storage": {"available": 10 << 40}}}, + {"uuid": str(uuid_mod.uuid4()), "name": "aggr2", + "space": {"block_storage": {"available": 30 << 40}}}, + ] + self.volumes: dict[str, dict[str, Any]] = {} + self.luns: dict[str, dict[str, Any]] = {} + self.namespaces: dict[str, dict[str, Any]] = {} + self.igroups: dict[str, dict[str, Any]] = {} + self.lun_maps: list[dict[str, Any]] = [] + self.subsystems: dict[str, dict[str, Any]] = {} + self.subsystem_maps: list[dict[str, Any]] = [] + self.jobs: dict[str, dict[str, Any]] = {} + #: Number of job polls answering ``running`` before a job runs. + self.job_polls = 1 + #: When True, jobs never finish. + self.jobs_stuck = False + self._job_failures: list[tuple[str, str]] = [] + + # -- fake controls ------------------------------------------------------ + + def set_credential(self, **fields: str) -> None: + self.username = fields["username"] + self.password = fields["password"] + + def fail_next_job(self, message: str, code: str = "917504") -> None: + """Make the next job created end in ``failure`` with this message.""" + self._job_failures.append((message, code)) + + def svm_ref(self, name: str) -> dict[str, str]: + if name not in self.svms: + raise _err(404, f'SVM "{name}" not found', "2621462") + return {"name": name, "uuid": self.svms[name]} + + def add_flexvol(self, name: str, size: int, svm: str = "svm1", + snapshot_reserve: int = 0) -> str: + vid = str(uuid_mod.uuid4()) + self.volumes[vid] = { + "uuid": vid, "name": name, "svm": self.svm_ref(svm), "size": size, + "type": "rw", "style": "flexvol", "state": "online", + "guarantee": {"type": "none"}, + "space": {"snapshot": {"reserve_percent": snapshot_reserve}}, + "snapshot_policy": {"name": "default"}, + "aggregates": [{"name": "aggr1", "uuid": self.aggregates[0]["uuid"]}], + "comment": "", + } + return vid + + def add_lun(self, path: str, size: int, svm: str = "svm1") -> str: + vol = self._vol_of_path(path, svm) + lid = str(uuid_mod.uuid4()) + self.luns[lid] = { + "uuid": lid, "name": path, "svm": self.svm_ref(svm), "os_type": "linux", + "serial_number": "".join(secrets.choice(_SERIAL_CHARS) for _ in range(12)), + "space": {"size": size, "guarantee": {"requested": False, "reserved": False}}, + "location": {"logical_unit": path.rsplit("/", 1)[1], + "volume": {"name": vol["name"], "uuid": vol["uuid"]}}, + "status": {"mapped": False, "state": "online"}, + } + return lid + + def add_foreign_lun(self, name: str, size: int) -> str: + flex = name.replace("-", "_") + self.add_flexvol(flex, size * 2) + return self.add_lun(f"/vol/{flex}/{name}", size) + + # -- auth / plumbing ------------------------------------------------------ + + def _auth(self, req: Request) -> None: + if req.basic_auth() != (self.username, self.password): + raise _err(401, "User is not authorized.", "6") + + def _collection(self, req: Request, records: list[dict[str, Any]], + keys: tuple[str, ...] = ("uuid", "name")) -> Reply: + filters = {k: v[0] for k, v in req.query.items() if k not in _RESERVED and v} + found = [r for r in records if all(_matches(r, k, v) for k, v in filters.items())] + return Reply(200, {"records": [self._fields(r, req, keys) for r in found], + "num_records": len(found), + "_links": {"self": {"href": req.path}}}) + + @staticmethod + def _fields(rec: dict[str, Any], req: Request, keys: tuple[str, ...]) -> dict[str, Any]: + fields = req.q("fields") + if fields == "*": + return copy.deepcopy(rec) + paths = [[k] for k in keys if k in rec] + if fields: + paths += [f.strip().split(".") for f in fields.split(",") if f.strip()] + return _project(rec, paths) + + @staticmethod + def _created(req: Request, rec: dict[str, Any], location: str) -> Reply: + if req.q("return_records") == "true": + return Reply(201, {"num_records": 1, "records": [copy.deepcopy(rec)]}, + {"Location": location}) + return Reply(201, None, {"Location": location}) + + def _svm_of(self, body: dict[str, Any]) -> dict[str, str]: + svm = (body.get("svm") or {}).get("name") + if not svm: + raise _err(400, 'Field "svm.name" is required.', "2") + return self.svm_ref(svm) + + def _vol_of_path(self, path: str, svm: str) -> dict[str, Any]: + m = _PATH_RE.match(path or "") + if not m: + raise _err(400, f'Invalid path "{path}". Paths must be of the form ' + '"/vol//".', "5374082") + for v in self.volumes.values(): + if v["name"] == m["vol"] and v["svm"]["name"] == svm: + return v + raise _err(404, f'Volume "{m["vol"]}" in SVM "{svm}" does not exist.', "917927") + + @staticmethod + def _usable(vol: dict[str, Any]) -> int: + reserve = vol["space"]["snapshot"]["reserve_percent"] + return vol["size"] * (100 - reserve) // 100 + + # -- jobs ----------------------------------------------------------------- + + def _job(self, description: str, action: Callable[[], None]) -> Reply: + jid = str(uuid_mod.uuid4()) + failure = self._job_failures.pop(0) if self._job_failures else None + self.jobs[jid] = {"uuid": jid, "description": description, "state": "queued", + "message": "", "code": 0, "_polls": self.job_polls, + "_action": action, "_failure": failure} + href = f"/api/cluster/jobs/{jid}" + return Reply(202, {"job": {"uuid": jid, "_links": {"self": {"href": href}}}}) + + @route("GET", r"/api/cluster/jobs/" + _U) + def get_job(self, req, uuid): + self._auth(req) + job = self.jobs.get(uuid) + if job is None: + raise _not_found() + if job["state"] in ("queued", "running"): + if self.jobs_stuck or job["_polls"] > 0: + job["_polls"] -= 1 + job["state"] = "running" + job["message"] = "In progress" + elif job["_failure"]: + job["state"], job["message"] = "failure", job["_failure"][0] + job["code"] = int(job["_failure"][1]) + else: + try: + job["_action"]() + job["state"], job["message"] = "success", "success" + except FakeError as e: + err = e.reply.body["error"] + job["state"], job["message"] = "failure", err["message"] + job["code"] = int(err["code"]) + return Reply(200, {k: v for k, v in job.items() if not k.startswith("_")}) + + # -- cluster ---------------------------------------------------------------- + + @route("GET", "/api/cluster") + def cluster(self, req): + self._auth(req) + return Reply(200, {"name": "fake-ontap", "uuid": "1cd8a442-86d1-11e0-ae1c-123478563412", + "version": {"full": "NetApp Release 9.14.1: Mon Jan 01 00:00:00 UTC " + "2024", "generation": 9, "major": 14, + "minor": 1}}) + + @route("GET", "/api/cluster/nodes") + def nodes(self, req): + self._auth(req) + return self._collection(req, [ + {"uuid": "6ab1b4b3-0000-0000-0000-000000000001", "name": "fake-ontap-01", + "model": "AFF-A400", "serial_number": "721802000123"}, + {"uuid": "6ab1b4b3-0000-0000-0000-000000000002", "name": "fake-ontap-02", + "model": "AFF-A400", "serial_number": "721802000124"}, + ]) + + @route("GET", "/api/svm/svms") + def get_svms(self, req): + self._auth(req) + return self._collection(req, [{"uuid": u, "name": n} for n, u in self.svms.items()]) + + @route("GET", "/api/storage/aggregates") + def get_aggregates(self, req): + self._auth(req) + return self._collection(req, self.aggregates) + + # -- FlexVols --------------------------------------------------------------- + + @route("GET", "/api/storage/volumes") + def get_volumes(self, req): + self._auth(req) + return self._collection(req, list(self.volumes.values())) + + @route("GET", "/api/storage/volumes/" + _U) + def get_volume(self, req, uuid): + self._auth(req) + if uuid not in self.volumes: + raise _not_found() + return Reply(200, self._fields(self.volumes[uuid], req, ("uuid", "name")) if req.q( + "fields") else copy.deepcopy(self.volumes[uuid])) + + @route("POST", "/api/storage/volumes") + def post_volume(self, req): + self._auth(req) + body = req.json() or {} + svm = self._svm_of(body) + name = body.get("name", "") + if not _FLEXVOL_RE.match(name): + raise _err(400, f'Invalid volume name "{name}". Volume names must begin with a ' + 'letter or underscore and contain only letters, digits and ' + 'underscores.', "917888") + size = int(body.get("size", 0)) + if size < MIN_VOLUME: + raise _err(400, f"Volume size {size} is too small; minimum is {MIN_VOLUME}.", + "917534") + aggrs = body.get("aggregates") or [] + if len(aggrs) > 1: + # Several aggregates would create a FlexGroup: the adapter must not. + raise _err(400, "Specifying multiple aggregates creates a FlexGroup volume, " + "which is not supported for LUNs.", "917833") + known = {a["name"]: a for a in self.aggregates} + for a in aggrs: + if a.get("name") not in known: + raise _err(404, f'Aggregate "{a.get("name")}" does not exist.', "917927") + size = -(-size // 4096) * 4096 + + def create() -> None: + if any(v["name"] == name and v["svm"]["name"] == svm["name"] + for v in self.volumes.values()): + raise _err(409, f'Duplicate volume name "{name}".', "917535") + vid = self.add_flexvol(name, size, svm["name"], + int(((body.get("space") or {}).get("snapshot") or {}) + .get("reserve_percent", 5))) + vol = self.volumes[vid] + vol["guarantee"] = {"type": (body.get("guarantee") or {}).get("type", "volume")} + vol["snapshot_policy"] = {"name": (body.get("snapshot_policy") or {}) + .get("name", "default")} + vol["comment"] = body.get("comment", "") + if aggrs: + a = known[aggrs[0]["name"]] + vol["aggregates"] = [{"name": a["name"], "uuid": a["uuid"]}] + + return self._job(f"POST /api/storage/volumes/{name}", create) + + @route("PATCH", "/api/storage/volumes/" + _U) + def patch_volume(self, req, uuid): + self._auth(req) + if uuid not in self.volumes: + raise _not_found() + body = req.json() or {} + vol = self.volumes[uuid] + + def modify() -> None: + if "size" in body: + size = -(-int(body["size"]) // 4096) * 4096 + reserve = vol["space"]["snapshot"]["reserve_percent"] + biggest = max([lun["space"]["size"] for lun in self._luns_in(uuid)] or [0]) + if size < MIN_VOLUME or size * (100 - reserve) // 100 < biggest: + raise _err(400, "Cannot shrink the volume below the space used by its " + "LUNs or namespaces.", "917627") + vol["size"] = size + + return self._job(f"PATCH /api/storage/volumes/{uuid}", modify) + + def _luns_in(self, vol_uuid: str) -> list[dict[str, Any]]: + objs = list(self.luns.values()) + list(self.namespaces.values()) + return [o for o in objs if o["location"]["volume"]["uuid"] == vol_uuid] + + @route("DELETE", "/api/storage/volumes/" + _U) + def delete_volume(self, req, uuid): + self._auth(req) + if uuid not in self.volumes: + raise _not_found() + + def delete() -> None: + contained = self._luns_in(uuid) + if any(o["status"]["mapped"] for o in contained): + raise _err(400, "Volume contains mapped LUNs or namespaces.", "917536") + for o in contained: + self.luns.pop(o["uuid"], None) + self.namespaces.pop(o["uuid"], None) + del self.volumes[uuid] + + return self._job(f"DELETE /api/storage/volumes/{uuid}", delete) + + # -- LUNs and namespaces ------------------------------------------------------ + + def _check_size(self, vol: dict[str, Any], size: int, block: int = 512) -> None: + if size < 4096 or size > MAX_LUN: + raise _err(400, f"Size {size} is out of range (4096..{MAX_LUN}).", "5374855") + if size % block: + raise _err(400, f"Size {size} is not a multiple of the block size {block}.", + "72089652") + if size > self._usable(vol): + raise _err(400, f'Size {size} exceeds the space available in volume ' + f'"{vol["name"]}".', "5374857") + + @route("GET", "/api/storage/luns") + def get_luns(self, req): + self._auth(req) + return self._collection(req, list(self.luns.values())) + + @route("GET", "/api/storage/luns/" + _U) + def get_lun(self, req, uuid): + self._auth(req) + if uuid not in self.luns: + raise _not_found() + return Reply(200, copy.deepcopy(self.luns[uuid])) + + @route("POST", "/api/storage/luns") + def post_lun(self, req): + self._auth(req) + body = req.json() or {} + svm = self._svm_of(body) + path = body.get("name", "") + vol = self._vol_of_path(path, svm["name"]) + if not body.get("os_type"): + raise _err(400, 'Field "os_type" is required.', "2") + if any(o["name"] == path for o in list(self.luns.values()) + + list(self.namespaces.values())): + raise _err(409, f'A LUN or namespace already exists at path "{path}".', "5374863") + size = int((body.get("space") or {}).get("size", 0)) + self._check_size(vol, size) + lid = self.add_lun(path, size, svm["name"]) + lun = self.luns[lid] + lun["os_type"] = body["os_type"] + requested = bool(((body.get("space") or {}).get("guarantee") or {}).get("requested")) + lun["space"]["guarantee"] = {"requested": requested, "reserved": requested} + return self._created(req, lun, f"/api/storage/luns/{lid}") + + @route("PATCH", "/api/storage/luns/" + _U) + def patch_lun(self, req, uuid): + self._auth(req) + lun = self.luns.get(uuid) + if lun is None: + raise _not_found() + size = ((req.json() or {}).get("space") or {}).get("size") + if size is not None: + size = int(size) + if size < lun["space"]["size"]: + raise _err(400, "Reducing the size of a LUN might cause permanent data loss " + "or corruption and is not supported by the LUN REST API.", + "5374922") + self._check_size(self.volumes[lun["location"]["volume"]["uuid"]], size) + lun["space"]["size"] = size + return Reply(200, {}) + + @route("DELETE", "/api/storage/luns/" + _U) + def delete_lun(self, req, uuid): + self._auth(req) + lun = self.luns.get(uuid) + if lun is None: + raise _not_found() + if lun["status"]["mapped"] and req.q("allow_delete_while_mapped") != "true": + raise _err(400, "The LUN is mapped; unmap it or set allow_delete_while_mapped.", + "5374875") + self.lun_maps = [m for m in self.lun_maps if m["lun"]["uuid"] != uuid] + del self.luns[uuid] + return Reply(200, {}) + + @route("GET", "/api/storage/namespaces") + def get_namespaces(self, req): + self._auth(req) + return self._collection(req, list(self.namespaces.values())) + + @route("POST", "/api/storage/namespaces") + def post_namespace(self, req): + self._auth(req) + body = req.json() or {} + svm = self._svm_of(body) + path = body.get("name", "") + vol = self._vol_of_path(path, svm["name"]) + if not body.get("os_type"): + raise _err(400, 'Field "os_type" is required.', "2") + if any(o["name"] == path for o in list(self.luns.values()) + + list(self.namespaces.values())): + raise _err(409, f'A LUN or namespace already exists at path "{path}".', "72090019") + space = body.get("space") or {} + block = int(space.get("block_size", 4096)) + if block not in (512, 4096): + raise _err(400, "block_size must be 512 or 4096.", "72089653") + size = int(space.get("size", 0)) + self._check_size(vol, size, block) + nid = str(uuid_mod.uuid4()) + self.namespaces[nid] = { + "uuid": nid, "name": path, "svm": svm, "os_type": body["os_type"], + "space": {"size": size, "block_size": block}, + "location": {"namespace": path.rsplit("/", 1)[1], + "volume": {"name": vol["name"], "uuid": vol["uuid"]}}, + "status": {"mapped": False, "state": "online"}, + } + return self._created(req, self.namespaces[nid], f"/api/storage/namespaces/{nid}") + + @route("PATCH", "/api/storage/namespaces/" + _U) + def patch_namespace(self, req, uuid): + self._auth(req) + ns = self.namespaces.get(uuid) + if ns is None: + raise _not_found() + size = ((req.json() or {}).get("space") or {}).get("size") + if size is not None: + size = int(size) + if size < ns["space"]["size"]: + raise _err(400, "Shrinking a namespace is not supported.", "72090031") + self._check_size(self.volumes[ns["location"]["volume"]["uuid"]], size, + ns["space"]["block_size"]) + ns["space"]["size"] = size + return Reply(200, {}) + + @route("DELETE", "/api/storage/namespaces/" + _U) + def delete_namespace(self, req, uuid): + self._auth(req) + ns = self.namespaces.get(uuid) + if ns is None: + raise _not_found() + if ns["status"]["mapped"] and req.q("allow_delete_while_mapped") != "true": + raise _err(400, "The namespace is mapped to a subsystem.", "72090024") + self.subsystem_maps = [m for m in self.subsystem_maps if m["namespace"]["uuid"] != uuid] + del self.namespaces[uuid] + return Reply(200, {}) + + # -- igroups ------------------------------------------------------------------- + + def _check_initiator(self, group: dict[str, Any], name: str) -> None: + proto = group["protocol"] + is_iscsi = name.lower().startswith(("iqn.", "eui.", "naa.")) + is_fc = bool(_WWPN_RE.match(name)) + if not (is_iscsi or is_fc) or (proto == "iscsi" and not is_iscsi) or ( + proto == "fcp" and not is_fc): + raise _err(400, f'Initiator "{name}" is not valid for an igroup of protocol ' + f'"{proto}".', "1254324") + for g in self.igroups.values(): + if g is group or g["svm"]["name"] != group["svm"]["name"]: + continue + if name.lower() in (i["name"].lower() for i in g["initiators"]) and \ + g["os_type"] != group["os_type"]: + raise _err(400, f'Initiator "{name}" is in igroup "{g["name"]}" with a ' + "different os_type.", "1254323") + if name.lower() in (i["name"].lower() for i in group["initiators"]): + raise _err(409, f'Initiator "{name}" is already in igroup "{group["name"]}".', + "1254327") + + @route("GET", "/api/protocols/san/igroups") + def get_igroups(self, req): + self._auth(req) + return self._collection(req, list(self.igroups.values())) + + @route("POST", "/api/protocols/san/igroups") + def post_igroup(self, req): + self._auth(req) + body = req.json() or {} + svm = self._svm_of(body) + name = body.get("name", "") + if not _IGROUP_RE.match(name): + raise _err(400, f'Invalid igroup name "{name}".', "5374737") + if any(g["name"] == name and g["svm"]["name"] == svm["name"] + for g in self.igroups.values()): + raise _err(409, f'An igroup named "{name}" already exists.', "5374734") + proto = body.get("protocol", "mixed") + if proto not in ("iscsi", "fcp", "mixed"): + raise _err(400, f'Invalid protocol "{proto}".', "2") + gid = str(uuid_mod.uuid4()) + group = {"uuid": gid, "name": name, "svm": svm, "protocol": proto, + "os_type": body.get("os_type", "linux"), "initiators": []} + for i in body.get("initiators") or []: + self._check_initiator(group, i["name"]) + group["initiators"].append({"name": i["name"]}) + self.igroups[gid] = group + return self._created(req, group, f"/api/protocols/san/igroups/{gid}") + + @route("PATCH", "/api/protocols/san/igroups/" + _U) + def patch_igroup(self, req, uuid): + self._auth(req) + group = self.igroups.get(uuid) + if group is None: + raise _not_found() + proto = (req.json() or {}).get("protocol") + if proto is not None: + if proto not in ("iscsi", "fcp", "mixed"): + raise _err(400, f'Invalid protocol "{proto}".', "2") + group["protocol"] = proto + return Reply(200, {}) + + @route("POST", "/api/protocols/san/igroups/" + _U + "/initiators") + def post_igroup_initiators(self, req, uuid): + self._auth(req) + group = self.igroups.get(uuid) + if group is None: + raise _not_found() + body = req.json() or {} + records = body.get("records") or [body] + for r in records: + self._check_initiator(group, r["name"]) + for r in records: + group["initiators"].append({"name": r["name"]}) + return Reply(201, {}) + + @route("DELETE", "/api/protocols/san/igroups/" + _U) + def delete_igroup(self, req, uuid): + self._auth(req) + if uuid not in self.igroups: + raise _not_found() + if any(m["igroup"]["uuid"] == uuid for m in self.lun_maps) and \ + req.q("allow_delete_while_mapped") != "true": + raise _err(400, "The igroup is mapped to one or more LUNs.", "5374852") + del self.igroups[uuid] + return Reply(200, {}) + + # -- lun-maps ---------------------------------------------------------------------- + + @route("GET", "/api/protocols/san/lun-maps") + def get_lun_maps(self, req): + self._auth(req) + return self._collection(req, self.lun_maps, keys=("svm", "lun", "igroup")) + + def _find(self, table: dict[str, dict[str, Any]], ref: dict[str, Any], svm: str, + what: str) -> dict[str, Any]: + for obj in table.values(): + if obj["svm"]["name"] != svm: + continue + if ref.get("uuid") == obj["uuid"] or (ref.get("name") and + ref.get("name") == obj["name"]): + return obj + raise _err(404, f'{what} "{ref.get("name") or ref.get("uuid")}" does not exist.', "4") + + @route("POST", "/api/protocols/san/lun-maps") + def post_lun_map(self, req): + self._auth(req) + body = req.json() or {} + svm = self._svm_of(body) + lun = self._find(self.luns, body.get("lun") or {}, svm["name"], "LUN") + group = self._find(self.igroups, body.get("igroup") or {}, svm["name"], "igroup") + if any(m["lun"]["uuid"] == lun["uuid"] and m["igroup"]["uuid"] == group["uuid"] + for m in self.lun_maps): + raise _err(409, "The LUN is already mapped to this igroup.", "5374922") + used = {m["logical_unit_number"] for m in self.lun_maps + if m["igroup"]["uuid"] == group["uuid"]} + number = body.get("logical_unit_number") + if number is None: + number = next(n for n in range(4096) if n not in used) + elif number in used: + raise _err(409, f"LUN number {number} is in use in this igroup.", "5374921") + m = {"svm": svm, "lun": {"uuid": lun["uuid"], "name": lun["name"]}, + "igroup": {"uuid": group["uuid"], "name": group["name"]}, + "logical_unit_number": number} + self.lun_maps.append(m) + lun["status"]["mapped"] = True + return self._created(req, m, f"/api/protocols/san/lun-maps/{lun['uuid']}/" + f"{group['uuid']}") + + @route("DELETE", "/api/protocols/san/lun-maps/" + r"(?P[0-9a-fA-F-]{36})/" + + r"(?P[0-9a-fA-F-]{36})") + def delete_lun_map(self, req, lun, igroup): + self._auth(req) + before = len(self.lun_maps) + self.lun_maps = [m for m in self.lun_maps + if not (m["lun"]["uuid"] == lun and m["igroup"]["uuid"] == igroup)] + if len(self.lun_maps) == before: + raise _not_found() + if lun in self.luns: + self.luns[lun]["status"]["mapped"] = any( + m["lun"]["uuid"] == lun for m in self.lun_maps) + return Reply(200, {}) + + # -- NVMe subsystems ----------------------------------------------------------------- + + @route("GET", "/api/protocols/nvme/subsystems") + def get_subsystems(self, req): + self._auth(req) + return self._collection(req, list(self.subsystems.values())) + + @staticmethod + def _check_nqn(nqn: str) -> None: + if not nqn.startswith("nqn."): + raise _err(400, f'Invalid host NQN "{nqn}".', "72089705") + + @route("POST", "/api/protocols/nvme/subsystems") + def post_subsystem(self, req): + self._auth(req) + body = req.json() or {} + svm = self._svm_of(body) + name = body.get("name", "") + if not _SUBSYS_RE.match(name): + raise _err(400, f'Invalid subsystem name "{name}".', "72089771") + if not body.get("os_type"): + raise _err(400, 'Field "os_type" is required.', "2") + if any(s["name"] == name and s["svm"]["name"] == svm["name"] + for s in self.subsystems.values()): + raise _err(409, f'Subsystem "{name}" already exists.', "72089709") + hosts = [] + for h in body.get("hosts") or []: + self._check_nqn(h["nqn"]) + hosts.append({"nqn": h["nqn"]}) + sid = str(uuid_mod.uuid4()) + self.subsystems[sid] = {"uuid": sid, "name": name, "svm": svm, + "os_type": body["os_type"], "comment": body.get("comment", ""), + "hosts": hosts, + "target_nqn": f"nqn.1992-08.com.netapp:sn.{sid.replace('-', '')}" + f":subsystem.{name}"} + return self._created(req, self.subsystems[sid], f"/api/protocols/nvme/subsystems/{sid}") + + @route("POST", "/api/protocols/nvme/subsystems/" + _U + "/hosts") + def post_subsystem_hosts(self, req, uuid): + self._auth(req) + sub = self.subsystems.get(uuid) + if sub is None: + raise _not_found() + body = req.json() or {} + records = body.get("records") or [body] + have = {h["nqn"] for h in sub["hosts"]} + for r in records: + self._check_nqn(r["nqn"]) + if r["nqn"] in have: + raise _err(409, f'Host "{r["nqn"]}" is already in subsystem "{sub["name"]}".', + "72089708") + sub["hosts"].extend({"nqn": r["nqn"]} for r in records) + return Reply(201, {}) + + @route("DELETE", "/api/protocols/nvme/subsystems/" + _U + "/hosts/(?P[^/]+)") + def delete_subsystem_host(self, req, uuid, nqn): + self._auth(req) + sub = self.subsystems.get(uuid) + if sub is None: + raise _not_found() + nqn = unquote(nqn) + if nqn not in {h["nqn"] for h in sub["hosts"]}: + raise _not_found() + sub["hosts"] = [h for h in sub["hosts"] if h["nqn"] != nqn] + return Reply(200, {}) + + @route("DELETE", "/api/protocols/nvme/subsystems/" + _U) + def delete_subsystem(self, req, uuid): + self._auth(req) + sub = self.subsystems.get(uuid) + if sub is None: + raise _not_found() + if any(m["subsystem"]["uuid"] == uuid for m in self.subsystem_maps) and \ + req.q("allow_delete_while_mapped") != "true": + raise _err(400, "The subsystem has mapped namespaces.", "72090025") + if sub["hosts"] and req.q("allow_delete_with_hosts") != "true": + raise _err(400, "The subsystem has hosts; set allow_delete_with_hosts.", + "72090026") + for m in [m for m in self.subsystem_maps if m["subsystem"]["uuid"] == uuid]: + self.namespaces[m["namespace"]["uuid"]]["status"]["mapped"] = False + self.subsystem_maps = [m for m in self.subsystem_maps if m["subsystem"]["uuid"] != uuid] + del self.subsystems[uuid] + return Reply(200, {}) + + # -- subsystem-maps -------------------------------------------------------------------- + + @route("GET", "/api/protocols/nvme/subsystem-maps") + def get_subsystem_maps(self, req): + self._auth(req) + return self._collection(req, self.subsystem_maps, keys=("svm", "namespace", "subsystem")) + + @route("POST", "/api/protocols/nvme/subsystem-maps") + def post_subsystem_map(self, req): + self._auth(req) + body = req.json() or {} + svm = self._svm_of(body) + ns = self._find(self.namespaces, body.get("namespace") or {}, svm["name"], "Namespace") + sub = self._find(self.subsystems, body.get("subsystem") or {}, svm["name"], + "Subsystem") + if any(m["namespace"]["uuid"] == ns["uuid"] for m in self.subsystem_maps): + raise _err(400, "The namespace is already mapped to a subsystem. A namespace " + "can be mapped to only one subsystem.", "72089771") + used = {int(m["nsid"].rstrip("h"), 16) for m in self.subsystem_maps + if m["subsystem"]["uuid"] == sub["uuid"]} + nsid = next(n for n in range(1, 4096) if n not in used) + m = {"svm": svm, "namespace": {"uuid": ns["uuid"], "name": ns["name"]}, + "subsystem": {"uuid": sub["uuid"], "name": sub["name"]}, + "nsid": f"{nsid:08x}h"} + self.subsystem_maps.append(m) + ns["status"]["mapped"] = True + return self._created(req, m, f"/api/protocols/nvme/subsystem-maps/{sub['uuid']}/" + f"{ns['uuid']}") + + @route("DELETE", "/api/protocols/nvme/subsystem-maps/" + r"(?P[0-9a-fA-F-]{36})/" + + r"(?P[0-9a-fA-F-]{36})") + def delete_subsystem_map(self, req, sub, ns): + self._auth(req) + before = len(self.subsystem_maps) + self.subsystem_maps = [m for m in self.subsystem_maps + if not (m["subsystem"]["uuid"] == sub + and m["namespace"]["uuid"] == ns)] + if len(self.subsystem_maps) == before: + raise _not_found() + if ns in self.namespaces: + self.namespaces[ns]["status"]["mapped"] = False + return Reply(200, {}) + + def not_routed(self, req: Request) -> Reply: + return Reply(404, {"error": {"message": f"API not found: {req.method} {req.path}", + "code": "3"}}) + + +def contract_setup(**options: Any) -> ContractSetup: + fake = FakeNetAppOntap(username="admin", password="netapp1!", svm="svm1") + return ContractSetup( + fake=fake, + config=make_config("netapp-ontap", "https://ontap.fake.example", + **{"svm": "svm1", **options}), + credential=Credential({"username": SecretStr("admin"), + "password": SecretStr("netapp1!")}), + bad_credential=Credential({"username": SecretStr("admin"), + "password": SecretStr("wrong")}), + # Default protocol_family is scsi: the contract maps every volume to + # hosts of each listed protocol, so only SCSI initiators are listed. + # NVMe is covered by tests/unit/storage_arrays/test_netapp_ontap.py. + initiators={ + Protocol.ISCSI: ( + (Initiator(protocol=Protocol.ISCSI, address="iqn.2026-01.io.sb:host-a"),), + (Initiator(protocol=Protocol.ISCSI, address="iqn.2026-01.io.sb:host-b"),), + ), + Protocol.FC: ( + (Initiator(protocol=Protocol.FC, address="21:00:00:24:FF:4C:1A:2B"),), + (Initiator(protocol=Protocol.FC, address="21:00:00:24:ff:4c:1a:2c"),), + ), + }, + create_foreign_volume=lambda name, size: fake.add_foreign_lun(name, size), + ) diff --git a/tests/unit/storage_arrays/test_contract.py b/tests/unit/storage_arrays/test_contract.py index 6e36507a59..1e63e0fdc8 100644 --- a/tests/unit/storage_arrays/test_contract.py +++ b/tests/unit/storage_arrays/test_contract.py @@ -76,7 +76,7 @@ def test_create_get_find(harness, cleanup): assert vol.size_bytes == round_size(10 * GIB + 1, caps.size_granularity_bytes, caps.min_size_bytes) assert vol.identifier and vol.identifier == vol.identifier.lower() - assert vol.wwn is None or vol.wwn.startswith("naa.") + assert vol.wwn is None or vol.wwn.startswith(("naa.", "eui.")) assert vol.nguid is None or vol.nguid.startswith("eui.") got = harness.client.get_volume(vol.id) @@ -177,6 +177,11 @@ def test_existing_host_gets_missing_initiators(harness, cleanup): name = f"sbtest-grow-{uuid.uuid4().hex[:6]}" host = harness.client.ensure_host(HostSpec(name=name, initiators=a)) cleanup[1].append(host) + limit = harness.client.capabilities.max_initiators_per_host + if limit is not None and len(a + b) > limit: + with pytest.raises(ArrayError, match="at most"): + harness.client.ensure_host(HostSpec(name=name, initiators=a + b)) + return assert harness.client.ensure_host(HostSpec(name=name, initiators=a + b)) == host # b's initiators now belong to that host: claiming them elsewhere conflicts with pytest.raises(ArrayConflictError): @@ -196,6 +201,20 @@ def test_wrong_identifier_is_refused(harness, cleanup): assert harness.client.get_volume(vol.id) is not None +def test_volume_of_another_record_is_refused(harness, cleanup): + """A reused array id/WWN must not pass for the recorded volume: the + name derived from the recorded UUID pins it.""" + vol_uuid = _uuid() + vol = harness.client.create_volume(vol_uuid, GIB) + cleanup[0].append(vol.id) + with pytest.raises(ArrayConflictError, match="name does not match"): + harness.client.delete_volume(vol.id, vol.identifier, volume_uuid=_uuid()) + with pytest.raises(ArrayConflictError, match="name does not match"): + harness.client.resize_volume(vol.id, 4 * GIB, volume_uuid=_uuid()) + assert harness.client.delete_volume(vol.id, vol.identifier, volume_uuid=vol_uuid) + cleanup[0].remove(vol.id) + + def test_foreign_volume_is_refused(harness): if harness.live: pytest.skip("live tier never touches foreign volumes") @@ -236,14 +255,11 @@ def test_rotated_credential_is_picked_up(harness): from pydantic import SecretStr from simplyblock_core.credentials import Credential - old_secret_values = {harness.setup.credential.get(k).get_secret_value() - for k in harness.setup.credential.field_names} harness.provider.credential = Credential({k: SecretStr(v) for k, v in new.items()}) - # A basic-auth adapter keeps the old password in its session until it is - # rejected; either way the client must recover with one invalidation. + # The client still holds the old credential; the array rejects it, the + # client invalidates once, resolves the rotated secret and succeeds. harness.client.get_info() - assert harness.provider.invalidated <= 1 - assert old_secret_values # silence unused + assert harness.provider.invalidated == 1 def test_server_error_does_not_leak_credentials(harness): @@ -268,3 +284,19 @@ def test_unsupported_protocol_is_refused_before_calling_the_array(harness): with pytest.raises(ArrayError, match="does not support"): harness.client.ensure_host(HostSpec(name="sbtest-unsup", initiators=(Initiator(protocol=p, address=address),))) + + +def test_delete_host_with_mappings_is_refused(harness, cleanup): + """Deleting a host must never silently drop a live mapping.""" + protocol = _protocols(harness)[0] + vol = harness.client.create_volume(_uuid(), GIB) + cleanup[0].append(vol.id) + host = harness.client.ensure_host(_host(harness, protocol, 0)) + cleanup[1].append(host) + harness.client.map_volume(vol.id, host) + try: + harness.client.delete_host(host) + except ArrayConflictError: + pass # refused: the expected outcome on arrays that own host objects + # Either way (refused, or a no-op as for PowerFlex SDCs), the mapping survives. + assert [m.host_id for m in harness.client.list_mappings(vol.id)] == [host] diff --git a/tests/unit/storage_arrays/test_dell_powerflex.py b/tests/unit/storage_arrays/test_dell_powerflex.py new file mode 100644 index 0000000000..504cef40ea --- /dev/null +++ b/tests/unit/storage_arrays/test_dell_powerflex.py @@ -0,0 +1,189 @@ +"""Dell PowerFlex specifics beyond the shared contract.""" +from __future__ import annotations + +import uuid + +import pytest + +from simplyblock_core.storage_arrays.base import ( + ArrayConflictError, + ArrayError, + ArrayNotFoundError, + ArrayRequestError, + HostSpec, + Initiator, + Protocol, +) +from simplyblock_core.storage_arrays.client import ArrayClient +from simplyblock_core.storage_arrays.testing import FakeTransport, make_config +from simplyblock_core.storage_arrays.testing.dell_powerflex import ( + FakePowerFlex, + contract_setup, +) + +from .conftest import StaticProvider + +GIB = 1 << 30 + + +def _client(setup, **options): + config = setup.config + if options: + config = make_config("dell-powerflex", config.endpoint, + **{**config.options, **options}) + return ArrayClient(config, StaticProvider(setup.credential), # type: ignore[arg-type] + transport=FakeTransport(setup.fake), + session_kwargs={"sleep": lambda s: None}) + + +def _sdc(setup, which=0) -> Initiator: + return setup.initiators[Protocol.SDC][which][0] + + +@pytest.fixture(params=[3, 4], ids=["v3-token", "v4-oauth"]) +def setup(request): + return contract_setup(generation=request.param) + + +def test_auto_auth_uses_generation_specific_login(setup): + with _client(setup) as c: + info = c.get_info() + fake: FakePowerFlex = setup.fake + paths = [p for _, p in fake.requests] + assert paths[0] == "/rest/auth/login" + if fake.generation == 3: + assert "/api/login" in paths and "R3_6" in info.version + else: + assert "/api/login" not in paths and "R4_5" in info.version + # close() logged out + assert not fake.tokens and not fake.access_tokens + + +def test_pinned_token_auth_skips_oauth_probe(): + setup = contract_setup(generation=3) + with _client(setup, auth="token") as c: + c.get_info() + assert ("POST", "/rest/auth/login") not in setup.fake.requests + + +def test_pinned_oauth_on_3x_fails(): + setup = contract_setup(generation=3) + with _client(setup, auth="oauth") as c, pytest.raises(ArrayNotFoundError): + c.get_info() + + +def test_bad_options_rejected(): + setup = contract_setup() + for opts in ({"auth": "kerberos"}, {"sdc_naming": "maybe"}, {"bogus": 1}): + with _client(setup, **opts) as c, pytest.raises(ArrayError): + c.get_info() + config = make_config("dell-powerflex", "https://pf.example") + with ArrayClient(config, StaticProvider(setup.credential), # type: ignore[arg-type] + transport=FakeTransport(setup.fake)) as c, \ + pytest.raises(ArrayError, match="storage_pool_id"): + c.get_info() + + +def test_sizes_round_to_8_gib(setup): + with _client(setup) as c: + vol = c.create_volume(str(uuid.uuid4()), 10 * GIB) + assert vol.size_bytes == 16 * GIB + raw = setup.fake.volumes[vol.id] + assert raw["sizeInKb"] == 16 * 1024 * 1024 + assert raw["volumeType"] == "ThinProvisioned" + grown = c.resize_volume(vol.id, 17 * GIB) + assert grown.size_bytes == 24 * GIB + assert vol.wwn is None and vol.nguid is None + assert vol.identifier == f"id.{vol.id}" + + +def test_not_found_500_is_none_but_other_500_raises(setup): + with _client(setup) as c: + assert c.get_volume("deadbeef00000001") is None + c.get_info() + setup.fake.fail_next(500, {"message": "MDM is busy", "httpStatusCode": 500, + "errorCode": 3}, path="Volume::") + with pytest.raises(ArrayRequestError, match="MDM is busy"): + c.get_volume("deadbeef00000001") + + +def test_duplicate_name_conflicts(setup): + setup.fake.add_volume("sb-taken", 8 * GIB) + with _client(setup) as c: + c.get_info() + adapter = c._adapter + assert adapter is not None + with pytest.raises(ArrayConflictError): + adapter.create_volume("sb-taken", 8 * GIB) + + +def test_ensure_host_finds_preregistered_sdc_and_claims_name(setup): + with _client(setup) as c: + host = c.ensure_host(HostSpec(name="worker-1", initiators=(_sdc(setup),))) + assert setup.fake.sdcs[host]["name"] == "worker-1" + # GUID match is case-insensitive + lower = Initiator(protocol=Protocol.SDC, address=_sdc(setup).address.lower()) + assert c.ensure_host(HostSpec(name="worker-1", initiators=(lower,))) == host + with pytest.raises(ArrayConflictError, match="worker-1"): + c.ensure_host(HostSpec(name="worker-2", initiators=(_sdc(setup),))) + # delete_host leaves the SDC alone + c.delete_host(host) + assert host in setup.fake.sdcs + + +def test_unknown_sdc_guid_is_not_found(setup): + ghost = Initiator(protocol=Protocol.SDC, address=str(uuid.uuid4())) + with _client(setup) as c, pytest.raises(ArrayNotFoundError, match="install the SDC"): + c.ensure_host(HostSpec(name="worker-9", initiators=(ghost,))) + + +def test_multi_sdc_host_is_refused_by_the_client(setup): + spec = HostSpec(name="worker-1", initiators=(_sdc(setup, 0), _sdc(setup, 1))) + with _client(setup) as c, pytest.raises(ArrayError, match="at most 1"): + c.ensure_host(spec) + + +def test_admin_named_sdc_and_ignore_mode(setup): + sid = setup.fake.add_sdc("ABCDEF01-0000-0000-0000-000000000001", name="esx-prod-7") + spec = HostSpec(name="worker-1", initiators=( + Initiator(protocol=Protocol.SDC, address="ABCDEF01-0000-0000-0000-000000000001"),)) + with _client(setup) as c, pytest.raises(ArrayConflictError): + c.ensure_host(spec) + with _client(setup, sdc_naming="ignore") as c: + assert c.ensure_host(spec) == sid + assert setup.fake.sdcs[sid]["name"] == "esx-prod-7" + + +def test_mapping_multi_sdc_and_null_mapped_info(setup): + with _client(setup) as c: + vol = c.create_volume(str(uuid.uuid4()), 8 * GIB) + assert setup.fake.volumes[vol.id]["mappedSdcInfo"] is None + assert c.list_mappings(vol.id) == [] + a = c.ensure_host(HostSpec(name="w-a", initiators=(_sdc(setup, 0),))) + b = c.ensure_host(HostSpec(name="w-b", initiators=(_sdc(setup, 1),))) + m = c.map_volume(vol.id, a) + assert m.lun is None + c.map_volume(vol.id, b) # needs allowMultipleMappings + assert {x.host_id for x in c.list_mappings(vol.id)} == {a, b} + c.unmap_volume(vol.id, a) + c.unmap_volume(vol.id, b) + assert setup.fake.volumes[vol.id]["mappedSdcInfo"] is None + assert c.delete_volume(vol.id) + + +def test_remove_mapped_volume_refused_by_array(setup): + with _client(setup) as c: + vol = c.create_volume(str(uuid.uuid4()), 8 * GIB) + host = c.ensure_host(HostSpec(name="w-a", initiators=(_sdc(setup, 0),))) + c.map_volume(vol.id, host) + adapter = c._adapter + assert adapter is not None + with pytest.raises(ArrayConflictError, match="mapped"): + adapter.delete_volume(vol.id) + + +def test_session_expiry_relogs_in(setup): + with _client(setup) as c: + c.get_info() + setup.fake.expire_sessions() + assert c.find_volume(str(uuid.uuid4())) is None diff --git a/tests/unit/storage_arrays/test_dell_powermax.py b/tests/unit/storage_arrays/test_dell_powermax.py new file mode 100644 index 0000000000..b3eceedfba --- /dev/null +++ b/tests/unit/storage_arrays/test_dell_powermax.py @@ -0,0 +1,256 @@ +"""Dell PowerMax specifics beyond the shared contract: cylinder sizing, +async jobs, one storage group + masking view per volume/host, hex LUNs, +non-unique volume identifiers.""" +from __future__ import annotations + +import uuid + +import pytest + +from simplyblock_core.storage_arrays.adapters.dell_powermax import ( + CYLINDER_BYTES, + DellPowerMaxAdapter, +) +from simplyblock_core.storage_arrays.base import ( + AdapterContext, + ArrayConflictError, + ArrayError, + ArrayNotFoundError, + ArrayRequestError, + ArrayUnsupportedError, + HostSpec, + Initiator, + Protocol, +) +from simplyblock_core.storage_arrays.client import ArrayClient +from simplyblock_core.storage_arrays.http import RestSession +from simplyblock_core.storage_arrays.testing import FakeTransport +from simplyblock_core.storage_arrays.testing.dell_powermax import ( + SYMMETRIX_ID, + contract_setup, +) + +GIB = 1 << 30 + + +class _Provider: + def __init__(self, credential): + self.credential = credential + + def resolve(self, ref, context): + return self.credential + + def invalidate(self, ref=None): + pass + + +def _client(setup) -> ArrayClient: + return ArrayClient(setup.config, _Provider(setup.credential), # type: ignore[arg-type] + transport=FakeTransport(setup.fake), + session_kwargs={"sleep": lambda s: None}) + + +def _adapter(setup, **options) -> DellPowerMaxAdapter: + opts = dict(setup.config.options) + opts.update(options) + opts = {k: v for k, v in opts.items() if v is not None} + config = setup.config.model_copy(update={"options": opts}) + session = RestSession.for_config(config, transport=FakeTransport(setup.fake), + sleep=lambda s: None) + adapter = DellPowerMaxAdapter(AdapterContext(config, setup.credential, session)) + adapter.login() + return adapter + + +def _iscsi(name: str) -> HostSpec: + return HostSpec(name=name, initiators=( + Initiator(protocol=Protocol.ISCSI, address=f"iqn.2026-01.io.sb:{name}"),)) + + +@pytest.fixture() +def setup(): + return contract_setup() + + +def test_cylinder_granularity(setup): + client = _client(setup) + vol = client.create_volume(str(uuid.uuid4()), 10 * GIB) + assert CYLINDER_BYTES == 1_966_080 + assert vol.size_bytes % CYLINDER_BYTES == 0 + assert vol.size_bytes == 5462 * CYLINDER_BYTES # ceil(10 GiB / 1920 KiB) + assert setup.fake.volumes[vol.id]["cap_cyl"] == 5462 + + +def test_one_storage_group_per_volume(setup): + client = _client(setup) + vol = client.create_volume(str(uuid.uuid4()), GIB) + sg = setup.fake.storage_groups[vol.name] + assert sg["volumes"] == [vol.id] and sg["srp"] == "SRP_1" and sg["slo"] == "NONE" + assert vol.wwn == "naa." + setup.fake.volumes[vol.id]["effective_wwn"].lower() + assert client.delete_volume(vol.id) + assert vol.name not in setup.fake.storage_groups + assert setup.fake.volumes == {} + + +def test_service_level_is_applied(setup): + adapter = _adapter(setup, service_level="Diamond") + vol = adapter.create_volume("sb-diamond", GIB) + assert setup.fake.storage_groups[vol.name]["slo"] == "Diamond" + + +def test_async_jobs_are_polled(setup): + adapter = _adapter(setup, async_jobs=True) + vol = adapter.create_volume("sb-async", 2 * GIB) + vol = adapter.resize_volume(vol.id, 4 * GIB) + assert vol.size_bytes >= 4 * GIB + host = adapter.ensure_host(_iscsi("sbtest-async")) + m = adapter.map_volume(vol.id, host) + assert m.lun == 1 + adapter.unmap_volume(vol.id, host) + adapter.delete_volume(vol.id) + jobs = setup.fake.jobs.values() + assert len(jobs) >= 5 and all(j["status"] == "SUCCEEDED" for j in jobs) + assert all(j["_polls"] == 2 for j in jobs) + assert any("/system/job/" in path for _, path in setup.fake.requests) + + +def test_failed_job_is_classified(setup): + adapter = _adapter(setup, async_jobs=True) + vol = adapter.create_volume("sb-jobfail", 4 * GIB) + with pytest.raises(ArrayRequestError, match="FAILED.*larger"): + adapter.resize_volume(vol.id, 2 * GIB) + adapter.ensure_host(_iscsi("sbtest-j1")) + with pytest.raises(ArrayConflictError, match="already in use"): + adapter.ensure_host(HostSpec(name="sbtest-j2", + initiators=_iscsi("sbtest-j1").initiators)) + + +def test_job_timeout(setup): + adapter = _adapter(setup, async_jobs=True, job_timeout_s=2) + with pytest.raises(ArrayRequestError, match="did not finish"): + adapter.create_volume("sb-slow", GIB) + + +def test_hex_lun_addresses(setup): + setup.fake.first_lun = 0x1A + adapter = _adapter(setup) + vol = adapter.create_volume("sb-hexlun", GIB) + host = adapter.ensure_host(_iscsi("sbtest-hex")) + assert adapter.map_volume(vol.id, host).lun == 26 + assert adapter.list_mappings(vol.id)[0].lun == 26 + + +def test_port_group_by_protocol(setup): + adapter = _adapter(setup) + vol = adapter.create_volume("sb-pg", GIB) + fc = adapter.ensure_host(HostSpec(name="sbtest-fc", initiators=( + Initiator(protocol=Protocol.FC, address="21:00:00:24:FF:4C:1A:2B"),))) + assert setup.fake.hosts[fc]["initiator"] == ["21000024ff4c1a2b"] + adapter.map_volume(vol.id, fc) + view = setup.fake.views[DellPowerMaxAdapter.view_name(vol.name, fc)] + assert view["pg"] == "sb_pg_fc" + + +def test_single_port_group_name(setup): + adapter = _adapter(setup, port_group="sb_pg_iscsi") + vol = adapter.create_volume("sb-pg1", GIB) + host = adapter.ensure_host(_iscsi("sbtest-pg1")) + adapter.map_volume(vol.id, host) + assert setup.fake.views[f"{vol.name}_{host}"]["pg"] == "sb_pg_iscsi" + + +def test_map_without_port_group_is_refused(setup): + adapter = _adapter(setup, port_group=None) + vol = adapter.create_volume("sb-nopg", GIB) + host = adapter.ensure_host(_iscsi("sbtest-nopg")) + with pytest.raises(ArrayError, match="port_group"): + adapter.map_volume(vol.id, host) + with pytest.raises(ArrayNotFoundError): + adapter.map_volume(vol.id, "sbtest-missing") + + +def test_long_host_name_gets_hashed_view_name(setup): + adapter = _adapter(setup) + vol = adapter.create_volume("sb-" + "a" * 24, GIB) + name = "sbtest-" + "h" * 57 + host = adapter.ensure_host(_iscsi(name)) + adapter.map_volume(vol.id, host) + (view,) = setup.fake.views + assert len(view) <= 64 and view.startswith(vol.name + "_") + assert adapter.map_volume(vol.id, host).host_id == host # idempotent + + +def test_duplicate_identifiers(setup): + adapter = _adapter(setup) + vol = adapter.create_volume("sb-dup", GIB) + setup.fake.add_volume("sb-dup", GIB) # same identifier, outside our SG + assert adapter.find_volume("sb-dup") == vol + setup.fake.add_volume("sb-dup2", GIB) + setup.fake.add_volume("sb-dup2", GIB) + with pytest.raises(ArrayConflictError, match="2 PowerMax devices"): + adapter.find_volume("sb-dup2") + + +def test_leftover_empty_storage_group_is_reused(setup): + adapter = _adapter(setup) + setup.fake.storage_groups["sb-left"] = setup.fake._sg_record("sb-left", "SRP_1", None) + vol = adapter.create_volume("sb-left", GIB) + assert setup.fake.storage_groups["sb-left"]["volumes"] == [vol.id] + with pytest.raises(ArrayConflictError, match="already exists"): + adapter.create_volume("sb-left", GIB) + + +def test_shared_storage_group_mapping_is_not_unmapped(setup): + adapter = _adapter(setup) + vol = adapter.create_volume("sb-shared", GIB) + host = adapter.ensure_host(_iscsi("sbtest-shared")) + fake = setup.fake + fake.storage_groups["customer_sg"] = fake._sg_record("customer_sg", "SRP_1", None) + fake.storage_groups["customer_sg"]["volumes"].append(vol.id) + fake.volumes[vol.id]["storageGroupId"].append("customer_sg") + adapter._call("POST", f"{adapter._slo}/maskingview", json={ + "maskingViewId": "customer_mv", + "hostOrHostGroupSelection": {"useExistingHostParam": {"hostId": host}}, + "portGroupSelection": {"useExistingPortGroupParam": {"portGroupId": "sb_pg_iscsi"}}, + "storageGroupSelection": {"useExistingStorageGroupParam": { + "storageGroupId": "customer_sg"}}}) + assert [m.host_id for m in adapter.list_mappings(vol.id)] == [host] + with pytest.raises(ArrayConflictError, match="shared storage group"): + adapter.unmap_volume(vol.id, host) + + +def test_errors_and_lookups(setup): + adapter = _adapter(setup) + assert adapter.get_volume("0FFFF") is None + assert adapter.list_mappings("0FFFF") == [] + adapter.unmap_volume("0FFFF", "nobody") + adapter.delete_host("nobody") + with pytest.raises(ArrayNotFoundError): + adapter.delete_volume("0FFFF") + + +def test_get_info_and_version_check(setup): + info = _adapter(setup).get_info() + assert info.model == "PowerMax_8500" and info.serial == SYMMETRIX_ID + assert "6079" in info.version + with pytest.raises(ArrayUnsupportedError, match="92"): + _adapter(setup, api_version="92").get_info() + + +def test_unknown_symmetrix(setup): + with pytest.raises(ArrayNotFoundError): + _adapter(setup, symmetrix_id="000197900999").get_info() + + +def test_symmetrix_id_is_required(setup): + config = setup.config.model_copy(update={"options": {}}) + session = RestSession.for_config(config, transport=FakeTransport(setup.fake)) + with pytest.raises(ArrayError, match="symmetrix_id"): + DellPowerMaxAdapter(AdapterContext(config, setup.credential, session)) + + +def test_basic_auth_on_every_request(setup): + adapter = _adapter(setup) + assert adapter.session.http.auth == ("smc", "pmax-pass") + adapter.close() + assert adapter.session.http.auth is None diff --git a/tests/unit/storage_arrays/test_dell_powerstore.py b/tests/unit/storage_arrays/test_dell_powerstore.py new file mode 100644 index 0000000000..eac8016a3b --- /dev/null +++ b/tests/unit/storage_arrays/test_dell_powerstore.py @@ -0,0 +1,212 @@ +"""Dell PowerStore specifics beyond the shared contract: CSRF token and +session cookie, PostgREST paging, 8 KiB granularity, 422 classification.""" +from __future__ import annotations + +import uuid + +import pytest +from pydantic import SecretStr + +from simplyblock_core.credentials import Credential +from simplyblock_core.storage_arrays.adapters.dell_powerstore import ( + TOKEN_HEADER, + DellPowerStoreAdapter, + powerstore_nguid, + powerstore_wwn, +) +from simplyblock_core.storage_arrays.base import ( + AdapterContext, + ArrayConflictError, + ArrayError, + HostSpec, + Initiator, + Protocol, +) +from simplyblock_core.storage_arrays.client import ArrayClient +from simplyblock_core.storage_arrays.http import RestSession +from simplyblock_core.storage_arrays.testing import FakeTransport, make_config +from simplyblock_core.storage_arrays.testing.dell_powerstore import contract_setup + +GIB = 1 << 30 + + +class _Provider: + def __init__(self, credential): + self.credential = credential + + def resolve(self, ref, context): + return self.credential + + def invalidate(self, ref=None): + pass + + +@pytest.fixture() +def setup(): + return contract_setup() + + +@pytest.fixture() +def client(setup): + c = ArrayClient(setup.config, _Provider(setup.credential), # type: ignore[arg-type] + transport=FakeTransport(setup.fake), + session_kwargs={"sleep": lambda s: None}) + yield c + c.close() + + +def _adapter(setup, **options) -> DellPowerStoreAdapter: + config = setup.config.model_copy(update={"options": options}) + session = RestSession.for_config(config, transport=FakeTransport(setup.fake)) + adapter = DellPowerStoreAdapter(AdapterContext(config, setup.credential, session)) + adapter.login() + return adapter + + +def _iscsi(name: str) -> HostSpec: + return HostSpec(name=name, initiators=( + Initiator(protocol=Protocol.ISCSI, address=f"iqn.2026-01.io.sb:{name}"),)) + + +def test_login_keeps_cookie_and_csrf_token_not_basic_auth(setup): + adapter = _adapter(setup) + assert adapter.session.http.auth is None + assert adapter.session.headers[TOKEN_HEADER] in setup.fake.sessions.values() + assert "auth_cookie" in adapter.session.http.cookies + vol = adapter.create_volume("sb-csrf", GIB) + assert vol.size_bytes == GIB + + +def test_mutation_without_csrf_token_is_forbidden(setup): + adapter = _adapter(setup) + adapter.session.headers.pop(TOKEN_HEADER) + assert adapter.find_volume("sb-none") is None # GET needs only the cookie + with pytest.raises(ArrayError, match="403"): + adapter.create_volume("sb-nocsrf", GIB) + + +def test_close_logs_out(setup): + adapter = _adapter(setup) + assert len(setup.fake.sessions) == 1 + adapter.close() + assert setup.fake.sessions == {} + assert ("POST", "/api/rest/logout") in setup.fake.requests + + +def test_size_is_rounded_to_8k(client, setup): + vol = client.create_volume(str(uuid.uuid4()), GIB + 1) + assert vol.size_bytes == GIB + 8192 + assert setup.fake.volumes[vol.id]["size"] % 8192 == 0 + + +def test_fake_rejects_unaligned_size(setup): + adapter = _adapter(setup) + with pytest.raises(ArrayError, match="multiple of 8192"): + adapter.create_volume("sb-odd", GIB + 512) + + +def test_identity_format(client): + vol = client.create_volume(str(uuid.uuid4()), GIB) + assert vol.wwn and vol.wwn.startswith("naa.68ccf098") and vol.wwn == vol.wwn.lower() + assert vol.nguid and vol.nguid.startswith("eui.") and len(vol.nguid) == 4 + 32 + assert powerstore_wwn("NAA.68CCF098ABC") == "naa.68ccf098abc" + assert powerstore_nguid("nguid.ABCD") == "eui.abcd" + assert powerstore_wwn(None) is None and powerstore_nguid("") is None + + +def test_select_and_filter_are_sent(client, setup): + client.find_volume(str(uuid.uuid4())) + adapter = client._adapter + assert adapter is not None + # unknown select fields are refused by the array (400), not silently ignored + with pytest.raises(ArrayError, match="400"): + adapter._list("/volume", "id,bogus") + + +def test_paged_host_lookup(setup): + setup.fake.page_limit = 2 + adapter = _adapter(setup) + ids = [adapter.ensure_host(_iscsi(f"sbtest-page-{i}")) for i in range(5)] + assert len(set(ids)) == 5 + # the last host sits on the third page of an unfiltered listing + assert len(adapter._list("/host", "id,name")) == 5 + assert adapter.ensure_host(_iscsi("sbtest-page-4")) == ids[4] + + +def test_fc_initiators_are_colon_separated_and_deduplicated(setup): + adapter = _adapter(setup) + spec = HostSpec(name="sbtest-fc", initiators=( + Initiator(protocol=Protocol.FC, address="0x21000024FF4C1A2B"),)) + host_id = adapter.ensure_host(spec) + ports = setup.fake.hosts[host_id]["host_initiators"] + assert [(p["port_name"], p["port_type"]) for p in ports] == [ + ("21:00:00:24:ff:4c:1a:2b", "FC")] + grown = HostSpec(name="sbtest-fc", initiators=spec.initiators + ( + Initiator(protocol=Protocol.FC, address="21:00:00:24:ff:4c:1a:2c"),)) + assert adapter.ensure_host(grown) == host_id + assert adapter.ensure_host(grown) == host_id + assert len(setup.fake.hosts[host_id]["host_initiators"]) == 2 + + +def test_nvme_host_uses_nvme_port_type(setup): + adapter = _adapter(setup) + spec = HostSpec(name="sbtest-nvme", initiators=( + Initiator(protocol=Protocol.NVME_TCP, address="nqn.2014-08.org.nvmexpress:uuid:x"),)) + host_id = adapter.ensure_host(spec) + assert setup.fake.hosts[host_id]["host_initiators"][0]["port_type"] == "NVMe" + assert setup.fake.hosts[host_id]["os_type"] == "Linux" + + +def test_initiator_conflict_is_classified(setup): + adapter = _adapter(setup) + adapter.ensure_host(_iscsi("sbtest-one")) + other = HostSpec(name="sbtest-two", initiators=_iscsi("sbtest-one").initiators) + with pytest.raises(ArrayConflictError, match="already registered"): + adapter.ensure_host(other) + + +def test_delete_attached_volume_is_conflict(setup): + adapter = _adapter(setup) + vol = adapter.create_volume("sb-attached", GIB) + host = adapter.ensure_host(_iscsi("sbtest-att")) + m = adapter.map_volume(vol.id, host) + assert m.lun == 1 + with pytest.raises(ArrayConflictError): + adapter.delete_volume(vol.id) + with pytest.raises(ArrayConflictError): + adapter.delete_host(host) + adapter.unmap_volume(vol.id, host) + adapter.delete_volume(vol.id) + assert adapter.get_volume(vol.id) is None + + +def test_luns_are_per_host(setup): + adapter = _adapter(setup) + host = adapter.ensure_host(_iscsi("sbtest-luns")) + luns = [adapter.map_volume(adapter.create_volume(f"sb-lun{i}", GIB).id, host).lun + for i in range(3)] + assert luns == [1, 2, 3] + + +def test_appliance_option_and_unknown_option(setup): + adapter = _adapter(setup, appliance_id="A2") + vol = adapter.create_volume("sb-a2", GIB) + assert setup.fake.volumes[vol.id]["appliance_id"] == "A2" + with pytest.raises(ArrayError, match="Unknown"): + _adapter(setup, pool="x") + + +def test_get_info(client): + info = client.get_info() + assert info.model == "PowerStore 1200T" + assert info.version == "PowerStoreOS 4.0.0.0" + assert info.serial == "PS4a7b5c3e9f01" + + +def test_api_token_credential_is_refused(): + setup = contract_setup() + config = make_config("dell-powerstore", "https://ps.example") + session = RestSession.for_config(config, transport=FakeTransport(setup.fake)) + with pytest.raises(ArrayError, match="username"): + DellPowerStoreAdapter(AdapterContext( + config, Credential({"api_token": SecretStr("t")}), session)) diff --git a/tests/unit/storage_arrays/test_framework.py b/tests/unit/storage_arrays/test_framework.py new file mode 100644 index 0000000000..5468600432 --- /dev/null +++ b/tests/unit/storage_arrays/test_framework.py @@ -0,0 +1,223 @@ +"""Vendor-neutral pieces: registry, naming/sizing, config validation, +RestSession error mapping and retries, HTTPS mock server end to end.""" +from __future__ import annotations + +import threading +import uuid + +import pytest +import requests +from pydantic import SecretStr, ValidationError + +from simplyblock_core.credentials import Credential +from simplyblock_core.storage_arrays.base import ( + ArrayAuthError, + ArrayConfig, + ArrayConflictError, + ArrayNotFoundError, + ArrayRequestError, + ArrayUnsupportedError, + HostSpec, + Initiator, + Protocol, + colon_wwpn, + normalize_wwpn, +) +from simplyblock_core.storage_arrays.client import ( + ArrayClient, + credential_context, + managed_name, + round_size, +) +from simplyblock_core.storage_arrays.http import RestSession +from simplyblock_core.storage_arrays.registry import ADAPTERS, ALIASES, canonical_vendor +from simplyblock_core.storage_arrays.testing import ( + FakeArray, + FakeTransport, + Reply, + route, + serve, +) +from simplyblock_core.storage_arrays.testing.pure import FakePureFlashArray + +from .conftest import StaticProvider + + +def _config(**kw): + base = dict(id="a1", vendor="pure", endpoint="https://pure01.example.com", + credential_ref={"kind": "vault-kv", "mount": "m", "path": "p"}) + base.update(kw) + return ArrayConfig(**base) + + +class TestRegistry: + + def test_all_eleven_systems_registered(self): + assert len(ADAPTERS) == 11 + + def test_aliases_resolve(self): + for alias, target in ALIASES.items(): + assert canonical_vendor(alias) == target + assert canonical_vendor(" Pure ") == "pure-flasharray" + + def test_unknown_vendor(self): + with pytest.raises(ArrayUnsupportedError, match="supported"): + canonical_vendor("acme-array") + + +class TestNamingAndSizing: + + def test_managed_name_fits_31_chars(self): + u = str(uuid.uuid4()) + assert managed_name(u, 31) == "sb-" + uuid.UUID(u).hex[:24] + assert len(managed_name(u, 20)) == 20 + + def test_managed_name_requires_uuid(self): + with pytest.raises(ValueError): + managed_name("not-a-uuid", 63) + + @pytest.mark.parametrize("size, gran, minimum, expected", [ + (1, 512, 1 << 20, 1 << 20), + ((1 << 30) + 1, 512, 1 << 20, (1 << 30) + 512), + (10 << 30, 8 << 30, 8 << 30, 16 << 30), + (8 << 30, 8 << 30, 8 << 30, 8 << 30), + ]) + def test_round_size(self, size, gran, minimum, expected): + assert round_size(size, gran, minimum) == expected + + def test_credential_context_normalizes_endpoint(self): + assert credential_context(_config(endpoint="https://PURE01.example.com/")) == \ + "array/a1/https://pure01.example.com:443" + assert credential_context(_config(endpoint="https://u.example:8443/univmax")) == \ + "array/a1/https://u.example:8443" + + +class TestConfigAndModel: + + def test_https_only(self): + with pytest.raises(ValidationError): + _config(endpoint="http://pure01.example.com") + + def test_wwpn_forms(self): + assert normalize_wwpn("21:00:00:24:FF:4C:1A:2B") == "21000024ff4c1a2b" + assert normalize_wwpn("0x21000024ff4c1a2b") == "21000024ff4c1a2b" + assert colon_wwpn("21000024FF4C1A2B") == "21:00:00:24:ff:4c:1a:2b" + with pytest.raises(ValueError): + normalize_wwpn("2100") + + def test_host_cannot_mix_scsi_and_nvme(self): + with pytest.raises(ValidationError): + HostSpec(name="h", initiators=( + Initiator(protocol=Protocol.ISCSI, address="iqn.x"), + Initiator(protocol=Protocol.NVME_TCP, address="nqn.x"))) + HostSpec(name="h", initiators=( + Initiator(protocol=Protocol.ISCSI, address="iqn.x"), + Initiator(protocol=Protocol.FC, address="2100000000000001"))) + + def test_unknown_option_is_refused(self): + provider = StaticProvider(Credential({"api_token": SecretStr("pure-token")})) + client = ArrayClient(_config(options={"bogus": 1}), provider, # type: ignore[arg-type] + transport=FakeTransport(FakePureFlashArray())) + with pytest.raises(Exception, match="Unknown .* options: bogus"): + client.get_info() + + def test_wrong_credential_shape_is_refused(self): + provider = StaticProvider(Credential({"username": SecretStr("u"), + "password": SecretStr("p")})) + client = ArrayClient(_config(), provider, # type: ignore[arg-type] + transport=FakeTransport(FakePureFlashArray())) + with pytest.raises(ArrayAuthError, match="needs credential fields api_token"): + client.get_info() + + +class _Flaky(FakeArray): + def __init__(self): + super().__init__() + self.calls = 0 + + @route("GET", "/flaky") + def flaky(self, req): + self.calls += 1 + return Reply(503 if self.calls < 3 else 200, {"ok": self.calls}) + + @route("POST", "/flaky") + def flaky_post(self, req): + self.calls += 1 + return Reply(503, {}) + + @route("GET", "/status/(?P\\d+)") + def status(self, req, code): + return Reply(int(code), {"error": "x"}) + + +class TestRestSession: + + def _session(self, fake): + return RestSession("https://x.example", transport=FakeTransport(fake), + sleep=lambda s: None) + + def test_idempotent_requests_are_retried(self): + fake = _Flaky() + assert self._session(fake).get("/flaky").json() == {"ok": 3} + + def test_non_idempotent_requests_are_not_retried(self): + fake = _Flaky() + with pytest.raises(ArrayRequestError): + self._session(fake).post("/flaky") + assert fake.calls == 1 + + @pytest.mark.parametrize("code, exc", [ + (401, ArrayAuthError), (403, ArrayAuthError), (404, ArrayNotFoundError), + (409, ArrayConflictError), (400, ArrayRequestError), (500, ArrayRequestError), + ]) + def test_status_mapping(self, code, exc): + with pytest.raises(exc): + self._session(_Flaky()).get(f"/status/{code}") + + def test_ok_statuses_are_returned(self): + resp = self._session(_Flaky()).get("/status/400", ok=(400,)) + assert resp.status_code == 400 + + def test_ca_bundle_file_is_removed_on_close(self): + import os + session = RestSession.for_config(_config(ca_bundle="-----BEGIN CERTIFICATE-----\n")) + path = session.http.verify + assert isinstance(path, str) and os.path.exists(path) + session.close() + assert not os.path.exists(path) + + def test_verify_false_only_when_configured(self): + assert RestSession.for_config(_config()).http.verify is True + assert RestSession.for_config(_config(verify_tls=False)).http.verify is False + + +class TestHttpsMockServer: + + def test_end_to_end_over_tls_with_pinned_ca(self): + fake = FakePureFlashArray(api_token="t0k") + server = serve(fake, "127.0.0.1", 0) + port = server.server_address[1] + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + with open(server.certfile) as f: + ca = f.read() + provider = StaticProvider(Credential({"api_token": SecretStr("t0k")})) + config = _config(endpoint=f"https://127.0.0.1:{port}", ca_bundle=ca) + with ArrayClient(config, provider) as client: # type: ignore[arg-type] + vol = client.create_volume(str(uuid.uuid4()), 1 << 30) + assert client.get_volume(vol.id) == vol + assert client.delete_volume(vol.id) + + # Without the pinned CA the self-signed server is refused. + with ArrayClient(_config(endpoint=f"https://127.0.0.1:{port}"), + provider) as client: # type: ignore[arg-type] + with pytest.raises(ArrayRequestError, match="SSLError"): + client.get_info() + finally: + server.shutdown() + server.server_close() + + def test_requests_session_is_plain(self): + # FakeTransport is mounted per session, never globally. + assert not isinstance(requests.Session().get_adapter("https://x"), FakeTransport) diff --git a/tests/unit/storage_arrays/test_hitachi_vsp.py b/tests/unit/storage_arrays/test_hitachi_vsp.py new file mode 100644 index 0000000000..f020fbeb60 --- /dev/null +++ b/tests/unit/storage_arrays/test_hitachi_vsp.py @@ -0,0 +1,360 @@ +"""Hitachi VSP specifics beyond the shared contract: path layouts, async +jobs, LDEV labels and paging, per-port host groups, LUN paths, locks.""" +from __future__ import annotations + +import uuid + +import pytest + +from simplyblock_core.storage_arrays.adapters import hitachi_vsp as vsp +from simplyblock_core.storage_arrays.base import ( + ArrayConflictError, + ArrayError, + ArrayRequestError, + HostSpec, + Initiator, + Protocol, +) +from simplyblock_core.storage_arrays.client import ArrayClient +from simplyblock_core.storage_arrays.testing import FakeTransport +from simplyblock_core.storage_arrays.testing.hitachi_vsp import contract_setup + +from .conftest import StaticProvider + +GIB = 1 << 30 +FC_A = Initiator(protocol=Protocol.FC, address="21:00:00:24:ff:4c:1a:2b") +FC_B = Initiator(protocol=Protocol.FC, address="21:00:00:24:ff:4c:1a:2c") +IQN_A = Initiator(protocol=Protocol.ISCSI, address="iqn.2026-01.io.sb:host-a") + + +def _client(**options): + setup = contract_setup(**options) + sleeps: list[float] = [] + client = ArrayClient(setup.config, StaticProvider(setup.credential), # type: ignore[arg-type] + transport=FakeTransport(setup.fake), + session_kwargs={"sleep": sleeps.append}) + return client, setup.fake, sleeps + + +@pytest.fixture() +def env(): + client, fake, sleeps = _client() + yield client, fake, sleeps + client.close() + + +def _uuid() -> str: + return str(uuid.uuid4()) + + +def test_embedded_paths_session_header_and_logout(env): + client, fake, _ = env + client.get_info() + assert ("POST", "/ConfigurationManager/v1/objects/sessions") in fake.requests + assert ("GET", "/ConfigurationManager/v1/objects/storages/instance") in fake.requests + assert len(fake.sessions) == 1 + client.close() + assert fake.sessions == {} + assert fake.requests[-1][0] == "DELETE" + assert fake.requests[-1][1].startswith("/ConfigurationManager/v1/objects/sessions/") + + +def test_info_fields(env): + client, fake, _ = env + info = client.get_info() + assert info.model == "VSP E990" + assert info.serial == str(fake.serial) + assert info.version.startswith("93-") + + +def test_server_mode_uses_storage_device_prefix(): + setup_fake = contract_setup().fake + client, fake, _ = _client(storage_device_id=setup_fake.storage_device_id) + try: + prefix = f"/ConfigurationManager/v1/objects/storages/{fake.storage_device_id}" + info = client.get_info() + assert info.serial == str(fake.serial) + vol = client.create_volume(_uuid(), GIB) + host = client.ensure_host(HostSpec(name="sbtest-srv", initiators=(FC_A,))) + client.map_volume(vol.id, host) + assert client.delete_volume(vol.id) + paths = [p for _, p in fake.requests] + assert all(p.startswith(prefix) for p in paths) + assert any(p.startswith(f"{prefix}/jobs/") for p in paths) + assert not any(p.startswith("/ConfigurationManager/v1/objects/ldevs") for p in paths) + finally: + client.close() + + +def test_wrong_storage_device_id_is_not_found(): + client, _, _ = _client(storage_device_id="938000999999") + try: + with pytest.raises(ArrayError): + client.get_info() + finally: + client.close() + + +def test_create_waits_for_jobs_and_labels_ldev(env): + client, fake, sleeps = env + fake.job_polls = 3 + vol = client.create_volume(_uuid(), 10 * GIB + 1) + lid = int(vol.id) + assert fake.ldevs[lid]["label"] == vol.name + assert vol.size_bytes == 10 * GIB + (1 << 20) # 1 MiB granularity + assert fake.ldevs[lid]["blocks"] * 512 == vol.size_bytes + assert vol.wwn == "naa." + fake.naa(lid).lower() + assert sleeps, "job polling must go through the session's sleep" + methods = [m for m, p in fake.requests if "/jobs/" in p] + assert len(methods) >= 2 * 4 # 2 jobs x (3 running + 1 completed) + + +def test_job_timeout_is_reported_without_real_sleep(): + client, fake, sleeps = _client(job_timeout_s=10) + try: + client.get_info() + fake.job_polls = 10**6 + with pytest.raises(ArrayRequestError, match="not completed after 10s"): + client.create_volume(_uuid(), GIB) + assert 10 <= sum(sleeps) < 20 + finally: + client.close() + + +def test_failed_job_maps_storage_error(env): + client, fake, _ = env + vol = client.create_volume(_uuid(), GIB) + host = client.ensure_host(HostSpec(name="sbtest-a", initiators=(FC_A,))) + client.map_volume(vol.id, host) + # LDEV delete with an LU path left fails inside the job (KART30000-E + SSB) + adapter = client._adapter + assert adapter is not None + with pytest.raises(ArrayConflictError, match="KART30000-E.*LU paths"): + adapter.delete_volume(vol.id) + assert int(vol.id) in fake.ldevs + + +def test_deleted_ldev_reads_not_defined(env): + client, fake, _ = env + vol = client.create_volume(_uuid(), GIB) + client.delete_volume(vol.id) + assert int(vol.id) not in fake.ldevs + assert client.get_volume(vol.id) is None + assert client.get_volume("not-a-number") is None + + +def test_label_failure_deletes_the_new_ldev(env): + client, fake, _ = env + client.get_info() + fake.fail_next(500, {"errorSource": "x", "message": "label failed", + "messageId": "KART30000-E"}, path=r"/ldevs/\d+$") + with pytest.raises(ArrayRequestError, match="label failed"): + client.create_volume(_uuid(), GIB) + assert fake.ldevs == {} + + +def test_find_pages_through_ldevs(env, monkeypatch): + client, fake, _ = env + monkeypatch.setattr(vsp, "PAGE_SIZE", 2) + for i in range(5): + fake.add_ldev(f"other-{i}", GIB) + vol_uuid = _uuid() + vol = client.create_volume(vol_uuid, GIB) + assert int(vol.id) == 5 + assert client.find_volume(vol_uuid) == vol + heads = [p for m, p in fake.requests if m == "GET" and p.endswith("/ldevs")] + assert len(heads) >= 3 + + +def test_duplicate_labels_conflict(env): + client, fake, _ = env + vol_uuid = _uuid() + name = client.volume_name(vol_uuid) + fake.add_ldev(name, GIB) + fake.add_ldev(name, GIB) + with pytest.raises(ArrayConflictError, match="Several LDEVs"): + client.find_volume(vol_uuid) + + +def test_ldev_range_option(): + client, fake, _ = _client(ldev_range="100-101") + try: + fake.add_ldev("outside", GIB, ldev_id=5) + a = client.create_volume(_uuid(), GIB) + b = client.create_volume(_uuid(), GIB) + assert {a.id, b.id} == {"100", "101"} + with pytest.raises(ArrayError, match="No free LDEV"): + client.create_volume(_uuid(), GIB) + finally: + client.close() + + +@pytest.mark.parametrize("options, match", [ + ({"ports": []}, "ports"), + ({"ports": ["eth0"]}, "ports"), + ({"ldev_range": "9-3"}, "ldev_range"), + ({"pool_id": "x"}, "pool_id"), + ({"bogus": 1}, "Unknown"), +]) +def test_bad_options(options, match): + client, _, _ = _client(**options) + with pytest.raises(ArrayError, match=match): + client.get_info() + + +def test_host_is_a_group_per_port_of_its_protocol(env): + client, fake, _ = env + host = client.ensure_host(HostSpec(name="sbtest-fc", initiators=(FC_A,))) + groups = {k: g for k, g in fake.groups.items() if g["name"] == host} + assert sorted(p for p, _ in groups) == ["CL1-A", "CL2-A"] + assert all(g["wwns"] == ["21000024ff4c1a2b"] for g in groups.values()) + assert all(g["mode"] == "LINUX/IRIX" for g in groups.values()) + + iscsi = client.ensure_host(HostSpec(name="sbtest-is", initiators=(IQN_A,))) + assert sorted(p for (p, _), g in fake.groups.items() if g["name"] == iscsi) == \ + ["CL1-B", "CL2-B"] + + client.delete_host(host) + assert not any(g["name"] == host for g in fake.groups.values()) + assert ("CL1-A", 0) in fake.groups # default group untouched + + +def test_host_mode_options(): + client, fake, _ = _client(host_mode="VMWARE_EX", host_mode_options=[54, 63]) + try: + client.ensure_host(HostSpec(name="sbtest-vm", initiators=(FC_A,))) + g = next(g for g in fake.groups.values() if g["name"] == "sbtest-vm") + assert g["mode"] == "VMWARE_EX" and g["modeOptions"] == [54, 63] + finally: + client.close() + + +def test_no_port_for_protocol(): + client, _, _ = _client(ports=["CL1-B"]) + try: + with pytest.raises(ArrayError, match="no configured fc port"): + client.ensure_host(HostSpec(name="sbtest-fc", initiators=(FC_A,))) + finally: + client.close() + + +def test_iscsi_ownership_is_enforced_by_scan(env): + """The array lets one IQN into several targets of a port; the adapter must not.""" + client, fake, _ = env + client.ensure_host(HostSpec(name="sbtest-a", initiators=(IQN_A,))) + with pytest.raises(ArrayConflictError, match="sbtest-a"): + client.ensure_host(HostSpec(name="sbtest-b", initiators=(IQN_A,))) + assert not any(g["name"] == "sbtest-b" for g in fake.groups.values()) + + +def test_fc_wwn_in_unmanaged_group_conflicts(env): + client, fake, _ = env + client.get_info() + fake.groups[("CL2-A", 0)]["wwns"].append("21000024ff4c1a2c") + with pytest.raises(ArrayConflictError, match="CL2-A"): + client.ensure_host(HostSpec(name="sbtest-b", initiators=(FC_B,))) + + +def test_same_lun_on_every_port(env): + client, fake, _ = env + other = client.create_volume(_uuid(), GIB) + vol = client.create_volume(_uuid(), GIB) + host = client.ensure_host(HostSpec(name="sbtest-a", initiators=(FC_A,))) + # occupy LUN 0 on the second port only + num = next(n for (p, n), g in fake.groups.items() if p == "CL2-A" and g["name"] == host) + fake.groups[("CL2-A", num)]["luns"][0] = int(other.id) + m = client.map_volume(vol.id, host) + assert m.lun == 1 + luns = {p: lun for (p, n), g in fake.groups.items() if g["name"] == host + for lun, lid in g["luns"].items() if lid == int(vol.id)} + assert luns == {"CL1-A": 1, "CL2-A": 1} + assert client.list_mappings(vol.id) == [m] + + +def test_map_repairs_missing_port_path(env): + client, fake, _ = env + vol = client.create_volume(_uuid(), GIB) + host = client.ensure_host(HostSpec(name="sbtest-a", initiators=(FC_A,))) + m = client.map_volume(vol.id, host) + num = next(n for (p, n), g in fake.groups.items() if p == "CL2-A" and g["name"] == host) + fake.groups[("CL2-A", num)]["luns"].clear() + assert client.map_volume(vol.id, host) == m + assert fake.groups[("CL2-A", num)]["luns"] == {m.lun: int(vol.id)} + + +def test_unmap_removes_every_port_path(env): + client, fake, _ = env + vol = client.create_volume(_uuid(), GIB) + host = client.ensure_host(HostSpec(name="sbtest-a", initiators=(FC_A,))) + client.map_volume(vol.id, host) + client.unmap_volume(vol.id, host) + assert not any(g["luns"] for g in fake.groups.values()) + client.unmap_volume(vol.id, host) + + +def test_map_to_unknown_host_is_not_found(env): + client, _, _ = env + vol = client.create_volume(_uuid(), GIB) + with pytest.raises(ArrayError, match="no host group"): + client.map_volume(vol.id, "sbtest-missing") + + +def test_lock_required_without_use_lock_fails(): + client, fake, _ = _client() + try: + fake.require_lock = True + with pytest.raises(ArrayError, match="not locked"): + client.create_volume(_uuid(), GIB) + finally: + client.close() + + +def test_use_lock_wraps_changes(): + client, fake, _ = _client(use_lock=True) + try: + fake.require_lock = True + vol = client.create_volume(_uuid(), GIB) + host = client.ensure_host(HostSpec(name="sbtest-a", initiators=(FC_A,))) + client.map_volume(vol.id, host) + client.resize_volume(vol.id, 2 * GIB) + assert client.delete_volume(vol.id) + client.delete_host(host) + assert fake.lock_owner is None + locks = [p for _, p in fake.requests if p.endswith("/lock/invoke")] + unlocks = [p for _, p in fake.requests if p.endswith("/unlock/invoke")] + assert len(locks) == len(unlocks) >= 6 + finally: + client.close() + + +def test_lock_released_when_change_fails(): + client, fake, _ = _client(use_lock=True) + try: + client.get_info() + fake.require_lock = True + fake.pools.clear() + with pytest.raises(ArrayError): + client.create_volume(_uuid(), GIB) + assert fake.lock_owner is None + finally: + client.close() + + +def test_resize_expands_by_difference(env): + client, fake, _ = env + vol = client.create_volume(_uuid(), 2 * GIB) + grown = client.resize_volume(vol.id, 3 * GIB) + assert grown.size_bytes == 3 * GIB + assert fake.ldevs[int(vol.id)]["blocks"] == 3 * GIB // 512 + + +def test_classify_error_bodies(): + nf = vsp._classify("GET x", 400, {"message": "The LDEV is not defined.", + "messageId": "KART30000-E"}) + assert type(nf).__name__ == "ArrayNotFoundError" + cf = vsp._classify("POST x", None, {"message": "already registered", + "messageId": "KART30000-E", + "errorCode": {"SSB1": "B957", "SSB2": "4184"}}) + assert isinstance(cf, ArrayConflictError) and "SSB1=B957" in str(cf) + other = vsp._classify("POST x", 503, {"message": "busy"}) + assert isinstance(other, ArrayRequestError) and other.status == 503 diff --git a/tests/unit/storage_arrays/test_hpe_nimble.py b/tests/unit/storage_arrays/test_hpe_nimble.py new file mode 100644 index 0000000000..aadf36ba31 --- /dev/null +++ b/tests/unit/storage_arrays/test_hpe_nimble.py @@ -0,0 +1,188 @@ +"""HPE Alletra 5000/6000 / Nimble adapter specifics beyond the shared contract.""" +from __future__ import annotations + +import dataclasses +import uuid + +import pytest + +from simplyblock_core.storage_arrays.base import ( + ArrayConflictError, + ArrayError, + HostSpec, + Initiator, + Protocol, +) +from simplyblock_core.storage_arrays.client import ArrayClient +from simplyblock_core.storage_arrays.testing import FakeTransport, make_config +from simplyblock_core.storage_arrays.testing.hpe_nimble import contract_setup + +from .conftest import StaticProvider + +GIB = 1 << 30 +MIB = 1 << 20 + + +def _client(**options): + setup = contract_setup() + if options: + setup = dataclasses.replace( + setup, config=make_config("hpe-nimble", "https://nimble.fake.example:5392", + **options)) + client = ArrayClient(setup.config, StaticProvider(setup.credential), # type: ignore[arg-type] + transport=FakeTransport(setup.fake), + session_kwargs={"sleep": lambda s: None}) + return client, setup.fake + + +def _iscsi(name, *iqns): + return HostSpec(name=name, initiators=tuple( + Initiator(protocol=Protocol.ISCSI, address=i) for i in iqns)) + + +def _fc(name, *wwpns): + return HostSpec(name=name, initiators=tuple( + Initiator(protocol=Protocol.FC, address=w) for w in wwpns)) + + +def test_token_released_by_id_on_close(): + client, fake = _client() + client.get_info() + assert len(fake.tokens) == 1 + (tid,) = fake.tokens + client.close() + assert fake.tokens == {} + assert ("DELETE", f"/v1/tokens/{tid}") in fake.requests + + +def test_port_5392_is_kept(): + setup = contract_setup() + sent: list[str] = [] + + class Recording(FakeTransport): + def send(self, request, **kw): + sent.append(request.url) + return super().send(request, **kw) + + client = ArrayClient(setup.config, StaticProvider(setup.credential), # type: ignore[arg-type] + transport=Recording(setup.fake)) + client.get_info() + assert sent and all(u.startswith("https://nimble.fake.example:5392/v1/") for u in sent) + + +def test_get_info(): + client, _ = _client() + info = client.get_info() + assert info.model == "AF40" and info.serial == "AF-123456" + assert info.version.startswith("6.") + + +def test_sizes_in_mib_and_eui_identity(): + client, fake = _client() + vol = client.create_volume(str(uuid.uuid4()), GIB + 1) + assert vol.size_bytes == GIB + MIB + raw = fake.volumes[vol.id] + assert raw["size"] == 1025 + assert vol.nguid is None and vol.wwn == "eui." + raw["serial_number"] + assert vol.identifier == vol.wwn + + +def test_pool_and_performance_policy_resolved_by_name(): + client, fake = _client(pool="fast", performance_policy="Oracle OLTP") + vol = client.create_volume(str(uuid.uuid4()), GIB) + raw = fake.volumes[vol.id] + assert raw["pool_name"] == "fast" and raw["perfpolicy_name"] == "Oracle OLTP" + + +def test_unknown_pool_is_an_error(): + client, fake = _client(pool="nope") + with pytest.raises(ArrayError, match="pool 'nope' not found"): + client.create_volume(str(uuid.uuid4()), GIB) + assert fake.volumes == {} + + +def test_delete_offlines_first(): + client, fake = _client() + vol = client.create_volume(str(uuid.uuid4()), GIB) + adapter = client._adapter + assert adapter is not None + # a direct DELETE of an online volume is refused by the array + with pytest.raises(ArrayConflictError, match="SM_vol_online"): + adapter._request("DELETE", f"/v1/volumes/{vol.id}") + assert client.delete_volume(vol.id) is True + calls = [(m, p) for m, p in fake.requests if p == f"/v1/volumes/{vol.id}"] + assert ("PUT", f"/v1/volumes/{vol.id}") in calls + assert calls.index(("PUT", f"/v1/volumes/{vol.id}")) < len(calls) - 1 + + +def test_fc_group_uses_colon_wwpns(): + client, fake = _client() + hid = client.ensure_host(_fc("sbfc", "2100000E1E2F3A4B")) + assert fake.groups[hid]["access_protocol"] == "fc" + assert [i["wwpn"] for i in fake.initiators.values()] == ["21:00:00:0e:1e:2f:3a:4b"] + assert client.ensure_host(_fc("sbfc", "21:00:00:0e:1e:2f:3a:4b")) == hid + assert len(fake.initiators) == 1 + + +def test_mixed_protocol_host_refused(): + client, _ = _client() + spec = HostSpec(name="sbmix", initiators=( + Initiator(protocol=Protocol.ISCSI, address="iqn.2026-01.io.sb:m"), + Initiator(protocol=Protocol.FC, address="2100000e1e2f3a4c"))) + with pytest.raises(ArrayError, match="either iSCSI or FC"): + client.ensure_host(spec) + + +def test_existing_group_of_other_protocol_conflicts(): + client, _ = _client() + client.ensure_host(_iscsi("sbsame", "iqn.2026-01.io.sb:s")) + with pytest.raises(ArrayConflictError, match="access_protocol iscsi"): + client.ensure_host(_fc("sbsame", "2100000e1e2f3a4d")) + + +def test_initiator_owned_elsewhere_conflicts_before_creating_group(): + client, fake = _client() + client.ensure_host(_iscsi("sbown", "iqn.2026-01.io.sb:o")) + with pytest.raises(ArrayConflictError, match="sbown"): + client.ensure_host(_iscsi("sbthief", "iqn.2026-01.io.sb:o")) + assert {g["name"] for g in fake.groups.values()} == {"sbown"} + + +def test_iscsi_luns_are_zero_with_volume_scoped_targets(): + client, fake = _client() + hid = client.ensure_host(_iscsi("sbvst", "iqn.2026-01.io.sb:v")) + luns = [client.map_volume(client.create_volume(str(uuid.uuid4()), GIB).id, hid).lun + for _ in range(2)] + assert luns == [0, 0] + + +def test_fc_luns_are_distinct_per_group(): + client, fake = _client() + hid = client.ensure_host(_fc("sbfc2", "2100000e1e2f3a4e")) + luns = [client.map_volume(client.create_volume(str(uuid.uuid4()), GIB).id, hid).lun + for _ in range(3)] + assert luns == [0, 1, 2] + + +def test_acr_is_applied_to_both_and_map_is_idempotent(): + client, fake = _client() + vol = client.create_volume(str(uuid.uuid4()), GIB) + hid = client.ensure_host(_iscsi("sbacr", "iqn.2026-01.io.sb:a")) + m = client.map_volume(vol.id, hid) + assert client.map_volume(vol.id, hid) == m + (acr,) = fake.acrs.values() + assert acr["apply_to"] == "both" and acr["vol_id"] == vol.id + + +def test_malformed_volume_id_is_none(): + client, _ = _client() + assert client.get_volume("not-a-nimble-id") is None + + +def test_host_in_use_cannot_be_deleted(): + client, _ = _client() + vol = client.create_volume(str(uuid.uuid4()), GIB) + hid = client.ensure_host(_iscsi("sbbusy", "iqn.2026-01.io.sb:b")) + client.map_volume(vol.id, hid) + with pytest.raises(ArrayConflictError, match="SM_igrp_has_acl"): + client.delete_host(hid) diff --git a/tests/unit/storage_arrays/test_hpe_wsapi.py b/tests/unit/storage_arrays/test_hpe_wsapi.py new file mode 100644 index 0000000000..d3fef3424e --- /dev/null +++ b/tests/unit/storage_arrays/test_hpe_wsapi.py @@ -0,0 +1,188 @@ +"""HPE WSAPI adapter specifics beyond the shared contract.""" +from __future__ import annotations + +import dataclasses +import uuid + +import pytest + +from simplyblock_core.storage_arrays.base import ( + ArrayConflictError, + ArrayError, + ArrayNotFoundError, + HostSpec, + Initiator, + Protocol, +) +from simplyblock_core.storage_arrays.client import ArrayClient +from simplyblock_core.storage_arrays.testing import FakeTransport, make_config +from simplyblock_core.storage_arrays.testing.hpe_wsapi import contract_setup + +from .conftest import StaticProvider + +GIB = 1 << 30 +MIB = 1 << 20 + + +def _client(**options): + setup = contract_setup() + if options: + setup = dataclasses.replace( + setup, config=make_config("hpe-wsapi", "https://wsapi.fake.example", + **{"cpg": "SSD_r6", **options})) + client = ArrayClient(setup.config, StaticProvider(setup.credential), # type: ignore[arg-type] + transport=FakeTransport(setup.fake), + session_kwargs={"sleep": lambda s: None}) + return client, setup.fake + + +def _iscsi(name, *iqns): + return HostSpec(name=name, initiators=tuple( + Initiator(protocol=Protocol.ISCSI, address=i) for i in iqns)) + + +def test_session_key_header_and_logout(): + client, fake = _client() + client.get_info() + assert len(fake.sessions) == 1 + client.close() + assert fake.sessions == set() + assert any(p.startswith("/api/v1/credentials/") for m, p in fake.requests if m == "DELETE") + + +def test_get_info_reads_system(): + client, _ = _client() + info = client.get_info() + assert info.model.startswith("HPE Alletra") and info.serial == "CZ12345678" + + +def test_cpg_option_required(): + from simplyblock_core.storage_arrays.adapters.hpe_wsapi import HpeWsapiAdapter + from simplyblock_core.storage_arrays.base import AdapterContext + from simplyblock_core.storage_arrays.http import RestSession + config = make_config("hpe-wsapi", "https://wsapi.fake.example") + ctx = AdapterContext(config, contract_setup().credential, RestSession(config.endpoint)) + with pytest.raises(ArrayError, match="cpg"): + HpeWsapiAdapter(ctx) + + +def test_invalid_provisioning_rejected(): + with pytest.raises(ArrayError, match="provisioning"): + _client(provisioning="full")[0].get_info() + + +def test_create_body_tpvv_and_reduce(): + client, fake = _client() + client.create_volume(str(uuid.uuid4()), GIB) + body = fake.created_bodies[-1] + assert body["tpvv"] is True and "reduce" not in body + assert body["cpg"] == "SSD_r6" and body["sizeMiB"] == 1024 + + client, fake = _client(provisioning="reduce") + client.create_volume(str(uuid.uuid4()), GIB) + assert fake.created_bodies[-1]["reduce"] is True and "tpvv" not in fake.created_bodies[-1] + + +def test_names_fit_31_chars_and_wwn_is_naa(): + client, fake = _client() + vol = client.create_volume(str(uuid.uuid4()), GIB) + assert len(vol.name) <= 31 and vol.id == vol.name + assert vol.wwn == "naa." + fake.volumes[vol.name]["wwn"].lower() + assert vol.wwn.startswith("naa.60002ac") + + +def test_size_rounds_to_256_mib(): + client, fake = _client() + vol = client.create_volume(str(uuid.uuid4()), GIB + 1) + assert vol.size_bytes == GIB + 256 * MIB + assert fake.volumes[vol.name]["sizeMiB"] == 1280 + + +def test_grow_sends_increment(): + client, fake = _client() + vol = client.create_volume(str(uuid.uuid4()), 2 * GIB) + seen = [] + orig = fake.put_volume + + def spy(req, name): + seen.append(req.json()) + return orig(req, name) + + fake._routes = [(m, p, spy if h == orig else h) for m, p, h in fake._routes] + grown = client.resize_volume(vol.id, 5 * GIB) + assert seen == [{"action": 3, "sizeMiB": 3 * 1024}] + assert grown.size_bytes == 5 * GIB + + +def test_delete_with_vlun_is_conflict_at_adapter_level(): + client, fake = _client() + vol = client.create_volume(str(uuid.uuid4()), GIB) + host = client.ensure_host(_iscsi("sbh1", "iqn.2026-01.io.sb:x")) + client.map_volume(vol.id, host) + adapter = client._adapter + assert adapter is not None + with pytest.raises(ArrayConflictError, match="code 34"): + adapter.delete_volume(vol.id) + # the client unmaps first + assert client.delete_volume(vol.id) is True + + +def test_vlun_location_and_dedup_of_active_paths(): + client, fake = _client() + vol = client.create_volume(str(uuid.uuid4()), GIB) + h = client.ensure_host(_iscsi("sbh2", "iqn.2026-01.io.sb:y")) + fake.vluns.append({"volumeName": "other", "hostname": h, "lun": 0}) # LUN 0 taken + fake.add_volume("other", GIB) + m = client.map_volume(vol.id, h) + assert m.lun == 1 + members = [x for x in fake._vlun_members(vol.id)] + assert len(members) == 1 + fake.paths_per_host + assert client.list_mappings(vol.id) == [m] + + +def test_missing_host_on_map_is_not_found(): + client, _ = _client() + vol = client.create_volume(str(uuid.uuid4()), GIB) + with pytest.raises(ArrayNotFoundError, match="code 17"): + client.map_volume(vol.id, "nohost") + + +def test_mixed_iscsi_fc_host_uses_two_requests(): + client, fake = _client() + spec = HostSpec(name="sbmixed", initiators=( + Initiator(protocol=Protocol.ISCSI, address="iqn.2026-01.io.sb:m"), + Initiator(protocol=Protocol.FC, address="10:00:00:00:c9:aa:bb:cc"))) + assert client.ensure_host(spec) == "sbmixed" + host = fake.hosts["sbmixed"] + assert [p["name"] for p in host["iSCSIPaths"]] == ["iqn.2026-01.io.sb:m"] + assert [p["wwn"] for p in host["FCPaths"]] == ["10000000C9AABBCC"] + assert client.ensure_host(spec) == "sbmixed" + + +def test_persona_option_used(): + client, fake = _client(persona=11) + client.ensure_host(_iscsi("sbvm", "iqn.2026-01.io.sb:v")) + assert fake.hosts["sbvm"]["persona"] == 11 + + +def test_path_owned_by_other_host_is_conflict(): + client, _ = _client() + client.ensure_host(_iscsi("sba", "iqn.2026-01.io.sb:dup")) + with pytest.raises(ArrayConflictError, match="code 73"): + client.ensure_host(_iscsi("sbb", "iqn.2026-01.io.sb:dup")) + + +def test_nvme_refused(): + client, fake = _client() + spec = HostSpec(name="sbn", initiators=( + Initiator(protocol=Protocol.NVME_TCP, address="nqn.2014-08.org.nvmexpress:uuid:x"),)) + with pytest.raises(ArrayError, match="does not support"): + client.ensure_host(spec) + assert not fake.requests + + +def test_host_name_limit_enforced_by_client(): + client, fake = _client() + with pytest.raises(ArrayError, match="exceeds 31"): + client.ensure_host(_iscsi("h" * 32, "iqn.2026-01.io.sb:long")) + assert not fake.requests diff --git a/tests/unit/storage_arrays/test_huawei_dorado.py b/tests/unit/storage_arrays/test_huawei_dorado.py new file mode 100644 index 0000000000..64945ff14b --- /dev/null +++ b/tests/unit/storage_arrays/test_huawei_dorado.py @@ -0,0 +1,172 @@ +"""Huawei OceanStor Dorado specifics beyond the shared contract suite.""" +from __future__ import annotations + +import uuid + +import pytest + +from simplyblock_core.storage_arrays.base import ( + ArrayAuthError, + ArrayConflictError, + ArrayError, + ArrayRequestError, + HostSpec, + Initiator, + Protocol, +) +from simplyblock_core.storage_arrays.client import ArrayClient +from simplyblock_core.storage_arrays.testing import FakeTransport +from simplyblock_core.storage_arrays.testing.huawei_dorado import contract_setup + +GIB = 1 << 30 +IQN_A = Initiator(protocol=Protocol.ISCSI, address="iqn.2026-01.io.sb:a") +IQN_B = Initiator(protocol=Protocol.ISCSI, address="iqn.2026-01.io.sb:b") + + +class _Provider: + def __init__(self, credential): + self.credential = credential + self.invalidated = 0 + + def resolve(self, ref, context): + return self.credential + + def invalidate(self, ref=None): + self.invalidated += 1 + + +def _client(**options): + setup = contract_setup() + if options: + setup.config = setup.config.model_copy( + update={"options": {**setup.config.options, **options}}) + client = ArrayClient(setup.config, _Provider(setup.credential), # type: ignore[arg-type] + transport=FakeTransport(setup.fake), + session_kwargs={"sleep": lambda s: None}) + return client, setup.fake + + +def _envelope(code, description="x"): + return {"data": {}, "error": {"code": code, "description": description}} + + +def test_login_and_device_scoped_paths(): + client, fake = _client() + info = client.get_info() + assert info.serial == fake.device_id and info.version == "6.1.5" + assert info.model == "OceanStor Dorado 5000 V6" + paths = [p for _, p in fake.requests] + assert paths[0] == "/deviceManager/rest/xx/sessions" + assert paths[1] == f"/deviceManager/rest/{fake.device_id}/system/" + client.close() + assert fake.requests[-1] == ("DELETE", f"/deviceManager/rest/{fake.device_id}/sessions") + assert not fake.tokens + + +def test_capacity_is_in_sectors_and_rounded_to_mib(): + client, fake = _client() + vol = client.create_volume(str(uuid.uuid4()), 10 * GIB + 1) + assert vol.size_bytes == 10 * GIB + (1 << 20) + assert fake.luns[vol.id]["CAPACITY"] == str((10 * GIB + (1 << 20)) // 512) + assert fake.luns[vol.id]["ALLOCTYPE"] == "1" + assert vol.wwn == "naa." + fake.luns[vol.id]["WWN"].lower() + assert len(vol.name) <= 31 + + +def test_unknown_pool(): + client, _ = _client(storage_pool="nope") + with pytest.raises(ArrayError, match="storage pool 'nope' not found"): + client.create_volume(str(uuid.uuid4()), GIB) + + +def test_http_200_error_envelopes_are_mapped(): + client, fake = _client() + client.get_info() + fake.fail_next(200, _envelope(1077948993, "The name already exists."), path="/lun$") + with pytest.raises(ArrayConflictError, match="1077948993"): + client.find_volume(str(uuid.uuid4())) + fake.fail_next(200, _envelope(1077949006, "The system is busy."), path="/lun$") + with pytest.raises(ArrayRequestError, match="1077949006"): + client.find_volume(str(uuid.uuid4())) + fake.fail_next(200, _envelope(1077936859, "The LUN does not exist."), path="/lun/") + assert client.get_volume("4242") is None + + +def test_minus_401_envelope_relogs_in_once(): + client, fake = _client() + client.get_info() + fake.expire_sessions() + client.get_info() + logins = [p for _, p in fake.requests if p.endswith("/xx/sessions")] + assert len(logins) == 2 + + +def test_wrong_password_is_auth_error(): + client, fake = _client() + fake.set_credential(username="admin", password="other") + with pytest.raises(ArrayAuthError, match="1077987870"): + client.get_info() + + +def test_mapping_triple_and_teardown(): + client, fake = _client() + v1 = client.create_volume(str(uuid.uuid4()), GIB) + v2 = client.create_volume(str(uuid.uuid4()), GIB) + host = client.ensure_host(HostSpec(name="sbtest-a", initiators=(IQN_A,))) + m1 = client.map_volume(v1.id, host) + m2 = client.map_volume(v2.id, host) + assert (m1.lun, m2.lun) == (1, 2) # HostLUNID parsed from ASSOCIATEMETADATA + assert {g["NAME"] for g in fake.lungroups.values()} == {f"sb_lg_{host}"} + assert {g["NAME"] for g in fake.hostgroups.values()} == {f"sb_hg_{host}"} + assert {v["NAME"] for v in fake.views.values()} == {f"sb_mv_{host}"} + assert client.map_volume(v1.id, host) == m1 + + with pytest.raises(ArrayConflictError, match="still has LUNs"): + client.delete_host(host) + client.delete_volume(v1.id) + client.delete_volume(v2.id) + client.delete_host(host) + assert not (fake.hosts or fake.lungroups or fake.hostgroups or fake.views) + assert fake.initiators["iscsi_initiator"]["iqn.2026-01.io.sb:a"]["ISFREE"] == "true" + # the freed initiator can be claimed by a new host + client.ensure_host(HostSpec(name="sbtest-b", initiators=(IQN_A,))) + + +def test_initiator_bound_to_foreign_host_creates_nothing(): + client, fake = _client() + owner = client.ensure_host(HostSpec(name="customer-host", initiators=(IQN_A,))) + with pytest.raises(ArrayConflictError, match="customer-host"): + client.ensure_host(HostSpec(name="sbtest-x", initiators=(IQN_B, IQN_A))) + assert [h["NAME"] for h in fake.hosts.values()] == ["customer-host"] + assert fake.initiators["iscsi_initiator"]["iqn.2026-01.io.sb:a"]["PARENTID"] == owner + + +def test_fc_initiator_ids_are_plain_lowercase_hex(): + client, fake = _client() + host = client.ensure_host(HostSpec(name="sbtest-fc", initiators=( + Initiator(protocol=Protocol.FC, address="21:00:00:24:FF:4C:1A:2B"),))) + ini = fake.initiators["fc_initiator"]["21000024ff4c1a2b"] + assert ini["PARENTID"] == host and ini["ISFREE"] == "false" + + +def test_host_in_foreign_hostgroup_conflicts_on_map(): + client, fake = _client() + vol = client.create_volume(str(uuid.uuid4()), GIB) + host = client.ensure_host(HostSpec(name="sbtest-a", initiators=(IQN_A,))) + gid = str(fake.next_id()) + fake.hostgroups[gid] = {"ID": gid, "NAME": "customer_hg", "TYPE": "14", + "DESCRIPTION": "", "hosts": {host}} + with pytest.raises(ArrayConflictError, match="customer_hg"): + client.map_volume(vol.id, host) + + +def test_lun_in_customer_lungroup_is_not_listed_and_blocks_delete(): + client, fake = _client() + vol = client.create_volume(str(uuid.uuid4()), GIB) + gid = str(fake.next_id()) + fake.lungroups[gid] = {"ID": gid, "NAME": "customer_lg", "TYPE": "256", + "DESCRIPTION": "", "luns": {vol.id}} + assert client.list_mappings(vol.id) == [] + with pytest.raises(ArrayRequestError): + client.delete_volume(vol.id) + assert client.get_volume(vol.id) is not None diff --git a/tests/unit/storage_arrays/test_ibm_flashsystem.py b/tests/unit/storage_arrays/test_ibm_flashsystem.py new file mode 100644 index 0000000000..be9e3d5d52 --- /dev/null +++ b/tests/unit/storage_arrays/test_ibm_flashsystem.py @@ -0,0 +1,187 @@ +"""IBM Storage Virtualize specifics beyond the shared contract suite.""" +from __future__ import annotations + +import uuid + +import pytest + +from simplyblock_core.storage_arrays.base import ( + ArrayConflictError, + ArrayNotFoundError, + ArrayRequestError, + ArrayUnsupportedError, + HostSpec, + Initiator, + Protocol, +) +from simplyblock_core.storage_arrays.client import ArrayClient +from simplyblock_core.storage_arrays.testing import FakeTransport +from simplyblock_core.storage_arrays.testing.ibm_flashsystem import contract_setup + +GIB = 1 << 30 + + +class _Provider: + def __init__(self, credential): + self.credential = credential + self.invalidated = 0 + + def resolve(self, ref, context): + return self.credential + + def invalidate(self, ref=None): + self.invalidated += 1 + + +def _client(**options): + setup = contract_setup() + if options: + setup.config = setup.config.model_copy( + update={"options": {**setup.config.options, **options}}) + client = ArrayClient(setup.config, _Provider(setup.credential), # type: ignore[arg-type] + transport=FakeTransport(setup.fake), + session_kwargs={"sleep": lambda s: None}) + return client, setup.fake + + +def _cmds(fake, name): + return [opts for cmd, _, opts in fake.commands if cmd == name] + + +def test_get_info(): + client, _ = _client() + info = client.get_info() + assert info.model == "IBM FlashSystem 7300" + assert info.version == "8.6.0.4" + assert info.serial == "000002042140A0B2" + + +def test_mkvolume_parameters_thin_default(): + client, fake = _client() + vol = client.create_volume(str(uuid.uuid4()), 10 * GIB + 1) + (opts,) = _cmds(fake, "mkvolume") + assert opts == {"name": vol.name, "pool": "Pool0", "size": 10 * GIB + 512, + "unit": "b", "thin": True} + assert vol.size_bytes == 10 * GIB + 512 + assert vol.wwn == "naa." + fake.vdisks[vol.id]["vdisk_UID"].lower() + # capacity must be read in bytes, never in the human-readable form + assert all(o.get("bytes") is True for o in _cmds(fake, "lsvdisk")) + + +def test_thick_volume_and_io_group(): + client, fake = _client(thin=False, io_group="io_grp1") + vol = client.create_volume(str(uuid.uuid4()), GIB) + (opts,) = _cmds(fake, "mkvolume") + assert "thin" not in opts and opts["iogrp"] == "io_grp1" + assert fake.vdisks[vol.id]["IO_group_name"] == "io_grp1" + + +def test_rest_v1_root(): + client, fake = _client(rest_root="/rest/v1") + client.create_volume(str(uuid.uuid4()), GIB) + assert all(path.startswith("/rest/v1/") for _, path in fake.requests) + + +def test_resize_sends_delta(): + client, fake = _client() + vol = client.create_volume(str(uuid.uuid4()), 8 * GIB) + client.resize_volume(vol.id, 20 * GIB) + assert _cmds(fake, "expandvdisksize") == [{"size": 12 * GIB, "unit": "b"}] + + +def test_unknown_pool_is_not_found(): + client, _ = _client(pool="NoSuchPool") + with pytest.raises(ArrayNotFoundError, match="CMMVC5754E"): + client.create_volume(str(uuid.uuid4()), GIB) + + +def test_cmmvc_codes_are_mapped(): + client, fake = _client() + fake.fail_next(500, b"CMMVC6035E The action failed as the object already exists.", + path="mkvolume") + with pytest.raises(ArrayConflictError, match="CMMVC6035E"): + client.create_volume(str(uuid.uuid4()), GIB) + fake.fail_next(500, b"CMMVC5786E The action failed because the cluster is not in a " + b"stable state.", path="mkvolume") + with pytest.raises(ArrayRequestError) as e: + client.create_volume(str(uuid.uuid4()), GIB) + assert e.value.status == 500 and "CMMVC5786E" in str(e.value) + + +def test_expired_token_is_403_and_relogs_in(): + client, fake = _client() + client.get_info() + fake.expire_sessions() + client.get_info() + assert [p for _, p in fake.requests].count("/rest/auth") == 2 + + +def test_volume_id_reuse_is_caught_by_identifier(): + client, _ = _client() + old = client.create_volume(str(uuid.uuid4()), GIB) + assert client.delete_volume(old.id) + new = client.create_volume(str(uuid.uuid4()), GIB) + assert new.id == old.id # the array hands out the lowest free id again + with pytest.raises(ArrayConflictError, match="does not match"): + client.delete_volume(old.id, expected_identifier=old.identifier) + assert client.get_volume(new.id) == new + + +def test_multi_host_mapping_uses_force_and_single_row_quirk(): + client, fake = _client() + vol = client.create_volume(str(uuid.uuid4()), GIB) + a = client.ensure_host(HostSpec(name="sbtest-a", initiators=( + Initiator(protocol=Protocol.ISCSI, address="iqn.2026-01.io.sb:a"),))) + b = client.ensure_host(HostSpec(name="sbtest-b", initiators=( + Initiator(protocol=Protocol.ISCSI, address="iqn.2026-01.io.sb:b"),))) + m = client.map_volume(vol.id, a) + assert m.lun == 0 + # one mapping: lsvdiskhostmap answers with a bare dict + assert client.list_mappings(vol.id) == [m] + client.map_volume(vol.id, b) + assert all(o.get("force") is True for o in _cmds(fake, "mkvdiskhostmap")) + assert {x.host_id for x in client.list_mappings(vol.id)} == {a, b} + + +def test_fc_host_wwpns_are_colon_separated_and_forced(): + client, fake = _client() + client.ensure_host(HostSpec(name="sbtest-fc", initiators=( + Initiator(protocol=Protocol.FC, address="21:00:00:24:ff:4c:1a:2b"), + Initiator(protocol=Protocol.FC, address="21:00:00:24:ff:4c:1a:2c")))) + (opts,) = _cmds(fake, "mkhost") + assert opts == {"name": "sbtest-fc", "fcwwpn": "21000024FF4C1A2B:21000024FF4C1A2C", + "force": True} + # re-run with the same ports: nothing is re-added + client.ensure_host(HostSpec(name="sbtest-fc", initiators=( + Initiator(protocol=Protocol.FC, address="21000024ff4c1a2b"),))) + assert _cmds(fake, "addhostport") == [] + + +def test_fc_port_of_other_host_conflicts(): + client, fake = _client() + wwpn = Initiator(protocol=Protocol.FC, address="21:00:00:24:ff:4c:1a:2b") + client.ensure_host(HostSpec(name="sbtest-one", initiators=(wwpn,))) + with pytest.raises(ArrayConflictError, match="registered to another host"): + client.ensure_host(HostSpec(name="sbtest-two", initiators=(wwpn,))) + assert "sbtest-two" not in fake.hosts + + +def test_nvme_host_protocol(): + client, fake = _client() + client.ensure_host(HostSpec(name="sbtest-nvme", initiators=( + Initiator(protocol=Protocol.NVME_TCP, address="nqn.2014-08.org.nvmexpress:uuid:x"),))) + assert fake.hosts["sbtest-nvme"]["protocol"] == "tcpnvme" + with pytest.raises(ArrayUnsupportedError, match="one transport"): + client.ensure_host(HostSpec(name="sbtest-mixed", initiators=( + Initiator(protocol=Protocol.NVME_TCP, address="nqn.2014-08.org.nvmexpress:uuid:y"), + Initiator(protocol=Protocol.NVME_RDMA, address="nqn.2014-08.org.nvmexpress:uuid:z")))) + + +def test_delete_host_with_mappings_conflicts(): + client, _ = _client() + vol = client.create_volume(str(uuid.uuid4()), GIB) + host = client.ensure_host(HostSpec(name="sbtest-busy", initiators=( + Initiator(protocol=Protocol.ISCSI, address="iqn.2026-01.io.sb:busy"),))) + client.map_volume(vol.id, host) + with pytest.raises(ArrayConflictError, match="CMMVC5871E"): + client.delete_host(host) diff --git a/tests/unit/storage_arrays/test_infinidat.py b/tests/unit/storage_arrays/test_infinidat.py new file mode 100644 index 0000000000..6b0b3ba41f --- /dev/null +++ b/tests/unit/storage_arrays/test_infinidat.py @@ -0,0 +1,147 @@ +"""Infinidat InfiniBox specifics beyond the shared contract.""" +from __future__ import annotations + +import uuid + +import pytest + +from simplyblock_core.storage_arrays.adapters.infinidat import infinibox_wwn +from simplyblock_core.storage_arrays.base import ( + ArrayConflictError, + ArrayError, + ArrayNotFoundError, + ArrayRequestError, + HostSpec, + Initiator, + Protocol, +) +from simplyblock_core.storage_arrays.client import ArrayClient +from simplyblock_core.storage_arrays.testing import FakeTransport, make_config +from simplyblock_core.storage_arrays.testing.infinidat import contract_setup + +from .conftest import StaticProvider + +GIB = 1 << 30 + + +@pytest.fixture() +def setup(): + return contract_setup() + + +def _client(setup, **options): + config = setup.config + if options: + config = make_config("infinidat-infinibox", config.endpoint, + **{**config.options, **options}) + return ArrayClient(config, StaticProvider(setup.credential), # type: ignore[arg-type] + transport=FakeTransport(setup.fake), + session_kwargs={"sleep": lambda s: None}) + + +def _iqn(n: str) -> Initiator: + return Initiator(protocol=Protocol.ISCSI, address=f"iqn.2026-01.io.sb:{n}") + + +def test_wwn_from_serial(): + assert infinibox_wwn("742B0F000004E2B000000000000F3A3") == "naa.6742b0f000004e2b000000000000f3a3" + assert infinibox_wwn("6742b0f000004e2b000000000000f3a3") == "naa.6742b0f000004e2b000000000000f3a3" + + +def test_volume_identity_and_pool(setup): + with _client(setup) as c: + vol = c.create_volume(str(uuid.uuid4()), 10 * GIB + 1) + raw = setup.fake.volumes[int(vol.id)] + assert vol.wwn == "naa.6" + raw["serial"] + assert len(vol.wwn) == len("naa.") + 32 + assert raw["pool_id"] == next(iter(setup.fake.pools)) + assert raw["provtype"] == "THIN" + assert vol.size_bytes == 10 * GIB + (1 << 20) + + +def test_thick_option_and_bad_option(setup): + with _client(setup, provtype="thick") as c: + vol = c.create_volume(str(uuid.uuid4()), GIB) + assert setup.fake.volumes[int(vol.id)]["provtype"] == "THICK" + with _client(setup, provtype="sparse") as c, pytest.raises(ArrayError, match="provtype"): + c.get_info() + + +def test_missing_pool(setup): + with _client(setup, pool="nope") as c, pytest.raises(ArrayNotFoundError, match="nope"): + c.create_volume(str(uuid.uuid4()), GIB) + + +def test_destructive_requests_send_approval(setup): + with _client(setup) as c: + vol = c.create_volume(str(uuid.uuid4()), GIB) + host = c.ensure_host(HostSpec(name="h1", initiators=(_iqn("a"),))) + c.map_volume(vol.id, host) + assert c.delete_volume(vol.id) # unmap + delete, both need approved=true + c.delete_host(host) + assert not setup.fake.volumes and not setup.fake.hosts + + +def test_approval_required_is_not_an_auth_error(setup): + with _client(setup) as c: + vol = c.create_volume(str(uuid.uuid4()), GIB) + setup.fake.fail_next(403, {"result": None, "error": { + "code": "APPROVAL_REQUIRED", "message": "needs approval"}, + "metadata": {"ready": True}}, path=r"/volumes/\d+$") + adapter = c._adapter + assert adapter is not None + with pytest.raises(ArrayRequestError, match="APPROVAL_REQUIRED"): + adapter.delete_volume(vol.id) + + +def test_conflicting_port_rolls_back_new_host(setup): + with _client(setup) as c: + c.ensure_host(HostSpec(name="h1", initiators=(_iqn("a"),))) + with pytest.raises(ArrayConflictError): + c.ensure_host(HostSpec(name="h2", initiators=(_iqn("b"), _iqn("a")))) + assert [h["name"] for h in setup.fake.hosts.values()] == ["h1"] + + +def test_fc_and_iscsi_ports_normalised(setup): + fc = Initiator(protocol=Protocol.FC, address="21:00:00:24:FF:4C:1A:2B") + with _client(setup) as c: + host = c.ensure_host(HostSpec(name="h1", initiators=(fc, _iqn("A")))) + ports = setup.fake.hosts[int(host)]["ports"] + assert {(p["type"], p["address"]) for p in ports} == { + ("FC", "21000024ff4c1a2b"), ("ISCSI", "iqn.2026-01.io.sb:a")} + # colon-formatted ports returned by the array still count as present + ports[0]["address"] = "21:00:00:24:ff:4c:1a:2b" + assert c.ensure_host(HostSpec(name="h1", initiators=(fc,))) == host + assert len(setup.fake.hosts[int(host)]["ports"]) == 2 + + +def test_luns_start_at_one_per_host(setup): + with _client(setup) as c: + host = c.ensure_host(HostSpec(name="h1", initiators=(_iqn("a"),))) + luns = [c.map_volume(c.create_volume(str(uuid.uuid4()), GIB).id, host).lun + for _ in range(3)] + assert luns == [1, 2, 3] + + +def test_pagination_walks_all_pages(setup, monkeypatch): + import simplyblock_core.storage_arrays.adapters.infinidat as mod + monkeypatch.setattr(mod, "_PAGE_SIZE", 2) + for i in range(5): + setup.fake.add_volume(f"sb-same-{i}", GIB) + with _client(setup) as c: + c.get_info() + adapter = c._adapter + assert adapter is not None + assert len(adapter._list("/volumes")) == 5 + + +def test_non_numeric_ids_are_absent(setup): + with _client(setup) as c: + assert c.get_volume("sb-abc") is None + c.delete_host("not-a-number") + + +def test_bad_credential_is_auth_error(setup): + setup.fake.set_credential(password="other") + with _client(setup) as c, pytest.raises(ArrayError): + c.get_info() diff --git a/tests/unit/storage_arrays/test_netapp_ontap.py b/tests/unit/storage_arrays/test_netapp_ontap.py new file mode 100644 index 0000000000..31d2326b76 --- /dev/null +++ b/tests/unit/storage_arrays/test_netapp_ontap.py @@ -0,0 +1,430 @@ +"""NetApp ONTAP adapter specifics beyond the shared contract.""" +from __future__ import annotations + +import uuid + +import pytest + +from simplyblock_core.storage_arrays.adapters.netapp_ontap import ( + VOLUME_SUBSYSTEM_COMMENT, + NetAppOntapAdapter, + flexvol_name, + ontap_wwn, + parse_nsid, +) +from simplyblock_core.storage_arrays.base import ( + ArrayConflictError, + ArrayError, + ArrayNotFoundError, + ArrayRequestError, + ArrayUnsupportedError, + HostSpec, + Initiator, + Protocol, +) +from simplyblock_core.storage_arrays.client import ArrayClient +from simplyblock_core.storage_arrays.testing import FakeError, FakeTransport +from simplyblock_core.storage_arrays.testing.netapp_ontap import ( + FakeNetAppOntap, + contract_setup, +) + +from .conftest import StaticProvider + +GIB = 1 << 30 +NQN_A = "nqn.2014-08.org.nvmexpress:uuid:host-a" +NQN_B = "nqn.2014-08.org.nvmexpress:uuid:host-b" + + +def make(**options): + setup = contract_setup(**options) + client = ArrayClient(setup.config, StaticProvider(setup.credential), # type: ignore[arg-type] + transport=FakeTransport(setup.fake), + session_kwargs={"sleep": lambda s: None}) + return client, setup.fake + + +def iscsi(name, *iqns): + return HostSpec(name=name, initiators=tuple( + Initiator(protocol=Protocol.ISCSI, address=a) for a in iqns)) + + +def nvme(name, *nqns): + return HostSpec(name=name, initiators=tuple( + Initiator(protocol=Protocol.NVME_TCP, address=a) for a in nqns)) + + +def calls(fake: FakeNetAppOntap, method: str, fragment: str) -> list[int]: + return [i for i, (m, p) in enumerate(fake.requests) if m == method and fragment in p] + + +# -- identity helpers ----------------------------------------------------------- + + +def test_wwn_from_serial(): + # 12 ASCII chars -> 24 hex digits behind NetApp's NAA-6 prefix + assert ontap_wwn("wCVt1]IlvQWv") == "naa.600a0980" + "7743567431" + "5d496c76515776" + assert len(ontap_wwn("wCVt1]IlvQWv")) == len("naa.") + 32 + + +def test_volume_wwn_matches_fake_serial(): + client, fake = make() + vol = client.create_volume(str(uuid.uuid4()), GIB) + serial = fake.luns[vol.id]["serial_number"] + assert vol.wwn == ontap_wwn(serial) == vol.identifier + assert vol.nguid is None + + +def test_parse_nsid_and_flexvol_name(): + assert parse_nsid("00000001h") == 1 + assert parse_nsid("0000001Ah") == 26 + assert parse_nsid(3) == 3 + assert parse_nsid(None) is None + assert flexvol_name("sb-0123abcd") == "sb_0123abcd" + + +# -- layout ------------------------------------------------------------------------ + + +def test_create_makes_thin_flexvol_then_lun(): + client, fake = make() + vol = client.create_volume(str(uuid.uuid4()), 10 * GIB) + lun = fake.luns[vol.id] + flex = fake.volumes[lun["location"]["volume"]["uuid"]] + assert flex["name"] == flexvol_name(vol.name) + assert lun["name"] == f"/vol/{flex['name']}/{vol.name}" + assert lun["os_type"] == "linux" + assert lun["space"]["guarantee"]["requested"] is False + assert flex["guarantee"]["type"] == "none" + assert flex["space"]["snapshot"]["reserve_percent"] == 0 + assert flex["snapshot_policy"]["name"] == "none" + assert flex["size"] >= 10 * GIB * 105 // 100 + assert calls(fake, "POST", "/api/storage/volumes")[0] < calls(fake, "POST", + "/api/storage/luns")[0] + + +def test_resize_grows_flexvol_before_lun(): + client, fake = make() + vol = client.create_volume(str(uuid.uuid4()), 4 * GIB) + fake.requests.clear() + grown = client.resize_volume(vol.id, 40 * GIB) + assert grown.size_bytes == 40 * GIB + vol_patch = calls(fake, "PATCH", "/api/storage/volumes/") + lun_patch = calls(fake, "PATCH", "/api/storage/luns/") + assert vol_patch and lun_patch and vol_patch[0] < lun_patch[0] + flex_uuid = fake.luns[vol.id]["location"]["volume"]["uuid"] + assert fake.volumes[flex_uuid]["size"] >= 40 * GIB + + +def test_fake_refuses_lun_larger_than_flexvol(): + """Guards the ordering above: the fake rejects a LUN that outgrows its FlexVol.""" + client, fake = make() + vol = client.create_volume(str(uuid.uuid4()), 4 * GIB) + adapter = client._adapter + assert adapter is not None + with pytest.raises(ArrayRequestError, match="exceeds"): + adapter._call("PATCH", f"/api/storage/luns/{vol.id}", + json={"space": {"size": 64 * GIB}}) + + +def test_delete_removes_lun_then_flexvol(): + client, fake = make() + vol = client.create_volume(str(uuid.uuid4()), GIB) + fake.requests.clear() + assert client.delete_volume(vol.id) + assert calls(fake, "DELETE", "/api/storage/luns/")[0] < calls( + fake, "DELETE", "/api/storage/volumes/")[0] + assert not fake.luns and not fake.volumes + + +def test_shared_flexvol_mode(): + client, fake = make(volume_per_lun=False, flexvol="sb_shared") + fake.add_flexvol("sb_shared", 100 * GIB) + vol = client.create_volume(str(uuid.uuid4()), 4 * GIB) + assert fake.luns[vol.id]["name"] == f"/vol/sb_shared/{vol.name}" + assert len(fake.volumes) == 1 + client.resize_volume(vol.id, 8 * GIB) + assert not calls(fake, "PATCH", "/api/storage/volumes/") + client.delete_volume(vol.id) + assert not fake.luns and [v["name"] for v in fake.volumes.values()] == ["sb_shared"] + + +def test_rerun_reuses_flexvol_of_interrupted_create(): + client, fake = make() + vol_uuid = str(uuid.uuid4()) + name = client.volume_name(vol_uuid) + fake.add_flexvol(flexvol_name(name), 2 * GIB) + vol = client.create_volume(vol_uuid, 8 * GIB) + assert len(fake.volumes) == 1 + assert fake.volumes[fake.luns[vol.id]["location"]["volume"]["uuid"]]["size"] >= 8 * GIB + + +def test_multiple_aggregates_pick_most_free_space(): + client, fake = make(aggregates="aggr1, aggr2") + vol = client.create_volume(str(uuid.uuid4()), GIB) + flex = fake.volumes[fake.luns[vol.id]["location"]["volume"]["uuid"]] + assert [a["name"] for a in flex["aggregates"]] == ["aggr2"] + + +# -- jobs ---------------------------------------------------------------------------- + + +def test_job_is_polled_until_success(): + client, fake = make() + fake.job_polls = 4 + client.create_volume(str(uuid.uuid4()), GIB) + assert len(calls(fake, "GET", "/api/cluster/jobs/")) == 5 + + +def test_job_failure_raises_and_rolls_nothing_back(): + client, fake = make() + fake.fail_next_job("Insufficient space in aggregate aggr1.", "917830") + with pytest.raises(ArrayRequestError, match="Insufficient space"): + client.create_volume(str(uuid.uuid4()), GIB) + assert not fake.volumes and not fake.luns + + +def test_duplicate_flexvol_job_failure_is_conflict(): + client, fake = make() + adapter_vol = "sb_dup" + fake.add_flexvol(adapter_vol, GIB) + client.get_info() + adapter = client._adapter + assert adapter is not None + with pytest.raises(ArrayConflictError, match="Duplicate"): + adapter._create_flexvol(adapter_vol, GIB) + + +def test_job_timeout(): + client, fake = make(job_timeout_s=10) + fake.jobs_stuck = True + with pytest.raises(ArrayRequestError, match="still running"): + client.create_volume(str(uuid.uuid4()), GIB) + + +def test_lun_create_failure_removes_new_flexvol(monkeypatch): + client, fake = make() + + def refuse(*a, **kw): + raise FakeError(400, {"error": {"message": "LUN creation refused", "code": "1"}}) + + monkeypatch.setattr(fake, "_check_size", refuse) + with pytest.raises(ArrayRequestError, match="refused"): + client.create_volume(str(uuid.uuid4()), GIB) + assert not fake.volumes + + +# -- hosts ------------------------------------------------------------------------------- + + +def test_igroup_is_mixed_linux_and_fc_wwpn_is_colon_lowercase(): + client, fake = make() + spec = HostSpec(name="h1", initiators=( + Initiator(protocol=Protocol.ISCSI, address="IQN.2026-01.io.sb:h1"), + Initiator(protocol=Protocol.FC, address="0x21000024FF4C1A2B"))) + assert client.ensure_host(spec) == "h1" + (group,) = fake.igroups.values() + assert group["protocol"] == "mixed" and group["os_type"] == "linux" + assert {i["name"] for i in group["initiators"]} == { + "iqn.2026-01.io.sb:h1", "21:00:00:24:ff:4c:1a:2b"} + + +def test_initiator_in_foreign_igroup_conflicts_although_ontap_allows_it(): + client, fake = make() + client.get_info() + adapter = client._adapter + assert adapter is not None + # ONTAP itself accepts the same IQN in a second igroup ... + for name in ("customer", "other"): + adapter._call("POST", "/api/protocols/san/igroups", json={ + "svm": {"name": "svm1"}, "name": name, "os_type": "linux", "protocol": "iscsi", + "initiators": [{"name": "iqn.2026-01.io.sb:x"}]}) + # ... the adapter refuses + with pytest.raises(ArrayConflictError, match="customer"): + client.ensure_host(iscsi("mine", "iqn.2026-01.io.sb:x")) + assert "mine" not in {g["name"] for g in fake.igroups.values()} + + +def test_existing_iscsi_igroup_is_widened_for_fc(): + client, fake = make() + client.get_info() + adapter = client._adapter + assert adapter is not None + adapter._call("POST", "/api/protocols/san/igroups", json={ + "svm": {"name": "svm1"}, "name": "h2", "os_type": "linux", "protocol": "iscsi", + "initiators": [{"name": "iqn.2026-01.io.sb:h2"}]}) + client.ensure_host(HostSpec(name="h2", initiators=( + Initiator(protocol=Protocol.ISCSI, address="iqn.2026-01.io.sb:h2"), + Initiator(protocol=Protocol.FC, address="21:00:00:24:ff:4c:1a:99")))) + (group,) = fake.igroups.values() + assert group["protocol"] == "mixed" and len(group["initiators"]) == 2 + + +def test_nvme_fc_wwpn_address_is_refused(): + client, _ = make() + with pytest.raises(ArrayUnsupportedError, match="NQN"): + client.ensure_host(HostSpec(name="fc", initiators=( + Initiator(protocol=Protocol.NVME_FC, address="21:00:00:24:ff:4c:1a:2b"),))) + + +def test_nvme_rdma_is_not_supported(): + client, _ = make() + with pytest.raises(ArrayError, match="does not support"): + client.ensure_host(HostSpec(name="r", initiators=( + Initiator(protocol=Protocol.NVME_RDMA, address=NQN_A),))) + + +# -- options ------------------------------------------------------------------------------- + + +@pytest.mark.parametrize(("options", "match"), [ + ({"svm": None}, "needs options: svm"), + ({"protocol_family": "fcoe"}, "protocol_family"), + ({"volume_per_lun": False}, "flexvol is required"), + ({"space_guarantee": "file"}, "space_guarantee"), + ({"snapshot_reserve_percent": 95}, "snapshot_reserve_percent"), + ({"namespace_block_size": 1024}, "namespace_block_size"), + ({"job_timeout_s": "soon"}, "job_timeout_s"), + ({"pool": "x"}, "Unknown NetApp ONTAP options"), +]) +def test_option_validation(options, match): + setup = contract_setup() + opts = {**setup.config.options, **options} + opts = {k: v for k, v in opts.items() if v is not None} + from simplyblock_core.storage_arrays.base import AdapterContext + from simplyblock_core.storage_arrays.http import RestSession + config = setup.config.model_copy(update={"options": opts}) + with pytest.raises(ArrayError, match=match): + NetAppOntapAdapter(AdapterContext(config, setup.credential, + RestSession(config.endpoint))) + + +def test_unknown_svm_fails_login(): + setup = contract_setup() + config = setup.config.model_copy(update={"options": {"svm": "nope"}}) + client = ArrayClient(config, StaticProvider(setup.credential), # type: ignore[arg-type] + transport=FakeTransport(setup.fake)) + with pytest.raises(ArrayNotFoundError, match="nope"): + client.get_info() + + +def test_get_info(): + client, _ = make() + info = client.get_info() + assert info.model == "AFF-A400" + assert info.version.startswith("NetApp Release 9.14.1") + assert info.serial + + +# -- NVMe family and protocol routing ------------------------------------------------------ + + +def test_nvme_family_creates_namespace(): + client, fake = make(protocol_family="nvme") + vol = client.create_volume(str(uuid.uuid4()), 8 * GIB) + assert vol.id in fake.namespaces and not fake.luns + ns = fake.namespaces[vol.id] + assert ns["space"]["block_size"] == 4096 and ns["os_type"] == "linux" + assert vol.wwn is None and vol.identifier == f"id.{vol.id}" + assert client.get_volume(vol.id) == vol + grown = client.resize_volume(vol.id, 16 * GIB, expected_identifier=vol.identifier) + assert grown.size_bytes == 16 * GIB + + +def test_nvme_multi_attach_through_volume_subsystem(): + client, fake = make(protocol_family="nvme") + vol = client.create_volume(str(uuid.uuid4()), 8 * GIB) + ha = client.ensure_host(nvme("node-a", NQN_A)) + hb = client.ensure_host(nvme("node-b", NQN_B)) + ma = client.map_volume(vol.id, ha) + assert ma.lun == 1 and ma.host_id == "node-a" + assert client.map_volume(vol.id, ha) == ma + client.map_volume(vol.id, hb) + assert {m.host_id for m in client.list_mappings(vol.id)} == {"node-a", "node-b"} + (smap,) = fake.subsystem_maps + vsub = fake.subsystems[smap["subsystem"]["uuid"]] + assert vsub["comment"] == VOLUME_SUBSYSTEM_COMMENT + assert vsub["name"] == flexvol_name(vol.name) + assert {h["nqn"] for h in vsub["hosts"]} == {NQN_A, NQN_B} + + client.unmap_volume(vol.id, ha) + client.unmap_volume(vol.id, ha) + assert [m.host_id for m in client.list_mappings(vol.id)] == ["node-b"] + + assert client.delete_volume(vol.id) + assert not fake.namespaces and not fake.subsystem_maps and not fake.volumes + assert {s["name"] for s in fake.subsystems.values()} == {"node-a", "node-b"} + client.delete_host(ha) + client.delete_host(hb) + assert not fake.subsystems + + +def test_volume_subsystem_does_not_count_as_host_owner(): + client, _ = make(protocol_family="nvme") + vol = client.create_volume(str(uuid.uuid4()), GIB) + client.map_volume(vol.id, client.ensure_host(nvme("node-a", NQN_A))) + # NQN_A is now in node-a and in the volume subsystem: re-ensuring is fine, + assert client.ensure_host(nvme("node-a", NQN_A)) == "node-a" + # but another host claiming it conflicts. + with pytest.raises(ArrayConflictError, match="node-a"): + client.ensure_host(nvme("node-x", NQN_A)) + + +def test_scsi_volume_to_nvme_host_is_unsupported_and_vice_versa(): + client, _ = make() + lun = client.create_volume(str(uuid.uuid4()), GIB) + host = client.ensure_host(nvme("nv", NQN_A)) + with pytest.raises(ArrayUnsupportedError, match="NVMe host"): + client.map_volume(lun.id, host) + + nclient, nfake = make(protocol_family="nvme") + ns = nclient.create_volume(str(uuid.uuid4()), GIB) + nclient.ensure_host(iscsi("sc", "iqn.2026-01.io.sb:sc")) + with pytest.raises(ArrayUnsupportedError, match="SCSI host"): + nclient.map_volume(ns.id, "sc") + assert not nfake.subsystem_maps + + +def test_volumes_of_the_other_family_are_still_found(): + client, fake = make(protocol_family="nvme") + ns = client.create_volume(str(uuid.uuid4()), GIB) + scsi_setup_config = client.config.model_copy( + update={"options": {"svm": "svm1", "protocol_family": "scsi"}}) + provider = StaticProvider(contract_setup().credential) + scsi_client = ArrayClient(scsi_setup_config, provider, # type: ignore[arg-type] + transport=FakeTransport(fake)) + assert scsi_client.get_volume(ns.id) == ns + assert scsi_client.delete_volume(ns.id) + assert not fake.namespaces + + +def test_namespace_mapped_to_foreign_subsystem_is_refused(): + client, fake = make(protocol_family="nvme") + vol = client.create_volume(str(uuid.uuid4()), GIB) + adapter = client._adapter + assert adapter is not None + adapter._call("POST", "/api/protocols/nvme/subsystems", json={ + "svm": {"name": "svm1"}, "name": "customer_ss", "os_type": "linux"}) + adapter._call("POST", "/api/protocols/nvme/subsystem-maps", json={ + "svm": {"name": "svm1"}, "namespace": {"uuid": vol.id}, + "subsystem": {"name": "customer_ss"}}) + client.ensure_host(nvme("node-a", NQN_A)) + with pytest.raises(ArrayConflictError, match="does not manage"): + client.map_volume(vol.id, "node-a") + + +def test_lun_numbers_come_from_lun_maps(): + client, fake = make() + host = client.ensure_host(iscsi("h", "iqn.2026-01.io.sb:h")) + v1 = client.create_volume(str(uuid.uuid4()), GIB) + v2 = client.create_volume(str(uuid.uuid4()), GIB) + assert client.map_volume(v1.id, host).lun == 0 + assert client.map_volume(v2.id, host).lun == 1 + assert {m["logical_unit_number"] for m in fake.lun_maps} == {0, 1} + + +def test_map_to_missing_host_is_not_found(): + client, _ = make() + vol = client.create_volume(str(uuid.uuid4()), GIB) + with pytest.raises(ArrayNotFoundError): + client.map_volume(vol.id, "ghost") From 144ca3790ca5eb3c3ad15b5f417d1f5ffd82ee9c Mon Sep 17 00:00:00 2001 From: michael Date: Fri, 20 Nov 2026 16:22:27 +0100 Subject: [PATCH 4/4] feat(array): SAN arrays as multi-attach plugins; credential references Plug the 11 storage_arrays adapters into the multi-attach array LUN mode of #1626 and move its array credentials onto simplyblock_core.credentials. Plugins (simplyblock_core/array/san.py): one ArrayPlugin per array family (pure-flasharray, netapp-ontap, dell-powerstore/-powermax/-powerflex, hpe-wsapi, hpe-nimble, ibm-flashsystem, hitachi-vsp, huawei-dorado, infinidat-infinibox), built in and declared as entry points. Ownership is encoded in the LUN name (sb-): SAN arrays have no tags, and every operation refuses another cluster's LUN. wwn is returned in the form lsblk reports. option `protocol` selects the host initiators. list_luns is not offered; cluster delete deletes the recorded LUNs. Host side: the agent reports its SAN initiators in /info (iSCSI IQN, FC WWPNs, NVMe host NQN, PowerFlex SDC GUID; /host/etc first on Kubernetes) and gets POST /scan_new_luns (SCSI host scan, NVMe namespace rescan). Node add and the attachment reconcile scan while they wait for a LUN; an agent without the endpoint is tolerated. WWN matching accepts naa.. Credentials: register_array no longer stores plaintext through kms.put_secret. Given credentials are wrapped by the cluster's credentials key (Vault Transit, KMIP, or the local KMS only with allow_local_kms_credentials), bound to array id + endpoint, and kept as Cluster.array_credential_ref; or credential_ref names an external Vault KV / KMIP secret that is only read. Arrays registered before keep working from their KMS path, which a re-registration removes. API/CLI: credential_ref / --credential-ref. CredentialProvider resolves the KMS connection per call. Co-Authored-By: Claude Opus 5.5 --- pyproject.toml | 11 + simplyblock_cli/cli-reference.yaml | 9 +- simplyblock_cli/cli.py | 1 + simplyblock_cli/clibase.py | 10 +- simplyblock_core/array/__init__.py | 64 +++- simplyblock_core/array/san.py | 340 ++++++++++++++++++ .../controllers/array_controller.py | 163 +++++++-- simplyblock_core/credentials.py | 11 +- simplyblock_core/models/cluster.py | 11 +- simplyblock_core/multi_attach.py | 3 +- simplyblock_core/snode_client.py | 5 + .../api/internal/storage_node/docker.py | 19 + .../api/internal/storage_node/kubernetes.py | 19 + simplyblock_web/api/v2/cluster/array.py | 18 +- simplyblock_web/node_utils.py | 74 +++- tests/unit/storage_arrays/test_san_plugin.py | 154 ++++++++ tests/unit/test_array_lifecycle.py | 144 +++++++- tests/unit/test_credentials.py | 4 + tests/unit/test_san_host_agent.py | 96 +++++ 19 files changed, 1094 insertions(+), 62 deletions(-) create mode 100644 simplyblock_core/array/san.py create mode 100644 tests/unit/storage_arrays/test_san_plugin.py create mode 100644 tests/unit/test_san_host_agent.py diff --git a/pyproject.toml b/pyproject.toml index 31d6e99c70..d92f5d6759 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -55,6 +55,17 @@ simplyblock-task-runner = "simplyblock_core.services.task_runners:main" # (simplyblock_core.array); the name is the value of Cluster.array_plugin. [project.entry-points."simplyblock.array_plugins"] aws-ebs = "simplyblock_core.array.aws_ebs:AwsEbsPlugin" +pure-flasharray = "simplyblock_core.array.san:PureFlashArrayPlugin" +netapp-ontap = "simplyblock_core.array.san:NetAppOntapPlugin" +dell-powerstore = "simplyblock_core.array.san:DellPowerStorePlugin" +dell-powermax = "simplyblock_core.array.san:DellPowerMaxPlugin" +dell-powerflex = "simplyblock_core.array.san:DellPowerFlexPlugin" +hpe-wsapi = "simplyblock_core.array.san:HpeWsapiPlugin" +hpe-nimble = "simplyblock_core.array.san:HpeNimblePlugin" +ibm-flashsystem = "simplyblock_core.array.san:IbmFlashSystemPlugin" +hitachi-vsp = "simplyblock_core.array.san:HitachiVspPlugin" +huawei-dorado = "simplyblock_core.array.san:HuaweiDoradoPlugin" +infinidat-infinibox = "simplyblock_core.array.san:InfinidatInfiniBoxPlugin" [dependency-groups] test = [ diff --git a/simplyblock_cli/cli-reference.yaml b/simplyblock_cli/cli-reference.yaml index d9e7a49083..9c23422597 100644 --- a/simplyblock_cli/cli-reference.yaml +++ b/simplyblock_cli/cli-reference.yaml @@ -1596,7 +1596,8 @@ commands: usage: > simplyblock creates, multi-attaches, grows, fences and deletes the LUNs of a multi-attach cluster through the array plugin registered here. The plugin is loaded and connected with the credentials before anything - is saved. The credentials are stored in the cluster's KMS, never in the cluster record. With --lun-size, + is saved. The credentials are wrapped by the cluster's KMS (or stay in an external Vault KV / KMIP secret named + by --credential-ref), never stored in the clear. With --lun-size, every node added afterwards gets a LUN of that size created and attached on the array. arguments: - name: "cluster_id" @@ -1624,6 +1625,12 @@ commands: aws_secret_access_key; omit to use the instance role). dest: credentials_file type: str + - name: "--credential-ref" + help: > + Instead of --credentials-file: a secret kept outside simplyblock, as JSON, e.g. + `{"kind": "vault-kv", "mount": "secret", "path": "arrays/pure01"}` or `{"kind": "kmip-secret", "uid": "42"}`. + dest: credential_ref + type: str - name: "--lun-size" help: "Size of the LUN created for each node added to the cluster, e.g. `1T`. Default: none." dest: lun_size diff --git a/simplyblock_cli/cli.py b/simplyblock_cli/cli.py index 68dfb20176..5f3d845cb8 100755 --- a/simplyblock_cli/cli.py +++ b/simplyblock_cli/cli.py @@ -583,6 +583,7 @@ def init_cluster__set_array(self, subparser): subcommand.add_argument('--endpoint', help='The array\'s management endpoint (for aws-ebs: an EC2 endpoint URL override, usually empty).', type=str, default='', dest='endpoint') subcommand.add_argument('--options', help='Plugin options as a JSON object, e.g. `{"az": "us-east-1a", "iops": 6000}`.', type=str, dest='options') subcommand.add_argument('--credentials-file', help='A JSON file with the array credentials as an object of strings (for aws-ebs: aws_access_key_id, aws_secret_access_key; omit to use the instance role).', type=str, dest='credentials_file') + subcommand.add_argument('--credential-ref', help='Instead of --credentials-file: a secret kept outside simplyblock, as JSON, e.g. `{"kind": "vault-kv", "mount": "secret", "path": "arrays/pure01"}` or `{"kind": "kmip-secret", "uid": "42"}`.', type=str, dest='credential_ref') subcommand.add_argument('--lun-size', help='Size of the LUN created for each node added to the cluster, e.g. `1T`. Default: none.', type=size_type(), default='0', dest='lun_size') def init_cluster__get_array(self, subparser): diff --git a/simplyblock_cli/clibase.py b/simplyblock_cli/clibase.py index bc4167faa1..9733aee3f7 100755 --- a/simplyblock_cli/clibase.py +++ b/simplyblock_cli/clibase.py @@ -879,9 +879,17 @@ def cluster__set_array(self, sub_command, args): raise ValueError("--credentials-file must hold a JSON object of strings") # Wrapped at the boundary; unwrapped only by the KMS and the plugin. credentials = {str(k): SecretStr(v) for k, v in raw.items()} + credential_ref = None + if getattr(args, "credential_ref", None): + try: + credential_ref = json.loads(args.credential_ref) + except json.JSONDecodeError as e: + raise ValueError(f"--credential-ref is not valid JSON: {e}") + if not isinstance(credential_ref, dict): + raise ValueError("--credential-ref must be a JSON object") view = array_controller.register_array( args.cluster_id, args.plugin, args.endpoint or "", options, credentials, - int(args.lun_size or 0)) + int(args.lun_size or 0), credential_ref=credential_ref) return _format_result([view], json=getattr(args, "json", False)) def cluster__get_array(self, sub_command, args): diff --git a/simplyblock_core/array/__init__.py b/simplyblock_core/array/__init__.py index cff580e013..b491a9d893 100644 --- a/simplyblock_core/array/__init__.py +++ b/simplyblock_core/array/__init__.py @@ -11,8 +11,8 @@ registry that loads a vendor plugin by name from the entry-point group ``simplyblock.array_plugins``. The array's credentials live in the KMS at ``cluster//array/``; the Cluster record keeps the plugin -name, endpoint and options only. Built-in plugin: ``aws-ebs`` -(:mod:`.aws_ebs`). Registration and the LUN lifecycle are in +name, endpoint and options only. Built-in plugins: ``aws-ebs`` +(:mod:`.aws_ebs`) and the SAN arrays (:mod:`.san`). Registration and the LUN lifecycle are in :mod:`simplyblock_core.controllers.array_controller`. Plugins are found only through the entry-point group or an explicit @@ -40,6 +40,18 @@ #: pyproject.toml). BUILTIN_PLUGINS = { "aws-ebs": "simplyblock_core.array.aws_ebs:AwsEbsPlugin", + # SAN arrays: the storage_arrays adapters (simplyblock_core.array.san). + "pure-flasharray": "simplyblock_core.array.san:PureFlashArrayPlugin", + "netapp-ontap": "simplyblock_core.array.san:NetAppOntapPlugin", + "dell-powerstore": "simplyblock_core.array.san:DellPowerStorePlugin", + "dell-powermax": "simplyblock_core.array.san:DellPowerMaxPlugin", + "dell-powerflex": "simplyblock_core.array.san:DellPowerFlexPlugin", + "hpe-wsapi": "simplyblock_core.array.san:HpeWsapiPlugin", + "hpe-nimble": "simplyblock_core.array.san:HpeNimblePlugin", + "ibm-flashsystem": "simplyblock_core.array.san:IbmFlashSystemPlugin", + "hitachi-vsp": "simplyblock_core.array.san:HitachiVspPlugin", + "huawei-dorado": "simplyblock_core.array.san:HuaweiDoradoPlugin", + "infinidat-infinibox": "simplyblock_core.array.san:InfinidatInfiniBoxPlugin", } @@ -269,10 +281,39 @@ def load_plugin(name: str, endpoint: str = "", options: dict | None = None, return plugin +def credential_context(array_id: str, endpoint: str) -> str: + """What an array's credentials are bound to: the array id and the + scheme/host/port of its endpoint. A credential wrapped for one array is + refused for another endpoint, so rewriting the endpoint in the database + cannot send it elsewhere.""" + from urllib.parse import urlsplit + ep = (endpoint or "").strip() + parts = urlsplit(ep) + if parts.scheme and parts.hostname: + port = parts.port or (443 if parts.scheme == "https" else 80) + ep = f"{parts.scheme}://{parts.hostname.lower()}:{port}" + return f"array/{array_id}/{ep}" + + +def credential_ref_view(cluster) -> dict: + """The cluster's array credential reference without anything secret: + the kind, and for an external secret where it lives.""" + ref = dict(getattr(cluster, "array_credential_ref", None) or {}) + if not ref: + return {} + if ref.get("kind") == "managed": + return {"kind": "managed", "backend": ref.get("backend", "")} + return {k: v for k, v in ref.items() if k in ("kind", "mount", "path", "version", "uid", "field")} + + def array_credentials(cluster) -> dict: - """The credentials of the cluster's array from the KMS (``SecretStr`` - values), or ``{}`` when the array was registered without any (e.g. the - EBS plugin on the instance role) or no array is registered. + """The credentials of the cluster's array (``SecretStr`` values), or + ``{}`` when the array was registered without any (e.g. the EBS plugin on + the instance role) or no array is registered. + + Read through ``Cluster.array_credential_ref`` (wrapped by the cluster's + KMS, or an external Vault KV / KMIP secret); arrays registered before + references existed are read from their KMS path. Raises: ArrayError: a secret is recorded but cannot be read. @@ -280,6 +321,16 @@ def array_credentials(cluster) -> dict: array_id = getattr(cluster, "array_id", "") or "" if not array_id or getattr(cluster, "array_has_credentials", False) is not True: return {} + ref = getattr(cluster, "array_credential_ref", None) or {} + if ref: + from simplyblock_core import credentials as creds_mod + try: + resolved = creds_mod.CredentialProvider(cluster, ttl_s=0).resolve( + ref, credential_context(array_id, getattr(cluster, "array_endpoint", "") or "")) + except creds_mod.CredentialError as e: + raise ArrayError(f"array credentials could not be read: {e}") from e + return {name: resolved.get(name) for name in resolved.field_names + if name != creds_mod.CONTEXT_FIELD} from simplyblock_core import kms try: with kms.create_kms_connection(cluster) as conn: @@ -319,7 +370,8 @@ def _config_key(cluster) -> tuple: getattr(cluster, "array_endpoint", "") or "", json.dumps(getattr(cluster, "array_options", None) or {}, sort_keys=True, default=str), getattr(cluster, "array_id", "") or "", - getattr(cluster, "array_has_credentials", False) is True) + getattr(cluster, "array_has_credentials", False) is True, + json.dumps(getattr(cluster, "array_credential_ref", None) or {}, sort_keys=True)) def cached_plugin_for_cluster(cluster, max_age: float | None = None) -> ArrayPlugin: diff --git a/simplyblock_core/array/san.py b/simplyblock_core/array/san.py new file mode 100644 index 0000000000..4950687f4f --- /dev/null +++ b/simplyblock_core/array/san.py @@ -0,0 +1,340 @@ +"""SAN array plugins: the vendor adapters of :mod:`simplyblock_core.storage_arrays` +as :class:`~simplyblock_core.array.ArrayPlugin` s. + +One plugin per supported array family (``pure-flasharray``, ``netapp-ontap``, +... see :data:`SAN_PLUGINS`). Each wraps an +:class:`~simplyblock_core.storage_arrays.client.ArrayClient`, which already +gives the plugin contract its guarantees: idempotent create / map / unmap / +delete, grow-only resize, one re-authentication on a rejected session. + +Ownership. SAN arrays mostly have no free-form tags, so a LUN's owner is +encoded in its name: ``sb-`` (27 characters, +inside every supported array's name limit). The cluster part makes every +operation refuse a LUN of another cluster (:class:`ForeignLunError`); the LUN +part is derived from the name the control plane asked for, so a retried +create finds the LUN it made before. + +Hosts. A storage node is registered with the initiators of the protocol named +by the ``protocol`` option (``iscsi``, ``fc``, ``nvme-tcp``, ``nvme-rdma``, +``nvme-fc``, ``sdc``), taken from what its agent reports +(``host_initiators``: ``iscsi_iqn``, ``fc_wwpns``, ``nvme_hostnqn``, +``sdc_guid``). The host object is named ``sb-`` (shortened with a +hash suffix where the array's limit is shorter). + +Identity. ``wwn`` is returned in the form the hosts report it (lsblk ``WWN``): +the NAA hex digits for SCSI, ``eui.`` for NVMe namespaces. + +Options (``Cluster.array_options``): ``protocol`` (required), ``ca_bundle`` +(PEM), ``verify_tls`` (default true), ``timeout_s``, and the adapter's own +options (``option_docs`` of the adapter: pool, SVM, CPG, port group, ...). +``host_portals`` (iSCSI / NVMe discovery portals the nodes log in to) is read +by the node-side scan, not here. +""" + +from __future__ import annotations + +import hashlib +import logging +import re +import uuid as uuid_mod +from typing import Any + +from pydantic import SecretStr, ValidationError + +from simplyblock_core.array import ArrayError, ArrayPlugin, ForeignLunError +from simplyblock_core.credentials import Credential +from simplyblock_core.storage_arrays import base as sa +from simplyblock_core.storage_arrays.client import MANAGED_PREFIX, ArrayClient + +logger = logging.getLogger() + +#: Options consumed by the plugin itself; everything else goes to the adapter. +_PLUGIN_OPTIONS = frozenset({"protocol", "ca_bundle", "verify_tls", "timeout_s", + "host_portals"}) + +#: ``host_initiators`` keys per protocol. +_INITIATOR_KEYS = { + sa.Protocol.ISCSI: "iscsi_iqn", + sa.Protocol.FC: "fc_wwpns", + sa.Protocol.NVME_TCP: "nvme_hostnqn", + sa.Protocol.NVME_RDMA: "nvme_hostnqn", + sa.Protocol.NVME_FC: "nvme_hostnqn", + sa.Protocol.SDC: "sdc_guid", +} + +_CLUSTER_HEX = 8 +_LUN_HEX = 16 + + +def _hex(text: str, n: int) -> str: + return hashlib.sha256(text.encode()).hexdigest()[:n] + + +def lun_uuid(cluster_id: str, name: str) -> str: + """The volume UUID whose managed name encodes cluster and LUN name.""" + hex32 = _hex(f"cluster:{cluster_id}", _CLUSTER_HEX) + _hex(f"lun:{cluster_id}/{name}", 24) + return str(uuid_mod.UUID(hex32)) + + +def cluster_prefix(cluster_id: str) -> str: + return MANAGED_PREFIX + _hex(f"cluster:{cluster_id}", _CLUSTER_HEX) + + +def host_wwn(vol: sa.Volume, protocol: sa.Protocol) -> str: + """The identity a host reports for ``vol`` (lsblk ``WWN``).""" + if protocol.is_nvme and vol.nguid: + return vol.nguid.lower() + if vol.wwn: + w = vol.wwn.lower() + return w.removeprefix("naa.") + return vol.identifier.lower() + + +def host_object_name(hostname: str, max_len: int) -> str: + clean = re.sub(r"[^A-Za-z0-9-]", "-", hostname or "").strip("-") or "host" + name = f"{MANAGED_PREFIX}{clean}" + if len(name) <= max_len: + return name + suffix = "-" + _hex(hostname, 8) + return name[: max_len - len(suffix)].rstrip("-") + suffix + + +class _StaticCredentials: + """The plugin gets its credentials already resolved (from the KMS).""" + + def __init__(self, fields: dict[str, SecretStr]): + self._credential = Credential(fields) + + def resolve(self, ref, context): + return self._credential + + def invalidate(self, ref=None): + pass + + +def _as_list(value) -> list[str]: + if not value: + return [] + if isinstance(value, str): + return [v for v in re.split(r"[\s,]+", value) if v] + return [str(v) for v in value if v] + + +class SanArrayPlugin(ArrayPlugin): + """Base of the per-vendor plugins; ``vendor`` is the adapter key.""" + + vendor: str = "" + + def __init__(self, endpoint: str = "", options: dict | None = None, credentials=None, + cluster_id: str = ""): + super().__init__(endpoint, options, credentials, cluster_id) + self.client: ArrayClient | None = None + #: Tests: a ``requests`` transport (vendor fake) and session kwargs. + self.transport: Any = None + self.session_kwargs: dict[str, Any] = {} + + # ------------------------------------------------------------ setup + + @property + def protocol(self) -> sa.Protocol: + raw = str(self.options.get("protocol") or "").strip().lower() + if not raw: + raise ArrayError(f"array plugin {self.vendor}: option 'protocol' is required " + f"({', '.join(p.value for p in sa.Protocol)})") + try: + return sa.Protocol(raw) + except ValueError: + raise ArrayError(f"array plugin {self.vendor}: unknown protocol {raw!r}") from None + + def connect(self, endpoint: str, credentials: dict, options: dict) -> None: + super().connect(endpoint, credentials, options) + if not self.cluster_id: + raise ArrayError("the plugin has no cluster id") + proto = self.protocol + adapter_opts = {k: v for k, v in self.options.items() if k not in _PLUGIN_OPTIONS} + try: + config = sa.ArrayConfig( + id=f"{self.cluster_id}", + vendor=self.vendor, + endpoint=endpoint, + # The plugin resolves nothing itself: the provider below hands + # back the credentials it was given. + credential_ref={"kind": "vault-kv", "mount": "-", "path": "-"}, + ca_bundle=self.options.get("ca_bundle") or None, + verify_tls=_truthy(self.options.get("verify_tls", True)), + timeout_s=float(self.options.get("timeout_s") or 60.0), + options=adapter_opts, + ) + except ValidationError as e: + raise ArrayError(f"array plugin {self.vendor}: {_first_error(e)}") from None + fields = {k: v if isinstance(v, SecretStr) else SecretStr(str(v)) + for k, v in (credentials or {}).items()} + self.client = ArrayClient(config, _StaticCredentials(fields), # type: ignore[arg-type] + transport=self.transport, session_kwargs=self.session_kwargs) + caps = self.client.capabilities + if proto not in caps.protocols: + raise ArrayError(f"{self.client.adapter_cls.display_name} does not support " + f"{proto.value} (supported: " + f"{', '.join(sorted(p.value for p in caps.protocols))})") + # Validates credential shape and options, logs in. + self._run(lambda c: c.get_info()) + + def _client(self) -> ArrayClient: + if self.client is None: + raise ArrayError("array plugin is not connected") + return self.client + + def _run(self, fn): + try: + return fn(self._client()) + except ArrayError: + raise + except sa.ArrayError as e: + raise ArrayError(str(e)) from e + + def capabilities(self) -> dict: + caps = self._client().capabilities if self.client else None + protocols = sorted(p.value for p in caps.protocols) if caps else [] + return {"protocols": protocols, "supports_reservations": False, "max_attachments": 0} + + # ---------------------------------------------------------- ownership + + def _prefix(self) -> str: + return cluster_prefix(self.cluster_id) + + def _owned_volume(self, lun_id: str) -> sa.Volume | None: + vol = self._run(lambda c: c.get_volume(lun_id)) + if vol is not None and not vol.name.startswith(self._prefix()): + raise ForeignLunError( + f"LUN {lun_id} ({vol.name}) was not created by simplyblock cluster " + f"{self.cluster_id}; it is not touched") + return vol + + def _view(self, vol: sa.Volume) -> dict: + hosts = [m.host_id for m in self._run(lambda c: c.list_mappings(vol.id))] + return {"id": vol.id, "wwn": host_wwn(vol, self.protocol), "size": vol.size_bytes, + "name": vol.name, "hosts": hosts} + + # --------------------------------------------------------- operations + + def ensure_host(self, name: str, initiators: dict) -> str: + proto = self.protocol + key = _INITIATOR_KEYS[proto] + addresses = _as_list((initiators or {}).get(key)) + if not addresses: + raise ArrayError( + f"host {name!r} reports no {proto.value} initiator ({key}); check the " + "host's initiator setup (iSCSI initiatorname, FC HBA, NVMe hostnqn, SDC)") + try: + spec = sa.HostSpec( + name=host_object_name(name, self._client().capabilities.max_name_len), + initiators=tuple(sa.Initiator(protocol=proto, address=a) for a in addresses)) + except ValidationError as e: + raise ArrayError(f"host {name!r}: {_first_error(e)}") from None + return self._run(lambda c: c.ensure_host(spec)) + + def create_lun(self, name: str, size_bytes: int, tags: dict) -> dict: + self.cluster_tags(tags, name) # refuses without a cluster id + if int(size_bytes) <= 0: + raise ArrayError("a LUN needs a size") + vol = self._run(lambda c: c.create_volume(lun_uuid(self.cluster_id, name), int(size_bytes))) + return {"id": vol.id, "wwn": host_wwn(vol, self.protocol), "size": vol.size_bytes} + + def attach(self, lun_id: str, host_id: str) -> None: + if self._owned_volume(lun_id) is None: + raise ArrayError(f"LUN {lun_id} not found") + self._run(lambda c: c.map_volume(lun_id, host_id)) + + def detach(self, lun_id: str, host_id: str, force: bool = False) -> None: + if self._owned_volume(lun_id) is None: + return + # An unmap at the array takes effect for the host at once, queued + # I/O included: the same with and without ``force``. + self._run(lambda c: c.unmap_volume(lun_id, host_id)) + + def resize(self, lun_id: str, size_bytes: int) -> None: + if self._owned_volume(lun_id) is None: + raise ArrayError(f"LUN {lun_id} not found") + self._run(lambda c: c.resize_volume(lun_id, int(size_bytes))) + + def get(self, lun_id: str) -> dict: + vol = self._owned_volume(lun_id) + if vol is None: + raise ArrayError(f"LUN {lun_id} not found") + return self._view(vol) + + def delete_lun(self, lun_id: str) -> None: + if self._owned_volume(lun_id) is None: + return + self._run(lambda c: c.delete_volume(lun_id)) + + def list_luns(self) -> list[dict]: + """Not offered by the SAN adapters (no portable prefix listing); + ``array_controller.delete_cluster_luns`` deletes the recorded LUNs.""" + raise NotImplementedError(f"{self.vendor}: listing LUNs is not supported") + + +def _truthy(v) -> bool: + if isinstance(v, bool): + return v + return str(v).strip().lower() not in ("0", "false", "no", "off", "") + + +def _first_error(e: ValidationError) -> str: + err = e.errors()[0] + loc = ".".join(str(p) for p in err.get("loc", ())) + return f"{loc}: {err.get('msg')}" if loc else str(err.get("msg")) + + +class PureFlashArrayPlugin(SanArrayPlugin): + vendor = "pure-flasharray" + + +class NetAppOntapPlugin(SanArrayPlugin): + vendor = "netapp-ontap" + + +class DellPowerStorePlugin(SanArrayPlugin): + vendor = "dell-powerstore" + + +class DellPowerMaxPlugin(SanArrayPlugin): + vendor = "dell-powermax" + + +class DellPowerFlexPlugin(SanArrayPlugin): + vendor = "dell-powerflex" + + +class HpeWsapiPlugin(SanArrayPlugin): + vendor = "hpe-wsapi" + + +class HpeNimblePlugin(SanArrayPlugin): + vendor = "hpe-nimble" + + +class IbmFlashSystemPlugin(SanArrayPlugin): + vendor = "ibm-flashsystem" + + +class HitachiVspPlugin(SanArrayPlugin): + vendor = "hitachi-vsp" + + +class HuaweiDoradoPlugin(SanArrayPlugin): + vendor = "huawei-dorado" + + +class InfinidatInfiniBoxPlugin(SanArrayPlugin): + vendor = "infinidat-infinibox" + + +#: Plugin name (= adapter key) -> import path, merged into BUILTIN_PLUGINS. +SAN_PLUGINS = { + cls.vendor: f"{__name__}:{cls.__name__}" + for cls in (PureFlashArrayPlugin, NetAppOntapPlugin, DellPowerStorePlugin, + DellPowerMaxPlugin, DellPowerFlexPlugin, HpeWsapiPlugin, HpeNimblePlugin, + IbmFlashSystemPlugin, HitachiVspPlugin, HuaweiDoradoPlugin, + InfinidatInfiniBoxPlugin) +} diff --git a/simplyblock_core/controllers/array_controller.py b/simplyblock_core/controllers/array_controller.py index 7619b88072..01956e0ae6 100644 --- a/simplyblock_core/controllers/array_controller.py +++ b/simplyblock_core/controllers/array_controller.py @@ -121,6 +121,7 @@ def array_view(cluster, capabilities=None) -> dict: "options": dict(cluster.array_options or {}), "lun_size": int(cluster.array_lun_size or 0), "has_credentials": bool(cluster.array_has_credentials), + "credential_ref": array.credential_ref_view(cluster), } if capabilities is not None: out["capabilities"] = capabilities @@ -128,21 +129,33 @@ def array_view(cluster, capabilities=None) -> dict: def register_array(cluster_id, plugin, endpoint="", options=None, credentials=None, - lun_size=0) -> dict: + lun_size=0, credential_ref=None) -> dict: """Register (or re-register, e.g. to rotate credentials) the storage array of a multi-attach cluster. - The plugin is loaded and connected with the given credentials and its - capabilities read before anything is saved. Credentials (a flat dict of - strings / SecretStr) are stored in the KMS; the Cluster record keeps the - plugin name, endpoint, options and LUN size. Returns the array view - (``array_view``) with the plugin's capabilities. + The plugin is loaded and connected with the credentials and its + capabilities read before anything is saved. The Cluster record keeps the + plugin name, endpoint, options, LUN size and a credential reference + (``Cluster.array_credential_ref``), never a credential: + + * ``credentials`` (a flat dict of strings / SecretStr) are wrapped by the + cluster's credentials key in its KMS (Vault Transit or KMIP; the local + KMS only with ``allow_local_kms_credentials``), bound to the array id + and endpoint, and only the wrapped form is kept; + * ``credential_ref`` names a secret kept outside simplyblock instead + (``{"kind": "vault-kv", "mount", "path"[, "version"]}`` or + ``{"kind": "kmip-secret", "uid"[, "field"]}``): simplyblock reads it + when it connects and never stores it. + + Returns the array view (``array_view``) with the plugin's capabilities. Raises: - ValueError: not a multi-attach cluster, the plugin cannot be loaded - or connected, its capabilities do not fit the cluster, or LUNs - created through another plugin exist. + ValueError: not a multi-attach cluster, both or a bad credential + source, the credentials cannot be stored or read, the plugin + cannot be loaded or connected, its capabilities do not fit the + cluster, or LUNs created through another plugin exist. """ + from simplyblock_core import credentials as creds_mod from simplyblock_core import kms db = _db() cluster = db.get_cluster_by_id(cluster_id) @@ -153,12 +166,32 @@ def register_array(cluster_id, plugin, endpoint="", options=None, credentials=No if int(lun_size or 0) < 0: raise ValueError("lun_size must not be negative") creds = _wrap_credentials(credentials) + if creds and credential_ref: + raise ValueError("give the credentials or a reference to them, not both") opts = dict(options or {}) nodes = db.get_storage_nodes_by_cluster_id(cluster_id) if (cluster.array_plugin and cluster.array_plugin != plugin and _managed_devices(nodes)): raise ValueError( f"LUNs created through plugin {cluster.array_plugin!r} exist; the plugin cannot change") + array_id = cluster.array_id or str(uuid_mod.uuid4()) + context = array.credential_context(array_id, endpoint or "") + ref: dict = {} + if credential_ref: + try: + parsed = creds_mod.CREDENTIAL_REF_ADAPTER.validate_python(dict(credential_ref)) + except Exception as e: # noqa: BLE001 - pydantic + raise ValueError(f"credential_ref is not a valid reference: {e}") from None + if isinstance(parsed, creds_mod.ManagedCredentialRef): + raise ValueError("credential_ref names an external secret (vault-kv or kmip-secret); " + "give the credentials themselves to have them stored") + ref = parsed.model_dump() + try: + resolved = creds_mod.CredentialProvider(cluster, ttl_s=0).resolve(parsed, context) + except creds_mod.CredentialError as e: + raise ValueError(f"the referenced credentials could not be read: {e}") from None + creds = {name: resolved.get(name) for name in resolved.field_names + if name != creds_mod.CONTEXT_FIELD} try: inst = array.load_plugin(plugin, endpoint, opts, credentials=creds, cluster_id=cluster_id) caps = dict(inst.capabilities() or {}) @@ -172,32 +205,32 @@ def register_array(cluster_id, plugin, endpoint="", options=None, credentials=No if max_att and max_att < needed: raise ValueError(f"the array presents a LUN to at most {max_att} hosts; the cluster needs {needed}") - array_id = cluster.array_id or str(uuid_mod.uuid4()) - path = kms.array_secret_path(cluster_id, array_id) - with kms.create_kms_connection(cluster) as conn: - if creds: - conn.put_secret(path, creds) - elif cluster.array_has_credentials: - conn.delete_secret(path) + if creds and not ref: + try: + ref = creds_mod.CredentialProvider(cluster).store(creds, context).model_dump() + except creds_mod.CredentialError as e: + raise ValueError(f"the array credentials could not be stored: {e}") from None + # A secret an earlier registration kept at the KMS path (before + # credential references) is removed once the new registration is saved. + legacy_secret = bool(cluster.array_has_credentials) and not cluster.array_credential_ref def mutate(fresh): fresh.array_id = array_id fresh.array_plugin = plugin fresh.array_endpoint = endpoint or "" fresh.array_options = opts - fresh.array_has_credentials = bool(creds) + fresh.array_credential_ref = ref + fresh.array_has_credentials = bool(ref) fresh.array_lun_size = int(lun_size or 0) - try: - db.atomic_update(cluster, mutate) - except Exception: - if creds and not cluster.array_has_credentials: - try: - with kms.create_kms_connection(cluster) as conn: - conn.delete_secret(path) - except Exception: # noqa: BLE001 - logger.exception("could not remove the array secret after a failed registration") - raise + db.atomic_update(cluster, mutate) + if legacy_secret: + try: + with kms.create_kms_connection(cluster) as conn: + conn.delete_secret(kms.array_secret_path(cluster_id, array_id)) + except Exception: # noqa: BLE001 + logger.exception("could not remove the array's earlier KMS secret") + array.forget_plugin(cluster_id) cluster = db.get_cluster_by_id(cluster_id) logger.info("Cluster %s: array %s registered (plugin %s, endpoint %s)", cluster_id, array_id, plugin, endpoint or "-") @@ -231,7 +264,9 @@ def delete_array(cluster_id, array_id, force=False) -> None: if managed and not force: raise ValueError(f"{len(managed)} LUN(s) created through the array exist; " "takeovers would lose their fence") - if cluster.array_id and cluster.array_has_credentials: + # A credential reference needs no cleanup: a managed one exists only in + # the record, an external one belongs to whoever created it. + if cluster.array_id and cluster.array_has_credentials and not cluster.array_credential_ref: with kms.create_kms_connection(cluster) as conn: conn.delete_secret(kms.array_secret_path(cluster_id, cluster.array_id)) @@ -240,6 +275,7 @@ def mutate(fresh): fresh.array_plugin = "" fresh.array_endpoint = "" fresh.array_options = {} + fresh.array_credential_ref = {} fresh.array_has_credentials = False fresh.array_lun_size = 0 @@ -249,11 +285,23 @@ def mutate(fresh): # ------------------------------------------------------------------- hosts -def host_initiators(hostname="", cloud_instance=None, system_id="", ip="") -> dict: - """What identifies a host on an array: its hostname, system id, IP and, - on AWS, the EC2 instance id (reported by the node agent from the - instance metadata service when its cloud probe runs).""" +#: SAN initiator keys the node agent reports (``san_initiators`` of its +#: /info; node_utils.get_san_initiators) and SAN plugins read. +SAN_INITIATOR_KEYS = ("iscsi_iqn", "fc_wwpns", "nvme_hostnqn", "sdc_guid") + + +def host_initiators(hostname="", cloud_instance=None, system_id="", ip="", + san_initiators=None) -> dict: + """What identifies a host on an array: its hostname, system id, IP, its + SAN initiators (iSCSI IQN, FC WWPNs, NVMe host NQN, PowerFlex SDC GUID, + as its agent reports them) and, on AWS, the EC2 instance id (reported by + the node agent from the instance metadata service when its cloud probe + runs).""" out = {"hostname": hostname} + for key in SAN_INITIATOR_KEYS: + value = (san_initiators or {}).get(key) + if value: + out[key] = value if ip: out["ip"] = ip if system_id: @@ -264,10 +312,21 @@ def host_initiators(hostname="", cloud_instance=None, system_id="", ip="") -> di return out +def _agent_san_initiators(node) -> dict: + """The SAN initiators the node's agent reports now ({} when it cannot be + asked, or is older than the report).""" + try: + info, _ = node.client(timeout=15, retry=1).info() + except Exception as e: # noqa: BLE001 + logger.warning("Node %s: SAN initiators not read from its agent: %s", node.get_id(), e) + return {} + return dict((info or {}).get("san_initiators") or {}) + + def _node_initiators(node) -> dict: cloud = {"cloud": getattr(node, "cloud_name", ""), "id": getattr(node, "cloud_instance_id", "")} return host_initiators(multi_attach.array_host(node), cloud, getattr(node, "system_uuid", ""), - getattr(node, "mgmt_ip", "") or "") + getattr(node, "mgmt_ip", "") or "", _agent_san_initiators(node)) def ensure_node_host(plugin, node, db=None) -> str: @@ -324,7 +383,8 @@ def provision_node_lun(cluster, snode_api, node_info, node_config, lblk_configur try: plugin = array.plugin_for_cluster(cluster) host_id = plugin.ensure_host(hostname, host_initiators( - hostname, node_info.get("cloud_instance"), node_info.get("system_id", ""), node_ip)) + hostname, node_info.get("cloud_instance"), node_info.get("system_id", ""), node_ip, + node_info.get("san_initiators"))) existing = next((e for e in lblk_configured or [] if e.get("array_lun_id")), None) if existing: lun = {"id": existing["array_lun_id"], "wwn": existing.get("lun_wwn", "")} @@ -342,6 +402,7 @@ def provision_node_lun(cluster, snode_api, node_info, node_config, lblk_configur deadline = time.monotonic() + timeout while True: + _scan_new_luns(snode_api) inventory, err = snode_api.get_blockdevices() found = _find_in_inventory(inventory, lun["wwn"]) if found: @@ -386,12 +447,26 @@ def add_lun_to_config(lblk_configured, entry) -> list: # ------------------------------------------------------------- attachments +def _scan_new_luns(snode_api) -> None: + """Have the host look for a LUN just presented to it. A SAN host sees a + new LUN only after a SCSI / NVMe rescan (an EBS attachment shows up by + itself, so a failure, or an agent without the endpoint, is not fatal: + the caller keeps polling).""" + try: + _, err = snode_api.scan_new_luns() + if err: + logger.debug("scan_new_luns: %s", err) + except Exception as e: # noqa: BLE001 + logger.debug("scan_new_luns: %s", e) + + def _lun_path_on(node, dev, timeout): """The path of the device's LUN on ``node`` from its agent, or "".""" owner_path = (dev.node_paths or {}).get(dev.node_id, {}).get("path", "") deadline = time.monotonic() + timeout while True: try: + _scan_new_luns(node.client(timeout=15, retry=1)) entries, _ = node.client(timeout=15, retry=1).lun_info(dev.lun_wwn) except Exception as e: # noqa: BLE001 logger.warning("lun_info on %s: %s", node.get_id(), e) @@ -711,12 +786,26 @@ def delete_cluster_luns(cluster, force=False) -> None: if not array_configured(cluster): return errors = [] + # The LUNs recorded on the cluster's devices, plus whatever the plugin + # lists (SAN plugins cannot list: their recorded LUNs are deleted). + recorded = [d.array_lun_id for _, d in + _managed_devices(_db().get_storage_nodes_by_cluster_id(cluster.get_id()))] + luns: list = [] try: plugin = array.plugin_for_cluster(cluster) - luns = plugin.list_luns() except Exception as e: # noqa: BLE001 - plugin, luns = None, [] + plugin = None errors.append(f"array: {e}") + if plugin is not None: + try: + luns = list(plugin.list_luns()) + except NotImplementedError: + logger.info("Cluster %s: the array plugin cannot list LUNs; deleting the %d recorded", + cluster.get_id(), len(recorded)) + except Exception as e: # noqa: BLE001 + errors.append(f"array: {e}") + listed = {lun["id"] for lun in luns} + luns += [{"id": lun_id} for lun_id in dict.fromkeys(recorded) if lun_id not in listed] for lun in luns: try: plugin.delete_lun(lun["id"]) # type: ignore[union-attr] @@ -727,7 +816,7 @@ def delete_cluster_luns(cluster, force=False) -> None: raise ValueError(f"array LUNs of the cluster could not be deleted: {'; '.join(errors)}") if errors: logger.error("Cluster %s deleted with array LUNs left behind: %s", cluster.get_id(), errors) - if cluster.array_id and cluster.array_has_credentials: + if cluster.array_id and cluster.array_has_credentials and not cluster.array_credential_ref: from simplyblock_core import kms try: with kms.create_kms_connection(cluster) as conn: diff --git a/simplyblock_core/credentials.py b/simplyblock_core/credentials.py index b65103acf2..066fcf2a1b 100644 --- a/simplyblock_core/credentials.py +++ b/simplyblock_core/credentials.py @@ -51,7 +51,6 @@ KMIPKMSSettings, KMSException, VaultKMSSettings, - create_kms_connection, ) if TYPE_CHECKING: @@ -158,7 +157,7 @@ def __init__( *, ttl_s: float = 300.0, clock: Callable[[], float] = time.monotonic, - kms_factory: Callable[..., KMS] = create_kms_connection, + kms_factory: Callable[..., KMS] | None = None, ): self._cluster = cluster self._ttl_s = ttl_s @@ -182,8 +181,14 @@ def _open_kms(self) -> KMS: settings = self._cluster.get_kms_settings() if isinstance(settings, VaultKMSSettings): cert_role = settings.credentials_cert_role + factory = self._kms_factory + if factory is None: + # Looked up per call, not bound at import: the KMS connection is + # replaced in tests and by callers that patch the package. + from simplyblock_core import kms as kms_pkg + factory = kms_pkg.create_kms_connection try: - return self._kms_factory(self._cluster, cert_role=cert_role) + return factory(self._cluster, cert_role=cert_role) except KMSException as e: raise CredentialError(f"Cannot connect to the KMS: {e.message}") from e diff --git a/simplyblock_core/models/cluster.py b/simplyblock_core/models/cluster.py index ae0c5f40a5..e6b2573fdb 100644 --- a/simplyblock_core/models/cluster.py +++ b/simplyblock_core/models/cluster.py @@ -236,8 +236,8 @@ def is_topology_owned(self) -> bool: # simplyblock.array_plugins, see simplyblock_core.array). Empty = no # plugin: a takeover is refused (never reopen a LUN unfenced). The array # is registered through controllers/array_controller (POST - # /clusters/{id}/arrays); its credentials live in the KMS at - # cluster//array/, never here. + # /clusters/{id}/arrays). Its credentials are never kept here, only a + # reference to them (array_credential_ref). array_plugin: str = "" array_endpoint: str = "" array_options: dict = default_factory(dict) @@ -245,6 +245,13 @@ def is_topology_owned(self) -> bool: # registered) and whether credentials were stored for it in the KMS. array_id: str = "" array_has_credentials: bool = False + # Where the array's credentials are (simplyblock_core.credentials): a + # "managed" reference (wrapped by the cluster's credentials key in its + # KMS, bound to array id + endpoint), or an external "vault-kv" / + # "kmip-secret" secret. {} with array_has_credentials = an array + # registered before references existed: its secret is in the KMS at + # cluster//array/. + array_credential_ref: dict = default_factory(dict) # Size in bytes of the LUN created for each node added to the cluster # while an array is registered; 0 = node adds create no LUN (the LUNs are # presented by the operator, as in phase 2/3). diff --git a/simplyblock_core/multi_attach.py b/simplyblock_core/multi_attach.py index ac17b752d5..756ac8c65f 100644 --- a/simplyblock_core/multi_attach.py +++ b/simplyblock_core/multi_attach.py @@ -325,8 +325,9 @@ def served_by_online_node(owner, nodes_by_id) -> list: def normalize_wwn(value) -> str: + # lsblk reports a SCSI WWN as 0x, arrays as naa.; the same id. v = (value or "").strip().lower() - return v.removeprefix("0x") + return v.removeprefix("0x").removeprefix("naa.") def lun_keys(device) -> set: diff --git a/simplyblock_core/snode_client.py b/simplyblock_core/snode_client.py index d4d806dcde..be0adc6ff0 100644 --- a/simplyblock_core/snode_client.py +++ b/simplyblock_core/snode_client.py @@ -263,6 +263,11 @@ def lun_info(self, wwn): Returns ``(result, error)``.""" return self._request("POST", "lun_info", {"wwn": wwn}) + def scan_new_luns(self): + """Have the host look for LUNs newly presented by a storage array. + Returns ``(result, error)``.""" + return self._request("POST", "scan_new_luns") + def rescan_block_device(self, device_path): """Re-read the size of a grown whole-disk block device (lblk). diff --git a/simplyblock_web/api/internal/storage_node/docker.py b/simplyblock_web/api/internal/storage_node/docker.py index b39d10cdc6..98d4403b6f 100644 --- a/simplyblock_web/api/internal/storage_node/docker.py +++ b/simplyblock_web/api/internal/storage_node/docker.py @@ -697,6 +697,22 @@ def rescan_block_device(body: _RescanBlockDeviceParams): return utils.get_response(None, str(e)) +@api.post('/scan_new_luns', responses={ + 200: {'content': {'application/json': {'schema': utils.response_schema({ + 'type': 'object', + 'properties': {'scanned': {'type': 'array', 'items': {'type': 'string'}}}, + })}}}, +}) +def scan_new_luns(): + """Look for LUNs / namespaces a storage array newly presented to this + host (SCSI host scan, NVMe namespace rescan). Existing devices are not + touched.""" + try: + return utils.get_response(node_utils.scan_for_new_luns()) + except OSError as e: + return utils.get_response(None, str(e)) + + class _DeviceSmartQuery(BaseModel): device_path: str @@ -788,6 +804,9 @@ def get_info(): "network_interface": core_utils.get_nics_data(), "cloud_instance": node_info["cloud_info"], + # SAN initiators (IQN, FC WWPNs, NVMe host NQN, SDC GUID): how a storage + # array knows this host (simplyblock_core.array.san). + "san_initiators": node_utils.get_san_initiators(), "lsblk": get_node_lsblk(), "nodes_config": get_nodes_config(), diff --git a/simplyblock_web/api/internal/storage_node/kubernetes.py b/simplyblock_web/api/internal/storage_node/kubernetes.py index 7bf55d9bbd..64b1c8ae41 100644 --- a/simplyblock_web/api/internal/storage_node/kubernetes.py +++ b/simplyblock_web/api/internal/storage_node/kubernetes.py @@ -316,6 +316,9 @@ def get_info(): "host_ip": os.environ.get("HOST_IP", ""), "cloud_instance": node_info["cloud_info"], + # SAN initiators (IQN, FC WWPNs, NVMe host NQN, SDC GUID): how a storage + # array knows this host (simplyblock_core.array.san). + "san_initiators": node_utils.get_san_initiators(), "nodes_config": get_nodes_config(), }) @@ -390,6 +393,22 @@ def rescan_block_device(body: _RescanBlockDeviceParams): return utils.get_response(None, str(e)) +@api.post('/scan_new_luns', responses={ + 200: {'content': {'application/json': {'schema': utils.response_schema({ + 'type': 'object', + 'properties': {'scanned': {'type': 'array', 'items': {'type': 'string'}}}, + })}}}, +}) +def scan_new_luns(): + """Look for LUNs / namespaces a storage array newly presented to this + host (SCSI host scan, NVMe namespace rescan). Existing devices are not + touched.""" + try: + return utils.get_response(node_utils.scan_for_new_luns()) + except OSError as e: + return utils.get_response(None, str(e)) + + class _DeviceSmartQuery(BaseModel): device_path: str diff --git a/simplyblock_web/api/v2/cluster/array.py b/simplyblock_web/api/v2/cluster/array.py index 1651cf095c..ef6afd5856 100644 --- a/simplyblock_web/api/v2/cluster/array.py +++ b/simplyblock_web/api/v2/cluster/array.py @@ -1,9 +1,10 @@ """The storage array of a multi-attach cluster (array LUN mode, phase 4). simplyblock creates, presents, grows, fences and deletes the cluster's LUNs -through the array plugin registered here. Credentials go to the KMS -(cluster//array/) and are never returned; everything else is -kept on the cluster record. See simplyblock_core.controllers.array_controller. +through the array plugin registered here. Credentials are wrapped by +the cluster's KMS (or stay in an external Vault KV / KMIP secret the request +references) and are never returned; everything else is kept on the cluster +record. See simplyblock_core.controllers.array_controller. """ from typing import Annotated, Any @@ -23,8 +24,13 @@ class ArrayParams(BaseModel): plugin: Annotated[str, Field(min_length=1, description="Plugin name (entry point in simplyblock.array_plugins), e.g. aws-ebs")] endpoint: str = "" options: dict[str, Any] = Field(default_factory=dict) - # Stored in the KMS only; masked in every representation of this model. + # Wrapped by the cluster's KMS, never stored in the clear; masked in every + # representation of this model. credentials: dict[str, SecretStr] = Field(default_factory=dict) + credential_ref: Annotated[dict[str, Any], Field(description=( + "Instead of credentials: a secret kept outside simplyblock, " + '{"kind": "vault-kv", "mount": ..., "path": ..., "version": ...} or ' + '{"kind": "kmip-secret", "uid": ..., "field": ...}'))] = Field(default_factory=dict) lun_size: Annotated[util.Size, Field(description="Size of the LUN created for each added node; 0 = none")] = 0 @@ -35,6 +41,7 @@ class ArrayDTO(BaseModel): options: dict[str, Any] lun_size: int has_credentials: bool + credential_ref: dict[str, Any] = Field(default_factory=dict) capabilities: dict[str, Any] | None = None @@ -46,7 +53,8 @@ def register(cluster: Cluster, parameters: ArrayParams) -> ArrayDTO: try: view = array_controller.register_array( cluster.get_id(), parameters.plugin, parameters.endpoint, parameters.options, - parameters.credentials, parameters.lun_size) + parameters.credentials, parameters.lun_size, + credential_ref=parameters.credential_ref or None) except ValueError as e: raise HTTPException(422, str(e)) return ArrayDTO(**view) diff --git a/simplyblock_web/node_utils.py b/simplyblock_web/node_utils.py index f973eed7a8..ad0a5a93b9 100644 --- a/simplyblock_web/node_utils.py +++ b/simplyblock_web/node_utils.py @@ -453,8 +453,80 @@ def simplyblock_data_signature(device_name: str) -> bool | None: def _normalize_wwn(value: str) -> str: + # lsblk reports a SCSI WWN as 0x, arrays as naa.; the same id. v = (value or "").strip().lower() - return v.removeprefix("0x") + return v.removeprefix("0x").removeprefix("naa.") + + +def _host_file(path: str) -> str: + """Contents of a host configuration file: the host's /etc as mounted into + the Kubernetes agent (/host/etc) first, then the local one (Docker agent + on the host).""" + for candidate in (f"/host{path}", path): + text = _read_sysfs(candidate) + if text: + return text + return "" + + +def get_san_initiators() -> dict: + """The host's SAN initiator identities, for registering it on a storage + array: ``iscsi_iqn`` (/etc/iscsi/initiatorname.iscsi), ``fc_wwpns`` (FC + HBA ports from /sys/class/fc_host), ``nvme_hostnqn`` (/etc/nvme/hostnqn) + and ``sdc_guid`` (PowerFlex SDC). Missing ones are left out. Read-only.""" + out: dict = {} + for line in _host_file("/etc/iscsi/initiatorname.iscsi").splitlines(): + line = line.strip() + if line.startswith("InitiatorName=") and not line.startswith("#"): + out["iscsi_iqn"] = line.split("=", 1)[1].strip() + break + wwpns = [] + base = "/sys/class/fc_host" + if os.path.isdir(base): + for host in sorted(os.listdir(base)): + name = _read_sysfs(f"{base}/{host}/port_name").lower() + if re.fullmatch(r"0x[0-9a-f]{16}", name) and int(name, 16): + wwpns.append(name.removeprefix("0x")) + if wwpns: + out["fc_wwpns"] = wwpns + nqn = _host_file("/etc/nvme/hostnqn").strip() + if nqn: + out["nvme_hostnqn"] = nqn + guid = "" + for drv_cfg in ("/opt/emc/scaleio/sdc/bin/drv_cfg", "/host/opt/emc/scaleio/sdc/bin/drv_cfg"): + if os.path.exists(drv_cfg): + guid, _, _ = shell_utils.run_command(f"{drv_cfg} --query_guid") + break + match = re.search(r"\b([0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12})\b", + guid or "") + if match: + out["sdc_guid"] = match.group(1) + return out + + +def scan_for_new_luns() -> dict: + """Make the kernel look for LUNs / namespaces newly presented to this host + by a storage array: every SCSI host (FC HBAs and iSCSI sessions alike) is + scanned (``- - -`` = all channels, targets, LUNs) and every NVMe + controller rescans its namespaces. Existing devices are not touched. + + The host must already have its SAN paths: iSCSI sessions logged in, FC + zoning done, NVMe-oF controllers connected. Returns ``{"scanned": [...]}``.""" + import glob as _glob + scanned: list[str] = [] + for path in sorted(_glob.glob("/sys/class/scsi_host/host*/scan")): + try: + _write_sysfs(path, "- - -") + scanned.append(path) + except OSError as e: + logger.warning("SCSI host scan %s failed: %s", path, e) + for path in sorted(_glob.glob("/sys/class/nvme/nvme*/rescan_controller")): + try: + _write_sysfs(path, "1") + scanned.append(path) + except OSError as e: + logger.warning("NVMe rescan %s failed: %s", path, e) + return {"scanned": scanned} def find_lun_devices(wwn: str) -> list[dict]: diff --git a/tests/unit/storage_arrays/test_san_plugin.py b/tests/unit/storage_arrays/test_san_plugin.py new file mode 100644 index 0000000000..e88bdfe14c --- /dev/null +++ b/tests/unit/storage_arrays/test_san_plugin.py @@ -0,0 +1,154 @@ +"""The SAN array plugins (simplyblock_core.array.san): every storage_arrays +adapter driven through the multi-attach ArrayPlugin contract, against its +vendor fake.""" +from __future__ import annotations + +import pytest + +from simplyblock_core import array, multi_attach +from simplyblock_core.array import san +from simplyblock_core.storage_arrays.base import Protocol +from simplyblock_core.storage_arrays.testing import FakeTransport + +from .conftest import VENDORS, fake_module + +GIB = 1 << 30 +LUN = "simplyblock-node-a-s0" + +_KEY = { + Protocol.ISCSI: "iscsi_iqn", + Protocol.FC: "fc_wwpns", + Protocol.NVME_TCP: "nvme_hostnqn", + Protocol.NVME_RDMA: "nvme_hostnqn", + Protocol.NVME_FC: "nvme_hostnqn", + Protocol.SDC: "sdc_guid", +} + + +class Bed: + def __init__(self, vendor: str): + self.vendor = vendor + self.setup = fake_module(vendor).contract_setup() + protos = list(self.setup.initiators) + self.protocol = Protocol.ISCSI if Protocol.ISCSI in protos else protos[0] + self.creds = {n: self.setup.credential.get(n) for n in self.setup.credential.field_names} + + def plugin(self, cluster_id: str = "cluster-1", **extra) -> san.SanArrayPlugin: + options = {**self.setup.config.options, "protocol": self.protocol.value, **extra} + p = array.plugin_class(self.vendor)(endpoint=self.setup.config.endpoint, options=options, + cluster_id=cluster_id) + assert isinstance(p, san.SanArrayPlugin) + p.transport = FakeTransport(self.setup.fake) + p.session_kwargs = {"sleep": lambda s: None} + p.connect(self.setup.config.endpoint, self.creds, options) + return p + + def initiators(self, which: int) -> dict: + group = self.setup.initiators[self.protocol][which] + key = _KEY[self.protocol] + addresses = [i.address for i in group] + value = addresses if key == "fc_wwpns" else addresses[0] + return {"hostname": f"node-{which}", key: value} + + +@pytest.fixture(params=VENDORS) +def bed(request) -> Bed: + return Bed(request.param) + + +def test_registered_as_builtin_plugins(): + assert set(san.SAN_PLUGINS) == set(VENDORS) + for name, path in san.SAN_PLUGINS.items(): + assert array.BUILTIN_PLUGINS[name] == path + assert array.plugin_class(name).vendor == name + + +def test_lifecycle_multi_attach_fence_grow_delete(bed): + p = bed.plugin() + caps = p.capabilities() + assert bed.protocol.value in caps["protocols"] + host_a = p.ensure_host("node-a", bed.initiators(0)) + assert p.ensure_host("node-a", bed.initiators(0)) == host_a # idempotent + + lun = p.create_lun(LUN, 10 * GIB, {"simplyblock-host": "node-a"}) + assert lun["size"] >= 10 * GIB + assert lun["wwn"] and not lun["wwn"].startswith("naa.") + assert p.create_lun(LUN, 10 * GIB, {})["id"] == lun["id"] # retried create + + p.attach(lun["id"], host_a) + p.attach(lun["id"], host_a) # idempotent + view = p.get(lun["id"]) + assert view["hosts"] == [host_a] + assert multi_attach.normalize_wwn(view["wwn"]) == multi_attach.normalize_wwn(lun["wwn"]) + + host_b = p.ensure_host("node-b", bed.initiators(1)) + p.attach(lun["id"], host_b) + assert sorted(p.get(lun["id"])["hosts"]) == sorted([host_a, host_b]) + p.detach(lun["id"], host_b) + assert p.get(lun["id"])["hosts"] == [host_a] + + assert p.fence(lun["id"], host_a) + assert p.get(lun["id"])["hosts"] == [] + assert p.unfence(lun["id"], host_a) + assert p.get(lun["id"])["hosts"] == [host_a] + + p.resize(lun["id"], 20 * GIB) + assert p.get(lun["id"])["size"] >= 20 * GIB + + p.delete_lun(lun["id"]) + with pytest.raises(array.ArrayError): + p.get(lun["id"]) + p.delete_lun(lun["id"]) # gone: succeeds + p.detach(lun["id"], host_a) # gone: succeeds + + +def test_other_clusters_luns_are_never_touched(bed): + mine = bed.plugin("cluster-1") + theirs = bed.plugin("cluster-2") + lun = mine.create_lun(LUN, 10 * GIB, {}) + # Same requested name, other cluster: a different LUN. + assert theirs.create_lun(LUN, 10 * GIB, {})["id"] != lun["id"] + for op in (lambda: theirs.get(lun["id"]), lambda: theirs.delete_lun(lun["id"]), + lambda: theirs.resize(lun["id"], 20 * GIB), + lambda: theirs.attach(lun["id"], "h"), lambda: theirs.detach(lun["id"], "h")): + with pytest.raises(array.ForeignLunError): + op() + assert mine.get(lun["id"])["size"] >= 10 * GIB + + foreign = bed.setup.create_foreign_volume("prod-db-01", 5 * GIB) + with pytest.raises(array.ForeignLunError): + mine.delete_lun(foreign) + + +def test_connect_validation(bed): + with pytest.raises(array.ArrayError, match="protocol"): + bed.plugin(protocol="") + with pytest.raises(array.ArrayError, match="unknown protocol"): + bed.plugin(protocol="carrier-pigeon") + unsupported = [p for p in Protocol if p.value not in + bed.plugin().capabilities()["protocols"]] + if unsupported: + with pytest.raises(array.ArrayError, match="does not support"): + bed.plugin(protocol=unsupported[0].value) + + +def test_host_without_initiator_of_the_protocol(bed): + p = bed.plugin() + with pytest.raises(array.ArrayError, match="reports no"): + p.ensure_host("node-a", {"hostname": "node-a"}) + + +def test_list_luns_falls_back_to_recorded(bed): + with pytest.raises(NotImplementedError): + bed.plugin().list_luns() + + +def test_names(): + assert len(san.lun_uuid("c", "x")) == 36 + a, b = san.lun_uuid("c1", LUN), san.lun_uuid("c2", LUN) + assert a != b and a == san.lun_uuid("c1", LUN) + assert san.host_object_name("node-a.example.com", 63) == "sb-node-a-example-com" + long = san.host_object_name("x" * 80, 31) + assert len(long) == 31 and long.startswith("sb-x") + assert san.host_object_name("x" * 80, 31) == long + assert san.host_object_name("y" * 80, 31) != long diff --git a/tests/unit/test_array_lifecycle.py b/tests/unit/test_array_lifecycle.py index 08a03fa341..3f115c6a6d 100644 --- a/tests/unit/test_array_lifecycle.py +++ b/tests/unit/test_array_lifecycle.py @@ -56,8 +56,10 @@ def clear(self, k): class FakeKMS: - """A KMS holding secrets in memory (as plaintext, like the stores).""" + """A KMS holding secrets in memory (as plaintext, like the stores), and + wrapping credentials by hex-encoding them (the real envelope format).""" store: ClassVar[dict] = {} + keks: ClassVar[set] = set() def __enter__(self): return self @@ -65,6 +67,23 @@ def __enter__(self): def __exit__(self, *a): return None + def ensure_key_encryption_key(self, name): + FakeKMS.keks.add(name) + + def _wrap_bytes(self, kek_name, plaintext): + return f"fake:{kek_name}:" + plaintext.hex() + + def _unwrap_bytes(self, kek_name, wrapped): + prefix = f"fake:{kek_name}:" + if not wrapped.startswith(prefix): + raise KMSException("wrong key") + return bytes.fromhex(wrapped[len(prefix):]) + + from simplyblock_core.kms._base import KMS as _KMS + wrap_secret = _KMS.wrap_secret + unwrap_secret = _KMS.unwrap_secret + del _KMS + def put_secret(self, path, data): from simplyblock_core.kms._base import secret_plaintext FakeKMS.store[path] = secret_plaintext(data) @@ -107,6 +126,8 @@ def _cluster(plugin=PLUGIN, multi=True, lun_size=0): cl.array_plugin = plugin cl.array_lun_size = lun_size cl.status = Cluster.STATUS_ACTIVE + # No external KMS in these tests: the local one, explicitly allowed. + cl.allow_local_kms_credentials = True return cl @@ -144,12 +165,14 @@ class _Case(unittest.TestCase): def setUp(self): FakeArrayPlugin.reset() FakeKMS.store = {} + FakeKMS.keks = set() array.register_plugin(PLUGIN, FakeArrayPlugin) self.addCleanup(array.unregister_plugin, PLUGIN) for target, attr, kw in ( (array_controller, "_event", {}), (array_controller, "_sleep", {}), - ("simplyblock_core.kms.create_kms_connection", None, {"side_effect": lambda c: FakeKMS()}), + ("simplyblock_core.kms.create_kms_connection", None, + {"side_effect": lambda c, **k: FakeKMS()}), ("simplyblock_core.models.lock.DbLock", None, {"side_effect": lambda *a, **k: nullcontext()})): p = patch(target, **kw) if attr is None else patch.object(target, attr, **kw) p.start() @@ -317,7 +340,7 @@ def test_foreign_lun_is_never_touched(self): class TestRegistration(_Case): - def test_register_stores_credentials_in_kms_only(self): + def test_register_keeps_only_wrapped_credentials(self): db = self.use_db(FakeDB(_cluster(plugin=""), [])) view = array_controller.register_array( CID, PLUGIN, "https://array", {"az": "z"}, {"password": "pw"}, lun_size=GIB) @@ -326,8 +349,14 @@ def test_register_stores_credentials_in_kms_only(self): self.assertEqual((cl.array_plugin, cl.array_endpoint, cl.array_options, cl.array_lun_size), (PLUGIN, "https://array", {"az": "z"}, GIB)) self.assertTrue(cl.array_has_credentials) - self.assertEqual(FakeKMS.store[array_secret_path(CID, cl.array_id)], {"password": "pw"}) + ref = cl.array_credential_ref + self.assertEqual((ref["kind"], ref["backend"], ref["kek_name"]), + ("managed", "local", f"credentials-{CID}")) + self.assertEqual(FakeKMS.store, {}) # nothing at the old KMS path self.assertNotIn("pw", json.dumps(cl.to_dict(unwrap_secrets=True), default=str)) + self.assertEqual(view["credential_ref"], {"kind": "managed", "backend": "local"}) + # Read back through the reference, bound to array id + endpoint. + self.assertEqual(array.array_credentials(cl)["password"].get_secret_value(), "pw") self.assertNotIn("credentials", view) self.assertNotIn("pw", json.dumps(view)) self.assertEqual(view["capabilities"]["max_attachments"], 16) @@ -342,8 +371,69 @@ def test_reregister_keeps_id_and_drops_old_secret(self): array_controller.register_array(CID, PLUGIN) self.assertEqual(db.cluster.array_id, aid) self.assertFalse(db.cluster.array_has_credentials) + self.assertEqual(db.cluster.array_credential_ref, {}) self.assertEqual(FakeKMS.store, {}) + def test_reregister_removes_a_legacy_kms_secret(self): + cl = _cluster() + cl.array_id, cl.array_has_credentials = "arr-1", True + FakeKMS.store[array_secret_path(CID, "arr-1")] = {"password": "old"} + db = self.use_db(FakeDB(cl, [])) + array_controller.register_array(CID, PLUGIN, credentials={"password": "new"}) + self.assertEqual(FakeKMS.store, {}) + self.assertEqual(db.cluster.array_credential_ref["kind"], "managed") + self.assertEqual(array.array_credentials(db.cluster)["password"].get_secret_value(), "new") + + def test_local_kms_needs_the_opt_in(self): + cl = _cluster(plugin="") + cl.allow_local_kms_credentials = False + db = self.use_db(FakeDB(cl, [])) + with self.assertRaisesRegex(ValueError, "allow_local_kms_credentials"): + array_controller.register_array(CID, PLUGIN, credentials={"password": "pw"}) + self.assertEqual((db.cluster.array_plugin, db.cluster.array_credential_ref), ("", {})) + # Without credentials (an instance role) nothing is stored: allowed. + array_controller.register_array(CID, PLUGIN) + self.assertEqual(db.cluster.array_plugin, PLUGIN) + + def test_endpoint_rewrite_does_not_release_the_credentials(self): + db = self.use_db(FakeDB(_cluster(plugin=""), [])) + array_controller.register_array(CID, PLUGIN, "https://array.example", + credentials={"password": "pw"}) + db.cluster.array_endpoint = "https://attacker.example" + with self.assertRaisesRegex(array.ArrayError, "different context"): + array.array_credentials(db.cluster) + + def test_external_vault_reference(self): + from simplyblock_core.kms import HCPClient + vault = MagicMock(spec=HCPClient) + vault.__enter__.return_value = vault + vault.read_kv_secret.return_value = {"password": SecretStr("ext")} + db = self.use_db(FakeDB(_cluster(plugin=""), [])) + ref = {"kind": "vault-kv", "mount": "secret", "path": "arrays/a1"} + with patch("simplyblock_core.kms.create_kms_connection", side_effect=lambda c, **k: vault): + view = array_controller.register_array(CID, PLUGIN, credential_ref=ref) + self.assertEqual(FakeArrayPlugin.connected[-1][1]["password"].get_secret_value(), "ext") + self.assertEqual(array.array_credentials(db.cluster)["password"].get_secret_value(), "ext") + self.assertEqual(db.cluster.array_credential_ref["path"], "arrays/a1") + self.assertEqual(view["credential_ref"]["kind"], "vault-kv") + vault.read_kv_secret.assert_called_with("secret", "arrays/a1", None) + + def test_reference_refusals(self): + db = self.use_db(FakeDB(_cluster(plugin=""), [])) + with self.assertRaisesRegex(ValueError, "not both"): + array_controller.register_array(CID, PLUGIN, credentials={"p": "x"}, + credential_ref={"kind": "vault-kv", "mount": "m", "path": "p"}) + with self.assertRaisesRegex(ValueError, "external secret"): + array_controller.register_array(CID, PLUGIN, credential_ref={ + "kind": "managed", "backend": "local", "kek_name": "k", "wrapped": "w"}) + with self.assertRaisesRegex(ValueError, "not a valid reference"): + array_controller.register_array(CID, PLUGIN, credential_ref={"kind": "nope"}) + # A Vault reference on a cluster whose KMS is not Vault. + with self.assertRaisesRegex(ValueError, "could not be read"): + array_controller.register_array(CID, PLUGIN, credential_ref={ + "kind": "vault-kv", "mount": "m", "path": "p"}) + self.assertEqual(db.cluster.array_plugin, "") + def test_refusals_save_nothing(self): db = self.use_db(FakeDB(_cluster(plugin="", multi=False), [])) with self.assertRaisesRegex(ValueError, "multi-attach"): @@ -416,6 +506,37 @@ def test_provision_creates_attaches_and_waits(self): self.assertEqual(entry2["array_lun_id"], lun["id"]) self.assertEqual(len(FakeArrayPlugin.luns), 1) + def test_san_initiators_reach_the_array_and_the_host_scans(self): + cl = _cluster(lun_size=GIB) + api = self._api(appear_after=2) + api.scan_new_luns.return_value = ({"scanned": ["/sys/class/scsi_host/host0/scan"]}, None) + info = {"hostname": "worker-2", "system_id": "sys", + "san_initiators": {"iscsi_iqn": "iqn.2026-01.io.sb:w2", "fc_wwpns": ["2100"], + "unknown": "dropped"}} + _, host = array_controller.provision_node_lun(cl, api, info, {"socket": 1}, []) + inits = FakeArrayPlugin.hosts[host]["initiators"] + self.assertEqual((inits["iscsi_iqn"], inits["fc_wwpns"]), ("iqn.2026-01.io.sb:w2", ["2100"])) + self.assertNotIn("unknown", inits) + # One scan per inventory poll until the LUN showed up. + self.assertEqual(api.scan_new_luns.call_count, api.get_blockdevices.call_count) + self.assertGreaterEqual(api.scan_new_luns.call_count, 3) + + def test_agent_without_scan_endpoint_still_provisions(self): + api = self._api() + api.scan_new_luns.side_effect = RuntimeError("404") + entry, _ = array_controller.provision_node_lun( + _cluster(lun_size=GIB), api, {"hostname": "w"}, {"socket": 0}, []) + self.assertTrue(entry["array_lun_id"]) + + def test_existing_node_initiators_come_from_its_agent(self): + n = _node("a") + n.agent.info.return_value = ({"san_initiators": {"nvme_hostnqn": "nqn.h:a"}}, None) + plugin = self.plugin(_cluster()) + db = FakeDB(_cluster(), [n]) + host = array_controller.ensure_node_host(plugin, n, db) + self.assertEqual(FakeArrayPlugin.hosts[host]["initiators"]["nvme_hostnqn"], "nqn.h:a") + self.assertEqual(n.array_host_id, host) + def test_lun_that_never_appears_fails(self): cl = _cluster(lun_size=GIB) with self.assertRaisesRegex(array_controller.ArrayLifecycleError, "did not appear"): @@ -676,6 +797,7 @@ def test_release_never_detaches_a_lun_the_node_serves(self): def test_delete_cluster_deletes_only_its_luns_and_secret(self): cl = _cluster() + self.use_db(FakeDB(cl, [])) cl.array_id, cl.array_has_credentials = "arr", True FakeKMS.store[array_secret_path(CID, "arr")] = {"k": "v"} p = self.plugin(cl) @@ -686,8 +808,20 @@ def test_delete_cluster_deletes_only_its_luns_and_secret(self): self.assertEqual(sorted(FakeArrayPlugin.luns), ["lun-foreign"]) self.assertEqual(FakeKMS.store, {}) + def test_delete_cluster_uses_recorded_luns_when_listing_is_unsupported(self): + cl = _cluster() + a = _node("a") + self.use_db(FakeDB(cl, [a])) + p = self.plugin(cl) + lun = p.create_lun("a", GIB, {}) + _lun_device(a, lun["id"], lun["wwn"]) + with patch.object(FakeArrayPlugin, "list_luns", side_effect=NotImplementedError): + array_controller.delete_cluster_luns(cl) + self.assertEqual(FakeArrayPlugin.luns, {}) + def test_delete_cluster_failure(self): cl = _cluster() + self.use_db(FakeDB(cl, [])) p = self.plugin(cl) p.create_lun("a", GIB, {}) FakeArrayPlugin.fail.add("delete_lun") @@ -1008,7 +1142,7 @@ def test_set_array_reads_and_wraps_credentials(self): json.dump({"aws_access_key_id": "AK", "aws_secret_access_key": "SK"}, f) self.addCleanup(os.unlink, f.name) args = MagicMock(cluster_id=CID, plugin="aws-ebs", endpoint="", options='{"az": "z"}', - credentials_file=f.name, lun_size=GIB, json=True) + credentials_file=f.name, credential_ref=None, lun_size=GIB, json=True) with patch.object(array_controller, "register_array", return_value={"id": "arr"}) as reg: CLIWrapperBase.cluster__set_array(MagicMock(), "set-array", args) a = reg.call_args.args diff --git a/tests/unit/test_credentials.py b/tests/unit/test_credentials.py index 5761f9920e..2319232688 100644 --- a/tests/unit/test_credentials.py +++ b/tests/unit/test_credentials.py @@ -48,6 +48,10 @@ def ensure_key_encryption_key(self, name): if name not in self.keks: self.create_key_encryption_key(name) + def put_secret(self, path, data): ... + def get_secret(self, path): ... + def delete_secret(self, path): ... + def _wrap_bytes(self, kek_name, plaintext): if kek_name not in self.keks: raise KMSException("no such KEK") diff --git a/tests/unit/test_san_host_agent.py b/tests/unit/test_san_host_agent.py new file mode 100644 index 0000000000..f3371675bc --- /dev/null +++ b/tests/unit/test_san_host_agent.py @@ -0,0 +1,96 @@ +"""Node agent, SAN host side: the initiator report (how an array knows the +host) and the scan for newly presented LUNs.""" +import os +import shutil +import tempfile +import unittest +from unittest.mock import patch + +from simplyblock_web import node_utils + + +class _Root(unittest.TestCase): + def setUp(self): + self.root = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self.root) + real_read, real_isdir, real_listdir = node_utils._read_sysfs, os.path.isdir, os.listdir + + def _map(p): + return os.path.join(self.root, p.lstrip("/")) if p.startswith("/") else p + for target, fn in ((node_utils, "_read_sysfs"),): + p = patch.object(target, fn, side_effect=lambda path: real_read(_map(path))) + p.start() + self.addCleanup(p.stop) + p = patch.object(node_utils.os.path, "isdir", side_effect=lambda path: real_isdir(_map(path))) + p.start() + self.addCleanup(p.stop) + p = patch.object(node_utils.os, "listdir", side_effect=lambda path: real_listdir(_map(path))) + p.start() + self.addCleanup(p.stop) + self.map = _map + + def mk(self, rel, content=""): + path = os.path.join(self.root, rel) + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w") as fh: + fh.write(content) + + +class TestInitiators(_Root): + + def test_reports_iqn_wwpns_and_hostnqn(self): + self.mk("etc/iscsi/initiatorname.iscsi", + "## generated\n#InitiatorName=iqn.ignored\nInitiatorName=iqn.1994-05.com.redhat:abc\n") + self.mk("sys/class/fc_host/host3/port_name", "0x21000024FF4C1A2B\n") + self.mk("sys/class/fc_host/host4/port_name", "0x0000000000000000\n") # unconfigured port + self.mk("etc/nvme/hostnqn", "nqn.2014-08.org.nvmexpress:uuid:1234\n") + with patch.object(node_utils.os.path, "exists", return_value=False): + out = node_utils.get_san_initiators() + self.assertEqual(out, { + "iscsi_iqn": "iqn.1994-05.com.redhat:abc", + "fc_wwpns": ["21000024ff4c1a2b"], + "nvme_hostnqn": "nqn.2014-08.org.nvmexpress:uuid:1234", + }) + + def test_kubernetes_agent_reads_the_hosts_etc(self): + self.mk("host/etc/nvme/hostnqn", "nqn.host") + self.mk("etc/nvme/hostnqn", "nqn.container") + with patch.object(node_utils.os.path, "exists", return_value=False): + self.assertEqual(node_utils.get_san_initiators()["nvme_hostnqn"], "nqn.host") + + def test_powerflex_sdc_guid(self): + with patch.object(node_utils.os.path, "exists", + side_effect=lambda p: p == "/opt/emc/scaleio/sdc/bin/drv_cfg"), \ + patch.object(node_utils.shell_utils, "run_command", + return_value=("INFO: DRV_CFG: Query GUID: 0E9B4C8A-1234-4ABC-9DEF-00112233AABB", + "", 0)): + self.assertEqual(node_utils.get_san_initiators()["sdc_guid"], + "0E9B4C8A-1234-4ABC-9DEF-00112233AABB") + + def test_nothing_configured(self): + with patch.object(node_utils.os.path, "exists", return_value=False): + self.assertEqual(node_utils.get_san_initiators(), {}) + + +class TestScan(_Root): + + def test_scans_scsi_hosts_and_nvme_controllers(self): + written = {} + paths = ["/sys/class/scsi_host/host0/scan", "/sys/class/scsi_host/host7/scan", + "/sys/class/nvme/nvme2/rescan_controller"] + with patch("glob.glob", side_effect=lambda pat: [p for p in paths if p.startswith(pat.split("*")[0])]), \ + patch.object(node_utils, "_write_sysfs", side_effect=lambda p, v: written.__setitem__(p, v)): + out = node_utils.scan_for_new_luns() + self.assertEqual(out["scanned"], paths) + self.assertEqual(written["/sys/class/scsi_host/host7/scan"], "- - -") + self.assertEqual(written["/sys/class/nvme/nvme2/rescan_controller"], "1") + + def test_a_failing_host_does_not_stop_the_scan(self): + paths = ["/sys/class/scsi_host/host0/scan", "/sys/class/scsi_host/host1/scan"] + + def write(p, v): + if p.endswith("host0/scan"): + raise OSError("busy") + with patch("glob.glob", side_effect=lambda pat: [p for p in paths if "scsi_host" in pat]), \ + patch.object(node_utils, "_write_sysfs", side_effect=write): + self.assertEqual(node_utils.scan_for_new_luns()["scanned"], paths[1:])