Skip to content

747 robustranged download support #759

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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
4 changes: 4 additions & 0 deletions openeo/rest/_testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,10 @@ def __init__(
requests_mock.delete(
re.compile(connection.build_url(r"/jobs/(job-\d+)/results$")), json=self._handle_delete_job_results
)
requests_mock.head(
re.compile(connection.build_url("/jobs/(.*?)/results/result.data$")),
headers={"Content-Length": "666"}
)
requests_mock.get(
re.compile(connection.build_url("/jobs/(.*?)/results/result.data$")),
content=self._handle_get_job_result_asset,
Expand Down
63 changes: 54 additions & 9 deletions openeo/rest/job.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@
import datetime
import json
import logging
import re
import time
import typing
from pathlib import Path
from typing import Dict, List, Optional, Union

import requests
import shutil

from openeo.internal.documentation import openeo_endpoint
from openeo.internal.jupyter import (
Expand Down Expand Up @@ -40,7 +42,8 @@


DEFAULT_JOB_RESULTS_FILENAME = "job-results.json"

MAX_RETRIES_PER_CHUNK = 3
RETRIABLE_STATUSCODES = [408, 429, 500, 501, 502, 503, 504]

class BatchJob:
"""
Expand Down Expand Up @@ -402,10 +405,7 @@ def download(
target = target / self.name
ensure_dir(target.parent)
logger.info("Downloading Job result asset {n!r} from {h!s} to {t!s}".format(n=self.name, h=self.href, t=target))
response = self._get_response(stream=True)
with target.open("wb") as f:
for block in response.iter_content(chunk_size=chunk_size):
f.write(block)
_download_chunked(self.href, target, chunk_size)
return target

def _get_response(self, stream=True) -> requests.Response:
Expand All @@ -424,6 +424,51 @@ def load_bytes(self) -> bytes:
# TODO: more `load` methods e.g.: load GTiff asset directly as numpy array


def _download_chunked(url: str, target: Path, chunk_size: int):
try:
file_size = _determine_content_length(url)
with target.open('wb') as f:
for from_byte_index in range(0, file_size, chunk_size):
to_byte_index = min(from_byte_index + chunk_size - 1, file_size - 1)
tries_left = MAX_RETRIES_PER_CHUNK
while tries_left > 0:
try:
range_headers = {"Range": f"bytes={from_byte_index}-{to_byte_index}"}
with requests.get(url, headers=range_headers, stream=True) as r:
if r.ok:
shutil.copyfileobj(r.raw, f)
break
else:
r.raise_for_status()
except requests.exceptions.HTTPError as error:
tries_left -= 1
if tries_left > 0 and error.response.status_code in RETRIABLE_STATUSCODES:
logger.warning(f"Failed to retrieve chunk {from_byte_index}-{to_byte_index} from {url} (status {error.response.status_code}) - retrying")
continue
else:
raise error
except requests.exceptions.HTTPError as http_error:
raise OpenEoApiPlainError(message=f"Failed to download {url}", http_status_code=http_error.response.status_code, error_message=http_error.response.text)


def _determine_content_length(url: str) -> int:
range_0_0_response = requests.get(url, headers={"Range": f"bytes=0-0"})
if range_0_0_response.status_code == 206:
content_range_header = range_0_0_response.headers.get("Content-Range")
match = re.match(r"^bytes \d+-\d+/(\d+)$", content_range_header)
if match:
return int(match.group(1))

content_range_prefix = "bytes 0-0/"
if content_range_header.startswith(content_range_prefix):
return int(content_range_header[len(content_range_prefix):])
head = requests.head(url, stream=True)
if head.ok:
return int(head.headers['Content-Length'])
else:
head.raise_for_status()


class MultipleAssetException(OpenEoClientException):
pass

Expand Down Expand Up @@ -501,7 +546,7 @@ def get_asset(self, name: str = None) -> ResultAsset:
"No asset {n!r} in: {a}".format(n=name, a=[a.name for a in assets])
)

def download_file(self, target: Union[Path, str] = None, name: str = None) -> Path:
def download_file(self, target: Union[Path, str] = None, name: str = None, chunk_size=DEFAULT_DOWNLOAD_CHUNK_SIZE) -> Path:
"""
Download single asset. Can be used when there is only one asset in the
:py:class:`JobResults`, or when the desired asset name is given explicitly.
Expand All @@ -513,12 +558,12 @@ def download_file(self, target: Union[Path, str] = None, name: str = None) -> Pa
:return: path of downloaded asset
"""
try:
return self.get_asset(name=name).download(target=target)
return self.get_asset(name=name).download(target=target, chunk_size=chunk_size)
except MultipleAssetException:
raise OpenEoClientException(
"Can not use `download_file` with multiple assets. Use `download_files` instead.")

def download_files(self, target: Union[Path, str] = None, include_stac_metadata: bool = True) -> List[Path]:
def download_files(self, target: Union[Path, str] = None, include_stac_metadata: bool = True, chunk_size=DEFAULT_DOWNLOAD_CHUNK_SIZE) -> List[Path]:
"""
Download all assets to given folder.

Expand All @@ -531,7 +576,7 @@ def download_files(self, target: Union[Path, str] = None, include_stac_metadata:
raise OpenEoClientException(f"Target argument {target} exists but isn't a folder.")
ensure_dir(target)

downloaded = [a.download(target) for a in self.get_assets()]
downloaded = [a.download(target, chunk_size=chunk_size) for a in self.get_assets()]

if include_stac_metadata:
# TODO #184: convention for metadata file name?
Expand Down
89 changes: 80 additions & 9 deletions tests/rest/test_job.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import inspect
import itertools
import json
import logging
Expand All @@ -11,16 +12,14 @@

import openeo
import openeo.rest.job
from openeo.rest import JobFailedException, OpenEoApiPlainError, OpenEoClientException
from openeo.rest import JobFailedException, OpenEoApiPlainError, OpenEoClientException, DEFAULT_DOWNLOAD_CHUNK_SIZE
from openeo.rest.job import BatchJob, ResultAsset
from openeo.rest.models.general import Link
from openeo.rest.models.logs import LogEntry

API_URL = "https://oeo.test"

TIFF_CONTENT = b'T1f7D6t6l0l' * 1000


TIFF_CONTENT = b'T1f7D6t6l0l' * 10000

@pytest.fixture
def con100(requests_mock):
Expand Down Expand Up @@ -74,7 +73,7 @@ def test_execute_batch(con100, requests_mock, tmpdir):
}
},
)
requests_mock.get(API_URL + "/jobs/f00ba5/files/output.tiff", text="tiffdata")
_mock_get_head_content(requests_mock, API_URL + "/jobs/f00ba5/files/output.tiff", "tiffdata")
requests_mock.get(API_URL + "/jobs/f00ba5/logs", json={'logs': []})

path = tmpdir.join("tmp.tiff")
Expand Down Expand Up @@ -231,7 +230,8 @@ def test_execute_batch_with_soft_errors(con100, requests_mock, tmpdir, error_res
}
},
)
requests_mock.get(API_URL + "/jobs/f00ba5/files/output.tiff", text="tiffdata")
_mock_get_head_content(requests_mock, API_URL + "/jobs/f00ba5/files/output.tiff", "tiffdata")
# requests_mock.get(API_URL + "/jobs/f00ba5/files/output.tiff", text="tiffdata")
requests_mock.get(API_URL + "/jobs/f00ba5/logs", json={'logs': []})

path = tmpdir.join("tmp.tiff")
Expand Down Expand Up @@ -536,10 +536,49 @@ def job_with_1_asset(con100, requests_mock, tmp_path) -> BatchJob:
requests_mock.get(API_URL + "/jobs/jj1/results", json={"assets": {
"1.tiff": {"href": API_URL + "/dl/jjr1.tiff", "type": "image/tiff; application=geotiff"},
}})
requests_mock.head(API_URL + "/dl/jjr1.tiff", headers={"Content-Length": f"{len(TIFF_CONTENT)}"})
requests_mock.get(API_URL + "/dl/jjr1.tiff", content=TIFF_CONTENT)

job = BatchJob("jj1", connection=con100)
return job

@pytest.fixture
def job_with_chunked_asset_using_head(con100, requests_mock, tmp_path) -> BatchJob:
requests_mock.get(API_URL + "/jobs/jj1/results", json={"assets": {
"1.tiff": {"href": API_URL + "/dl/jjr1.tiff", "type": "image/tiff; application=geotiff"},
}})
requests_mock.head(API_URL + "/dl/jjr1.tiff", headers={"Content-Length": f"{len(TIFF_CONTENT)}"})

chunk_size = 1000
for r in range(0, len(TIFF_CONTENT), chunk_size):
from_bytes = r
to_bytes = min(r + chunk_size, len(TIFF_CONTENT)) - 1
# fail the 1st time, serve the content chunk the 2nd time
requests_mock.get(API_URL + "/dl/jjr1.tiff", request_headers={"Range": "bytes=0-0"},
response_list=[{"status_code": 404, "text": "Not found"}])
requests_mock.get(API_URL + "/dl/jjr1.tiff", request_headers={"Range": f"bytes={from_bytes}-{to_bytes}"},
response_list = [{"status_code": 500, "text": "Server error"},
{"status_code": 206, "content": TIFF_CONTENT[from_bytes:to_bytes+1]}])
job = BatchJob("jj1", connection=con100)
return job

@pytest.fixture
def job_with_chunked_asset_using_get_0_0(con100, requests_mock, tmp_path) -> BatchJob:
requests_mock.get(API_URL + "/jobs/jj1/results", json={"assets": {
"1.tiff": {"href": API_URL + "/dl/jjr1.tiff", "type": "image/tiff; application=geotiff"},
}})
requests_mock.get(API_URL + "/dl/jjr1.tiff", request_headers={"Range": "bytes=0-0"},
response_list=[{"status_code": 206, "text": "", "headers": {"Content-Range": f"bytes 0-0/{len(TIFF_CONTENT)}"}}])
chunk_size = 1000
for r in range(0, len(TIFF_CONTENT), chunk_size):
from_bytes = r
to_bytes = min(r + chunk_size, len(TIFF_CONTENT)) - 1
# fail the 1st time, serve the content chunk the 2nd time
requests_mock.get(API_URL + "/dl/jjr1.tiff", request_headers={"Range": f"bytes={from_bytes}-{to_bytes}"},
response_list = [{"status_code": 408, "text": "Server error"},
{"status_code": 206, "content": TIFF_CONTENT[from_bytes:to_bytes+1]}])
job = BatchJob("jj1", connection=con100)
return job

@pytest.fixture
def job_with_2_assets(con100, requests_mock, tmp_path) -> BatchJob:
Expand All @@ -551,8 +590,11 @@ def job_with_2_assets(con100, requests_mock, tmp_path) -> BatchJob:
"2.tiff": {"href": API_URL + "/dl/jjr2.tiff", "type": "image/tiff; application=geotiff"},
}
})
requests_mock.head(API_URL + "/dl/jjr1.tiff", headers={"Content-Length": f"{len(TIFF_CONTENT)}"})
requests_mock.get(API_URL + "/dl/jjr1.tiff", content=TIFF_CONTENT)
requests_mock.head(API_URL + "/dl/jjr2.tiff", headers={"Content-Length": f"{len(TIFF_CONTENT)}"})
requests_mock.get(API_URL + "/dl/jjr2.tiff", content=TIFF_CONTENT)

job = BatchJob("jj2", connection=con100)
return job

Expand All @@ -574,6 +616,21 @@ def test_get_results_download_file(job_with_1_asset: BatchJob, tmp_path):
with target.open("rb") as f:
assert f.read() == TIFF_CONTENT

def test_get_results_download_chunked_file_using_get_0_0(job_with_chunked_asset_using_get_0_0: BatchJob, tmp_path):
job = job_with_chunked_asset_using_get_0_0
target = tmp_path / "result.tiff"
res = job.get_results().download_file(target, chunk_size=1000)
assert res == target
with target.open("rb") as f:
assert f.read() == TIFF_CONTENT

def test_get_results_download_chunked_file_using_head(job_with_chunked_asset_using_head: BatchJob, tmp_path):
job = job_with_chunked_asset_using_head
target = tmp_path / "result.tiff"
res = job.get_results().download_file(target, chunk_size=1000)
assert res == target
with target.open("rb") as f:
assert f.read() == TIFF_CONTENT

def test_download_result_folder(job_with_1_asset: BatchJob, tmp_path):
job = job_with_1_asset
Expand Down Expand Up @@ -714,7 +771,7 @@ def test_get_results_download_files_include_stac_metadata(

def test_result_asset_download_file(con100, requests_mock, tmp_path):
href = API_URL + "/dl/jjr1.tiff"
requests_mock.get(href, content=TIFF_CONTENT)
_mock_get_head_content(requests_mock, href, TIFF_CONTENT)

job = BatchJob("jj", connection=con100)
asset = ResultAsset(job, name="1.tiff", href=href, metadata={'type': 'image/tiff; application=geotiff'})
Expand All @@ -729,6 +786,7 @@ def test_result_asset_download_file(con100, requests_mock, tmp_path):

def test_result_asset_download_file_error(con100, requests_mock, tmp_path):
href = API_URL + "/dl/jjr1.tiff"
requests_mock.head(href, status_code=500, text="Nope!")
requests_mock.get(href, status_code=500, text="Nope!")

job = BatchJob("jj", connection=con100)
Expand All @@ -743,7 +801,7 @@ def test_result_asset_download_file_error(con100, requests_mock, tmp_path):

def test_result_asset_download_folder(con100, requests_mock, tmp_path):
href = API_URL + "/dl/jjr1.tiff"
requests_mock.get(href, content=TIFF_CONTENT)
_mock_get_head_content(requests_mock, href, TIFF_CONTENT)

job = BatchJob("jj", connection=con100)
asset = ResultAsset(job, name="1.tiff", href=href, metadata={"type": "image/tiff; application=geotiff"})
Expand All @@ -770,7 +828,7 @@ def test_result_asset_load_json(con100, requests_mock):

def test_result_asset_load_bytes(con100, requests_mock):
href = API_URL + "/dl/jjr1.tiff"
requests_mock.get(href, content=TIFF_CONTENT)
_mock_get_head_content(requests_mock, href, TIFF_CONTENT)

job = BatchJob("jj", connection=con100)
asset = ResultAsset(job, name="out.tiff", href=href, metadata={"type": "image/tiff; application=geotiff"})
Expand All @@ -797,6 +855,7 @@ def download_tiff(request, context):
return TIFF_CONTENT

requests_mock.get(API_URL + "/jobs/jj1/results", json=get_results)
requests_mock.head("https://evilcorp.test/dl/jjr1.tiff", headers={"Content-Length": "666"})
requests_mock.get("https://evilcorp.test/dl/jjr1.tiff", content=download_tiff)

con100.authenticate_basic("john", "j0hn")
Expand Down Expand Up @@ -880,3 +939,15 @@ def get_jobs(request, context):
assert jobs.links == [Link(rel="next", href="https://oeo.test/jobs?limit=2&offset=2")]
assert jobs.ext_federation_missing() == ["oeob"]
assert "Partial job listing: missing federation components: ['oeob']." in caplog.text


def _mock_get_head_content(requests_mock, url: str, content):
if callable(content):
requests_mock.head(url, headers={"Content-Length": "666"})
requests_mock.get(url, content=content)
elif type(content) == str:
requests_mock.head(url, headers={"Content-Length": f"{len(content)}"})
requests_mock.get(url, text=content)
else:
requests_mock.head(url, headers={"Content-Length": f"{len(content)}"})
requests_mock.get(url, content=content)