Skip to content

Commit 8567d8d

Browse files
authored
Instrument Server Fixes (#560)
- Added logic to instrument server's 'upload_gain_reference()' function to look for 'rsync_path' key from MachineConfig before settling on using Murfey's URL. - Added logs to describe parameters passed to functions for more effective debuging.
1 parent 9ea4921 commit 8567d8d

File tree

3 files changed

+50
-8
lines changed

3 files changed

+50
-8
lines changed

src/murfey/instrument_server/api.py

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from functools import partial
88
from logging import getLogger
99
from pathlib import Path
10-
from typing import Annotated, Dict, List, Optional, Union
10+
from typing import Annotated, Any, Dict, List, Optional, Union
1111
from urllib.parse import urlparse
1212

1313
import requests
@@ -328,19 +328,43 @@ def upload_gain_reference(
328328
safe_gain_path = sanitise(str(gain_reference.gain_path))
329329
safe_visit_path = sanitise(gain_reference.visit_path)
330330
safe_destination_dir = sanitise(gain_reference.gain_destination_dir)
331-
machine_config = requests.get(
331+
332+
# Load machine config and other needed properties
333+
machine_config: dict[str, Any] = requests.get(
332334
f"{_get_murfey_url()}/instruments/{sanitise_nonpath(instrument_name)}/machine",
333335
headers={"Authorization": f"Bearer {tokens[session_id]}"},
334336
).json()
337+
338+
# Validate that file passed is from the gain reference directory
339+
gain_ref_dir = machine_config.get("gain_reference_directory", "")
340+
if not safe_gain_path.startswith(gain_ref_dir):
341+
raise ValueError(
342+
"Gain reference file does not originate from the gain reference directory "
343+
f"{gain_ref_dir!r}"
344+
)
345+
346+
# Return the rsync URL if set, otherwise assume you are syncing via Murfey
347+
rsync_url = urlparse(str(machine_config.get("rsync_url", _get_murfey_url())))
348+
rsync_module = machine_config.get("rsync_module", "data")
349+
rsync_path = f"{rsync_url.hostname}::{rsync_module}/{safe_visit_path}/{safe_destination_dir}/{secure_filename(gain_reference.gain_path.name)}"
350+
351+
# Run rsync subprocess to transfer gain reference
335352
cmd = [
336353
"rsync",
337354
posix_path(Path(safe_gain_path)),
338-
f"{urlparse(_get_murfey_url(), allow_fragments=False).hostname}::{machine_config.get('rsync_module', 'data')}/{safe_visit_path}/{safe_destination_dir}/{secure_filename(gain_reference.gain_path.name)}",
355+
rsync_path,
339356
]
340-
gain_rsync = subprocess.run(cmd)
357+
gain_rsync = subprocess.run(
358+
cmd,
359+
capture_output=True,
360+
text=True,
361+
)
341362
if gain_rsync.returncode:
342363
logger.warning(
343-
f"Gain reference file {safe_gain_path} was not successfully transferred to {safe_visit_path}/processing"
364+
f"Failed to transfer gain reference file {safe_gain_path!r} to {f'{safe_visit_path}/processing'!r} \n"
365+
f"Executed the following command: {' '.join(cmd)!r} \n"
366+
f"Returned the following error: \n"
367+
f"{gain_rsync.stderr}"
344368
)
345369
return {"success": False}
346370
return {"success": True}

src/murfey/server/__init__.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2291,6 +2291,10 @@ def feedback_callback(header: dict, message: dict) -> None:
22912291
_transport_object.transport.ack(header)
22922292
return None
22932293
elif message["register"] == "data_collection":
2294+
logger.debug(
2295+
f"Received message named 'data_collection' containing the following items:\n"
2296+
f"{', '.join([f'{sanitise(key)}: {sanitise(value)}' for key, value in message.items()])}"
2297+
)
22942298
murfey_session_id = message["session_id"]
22952299
ispyb_session_id = murfey.server.ispyb.get_session_id(
22962300
microscope=message["microscope"],
@@ -2309,7 +2313,9 @@ def feedback_callback(header: dict, message: dict) -> None:
23092313
# flush_data_collections(message["source"], murfey_db)
23102314
else:
23112315
logger.warning(
2312-
f"No data collection group ID was found for image directory {sanitise(message['image_directory'])} and source {sanitise(message['source'])}"
2316+
"No data collection group ID was found for image directory "
2317+
f"{sanitise(message['image_directory'])} and source "
2318+
f"{sanitise(message['source'])}"
23132319
)
23142320
if _transport_object:
23152321
_transport_object.transport.nack(header, requeue=True)

src/murfey/server/ispyb.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import datetime
44
import logging
5-
from typing import Callable, List, Literal, Optional
5+
from typing import Callable, Generator, List, Literal, Optional
66

77
import ispyb
88

@@ -30,6 +30,7 @@
3030
url,
3131
)
3232

33+
from murfey.util import sanitise
3334
from murfey.util.config import get_security_config
3435
from murfey.util.models import FoilHoleParameters, GridSquareParameters, Sample, Visit
3536

@@ -535,7 +536,7 @@ def do_buffer_lookup(self, app_id: int, uuid: int) -> Optional[int]:
535536
return reference
536537

537538

538-
def _get_session() -> sqlalchemy.orm.Session:
539+
def _get_session() -> Generator[Optional[sqlalchemy.orm.Session], None, None]:
539540
db = Session()
540541
if db is None:
541542
yield None
@@ -557,6 +558,17 @@ def get_session_id(
557558
visit_number: str,
558559
db: sqlalchemy.orm.Session | None,
559560
) -> int | None:
561+
562+
# Log received lookup parameters
563+
log.debug(
564+
"Looking up ISPyB BLSession ID using the following values:\n"
565+
f"microscope: {sanitise(microscope)}\n"
566+
f"proposal_code: {sanitise(proposal_code)}\n"
567+
f"proposal_number: {sanitise(proposal_number)}\n"
568+
f"visit_number: {sanitise(visit_number)}\n"
569+
)
570+
571+
# Lookup BLSession ID
560572
if db is None:
561573
return None
562574
query = (

0 commit comments

Comments
 (0)