diff --git a/config.yml b/config.yml index d0eec943..ce17e570 100644 --- a/config.yml +++ b/config.yml @@ -1,5 +1,34 @@ globus: globus_endpoints: + + # Dichroism (4.0.2 and 6.3.1) ENDPOINTS + + bl402-compute-dtn: + root_path: / + uri: compute-dtn.als.lbl.gov + uuid: TBD + name: bl402-compute-dtn + + bl402-nersc_alsdev_raw: + root_path: /global/cfs/cdirs/als/data_mover/4.0.2/raw + uri: nersc.gov + uuid: d40248e6-d874-4f7b-badd-2c06c16f1a58 + name: bl402-nersc_alsdev_raw + + bl631-compute-dtn: + root_path: / + uri: compute-dtn.als.lbl.gov + uuid: 23af478e-d459-4e78-9753-5091b5fb432a + name: bl631-compute-dtn + + bl631-nersc_alsdev_raw: + root_path: /global/cfs/cdirs/als/data_mover/6.3.1/raw + uri: nersc.gov + uuid: d40248e6-d874-4f7b-badd-2c06c16f1a58 + name: bl631-nersc_alsdev_raw + + # 8.3.2 ENDPOINTS + spot832: root_path: / uri: spot832.lbl.gov diff --git a/docs/mkdocs/docs/dichroism.md b/docs/mkdocs/docs/dichroism.md new file mode 100644 index 00000000..6a6e6e61 --- /dev/null +++ b/docs/mkdocs/docs/dichroism.md @@ -0,0 +1,159 @@ +# Dichroism Beamline Flows +This page documents the workflows supported by Splash Flows for the ALS Dichroism beamlines: + +- [Beamline 4.0.2](https://als.lbl.gov/beamlines/4-0-2/) +- [Beamline 6.3.1](https://als.lbl.gov/beamlines/6-3-1/) + +## File Watcher +There is a file watcher on the acquisition system that listens for new scans that have finished writing to disk. From there, a Prefect Flow we call `dispatcher` kicks off the downstream steps: + +- Copy scans in real time from a Globus collection on the compute-dtn server to `NERSC CFS` using Globus Transfer. +- Copy project data to `NERSC HPSS` for long-term storage (TBD). +- Ingest into SciCat (TBD). +- Schedule data pruning from `compute-dtn` and `NERSC CFS`. + +## Prefect Configuration + +### Registered Flows +#### [dispatcher.py](orchestration/flows/dichroism/dispatcher.py) +The Dispatcher Prefect Flow manages the logic for handling the order and execution of data tasks. Once a new file is written, the `dispatcher()` Flow is called with either `BL402` or `BL631` as a parameter to specify the beamline. The dispatcher handles the synchronous call to the appropriate move task. + +#### [move.py](orchestration/flows/dichroism/move.py) +Contains separate move tasks/flows for each beamline: + +- `process_new_402_file`: Flow to process a new file at BL 4.0.2 +- `process_new_631_file`: Flow to process a new file at BL 6.3.1 + +Each flow performs the following steps: + +- Copy the file from `compute-dtn` to `NERSC CFS` and ingest the file path and metadata into SciCat. +- Schedule pruning from `compute-dtn`. +- Copy the file from `NERSC CFS` to `NERSC HPSS`. Ingest the archived file path in SciCat. +- Schedule pruning from `NERSC CFS` (after archiving). + +### Work Pools and Queues +The following work pools are defined in `orchestration/flows/dichroism/prefect.yaml`: + +| Deployment | Work Pool | Work Queue | +|------------|-----------|------------| +| `run_dichroism_dispatcher` | `dispatcher_dichroism_pool` | `dispatcher_402_queue` / `dispatcher_631_queue` | +| `new_file_402` | `new_file_dichroism_pool` | `new_file_402_queue` | +| `new_file_631` | `new_file_dichroism_pool` | `new_file_631_queue` | +| `test_transfers_dichroism` | `new_file_dichroism_pool` | `test_transfers_dichroism_queue` | + +Both beamlines share the same work pools but use separate queues for fine-grained control. + +### Endpoint Configuration +**Globus Endpoints** +Endpoints are defined in config.yml: +```yaml +bl402-compute-dtn: + root_path: / + uri: compute-dtn.als.lbl.gov + uuid: + name: bl402-compute-dtn + +bl402-nersc_alsdev_raw: + root_path: /global/cfs/cdirs/als/data_mover/4.0.2/raw + uri: nersc.gov + uuid: + name: bl402-nersc_alsdev_raw + +bl631-compute-dtn: + root_path: / + uri: compute-dtn.als.lbl.gov + uuid: + name: bl631-compute-dtn + +bl631-nersc_alsdev_raw: + root_path: /global/cfs/cdirs/als/data_mover/6.3.1/raw + uri: nersc.gov + uuid: + name: bl631-nersc_alsdev_raw +``` + +#### Deployment +**Register Flows** +Using the init script with Docker: +```bash +BEAMLINE=dichroism ./init_work_pools.py +``` +Or deploy manually: +```bash +prefect deploy --prefect-file orchestration/flows/dichroism/prefect.yaml --all +``` +Start Workers + +```bash +prefect worker start --pool "dispatcher_dichroism_pool" +prefect worker start --pool "new_file_dichroism_pool" +``` + +Deployment of the Prefect Server and Workers is handled in the [als_ansible](https://github.com/als-computing/als_ansible) repository. + +#### VM Details +The computing backend runs on a VM managed by ALS IT staff. +flow-dichroism.als.lbl.gov + +## Flow Diagram +```mermaid +sequenceDiagram + participant DET as Detector/
File Watcher + participant DISP as Prefect
Dispatcher + participant DTN as compute-dtn
Storage + participant GLOB as Globus
Transfer + participant CFS as NERSC
CFS + participant CAT as SciCat
Metadata + participant HPSS as NERSC
HPSS + + %% Initial Trigger + DET->>DET: Monitor filesystem + DET->>DISP: Trigger on new file + DISP->>DISP: Route to BL402 or BL631 + + %% Flow 1: new_file (402 or 631) + rect rgb(220, 230, 255) + note over DISP,CAT: FLOW 1: new_file_402 / new_file_631 + DISP->>GLOB: Init transfer + activate GLOB + GLOB->>DTN: Read from compute-dtn + DTN-->>GLOB: Data + GLOB->>CFS: Write to NERSC CFS + GLOB-->>DISP: Transfer complete + deactivate GLOB + + DISP->>CAT: Register metadata (TBD) + end + + %% Flow 2: HPSS Archive + rect rgb(220, 255, 230) + note over DISP,HPSS: FLOW 2: HPSS Archive (TBD) + DISP->>GLOB: Init archive transfer + activate GLOB + GLOB->>CFS: Read from CFS + CFS-->>GLOB: Data + GLOB->>HPSS: Write to tape + GLOB-->>DISP: Archive complete + deactivate GLOB + + DISP->>CAT: Update metadata (TBD) + end + + %% Flow 3: Scheduled Pruning + rect rgb(255, 255, 220) + note over DISP,CFS: FLOW 3: Scheduled Pruning + DISP->>DISP: Schedule prune (6 months) + + DISP->>DTN: Prune from compute-dtn + activate DTN + DTN->>DTN: Delete expired data + DTN-->>DISP: Pruning complete + deactivate DTN + + DISP->>CFS: Prune from CFS (after HPSS) + activate CFS + CFS->>CFS: Delete expired data + CFS-->>DISP: Pruning complete + deactivate CFS + end +``` \ No newline at end of file diff --git a/docs/mkdocs/mkdocs.yml b/docs/mkdocs/mkdocs.yml index 728a990e..b2bc49fe 100644 --- a/docs/mkdocs/mkdocs.yml +++ b/docs/mkdocs/mkdocs.yml @@ -13,8 +13,11 @@ nav: - Home: index.md - Installation and Requirements: install.md - Getting Started: getting_started.md -- Compute at ALCF: alcf832.md -- Compute at NERSC: nersc832.md +- Beamline Implementations: + - Beamline 8.3.2 - Microtomography: + - Compute at ALCF: alcf832.md + - Compute at NERSC: nersc832.md + - Dichroism Beamlines (4.0.2 and 6.3.1): dichroism.md - Orchestration: orchestration.md - Configuration: configuration.md # - Troubleshooting: troubleshooting.md diff --git a/init_work_pools.py b/init_work_pools.py index b4ceb255..35dee3d8 100644 --- a/init_work_pools.py +++ b/init_work_pools.py @@ -14,6 +14,8 @@ - Deploys all flows defined in the beamline's prefect.yaml. - Creates/updates Prefect Secret blocks for GLOBUS_CLIENT_ID and GLOBUS_CLIENT_SECRET if the corresponding environment variables are present. Otherwise warns and continues. + + Environment Variables: BEAMLINE The beamline identifier (e.g., 832). Required. PREFECT_API_URL Override the Prefect server API URL. @@ -48,10 +50,15 @@ def check_env() -> tuple[str, str, str]: """Validate required environment variables and paths.""" beamline = os.environ.get("BEAMLINE") if not beamline: - logger.error("Must set BEAMLINE (e.g., 832, 733)") + logger.error("Must set BEAMLINE (e.g., 832, 733, dichroism)") sys.exit(1) - prefect_yaml = f"orchestration/flows/bl{beamline}/prefect.yaml" + # Check if the beamline identifier is a number or a string to get the correct flows folder name + if beamline.isdigit(): + prefect_yaml = f"orchestration/flows/bl{beamline}/prefect.yaml" + else: + prefect_yaml = f"orchestration/flows/{beamline}/prefect.yaml" + if not os.path.isfile(prefect_yaml): logger.error(f"[Init:{beamline}] Expected {prefect_yaml} not found!") sys.exit(1) diff --git a/orchestration/_tests/test_dichroism/__init__.py b/orchestration/_tests/test_dichroism/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/orchestration/_tests/test_dichroism/test_move.py b/orchestration/_tests/test_dichroism/test_move.py new file mode 100644 index 00000000..10090b3d --- /dev/null +++ b/orchestration/_tests/test_dichroism/test_move.py @@ -0,0 +1,349 @@ +'''Pytest unit tests for Dichroism move flow. ''' + +import logging +import pytest +from uuid import uuid4 + +from prefect.testing.utilities import prefect_test_harness +from prefect.blocks.system import Secret +from prefect.variables import Variable +from pytest_mock import MockFixture + +from orchestration._tests.test_transfer_controller import MockSecret + +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + + +@pytest.fixture(autouse=True, scope="session") +def prefect_test_fixture(): + """ + A pytest fixture that automatically sets up and tears down the Prefect test harness + for the entire test session. It creates and saves test secrets and configurations + required for Globus integration. + + Yields: + None + """ + with prefect_test_harness(): + globus_client_id = Secret(value=str(uuid4())) + globus_client_id.save(name="globus-client-id", overwrite=True) + + globus_client_secret = Secret(value=str(uuid4())) + globus_client_secret.save(name="globus-client-secret", overwrite=True) + + Variable.set( + name="globus-settings", + value={"max_wait_seconds": 600}, + overwrite=True, + _sync=True + ) + + Variable.set( + name="dichroism-settings", + value={ + "delete_data402_files_after_days": 180, + "delete_data631_files_after_days": 180 + }, + overwrite=True, + _sync=True + ) + + yield + + +# ---------------------------- +# Tests for 402 +# ---------------------------- + +def test_process_new_402_file_task(mocker: MockFixture) -> None: + """ + Test the process_new_402_file flow from orchestration.flows.dichroism.move. + + This test verifies that: + - The get_transfer_controller function is called (patched) with the correct parameters. + - The returned transfer controller's copy method is called with the expected file path, + source, and destination endpoints from the provided configuration. + + Parameters: + mocker (MockFixture): The pytest-mock fixture for patching and mocking objects. + """ + # Import the flow to test. + from orchestration.flows.dichroism.move import process_new_402_file_task + + # Patch the Secret.load and init_transfer_client in the configuration context. + with mocker.patch('prefect.blocks.system.Secret.load', return_value=MockSecret()): + mocker.patch( + "orchestration.flows.dichroism.config.transfer.init_transfer_client", + return_value=mocker.MagicMock() # Return a dummy TransferClient + ) + # Patch the schedule_prefect_flow call to avoid real Prefect interaction + mocker.patch( + "orchestration.flows.dichroism.move.schedule_prefect_flow", + return_value=None + ) + + # Instantiate the mock configuration. + from orchestration.flows.dichroism.config import ConfigDichroism + mock_config = ConfigDichroism() + + # Generate a test file path. + test_file_path = f"/tmp/test_file_{uuid4()}.txt" + + # Create a mock transfer controller with a mocked 'copy' method. + mock_transfer_controller = mocker.MagicMock() + mock_transfer_controller.copy.return_value = True + + mock_prune = mocker.patch( + "orchestration.flows.dichroism.move.prune", + return_value=None + ) + + # Patch get_transfer_controller where it is used in process_new_931_file_task. + mocker.patch( + "orchestration.flows.dichroism.move.get_transfer_controller", + return_value=mock_transfer_controller + ) + + # Execute the move flow with the test file path and mock configuration. + result = process_new_402_file_task(file_path=test_file_path, config=mock_config) + + # Verify that the transfer controller's copy method was called exactly once. + assert mock_transfer_controller.copy.call_count == 1, "Transfer controller copy method should be called exactly once" + assert result is None, "The flow should return None" + assert mock_prune.call_count == 1, "Prune function should be called exactly once" + + # Reset mocks and test with config=None + mock_transfer_controller.copy.reset_mock() + mock_prune.reset_mock() + + result = process_new_402_file_task(file_path=test_file_path, config=None) + assert mock_transfer_controller.copy.call_count == 1, "Transfer controller copy method should be called exactly once" + assert result is None, "The flow should return None" + assert mock_prune.call_count == 1, "Prune function should be called exactly once" + + +# ---------------------------- +# Tests for 631 +# ---------------------------- + +def test_process_new_631_file_task(mocker: MockFixture) -> None: + """ + Test the process_new_631_file flow from orchestration.flows.dichroism.move. + + This test verifies that: + - The get_transfer_controller function is called (patched) with the correct parameters. + - The returned transfer controller's copy method is called with the expected file path, + source, and destination endpoints from the provided configuration. + + Parameters: + mocker (MockFixture): The pytest-mock fixture for patching and mocking objects. + """ + # Import the flow to test. + from orchestration.flows.dichroism.move import process_new_631_file_task + + # Patch the Secret.load and init_transfer_client in the configuration context. + with mocker.patch('prefect.blocks.system.Secret.load', return_value=MockSecret()): + mocker.patch( + "orchestration.flows.dichroism.config.transfer.init_transfer_client", + return_value=mocker.MagicMock() # Return a dummy TransferClient + ) + # Patch the schedule_prefect_flow call to avoid real Prefect interaction + mocker.patch( + "orchestration.flows.dichroism.move.schedule_prefect_flow", + return_value=None + ) + + # Instantiate the dummy configuration. + from orchestration.flows.dichroism.config import ConfigDichroism + mock_config = ConfigDichroism() + + # Generate a test file path. + test_file_path = f"/tmp/test_file_{uuid4()}.txt" + + # Create a mock transfer controller with a mocked 'copy' method. + mock_transfer_controller = mocker.MagicMock() + mock_transfer_controller.copy.return_value = True + + mock_prune = mocker.patch( + "orchestration.flows.dichroism.move.prune", + return_value=None + ) + + # Patch get_transfer_controller where it is used in process_new_931_file_task. + mocker.patch( + "orchestration.flows.dichroism.move.get_transfer_controller", + return_value=mock_transfer_controller + ) + + # Execute the move flow with the test file path and mock configuration. + result = process_new_631_file_task(file_path=test_file_path, config=mock_config) + + # Verify that the transfer controller's copy method was called exactly once. + assert mock_transfer_controller.copy.call_count == 1, "Transfer controller copy method should be called exactly once" + assert result is None, "The flow should return None" + assert mock_prune.call_count == 1, "Prune function should be called exactly once" + + # Reset mocks and test with config=None + mock_transfer_controller.copy.reset_mock() + mock_prune.reset_mock() + + result = process_new_631_file_task(file_path=test_file_path, config=None) + assert mock_transfer_controller.copy.call_count == 1, "Transfer controller copy method should be called exactly once" + assert result is None, "The flow should return None" + assert mock_prune.call_count == 1, "Prune function should be called exactly once" + + +def test_dispatcher_dichroism_flow(mocker: MockFixture) -> None: + """ + Test the dispatcher flow for Dichroism. + + This test verifies that: + - The process_new_402_file_task or process_new_631_file_task functions are called with the correct parameters + when the dispatcher flow is executed. + Parameters: + mocker (MockFixture): The pytest-mock fixture for patching and mocking objects. + """ + # Import the dispatcher flow to test. + from orchestration.flows.dichroism.dispatcher import dispatcher + + # Create a mock configuration object. + class MockConfig: + pass + + mock_config = MockConfig() + + # Generate a test file path. + test_file = f"/tmp/test_file_{uuid4()}.txt" + + # ----------------------------- + # Common patches used by dispatcher + # ----------------------------- + mocker.patch("prefect.blocks.system.Secret.load", return_value=MockSecret()) + mocker.patch( + "orchestration.flows.dichroism.config.transfer.init_transfer_client", + return_value=mocker.MagicMock() + ) + mocker.patch( + "orchestration.flows.dichroism.move.schedule_prefect_flow", + return_value=None + ) + + # --------------------------------- + # Patch BOTH processing tasks + # --------------------------------- + mock_402 = mocker.patch( + "orchestration.flows.dichroism.dispatcher.process_new_402_file_task", + return_value=None + ) + mock_631 = mocker.patch( + "orchestration.flows.dichroism.dispatcher.process_new_631_file_task", + return_value=None + ) + + # ---------------------------------------------------------------------- + # 402 TEST + # ---------------------------------------------------------------------- + dispatcher( + file_path=test_file, + is_export_control=False, + config=mock_config, + beamline="BL402" + ) + + mock_402.assert_called_once_with(file_path=test_file, config=mock_config) + mock_631.assert_not_called() + + # Reset mocks to reuse + mock_402.reset_mock() + mock_631.reset_mock() + + # ---------------------------------------------------------------------- + # 402 TEST – config=None should still call 402 + # ---------------------------------------------------------------------- + dispatcher( + file_path=test_file, + is_export_control=False, + config=None, + beamline="BL402" + ) + + mock_402.assert_called_once() + mock_631.assert_not_called() + + mock_402.reset_mock() + mock_631.reset_mock() + + # ---------------------------------------------------------------------- + # 631 TEST + # ---------------------------------------------------------------------- + dispatcher( + file_path=test_file, + is_export_control=False, + config=mock_config, + beamline="BL631" + ) + + mock_631.assert_called_once_with(file_path=test_file, config=mock_config) + mock_402.assert_not_called() + + mock_402.reset_mock() + mock_631.reset_mock() + + # ---------------------------------------------------------------------- + # 631 TEST – config=None + # ---------------------------------------------------------------------- + dispatcher( + file_path=test_file, + is_export_control=False, + config=None, + beamline="BL631" + ) + + mock_631.assert_called_once() + mock_402.assert_not_called() + + mock_402.reset_mock() + mock_631.reset_mock() + + # ---------------------------------------------------------------------- + # Missing file_path → ValueError + # ---------------------------------------------------------------------- + with pytest.raises(ValueError): + dispatcher( + file_path=None, + is_export_control=False, + config=mock_config, + beamline="BL402" + ) + + mock_402.assert_not_called() + mock_631.assert_not_called() + + # ---------------------------------------------------------------------- + # export control flag blocks execution + # ---------------------------------------------------------------------- + with pytest.raises(ValueError): + dispatcher( + file_path=test_file, + is_export_control=True, + config=mock_config, + beamline="BL402" + ) + + mock_402.assert_not_called() + mock_631.assert_not_called() + + # ---------------------------------------------------------------------- + # Missing beamline enum → ValueError + # ---------------------------------------------------------------------- + with pytest.raises(ValueError): + dispatcher( + file_path=test_file, + is_export_control=False, + config=mock_config, + beamline=None + ) + + mock_402.assert_not_called() + mock_631.assert_not_called() diff --git a/orchestration/_tests/test_globus_flow.py b/orchestration/_tests/test_globus_flow.py index b71be618..b9c36a91 100644 --- a/orchestration/_tests/test_globus_flow.py +++ b/orchestration/_tests/test_globus_flow.py @@ -25,13 +25,13 @@ def prefect_test_fixture(): """ with prefect_test_harness(): globus_client_id = Secret(value=str(uuid4())) - globus_client_id.save(name="globus-client-id") + globus_client_id.save(name="globus-client-id", overwrite=True) globus_client_secret = Secret(value=str(uuid4())) - globus_client_secret.save(name="globus-client-secret") + globus_client_secret.save(name="globus-client-secret", overwrite=True) globus_compute_endpoint = Secret(value=str(uuid4())) - globus_compute_endpoint.save(name="globus-compute-endpoint") + globus_compute_endpoint.save(name="globus-compute-endpoint", overwrite=True) Variable.set( name="pruning-config", diff --git a/orchestration/flows/dichroism/__init__.py b/orchestration/flows/dichroism/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/orchestration/flows/dichroism/config.py b/orchestration/flows/dichroism/config.py new file mode 100644 index 00000000..643943ca --- /dev/null +++ b/orchestration/flows/dichroism/config.py @@ -0,0 +1,15 @@ +from globus_sdk import TransferClient +from orchestration.globus import transfer + + +# TODO: Use BeamlineConfig base class (Waiting for PR #62 to be merged) +class ConfigDichroism: + def __init__(self) -> None: + config = transfer.get_config() + self.endpoints = transfer.build_endpoints(config) + self.apps = transfer.build_apps(config) + self.tc: TransferClient = transfer.init_transfer_client(self.apps["als_transfer"]) + self.bl402_compute_dtn = self.endpoints["bl402-compute-dtn"] + self.bl402_nersc_alsdev_raw = self.endpoints["bl402-nersc_alsdev_raw"] + self.bl631_compute_dtn = self.endpoints["bl631-compute-dtn"] + self.bl631_nersc_alsdev_raw = self.endpoints["bl631-nersc_alsdev_raw"] diff --git a/orchestration/flows/dichroism/dispatcher.py b/orchestration/flows/dichroism/dispatcher.py new file mode 100644 index 00000000..16d49439 --- /dev/null +++ b/orchestration/flows/dichroism/dispatcher.py @@ -0,0 +1,83 @@ +from enum import Enum +import logging +from prefect import flow +from typing import Optional, Union, Any + +from orchestration.flows.dichroism.config import ConfigDichroism +from orchestration.flows.dichroism.move import process_new_402_file_task, process_new_631_file_task + +logger = logging.getLogger(__name__) + + +class DichroismBeamlineEnum(str, Enum): + BL402 = "BL402" + BL631 = "BL631" + + +# TODO Once this PR (https://github.com/als-computing/splash_flows/pull/62) is merged, we can use config: Config402 +@flow(name="dispatcher", flow_run_name="dispatcher-{file_path}") +def dispatcher( + file_path: Optional[str] = None, + is_export_control: bool = False, + config: Optional[Union[dict, Any]] = None, + beamline: Optional[DichroismBeamlineEnum] = None +) -> None: + """ + Dispatcher flow for BL402 beamline that launches the new_402_file_flow. + + :param file_path: Path to the file to be processed. + :param is_export_control: Flag indicating if export control measures should be applied. + (Not used in the current BL402 processing) + :param config: Configuration settings for processing. + Expected to be an instance of ConfigDichroism or a dict that can be converted. + :param beamline: Beamline identifier (must be either BL402, BL631). + :raises ValueError: If no configuration is provided. + :raises TypeError: If the provided configuration is not a dict or ConfigDichroism. + """ + + logger.info("Starting dispatcher flow for Dichroism.") + logger.info(f"Parameters received: file_path={file_path}, is_export_control={is_export_control}", beamline=beamline) + + # Validate inputs and raise errors if necessary. The ValueErrors prevent the rest of the flow from running. + if file_path is None: + logger.error("No file_path provided to dispatcher.") + raise ValueError("File path is required for processing.") + + if is_export_control: + logger.error("Data is under export control. Processing is not allowed.") + raise ValueError("Data is under export control. Processing is not allowed.") + + if config is None: + logger.info("No config provided, initializing default ConfigDichroism.") + config = ConfigDichroism() + + if beamline is None: + logger.error("No beamline specified.") + raise ValueError("Beamline must be specified as either BL402 or BL631.") + + if beamline == DichroismBeamlineEnum.BL402: + logger.info("Dispatching to BL402 processing flow.") + try: + process_new_402_file_task( + file_path=file_path, + config=config + ) + logger.info("Dispatcher flow completed successfully for BL402.") + except Exception as e: + logger.error(f"Error during processing in dispatcher flow for BL402: {e}") + raise + elif beamline == DichroismBeamlineEnum.BL631: + logger.info("Dispatching to BL631 processing flow.") + try: + process_new_631_file_task( + file_path=file_path, + config=config + ) + logger.info("Dispatcher flow completed successfully for BL631.") + except Exception as e: + logger.error(f"Error during processing in dispatcher flow for BL631: {e}") + raise + else: + logger.error(f"Invalid beamline specified: {beamline}") + raise ValueError(f"Invalid beamline specified: {beamline}. Must be either BL402 or BL631.") + logger.info("Dispatcher flow finished.") diff --git a/orchestration/flows/dichroism/move.py b/orchestration/flows/dichroism/move.py new file mode 100644 index 00000000..8d7f97c7 --- /dev/null +++ b/orchestration/flows/dichroism/move.py @@ -0,0 +1,318 @@ +import datetime +import logging +from typing import Optional + +from prefect import flow, task +from prefect.variables import Variable + +from orchestration.flows.dichroism.config import ConfigDichroism +from orchestration.globus.transfer import GlobusEndpoint, prune_one_safe +from orchestration.prefect import schedule_prefect_flow +from orchestration.transfer_controller import CopyMethod, get_transfer_controller + +logger = logging.getLogger(__name__) + +# Prune code is from the prune_controller in this PR: https://github.com/als-computing/splash_flows_globus/pulls +# Note: once the PR is merged, we can import prune_controller directly instead of copying the code here. + + +def prune( + file_path: str = None, + source_endpoint: GlobusEndpoint = None, + check_endpoint: Optional[GlobusEndpoint] = None, + days_from_now: float = 0.0, + config: ConfigDichroism = None +) -> bool: + """ + Prune (delete) data from a globus endpoint. + If days_from_now is 0, executes pruning immediately. + Otherwise, schedules pruning for future execution using Prefect. + Args: + file_path (str): The path to the file or directory to prune + source_endpoint (GlobusEndpoint): The globus endpoint containing the data + check_endpoint (Optional[GlobusEndpoint]): If provided, verify data exists here before pruning + days_from_now (float): Delay before pruning; if 0, prune immediately + Returns: + bool: True if pruning was successful or scheduled successfully, False otherwise + """ + if not file_path: + logger.error("No file_path provided for pruning operation") + return False + + if not source_endpoint: + logger.error("No source_endpoint provided for pruning operation") + return False + + if not config: + config = ConfigDichroism() + + if days_from_now < 0: + raise ValueError(f"Invalid days_from_now: {days_from_now}") + + logger.info(f"Setting up pruning of '{file_path}' from '{source_endpoint.name}'") + + # convert float days → timedelta + delay: datetime.timedelta = datetime.timedelta(days=days_from_now) + + # If days_from_now is 0, prune immediately + if delay.total_seconds() == 0: + logger.info(f"Executing immediate pruning of '{file_path}' from '{source_endpoint.name}'") + return _prune_globus_endpoint( + relative_path=file_path, + source_endpoint=source_endpoint, + check_endpoint=check_endpoint, + config=config + ) + else: + # Otherwise, schedule pruning for future execution + logger.info(f"Scheduling pruning of '{file_path}' from '{source_endpoint.name}' " + f"in {delay.total_seconds()/86400:.1f} days") + + try: + schedule_prefect_flow( + deployment_name="prune_globus_endpoint/prune_globus_endpoint", + parameters={ + "relative_path": file_path, + "source_endpoint": source_endpoint, + "check_endpoint": check_endpoint, + "config": config + }, + duration_from_now=delay, + ) + logger.info(f"Successfully scheduled pruning task for {delay.total_seconds()/86400:.1f} days from now") + return True + except Exception as e: + logger.error(f"Failed to schedule pruning task: {str(e)}", exc_info=True) + return False + +# Prune code is from the prune_controller in this PR: https://github.com/als-computing/splash_flows_globus/pulls +# Note: once the PR is merged, we can import prune_controller directly instead of copying the code here. + + +# @staticmethod +@flow(name="prune_globus_endpoint", flow_run_name="prune_globus_endpoint-{relative_path}") +def _prune_globus_endpoint( + relative_path: str, + source_endpoint: GlobusEndpoint, + check_endpoint: Optional[GlobusEndpoint] = None, + config: ConfigDichroism = None +) -> None: + """ + Prefect flow that performs the actual Globus endpoint pruning operation. + Args: + relative_path (str): The path of the file or directory to prune + source_endpoint (GlobusEndpoint): The Globus endpoint to prune from + check_endpoint (Optional[GlobusEndpoint]): If provided, verify data exists here before pruning + config (BeamlineConfig): Configuration object with transfer client + """ + logger.info(f"Running Globus pruning flow for '{relative_path}' from '{source_endpoint.name}'") + + if not config: + config = ConfigDichroism() + + globus_settings = Variable.get("globus-settings") + max_wait_seconds = globus_settings["max_wait_seconds"] + + flow_name = f"prune_from_{source_endpoint.name}" + logger.info(f"Running flow: {flow_name}") + logger.info(f"Pruning {relative_path} from source endpoint: {source_endpoint.name}") + prune_one_safe( + file=relative_path, + if_older_than_days=0, + transfer_client=config.tc, + source_endpoint=source_endpoint, + check_endpoint=check_endpoint, + logger=logger, + max_wait_seconds=max_wait_seconds + ) + +# ---------------------------------------------- +# Flow and task to process new files at BL 4.0.2 +# ---------------------------------------------- + + +@flow(name="new_402_file_flow", flow_run_name="process_new-{file_path}") +def process_new_402_file_flow( + file_path: str, + config: Optional[ConfigDichroism] = None +) -> None: + process_new_402_file_task( + file_path=file_path, + config=config + ) + + +@task(name="new_402_file_task") +def process_new_402_file_task( + file_path: str, + config: Optional[ConfigDichroism] = None +) -> None: + """ + Flow to process a new file at BL 4.0.2 + 1. Copy the file from the data402 to NERSC CFS. Ingest file path in SciCat. + 2. Schedule pruning from data402. 6 months from now. + 3. Copy the file from NERSC CFS to NERSC HPSS. Ingest file path in SciCat. + 4. Schedule pruning from NERSC CFS. + + :param file_path: Path to the new file to be processed. + :param config: Configuration settings for processing. + """ + + logger.info(f"Processing new 402 file: {file_path}") + + if not config: + config = ConfigDichroism() + + transfer_controller = get_transfer_controller( + transfer_type=CopyMethod.GLOBUS, + config=config + ) + + transfer_controller.copy( + file_path=file_path, + source=config.bl402_compute_dtn, + destination=config.bl402_nersc_alsdev_raw + ) + + # TODO: Ingest file path in SciCat + # Waiting for PR #62 to be merged (scicat_controller) + + # Schedule pruning from QNAP + # Waiting for PR #62 to be merged (prune_controller) + # TODO: Determine scheduling days_from_now based on beamline needs + + dichroism_settings = Variable.get("dichroism-settings") + + prune( + file_path=file_path, + source_endpoint=config.bl402_compute_dtn, + check_endpoint=config.bl402_nersc_alsdev_raw, + days_from_now=dichroism_settings["delete_data402_files_after_days"] # determine appropriate value: currently 6 months + ) + + # TODO: Copy the file from NERSC CFS to NERSC HPSS.. after 2 years? + # Waiting for PR #62 to be merged (transfer_controller) + + # TODO: Ingest file path in SciCat + # Waiting for PR #62 to be merged (scicat_controller) + + +@flow(name="move_402_flight_check", flow_run_name="move_402_flight_check-{file_path}") +def move_402_flight_check( + file_path: str = "test_directory/test.txt", +): + """Please keep your arms and legs inside the vehicle at all times.""" + logger.info("402 flight check: testing transfer from data402 to NERSC CFS") + + config = ConfigDichroism() + + transfer_controller = get_transfer_controller( + transfer_type=CopyMethod.GLOBUS, + config=config + ) + + success = transfer_controller.copy( + file_path=file_path, + source=config.bl402_compute_dtn, + destination=config.bl402_nersc_alsdev_raw + ) + if success is True: + logger.info("402 flight check: transfer successful") + else: + logger.error("402 flight check: transfer failed") + raise RuntimeError("402 flight check: transfer failed") + +# ---------------------------------------------- +# Flow and task to process new files at BL 6.3.1 +# ---------------------------------------------- + + +@flow(name="new_631_file_flow", flow_run_name="process_new-{file_path}") +def process_new_631_file_flow( + file_path: str, + config: Optional[ConfigDichroism] = None +) -> None: + process_new_631_file_task( + file_path=file_path, + config=config + ) + + +@task(name="new_631_file_task") +def process_new_631_file_task( + file_path: str, + config: Optional[ConfigDichroism] = None +) -> None: + """ + Flow to process a new file at BL 6.3.1 + 1. Copy the file from the data631 to NERSC CFS. Ingest file path in SciCat. + 2. Schedule pruning from data631. 6 months from now. + 3. Copy the file from NERSC CFS to NERSC HPSS. Ingest file path in SciCat. + 4. Schedule pruning from NERSC CFS. + + :param file_path: Path to the new file to be processed. + :param config: Configuration settings for processing. + """ + + logger.info(f"Processing new 631 file: {file_path}") + + if not config: + config = ConfigDichroism() + + transfer_controller = get_transfer_controller( + transfer_type=CopyMethod.GLOBUS, + config=config + ) + + transfer_controller.copy( + file_path=file_path, + source=config.bl631_compute_dtn, + destination=config.bl631_nersc_alsdev_raw + ) + + # TODO: Ingest file path in SciCat + # Waiting for PR #62 to be merged (scicat_controller) + + # Waiting for PR #62 to be merged (prune_controller) + # TODO: Determine scheduling days_from_now based on beamline needs + + dichroism_settings = Variable.get("dichroism-settings") + + prune( + file_path=file_path, + source_endpoint=config.bl631_compute_dtn, + check_endpoint=config.bl631_nersc_alsdev_raw, + days_from_now=dichroism_settings["delete_data631_files_after_days"] # determine appropriate value: currently 6 months + ) + + # TODO: Copy the file from NERSC CFS to NERSC HPSS.. after 2 years? + # Waiting for PR #62 to be merged (transfer_controller) + + # TODO: Ingest file path in SciCat + # Waiting for PR #62 to be merged (scicat_controller) + + +@flow(name="move_631_flight_check", flow_run_name="move_631_flight_check-{file_path}") +def move_631_flight_check( + file_path: str = "test_directory/test.txt", +): + """Please keep your arms and legs inside the vehicle at all times.""" + logger.info("631 flight check: testing transfer from data631 to NERSC CFS") + + config = ConfigDichroism() + + transfer_controller = get_transfer_controller( + transfer_type=CopyMethod.GLOBUS, + config=config + ) + + success = transfer_controller.copy( + file_path=file_path, + source=config.bl631_compute_dtn, + destination=config.bl631_nersc_alsdev_raw + ) + if success is True: + logger.info("631 flight check: transfer successful") + else: + logger.error("631 flight check: transfer failed") + raise RuntimeError("631 flight check: transfer failed") diff --git a/orchestration/flows/dichroism/prefect.yaml b/orchestration/flows/dichroism/prefect.yaml new file mode 100644 index 00000000..3325bfec --- /dev/null +++ b/orchestration/flows/dichroism/prefect.yaml @@ -0,0 +1,56 @@ +name: dichroism +prefect-version: 3.4.2 +deployments: +- name: run_dichroism_dispatcher + entrypoint: orchestration/flows/dichroism/dispatcher.py:dispatcher + work_pool: + name: dispatcher_dichroism_pool + work_queue_name: dispatcher_dichroism_queue + +# 4.0.2 Flows +- name: new_file_402_flow + entrypoint: orchestration/flows/dichroism/move.py:process_new_402_file_flow + work_pool: + name: new_file_dichroism_pool + work_queue_name: new_file_402_queue + +- name: new_file_402_flight_check + entrypoint: orchestration/flows/dichroism/move.py:move_402_flight_check + work_pool: + name: new_file_dichroism_pool + work_queue_name: move_file_402_flight_check_queue + schedules: + - cron: "0 */12 * * *" # Every 12 hours + slug: "test-move-402-flight-check" + timezone: America/Los_Angeles + active: true + +- name: prune_data402 + entrypoint: orchestration/flows/dichroism/move.py:_prune_globus_endpoint + work_pool: + name: prune_dichroism_pool + work_queue_name: prune_402_queue + +# 6.3.1 Flows +- name: new_file_631_flow + entrypoint: orchestration/flows/dichroism/move.py:process_new_631_file_flow + work_pool: + name: new_file_dichroism_pool + work_queue_name: new_file_631_queue + +- name: new_file_631_flight_check + entrypoint: orchestration/flows/dichroism/move.py:move_631_flight_check + work_pool: + name: new_file_dichroism_pool + work_queue_name: move_file_631_flight_check_queue + schedules: + - cron: "0 */12 * * *" # Every 12 hours + slug: "test-move-631-flight-check" + timezone: America/Los_Angeles + active: true + +- name: prune_data631 + entrypoint: orchestration/flows/dichroism/move.py:_prune_globus_endpoint + work_pool: + name: prune_dichroism_pool + work_queue_name: prune_631_queue