-
Notifications
You must be signed in to change notification settings - Fork 551
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
Add s3 provider #1009
Open
dolfandringa
wants to merge
4
commits into
jupyter:main
Choose a base branch
from
dolfandringa:add_s3_provider
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Add s3 provider #1009
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
2ab493a
Added s3 provider
dolfandringa 1aada74
Added recompiled requirements.txt and some linting fixes
dolfandringa efe20a0
Added test attempt that won't work because the server is started with…
dolfandringa 25e9afa
Added docs in readme file
dolfandringa File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
from .handlers import default_handlers | ||
from .handlers import S3Handler | ||
from .handlers import uri_rewrites |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,149 @@ | ||
# ----------------------------------------------------------------------------- | ||
# Copyright (C) Jupyter Development Team | ||
# | ||
# Distributed under the terms of the BSD License. The full license is in | ||
# the file COPYING, distributed as part of this software. | ||
# ----------------------------------------------------------------------------- | ||
import errno | ||
import io | ||
import os | ||
from datetime import datetime | ||
from urllib.parse import urlparse | ||
|
||
import boto3 | ||
import botocore | ||
from tornado import iostream | ||
from tornado import web | ||
|
||
from .. import _load_handler_from_location | ||
from ...utils import url_path_join | ||
from ..base import cached | ||
from ..base import RenderingHandler | ||
|
||
|
||
class S3Handler(RenderingHandler): | ||
"""Renderer for s3:// | ||
|
||
Serving notebooks from S3 buckets | ||
""" | ||
|
||
def initialize(self, **kwargs): | ||
self.s3_client = boto3.client("s3") | ||
self._downloadable_data = None | ||
self._downloaded_path = None | ||
super().initialize(**kwargs) | ||
|
||
async def download(self, path): | ||
"""Download the notebook""" | ||
headers = await self.get_notebook_headers(path) | ||
filename = os.path.basename(path) | ||
self.set_header("Content-Length", headers["ContentLength"]) | ||
# Escape commas to workaround Chrome issue with commas in download filenames | ||
self.set_header( | ||
"Content-Disposition", | ||
"attachment; filename={};".format(filename.replace(",", "_")), | ||
) | ||
if self._downloaded_path == path and self._downloadable_data is not None: | ||
content = self._downloadable_data | ||
else: | ||
content = await self.read_s3_file(path) | ||
|
||
if isinstance(content, bytes): | ||
content = [content] | ||
for chunk in content: | ||
try: | ||
self.write(chunk) | ||
await self.flush() | ||
except iostream.StreamClosedError: | ||
return | ||
|
||
async def get_notebook_data(self, path): | ||
"""Get additional notebook data""" | ||
is_download = self.get_query_arguments("download") | ||
if is_download: | ||
await self.download(path) | ||
return | ||
|
||
return path | ||
|
||
async def get_notebook_headers(self, path): | ||
"""Get the size of a notebook file.""" | ||
o = urlparse(path) | ||
bucket = o.netloc | ||
key = o.path[1:] | ||
self.log.debug("Getting headers for %s from %s", key, bucket) | ||
try: | ||
head = self.s3_client.head_object(Bucket=bucket, Key=key) | ||
except botocore.exceptions.ClientError as ex: | ||
if ex.response["Error"]["Code"] == "404": | ||
self.log.info("The notebook %s does not exist.", path) | ||
raise web.HTTPError(404) | ||
raise ex | ||
return head | ||
|
||
async def read_s3_file(self, path): | ||
"""Download the notebook file from s3.""" | ||
o = urlparse(path) | ||
bucket = o.netloc | ||
key = o.path[1:] | ||
s3_file = io.BytesIO() | ||
self.log.debug("Reading %s from %s", key, bucket) | ||
try: | ||
self.s3_client.download_fileobj(bucket, key, s3_file) | ||
except botocore.exceptions.ClientError as ex: | ||
if ex.response["Error"]["Code"] == "404": | ||
self.log.info("The notebook %s does not exist.", path) | ||
raise web.HTTPError(404) | ||
raise ex | ||
s3_file.seek(0) | ||
self.log.debug("Done downloading.") | ||
self._downloadable_data = s3_file.read().decode("utf-8") | ||
self._downloaded_path = path | ||
return self._downloadable_data | ||
|
||
async def deliver_notebook(self, path): | ||
nbdata = await self.read_s3_file(path) | ||
|
||
# Explanation of some kwargs passed into `finish_notebook`: | ||
# breadcrumbs: list of dict | ||
# Breadcrumb 'name' and 'url' to render as links at the top of the notebook page | ||
# title: str | ||
# Title to use as the HTML page title (i.e., text on the browser tab) | ||
await self.finish_notebook( | ||
nbdata, | ||
download_url="?download", | ||
msg="file from s3: %s" % path, | ||
public=False, | ||
breadcrumbs=[], | ||
title=os.path.basename(path), | ||
) | ||
|
||
@cached | ||
async def get(self, path): | ||
"""Get an s3 notebook | ||
|
||
Parameters | ||
========== | ||
path: str | ||
s3 uri | ||
""" | ||
fullpath = await self.get_notebook_data(path) | ||
|
||
# get_notebook_data returns None if a directory is to be shown or a notebook is to be downloaded, | ||
# i.e. if no notebook is supposed to be rendered, making deliver_notebook inappropriate | ||
if fullpath is not None: | ||
await self.deliver_notebook(fullpath) | ||
|
||
|
||
def default_handlers(handlers=[], **handler_names): | ||
"""Tornado handlers""" | ||
|
||
s3_handler = _load_handler_from_location(handler_names["s3_handler"]) | ||
|
||
return handlers + [(r"/(s3%3A//.*)", s3_handler, {})] | ||
|
||
|
||
def uri_rewrites(rewrites=[]): | ||
return [ | ||
(r"^(s3://.*)$", "{0}"), | ||
] |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,96 @@ | ||
# ----------------------------------------------------------------------------- | ||
# Copyright (C) Jupyter Development Team | ||
# | ||
# Distributed under the terms of the BSD License. The full license is in | ||
# the file COPYING, distributed as part of this software. | ||
# ----------------------------------------------------------------------------- | ||
import io | ||
import json | ||
from copy import deepcopy | ||
from unittest.mock import patch | ||
|
||
import boto3 | ||
import requests | ||
|
||
from ....tests.base import FormatHTMLMixin | ||
from ....tests.base import NBViewerTestCase | ||
|
||
|
||
MOCK_NOTEBOOK = { | ||
"cells": [ | ||
{ | ||
"cell_type": "code", | ||
"execution_count": None, | ||
"id": "b0939771-a810-4ee0-b440-dbbaeb4f1653", | ||
"metadata": {}, | ||
"outputs": [], | ||
"source": [], | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": None, | ||
"id": "cc0d476a-d09c-4919-8dd2-c8d67f7431b3", | ||
"metadata": {}, | ||
"outputs": [], | ||
"source": [], | ||
}, | ||
], | ||
"metadata": { | ||
"kernelspec": { | ||
"display_name": "Python 3 (ipykernel)", | ||
"language": "python", | ||
"name": "python3", | ||
}, | ||
"language_info": { | ||
"codemirror_mode": {"name": "ipython", "version": 3}, | ||
"file_extension": ".py", | ||
"mimetype": "text/x-python", | ||
"name": "python", | ||
"nbconvert_exporter": "python", | ||
"pygments_lexer": "ipython3", | ||
"version": "3.9.12", | ||
}, | ||
}, | ||
"nbformat": 4, | ||
"nbformat_minor": 5, | ||
} | ||
|
||
|
||
class MockBoto3: | ||
def download_fileobj(self, Bucket, Key, fileobj): | ||
"""Mock downloading fileobjects""" | ||
data = deepcopy(MOCK_NOTEBOOK) | ||
data["cells"][0]["source"] = [f"print({Bucket})", f"print({Key})"] | ||
bin_data = json.dumps(data).encode("utf-8") | ||
fileobj.write(bin_data) | ||
|
||
def head_object(self, Bucket, Key): | ||
"""Mock getting key headers""" | ||
output_file = io.BytesIO() | ||
f = self.download_fileobj(Bucket, Key, output_file) | ||
f.seek(0) | ||
return {"ContentLength": len(f.read())} | ||
|
||
|
||
""" | ||
# This test won't work because the server is started through subprocess.POpen, so we can't mock boto3. | ||
|
||
class S3TestCase(NBViewerTestCase): | ||
|
||
@patch("boto3.client") | ||
def test_url(self, mock_boto3_client): | ||
mockBoto3 = MockBoto3() | ||
mock_boto3_client.return_value = mockBoto3 | ||
with patch.object(mockBoto3, 'download_fileobj') as mock_download: | ||
bucket="my_bucket" | ||
key="my_file.ipynb" | ||
url = self.url(f"s3%3A//{bucket}/{key}") | ||
r = requests.get(url) | ||
self.assertEqual(r.status_code, 200) | ||
args = mock_download.call_args_list[-1][:2] | ||
self.assertEqual(args, (bucket, key)) | ||
|
||
|
||
class FormatHTMLLocalFileDefaultTestCase(S3TestCase, FormatHTMLMixin): | ||
pass | ||
""" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I wanted to prevent re-fetching the file from s3. Maybe there is a beter way to cache the boto3 s3 transfer using memcached somehow. Any suggestions are welcome.