Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /DiamondLightSource_python-murfey /src /murfey /server /api /instrument.py
| from __future__ import annotations | |
| import asyncio | |
| import datetime | |
| import logging | |
| from pathlib import Path | |
| from typing import Annotated, Any, List, Optional | |
| from urllib.parse import quote | |
| import aiohttp | |
| from fastapi import APIRouter, Depends | |
| from pydantic import BaseModel | |
| from sqlmodel import select | |
| from werkzeug.utils import secure_filename | |
| try: | |
| from smartem_backend.api_client import SmartEMAPIClient | |
| from smartem_common.schemas import AcquisitionData, MicroscopeData | |
| from murfey.util.config import get_smartem_keycloak_client | |
| if keycloak_client := get_smartem_keycloak_client(): | |
| SMARTEM_ACTIVE = True | |
| else: | |
| SMARTEM_ACTIVE = False | |
| except ImportError: | |
| keycloak_client = None | |
| SMARTEM_ACTIVE = False | |
| import murfey.server.prometheus as prom | |
| from murfey.server.api.auth import ( | |
| MurfeyInstrumentNameFrontend as MurfeyInstrumentName, | |
| MurfeySessionIDFrontend as MurfeySessionID, | |
| create_access_token, | |
| instrument_server_tokens, | |
| oauth2_scheme, | |
| validate_token, | |
| ) | |
| from murfey.server.murfey_db import murfey_db | |
| from murfey.util import safe_chmod, sanitise, secure_path | |
| from murfey.util.api import url_path_for | |
| from murfey.util.config import get_machine_config | |
| from murfey.util.db import RsyncInstance, Session, SessionProcessingParameters | |
| from murfey.util.models import File, MultigridWatcherSetup, UpstreamFileRequestInfo | |
| # Create APIRouter class object | |
| router = APIRouter( | |
| prefix="/instrument_server", | |
| dependencies=[Depends(validate_token)], | |
| tags=["Instrument Server"], | |
| ) | |
| log = logging.getLogger("murfey.server.api.instrument") | |
| lock = asyncio.Lock() | |
| async def activate_instrument_server_for_session( | |
| instrument_name: MurfeyInstrumentName, | |
| session_id: int, | |
| token_in: Annotated[str, Depends(oauth2_scheme)], | |
| db=murfey_db, | |
| ): | |
| log.info( | |
| f"Activating instrument server for session {int(sanitise(str(session_id)))}" | |
| ) | |
| if not session_id > 0: | |
| log.warning("Invalid session ID") | |
| return False | |
| visit_name = db.exec(select(Session).where(Session.id == session_id)).one().visit | |
| timestamp = datetime.datetime.now().timestamp() | |
| token = create_access_token( | |
| {"timestamp": timestamp, "session": session_id, "visit": visit_name}, | |
| token=token_in, | |
| ) | |
| async with lock: | |
| instrument_server_tokens[session_id] = {} | |
| machine_config = get_machine_config(instrument_name=instrument_name)[ | |
| instrument_name | |
| ] | |
| async with aiohttp.ClientSession() as clientsession: | |
| async with clientsession.post( | |
| f"{machine_config.instrument_server_url}{url_path_for('api.router', 'token_handshake_for_session', session_id=session_id)}", | |
| json={"access_token": token, "token_type": "bearer"}, | |
| ) as response: | |
| success = response.status == 200 | |
| instrument_server_token = await response.json() | |
| instrument_server_tokens[session_id] = instrument_server_token | |
| if success: | |
| log.info("Handshake successful") | |
| else: | |
| log.warning("Handshake unsuccessful") | |
| return success | |
| async def check_if_session_is_active( | |
| instrument_name: MurfeyInstrumentName, session_id: int | |
| ): | |
| if instrument_server_tokens.get(session_id) is None: | |
| return {"active": False} | |
| async with lock: | |
| async with aiohttp.ClientSession() as clientsession: | |
| machine_config = get_machine_config(instrument_name=instrument_name)[ | |
| instrument_name | |
| ] | |
| async with clientsession.get( | |
| f"{machine_config.instrument_server_url}{url_path_for('api.router', 'check_token', session_id=session_id)}", | |
| headers={ | |
| "Authorization": f"Bearer {instrument_server_tokens[session_id]['access_token']}" | |
| }, | |
| ) as response: | |
| return {"active": response.status == 200} | |
| async def check_multigrid_controller_status(session_id: MurfeySessionID, db=murfey_db): | |
| session = db.exec(select(Session).where(Session.id == session_id)).one() | |
| instrument_name = session.instrument_name | |
| machine_config = get_machine_config(instrument_name=instrument_name)[ | |
| instrument_name | |
| ] | |
| if machine_config.instrument_server_url: | |
| log.debug( | |
| f"Submitting request to inspect multigrid controller for session {session_id}" | |
| ) | |
| # Treat it as absent if the server-side has no stored token for the session | |
| if ( | |
| instrument_server_tokens.get(session_id, {}).get("access_token", None) | |
| is None | |
| ): | |
| return {"exists": False} | |
| async with aiohttp.ClientSession() as clientsession: | |
| async with clientsession.get( | |
| f"{machine_config.instrument_server_url}{url_path_for('api.router', 'check_multigrid_controller_status', session_id=session_id)}", | |
| headers={ | |
| "Authorization": f"Bearer {instrument_server_tokens[session_id]['access_token']}" | |
| }, | |
| ) as resp: | |
| data: dict[str, Any] = await resp.json() | |
| else: | |
| data = {"detail": "No instrument server URL found"} | |
| log.debug(f"Received response: {data}") | |
| return data | |
| async def setup_multigrid_watcher( | |
| session_id: MurfeySessionID, watcher_spec: MultigridWatcherSetup, db=murfey_db | |
| ): | |
| data = {} | |
| session = db.exec(select(Session).where(Session.id == session_id)).one() | |
| instrument_name = session.instrument_name | |
| machine_config = get_machine_config(instrument_name=instrument_name)[ | |
| instrument_name | |
| ] | |
| if machine_config.instrument_server_url: | |
| session = db.exec(select(Session).where(Session.id == session_id)).one() | |
| visit = session.visit | |
| async with aiohttp.ClientSession() as clientsession: | |
| acquisition_uuid = session.smartem_acquisition_uuid | |
| if ( | |
| SMARTEM_ACTIVE | |
| and machine_config.smartem_api_url | |
| and acquisition_uuid is None | |
| ): | |
| log.info("registering an acquisition with smartem") | |
| try: | |
| microscope_data = MicroscopeData(instrument_id=instrument_name) | |
| smartem_client = SmartEMAPIClient( | |
| base_url=machine_config.smartem_api_url, | |
| logger=log, | |
| keycloak_client=keycloak_client, | |
| ) | |
| acquisition_data = AcquisitionData( | |
| name=visit, | |
| id=visit, | |
| instrument=microscope_data, | |
| storage_path=str( | |
| secure_path( | |
| machine_config.rsync_basepath | |
| / str(datetime.datetime.now().year) | |
| / visit | |
| ) | |
| ) | |
| if machine_config.rsync_basepath | |
| else "", | |
| atlas_path=str( | |
| secure_path(watcher_spec.source / visit / "atlas") | |
| ), | |
| start_time=datetime.datetime.now(), | |
| ) | |
| acquisition_response_data = smartem_client.create_acquisition( | |
| acquisition_data | |
| ) | |
| acquisition_uuid = acquisition_response_data.uuid | |
| except Exception: | |
| log.warning( | |
| "failed to register acquisition with smartem", exc_info=True | |
| ) | |
| elif acquisition_uuid is None: | |
| log.info("smartem not configured") | |
| if acquisition_uuid is not None: | |
| session = db.exec(select(Session).where(Session.id == session_id)).one() | |
| session.smartem_acquisition_uuid = acquisition_uuid | |
| db.add(session) | |
| db.commit() | |
| async with clientsession.post( | |
| f"{machine_config.instrument_server_url}{url_path_for('api.router', 'setup_multigrid_watcher', session_id=session_id)}", | |
| json={ | |
| "source": str(secure_path(watcher_spec.source / visit)), | |
| "visit": visit, | |
| "label": visit, | |
| "instrument_name": instrument_name, | |
| "destination_overrides": { | |
| str(k): v for k, v in watcher_spec.destination_overrides.items() | |
| }, | |
| "rsync_restarts": watcher_spec.rsync_restarts, | |
| "visit_end_time": ( | |
| str(session.visit_end_time) if session.visit_end_time else None | |
| ), | |
| "acquisition_uuid": acquisition_uuid, | |
| "serialem": watcher_spec.serialem, | |
| }, | |
| headers={ | |
| "Authorization": f"Bearer {instrument_server_tokens[session_id]['access_token']}" | |
| }, | |
| ) as resp: | |
| data = await resp.json() | |
| return data | |
| async def start_multigrid_watcher(session_id: MurfeySessionID, db=murfey_db): | |
| data = {} | |
| session = db.exec(select(Session).where(Session.id == session_id)).one() | |
| process = session.process | |
| instrument_name = session.instrument_name | |
| machine_config = get_machine_config(instrument_name=instrument_name)[ | |
| instrument_name | |
| ] | |
| if machine_config.instrument_server_url: | |
| log.debug( | |
| f"Submitting request to start multigrid watcher for session {session_id} " | |
| f"with processing {('enabled' if process else 'disabled')}" | |
| ) | |
| async with aiohttp.ClientSession() as clientsession: | |
| async with clientsession.post( | |
| f"{machine_config.instrument_server_url}{url_path_for('api.router', 'start_multigrid_watcher', session_id=session_id)}?process={'true' if process else 'false'}", | |
| headers={ | |
| "Authorization": f"Bearer {instrument_server_tokens[session_id]['access_token']}" | |
| }, | |
| ) as resp: | |
| data = await resp.json() | |
| log.debug(f"Received response: {data}") | |
| return data | |
| async def update_visit_end_time( | |
| session_id: MurfeySessionID, end_time: datetime.datetime, db=murfey_db | |
| ): | |
| # Load data for session | |
| session_entry = db.exec(select(Session).where(Session.id == session_id)).one() | |
| instrument_name = session_entry.instrument_name | |
| # Update visit end time in database | |
| session_entry.visit_end_time = end_time | |
| db.add(session_entry) | |
| db.commit() | |
| # Update the alert endtime on prometheus | |
| if end_time: | |
| prom.alert_end_time.labels(visit=session_entry.visit).set(end_time.timestamp()) | |
| # Update the multigrid controller | |
| data = {} | |
| machine_config = get_machine_config(instrument_name=instrument_name)[ | |
| instrument_name | |
| ] | |
| if machine_config.instrument_server_url: | |
| async with aiohttp.ClientSession() as clientsession: | |
| async with clientsession.post( | |
| f"{machine_config.instrument_server_url}{url_path_for('api.router', 'update_multigrid_controller_visit_end_time', session_id=session_id)}?end_time={quote(end_time.isoformat())}", | |
| headers={ | |
| "Authorization": f"Bearer {instrument_server_tokens[session_id]['access_token']}" | |
| }, | |
| ) as resp: | |
| data = await resp.json() | |
| return data | |
| class ProvidedProcessingParameters(BaseModel): | |
| dose_per_frame: float | |
| extract_downscale: bool = True | |
| particle_diameter: Optional[float] = None | |
| symmetry: str = "C1" | |
| eer_fractionation: int = 20 | |
| run_class3d: bool = True | |
| async def pass_proc_params_to_instrument_server( | |
| session_id: MurfeySessionID, proc_params: ProvidedProcessingParameters, db=murfey_db | |
| ): | |
| session = db.exec(select(Session).where(Session.id == session_id)).one() | |
| existing_parameters = db.exec( | |
| select(SessionProcessingParameters).where( | |
| SessionProcessingParameters.session_id == session_id | |
| ) | |
| ).all() | |
| if not existing_parameters: | |
| session_processing_parameters = SessionProcessingParameters( | |
| session_id=session_id, | |
| dose_per_frame=proc_params.dose_per_frame, | |
| gain_ref=session.current_gain_ref, | |
| symmetry=proc_params.symmetry, | |
| eer_fractionation=proc_params.eer_fractionation, | |
| run_class3d=proc_params.run_class3d, | |
| ) | |
| else: | |
| session_processing_parameters = existing_parameters[0] | |
| session_processing_parameters.dose_per_frame = proc_params.dose_per_frame | |
| session_processing_parameters.eer_fractionation = proc_params.eer_fractionation | |
| session_processing_parameters.symmetry = proc_params.symmetry | |
| session_processing_parameters.run_class3d = proc_params.run_class3d | |
| db.add(session_processing_parameters) | |
| db.commit() | |
| data = {} | |
| instrument_name = ( | |
| db.exec(select(Session).where(Session.id == session_id)).one().instrument_name | |
| ) | |
| machine_config = get_machine_config(instrument_name=instrument_name)[ | |
| instrument_name | |
| ] | |
| if machine_config.instrument_server_url: | |
| label = db.exec(select(Session).where(Session.id == session_id)).one().name | |
| async with aiohttp.ClientSession() as clientsession: | |
| async with clientsession.post( | |
| f"{machine_config.instrument_server_url}{url_path_for('api.router', 'register_processing_parameters', session_id=session_id)}", | |
| json={ | |
| "label": label, | |
| "params": { | |
| "dose_per_frame": proc_params.dose_per_frame, | |
| "symmetry": proc_params.symmetry, | |
| "eer_fractionation": proc_params.eer_fractionation, | |
| "gain_ref": session.current_gain_ref, | |
| }, | |
| }, | |
| headers={ | |
| "Authorization": f"Bearer {instrument_server_tokens[session_id]['access_token']}" | |
| }, | |
| ) as resp: | |
| data = await resp.json() | |
| return data | |
| async def check_instrument_server(instrument_name: MurfeyInstrumentName): | |
| data = None | |
| machine_config = get_machine_config(instrument_name=instrument_name)[ | |
| instrument_name | |
| ] | |
| if machine_config.instrument_server_url: | |
| async with aiohttp.ClientSession() as clientsession: | |
| async with clientsession.get( | |
| f"{machine_config.instrument_server_url}{url_path_for('api.router', 'health')}", | |
| ) as resp: | |
| data = await resp.json() | |
| return data | |
| async def get_possible_otf_dirs( | |
| instrument_name: MurfeyInstrumentName, | |
| session_id: MurfeySessionID, | |
| ) -> list[File]: | |
| """ | |
| Submits a GET request to the client-side instrument server to get all top-level | |
| directories found under the configured OTF files directory. | |
| """ | |
| data: list[File] = [] | |
| machine_config = get_machine_config(instrument_name=instrument_name)[ | |
| instrument_name | |
| ] | |
| if machine_config.instrument_server_url: | |
| async with lock: | |
| token = instrument_server_tokens[session_id]["access_token"] | |
| async with aiohttp.ClientSession() as clientsession: | |
| url_path = url_path_for( | |
| "api.router", | |
| "get_possible_otf_dirs", | |
| instrument_name=sanitise(instrument_name), | |
| session_id=session_id, | |
| ) | |
| async with clientsession.get( | |
| f"{machine_config.instrument_server_url}{url_path}", | |
| headers={"Authorization": f"Bearer {token}"}, | |
| ) as resp: | |
| data = await resp.json() | |
| return data | |
| class OTFDirectoryUploadRequest(BaseModel): | |
| dir_path: Path | |
| async def request_otf_dir_upload( | |
| session_id: MurfeySessionID, | |
| otf_dir_request: OTFDirectoryUploadRequest, | |
| db=murfey_db, | |
| ): | |
| # Load session information from database | |
| murfey_session = db.exec(select(Session).where(Session.id == session_id)).one() | |
| visit_name = murfey_session.visit | |
| instrument_name = murfey_session.instrument_name | |
| # Load machine config | |
| machine_config = get_machine_config(instrument_name=instrument_name)[ | |
| instrument_name | |
| ] | |
| # Default data to return | |
| data: dict[str, Any] = {"success": False} | |
| # Load the rsync basepath | |
| rsync_basepath = machine_config.rsync_basepath | |
| if rsync_basepath is None: | |
| log.error(f"No rsync basepath was configured for instrument {instrument_name}") | |
| return data | |
| # Construct the partial and full paths to the server-side visit directory | |
| visit_path = f"{datetime.datetime.now().year}/{visit_name}" | |
| visit_dir = rsync_basepath / visit_path | |
| if not visit_dir.exists(): # Check previous year in case of rollover | |
| visit_dir_prev = visit_dir | |
| visit_path = f"{datetime.datetime.now().year - 1}/{visit_name}" | |
| visit_dir = rsync_basepath / visit_path | |
| if not visit_dir.exists(): | |
| log.error( | |
| "Unable to find visit directory under " | |
| f"{str(visit_dir_prev)} or {str(visit_dir)}" | |
| ) | |
| return data | |
| # Ensure that the OTF destination directory exists | |
| otf_dir = visit_dir / machine_config.gain_directory_name | |
| otf_dir.mkdir(exist_ok=True) | |
| safe_chmod(otf_dir, mode=machine_config.mkdir_chmod) # Set permissions | |
| if machine_config.instrument_server_url: | |
| async with aiohttp.ClientSession() as clientsession: | |
| url_path = url_path_for( | |
| "api.router", | |
| "upload_otf_dir", | |
| instrument_name=instrument_name, | |
| session_id=session_id, | |
| ) | |
| payload = { | |
| "dir_path": str(otf_dir_request.dir_path), | |
| "visit_path": visit_path, | |
| "destination_dir": machine_config.gain_directory_name, | |
| } | |
| async with clientsession.post( | |
| f"{machine_config.instrument_server_url}{url_path}", | |
| json=payload, | |
| headers={ | |
| "Authorization": f"Bearer {instrument_server_tokens[session_id]['access_token']}" | |
| }, | |
| ) as resp: | |
| data = await resp.json() | |
| else: | |
| log.error( | |
| f"No instrument server URL was configured for instrument {instrument_name}" | |
| ) | |
| return data | |
| async def get_possible_gain_references( | |
| instrument_name: MurfeyInstrumentName, session_id: MurfeySessionID | |
| ) -> List[File]: | |
| data = [] | |
| machine_config = get_machine_config(instrument_name=instrument_name)[ | |
| instrument_name | |
| ] | |
| if machine_config.instrument_server_url: | |
| async with lock: | |
| token = instrument_server_tokens[session_id]["access_token"] | |
| async with aiohttp.ClientSession() as clientsession: | |
| async with clientsession.get( | |
| f"{machine_config.instrument_server_url}{url_path_for('api.router', 'get_possible_gain_references', instrument_name=sanitise(instrument_name), session_id=session_id)}", | |
| headers={"Authorization": f"Bearer {token}"}, | |
| ) as resp: | |
| data = await resp.json() | |
| return data | |
| class GainReferenceRequest(BaseModel): | |
| gain_path: Path | |
| async def request_gain_reference_upload( | |
| session_id: MurfeySessionID, | |
| gain_reference_request: GainReferenceRequest, | |
| db=murfey_db, | |
| ): | |
| instrument_name = ( | |
| db.exec(select(Session).where(Session.id == session_id)).one().instrument_name | |
| ) | |
| machine_config = get_machine_config(instrument_name=instrument_name)[ | |
| instrument_name | |
| ] | |
| visit = db.exec(select(Session).where(Session.id == session_id)).one().visit | |
| visit_path = f"{datetime.datetime.now().year}/{visit}" | |
| data = {} | |
| if machine_config.instrument_server_url: | |
| async with aiohttp.ClientSession() as clientsession: | |
| async with clientsession.post( | |
| f"{machine_config.instrument_server_url}{url_path_for('api.router', 'upload_gain_reference', instrument_name=instrument_name, session_id=session_id)}", | |
| json={ | |
| "gain_path": str(gain_reference_request.gain_path), | |
| "visit_path": visit_path, | |
| "gain_destination_dir": machine_config.gain_directory_name, | |
| }, | |
| headers={ | |
| "Authorization": f"Bearer {instrument_server_tokens[session_id]['access_token']}" | |
| }, | |
| ) as resp: | |
| data = await resp.json() | |
| return data | |
| async def request_upstream_tiff_data_download( | |
| visit_name: str, session_id: MurfeySessionID, db=murfey_db | |
| ): | |
| data = {} | |
| instrument_name = ( | |
| db.exec(select(Session).where(Session.id == session_id)).one().instrument_name | |
| ) | |
| machine_config = get_machine_config(instrument_name=instrument_name)[ | |
| instrument_name | |
| ] | |
| if machine_config.upstream_data_download_directory: | |
| download_dir = str( | |
| machine_config.upstream_data_download_directory | |
| / secure_filename(visit_name) | |
| ) | |
| if machine_config.instrument_server_url: | |
| async with aiohttp.ClientSession() as clientsession: | |
| async with clientsession.post( | |
| f"{machine_config.instrument_server_url}{url_path_for('api.router', 'gather_upstream_tiffs', visit_name=secure_filename(visit_name), session_id=session_id)}", | |
| json={"download_dir": download_dir}, | |
| headers={ | |
| "Authorization": f"Bearer {instrument_server_tokens[session_id]['access_token']}" | |
| }, | |
| ) as resp: | |
| data = await resp.json() | |
| return data | |
| async def request_upstream_file_download( | |
| visit_name: str, | |
| session_id: MurfeySessionID, | |
| upstream_file_request: UpstreamFileRequestInfo, | |
| db=murfey_db, | |
| ): | |
| """ | |
| Forwards a request to the instrument server to trigger a file download request. | |
| """ | |
| # Load the current instrument's machine config | |
| instrument_name = ( | |
| db.exec(select(Session).where(Session.id == session_id)).one().instrument_name | |
| ) | |
| machine_config = get_machine_config(instrument_name=instrument_name)[ | |
| instrument_name | |
| ] | |
| # Log and return errors if download directory or URL weren't specified | |
| if not machine_config.upstream_data_download_directory: | |
| log.error("No download directory was configured for this instrument") | |
| return { | |
| "success": False, | |
| "detail": "No download directory configured", | |
| } | |
| if not machine_config.instrument_server_url: | |
| log.error("Couldn't find instrument server URL to post request to") | |
| return { | |
| "success": False, | |
| "detail": "No instrument server URL", | |
| } | |
| # Forward the download request | |
| download_dir = str( | |
| machine_config.upstream_data_download_directory / secure_filename(visit_name) | |
| ) | |
| async with aiohttp.ClientSession() as clientsession: | |
| url_path = url_path_for( | |
| "api.router", | |
| "run_upstream_file_download_request", | |
| visit_name=secure_filename(visit_name), | |
| session_id=session_id, | |
| ) | |
| async with clientsession.post( | |
| f"{machine_config.instrument_server_url}{url_path}", | |
| headers={ | |
| "Authorization": f"Bearer {instrument_server_tokens[session_id]['access_token']}" | |
| }, | |
| json={ | |
| "download_dir": download_dir, | |
| "upstream_instrument": upstream_file_request.upstream_instrument, | |
| "upstream_visit_path": str(upstream_file_request.upstream_visit_path), | |
| "search_strings": upstream_file_request.search_strings, | |
| }, | |
| ) as resp: | |
| data = await resp.json() | |
| return data | |
| class RsyncerSource(BaseModel): | |
| source: str | |
| async def stop_rsyncer( | |
| session_id: MurfeySessionID, rsyncer_source: RsyncerSource, db=murfey_db | |
| ): | |
| data = {} | |
| instrument_name = ( | |
| db.exec(select(Session).where(Session.id == session_id)).one().instrument_name | |
| ) | |
| machine_config = get_machine_config(instrument_name=instrument_name)[ | |
| instrument_name | |
| ] | |
| if machine_config.instrument_server_url: | |
| async with aiohttp.ClientSession() as clientsession: | |
| async with clientsession.post( | |
| f"{machine_config.instrument_server_url}{url_path_for('api.router', 'stop_rsyncer', session_id=session_id)}", | |
| json={ | |
| "source": str(secure_path(Path(rsyncer_source.source))), | |
| }, | |
| headers={ | |
| "Authorization": f"Bearer {instrument_server_tokens[session_id]['access_token']}" | |
| }, | |
| ) as resp: | |
| data = await resp.json() | |
| return data | |
| async def finalise_rsyncer( | |
| session_id: MurfeySessionID, rsyncer_source: RsyncerSource, db=murfey_db | |
| ): | |
| data = {} | |
| instrument_name = ( | |
| db.exec(select(Session).where(Session.id == session_id)).one().instrument_name | |
| ) | |
| machine_config = get_machine_config(instrument_name=instrument_name)[ | |
| instrument_name | |
| ] | |
| if machine_config.instrument_server_url: | |
| async with aiohttp.ClientSession() as clientsession: | |
| async with clientsession.post( | |
| f"{machine_config.instrument_server_url}{url_path_for('api.router', 'finalise_rsyncer', session_id=session_id)}", | |
| json={ | |
| "source": str(secure_path(Path(rsyncer_source.source))), | |
| }, | |
| headers={ | |
| "Authorization": f"Bearer {instrument_server_tokens[session_id]['access_token']}" | |
| }, | |
| ) as resp: | |
| data = await resp.json() | |
| return data | |
| async def finalise_session(session_id: MurfeySessionID, db=murfey_db): | |
| log.debug(f"Finalising session {session_id}") | |
| data = {} | |
| instrument_name = ( | |
| db.exec(select(Session).where(Session.id == session_id)).one().instrument_name | |
| ) | |
| machine_config = get_machine_config(instrument_name=instrument_name)[ | |
| instrument_name | |
| ] | |
| if machine_config.instrument_server_url: | |
| async with aiohttp.ClientSession() as clientsession: | |
| async with clientsession.post( | |
| f"{machine_config.instrument_server_url}{url_path_for('api.router', 'finalise_session', session_id=session_id)}", | |
| headers={ | |
| "Authorization": f"Bearer {instrument_server_tokens[session_id]['access_token']}" | |
| }, | |
| ) as resp: | |
| data = await resp.json() | |
| log.debug(f"Received response {data}") | |
| return data | |
| async def abandon_session(session_id: MurfeySessionID, db=murfey_db): | |
| data = {} | |
| instrument_name = ( | |
| db.exec(select(Session).where(Session.id == session_id)).one().instrument_name | |
| ) | |
| machine_config = get_machine_config(instrument_name=instrument_name)[ | |
| instrument_name | |
| ] | |
| if machine_config.instrument_server_url: | |
| async with aiohttp.ClientSession() as clientsession: | |
| async with clientsession.post( | |
| f"{machine_config.instrument_server_url}{url_path_for('api_router', 'abandon_controller', session_id=session_id)}", | |
| headers={ | |
| "Authorization": f"Bearer {instrument_server_tokens[session_id]['access_token']}" | |
| }, | |
| ) as resp: | |
| data = await resp.json() | |
| return data | |
| async def remove_rsyncer( | |
| session_id: MurfeySessionID, rsyncer_source: RsyncerSource, db=murfey_db | |
| ): | |
| data = {} | |
| instrument_name = ( | |
| db.exec(select(Session).where(Session.id == session_id)).one().instrument_name | |
| ) | |
| machine_config = get_machine_config(instrument_name=instrument_name)[ | |
| instrument_name | |
| ] | |
| if isinstance(session_id, int): | |
| if machine_config.instrument_server_url: | |
| async with aiohttp.ClientSession() as clientsession: | |
| async with clientsession.post( | |
| f"{machine_config.instrument_server_url}{url_path_for('api.router', 'remove_rsyncer', session_id=session_id)}", | |
| json={ | |
| "source": str(secure_path(Path(rsyncer_source.source))), | |
| }, | |
| headers={ | |
| "Authorization": f"Bearer {instrument_server_tokens[session_id]['access_token']}" | |
| }, | |
| ) as resp: | |
| data = await resp.json() | |
| return data | |
| async def restart_rsyncer( | |
| session_id: MurfeySessionID, rsyncer_source: RsyncerSource, db=murfey_db | |
| ): | |
| data = {} | |
| instrument_name = ( | |
| db.exec(select(Session).where(Session.id == session_id)).one().instrument_name | |
| ) | |
| machine_config = get_machine_config(instrument_name=instrument_name)[ | |
| instrument_name | |
| ] | |
| if isinstance(session_id, int): | |
| if machine_config.instrument_server_url: | |
| async with aiohttp.ClientSession() as clientsession: | |
| async with clientsession.post( | |
| f"{machine_config.instrument_server_url}{url_path_for('api.router', 'restart_rsyncer', session_id=session_id)}", | |
| json={ | |
| "source": str(secure_path(Path(rsyncer_source.source))), | |
| }, | |
| headers={ | |
| "Authorization": f"Bearer {instrument_server_tokens[session_id]['access_token']}" | |
| }, | |
| ) as resp: | |
| data = await resp.json() | |
| return data | |
| async def flush_skipped_rsyncer( | |
| session_id: MurfeySessionID, rsyncer_source: RsyncerSource, db=murfey_db | |
| ): | |
| # Load data for session | |
| session_entry = db.exec(select(Session).where(Session.id == session_id)).one() | |
| instrument_name = session_entry.instrument_name | |
| # Define a new visit end time that's slightly ahead of current time | |
| new_end_time = datetime.datetime.now().replace( | |
| second=0, microsecond=0 | |
| ) + datetime.timedelta(minutes=5) | |
| # Update the stored visit end time if the new one exceeds it | |
| if session_entry.visit_end_time: | |
| if new_end_time > session_entry.visit_end_time: | |
| session_entry.visit_end_time = new_end_time | |
| db.add(session_entry) | |
| db.commit() | |
| # Send request to flush rsyncer | |
| update_result: dict = {} | |
| flush_result: dict = {} | |
| machine_config = get_machine_config(instrument_name=instrument_name)[ | |
| instrument_name | |
| ] | |
| if isinstance(session_id, int): | |
| if machine_config.instrument_server_url: | |
| async with aiohttp.ClientSession() as clientsession: | |
| # Send request to instrument server to update multigrid controller | |
| async with clientsession.post( | |
| f"{machine_config.instrument_server_url}{url_path_for('api.router', 'update_multigrid_controller_visit_end_time', session_id=session_id)}?end_time={quote(session_entry.visit_end_time.isoformat())}", | |
| headers={ | |
| "Authorization": f"Bearer {instrument_server_tokens[session_id]['access_token']}" | |
| }, | |
| ) as resp: | |
| update_result = await resp.json() | |
| if not update_result.get("success", False): | |
| return {"success": False} | |
| # Send request to flush the rsyncer | |
| async with clientsession.post( | |
| f"{machine_config.instrument_server_url}{url_path_for('api.router', 'flush_skipped_rsyncer', session_id=session_id)}", | |
| json={ | |
| "source": str(secure_path(Path(rsyncer_source.source))), | |
| }, | |
| headers={ | |
| "Authorization": f"Bearer {instrument_server_tokens[session_id]['access_token']}" | |
| }, | |
| ) as resp: | |
| flush_result = await resp.json() | |
| if not flush_result.get("success", False): | |
| return {"success": False} | |
| # Reset the skipped file count for the specific Prometheus gauge to 0 | |
| prom.skipped_files.labels( | |
| rsync_source=rsyncer_source.source, visit=session_entry.visit | |
| ).set(0) | |
| return flush_result | |
| class RSyncerInfo(BaseModel): | |
| source: str | |
| num_files_transferred: int | |
| num_files_in_queue: int | |
| num_files_to_analyse: int | |
| alive: bool | |
| stopping: bool | |
| analyser_alive: bool | |
| analyser_stopping: bool | |
| destination: str | |
| tag: str | |
| files_transferred: int | |
| files_counted: int | |
| transferring: bool | |
| session_id: int | |
| num_files_skipped: int = 0 | |
| async def get_rsyncer_info( | |
| instrument_name: MurfeyInstrumentName, session_id: MurfeySessionID, db=murfey_db | |
| ) -> List[RSyncerInfo]: | |
| rsyncer_list = [] | |
| analyser_list = [] | |
| machine_config = get_machine_config(instrument_name=instrument_name)[ | |
| instrument_name | |
| ] | |
| rsync_instances = db.exec( | |
| select(RsyncInstance).where(RsyncInstance.session_id == session_id) | |
| ).all() | |
| if machine_config.instrument_server_url: | |
| try: | |
| async with lock: | |
| token = instrument_server_tokens[session_id]["access_token"] | |
| async with aiohttp.ClientSession() as clientsession: | |
| async with clientsession.get( | |
| f"{machine_config.instrument_server_url}{url_path_for('api.router', 'get_rsyncer_info', session_id=session_id)}", | |
| headers={"Authorization": f"Bearer {token}"}, | |
| ) as resp: | |
| if resp.status == 200: | |
| rsyncer_list = await resp.json() | |
| else: | |
| rsyncer_list = [] | |
| except KeyError: | |
| rsyncer_list = [] | |
| except Exception: | |
| log.warning( | |
| "Exception encountered gathering rsyncer info from the instrument server", | |
| exc_info=True, | |
| ) | |
| try: | |
| async with lock: | |
| token = instrument_server_tokens[session_id]["access_token"] | |
| async with aiohttp.ClientSession() as clientsession: | |
| async with clientsession.get( | |
| f"{machine_config.instrument_server_url}{url_path_for('api.router', 'get_analyser_info', session_id=session_id)}", | |
| headers={"Authorization": f"Bearer {token}"}, | |
| ) as resp: | |
| if resp.status == 200: | |
| analyser_list = await resp.json() | |
| else: | |
| analyser_list = [] | |
| except KeyError: | |
| analyser_list = [] | |
| except Exception: | |
| log.warning( | |
| "Exception encountered gathering analyser info from the instrument server", | |
| exc_info=True, | |
| ) | |
| combined_data = [] | |
| rsyncer_source_lookup = {d["source"]: d for d in rsyncer_list} | |
| analyser_source_lookup = {d["source"]: d for d in analyser_list} | |
| for ri in rsync_instances: | |
| rsync_data = rsyncer_source_lookup.get(ri.source, {}) | |
| analyser_data = analyser_source_lookup.get(ri.source, {}) | |
| combined_data.append( | |
| RSyncerInfo( | |
| source=ri.source, | |
| num_files_transferred=rsync_data.get("num_files_transferred", 0), | |
| num_files_in_queue=rsync_data.get("num_files_in_queue", 0), | |
| num_files_to_analyse=analyser_data.get("num_files_in_queue", 0), | |
| alive=rsync_data.get("alive", False), | |
| stopping=rsync_data.get("stopping", True), | |
| analyser_alive=analyser_data.get("alive", False), | |
| analyser_stopping=analyser_data.get("stopping", True), | |
| destination=ri.destination, | |
| tag=ri.tag, | |
| files_transferred=ri.files_transferred, | |
| files_counted=ri.files_counted, | |
| transferring=ri.transferring, | |
| session_id=session_id, | |
| num_files_skipped=rsync_data.get("num_files_skipped", 0), | |
| ) | |
| ) | |
| return combined_data | |
Xet Storage Details
- Size:
- 38.2 kB
- Xet hash:
- 833ad787c8baaabcf641cf7ada1bcee095cf9b5bfbcc42efc0a41a7cd25b2fb6
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.