Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/pipelines/isce3_rtc.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ At runtime, the script [run_isce3_rtc_pipeline.sh](../../scripts/run_isce3_rtc_p
--skip-upload-to-s3=false
--scene-data-source=("AUS_COP_HUB" "ASF" "CDSE") # order of preference
--orbit-data-source=("AUS_COP_HUB" "ASF" "CDSE") # order of preference
--scene-download-timeout-mins=60 # per scene data source
--skip-validate-stac=false
--skip-upload-processed-scene-tracking-file=false
--skip-rtc=false
Expand Down Expand Up @@ -162,6 +163,7 @@ At runtime, the script [run_isce3_rtc_pipeline.sh](../../scripts/run_isce3_rtc_p
- `skip-upload-to-s3` -> Make the products, but skip uploading them to AWS S3.
- `scene-data-source` -> Where to download the scene SLC file. Can be single string or a list of preferences separated by a space. Supported values are any of `AUS_COP_HUB`, `ASF` or `CDSE`. The default is (`AUS_COP_HUB` `ASF` `CDSE`).
- `orbit-data-source` -> Where to download the orbit files. Can be single string or a list of preferences separated by a space. Can be any of `AUS_COP_HUB`, `ASF` or `CDSE`. The default is (`AUS_COP_HUB` `ASF` `CDSE`).
- `scene-download-timeout-mins` -> The maximum number of minutes allowed to download the scene from each source in `scene-data-source`. If a source times out, its download process (and any subprocesses) is stopped, partial files it created are removed and the next source is tried. If all sources fail and at least one timed out, the workflow exits with code 102. The default is 60.
- `skip-validate-stac` -> To skip validation of the created STAC doc within the code. If this is not set and the stac is invalid, products will not be uploaded. By default we want to validate the stac.
- `skip-upload-processed-scene-tracking-file` -> By default a small .json file (`{scene}.json`) is uploaded to a monitoring subfolder of the provided `s3_project_folder`. These can be easily parsed to check for which scenes have been processed. Setting this skips the upload of that file. By default, the file is uploaded to: RTC_S1 -> `{s3_project_folder}/monitoring/processed_scenes` and RTC_S1_STATIC -> `{s3_project_folder}/monitoring/processed_scenes_static_layers`
- `link-static-layers` -> Flag to link RTC_S1_STATIC products to RTC_S1 in stac metadata. The RTC_S1_STATIC products must exist for the given bursts.
Expand Down
13 changes: 12 additions & 1 deletion sar_pipeline/pipelines/isce3_rtc/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,16 @@
is_flag=True,
help="Save the burst geometries to a geojson",
)
@click.option(
"--scene-download-timeout-mins",
required=False,
default=60,
type=float,
help="Maximum number of minutes allowed to download the scene from each "
"data source in --scene-data-source. If a source times out, it is stopped "
"and the next source is tried. If all sources fail and at least one timed "
"out, the process exits with code 102.",
)
@log_timing
def get_data_for_scene_and_make_run_config(
scene,
Expand All @@ -263,6 +273,7 @@ def get_data_for_scene_and_make_run_config(
orbit_data_source,
make_folders,
save_burst_geometries,
scene_download_timeout_mins,
):
"""
Retrieve all required inputs for RTC_S1 or RTC_S1_STATIC processing, including scene data, orbit files,
Expand Down Expand Up @@ -478,7 +489,7 @@ def get_data_for_scene_and_make_run_config(
# iterate through the preferences for the scene data source and download the scene
SCENE_PATH, scene_polygon, input_scene_url = (
download_scene_from_preference_list_with_timeout(
timeout_mins=60,
timeout_mins=scene_download_timeout_mins,
early_exit_code=102,
scene_data_source_preferences=scene_data_sources,
scene=scene,
Expand Down
229 changes: 187 additions & 42 deletions sar_pipeline/preparation/downloads/scenes.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
import shutil
import tempfile
import multiprocessing
import inspect
import signal
import sys
from cdsetool.query import query_features, FeatureQuery
from cdsetool.credentials import Credentials
Expand Down Expand Up @@ -842,68 +844,211 @@ def download_scene_from_preference_list(
return SCENE_PATH, scene_polygon, scene_url


# Seconds to wait after SIGTERM before SIGKILL when stopping a download process
_KILL_GRACE_SECONDS = 5

# Signature used to find the scene and download folder in the arguments passed
# to download_scene_from_preference_list_with_timeout
_PREFERENCE_LIST_SIGNATURE = inspect.signature(download_scene_from_preference_list)


def _download_scene_in_child_process(conn, args: tuple, kwargs: dict) -> None:
"""Target for the child process that downloads a scene from a single source.
The result, or the raised exception, is sent back to the parent through `conn`.
"""
# Lead a new process group so the parent can kill this process and all of
# its descendants on timeout. This includes the `shell=True` subprocesses
# used for pygssearch (AUS_COP_HUB), which would otherwise be orphaned and
# keep downloading after this process is killed.
os.setpgrp()
try:
payload = ("ok", download_scene_from_preference_list(*args, **kwargs))
except BaseException as e:
payload = ("error", e)
try:
conn.send(payload)
except Exception:
# the result or exception could not be pickled, send a description instead
conn.send(
(
"error",
SceneDownloadError(
f"Could not return the result of the download process : {payload[1]!r}"
),
)
)
finally:
conn.close()


def _kill_process_group(process) -> None:
"""Stop a download process and every process in its process group."""
for sig in (signal.SIGTERM, signal.SIGKILL):
try:
os.killpg(process.pid, sig)
except (ProcessLookupError, PermissionError):
# group already gone (or not yet created), fall back to the process itself
if process.is_alive():
process.kill()
if sig == signal.SIGTERM:
process.join(_KILL_GRACE_SECONDS)
process.join()


def _run_single_source_download_with_timeout(
timeout_seconds: float, args: tuple, kwargs: dict
):
"""Run `download_scene_from_preference_list` in a child process and return
its result. Raises SceneDownloadTimeoutError if it does not finish in time.
"""
# Use fork explicitly so behaviour does not depend on the default start
# method of the Python version (forkserver from Python 3.14). Forking also
# means patched functions in tests propagate to the child process.
ctx = multiprocessing.get_context("fork")
parent_conn, child_conn = ctx.Pipe(duplex=False)
process = ctx.Process(
target=_download_scene_in_child_process,
args=(child_conn, args, kwargs),
daemon=True,
)
process.start()
child_conn.close()
try:
if not parent_conn.poll(timeout_seconds):
raise SceneDownloadTimeoutError(
f"Scene download timed out after {timeout_seconds / 60:g} minutes."
)
try:
status, payload = parent_conn.recv()
except EOFError:
process.join(_KILL_GRACE_SECONDS)
raise SceneDownloadError(
f"Download process exited without a result (exit code {process.exitcode})"
)
if status == "error":
if isinstance(payload, Exception):
raise payload
raise SceneDownloadError(f"Download process failed : {payload!r}")
# let the child exit cleanly before cleaning up any leftover descendants
process.join(_KILL_GRACE_SECONDS)
return payload
finally:
_kill_process_group(process)
parent_conn.close()


def _partial_scene_paths(scene: str, download_folder: Path) -> set[Path]:
"""Files and folders that a scene download attempt may leave behind if it
is stopped part way through. A completed .SAFE is not included as it only
appears once extraction has finished (see `_unzip_scene`) and can be reused.
"""
download_folder = Path(download_folder)
paths = {
download_folder / f"{scene}.zip", # AUS_COP_HUB and ASF
download_folder / f"{scene}.SAFE.zip", # CDSE
}
# temporary extraction folders created by _unzip_scene
paths.update(download_folder.glob(".extracting_*"))
return {p for p in paths if p.exists()}


def _remove_new_partial_scene_files(
scene: str, download_folder: Path, existing_paths: set[Path]
) -> None:
"""Remove partial files created by a failed or stopped download attempt.
AUS_COP_HUB and ASF both download to `{scene}.zip`, so a partial zip left by
one source would otherwise be picked up by the next as an existing download.
Paths that existed before the attempt (e.g. pre-staged inputs) are kept.
"""
for path in _partial_scene_paths(scene, download_folder) - existing_paths:
logger.info(f"Removing partial download : {path}")
if path.is_dir():
shutil.rmtree(path, ignore_errors=True)
else:
path.unlink(missing_ok=True)


def download_scene_from_preference_list_with_timeout(
scene_data_source_preferences: list,
timeout_mins: int = 60,
timeout_mins: float = 60,
early_exit_code: int | None = 102,
*args,
**kwargs,
):
"""
Run `download_scene_from_preference_list` with a timeout. Each
source is allowed timeout minutes.
Run `download_scene_from_preference_list` for each data source in order
of preference until the scene is downloaded. Each source is run in its own
process and allowed `timeout_mins` minutes. If a source fails or times out,
its process (and any subprocesses) is stopped, partial files it created are
removed and the next source is tried.

Parameters
----------
scene_data_source_preferences:
preference list of data sources to try
timeout_mins : int
Maximum number of minutes before timing out.
timeout_mins : float
Maximum number of minutes allowed for each data source.
early_exit_code:
If a specific exit code should be raised on timeout
If a specific exit code should be raised when all sources fail and at
least one of them timed out.
*args, **kwargs
Passed directly to `download_scene_from_preference_list`.

Returns
-------
tuple[Path, shapely.geometry.shape, str]
The Path to the downloaded scene, the scene geometry and scene url

Raises
------
SceneDownloadTimeoutError
If the download takes longer than the timeout.
If all sources fail, at least one timed out and early_exit_code is None.
SceneDownloadError
If all sources fail without timing out.
"""
timeout_seconds = timeout_mins * 60
current_sources = list(scene_data_source_preferences) # avoid mutating caller list

with multiprocessing.Pool(processes=1) as pool:
async_result = pool.apply_async(
download_scene_from_preference_list,
args,
dict(kwargs, scene_data_source_preferences=current_sources),
sources = list(scene_data_source_preferences) # avoid mutating caller list
if not sources:
raise ValueError("At least one scene data source must be provided")

bound_args = _PREFERENCE_LIST_SIGNATURE.bind(
*args, **dict(kwargs, scene_data_source_preferences=sources)
).arguments
scene = bound_args["scene"]
download_folder = Path(bound_args["download_folder"])

timed_out_sources = []
last_error = None
for i, source in enumerate(sources):
logger.info(
f"Attempting to download scene from preference {i+1} of {len(sources)} : "
f"{source} (timeout {timeout_mins:g} minutes)"
)
existing_paths = _partial_scene_paths(scene, download_folder)
try:
return async_result.get(timeout=timeout_seconds)

except multiprocessing.context.TimeoutError:
msg = f"Scene download timed out after {timeout_mins} minutes."
error = SceneDownloadTimeoutError(msg)
logger.exception(error)

# Always terminate the stuck worker
pool.terminate()
pool.join()

if len(current_sources) > 1:
# Try again with the first option removed
logger.info(
f"Removing preference '{current_sources[0]}' from list and retrying download"
)
return download_scene_from_preference_list_with_timeout(
scene_data_source_preferences=current_sources[1:],
timeout_mins=timeout_mins,
early_exit_code=early_exit_code,
*args,
**kwargs,
)
else:
# All options exhausted
if early_exit_code is not None:
sys.exit(early_exit_code)
raise error
return _run_single_source_download_with_timeout(
timeout_seconds,
args,
dict(kwargs, scene_data_source_preferences=[source]),
)
except SceneDownloadTimeoutError as e:
logger.error(f"Scene download from {source} timed out : {e}")
timed_out_sources.append(source)
last_error = e
except Exception as e:
logger.error(f"Scene download from {source} failed : {e!r}")
last_error = e
_remove_new_partial_scene_files(scene, download_folder, existing_paths)

if timed_out_sources:
error = SceneDownloadTimeoutError(
f"Scene could not be downloaded from any data source provided : {sources}. "
f"Sources that timed out after {timeout_mins:g} minutes : {timed_out_sources}"
)
logger.error(error)
if early_exit_code is not None:
sys.exit(early_exit_code)
raise error from last_error
raise SceneDownloadError(
f"Scene could not be downloaded from any data source provided : {sources}"
) from last_error
7 changes: 7 additions & 0 deletions scripts/run_isce3_rtc_pipeline.sh
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ make_existing_products=false
skip_upload_to_s3=false
scene_data_source=("AUS_COP_HUB" "ASF" "CDSE")
orbit_data_source=("ASF" "CDSE")
scene_download_timeout_mins="" # if empty, the cli default (60 minutes per data source) is used
skip_validate_stac=false
skip_upload_processed_scene_tracking_file=false
skip_rtc=false
Expand Down Expand Up @@ -59,6 +60,7 @@ while [[ "$#" -gt 0 ]]; do
--linked-static-layers-collection-number) linked_static_layers_collection_number="$2"; shift 2 ;;
--linked-static-layers-s3-project-folder) linked_static_layers_s3_project_folder="$2"; shift 2 ;;
--processed-scene-tracking-file-s3-folder) processed_scene_tracking_file_s3_folder="$2"; shift 2 ;;
--scene-download-timeout-mins) scene_download_timeout_mins="$2"; shift 2 ;;
--scene-data-source)
scene_data_source=() # clear the default
shift
Expand Down Expand Up @@ -153,6 +155,7 @@ echo make-existing-products : "$make_existing_products"
echo skip-upload-to-s3 : "$skip_upload_to_s3"
echo scene-data-source : ${scene_data_source[*]}
echo orbit-data-source : ${orbit_data_source[*]}
echo scene-download-timeout-mins : "${scene_download_timeout_mins:-default}"
echo skip-validate-stac : "$skip_validate_stac"
echo processed-scene-tracking-file-s3-folder : "$processed_scene_tracking_file_s3_folder"
echo skip-rtc : "$skip_rtc"
Expand Down Expand Up @@ -223,6 +226,10 @@ fi
if [[ ${#orbit_data_source[@]} -gt 0 ]]; then
cmd+=(--orbit-data-source "${orbit_data_source[*]}")
fi
# Conditionally add --scene-download-timeout-mins if set
if [[ -n "$scene_download_timeout_mins" ]]; then
cmd+=(--scene-download-timeout-mins "$scene_download_timeout_mins")
fi


if [ "$make_existing_products" = true ] ; then
Expand Down
Loading
Loading