Skip to content
Merged
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
1 change: 1 addition & 0 deletions SPRINTLOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -618,5 +618,6 @@ _Empty sprint_

- Fix --no-prompt silently skipping user activation and deactivation ([#1008](https://github.com/ScilifelabDataCentre/dds_cli/pull/1008))
- Remove resolved entries from dds_failed_delivery.json after retry ([#999](https://github.com/ScilifelabDataCentre/dds_cli/pull/999))
- Retry API calls once on a 502/503 from the proxy, and stop uploads/downloads during maintenance ([#1009](https://github.com/ScilifelabDataCentre/dds_cli/pull/1009))
- Improved documentation of installation instructions ([#1013](https://github.com/ScilifelabDataCentre/dds_cli/pull/1013))
- Update dependency pytest to 9.2.0 ([#998](https://github.com/ScilifelabDataCentre/dds_cli/pull/998))
3 changes: 3 additions & 0 deletions dds_cli/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1918,6 +1918,9 @@ def get_data(
progress=progress,
)
] = next_file

# Maintenance stopped the download: exit with the error
getter.raise_if_service_unavailable()
except (
dds_cli.exceptions.InvalidMethodError,
OSError,
Expand Down
23 changes: 23 additions & 0 deletions dds_cli/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@
class DDSBaseClass:
"""Data Delivery System base class. For common operations."""

# Set when the DDS backend answers 503 (maintenance), see 'stop_for_maintenance'
service_unavailable: typing.Optional[exceptions.ServiceUnavailableError] = None

def __init__(
self,
project=None,
Expand Down Expand Up @@ -117,6 +120,26 @@ def __exit__(self, exception_type, exception_value, traceback, max_fileerrs: int

# Public methods ############################### Public methods #

def stop_for_maintenance(self, err: exceptions.ServiceUnavailableError) -> None:
"""Stop the delivery because the DDS backend is unavailable (e.g. maintenance).

Called from the worker threads. Files not yet started are cancelled (same flag
as Ctrl+C). Ongoing downloads stop at the next chunk, ongoing uploads stop
before the S3 upload; an S3 upload that has already started is finished.
The caller marks its own file as failed, so it is saved in the failed
delivery log as usual.
Call 'raise_if_service_unavailable' after the threads are done.
"""
if self.service_unavailable is None:
self.service_unavailable = err
LOG.error("%s. Stopping: files not started yet are cancelled.", str(err).rstrip("."))
self.stop_doing = True

def raise_if_service_unavailable(self) -> None:
"""Raise the error saved by 'stop_for_maintenance', if any."""
if self.service_unavailable is not None:
raise self.service_unavailable

def set_token(self, token_dict: dict) -> None:
"""Sets the token for the base class.
Called from auth class to set the token when authenticating
Expand Down
11 changes: 11 additions & 0 deletions dds_cli/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,15 @@
TODO: Move other constants here from __init__.py.
"""

# perform_request_with_retry retries once on an answer with one of these status codes
# AND without a JSON body (NonJsonResponseError). Such an answer comes from the proxy
# (Traefik), not from the DDS API: a 502 there usually means the backend closed an idle
# connection, i.e. the request did not reach the backend.
# The status code alone is not enough: a 503 WITH a JSON body comes from the DDS API
# (maintenance, ServiceUnavailableError) and must never be retried.
API_NON_JSON_RETRY_STATUS_CODES = (502, 503)
API_RETRY_WAIT = 1 # seconds

# Timeout settings for upload and download
READ_TIMEOUT = 300
CONNECT_TIMEOUT = 60
Expand All @@ -17,6 +26,8 @@

# Import these constants when using '*'
__all__ = [
"API_NON_JSON_RETRY_STATUS_CODES",
"API_RETRY_WAIT",
"READ_TIMEOUT",
"CONNECT_TIMEOUT",
"DOWNLOAD_MAX_RETRIES",
Expand Down
9 changes: 7 additions & 2 deletions dds_cli/custom_decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,18 @@ def wrapped(self, file, *args, **kwargs):
# Check if keyboardinterrupt in dds
if self.stop_doing:
# TODO (ina): Add save to status here
message = f"KeyboardInterrupt - cancelling file {escape(file)}"
reason = (
"Service unavailable"
if getattr(self, "service_unavailable", None)
else "KeyboardInterrupt"
)
message = f"{reason} - cancelling file {escape(str(file))}"
LOG.warning(message)
return False # Do not proceed

# Return if file cancelled by another file
if self.status[file]["cancel"]:
message = f"File already cancelled, stopping file {escape(file)}"
message = f"File already cancelled, stopping file {escape(str(file))}"
LOG.warning(message)
return False

Expand Down
33 changes: 29 additions & 4 deletions dds_cli/data_getter.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,9 +257,14 @@ def get(self, file, progress, task):
backoff_factor = constants.DOWNLOAD_BACKOFF_FACTOR
wait = constants.DOWNLOAD_INITIAL_WAIT
retry_messages = []
cancelled = False

for attempt in range(1, max_retries + 1):
error = ""
if self.service_unavailable:
# Maintenance seen by another thread: don't start a new attempt.
cancelled = True
break
if attempt > 1:
progress.reset(task, completed=0)
# Drop the partial file from the previous attempt before retrying.
Expand Down Expand Up @@ -287,10 +292,17 @@ def get(self, file, progress, task):
content_length = 0
with file_local.open(mode="wb") as new_file:
for chunk in req.iter_content(chunk_size=FileSegment.SEGMENT_SIZE_CIPHER):
if self.service_unavailable:
# Maintenance seen by another thread: stop this download.
cancelled = True
break
progress.update(task, advance=len(chunk))
new_file.write(chunk)
bytes_written += len(chunk)

if cancelled:
break

# Guard against silent truncation: requests/urllib3 do not
# validate that bytes received == Content-Length. A clean TCP
# FIN mid-stream otherwise looks like an EOF and the loop exits
Expand Down Expand Up @@ -340,7 +352,11 @@ def get(self, file, progress, task):
)
break

if not downloaded and error:
if cancelled:
error = f"Service unavailable - download of '{file_name_in_db}' cancelled"
LOG.warning(error)
self._remove_partial(file_local, file_name_in_db)
elif not downloaded and error:
if retry_messages:
error = " | ".join(retry_messages) + f" | Final error: {error}"
LOG.error(
Expand Down Expand Up @@ -387,17 +403,26 @@ def update_db(self, file):
filename = {"name": fileinfo["name_in_db"]}
params = {"project": self.project}

# Send file info to API
# Send file info to API.
# Catch all API errors: a failed update must not stop the other downloads.
# Exception: maintenance (ServiceUnavailableError) stops the files not started yet.
try:
response_json, _ = dds_cli.utils.perform_request(
response_json, _ = dds_cli.utils.perform_request_with_retry(
DDSEndpoint.FILE_UPDATE,
method="put",
params=params,
json=filename,
headers=self.token,
error_message="Failed to update file information",
)
except dds_cli.exceptions.ApiRequestError as err:
except dds_cli.exceptions.ServiceUnavailableError as err:
self.stop_for_maintenance(err)
message = str(err)
except (
dds_cli.exceptions.ApiRequestError,
dds_cli.exceptions.ApiResponseError,
dds_cli.exceptions.DDSCLIException,
) as err:
updated_in_db = False
message = str(err)
else:
Expand Down
64 changes: 61 additions & 3 deletions dds_cli/data_putter.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,15 @@ def put(
for x in [y.id for y in progress.tasks if y.fields.get("step") != "put"]
]

# Maintenance stopped the upload: the API is down, don't call it again.
if putter.service_unavailable is not None:
if putter.failed_delivery_log.is_file():
LOG.warning(
"The files that failed are listed in: %s",
str(putter.failed_delivery_log),
)
putter.raise_if_service_unavailable()

# Make a single database update for files that have failed
# Json file for failed files should only be created if there has been an error
if putter.failed_delivery_log.is_file():
Expand Down Expand Up @@ -342,7 +351,14 @@ def protect_and_upload(self, file, progress):
file_info["path_processed"].stat().st_size,
)

if saved:
if saved and self.service_unavailable:
# Maintenance seen by another thread: don't upload. The file could not be
# added to the database, so it would only be an orphan object in the bucket.
message = f"Service unavailable - upload of '{file_path_raw}' cancelled"
LOG.warning(message)
self.status[file]["failed_op"] = "put"
dr.DataRemover.delete_tempfile(file=file_info["path_processed"])
elif saved:
LOG.debug(
"File successfully encrypted: '%s'",
file_path_raw,
Expand Down Expand Up @@ -454,7 +470,8 @@ def add_file_db(self, file):
# Send file info to API - post if new file, put if overwrite
request_method = "put" if fileinfo["overwrite"] else "post"
try:
response_json, _ = dds_cli.utils.perform_request(
# Retry once on 502/503 before we fall back to 'retry_add_file_db' at the end.
response_json, _ = dds_cli.utils.perform_request_with_retry(
DDSEndpoint.FILE_NEW,
method=request_method,
params=params,
Expand All @@ -466,16 +483,57 @@ def add_file_db(self, file):
LOG.debug("API call for file '%s: Adding to database'", fileinfo["path_raw"])
with self._db_add_lock:
self.any_successful_db_add = True
except dds_cli.exceptions.ServiceUnavailableError as err:
# Maintenance: stop the upload. Don't raise here: this file is in the bucket,
# so it must be saved in the failed delivery log ('add_file_db' failed).
self.stop_for_maintenance(err)
message = str(err)
except (
dds_cli.exceptions.ApiRequestError,
dds_cli.exceptions.ApiResponseError,
dds_cli.exceptions.DDSCLIException,
) as err:
message = str(err)
LOG.warning(message)
if request_method == "post" and self._added_by_earlier_request(file=file):
# The first POST got a proxy 502/503 but did reach the backend, so the
# retry failed because the file already exists. The file is added.
added_to_db, message = (True, f"File '{file}' added to db.")
with self._db_add_lock:
self.any_successful_db_add = True
else:
LOG.warning(message)

return added_to_db, message

def _added_by_earlier_request(self, file) -> bool:
"""Check if the file is in the database with the name in bucket of this upload.

'name_in_bucket' is new for each upload, so a match means that one of our own
requests added the file. Any error here: return False (the file stays failed).
"""
try:
response_json, _ = dds_cli.utils.perform_request(
DDSEndpoint.FILE_MATCH,
method="get",
params={"project": self.project},
headers=self.token,
json=[file],
error_message="Failed to check if the file is in the database",
)
except (
dds_cli.exceptions.ApiRequestError,
dds_cli.exceptions.ApiResponseError,
dds_cli.exceptions.DDSCLIException,
) as err:
LOG.debug("Could not check if '%s' is in the database: %s", escape(file), err)
return False

files_in_db = response_json.get("files") or {}
added = files_in_db.get(file) == self.filehandler.data[file]["path_remote"]
if added:
LOG.info("File '%s' was added to the database by an earlier request.", escape(file))
return added

def retry_add_file_db(self):
"""Attempting to save the files to the database.

Expand Down
14 changes: 14 additions & 0 deletions dds_cli/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,13 @@ def __str__(self):
return msg


class ServiceUnavailableError(DDSCLIException):
"""The DDS backend answered 503 Service Unavailable, e.g. because maintenance is ongoing.

Ongoing deliveries must stop: this is not retried and not ignored.
"""


class AuthenticationError(click.ClickException):
"""Errors due to user authentication."""

Expand Down Expand Up @@ -99,6 +106,13 @@ def __init__(self, message, status_code=None):
super().__init__(message)


class NonJsonResponseError(ApiResponseError):
"""The answer has no valid JSON body, so it did not come from the DDS API.

Usually an error page from the proxy (Traefik), e.g. 502 Bad Gateway.
"""


class UploadError(Exception):
"""Errors relating to file uploads."""

Expand Down
45 changes: 44 additions & 1 deletion dds_cli/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import http
from typing import Dict, List, Union
import logging
import time
from datetime import datetime

import requests
Expand All @@ -19,6 +20,9 @@

import dds_cli.exceptions
from dds_cli import __version__, DDSEndpoint
from dds_cli import constants

LOG = logging.getLogger(__name__)

console = rich.console.Console()
stderr_console = rich.console.Console(stderr=True)
Expand Down Expand Up @@ -239,7 +243,7 @@ def transform_paths(json_input):
)
response_json = response.json()
except simplejson.JSONDecodeError as err:
raise dds_cli.exceptions.ApiResponseError(
raise dds_cli.exceptions.NonJsonResponseError(
message=(
f"Response code: {response.status_code}. "
f"The request did not return a valid JSON response. Details: {err}"
Expand Down Expand Up @@ -298,6 +302,14 @@ def transform_paths(json_input):
message=message, status_code=response.status_code
)

# Handle 503 from the DDS backend itself, e.g. maintenance.
# (A 503 from the proxy has no JSON body and is raised as NonJsonResponseError above.)
if response.status_code == http.HTTPStatus.SERVICE_UNAVAILABLE:
raise dds_cli.exceptions.ServiceUnavailableError(
message=f"{message}: {response_json.get('message', 'Service unavailable')}",
status_code=response.status_code,
)

raise dds_cli.exceptions.DDSCLIException(
message=f"{message}: {response_json.get('message', 'Unexpected error!')}",
status_code=response.status_code,
Expand All @@ -306,6 +318,37 @@ def transform_paths(json_input):
return response_json, additional_errors


def perform_request_with_retry(*args, retries: int = 1, **kwargs):
"""Same as perform_request, but retry on a 502/503 from the proxy.

A 502 from Traefik usually means that the backend closed an idle keep-alive
connection just before the request was sent. The request did not reach the
backend, so it is safe to send it again.

Both conditions are needed for a retry:
- the answer has no JSON body (NonJsonResponseError), i.e. it is from the proxy
- the status code is in API_NON_JSON_RETRY_STATUS_CODES
A 503 from the DDS API (maintenance) has a JSON body, is raised as
ServiceUnavailableError and is never retried.
"""
for _ in range(retries):
try:
return perform_request(*args, **kwargs)
except dds_cli.exceptions.NonJsonResponseError as err:
status_code = getattr(err, "status_code", None)
if status_code not in constants.API_NON_JSON_RETRY_STATUS_CODES:
raise
LOG.warning(
"API request failed with status %s, retrying in %ss: %s",
status_code,
constants.API_RETRY_WAIT,
err,
)
time.sleep(constants.API_RETRY_WAIT)
# Last attempt: any error goes to the caller
return perform_request(*args, **kwargs)


def parse_project_errors(errors):
"""Parse all errors related to projects."""
msg = ""
Expand Down
Loading