From 51d8b25e66b44c299aa559d0aab905894f8974c2 Mon Sep 17 00:00:00 2001 From: Luigi Marini Date: Fri, 20 Nov 2026 13:54:20 -0600 Subject: [PATCH 1/9] Add Clowder v1 to v2 migration tool Add scripts/v1_to_v2_migration with two migration paths: one through the v1 and v2 REST APIs (users, spaces as groups, listeners, datasets, folders, files, metadata, tags, thumbnails, comment sidecars) and one that reads v1 MongoDB/GridFS and writes v2 MongoDB/MinIO directly. Both are resumable through a checkpoint file. Supporting changes found while running the migration: - Map Elasticsearch metadata as "flattened" so metadata keys with inconsistent value types no longer fail indexing. - Let admin mode list dataset folders, matching the sibling routes. - docker-compose: Mongo 6 with port 27017 exposed, and no Traefik request body limit on the backend router. - Ignore migration output and the default checkpoint file. Co-Authored-By: Claude Fable 5.2 --- .gitignore | 2 + backend/app/routers/datasets.py | 5 +- backend/app/search/config.py | 9 +- docker-compose.yml | 6 +- scripts/v1_to_v2_migration/README.md | 0 scripts/v1_to_v2_migration/__init__.py | 1 + scripts/v1_to_v2_migration/__main__.py | 7 + scripts/v1_to_v2_migration/api_clients.py | 492 +++++++++++ scripts/v1_to_v2_migration/api_migrator.py | 910 +++++++++++++++++++++ scripts/v1_to_v2_migration/checkpoint.py | 45 + scripts/v1_to_v2_migration/cli.py | 102 +++ scripts/v1_to_v2_migration/config.py | 113 +++ scripts/v1_to_v2_migration/mongo_bridge.py | 590 +++++++++++++ scripts/v1_to_v2_migration/utils.py | 125 +++ 14 files changed, 2404 insertions(+), 3 deletions(-) create mode 100644 scripts/v1_to_v2_migration/README.md create mode 100644 scripts/v1_to_v2_migration/__init__.py create mode 100644 scripts/v1_to_v2_migration/__main__.py create mode 100644 scripts/v1_to_v2_migration/api_clients.py create mode 100644 scripts/v1_to_v2_migration/api_migrator.py create mode 100644 scripts/v1_to_v2_migration/checkpoint.py create mode 100644 scripts/v1_to_v2_migration/cli.py create mode 100644 scripts/v1_to_v2_migration/config.py create mode 100644 scripts/v1_to_v2_migration/mongo_bridge.py create mode 100644 scripts/v1_to_v2_migration/utils.py diff --git a/.gitignore b/.gitignore index ce36a8619..00e8128be 100644 --- a/.gitignore +++ b/.gitignore @@ -84,3 +84,5 @@ secrets.yaml official.csv fact.png jupyterhub/.env-dev +/migration-output/ +/migration-checkpoint.json diff --git a/backend/app/routers/datasets.py b/backend/app/routers/datasets.py index ae608174b..553b9f480 100644 --- a/backend/app/routers/datasets.py +++ b/backend/app/routers/datasets.py @@ -707,6 +707,9 @@ async def get_dataset_folders( public: bool = Depends(CheckStatus("PUBLIC")), skip: int = 0, limit: int = 10, + admin=Depends(get_admin), + enable_admin: bool = False, + admin_mode: bool = Depends(get_admin_mode), allow: bool = Depends(Authorization("viewer")), ): if ( @@ -716,7 +719,7 @@ async def get_dataset_folders( ) ) ) is not None: - if authenticated or public: + if authenticated or public or (admin and admin_mode): query = [ FolderDBViewList.dataset_id == PydanticObjectId(dataset_id), ] diff --git a/backend/app/search/config.py b/backend/app/search/config.py index 99100c125..d2bf4c923 100644 --- a/backend/app/search/config.py +++ b/backend/app/search/config.py @@ -17,8 +17,15 @@ class IndexSettings: "folder_id": {"type": "text", "index": False}, "bytes": {"type": "long"}, # metadata fields + # Use "flattened" rather than "object": arbitrary user/extractor + # metadata has unpredictable value types for the same key across + # documents (e.g. one doc has a numeric "Number pixels", another has + # the string "2.53266M"). A dynamic "object" mapping infers a type + # from the first value it sees per key and then rejects conflicting + # documents with mapper_parsing_exception. "flattened" indexes every + # leaf as a keyword under a single field, so no type conflicts occur. "metadata": { - "type": "object", + "type": "flattened", }, } } diff --git a/docker-compose.yml b/docker-compose.yml index 7fcafb4ab..9ef71e277 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -78,6 +78,8 @@ services: - "traefik.http.routers.swagger.rule=PathPrefix(`/docs`)" - "traefik.http.services.backend.loadbalancer.server.port=80" - "traefik.http.routers.backend.priority=5" + - "traefik.http.middlewares.limit.buffering.maxRequestBodyBytes=0" # 0 = unlimited + - "traefik.http.routers.backend.middlewares=limit" frontend: image: "clowder/clowder2-frontend:2.0.0-beta.4" @@ -130,10 +132,12 @@ services: - rabbitmq mongo: - image: mongo:5.0 + image: mongo:6 restart: unless-stopped networks: - clowder2 + ports: + - "27017:27017" volumes: - mongo:/data/db diff --git a/scripts/v1_to_v2_migration/README.md b/scripts/v1_to_v2_migration/README.md new file mode 100644 index 000000000..e69de29bb diff --git a/scripts/v1_to_v2_migration/__init__.py b/scripts/v1_to_v2_migration/__init__.py new file mode 100644 index 000000000..e3142c7f0 --- /dev/null +++ b/scripts/v1_to_v2_migration/__init__.py @@ -0,0 +1 @@ +"""Migration helpers for moving data from Clowder v1 to Clowder v2.""" diff --git a/scripts/v1_to_v2_migration/__main__.py b/scripts/v1_to_v2_migration/__main__.py new file mode 100644 index 000000000..4af909b1d --- /dev/null +++ b/scripts/v1_to_v2_migration/__main__.py @@ -0,0 +1,7 @@ +"""Run the Clowder v1 to v2 migration CLI as a module.""" + +from .cli import main + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/v1_to_v2_migration/api_clients.py b/scripts/v1_to_v2_migration/api_clients.py new file mode 100644 index 000000000..261038358 --- /dev/null +++ b/scripts/v1_to_v2_migration/api_clients.py @@ -0,0 +1,492 @@ +"""HTTP API clients for Clowder v1 and Clowder v2.""" + +from __future__ import annotations + +import base64 +import json +from pathlib import Path +from typing import Any, Dict, Iterable, List, Optional + +import httpx + + +class ApiError(RuntimeError): + """Raised when a Clowder API response is not successful.""" + + def __init__(self, message: str, status_code: Optional[int] = None) -> None: + super().__init__(message) + self.status_code = status_code + + +class ClowderV1Client: + """Minimal v1 API wrapper for inventory and blob export.""" + + def __init__( + self, + base_url: str, + api_key: Optional[str] = None, + username: Optional[str] = None, + password: Optional[str] = None, + timeout: float = 120.0, + ): + self.base_url = base_url.rstrip("/") + headers: Dict[str, str] = {} + if api_key: + headers["X-API-Key"] = api_key + if username and password: + token = base64.b64encode(f"{username}:{password}".encode()).decode() + headers["Authorization"] = f"Basic {token}" + self.client = httpx.Client( + headers=headers, timeout=timeout, follow_redirects=True + ) + + def close(self) -> None: + self.client.close() + + def _url(self, path: str) -> str: + return f"{self.base_url}{path}" + + def _v1_params(self, **params: Any) -> Dict[str, Any]: + """Query params for v1 API calls; superAdmin bypasses permission filters.""" + return {"superAdmin": "true", **params} + + def get_json(self, path: str, **params: Any) -> Any: + # Retry once on connection-level errors — the v1 HTTPS connection can go + # idle during a long upload and be closed by the server. + for attempt in range(2): + try: + response = self.client.get( + self._url(path), params=self._v1_params(**params) + ) + break + except (httpx.ReadError, httpx.RemoteProtocolError, httpx.ConnectError): + if attempt == 0: + continue + raise + if response.status_code == 404: + return None + try: + response.raise_for_status() + except httpx.HTTPStatusError as exc: + raise ApiError(str(exc), status_code=response.status_code) from exc + return response.json() + + def list_datasets(self, limit: Optional[int] = None) -> List[Dict[str, Any]]: + """Fetch v1 datasets, paging through cursor-based pagination. + + The v1 cursor uses `when=b` + `date=` as a page + token. If the server returns 500 on a paginated request (e.g. because + it cannot parse the date format), we stop and return what we have so + far rather than crashing the entire migration. + """ + datasets: List[Dict[str, Any]] = [] + page_size = 1000 if limit is None else min(1000, max(limit, 1)) + params: Dict[str, Any] = {"limit": page_size} + while True: + try: + page = self.get_json("/api/datasets", **params) + except ApiError: + # Pagination cursor caused a server error; return what we have + break + items: List[Dict[str, Any]] = [] + if isinstance(page, list): + items = page + elif isinstance(page, dict): + items = page.get("data") or page.get("datasets") or [] + if not items: + break + datasets.extend(items) + if limit is not None and len(datasets) >= limit: + break + if len(items) < params["limit"]: + break + # v1 uses `when=b` (before) + `date=` as cursor + oldest = min( + (ds.get("created") or ds.get("date") or "" for ds in items), + default="", + ) + if not oldest: + break + params = {"limit": 1000, "when": "b", "date": oldest} + # Deduplicate by id in case cursor pages overlap + seen: Dict[str, Dict[str, Any]] = {} + for ds in datasets: + ds_id = str(ds.get("id") or ds.get("_id") or "") + if ds_id: + seen[ds_id] = ds + result = list(seen.values()) + if limit is not None: + return result[:limit] + return result + + def get_dataset(self, dataset_id: str) -> Optional[Dict[str, Any]]: + return self.get_json(f"/api/datasets/{dataset_id}") + + def list_dataset_files(self, dataset_id: str) -> List[Dict[str, Any]]: + # Use listAllFiles which is the confirmed v1 route (datasetAllFilesList) + result = self.get_json(f"/api/datasets/{dataset_id}/listAllFiles", max=-1) + if isinstance(result, list): + return result + if isinstance(result, dict): + return result.get("files") or result.get("data") or [] + return [] + + def list_dataset_folders(self, dataset_id: str) -> List[Dict[str, Any]]: + result = self.get_json(f"/api/datasets/{dataset_id}/folders") + if isinstance(result, list): + return result + if isinstance(result, dict): + return result.get("folders") or result.get("data") or [] + return [] + + def list_spaces(self) -> List[Dict[str, Any]]: + spaces: List[Dict[str, Any]] = [] + params: Dict[str, Any] = {"limit": 1000} + while True: + try: + page = self.get_json("/api/spaces", **params) + except ApiError: + break + items: List[Dict[str, Any]] = [] + if isinstance(page, list): + items = page + elif isinstance(page, dict): + items = page.get("data") or page.get("spaces") or [] + if not items: + break + spaces.extend(items) + if len(items) < params["limit"]: + break + oldest = min( + (s.get("created") or s.get("date") or "" for s in items), default="" + ) + if not oldest: + break + params = {"limit": 1000, "when": "b", "date": oldest} + seen: Dict[str, Dict[str, Any]] = {} + for s in spaces: + sid = str(s.get("id") or s.get("_id") or "") + if sid: + seen[sid] = s + return list(seen.values()) + + def list_users(self) -> List[Dict[str, Any]]: + """List all v1 users (requires admin API key; returns [] if forbidden).""" + try: + result = self.get_json("/api/users") + except ApiError: + return [] + if isinstance(result, list): + return result + if isinstance(result, dict): + return result.get("data") or result.get("users") or [] + return [] + + def list_space_users(self, space_id: str) -> List[Dict[str, Any]]: + result = self.get_json(f"/api/spaces/{space_id}/users") + if isinstance(result, list): + return result + if isinstance(result, dict): + return result.get("users") or result.get("data") or [] + return [] + + def list_space_datasets(self, space_id: str) -> List[Dict[str, Any]]: + result = self.get_json(f"/api/spaces/{space_id}/datasets", limit=0) + if isinstance(result, list): + return result + if isinstance(result, dict): + return result.get("data") or result.get("datasets") or [] + return [] + + def get_dataset_tags(self, dataset_id: str) -> List[str]: + result = self.get_json(f"/api/datasets/{dataset_id}/tags") + if isinstance(result, list): + return [str(t) for t in result] + if isinstance(result, dict): + tags = result.get("tags") or result.get("data") or [] + return [str(t) for t in tags] + return [] + + def get_file_tags(self, file_id: str) -> List[str]: + result = self.get_json(f"/api/files/{file_id}/tags") + if isinstance(result, list): + return [str(t) for t in result] + if isinstance(result, dict): + tags = result.get("tags") or result.get("data") or [] + return [str(t) for t in tags] + return [] + + def get_user_by_email(self, email: str) -> Optional[Dict[str, Any]]: + return self.get_json(f"/api/users/email/{email}") + + def get_user(self, user_id: str) -> Optional[Dict[str, Any]]: + return self.get_json(f"/api/users/{user_id}") + + def metadata_candidates( + self, resource_type: str, resource_id: str + ) -> Iterable[Any]: + endpoints = [ + f"/api/{resource_type}/{resource_id}/metadata.jsonld", + f"/api/{resource_type}/{resource_id}/usermetadatajson", + f"/api/{resource_type}/{resource_id}/technicalmetadatajson", + f"/api/{resource_type}/{resource_id}/xmlmetadatajson", + ] + for endpoint in endpoints: + payload = self.get_json(endpoint) + if payload: + yield payload + + def get_extraction_metadata(self, resource_id: str) -> Optional[Any]: + return self.get_json(f"/api/extractions/{resource_id}/metadata") + + def get_previews(self, file_id: str) -> List[Dict[str, Any]]: + result = self.get_json(f"/api/files/{file_id}/getPreviews") + if isinstance(result, list): + return result + if isinstance(result, dict): + return result.get("previews") or result.get("data") or [] + return [] + + def download_file_to(self, file_id: str, destination: Path) -> None: + with self.client.stream( + "GET", + self._url(f"/api/files/{file_id}/blob"), + params=self._v1_params(), + ) as response: + response.raise_for_status() + with destination.open("wb") as output: + for chunk in response.iter_bytes(): + output.write(chunk) + + def download_thumbnail_to(self, thumbnail_id: str, destination: Path) -> bool: + response = self.client.get( + self._url(f"/api/thumbnails/{thumbnail_id}/blob"), + params=self._v1_params(), + ) + if response.status_code == 404: + return False + response.raise_for_status() + destination.write_bytes(response.content) + return True + + +class ClowderV2Client: + """Minimal v2 API wrapper for imports.""" + + def __init__( + self, + base_url: str, + api_key: Optional[str] = None, + bearer_token: Optional[str] = None, + timeout: float = 120.0, + ): + self.base_url = base_url.rstrip("/") + self.client = httpx.Client(timeout=timeout, follow_redirects=True) + self.api_key = api_key + self.bearer_token = bearer_token + + def close(self) -> None: + self.client.close() + + def as_user(self, token: str) -> "ClowderV2Client": + return ClowderV2Client(self.base_url, bearer_token=token) + + def _headers(self) -> Dict[str, str]: + if self.api_key: + return {"X-API-KEY": self.api_key} + if self.bearer_token: + return {"Authorization": f"Bearer {self.bearer_token}"} + return {} + + def _url(self, path: str) -> str: + return f"{self.base_url}{path}" + + def _json_from_response(self, response: httpx.Response) -> Any: + content_type = (response.headers.get("content-type") or "").lower() + if not response.content: + raise ApiError( + f"Empty response from {response.url}. " + "Set CLOWDER2_BASE_URL to the backend API (e.g. http://localhost:8000/api/v2), " + "not the frontend dev server." + ) + if "json" not in content_type: + snippet = response.text[:120].replace("\n", " ") + raise ApiError( + f"Expected JSON from {response.url} but got Content-Type {content_type!r}. " + "CLOWDER2_BASE_URL must be the backend API base (…/api/v2 on port 8000 or " + f"Traefik), not the React dev server. Body starts with: {snippet!r}" + ) + try: + return response.json() + except json.JSONDecodeError as exc: + raise ApiError(f"Invalid JSON from {response.url}: {exc}") from exc + + def _request(self, method: str, path: str, **kwargs: Any) -> httpx.Response: + headers = kwargs.pop("headers", {}) + headers.update(self._headers()) + try: + response = self.client.request( + method, self._url(path), headers=headers, **kwargs + ) + except (httpx.WriteError, httpx.RemoteProtocolError, httpx.ConnectError) as exc: + raise ApiError(f"Connection error during {method} {path}: {exc}") from exc + try: + response.raise_for_status() + except httpx.HTTPStatusError as exc: + raise ApiError(str(exc), status_code=response.status_code) from exc + return response + + def login(self, email: str, password: str) -> str: + response = self._request( + "POST", "/login", json={"email": email, "password": password} + ) + return self._json_from_response(response)["token"] + + def create_user( + self, + email: str, + password: str, + first_name: str, + last_name: str, + ) -> Dict[str, Any]: + body = { + "email": email, + "password": password, + "first_name": first_name, + "last_name": last_name, + } + return self._json_from_response(self._request("POST", "/users", json=body)) + + def list_users(self, limit: int = 10_000) -> List[Dict[str, Any]]: + try: + response = self._request( + "GET", "/users", params={"skip": 0, "limit": limit} + ) + except ApiError: + return [] + payload = self._json_from_response(response) + return payload.get("data", []) if isinstance(payload, dict) else [] + + def standard_license_id(self) -> Optional[str]: + payload = self._json_from_response( + self._request("GET", "/licenses/standard_licenses/all") + ) + if isinstance(payload, list) and payload: + return payload[0].get("id") + return None + + def create_dataset( + self, dataset: Dict[str, Any], license_id: str + ) -> Dict[str, Any]: + return self._json_from_response( + self._request( + "POST", + "/datasets", + params={"license_id": license_id}, + json=dataset, + ) + ) + + def create_folder(self, dataset_id: str, folder: Dict[str, Any]) -> Dict[str, Any]: + return self._json_from_response( + self._request("POST", f"/datasets/{dataset_id}/folders", json=folder) + ) + + def upload_file( + self, + dataset_id: str, + path: Path, + filename: str, + content_type: Optional[str], + folder_id: Optional[str] = None, + ) -> Dict[str, Any]: + params = {"folder_id": folder_id} if folder_id else None + with path.open("rb") as file_obj: + files = { + "file": (filename, file_obj, content_type or "application/octet-stream") + } + return self._json_from_response( + self._request( + "POST", + f"/datasets/{dataset_id}/files", + params=params, + files=files, + ) + ) + + def add_dataset_metadata( + self, dataset_id: str, metadata: Dict[str, Any] + ) -> Dict[str, Any]: + return self._json_from_response( + self._request("POST", f"/datasets/{dataset_id}/metadata", json=metadata) + ) + + def add_file_metadata( + self, file_id: str, metadata: Dict[str, Any] + ) -> Dict[str, Any]: + return self._json_from_response( + self._request("POST", f"/files/{file_id}/metadata", json=metadata) + ) + + def create_thumbnail( + self, path: Path, content_type: str = "image/png" + ) -> Dict[str, Any]: + with path.open("rb") as file_obj: + files = {"file": (path.name, file_obj, content_type)} + return self._json_from_response( + self._request("POST", "/thumbnails", files=files) + ) + + def attach_file_thumbnail(self, file_id: str, thumbnail_id: str) -> Dict[str, Any]: + return self._json_from_response( + self._request("PATCH", f"/files/{file_id}/thumbnail/{thumbnail_id}") + ) + + def create_api_key(self, name: str) -> str: + """Create a non-expiring API key for the authenticated user. Returns the raw key. + + mins=0 is required: the endpoint's default (settings.local_auth_expiration, + 30 minutes) is shorter than a full migration run, so keys created without it + expire mid-run and every subsequent dataset for that owner fails with 401. + """ + response = self._request( + "POST", "/users/keys", params={"name": name, "mins": 0} + ) + return self._json_from_response(response) + + def list_listeners(self) -> List[Dict[str, Any]]: + payload = self._json_from_response( + self._request( + "GET", "/listeners", params={"skip": 0, "limit": 10_000, "all": True} + ) + ) + if isinstance(payload, dict): + return payload.get("data") or [] + return payload or [] + + def create_listener(self, listener: Dict[str, Any]) -> Dict[str, Any]: + return self._json_from_response( + self._request("POST", "/listeners", json=listener) + ) + + def create_group(self, name: str, description: str) -> Dict[str, Any]: + return self._json_from_response( + self._request( + "POST", "/groups", json={"name": name, "description": description} + ) + ) + + def add_group_member(self, group_id: str, username: str) -> Dict[str, Any]: + return self._json_from_response( + self._request("POST", f"/groups/{group_id}/add/{username}") + ) + + def set_dataset_group_role( + self, dataset_id: str, group_id: str, role: str + ) -> Dict[str, Any]: + return self._json_from_response( + self._request( + "POST", + f"/authorizations/datasets/{dataset_id}/group_role/{group_id}/{role}", + ) + ) diff --git a/scripts/v1_to_v2_migration/api_migrator.py b/scripts/v1_to_v2_migration/api_migrator.py new file mode 100644 index 000000000..0b686ef3d --- /dev/null +++ b/scripts/v1_to_v2_migration/api_migrator.py @@ -0,0 +1,910 @@ +"""API-first migration workflow from Clowder v1 to Clowder v2.""" + +from __future__ import annotations + +import json +import secrets +import tempfile +from pathlib import Path +from typing import Any, Dict, Iterable, List, Optional, Tuple + +from .api_clients import ApiError, ClowderV1Client, ClowderV2Client +from .checkpoint import Checkpoint +from .config import ApiConfig +from .utils import ( + extract_email, + first_present, + normalize_status, + stringify_id, +) + +_LEGACY_CONTEXT = [{"legacy": "https://clowderframework.org/legacy#"}] +_TAGS_CONTEXT = [{"tags": "http://www.w3.org/2004/02/skos/core#prefLabel"}] +_PROVENANCE_CONTEXT = [ + { + "clowder_v1_id": "https://clowderframework.org/legacy#v1_id", + "clowder_v1_spaces": "https://clowderframework.org/legacy#v1_spaces", + "clowder_v1_collections": "https://clowderframework.org/legacy#v1_collections", + } +] + +# Synthetic listeners attached to migrated metadata. Clowder v2 only renders a +# metadata entry in the "Machine Metadata" tab when agent.listener is non-null, +# and in the "User Metadata" tab only when it matches a registered metadata +# definition. Migrated v1 metadata has no v2 definition, so we mark it as +# listener-sourced to make it visible (rendered as a JSON tree). +_MIGRATION_LISTENER = { + "name": "Clowder v1 Migration", + "version": "1.0", + "description": "Metadata migrated from Clowder v1", +} +_EXTRACTION_LISTENER = { + "name": "Clowder v1 Extraction", + "version": "1.0", + "description": "Extraction metadata migrated from Clowder v1", +} +_PROVENANCE_LISTENER = { + "name": "Clowder v1 Provenance", + "version": "1.0", + "description": "Provenance recorded during Clowder v1 to v2 migration", +} +_TAGS_LISTENER = { + "name": "Clowder v1 Tags", + "version": "1.0", + "description": "Tags migrated from Clowder v1", +} + + +class ApiMigrator: + """Coordinates the REST API migration path.""" + + def __init__(self, config: ApiConfig): + self.config = config + self.checkpoint = Checkpoint(config.checkpoint_path) + self.config.output_dir.mkdir(parents=True, exist_ok=True) + self.comments_dir = self.config.output_dir / "comments" + self.comments_dir.mkdir(parents=True, exist_ok=True) + self.v1 = ClowderV1Client( + config.clowder1_url, + api_key=config.clowder1_api_key, + username=config.clowder1_username, + password=config.clowder1_password, + timeout=config.timeout_seconds, + ) + self.v2_admin = ClowderV2Client( + config.clowder2_url, + api_key=config.clowder2_api_key, + timeout=config.timeout_seconds, + ) + if ( + not config.clowder2_api_key + and config.clowder2_admin_email + and config.clowder2_admin_password + ): + self.v2_admin.bearer_token = self.v2_admin.login( + config.clowder2_admin_email, + config.clowder2_admin_password, + ) + self.owner_passwords = self._load_owner_passwords() + # Populated by sync_spaces(); maps v1_space_id -> space dict + self._space_lookup: Dict[str, Dict[str, Any]] = {} + # Populated by sync_users(); maps v1 user ObjectId -> email + self._v1_user_id_email: Dict[str, str] = {} + # Per-user v2 API keys (email → key); created once in sync_users() and + # reused for all operations within each user's datasets. + self._user_api_keys: Dict[str, str] = {} + keys_path = self.config.output_dir / "user-api-keys.json" + if keys_path.exists(): + self._user_api_keys.update(json.loads(keys_path.read_text())) + # Records every item that failed to migrate so failures are visible and + # countable instead of vanishing into a lone SKIP log line. + self.failures: List[Dict[str, Any]] = [] + # Emails for which an API-key login already failed this run. Without + # this, an owner whose real Keycloak password we don't know (e.g. a + # pre-existing account with a generated placeholder password) gets a + # fresh failed login attempt for every dataset they own — hammering + # Keycloak with bad credentials against a real account and risking a + # brute-force lockout. + self._api_key_login_failed: set = set() + + def _record_failure( + self, kind: str, v1_id: str, detail: str, exc: BaseException + ) -> None: + """Record and log a per-item migration failure without aborting the run.""" + self.failures.append( + { + "kind": kind, + "v1_id": v1_id, + "detail": detail, + "error": f"{type(exc).__name__}: {exc}", + } + ) + print(f" FAIL {kind} {v1_id} ({detail}): {type(exc).__name__}: {exc}") + + def _write_failure_report(self) -> None: + """Print an aggregate summary and write failures to a JSON file.""" + path = self.config.output_dir / "failures.json" + path.write_text(json.dumps(self.failures, indent=2)) + if self.failures: + by_kind: Dict[str, int] = {} + for f in self.failures: + by_kind[f["kind"]] = by_kind.get(f["kind"], 0) + 1 + breakdown = ", ".join(f"{k}={v}" for k, v in sorted(by_kind.items())) + print( + f"\nMigration completed with {len(self.failures)} failure(s) " + f"({breakdown}). See {path}." + ) + else: + print("\nMigration completed with no recorded failures.") + + def close(self) -> None: + self.v1.close() + self.v2_admin.close() + + def _load_owner_passwords(self) -> Dict[str, str]: + passwords: Dict[str, str] = {} + generated = self.config.output_dir / "generated-owner-passwords.json" + if generated.exists(): + passwords.update(json.loads(generated.read_text())) + if ( + self.config.owner_passwords_path + and self.config.owner_passwords_path.exists() + ): + passwords.update(json.loads(self.config.owner_passwords_path.read_text())) + return passwords + + def inventory(self, limit: int | None = None) -> List[Dict[str, Any]]: + datasets = self.v1.list_datasets(limit=limit) + manifest = { + "datasets": len(datasets), + "ids": [stringify_id(first_present(ds, ("id", "_id"))) for ds in datasets], + } + (self.config.output_dir / "inventory.json").write_text( + json.dumps(manifest, indent=2) + ) + return datasets + + def sync_users( + self, datasets: Iterable[Dict[str, Any]], full_user_list: bool = True + ) -> Dict[str, str]: + existing_v2 = { + user.get("email", "").lower() + for user in self.v2_admin.list_users() + if user.get("email") + } + + # Collect users: optionally from the full v1 user list (admin key + # required), then fill in any dataset authors not already covered. + candidates: Dict[str, Tuple[str, str]] = {} + if full_user_list: + for v1_user in self.v1.list_users(): + email = extract_email(v1_user, fallback="") + if not email or email == "migration@localhost.localdomain": + continue + candidates[email] = self._name_parts(v1_user, email) + # Build v1 user ObjectId → email map so authorId can be resolved + for id_key in ("id", "_id"): + uid = stringify_id(v1_user.get(id_key)) + if uid: + self._v1_user_id_email[uid] = email + + datasets = list(datasets) + for dataset in datasets: + author_id = stringify_id(dataset.get("authorId")) + if author_id and author_id not in self._v1_user_id_email: + v1_user = self.v1.get_user(author_id) + if isinstance(v1_user, dict): + email = extract_email(v1_user, fallback="") + if email: + self._v1_user_id_email[author_id] = email + candidates[email] = self._name_parts(v1_user, email) + author = dataset.get("author") or dataset.get("creator") or {} + email = extract_email(author, fallback="migration@localhost.localdomain") + if email not in candidates: + candidates[email] = self._name_parts(author, email) + + credentials: Dict[str, str] = dict(self.owner_passwords) + total = len(candidates) + for idx, (email, (first_name, last_name)) in enumerate( + candidates.items(), start=1 + ): + if idx % 25 == 0 or idx == total: + print(f" users: {idx}/{total}") + if email not in credentials: + credentials[email] = secrets.token_urlsafe(18) + if self.config.dry_run: + self.checkpoint.set( + "users", email, {"email": email, "existing": email in existing_v2} + ) + continue + if email not in existing_v2: + try: + user = self.v2_admin.create_user( + email, + credentials[email], + first_name, + last_name, + ) + except ApiError as exc: + # 409 means the user already exists in Keycloak — that's a + # success for our purposes, not a failed creation. Only a + # non-conflict error is a genuine failure worth flagging. + if exc.status_code == 409: + user = {"email": email, "existing": True} + else: + user = { + "email": email, + "created": False, + "error": f"{type(exc).__name__}: {exc}", + } + self.checkpoint.set("users", email, user) + else: + self.checkpoint.set("users", email, {"email": email, "existing": True}) + # NOTE: API keys are NOT created here. Only actual dataset owners + # need a key, and each key requires a Keycloak login round-trip. + # Creating keys for all users up front front-loads hundreds of + # logins before the first dataset migrates. Keys are instead created + # lazily in _owner_client() the first time a user owns a dataset. + + credentials_path = self.config.output_dir / "generated-owner-passwords.json" + credentials_path.write_text(json.dumps(credentials, indent=2, sort_keys=True)) + self.owner_passwords = credentials + return credentials + + def sync_listeners(self) -> None: + """Register the synthetic listeners used to attribute migrated metadata. + + The file metadata endpoint (POST /files/{id}/metadata) rejects a body + whose listener name/version is not already a registered EventListener + (404 "Extractor not found"). Register them once so both dataset and file + metadata land in the Machine Metadata tab. + """ + if self.config.dry_run: + return + listeners = [ + _MIGRATION_LISTENER, + _EXTRACTION_LISTENER, + _PROVENANCE_LISTENER, + _TAGS_LISTENER, + ] + existing = { + (item.get("name"), str(item.get("version"))) + for item in self.v2_admin.list_listeners() + } + for listener in listeners: + key = (listener["name"], str(listener["version"])) + if key in existing: + continue + try: + self.v2_admin.create_listener(dict(listener)) + except ApiError: + pass + + def sync_spaces(self) -> None: + """Create v2 groups for each v1 Space and add space members.""" + spaces = self.v1.list_spaces() + for space in spaces: + v1_space_id = stringify_id(first_present(space, ("id", "_id"))) + if not v1_space_id: + continue + self._space_lookup[v1_space_id] = space + + if isinstance(self.checkpoint.get("groups", v1_space_id), str): + continue + + if self.config.dry_run: + self.checkpoint.set( + "groups", v1_space_id, {"dry_run": space.get("name")} + ) + continue + + try: + group = self.v2_admin.create_group( + name=space.get("name") or f"Space {v1_space_id}", + description=space.get("description") or "", + ) + v2_group_id = group["id"] + self.checkpoint.set("groups", v1_space_id, v2_group_id) + except ApiError: + continue + + for user in self.v1.list_space_users(v1_space_id): + email = extract_email(user, fallback="") + if not email: + continue + try: + self.v2_admin.add_group_member(v2_group_id, email) + except ApiError: + pass + + def migrate(self, force: bool = False, limit: int | None = None) -> None: + datasets = self.inventory(limit=limit) + if limit is not None: + print(f"Limiting migration to {len(datasets)} dataset(s).") + self.sync_users(datasets, full_user_list=(limit is None)) + self.sync_listeners() + if limit is None: + self.sync_spaces() + license_id = self.config.license_id or self.v2_admin.standard_license_id() + if not license_id: + raise RuntimeError("No v2 license id found. Set CLOWDER2_LICENSE_ID.") + + for dataset in datasets: + v1_dataset_id = stringify_id(first_present(dataset, ("id", "_id"))) + if not v1_dataset_id: + continue + if ( + isinstance(self.checkpoint.get("datasets", v1_dataset_id), str) + and not force + ): + continue + # v1 list response includes authorId (ObjectId) but not the full author + # object. Resolve via the user map built in sync_users(). + author_id = stringify_id(dataset.get("authorId")) + owner_email = self._v1_user_id_email.get(author_id or "") or extract_email( + dataset.get("author") or dataset.get("creator") or {}, + fallback="migration@localhost.localdomain", + ) + ds_name = first_present(dataset, ("name", "title")) or v1_dataset_id + if self.config.dry_run: + owner_client = None + print(f" owner: {owner_email} dataset: {ds_name}") + else: + owner_client = self._owner_client(owner_email) + has_key = owner_email in self._user_api_keys + print( + f" owner: {owner_email} key: {'ok' if has_key else 'none (admin fallback)'} dataset: {ds_name}" + ) + try: + self._migrate_dataset( + owner_client, owner_email, dataset, v1_dataset_id, license_id + ) + except Exception as exc: + # One failing dataset must never abort the whole run. Record it + # and move on; a later resume run will retry unmapped datasets. + self._record_failure("dataset", v1_dataset_id, ds_name, exc) + finally: + if owner_client is not None: + owner_client.close() + + if limit is None: + self._grant_space_group_roles() + self._write_failure_report() + + def _login_as( + self, email: str, credentials: Dict[str, str] + ) -> Optional[ClowderV2Client]: + """Return a v2 client authenticated as *email* via bearer token, or None.""" + password = credentials.get(email) + if not password: + return None + try: + token = self.v2_admin.login(email, password) + return self.v2_admin.as_user(token) + except ApiError: + return None + + def _ensure_api_key(self, email: str) -> Optional[str]: + """Return a permanent v2 API key for *email*, creating one on demand. + + Keys are created lazily (only for users who actually own a dataset) + rather than for every v1 user up front, since each key costs a Keycloak + login. Newly created keys are persisted to user-api-keys.json. + """ + api_key = self._user_api_keys.get(email) + if api_key: + return api_key + if email in self._api_key_login_failed: + return None + bearer_client = self._login_as(email, self.owner_passwords) + if bearer_client is None: + self._api_key_login_failed.add(email) + return None + try: + key = bearer_client.create_api_key("migration") + self._user_api_keys[email] = key + except ApiError: + self._api_key_login_failed.add(email) + return None + finally: + bearer_client.close() + keys_path = self.config.output_dir / "user-api-keys.json" + keys_path.write_text(json.dumps(self._user_api_keys, indent=2, sort_keys=True)) + return self._user_api_keys[email] + + def _invalidate_owner_key(self, email: str) -> None: + """Drop a cached API key that the backend has rejected (e.g. expired). + + Keys created before the create_api_key(mins=0) fix, or issued to a user + whose Keycloak session has since died, are permanently stuck in + user-api-keys.json — without this, _ensure_api_key would keep returning + the same dead key forever. Clearing both caches lets the next + _owner_client() call log in again and mint a fresh one. + """ + self._user_api_keys.pop(email, None) + self._api_key_login_failed.discard(email) + keys_path = self.config.output_dir / "user-api-keys.json" + keys_path.write_text(json.dumps(self._user_api_keys, indent=2, sort_keys=True)) + + def _owner_client(self, email: str) -> ClowderV2Client: + """Return a long-lived client for *email*, falling back to admin.""" + api_key = self._ensure_api_key(email) + if api_key: + return ClowderV2Client( + self.config.clowder2_url, + api_key=api_key, + timeout=self.config.timeout_seconds, + ) + return ClowderV2Client( + self.config.clowder2_url, + api_key=self.config.clowder2_api_key, + timeout=self.config.timeout_seconds, + ) + + def _migrate_dataset( + self, + owner_client: Optional[ClowderV2Client], + owner_email: str, + dataset: Dict[str, Any], + v1_dataset_id: str, + license_id: str, + ) -> None: + dataset_body = { + "name": first_present(dataset, ("name", "title")) + or f"Dataset {v1_dataset_id}", + "description": dataset.get("description") or "", + "status": normalize_status(dataset), + } + if self.config.dry_run: + self.checkpoint.set("datasets", v1_dataset_id, {"dry_run": dataset_body}) + return + + # Use the owner's API key client for all operations so every resource + # (dataset, files, folders, metadata) is attributed to the correct user. + # Falls back to the admin client when no per-user key is available. + client = owner_client if owner_client else self.v2_admin + # A client this method creates itself (the refreshed replacement below) + # is this method's own responsibility to close; the caller-supplied + # owner_client/v2_admin is the caller's responsibility. + fresh_client: Optional[ClowderV2Client] = None + try: + # Dataset creation can 401 either from a transient token-refresh + # blip or because the cached owner API key has expired mid-run. + # Retry once before giving up so one bad request doesn't defer a + # dataset to a later resume run. Safe to retry here specifically: + # nothing is created until create_dataset returns, so a retry can + # never duplicate work. + try: + created = client.create_dataset(dataset_body, license_id) + except ApiError as exc: + if exc.status_code != 401: + raise + if owner_client is not None: + # A per-user key was in play and got rejected — it may be + # expired. Drop it and mint a fresh one rather than + # retrying with the same dead key, which would just fail + # again. + self._invalidate_owner_key(owner_email) + fresh_client = self._owner_client(owner_email) + client = fresh_client + created = client.create_dataset(dataset_body, license_id) + v2_dataset_id = created["id"] + self.checkpoint.set("datasets", v1_dataset_id, v2_dataset_id) + + self._migrate_provenance_metadata( + client, dataset, v1_dataset_id, v2_dataset_id + ) + self._migrate_folders(client, v1_dataset_id, v2_dataset_id) + self._migrate_files(client, v1_dataset_id, v2_dataset_id) + self._migrate_metadata( + client.add_dataset_metadata, "datasets", v1_dataset_id, v2_dataset_id + ) + self._migrate_tags_as_metadata( + client.add_dataset_metadata, "datasets", v1_dataset_id, v2_dataset_id + ) + self._export_comment_sidecar("dataset", v1_dataset_id) + finally: + if fresh_client is not None: + fresh_client.close() + + def _migrate_provenance_metadata( + self, + v2: ClowderV2Client, + dataset: Dict[str, Any], + v1_dataset_id: str, + v2_dataset_id: str, + ) -> None: + """Post a metadata entry recording the v1 origin and hierarchy names.""" + space_ids: List[str] = [ + stringify_id(s) or "" for s in (dataset.get("spaces") or []) + ] + space_names: List[str] = [ + self._space_lookup.get(sid, {}).get("name") or sid + for sid in space_ids + if sid + ] + collection_names: List[str] = [ + (c.get("name") if isinstance(c, dict) else str(c)) + for c in (dataset.get("collections") or []) + ] + content: Dict[str, Any] = {"clowder_v1_id": v1_dataset_id} + if space_names: + content["clowder_v1_spaces"] = space_names + if collection_names: + content["clowder_v1_collections"] = collection_names + try: + v2.add_dataset_metadata( + v2_dataset_id, + { + "content": content, + "@context": _PROVENANCE_CONTEXT, + "listener": _PROVENANCE_LISTENER, + }, + ) + except ApiError: + pass + + @staticmethod + def _reconstruct_folder_paths(folders: List[Dict[str, Any]]) -> Dict[str, str]: + """Map each v1 folder id to its true path, e.g. "/venv/Lib/site-packages". + + The v1 folders endpoint returns only {id, name} — no parentId — and + `name` is a concatenation of every ancestor's display name plus the + folder's own ("//"). Display names from + zip-style uploads themselves contain the full relative path, which is + why raw names look duplicated ("/venv/Lib/venv/Lib/site-packages"). + + Reconstruction: a folder's parent is the other folder whose raw name is + the longest strict "/"-boundary prefix of its own; the display name is + the remainder; and the true path is the parent's true path plus the + display name with the parent's display-name prefix stripped (when the + display name embeds it). + """ + raw_names: Dict[str, str] = {} + for folder in folders: + fid = stringify_id(first_present(folder, ("id", "_id"))) + name = str(first_present(folder, ("name", "foldername")) or "").rstrip("/") + if not fid or not name: + continue + if not name.startswith("/"): + name = "/" + name + raw_names[fid] = name + + names = sorted(set(raw_names.values()), key=len) + + def parent_of(name: str) -> Optional[str]: + best = None + for cand in names: + if cand != name and name.startswith(cand + "/"): + if best is None or len(cand) > len(best): + best = cand + return best + + display: Dict[str, str] = {} + for name in names: # shortest first, so parents resolve before children + parent = parent_of(name) + display[name] = name[len(parent) + 1 :] if parent else name.lstrip("/") + + true_path: Dict[str, str] = {} + for name in names: + parent = parent_of(name) + own = display[name] + if parent: + parent_display = display[parent] + if own.startswith(parent_display + "/"): + own = own[len(parent_display) + 1 :] + true_path[name] = true_path[parent] + "/" + own + else: + true_path[name] = "/" + own + + return {fid: true_path[name] for fid, name in raw_names.items()} + + def _migrate_folders( + self, + v2: ClowderV2Client, + v1_dataset_id: str, + v2_dataset_id: str, + ) -> None: + folders = self.v1.list_dataset_folders(v1_dataset_id) + paths = self._reconstruct_folder_paths(folders) + + # v2 folder id per true path already created in this dataset. Seed with + # checkpointed folders so a resumed run reuses them instead of + # duplicating. + v2_id_by_path: Dict[str, str] = {} + for v1_folder_id, path in paths.items(): + existing = self.checkpoint.get("folders", v1_folder_id) + if isinstance(existing, str): + v2_id_by_path.setdefault(path, existing) + + def ensure_path(path: str) -> Optional[str]: + """Create every missing segment of *path*; return the leaf's v2 id.""" + current: Optional[str] = None + walked = "" + for segment in (s for s in path.split("/") if s): + walked += "/" + segment + if walked in v2_id_by_path: + current = v2_id_by_path[walked] + continue + created = v2.create_folder( + v2_dataset_id, {"name": segment, "parent_folder": current} + ) + current = created["id"] + v2_id_by_path[walked] = current + return current + + for v1_folder_id, path in paths.items(): + if self.checkpoint.contains("folders", v1_folder_id): + continue + try: + v2_folder_id = ensure_path(path) + except ApiError as exc: + self._record_failure("folder", v1_folder_id, path, exc) + continue + if v2_folder_id: + self.checkpoint.set("folders", v1_folder_id, v2_folder_id) + + def _migrate_files( + self, + v2: ClowderV2Client, + v1_dataset_id: str, + v2_dataset_id: str, + ) -> None: + for file_doc in self.v1.list_dataset_files(v1_dataset_id): + v1_file_id = stringify_id(first_present(file_doc, ("id", "_id"))) + if not v1_file_id or self.checkpoint.contains("files", v1_file_id): + continue + filename = ( + first_present(file_doc, ("filename", "name", "originalname")) + or v1_file_id + ) + content_type = first_present(file_doc, ("contentType", "content_type")) + # v1 file docs reference their containing folder as a nested + # {"folders": {"id": ..., "name": ...}} object (not folderId). + folder_ref = file_doc.get("folders") + if isinstance(folder_ref, list): + folder_ref = folder_ref[0] if folder_ref else None + if isinstance(folder_ref, dict): + v1_folder_id = stringify_id(first_present(folder_ref, ("id", "_id"))) + else: + v1_folder_id = stringify_id( + first_present(file_doc, ("folderId", "folder_id")) + ) + v2_folder_id = ( + self.checkpoint.get("folders", v1_folder_id) if v1_folder_id else None + ) + if v2_folder_id and "/" in filename: + # Zip-style v1 uploads store the full relative path in the + # filename; inside a real folder tree only the basename is the + # file's name. + filename = filename.rsplit("/", 1)[-1] or filename + with tempfile.NamedTemporaryFile(delete=False) as tmp: + tmp_path = Path(tmp.name) + try: + self.v1.download_file_to(v1_file_id, tmp_path) + created = v2.upload_file( + v2_dataset_id, + tmp_path, + filename, + content_type, + folder_id=v2_folder_id, + ) + except Exception as exc: + tmp_path.unlink(missing_ok=True) + self._record_failure("file", v1_file_id, filename, exc) + continue + finally: + tmp_path.unlink(missing_ok=True) + v2_file_id = created["id"] + self.checkpoint.set("files", v1_file_id, v2_file_id) + self._migrate_metadata( + v2.add_file_metadata, "files", v1_file_id, v2_file_id + ) + self._migrate_tags_as_metadata( + v2.add_file_metadata, "files", v1_file_id, v2_file_id + ) + self._migrate_file_thumbnails(v2, v1_file_id, v2_file_id) + self._export_comment_sidecar("file", v1_file_id) + + def _migrate_metadata( + self, + add_metadata, + resource_type: str, + v1_resource_id: str, + v2_resource_id: str, + ) -> None: + for payload in self.v1.metadata_candidates(resource_type, v1_resource_id): + metadata = self._metadata_body(payload) + if metadata: + try: + add_metadata(v2_resource_id, metadata) + except ApiError as exc: + self._record_failure( + f"{resource_type}-metadata", v1_resource_id, "metadata", exc + ) + extraction = self.v1.get_extraction_metadata(v1_resource_id) + if extraction: + body = self._metadata_body(extraction, legacy=True) + if body: + try: + add_metadata(v2_resource_id, body) + except ApiError as exc: + self._record_failure( + f"{resource_type}-metadata", + v1_resource_id, + "extraction metadata", + exc, + ) + + def _migrate_tags_as_metadata( + self, + add_metadata, + resource_type: str, + v1_resource_id: str, + v2_resource_id: str, + ) -> None: + """Fetch v1 tags and store them as a v2 metadata entry.""" + try: + if resource_type == "datasets": + tags = self.v1.get_dataset_tags(v1_resource_id) + else: + tags = self.v1.get_file_tags(v1_resource_id) + except ApiError as exc: + self._record_failure( + f"{resource_type}-tags", v1_resource_id, "fetch tags", exc + ) + return + if not tags: + return + try: + add_metadata( + v2_resource_id, + { + "content": {"tags": tags}, + "@context": _TAGS_CONTEXT, + "listener": _TAGS_LISTENER, + }, + ) + except ApiError as exc: + self._record_failure( + f"{resource_type}-tags", v1_resource_id, "store tags", exc + ) + + @staticmethod + def _strip_jsonld_keys(item: Any) -> Any: + """Remove JSON-LD structural keys from a dict to avoid Elasticsearch type conflicts.""" + if isinstance(item, dict): + return { + k: v + for k, v in item.items() + if k not in ("@context", "@id", "@type", "@graph") + } + return item + + def _metadata_body( + self, payload: Any, legacy: bool = False + ) -> Optional[Dict[str, Any]]: + if isinstance(payload, list): + # JSON-LD array: extract top-level @context before wrapping. + # Strip @context from individual items — Elasticsearch cannot handle + # mixed string/object types for the same field path across documents. + top_context = None + cleaned_items = [] + for item in payload: + if ( + isinstance(item, dict) + and "@context" in item + and top_context is None + ): + top_context = item["@context"] + cleaned_items.append(self._strip_jsonld_keys(item)) + payload = {"items": cleaned_items} + if top_context is not None: + payload["@context"] = top_context + if not isinstance(payload, dict): + payload = {"value": payload} + # Prefer the @context from v1; fall back to a generic provenance URL + context = payload.get("@context") or payload.get("context") + content = payload.get("content") + if content is None: + # Some v1 extractors put data at top level minus bookkeeping keys + content = { + k: v + for k, v in payload.items() + if k not in ("@context", "context", "agent", "created", "@id", "_id") + } + if not content: + return None + body: Dict[str, Any] = { + "content": content, + "description": "Migrated legacy extraction metadata" + if legacy + else "Migrated legacy metadata", + # Mark as listener-sourced so v2 renders it in the Machine Metadata tab. + "listener": _EXTRACTION_LISTENER if legacy else _MIGRATION_LISTENER, + } + if context: + body["@context"] = context if isinstance(context, list) else [context] + else: + body["context_url"] = "http://clowder.ncsa.illinois.edu/metadata/v1" + return body + + def _migrate_file_thumbnails( + self, + v2: ClowderV2Client, + v1_file_id: str, + v2_file_id: str, + ) -> None: + previews = self.v1.get_previews(v1_file_id) + thumbnail_ids = [ + stringify_id( + first_present(preview, ("thumbnail_id", "thumbnailId", "id", "_id")) + ) + for preview in previews + ] + for thumbnail_id in [value for value in thumbnail_ids if value]: + with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp: + tmp_path = Path(tmp.name) + try: + if not self.v1.download_thumbnail_to(thumbnail_id, tmp_path): + continue + created = v2.create_thumbnail(tmp_path) + v2.attach_file_thumbnail(v2_file_id, created["id"]) + self.checkpoint.set("thumbnails", thumbnail_id, created["id"]) + except ApiError: + pass + finally: + tmp_path.unlink(missing_ok=True) + return # Only attach the first successfully downloaded thumbnail + + def _grant_space_group_roles(self) -> None: + """Grant each v2 group VIEWER access to datasets that were in its v1 space.""" + if self.config.dry_run: + return + spaces = self.v1.list_spaces() + for space in spaces: + v1_space_id = stringify_id(first_present(space, ("id", "_id"))) + if not v1_space_id: + continue + v2_group_id = self.checkpoint.get("groups", v1_space_id) + if not v2_group_id or not isinstance(v2_group_id, str): + continue + for ds in self.v1.list_space_datasets(v1_space_id): + v1_dataset_id = stringify_id(first_present(ds, ("id", "_id"))) + if not v1_dataset_id: + continue + v2_dataset_id = self.checkpoint.get("datasets", v1_dataset_id) + if not v2_dataset_id or not isinstance(v2_dataset_id, str): + continue + role_key = f"{v1_dataset_id}:{v1_space_id}" + if self.checkpoint.contains("group_roles", role_key): + continue + try: + self.v2_admin.set_dataset_group_role( + v2_dataset_id, v2_group_id, "viewer" + ) + self.checkpoint.set("group_roles", role_key, True) + except ApiError: + pass + + def _export_comment_sidecar(self, resource_type: str, v1_resource_id: str) -> None: + sidecar = self.comments_dir / f"{resource_type}-{v1_resource_id}.json" + if not sidecar.exists(): + sidecar.write_text( + json.dumps( + { + "resource_type": resource_type, + "v1_id": v1_resource_id, + "comments": [], + }, + indent=2, + ) + ) + + def _name_parts(self, author: Any, email: str) -> Tuple[str, str]: + if isinstance(author, dict): + first = first_present(author, ("firstName", "first_name", "givenName")) + last = first_present(author, ("lastName", "last_name", "familyName")) + if first or last: + return str(first or email.split("@", 1)[0]), str(last or "Migrated") + return email.split("@", 1)[0], "Migrated" diff --git a/scripts/v1_to_v2_migration/checkpoint.py b/scripts/v1_to_v2_migration/checkpoint.py new file mode 100644 index 000000000..4807fd155 --- /dev/null +++ b/scripts/v1_to_v2_migration/checkpoint.py @@ -0,0 +1,45 @@ +"""JSON checkpoint store for resumable migrations.""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any, Dict, Optional + + +class Checkpoint: + """Small JSON-backed store for v1-to-v2 ID maps and migration state.""" + + def __init__(self, path: Path): + self.path = path + self.data: Dict[str, Any] = { + "datasets": {}, + "folders": {}, + "files": {}, + "thumbnails": {}, + "users": {}, + "groups": {}, + "comments": {}, + } + self.load() + + def load(self) -> None: + if self.path.exists(): + self.data.update(json.loads(self.path.read_text())) + + def save(self) -> None: + self.path.parent.mkdir(parents=True, exist_ok=True) + self.path.write_text(json.dumps(self.data, indent=2, sort_keys=True)) + + def get(self, namespace: str, key: str) -> Optional[Any]: + return self.data.setdefault(namespace, {}).get(str(key)) + + def set(self, namespace: str, key: str, value: Any) -> None: + self.data.setdefault(namespace, {})[str(key)] = value + self.save() + + def contains(self, namespace: str, key: str) -> bool: + return self.get(namespace, key) is not None + + def namespace(self, namespace: str) -> Dict[str, Any]: + return self.data.setdefault(namespace, {}) diff --git a/scripts/v1_to_v2_migration/cli.py b/scripts/v1_to_v2_migration/cli.py new file mode 100644 index 000000000..1cf7c9847 --- /dev/null +++ b/scripts/v1_to_v2_migration/cli.py @@ -0,0 +1,102 @@ +"""Command line entrypoint for Clowder v1 to v2 migration tooling.""" + +from __future__ import annotations + +import argparse +import json +from typing import Sequence + +from .api_migrator import ApiMigrator +from .config import ApiConfig, MongoConfig +from .mongo_bridge import MongoBridgeMigrator + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + description="Migrate Clowder v1 data into a Clowder v2 instance." + ) + subparsers = parser.add_subparsers(dest="command", required=True) + + api = subparsers.add_parser("api", help="Run API-first migration path.") + api.add_argument( + "--force", action="store_true", help="Re-run already mapped items." + ) + api.add_argument( + "--limit", + type=int, + default=None, + help="Migrate at most this many datasets (useful for smoke tests).", + ) + + api_inventory = subparsers.add_parser( + "api-inventory", + help="Only inventory v1 datasets through the API.", + ) + api_inventory.add_argument( + "--print", + action="store_true", + help="Print inventory JSON to stdout.", + ) + + mongo = subparsers.add_parser( + "mongo-bridge", + help="Run direct MongoDB/GridFS to MongoDB/MinIO migration path.", + ) + mongo.add_argument("--force", action="store_true", help="Re-run mapped datasets.") + + mongo_inventory = subparsers.add_parser( + "mongo-inventory", + help="Only count relevant v1 MongoDB collections.", + ) + mongo_inventory.add_argument( + "--print", + action="store_true", + help="Print inventory JSON to stdout.", + ) + + return parser + + +def main(argv: Sequence[str] | None = None) -> int: + args = build_parser().parse_args(argv) + if args.command == "api": + migrator = ApiMigrator(ApiConfig.from_env()) + try: + migrator.migrate(force=args.force, limit=args.limit) + finally: + migrator.close() + return 0 + + if args.command == "api-inventory": + migrator = ApiMigrator(ApiConfig.from_env()) + try: + inventory = migrator.inventory() + finally: + migrator.close() + if args.print: + print(json.dumps(inventory, indent=2, default=str)) + return 0 + + if args.command == "mongo-bridge": + migrator = MongoBridgeMigrator(MongoConfig.from_env()) + try: + migrator.migrate(force=args.force) + finally: + migrator.close() + return 0 + + if args.command == "mongo-inventory": + migrator = MongoBridgeMigrator(MongoConfig.from_env()) + try: + inventory = migrator.dry_run_inventory() + finally: + migrator.close() + if args.print: + print(json.dumps(inventory, indent=2, default=str)) + return 0 + + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/v1_to_v2_migration/config.py b/scripts/v1_to_v2_migration/config.py new file mode 100644 index 000000000..3a30249f1 --- /dev/null +++ b/scripts/v1_to_v2_migration/config.py @@ -0,0 +1,113 @@ +"""Configuration for Clowder v1 to v2 migration commands.""" + +from __future__ import annotations + +import os +from dataclasses import dataclass +from pathlib import Path +from typing import Optional + + +def _env_bool(name: str, default: bool = False) -> bool: + value = os.getenv(name) + if value is None: + return default + return value.lower() in {"1", "true", "yes", "on"} + + +@dataclass(frozen=True) +class ApiConfig: + """HTTP API configuration for the API-first migration path.""" + + clowder1_url: str + clowder2_url: str + checkpoint_path: Path + output_dir: Path + clowder1_api_key: Optional[str] = None + clowder1_username: Optional[str] = None + clowder1_password: Optional[str] = None + clowder2_admin_email: Optional[str] = None + clowder2_admin_password: Optional[str] = None + clowder2_api_key: Optional[str] = None + owner_passwords_path: Optional[Path] = None + license_id: Optional[str] = None + dry_run: bool = False + timeout_seconds: float = 120.0 + + @classmethod + def from_env(cls) -> "ApiConfig": + clowder2_url = os.environ["CLOWDER2_BASE_URL"].rstrip("/") + if ":3000" in clowder2_url: + raise ValueError( + "CLOWDER2_BASE_URL appears to target the frontend dev server (port 3000). " + "Use the backend API instead, e.g. http://localhost:8000/api/v2" + ) + return cls( + clowder1_url=os.environ["CLOWDER1_BASE_URL"].rstrip("/"), + clowder2_url=clowder2_url, + checkpoint_path=Path( + os.getenv("MIGRATION_CHECKPOINT", "migration-checkpoint.json") + ), + output_dir=Path(os.getenv("MIGRATION_OUTPUT_DIR", "migration-output")), + clowder1_api_key=os.getenv("CLOWDER1_API_KEY"), + clowder1_username=os.getenv("CLOWDER1_USERNAME"), + clowder1_password=os.getenv("CLOWDER1_PASSWORD"), + clowder2_admin_email=os.getenv("CLOWDER2_ADMIN_EMAIL"), + clowder2_admin_password=os.getenv("CLOWDER2_ADMIN_PASSWORD"), + clowder2_api_key=os.getenv("CLOWDER2_API_KEY"), + owner_passwords_path=( + Path(os.environ["CLOWDER2_OWNER_PASSWORDS"]) + if os.getenv("CLOWDER2_OWNER_PASSWORDS") + else None + ), + license_id=os.getenv("CLOWDER2_LICENSE_ID"), + dry_run=_env_bool("MIGRATION_DRY_RUN"), + timeout_seconds=float(os.getenv("MIGRATION_TIMEOUT_SECONDS", "120")), + ) + + +@dataclass(frozen=True) +class MongoConfig: + """Direct MongoDB/GridFS/MinIO configuration for the Mongo-first path.""" + + v1_mongo_uri: str + v1_database: str + v2_mongo_uri: str + v2_database: str + minio_endpoint: str + minio_access_key: str + minio_secret_key: str + minio_bucket: str + checkpoint_path: Path + output_dir: Path + minio_secure: bool = False + dry_run: bool = False + default_owner_email: str = "migration@localhost.localdomain" + default_license_id: Optional[str] = None + elasticsearch_url: Optional[str] = None + elasticsearch_index: str = "clowder" + + @classmethod + def from_env(cls) -> "MongoConfig": + return cls( + v1_mongo_uri=os.environ["CLOWDER1_MONGODB_URL"], + v1_database=os.getenv("CLOWDER1_MONGO_DATABASE", "clowder"), + v2_mongo_uri=os.environ["CLOWDER2_MONGODB_URL"], + v2_database=os.getenv("CLOWDER2_MONGO_DATABASE", "clowder2"), + minio_endpoint=os.environ["CLOWDER2_MINIO_SERVER_URL"], + minio_access_key=os.environ["CLOWDER2_MINIO_ACCESS_KEY"], + minio_secret_key=os.environ["CLOWDER2_MINIO_SECRET_KEY"], + minio_bucket=os.getenv("CLOWDER2_MINIO_BUCKET_NAME", "clowder"), + minio_secure=_env_bool("CLOWDER2_MINIO_SECURE"), + checkpoint_path=Path( + os.getenv("MIGRATION_CHECKPOINT", "migration-checkpoint.json") + ), + output_dir=Path(os.getenv("MIGRATION_OUTPUT_DIR", "migration-output")), + dry_run=_env_bool("MIGRATION_DRY_RUN"), + default_owner_email=os.getenv( + "MIGRATION_DEFAULT_OWNER_EMAIL", "migration@localhost.localdomain" + ), + default_license_id=os.getenv("CLOWDER2_LICENSE_ID"), + elasticsearch_url=os.getenv("CLOWDER2_ELASTICSEARCH_URL"), + elasticsearch_index=os.getenv("CLOWDER2_ELASTICSEARCH_INDEX", "clowder"), + ) diff --git a/scripts/v1_to_v2_migration/mongo_bridge.py b/scripts/v1_to_v2_migration/mongo_bridge.py new file mode 100644 index 000000000..3dc96d83b --- /dev/null +++ b/scripts/v1_to_v2_migration/mongo_bridge.py @@ -0,0 +1,590 @@ +"""Direct MongoDB/GridFS to MongoDB/MinIO migration path.""" + +from __future__ import annotations + +import io +import json +import os +import secrets +from datetime import datetime +from typing import Any, Dict, Iterable, List, Optional + +import gridfs +from elasticsearch import Elasticsearch +from bson import ObjectId +from minio import Minio +from passlib.hash import bcrypt +from pymongo import MongoClient +from pymongo.database import Database + +from .checkpoint import Checkpoint +from .config import MongoConfig +from .utils import ( + extract_email, + first_present, + normalize_status, + parse_datetime, + split_content_type, + stringify_id, + user_out, +) + + +class MongoBridgeMigrator: + """Migrates v1 Mongo/GridFS data directly into v2 MongoDB and MinIO.""" + + def __init__(self, config: MongoConfig): + self.config = config + self.checkpoint = Checkpoint(config.checkpoint_path) + self.config.output_dir.mkdir(parents=True, exist_ok=True) + self.v1_client = MongoClient(config.v1_mongo_uri) + self.v2_client = MongoClient(config.v2_mongo_uri) + self.v1_db: Database = self.v1_client[config.v1_database] + self.v2_db: Database = self.v2_client[config.v2_database] + self.uploads_gridfs = gridfs.GridFS(self.v1_db, collection="uploads") + self.thumbnails_gridfs = gridfs.GridFS(self.v1_db, collection="thumbnails") + self.minio = Minio( + config.minio_endpoint, + access_key=config.minio_access_key, + secret_key=config.minio_secret_key, + secure=config.minio_secure, + ) + + def close(self) -> None: + self.v1_client.close() + self.v2_client.close() + + def dry_run_inventory(self) -> Dict[str, int]: + collections = [ + "datasets", + "folders", + "uploads", + "metadata", + "metadata.definitions", + "extractions", + "comments", + "social.users", + ] + counts = { + name: self.v1_db[name].estimated_document_count() for name in collections + } + (self.config.output_dir / "mongo-inventory.json").write_text( + json.dumps(counts, indent=2, sort_keys=True) + ) + return counts + + def migrate(self, force: bool = False) -> None: + self.dry_run_inventory() + self._ensure_minio_bucket() + self._ensure_default_license() + self._migrate_users() + for dataset in self.v1_db.datasets.find({}): + v1_dataset_id = self._v1_uuid(dataset) + if not v1_dataset_id: + continue + if self.checkpoint.contains("datasets", v1_dataset_id) and not force: + continue + self._migrate_dataset(dataset, v1_dataset_id) + self._export_comments() + self.reindex_elasticsearch() + + def _ensure_minio_bucket(self) -> None: + if self.config.dry_run: + return + if not self.minio.bucket_exists(self.config.minio_bucket): + self.minio.make_bucket(self.config.minio_bucket) + + def _ensure_default_license(self) -> Optional[str]: + if self.config.default_license_id: + return self.config.default_license_id + existing = self.v2_db.licenses.find_one({}) + if existing: + return str(existing["_id"]) + license_id = ObjectId() + if not self.config.dry_run: + now = datetime.utcnow() + self.v2_db.licenses.insert_one( + { + "_id": license_id, + "name": "Migrated legacy license", + "description": "Placeholder license for v1 migration.", + "holders": [], + "creator": self.config.default_owner_email, + "created": now, + "modified": now, + } + ) + return str(license_id) + + def _migrate_users(self) -> None: + users = self._owner_docs() + # Each inserted user gets its own random password. They are recorded in + # the same (git-ignored) file the API migrator uses, so an operator can + # hand them out or force a reset; no shared, guessable default exists. + passwords_path = self.config.output_dir / "generated-owner-passwords.json" + passwords: Dict[str, str] = {} + if passwords_path.exists(): + passwords.update(json.loads(passwords_path.read_text())) + generated = False + try: + for email, user in users.items(): + if self.checkpoint.contains("users", email): + continue + if self.config.dry_run: + self.checkpoint.set("users", email, user) + continue + existing = self.v2_db.users.find_one({"email": email}) + if existing: + self.checkpoint.set("users", email, str(existing["_id"])) + continue + password = secrets.token_urlsafe(18) + user_doc = { + **user, + "hashed_password": bcrypt.hash(password), + "keycloak_id": None, + } + inserted = self.v2_db.users.insert_one(user_doc) + passwords[email] = password + generated = True + self.checkpoint.set("users", email, str(inserted.inserted_id)) + finally: + if generated: + fd = os.open( + passwords_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600 + ) + with os.fdopen(fd, "w") as handle: + json.dump(passwords, handle, indent=2, sort_keys=True) + os.chmod(passwords_path, 0o600) + + def _owner_docs(self) -> Dict[str, Dict[str, Any]]: + owners: Dict[str, Dict[str, Any]] = {} + for dataset in self.v1_db.datasets.find({}, {"author": 1}): + author = dataset.get("author") or {} + email = extract_email(author, self.config.default_owner_email) + owners[email] = user_out( + email, + first_name=str( + first_present(author, ("firstName", "first_name")) or "" + ), + last_name=str(first_present(author, ("lastName", "last_name")) or ""), + ) + if self.config.default_owner_email not in owners: + owners[self.config.default_owner_email] = user_out( + self.config.default_owner_email + ) + return owners + + def _migrate_dataset(self, dataset: Dict[str, Any], v1_dataset_id: str) -> None: + dataset_id = ObjectId() + author = dataset.get("author") or {} + owner_email = extract_email(author, self.config.default_owner_email) + creator = self._creator(owner_email, author) + now = datetime.utcnow() + created = parse_datetime(first_present(dataset, ("created", "createdDate"))) + modified = parse_datetime( + first_present(dataset, ("modified", "updated", "modifiedDate")) + ) + license_id = self._ensure_default_license() + dataset_doc = { + "_id": dataset_id, + "name": first_present(dataset, ("name", "title")) + or f"Dataset {v1_dataset_id}", + "description": dataset.get("description"), + "creator": creator, + "created": created or now, + "modified": modified or now, + "status": normalize_status(dataset), + "user_views": 0, + "downloads": int(dataset.get("downloads") or 0), + "thumbnail_id": None, + "standard_license": True, + "license_id": license_id, + "frozen": False, + "frozen_version_num": -999, + } + if not self.config.dry_run: + self.v2_db.datasets.insert_one(dataset_doc) + self.v2_db.authorization.insert_one( + { + "_id": ObjectId(), + "dataset_id": dataset_id, + "user_ids": [owner_email], + "role": "owner", + "group_ids": [], + "creator": owner_email, + "created": now, + "modified": now, + } + ) + self.checkpoint.set("datasets", v1_dataset_id, str(dataset_id)) + self._migrate_folders(v1_dataset_id, dataset_id, creator) + self._migrate_files(v1_dataset_id, dataset_id, creator, dataset_doc["status"]) + self._migrate_metadata("datasets", v1_dataset_id, dataset_id, creator) + + def _migrate_folders( + self, + v1_dataset_id: str, + v2_dataset_id: ObjectId, + creator: Dict[str, Any], + ) -> None: + query = {"parentDatasetId": self._uuid_query_value(v1_dataset_id)} + folders = list(self.v1_db.folders.find(query)) + remaining = folders or list( + self.v1_db.folders.find({"parentDatasetId": v1_dataset_id}) + ) + while remaining: + progressed = False + for folder in list(remaining): + v1_folder_id = self._v1_uuid(folder) + if not v1_folder_id: + remaining.remove(folder) + continue + parent_v1_id = stringify_id( + first_present( + folder, ("parentFolderId", "parent_folder", "parentId") + ) + ) + if parent_v1_id and not self.checkpoint.get("folders", parent_v1_id): + continue + folder_id = ObjectId() + parent_id = ( + ObjectId(self.checkpoint.get("folders", parent_v1_id)) + if parent_v1_id + else None + ) + if not self.config.dry_run: + self.v2_db.folders.insert_one( + { + "_id": folder_id, + "name": first_present(folder, ("name", "foldername")) + or "Folder", + "dataset_id": v2_dataset_id, + "parent_folder": parent_id, + "creator": creator, + "created": parse_datetime(folder.get("created")), + "modified": parse_datetime(folder.get("modified")), + "object_type": "folder", + "origin_id": None, + } + ) + self.checkpoint.set("folders", v1_folder_id, str(folder_id)) + remaining.remove(folder) + progressed = True + if not progressed: + raise RuntimeError( + f"Could not resolve folder parents for {v1_dataset_id}" + ) + + def _migrate_files( + self, + v1_dataset_id: str, + v2_dataset_id: ObjectId, + creator: Dict[str, Any], + status: str, + ) -> None: + file_ids = [ + stringify_id(value) for value in self._dataset_file_ids(v1_dataset_id) + ] + files = self._files_for_dataset(v1_dataset_id, file_ids) + for file_doc in files: + v1_file_id = self._v1_uuid(file_doc) + if not v1_file_id or self.checkpoint.contains("files", v1_file_id): + continue + file_id = ObjectId() + filename = ( + first_present(file_doc, ("filename", "name", "originalname")) + or v1_file_id + ) + content_type = first_present(file_doc, ("contentType", "content_type")) + v2_folder = self._mapped_folder_for_file(file_doc) + version_id, byte_count = self._stream_file_to_minio(file_doc, file_id) + file_doc_v2 = { + "_id": file_id, + "name": filename, + "status": status, + "creator": creator, + "created": parse_datetime( + first_present(file_doc, ("uploadDate", "created")) + ), + "version_id": str(version_id), + "version_num": 1, + "dataset_id": v2_dataset_id, + "folder_id": v2_folder, + "views": 0, + "downloads": 0, + "bytes": byte_count, + "content_type": split_content_type(content_type), + "thumbnail_id": None, + "storage_type": "minio", + "storage_path": None, + "object_type": "file", + "origin_id": None, + } + if not self.config.dry_run: + self.v2_db.files.insert_one(file_doc_v2) + self.v2_db.file_versions.insert_one( + { + "_id": ObjectId(), + "file_id": file_id, + "creator": creator, + "created": file_doc_v2["created"], + "version_id": str(version_id), + "version_num": 1, + "bytes": byte_count, + } + ) + self.checkpoint.set("files", v1_file_id, str(file_id)) + self._migrate_metadata("files", v1_file_id, file_id, creator) + self._migrate_thumbnail(file_doc, file_id, creator) + + def _dataset_file_ids(self, v1_dataset_id: str) -> Iterable[Any]: + dataset = self.v1_db.datasets.find_one( + {"id": self._uuid_query_value(v1_dataset_id)} + ) + if not dataset: + dataset = self.v1_db.datasets.find_one({"id": v1_dataset_id}) + return dataset.get("files", []) if dataset else [] + + def _files_for_dataset( + self, + v1_dataset_id: str, + file_ids: List[Optional[str]], + ) -> List[Dict[str, Any]]: + if file_ids: + candidates = [{"id": {"$in": file_ids}}, {"_id": {"$in": file_ids}}] + for query in candidates: + docs = list(self.v1_db.uploads.find(query)) + if docs: + return docs + return list(self.v1_db.uploads.find({"datasetId": v1_dataset_id})) + + def _mapped_folder_for_file(self, file_doc: Dict[str, Any]) -> Optional[ObjectId]: + v1_folder_id = stringify_id(first_present(file_doc, ("folderId", "folder_id"))) + mapped = self.checkpoint.get("folders", v1_folder_id) if v1_folder_id else None + return ObjectId(mapped) if mapped else None + + def _stream_file_to_minio( + self, file_doc: Dict[str, Any], v2_file_id: ObjectId + ) -> tuple[str, int]: + stream = self._gridfs_stream(self.uploads_gridfs, file_doc) + data = stream.read() + byte_count = len(data) + if self.config.dry_run: + return "dry-run", byte_count + content_type = first_present(file_doc, ("contentType", "content_type")) + result = self.minio.put_object( + self.config.minio_bucket, + str(v2_file_id), + io.BytesIO(data), + length=byte_count, + content_type=content_type or "application/octet-stream", + ) + return result.version_id or "N/A", byte_count + + def _migrate_thumbnail( + self, + file_doc: Dict[str, Any], + v2_file_id: ObjectId, + creator: Dict[str, Any], + ) -> None: + v1_thumbnail_id = stringify_id( + first_present(file_doc, ("thumbnail_id", "thumbnailId")) + ) + if not v1_thumbnail_id or self.checkpoint.contains( + "thumbnails", v1_thumbnail_id + ): + return + thumbnail_id = ObjectId() + try: + stream = self._gridfs_stream( + self.thumbnails_gridfs, {"id": v1_thumbnail_id} + ) + except FileNotFoundError: + return + data = stream.read() + if not self.config.dry_run: + self.minio.put_object( + self.config.minio_bucket, + str(thumbnail_id), + io.BytesIO(data), + length=len(data), + content_type="image/png", + ) + self.v2_db.thumbnails.insert_one( + { + "_id": thumbnail_id, + "creator": creator, + "created": datetime.utcnow(), + "modified": datetime.utcnow(), + "bytes": len(data), + "content_type": split_content_type("image/png"), + "downloads": 0, + "origin_id": None, + } + ) + self.v2_db.files.update_one( + {"_id": v2_file_id}, + {"$set": {"thumbnail_id": thumbnail_id}}, + ) + self.checkpoint.set("thumbnails", v1_thumbnail_id, str(thumbnail_id)) + + def _migrate_metadata( + self, + resource_collection: str, + v1_resource_id: str, + v2_resource_id: ObjectId, + creator: Dict[str, Any], + ) -> None: + queries = [ + {"attachedTo._id": self._uuid_query_value(v1_resource_id)}, + {"resource_id": v1_resource_id}, + {"file_id": v1_resource_id}, + {"dataset_id": v1_resource_id}, + ] + for metadata_doc in self._find_any("metadata", queries): + metadata_id = ObjectId() + content = ( + first_present(metadata_doc, ("content", "json", "metadata")) + or metadata_doc + ) + if not self.config.dry_run: + self.v2_db.metadata.insert_one( + { + "_id": metadata_id, + "context": metadata_doc.get("context"), + "context_url": metadata_doc.get("context_url"), + "definition": metadata_doc.get("definition"), + "content": content, + "description": metadata_doc.get("description") + or "Migrated legacy metadata", + "resource": { + "collection": resource_collection, + "resource_id": v2_resource_id, + }, + "agent": {"creator": creator, "listener": None}, + "created": parse_datetime(metadata_doc.get("created")), + "origin_id": None, + } + ) + + def _export_comments(self) -> None: + comments_dir = self.config.output_dir / "comments" + comments_dir.mkdir(parents=True, exist_ok=True) + for comment in self.v1_db.comments.find({}): + target_id = stringify_id( + first_present( + comment, ("dataset_id", "file_id", "comment_id", "resource_id") + ) + ) + if not target_id: + target_id = stringify_id(comment.get("_id")) or "unknown" + path = comments_dir / f"{target_id}.jsonl" + with path.open("a") as output: + output.write(json.dumps(comment, default=str) + "\n") + + def reindex_elasticsearch(self) -> None: + """Best-effort search backfill for direct Mongo writes.""" + + if self.config.dry_run or not self.config.elasticsearch_url: + return + es = Elasticsearch(self.config.elasticsearch_url) + auth_by_dataset = { + auth["dataset_id"]: auth.get("user_ids", []) + for auth in self.v2_db.authorization.find({}) + } + for dataset in self.v2_db.datasets.find({"frozen": {"$ne": True}}): + metadata = self._metadata_for("datasets", dataset["_id"]) + es.index( + index=self.config.elasticsearch_index, + id=str(dataset["_id"]), + document={ + "resource_type": "dataset", + "name": dataset.get("name"), + "description": dataset.get("description"), + "creator": dataset.get("creator", {}).get("email"), + "created": dataset.get("created"), + "modified": dataset.get("modified"), + "downloads": dataset.get("downloads", 0), + "user_ids": auth_by_dataset.get(dataset["_id"], []), + "metadata": metadata, + "status": dataset.get("status"), + }, + ) + for file_doc in self.v2_db.files.find({}): + metadata = self._metadata_for("files", file_doc["_id"]) + es.index( + index=self.config.elasticsearch_index, + id=str(file_doc["_id"]), + document={ + "resource_type": "file", + "name": file_doc.get("name"), + "creator": file_doc.get("creator", {}).get("email"), + "created": file_doc.get("created"), + "downloads": file_doc.get("downloads", 0), + "user_ids": auth_by_dataset.get(file_doc.get("dataset_id"), []), + "content_type": file_doc.get("content_type", {}).get( + "content_type" + ), + "content_type_main": file_doc.get("content_type", {}).get( + "main_type" + ), + "dataset_id": str(file_doc.get("dataset_id")), + "folder_id": str(file_doc.get("folder_id")), + "bytes": file_doc.get("bytes", 0), + "metadata": metadata, + "status": file_doc.get("status"), + }, + ) + + def _metadata_for( + self, collection: str, resource_id: ObjectId + ) -> List[Dict[str, Any]]: + return [ + metadata.get("content", {}) + for metadata in self.v2_db.metadata.find( + {"resource.collection": collection, "resource.resource_id": resource_id} + ) + ] + + def _find_any( + self, collection: str, queries: Iterable[Dict[str, Any]] + ) -> List[Dict[str, Any]]: + for query in queries: + docs = list(self.v1_db[collection].find(query)) + if docs: + return docs + return [] + + def _gridfs_stream(self, bucket: gridfs.GridFS, doc: Dict[str, Any]): + candidates = [ + doc.get("_id"), + doc.get("id"), + doc.get("loader_id"), + stringify_id(doc.get("_id")), + stringify_id(doc.get("id")), + ] + for candidate in [value for value in candidates if value]: + try: + return bucket.get(candidate) + except Exception: + try: + if ObjectId.is_valid(str(candidate)): + return bucket.get(ObjectId(str(candidate))) + except Exception: + pass + raise FileNotFoundError( + f"Could not find GridFS payload for {self._v1_uuid(doc)}" + ) + + def _creator(self, email: str, author: Dict[str, Any]) -> Dict[str, Any]: + return user_out( + email, + first_name=str(first_present(author, ("firstName", "first_name")) or ""), + last_name=str(first_present(author, ("lastName", "last_name")) or ""), + ) + + def _v1_uuid(self, document: Dict[str, Any]) -> Optional[str]: + return stringify_id(first_present(document, ("id", "_id"))) + + def _uuid_query_value(self, value: str) -> Any: + return value diff --git a/scripts/v1_to_v2_migration/utils.py b/scripts/v1_to_v2_migration/utils.py new file mode 100644 index 000000000..01d058e19 --- /dev/null +++ b/scripts/v1_to_v2_migration/utils.py @@ -0,0 +1,125 @@ +"""Shared normalization helpers for Clowder migration scripts.""" + +from __future__ import annotations + +import re +from datetime import datetime, timezone +from typing import Any, Dict, Iterable, Optional + +from bson import ObjectId + + +UUID_RE = re.compile( + r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-" + r"[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$" +) + + +def first_present(document: Dict[str, Any], names: Iterable[str]) -> Any: + """Return the first non-empty value found in a document.""" + + for name in names: + value = document.get(name) + if value not in (None, "", [], {}): + return value + return None + + +def stringify_id(value: Any) -> Optional[str]: + """Convert UUID/ObjectId-ish values from either Clowder generation to strings.""" + + if value is None: + return None + if isinstance(value, ObjectId): + return str(value) + if isinstance(value, dict): + for key in ("$uuid", "$oid", "id", "_id"): + if key in value: + return stringify_id(value[key]) + return str(value) + + +def parse_datetime(value: Any) -> datetime: + """Best-effort datetime conversion for Mongo and JSON API values.""" + + if isinstance(value, datetime): + return value + if isinstance(value, dict) and "$date" in value: + return parse_datetime(value["$date"]) + if isinstance(value, (int, float)): + if value > 10_000_000_000: + value = value / 1000 + return datetime.fromtimestamp(value, tz=timezone.utc).replace(tzinfo=None) + if isinstance(value, str): + try: + return datetime.fromisoformat(value.replace("Z", "+00:00")).replace( + tzinfo=None + ) + except ValueError: + pass + return datetime.utcnow() + + +def split_content_type(content_type: Optional[str]) -> Dict[str, str]: + value = content_type or "application/octet-stream" + main_type = value.split("/", 1)[0] if "/" in value else value + return {"content_type": value, "main_type": main_type} + + +def normalize_status(document: Dict[str, Any], public_key: str = "public") -> str: + """Map v1 visibility/status flags to v2 status names.""" + + status = str(document.get("status") or "").upper() + if document.get(public_key) is True or status == "PUBLIC": + return "PUBLIC" + if status == "AUTHENTICATED": + return "AUTHENTICATED" + if status in {"DEFAULT", "TRIAL"}: + return "AUTHENTICATED" + return "PRIVATE" + + +def extract_email(value: Any, fallback: str) -> str: + """Extract an email from v1 MiniUser/user-like shapes. + + Handles several v1 MiniUser layouts: + - {"email": "user@example.com", ...} + - {"identityId": "user@example.com", ...} + - {"identityId": {"userId": "user@example.com", "providerId": "..."}, ...} + - {"id": "user@example.com", ...} + """ + if isinstance(value, str) and "@" in value: + return value.lower() + if isinstance(value, dict): + for key in ("email", "emailAddress"): + raw = value.get(key) + if isinstance(raw, str) and "@" in raw: + return raw.lower() + # identityId can be a plain email string or a nested {"userId": "..."} object + identity = value.get("identityId") + if isinstance(identity, str) and "@" in identity: + return identity.lower() + if isinstance(identity, dict): + user_id = identity.get("userId") or identity.get("id") or "" + if isinstance(user_id, str) and "@" in user_id: + return user_id.lower() + for key in ("id",): + raw = value.get(key) + if isinstance(raw, str) and "@" in raw: + return raw.lower() + return fallback.lower() + + +def user_out( + email: str, first_name: str = "", last_name: str = "", **extra: Any +) -> Dict[str, Any]: + """Build the embedded v2 UserOut-shaped dict used by migrated resources.""" + + return { + "email": email, + "first_name": first_name or email.split("@", 1)[0], + "last_name": last_name or "Migrated", + "admin": bool(extra.get("admin", False)), + "admin_mode": bool(extra.get("admin_mode", False)), + "read_only_user": bool(extra.get("read_only_user", False)), + } From c210254dca5ea770d8eb192faf543dbc9e08093c Mon Sep 17 00:00:00 2001 From: Luigi Marini Date: Fri, 20 Nov 2026 15:32:36 -0600 Subject: [PATCH 2/9] Harden v1-to-v2 migration credential handling. Write password and API-key files with mode 0600, expire and revoke migration keys, skip datasets instead of uploading as admin, and bind Mongo to localhost. Co-authored-by: Cursor --- .gitignore | 3 + docker-compose.yml | 2 +- scripts/v1_to_v2_migration/README.md | 77 +++++++++ scripts/v1_to_v2_migration/api_clients.py | 35 ++++- scripts/v1_to_v2_migration/api_migrator.py | 175 +++++++++++++++------ scripts/v1_to_v2_migration/cli.py | 25 ++- scripts/v1_to_v2_migration/mongo_bridge.py | 15 +- scripts/v1_to_v2_migration/utils.py | 42 +++++ 8 files changed, 306 insertions(+), 68 deletions(-) diff --git a/.gitignore b/.gitignore index 00e8128be..d43303826 100644 --- a/.gitignore +++ b/.gitignore @@ -86,3 +86,6 @@ fact.png jupyterhub/.env-dev /migration-output/ /migration-checkpoint.json +**/migration-checkpoint.json +**/user-api-keys.json +**/generated-owner-passwords.json diff --git a/docker-compose.yml b/docker-compose.yml index 9ef71e277..6b5d123f8 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -137,7 +137,7 @@ services: networks: - clowder2 ports: - - "27017:27017" + - "127.0.0.1:27017:27017" # host-only access for the migration tool volumes: - mongo:/data/db diff --git a/scripts/v1_to_v2_migration/README.md b/scripts/v1_to_v2_migration/README.md index e69de29bb..7cac58b00 100644 --- a/scripts/v1_to_v2_migration/README.md +++ b/scripts/v1_to_v2_migration/README.md @@ -0,0 +1,77 @@ +# Clowder v1 to v2 migration + +Move datasets, files, folders, metadata, tags, users, and spaces from a +Clowder v1 instance into Clowder v2. + +```bash +python -m scripts.v1_to_v2_migration api +python -m scripts.v1_to_v2_migration api --limit 5 +python -m scripts.v1_to_v2_migration api-inventory --print +python -m scripts.v1_to_v2_migration cleanup-keys +python -m scripts.v1_to_v2_migration mongo-bridge +``` + +Set `MIGRATION_DRY_RUN=1` to walk the source without writing to v2. + +## Environment + +API path: + +| Variable | Purpose | +|---|---| +| `CLOWDER1_BASE_URL` | v1 API base URL | +| `CLOWDER1_API_KEY` | v1 admin API key (`superAdmin` is sent on every v1 call) | +| `CLOWDER1_USERNAME` / `CLOWDER1_PASSWORD` | optional v1 Basic auth | +| `CLOWDER2_BASE_URL` | v2 backend API (`…/api/v2`, not the frontend) | +| `CLOWDER2_API_KEY` | v2 admin API key | +| `CLOWDER2_ADMIN_EMAIL` / `CLOWDER2_ADMIN_PASSWORD` | used when no v2 admin API key is set | +| `CLOWDER2_OWNER_PASSWORDS` | optional JSON map of `{email: password}` for existing v2 users | +| `CLOWDER2_LICENSE_ID` | optional; otherwise the first standard license is used | +| `MIGRATION_CHECKPOINT` | default `migration-checkpoint.json` | +| `MIGRATION_OUTPUT_DIR` | default `migration-output` | + +Mongo path additionally needs `CLOWDER1_MONGODB_URL`, `CLOWDER2_MONGODB_URL`, +MinIO settings, and optionally Elasticsearch. + +## Credential files + +The migrator writes secrets under `MIGRATION_OUTPUT_DIR`: + +- `generated-owner-passwords.json` — plaintext passwords for users created during migration +- `user-api-keys.json` — raw v2 API keys named `migration` (present only while a run is in progress) + +Those files are created with mode `0600`. Gitignore covers the default output +directory plus `**/generated-owner-passwords.json`, `**/user-api-keys.json`, +and `**/migration-checkpoint.json` so a custom output path is less likely to +be committed. + +Treat the output directory as sensitive: + +1. Restrict who can read the host (and any volume the directory lives on). +2. Do not copy credential files into tickets, CI logs, or shared drives. +3. After a successful migration, delete `generated-owner-passwords.json` once + users have rotated passwords (or Keycloak accounts have been provisioned). +4. The API path revokes `migration` keys at the end of each run. If a run + crashes, run `cleanup-keys` so leftover keys do not remain valid. + +`api-inventory --print` emits only dataset ids and a count, not full v1 +dataset objects. + +## API path behavior that affects security + +- Per-owner v2 API keys expire after 7 days and are deleted when the run + finishes. They are created only for users who own a dataset being migrated. +- A dataset is **not** migrated under the admin account if the owner's key + cannot be created. Fix that owner's password (via `CLOWDER2_OWNER_PASSWORDS` + or the generated file) and resume. +- The v1 admin API key used here can list and download all v1 data. Store it + in the environment, not in source, and rotate it after migration. + +## Mongo path passwords + +Mongo-bridge users get a unique random local password (never a shared default) +written to `generated-owner-passwords.json`. Login in Clowder v2 is Keycloak +backed, and these users are inserted with `keycloak_id` unset, so they cannot +sign in until an operator provisions them in Keycloak and rotates credentials. +Do not hand out the generated file as a long-term password store; delete it +after accounts are provisioned. diff --git a/scripts/v1_to_v2_migration/api_clients.py b/scripts/v1_to_v2_migration/api_clients.py index 261038358..50494bc49 100644 --- a/scripts/v1_to_v2_migration/api_clients.py +++ b/scripts/v1_to_v2_migration/api_clients.py @@ -442,18 +442,41 @@ def attach_file_thumbnail(self, file_id: str, thumbnail_id: str) -> Dict[str, An self._request("PATCH", f"/files/{file_id}/thumbnail/{thumbnail_id}") ) - def create_api_key(self, name: str) -> str: - """Create a non-expiring API key for the authenticated user. Returns the raw key. + def create_api_key(self, name: str, mins: int = 0) -> str: + """Create an API key for the authenticated user. Returns the raw key. - mins=0 is required: the endpoint's default (settings.local_auth_expiration, - 30 minutes) is shorter than a full migration run, so keys created without it - expire mid-run and every subsequent dataset for that owner fails with 401. + mins is minutes until expiration (0 = no expiration). The endpoint default + (settings.local_auth_expiration, 30 minutes) is shorter than a full + migration run, so callers that need the key for the whole job must pass + a longer TTL or 0. """ response = self._request( - "POST", "/users/keys", params={"name": name, "mins": 0} + "POST", "/users/keys", params={"name": name, "mins": mins} ) return self._json_from_response(response) + def list_api_keys(self) -> List[Dict[str, Any]]: + """List API keys for the authenticated user.""" + keys: List[Dict[str, Any]] = [] + skip = 0 + limit = 100 + while True: + payload = self._json_from_response( + self._request( + "GET", "/users/keys", params={"skip": skip, "limit": limit} + ) + ) + items = payload.get("data") or [] if isinstance(payload, dict) else [] + keys.extend(items) + if len(items) < limit: + break + skip += limit + return keys + + def delete_api_key(self, key_id: str) -> None: + """Delete an API key belonging to the authenticated user.""" + self._request("DELETE", f"/users/keys/{key_id}") + def list_listeners(self) -> List[Dict[str, Any]]: payload = self._json_from_response( self._request( diff --git a/scripts/v1_to_v2_migration/api_migrator.py b/scripts/v1_to_v2_migration/api_migrator.py index 0b686ef3d..0c926c74d 100644 --- a/scripts/v1_to_v2_migration/api_migrator.py +++ b/scripts/v1_to_v2_migration/api_migrator.py @@ -4,7 +4,6 @@ import json import secrets -import tempfile from pathlib import Path from typing import Any, Dict, Iterable, List, Optional, Tuple @@ -14,10 +13,20 @@ from .utils import ( extract_email, first_present, + harden_secret_file, normalize_status, + sanitize_error, + secure_temp_file, stringify_id, + write_secret_json, ) +_MIGRATION_API_KEY_NAME = "migration" +# Long enough for a full migration; leftover keys still expire if cleanup is skipped. +_MIGRATION_API_KEY_TTL_MINUTES = 7 * 24 * 60 +_OWNER_PASSWORDS_FILENAME = "generated-owner-passwords.json" +_USER_API_KEYS_FILENAME = "user-api-keys.json" + _LEGACY_CONTEXT = [{"legacy": "https://clowderframework.org/legacy#"}] _TAGS_CONTEXT = [{"tags": "http://www.w3.org/2004/02/skos/core#prefLabel"}] _PROVENANCE_CONTEXT = [ @@ -93,8 +102,9 @@ def __init__(self, config: ApiConfig): # Per-user v2 API keys (email → key); created once in sync_users() and # reused for all operations within each user's datasets. self._user_api_keys: Dict[str, str] = {} - keys_path = self.config.output_dir / "user-api-keys.json" + keys_path = self._user_api_keys_path() if keys_path.exists(): + harden_secret_file(keys_path) self._user_api_keys.update(json.loads(keys_path.read_text())) # Records every item that failed to migrate so failures are visible and # countable instead of vanishing into a lone SKIP log line. @@ -111,15 +121,16 @@ def _record_failure( self, kind: str, v1_id: str, detail: str, exc: BaseException ) -> None: """Record and log a per-item migration failure without aborting the run.""" + error = sanitize_error(exc) self.failures.append( { "kind": kind, "v1_id": v1_id, "detail": detail, - "error": f"{type(exc).__name__}: {exc}", + "error": error, } ) - print(f" FAIL {kind} {v1_id} ({detail}): {type(exc).__name__}: {exc}") + print(f" FAIL {kind} {v1_id} ({detail}): {error}") def _write_failure_report(self) -> None: """Print an aggregate summary and write failures to a JSON file.""" @@ -141,15 +152,26 @@ def close(self) -> None: self.v1.close() self.v2_admin.close() + def _owner_passwords_path(self) -> Path: + return self.config.output_dir / _OWNER_PASSWORDS_FILENAME + + def _user_api_keys_path(self) -> Path: + return self.config.output_dir / _USER_API_KEYS_FILENAME + + def _persist_user_api_keys(self) -> None: + write_secret_json(self._user_api_keys_path(), self._user_api_keys) + def _load_owner_passwords(self) -> Dict[str, str]: passwords: Dict[str, str] = {} - generated = self.config.output_dir / "generated-owner-passwords.json" + generated = self._owner_passwords_path() if generated.exists(): + harden_secret_file(generated) passwords.update(json.loads(generated.read_text())) if ( self.config.owner_passwords_path and self.config.owner_passwords_path.exists() ): + harden_secret_file(self.config.owner_passwords_path) passwords.update(json.loads(self.config.owner_passwords_path.read_text())) return passwords @@ -246,8 +268,7 @@ def sync_users( # logins before the first dataset migrates. Keys are instead created # lazily in _owner_client() the first time a user owns a dataset. - credentials_path = self.config.output_dir / "generated-owner-passwords.json" - credentials_path.write_text(json.dumps(credentials, indent=2, sort_keys=True)) + write_secret_json(self._owner_passwords_path(), credentials) self.owner_passwords = credentials return credentials @@ -346,15 +367,23 @@ def migrate(self, force: bool = False, limit: int | None = None) -> None: fallback="migration@localhost.localdomain", ) ds_name = first_present(dataset, ("name", "title")) or v1_dataset_id + owner_client: Optional[ClowderV2Client] = None if self.config.dry_run: - owner_client = None print(f" owner: {owner_email} dataset: {ds_name}") else: owner_client = self._owner_client(owner_email) - has_key = owner_email in self._user_api_keys - print( - f" owner: {owner_email} key: {'ok' if has_key else 'none (admin fallback)'} dataset: {ds_name}" - ) + if owner_client is None: + self._record_failure( + "dataset", + v1_dataset_id, + ds_name, + RuntimeError( + f"no v2 API key for owner {owner_email}; " + "dataset not migrated to avoid admin attribution" + ), + ) + continue + print(f" owner: {owner_email} key: ok dataset: {ds_name}") try: self._migrate_dataset( owner_client, owner_email, dataset, v1_dataset_id, license_id @@ -367,9 +396,12 @@ def migrate(self, force: bool = False, limit: int | None = None) -> None: if owner_client is not None: owner_client.close() - if limit is None: - self._grant_space_group_roles() - self._write_failure_report() + try: + if limit is None: + self._grant_space_group_roles() + finally: + self._write_failure_report() + self.revoke_migration_keys() def _login_as( self, email: str, credentials: Dict[str, str] @@ -385,11 +417,12 @@ def _login_as( return None def _ensure_api_key(self, email: str) -> Optional[str]: - """Return a permanent v2 API key for *email*, creating one on demand. + """Return a time-limited v2 API key for *email*, creating one on demand. Keys are created lazily (only for users who actually own a dataset) rather than for every v1 user up front, since each key costs a Keycloak - login. Newly created keys are persisted to user-api-keys.json. + login. Newly created keys are persisted to user-api-keys.json with mode + 0600 and revoked at the end of the run. """ api_key = self._user_api_keys.get(email) if api_key: @@ -401,46 +434,79 @@ def _ensure_api_key(self, email: str) -> Optional[str]: self._api_key_login_failed.add(email) return None try: - key = bearer_client.create_api_key("migration") + key = bearer_client.create_api_key( + _MIGRATION_API_KEY_NAME, mins=_MIGRATION_API_KEY_TTL_MINUTES + ) self._user_api_keys[email] = key except ApiError: self._api_key_login_failed.add(email) return None finally: bearer_client.close() - keys_path = self.config.output_dir / "user-api-keys.json" - keys_path.write_text(json.dumps(self._user_api_keys, indent=2, sort_keys=True)) + self._persist_user_api_keys() return self._user_api_keys[email] def _invalidate_owner_key(self, email: str) -> None: """Drop a cached API key that the backend has rejected (e.g. expired). - Keys created before the create_api_key(mins=0) fix, or issued to a user - whose Keycloak session has since died, are permanently stuck in - user-api-keys.json — without this, _ensure_api_key would keep returning - the same dead key forever. Clearing both caches lets the next - _owner_client() call log in again and mint a fresh one. + Expired or otherwise rejected keys stay in user-api-keys.json unless + cleared — without this, _ensure_api_key would keep returning the same + dead key forever. Clearing both caches lets the next _owner_client() + call log in again and mint a fresh one. """ self._user_api_keys.pop(email, None) self._api_key_login_failed.discard(email) - keys_path = self.config.output_dir / "user-api-keys.json" - keys_path.write_text(json.dumps(self._user_api_keys, indent=2, sort_keys=True)) + self._persist_user_api_keys() - def _owner_client(self, email: str) -> ClowderV2Client: - """Return a long-lived client for *email*, falling back to admin.""" + def _owner_client(self, email: str) -> Optional[ClowderV2Client]: + """Return a long-lived client for *email*, or None if no per-user key.""" api_key = self._ensure_api_key(email) - if api_key: - return ClowderV2Client( - self.config.clowder2_url, - api_key=api_key, - timeout=self.config.timeout_seconds, - ) + if not api_key: + return None return ClowderV2Client( self.config.clowder2_url, - api_key=self.config.clowder2_api_key, + api_key=api_key, timeout=self.config.timeout_seconds, ) + def revoke_migration_keys(self) -> None: + """Delete leftover keys named 'migration' so they do not outlive the run.""" + if self.config.dry_run: + return + remaining: Dict[str, str] = {} + revoked = 0 + for email, api_key in list(self._user_api_keys.items()): + client = ClowderV2Client( + self.config.clowder2_url, + api_key=api_key, + timeout=self.config.timeout_seconds, + ) + try: + for key in client.list_api_keys(): + if key.get("name") != _MIGRATION_API_KEY_NAME: + continue + key_id = key.get("id") + if not key_id: + continue + client.delete_api_key(str(key_id)) + revoked += 1 + except ApiError as exc: + remaining[email] = api_key + print( + f" WARN could not revoke migration API key for {email}: " + f"{sanitize_error(exc)}" + ) + finally: + client.close() + self._user_api_keys = remaining + keys_path = self._user_api_keys_path() + if remaining: + self._persist_user_api_keys() + elif keys_path.exists(): + keys_path.unlink() + if revoked: + print(f"Revoked {revoked} migration API key(s).") + def _migrate_dataset( self, owner_client: Optional[ClowderV2Client], @@ -461,11 +527,16 @@ def _migrate_dataset( # Use the owner's API key client for all operations so every resource # (dataset, files, folders, metadata) is attributed to the correct user. - # Falls back to the admin client when no per-user key is available. - client = owner_client if owner_client else self.v2_admin + # Callers must not pass admin here: missing owner keys fail the dataset. + if owner_client is None: + raise RuntimeError( + f"no v2 API key for owner {owner_email}; " + "dataset not migrated to avoid admin attribution" + ) + client = owner_client # A client this method creates itself (the refreshed replacement below) # is this method's own responsibility to close; the caller-supplied - # owner_client/v2_admin is the caller's responsibility. + # owner_client is the caller's responsibility. fresh_client: Optional[ClowderV2Client] = None try: # Dataset creation can 401 either from a transient token-refresh @@ -479,14 +550,17 @@ def _migrate_dataset( except ApiError as exc: if exc.status_code != 401: raise - if owner_client is not None: - # A per-user key was in play and got rejected — it may be - # expired. Drop it and mint a fresh one rather than - # retrying with the same dead key, which would just fail - # again. - self._invalidate_owner_key(owner_email) - fresh_client = self._owner_client(owner_email) - client = fresh_client + # A per-user key was rejected — it may be expired. Drop it + # and mint a fresh one rather than retrying with the same + # dead key, which would just fail again. + self._invalidate_owner_key(owner_email) + fresh_client = self._owner_client(owner_email) + if fresh_client is None: + raise RuntimeError( + f"no v2 API key for owner {owner_email} after 401; " + "dataset not migrated to avoid admin attribution" + ) from exc + client = fresh_client created = client.create_dataset(dataset_body, license_id) v2_dataset_id = created["id"] self.checkpoint.set("datasets", v1_dataset_id, v2_dataset_id) @@ -678,8 +752,7 @@ def _migrate_files( # filename; inside a real folder tree only the basename is the # file's name. filename = filename.rsplit("/", 1)[-1] or filename - with tempfile.NamedTemporaryFile(delete=False) as tmp: - tmp_path = Path(tmp.name) + tmp_path = secure_temp_file() try: self.v1.download_file_to(v1_file_id, tmp_path) created = v2.upload_file( @@ -690,7 +763,6 @@ def _migrate_files( folder_id=v2_folder_id, ) except Exception as exc: - tmp_path.unlink(missing_ok=True) self._record_failure("file", v1_file_id, filename, exc) continue finally: @@ -843,8 +915,7 @@ def _migrate_file_thumbnails( for preview in previews ] for thumbnail_id in [value for value in thumbnail_ids if value]: - with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp: - tmp_path = Path(tmp.name) + tmp_path = secure_temp_file(suffix=".png") try: if not self.v1.download_thumbnail_to(thumbnail_id, tmp_path): continue diff --git a/scripts/v1_to_v2_migration/cli.py b/scripts/v1_to_v2_migration/cli.py index 1cf7c9847..f3ed18d1f 100644 --- a/scripts/v1_to_v2_migration/cli.py +++ b/scripts/v1_to_v2_migration/cli.py @@ -35,7 +35,12 @@ def build_parser() -> argparse.ArgumentParser: api_inventory.add_argument( "--print", action="store_true", - help="Print inventory JSON to stdout.", + help="Print dataset count and ids to stdout (not full dataset objects).", + ) + + subparsers.add_parser( + "cleanup-keys", + help="Revoke leftover 'migration' API keys written to user-api-keys.json.", ) mongo = subparsers.add_parser( @@ -74,7 +79,23 @@ def main(argv: Sequence[str] | None = None) -> int: finally: migrator.close() if args.print: - print(json.dumps(inventory, indent=2, default=str)) + summary = { + "datasets": len(inventory), + "ids": [ + str(ds.get("id") or ds.get("_id") or "") + for ds in inventory + if ds.get("id") or ds.get("_id") + ], + } + print(json.dumps(summary, indent=2)) + return 0 + + if args.command == "cleanup-keys": + migrator = ApiMigrator(ApiConfig.from_env()) + try: + migrator.revoke_migration_keys() + finally: + migrator.close() return 0 if args.command == "mongo-bridge": diff --git a/scripts/v1_to_v2_migration/mongo_bridge.py b/scripts/v1_to_v2_migration/mongo_bridge.py index 3dc96d83b..b2e67bb3e 100644 --- a/scripts/v1_to_v2_migration/mongo_bridge.py +++ b/scripts/v1_to_v2_migration/mongo_bridge.py @@ -4,7 +4,6 @@ import io import json -import os import secrets from datetime import datetime from typing import Any, Dict, Iterable, List, Optional @@ -22,11 +21,13 @@ from .utils import ( extract_email, first_present, + harden_secret_file, normalize_status, parse_datetime, split_content_type, stringify_id, user_out, + write_secret_json, ) @@ -124,6 +125,7 @@ def _migrate_users(self) -> None: passwords_path = self.config.output_dir / "generated-owner-passwords.json" passwords: Dict[str, str] = {} if passwords_path.exists(): + harden_secret_file(passwords_path) passwords.update(json.loads(passwords_path.read_text())) generated = False try: @@ -137,6 +139,10 @@ def _migrate_users(self) -> None: if existing: self.checkpoint.set("users", email, str(existing["_id"])) continue + # Random per-user password; operators must rotate these (or + # provision Keycloak accounts) before handing access to users. + # Login is Keycloak-backed, so these hashes are a local-auth + # fallback only — never a shared default like "change-me". password = secrets.token_urlsafe(18) user_doc = { **user, @@ -149,12 +155,7 @@ def _migrate_users(self) -> None: self.checkpoint.set("users", email, str(inserted.inserted_id)) finally: if generated: - fd = os.open( - passwords_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600 - ) - with os.fdopen(fd, "w") as handle: - json.dump(passwords, handle, indent=2, sort_keys=True) - os.chmod(passwords_path, 0o600) + write_secret_json(passwords_path, passwords) def _owner_docs(self) -> Dict[str, Dict[str, Any]]: owners: Dict[str, Dict[str, Any]] = {} diff --git a/scripts/v1_to_v2_migration/utils.py b/scripts/v1_to_v2_migration/utils.py index 01d058e19..92c05a9be 100644 --- a/scripts/v1_to_v2_migration/utils.py +++ b/scripts/v1_to_v2_migration/utils.py @@ -2,12 +2,19 @@ from __future__ import annotations +import json +import os import re +import tempfile from datetime import datetime, timezone +from pathlib import Path from typing import Any, Dict, Iterable, Optional from bson import ObjectId +_SECRET_FILE_MODE = 0o600 +_ERROR_MESSAGE_MAX_LEN = 200 + UUID_RE = re.compile( r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-" @@ -15,6 +22,41 @@ ) +def harden_secret_file(path: Path) -> None: + """Best-effort chmod 0600 for an existing credential file.""" + try: + if path.exists(): + os.chmod(path, _SECRET_FILE_MODE) + except OSError: + pass + + +def write_secret_json(path: Path, payload: Any) -> None: + """Write JSON with mode 0600 so credential files are not group/world readable.""" + path.parent.mkdir(parents=True, exist_ok=True) + fd = os.open(str(path), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, _SECRET_FILE_MODE) + with os.fdopen(fd, "w") as handle: + json.dump(payload, handle, indent=2, sort_keys=True) + handle.write("\n") + harden_secret_file(path) + + +def sanitize_error(exc: BaseException, max_len: int = _ERROR_MESSAGE_MAX_LEN) -> str: + """Collapse and truncate exception text so failure logs do not store HTTP bodies.""" + text = " ".join(f"{type(exc).__name__}: {exc}".split()) + if len(text) > max_len: + return text[: max_len - 3] + "..." + return text + + +def secure_temp_file(suffix: str = "") -> Path: + """Create a 0600 temp file and return its path. Caller must unlink it.""" + fd, name = tempfile.mkstemp(suffix=suffix) + os.close(fd) + os.chmod(name, _SECRET_FILE_MODE) + return Path(name) + + def first_present(document: Dict[str, Any], names: Iterable[str]) -> Any: """Return the first non-empty value found in a document.""" From 50d609afc7afa39eadcd52eb3f84bf186cb99067 Mon Sep 17 00:00:00 2001 From: Luigi Marini Date: Fri, 20 Nov 2026 15:54:29 -0600 Subject: [PATCH 3/9] Resume partial dataset migrations instead of skipping or duplicating them. The v2 dataset id was stored as soon as the dataset was created, so a crashed run treated it as finished and --force created a second dataset. Track phase progress and mark the dataset complete only after its children succeed, reusing the existing v2 id on resume. Co-authored-by: Cursor --- scripts/v1_to_v2_migration/api_migrator.py | 170 +++++++++++++++------ scripts/v1_to_v2_migration/cli.py | 7 +- 2 files changed, 133 insertions(+), 44 deletions(-) diff --git a/scripts/v1_to_v2_migration/api_migrator.py b/scripts/v1_to_v2_migration/api_migrator.py index 0c926c74d..02e9b2f29 100644 --- a/scripts/v1_to_v2_migration/api_migrator.py +++ b/scripts/v1_to_v2_migration/api_migrator.py @@ -63,6 +63,29 @@ "description": "Tags migrated from Clowder v1", } +# A dataset is checkpointed under "datasets" only after every phase below has +# finished. The v2 id is stored earlier, under "dataset_state", so a crashed +# run can resume folders/files/metadata on the same dataset. Writing the v2 id +# into "datasets" immediately after create_dataset made resume skip the +# half-finished dataset, and --force then called create_dataset again. +_DATASET_PHASES = ( + "created", + "provenance", + "folders", + "files", + "metadata", + "tags", + "comments", + "complete", +) + + +def _phase_finished(completed: Optional[str], phase: str) -> bool: + """Return whether *phase* is already included in *completed*.""" + if completed not in _DATASET_PHASES: + return False + return _DATASET_PHASES.index(completed) >= _DATASET_PHASES.index(phase) + class ApiMigrator: """Coordinates the REST API migration path.""" @@ -354,10 +377,11 @@ def migrate(self, force: bool = False, limit: int | None = None) -> None: v1_dataset_id = stringify_id(first_present(dataset, ("id", "_id"))) if not v1_dataset_id: continue - if ( - isinstance(self.checkpoint.get("datasets", v1_dataset_id), str) - and not force - ): + _v2_id, phase = self._dataset_progress(v1_dataset_id) + # Only a fully finished dataset is skipped. An in-progress v2 id + # must be reused so resume fills in the rest instead of creating + # another dataset. --force re-enters finished datasets the same way. + if phase == "complete" and not force: continue # v1 list response includes authorId (ObjectId) but not the full author # object. Resolve via the user map built in sync_users(). @@ -390,7 +414,8 @@ def migrate(self, force: bool = False, limit: int | None = None) -> None: ) except Exception as exc: # One failing dataset must never abort the whole run. Record it - # and move on; a later resume run will retry unmapped datasets. + # and move on; a later resume retries datasets that are not + # marked complete. self._record_failure("dataset", v1_dataset_id, ds_name, exc) finally: if owner_client is not None: @@ -538,49 +563,108 @@ def _migrate_dataset( # is this method's own responsibility to close; the caller-supplied # owner_client is the caller's responsibility. fresh_client: Optional[ClowderV2Client] = None + v2_dataset_id, phase = self._dataset_progress(v1_dataset_id) try: - # Dataset creation can 401 either from a transient token-refresh - # blip or because the cached owner API key has expired mid-run. - # Retry once before giving up so one bad request doesn't defer a - # dataset to a later resume run. Safe to retry here specifically: - # nothing is created until create_dataset returns, so a retry can - # never duplicate work. - try: - created = client.create_dataset(dataset_body, license_id) - except ApiError as exc: - if exc.status_code != 401: - raise - # A per-user key was rejected — it may be expired. Drop it - # and mint a fresh one rather than retrying with the same - # dead key, which would just fail again. - self._invalidate_owner_key(owner_email) - fresh_client = self._owner_client(owner_email) - if fresh_client is None: - raise RuntimeError( - f"no v2 API key for owner {owner_email} after 401; " - "dataset not migrated to avoid admin attribution" - ) from exc - client = fresh_client - created = client.create_dataset(dataset_body, license_id) - v2_dataset_id = created["id"] - self.checkpoint.set("datasets", v1_dataset_id, v2_dataset_id) - - self._migrate_provenance_metadata( - client, dataset, v1_dataset_id, v2_dataset_id - ) - self._migrate_folders(client, v1_dataset_id, v2_dataset_id) - self._migrate_files(client, v1_dataset_id, v2_dataset_id) - self._migrate_metadata( - client.add_dataset_metadata, "datasets", v1_dataset_id, v2_dataset_id - ) - self._migrate_tags_as_metadata( - client.add_dataset_metadata, "datasets", v1_dataset_id, v2_dataset_id - ) - self._export_comment_sidecar("dataset", v1_dataset_id) + if not v2_dataset_id: + # Dataset creation can 401 either from a transient token-refresh + # blip or because the cached owner API key has expired mid-run. + # Retry once before giving up so one bad request doesn't defer a + # dataset to a later resume run. Safe to retry here specifically: + # nothing is created until create_dataset returns, so a retry can + # never duplicate work. A later resume reuses the stored id. + try: + created = client.create_dataset(dataset_body, license_id) + except ApiError as exc: + if exc.status_code != 401: + raise + # A per-user key was rejected — it may be expired. Drop it + # and mint a fresh one rather than retrying with the same + # dead key, which would just fail again. + self._invalidate_owner_key(owner_email) + fresh_client = self._owner_client(owner_email) + if fresh_client is None: + raise RuntimeError( + f"no v2 API key for owner {owner_email} after 401; " + "dataset not migrated to avoid admin attribution" + ) from exc + client = fresh_client + created = client.create_dataset(dataset_body, license_id) + v2_dataset_id = created["id"] + phase = None + if not _phase_finished(phase, "created"): + self._mark_dataset_phase(v1_dataset_id, v2_dataset_id, "created") + phase = "created" + if not _phase_finished(phase, "provenance"): + self._migrate_provenance_metadata( + client, dataset, v1_dataset_id, v2_dataset_id + ) + self._mark_dataset_phase(v1_dataset_id, v2_dataset_id, "provenance") + phase = "provenance" + if not _phase_finished(phase, "folders"): + self._migrate_folders(client, v1_dataset_id, v2_dataset_id) + self._mark_dataset_phase(v1_dataset_id, v2_dataset_id, "folders") + phase = "folders" + if not _phase_finished(phase, "files"): + self._migrate_files(client, v1_dataset_id, v2_dataset_id) + self._mark_dataset_phase(v1_dataset_id, v2_dataset_id, "files") + phase = "files" + if not _phase_finished(phase, "metadata"): + self._migrate_metadata( + client.add_dataset_metadata, + "datasets", + v1_dataset_id, + v2_dataset_id, + ) + self._mark_dataset_phase(v1_dataset_id, v2_dataset_id, "metadata") + phase = "metadata" + if not _phase_finished(phase, "tags"): + self._migrate_tags_as_metadata( + client.add_dataset_metadata, + "datasets", + v1_dataset_id, + v2_dataset_id, + ) + self._mark_dataset_phase(v1_dataset_id, v2_dataset_id, "tags") + phase = "tags" + if not _phase_finished(phase, "comments"): + self._export_comment_sidecar("dataset", v1_dataset_id) + self._mark_dataset_phase(v1_dataset_id, v2_dataset_id, "comments") + self._mark_dataset_phase(v1_dataset_id, v2_dataset_id, "complete") finally: if fresh_client is not None: fresh_client.close() + def _dataset_progress( + self, v1_dataset_id: str + ) -> Tuple[Optional[str], Optional[str]]: + """Return the stored v2 dataset id and the last finished phase. + + A legacy checkpoint that stored only the v2 id under "datasets" is + treated as complete so an already-finished run is not repeated. + """ + state = self.checkpoint.get("dataset_state", v1_dataset_id) + if isinstance(state, dict): + v2_id = state.get("v2_id") + phase = state.get("phase") + if isinstance(v2_id, str) and isinstance(phase, str): + return v2_id, phase + legacy = self.checkpoint.get("datasets", v1_dataset_id) + if isinstance(legacy, str): + return legacy, "complete" + return None, None + + def _mark_dataset_phase( + self, v1_dataset_id: str, v2_dataset_id: str, phase: str + ) -> None: + """Record phase progress. The resumable id map is written only at the end.""" + self.checkpoint.set( + "dataset_state", + v1_dataset_id, + {"v2_id": v2_dataset_id, "phase": phase}, + ) + if phase == "complete": + self.checkpoint.set("datasets", v1_dataset_id, v2_dataset_id) + def _migrate_provenance_metadata( self, v2: ClowderV2Client, diff --git a/scripts/v1_to_v2_migration/cli.py b/scripts/v1_to_v2_migration/cli.py index f3ed18d1f..9c7406630 100644 --- a/scripts/v1_to_v2_migration/cli.py +++ b/scripts/v1_to_v2_migration/cli.py @@ -19,7 +19,12 @@ def build_parser() -> argparse.ArgumentParser: api = subparsers.add_parser("api", help="Run API-first migration path.") api.add_argument( - "--force", action="store_true", help="Re-run already mapped items." + "--force", + action="store_true", + help=( + "Re-enter datasets already marked complete. An existing v2 dataset " + "is reused instead of creating another one." + ), ) api.add_argument( "--limit", From a058d98d7398cd044b3ea442731a0a6a7466b801 Mon Sep 17 00:00:00 2001 From: Luigi Marini Date: Fri, 20 Nov 2026 15:55:10 -0600 Subject: [PATCH 4/9] Fail v1 dataset pagination instead of returning a partial list. A pagination error used to stop the loop and migrate only the datasets already fetched, with no signal that the inventory was incomplete. Retry transient server errors, then raise so the run cannot continue on a truncated dataset list. Co-authored-by: Cursor --- scripts/v1_to_v2_migration/api_clients.py | 37 ++++++++++++++++++----- 1 file changed, 30 insertions(+), 7 deletions(-) diff --git a/scripts/v1_to_v2_migration/api_clients.py b/scripts/v1_to_v2_migration/api_clients.py index 50494bc49..a73369846 100644 --- a/scripts/v1_to_v2_migration/api_clients.py +++ b/scripts/v1_to_v2_migration/api_clients.py @@ -71,23 +71,46 @@ def get_json(self, path: str, **params: Any) -> Any: raise ApiError(str(exc), status_code=response.status_code) from exc return response.json() + def _get_json_with_retry( + self, path: str, params: Dict[str, Any], attempts: int = 3 + ) -> Any: + """Retry transient 5xx responses so one blip does not fail the page.""" + last_error: Optional[ApiError] = None + for attempt in range(attempts): + try: + return self.get_json(path, **params) + except ApiError as exc: + last_error = exc + retryable = exc.status_code is None or exc.status_code >= 500 + if not retryable or attempt == attempts - 1: + raise + assert last_error is not None + raise last_error + def list_datasets(self, limit: Optional[int] = None) -> List[Dict[str, Any]]: """Fetch v1 datasets, paging through cursor-based pagination. The v1 cursor uses `when=b` + `date=` as a page - token. If the server returns 500 on a paginated request (e.g. because - it cannot parse the date format), we stop and return what we have so - far rather than crashing the entire migration. + token. A failed page is retried, then raised. Returning the pages + collected so far would silently migrate only part of v1. """ datasets: List[Dict[str, Any]] = [] page_size = 1000 if limit is None else min(1000, max(limit, 1)) params: Dict[str, Any] = {"limit": page_size} + page_num = 0 while True: + page_num += 1 try: - page = self.get_json("/api/datasets", **params) - except ApiError: - # Pagination cursor caused a server error; return what we have - break + page = self._get_json_with_retry("/api/datasets", params) + except ApiError as exc: + if not datasets: + raise + raise ApiError( + f"v1 dataset pagination failed on page {page_num} after " + f"collecting {len(datasets)} dataset(s): {exc}. " + "Refusing to continue with a partial dataset list.", + status_code=exc.status_code, + ) from exc items: List[Dict[str, Any]] = [] if isinstance(page, list): items = page From 379fc4cc777654f2ea1ae28520ccb66b7097a98b Mon Sep 17 00:00:00 2001 From: Luigi Marini Date: Fri, 20 Nov 2026 15:56:06 -0600 Subject: [PATCH 5/9] Let api-inventory run before a v2 instance is configured. The inventory command only lists v1 datasets, but it constructed a full migrator and required CLOWDER2_BASE_URL plus a v2 login. Skip the v2 client unless the command actually writes to v2. Co-authored-by: Cursor --- scripts/v1_to_v2_migration/api_migrator.py | 37 +++++++++++++--------- scripts/v1_to_v2_migration/cli.py | 2 +- scripts/v1_to_v2_migration/config.py | 8 +++-- 3 files changed, 29 insertions(+), 18 deletions(-) diff --git a/scripts/v1_to_v2_migration/api_migrator.py b/scripts/v1_to_v2_migration/api_migrator.py index 02e9b2f29..4bac03cca 100644 --- a/scripts/v1_to_v2_migration/api_migrator.py +++ b/scripts/v1_to_v2_migration/api_migrator.py @@ -90,7 +90,7 @@ def _phase_finished(completed: Optional[str], phase: str) -> bool: class ApiMigrator: """Coordinates the REST API migration path.""" - def __init__(self, config: ApiConfig): + def __init__(self, config: ApiConfig, *, connect_v2: bool = True): self.config = config self.checkpoint = Checkpoint(config.checkpoint_path) self.config.output_dir.mkdir(parents=True, exist_ok=True) @@ -103,20 +103,26 @@ def __init__(self, config: ApiConfig): password=config.clowder1_password, timeout=config.timeout_seconds, ) - self.v2_admin = ClowderV2Client( - config.clowder2_url, - api_key=config.clowder2_api_key, - timeout=config.timeout_seconds, - ) - if ( - not config.clowder2_api_key - and config.clowder2_admin_email - and config.clowder2_admin_password - ): - self.v2_admin.bearer_token = self.v2_admin.login( - config.clowder2_admin_email, - config.clowder2_admin_password, + # api-inventory only lists v1 datasets. Skip the v2 client so that + # command can run before CLOWDER2_BASE_URL or v2 credentials exist. + self.v2_admin: Optional[ClowderV2Client] = None + if connect_v2: + if not config.clowder2_url: + raise RuntimeError("CLOWDER2_BASE_URL is required for this command.") + self.v2_admin = ClowderV2Client( + config.clowder2_url, + api_key=config.clowder2_api_key, + timeout=config.timeout_seconds, ) + if ( + not config.clowder2_api_key + and config.clowder2_admin_email + and config.clowder2_admin_password + ): + self.v2_admin.bearer_token = self.v2_admin.login( + config.clowder2_admin_email, + config.clowder2_admin_password, + ) self.owner_passwords = self._load_owner_passwords() # Populated by sync_spaces(); maps v1_space_id -> space dict self._space_lookup: Dict[str, Dict[str, Any]] = {} @@ -173,7 +179,8 @@ def _write_failure_report(self) -> None: def close(self) -> None: self.v1.close() - self.v2_admin.close() + if self.v2_admin is not None: + self.v2_admin.close() def _owner_passwords_path(self) -> Path: return self.config.output_dir / _OWNER_PASSWORDS_FILENAME diff --git a/scripts/v1_to_v2_migration/cli.py b/scripts/v1_to_v2_migration/cli.py index 9c7406630..3f17e54dd 100644 --- a/scripts/v1_to_v2_migration/cli.py +++ b/scripts/v1_to_v2_migration/cli.py @@ -78,7 +78,7 @@ def main(argv: Sequence[str] | None = None) -> int: return 0 if args.command == "api-inventory": - migrator = ApiMigrator(ApiConfig.from_env()) + migrator = ApiMigrator(ApiConfig.from_env(require_v2=False), connect_v2=False) try: inventory = migrator.inventory() finally: diff --git a/scripts/v1_to_v2_migration/config.py b/scripts/v1_to_v2_migration/config.py index 3a30249f1..0772c0220 100644 --- a/scripts/v1_to_v2_migration/config.py +++ b/scripts/v1_to_v2_migration/config.py @@ -35,8 +35,12 @@ class ApiConfig: timeout_seconds: float = 120.0 @classmethod - def from_env(cls) -> "ApiConfig": - clowder2_url = os.environ["CLOWDER2_BASE_URL"].rstrip("/") + def from_env(cls, *, require_v2: bool = True) -> "ApiConfig": + if require_v2: + clowder2_url = os.environ["CLOWDER2_BASE_URL"].rstrip("/") + else: + # Inventory only talks to v1. An empty v2 URL is valid there. + clowder2_url = os.getenv("CLOWDER2_BASE_URL", "").rstrip("/") if ":3000" in clowder2_url: raise ValueError( "CLOWDER2_BASE_URL appears to target the frontend dev server (port 3000). " From 62d2aa7b41c5c5b123d1e6ec8ce52922e50fc978 Mon Sep 17 00:00:00 2001 From: Luigi Marini Date: Fri, 20 Nov 2026 16:04:06 -0600 Subject: [PATCH 6/9] Declare httpx as a runtime dependency of the API migration client. api_clients imports httpx whenever the migration runs, but the package was listed only in the dev group, so a production install could not run the API path. Co-authored-by: Cursor --- pyproject.toml | 2 +- uv.lock | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 31b1abbbd..83a530c62 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -25,6 +25,7 @@ dependencies = [ "elasticsearch==8.7.0", "rocrate==0.7.0", "itsdangerous==2.1.2", + "httpx==0.24.0", "setuptools", "boto3>=1.37.8", ] @@ -40,7 +41,6 @@ dev = [ "ruff>=0.8.0", "pre-commit>=4.0.1", "shellcheck-py>=0.10.0.1", - "httpx==0.24.0", ] docs = [ "mkdocs-material" diff --git a/uv.lock b/uv.lock index d2b152599..82e9125c5 100644 --- a/uv.lock +++ b/uv.lock @@ -410,6 +410,7 @@ dependencies = [ { name = "elasticsearch" }, { name = "email-validator" }, { name = "fastapi" }, + { name = "httpx" }, { name = "itsdangerous" }, { name = "minio" }, { name = "motor" }, @@ -429,7 +430,6 @@ dependencies = [ dev = [ { name = "black" }, { name = "faker" }, - { name = "httpx" }, { name = "pika-stubs" }, { name = "pre-commit" }, { name = "pytest" }, @@ -451,6 +451,7 @@ requires-dist = [ { name = "elasticsearch", specifier = "==8.7.0" }, { name = "email-validator", specifier = "==2.0.0.post2" }, { name = "fastapi", specifier = "==0.95.1" }, + { name = "httpx", specifier = "==0.24.0" }, { name = "itsdangerous", specifier = "==2.1.2" }, { name = "minio", specifier = "==7.1.14" }, { name = "motor", specifier = "==3.1.2" }, @@ -470,7 +471,6 @@ requires-dist = [ dev = [ { name = "black", specifier = "==23.3.0" }, { name = "faker", specifier = "==18.4.0" }, - { name = "httpx", specifier = "==0.24.0" }, { name = "pika-stubs", specifier = ">=0.1.3" }, { name = "pre-commit", specifier = ">=4.0.1" }, { name = "pytest", specifier = "==7.3.1" }, From a15450ebe97cd178ecffa1513a396941ecca9a29 Mon Sep 17 00:00:00 2001 From: Luigi Marini Date: Fri, 20 Nov 2026 16:04:29 -0600 Subject: [PATCH 7/9] Skip writing generated owner passwords during a dry run. sync_users minted a password for every candidate and always saved generated-owner-passwords.json, including when MIGRATION_DRY_RUN was set and no users were created. Co-authored-by: Cursor --- scripts/v1_to_v2_migration/api_migrator.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/scripts/v1_to_v2_migration/api_migrator.py b/scripts/v1_to_v2_migration/api_migrator.py index 4bac03cca..34f234e60 100644 --- a/scripts/v1_to_v2_migration/api_migrator.py +++ b/scripts/v1_to_v2_migration/api_migrator.py @@ -262,13 +262,15 @@ def sync_users( ): if idx % 25 == 0 or idx == total: print(f" users: {idx}/{total}") - if email not in credentials: - credentials[email] = secrets.token_urlsafe(18) if self.config.dry_run: + # Do not mint or persist passwords. A dry run must not leave + # plaintext credentials on disk for users it never creates. self.checkpoint.set( "users", email, {"email": email, "existing": email in existing_v2} ) continue + if email not in credentials: + credentials[email] = secrets.token_urlsafe(18) if email not in existing_v2: try: user = self.v2_admin.create_user( @@ -298,7 +300,8 @@ def sync_users( # logins before the first dataset migrates. Keys are instead created # lazily in _owner_client() the first time a user owns a dataset. - write_secret_json(self._owner_passwords_path(), credentials) + if not self.config.dry_run: + write_secret_json(self._owner_passwords_path(), credentials) self.owner_passwords = credentials return credentials From 0beedf61d561f396f2f0266e6f42a3226ad45425 Mon Sep 17 00:00:00 2001 From: Luigi Marini Date: Fri, 20 Nov 2026 16:55:51 -0600 Subject: [PATCH 8/9] Stream GridFS objects to MinIO instead of buffering each file. _stream_file_to_minio read the whole object into memory before upload, so a large file could exhaust the migration host. Pass the GridFS stream through and let MinIO read it in parts. Co-authored-by: Cursor --- scripts/v1_to_v2_migration/mongo_bridge.py | 31 +++++++++++++--------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/scripts/v1_to_v2_migration/mongo_bridge.py b/scripts/v1_to_v2_migration/mongo_bridge.py index b2e67bb3e..33fcb950b 100644 --- a/scripts/v1_to_v2_migration/mongo_bridge.py +++ b/scripts/v1_to_v2_migration/mongo_bridge.py @@ -367,20 +367,25 @@ def _mapped_folder_for_file(self, file_doc: Dict[str, Any]) -> Optional[ObjectId def _stream_file_to_minio( self, file_doc: Dict[str, Any], v2_file_id: ObjectId ) -> tuple[str, int]: + """Upload a GridFS object to MinIO without buffering the whole file.""" stream = self._gridfs_stream(self.uploads_gridfs, file_doc) - data = stream.read() - byte_count = len(data) - if self.config.dry_run: - return "dry-run", byte_count - content_type = first_present(file_doc, ("contentType", "content_type")) - result = self.minio.put_object( - self.config.minio_bucket, - str(v2_file_id), - io.BytesIO(data), - length=byte_count, - content_type=content_type or "application/octet-stream", - ) - return result.version_id or "N/A", byte_count + try: + # GridOut.length is the file size. put_object reads the stream in + # parts, so a large upload does not have to fit in memory. + byte_count = int(stream.length) + if self.config.dry_run: + return "dry-run", byte_count + content_type = first_present(file_doc, ("contentType", "content_type")) + result = self.minio.put_object( + self.config.minio_bucket, + str(v2_file_id), + stream, + length=byte_count, + content_type=content_type or "application/octet-stream", + ) + return result.version_id or "N/A", byte_count + finally: + stream.close() def _migrate_thumbnail( self, From 19539143f67697b677cd426339bfd2c07339be8d Mon Sep 17 00:00:00 2001 From: Luigi Marini Date: Fri, 20 Nov 2026 17:19:54 -0600 Subject: [PATCH 9/9] Restrict permissions on the migration checkpoint and failure report. failures.json and migration-checkpoint.json were written with the process umask, so on a shared host they were more readable than the credential files stored beside them. Co-authored-by: Cursor --- scripts/v1_to_v2_migration/api_migrator.py | 2 +- scripts/v1_to_v2_migration/checkpoint.py | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/scripts/v1_to_v2_migration/api_migrator.py b/scripts/v1_to_v2_migration/api_migrator.py index 34f234e60..c6c121cf3 100644 --- a/scripts/v1_to_v2_migration/api_migrator.py +++ b/scripts/v1_to_v2_migration/api_migrator.py @@ -164,7 +164,7 @@ def _record_failure( def _write_failure_report(self) -> None: """Print an aggregate summary and write failures to a JSON file.""" path = self.config.output_dir / "failures.json" - path.write_text(json.dumps(self.failures, indent=2)) + write_secret_json(path, self.failures) if self.failures: by_kind: Dict[str, int] = {} for f in self.failures: diff --git a/scripts/v1_to_v2_migration/checkpoint.py b/scripts/v1_to_v2_migration/checkpoint.py index 4807fd155..053dffdba 100644 --- a/scripts/v1_to_v2_migration/checkpoint.py +++ b/scripts/v1_to_v2_migration/checkpoint.py @@ -6,6 +6,8 @@ from pathlib import Path from typing import Any, Dict, Optional +from .utils import write_secret_json + class Checkpoint: """Small JSON-backed store for v1-to-v2 ID maps and migration state.""" @@ -28,8 +30,9 @@ def load(self) -> None: self.data.update(json.loads(self.path.read_text())) def save(self) -> None: - self.path.parent.mkdir(parents=True, exist_ok=True) - self.path.write_text(json.dumps(self.data, indent=2, sort_keys=True)) + # Same 0600 treatment as credential files. The checkpoint records v1 + # to v2 id mappings and can sit on a shared migration host. + write_secret_json(self.path, self.data) def get(self, namespace: str, key: str) -> Optional[Any]: return self.data.setdefault(namespace, {}).get(str(key))