#22 blackened code

This commit is contained in:
Alok Saldanha
2020-08-10 17:56:32 -04:00
parent 63cdfe1953
commit bfa80f7ef8
15 changed files with 295 additions and 151 deletions
+6 -2
View File
@@ -22,8 +22,10 @@ process_backend = SubprocessBackend()
def is_port_in_use(port): def is_port_in_use(port):
import socket import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
return s.connect_ex(('localhost', port)) == 0 return s.connect_ex(("localhost", port)) == 0
class BackendCache: class BackendCache:
def __init__(self): def __init__(self):
@@ -38,7 +40,9 @@ class BackendCache:
matches = [ matches = [
c c
for c in contents for c in contents
if c.key.dataset == key.dataset and c.key.annotation_file == key.annotation_file and c.status != "terminated" if c.key.dataset == key.dataset
and c.key.annotation_file == key.annotation_file
and c.status != "terminated"
] ]
if len(matches) == 0: if len(matches) == 0:
+31 -34
View File
@@ -18,6 +18,7 @@ from cellxgene_gateway.cellxgene_exception import CellxgeneException
from cellxgene_gateway.util import current_time_stamp from cellxgene_gateway.util import current_time_stamp
from cellxgene_gateway.flask_util import querystring from cellxgene_gateway.flask_util import querystring
class CacheEntry: class CacheEntry:
def __init__( def __init__(
self, self,
@@ -79,8 +80,10 @@ class CacheEntry:
pid = self.pid pid = self.pid
if pid != None and self.status != "terminated": if pid != None and self.status != "terminated":
terminated = [] terminated = []
def on_terminate(p): def on_terminate(p):
terminated.append(p.pid) terminated.append(p.pid)
p = psutil.Process(pid) p = psutil.Process(pid)
children = p.children() children = p.children()
for child in children: for child in children:
@@ -89,44 +92,46 @@ class CacheEntry:
terminated.append(p.pid) terminated.append(p.pid)
p.terminate() p.terminate()
psutil.wait_procs([p], callback=on_terminate) psutil.wait_procs([p], callback=on_terminate)
logging.getLogger("cellxgene_gateway").info(f"terminated {terminated}") logging.getLogger("cellxgene_gateway").info(
f"terminated {terminated}"
)
self.status = "terminated" self.status = "terminated"
def serve_content(self, path): def serve_content(self, path):
gateway_basepath = ( gateway_basepath = f"{env.external_protocol}://{env.external_host}/view/{self.key.pathpart}/"
f"{env.external_protocol}://{env.external_host}/view/{self.key.pathpart}/"
)
subpath = path[len(self.key.pathpart) :] # noqa: E203 subpath = path[len(self.key.pathpart) :] # noqa: E203
if len(subpath) == 0: if len(subpath) == 0:
r = make_response(f"Redirect to {gateway_basepath}\n", 301) r = make_response(f"Redirect to {gateway_basepath}\n", 301)
r.headers["location"] = gateway_basepath+querystring() r.headers["location"] = gateway_basepath + querystring()
return r return r
elif self.status == "loading": elif self.status == "loading":
launch_time = datetime.datetime.fromtimestamp(self.launchtime) launch_time = datetime.datetime.fromtimestamp(self.launchtime)
return render_template( return render_template(
"loading.html", launchtime=launch_time, all_output=self.all_output "loading.html",
launchtime=launch_time,
all_output=self.all_output,
) )
port = self.port port = self.port
cellxgene_basepath = f"http://127.0.0.1:{port}" cellxgene_basepath = f"http://127.0.0.1:{port}"
headers = {} headers = {}
copy_headers = [ copy_headers = [
'accept', "accept",
'accept-encoding', "accept-encoding",
'accept-language', "accept-language",
'cache-control', "cache-control",
'connection', "connection",
'content-length', "content-length",
'content-type', "content-type",
'cookie', "cookie",
'host', "host",
'origin', "origin",
'pragma', "pragma",
'referer', "referer",
'sec-fetch-mode', "sec-fetch-mode",
'sec-fetch-site', "sec-fetch-site",
'user-agent' "user-agent",
] ]
for h in copy_headers: for h in copy_headers:
if h in request.headers: if h in request.headers:
@@ -135,20 +140,14 @@ class CacheEntry:
full_path = cellxgene_basepath + subpath + querystring() full_path = cellxgene_basepath + subpath + querystring()
if request.method in ["GET", "HEAD", "OPTIONS"]: if request.method in ["GET", "HEAD", "OPTIONS"]:
cellxgene_response = get( cellxgene_response = get(full_path, headers=headers)
full_path, headers=headers
)
elif request.method == "PUT": elif request.method == "PUT":
cellxgene_response = put( cellxgene_response = put(
full_path, full_path, headers=headers, data=request.data,
headers=headers,
data=request.data,
) )
elif request.method == "POST": elif request.method == "POST":
cellxgene_response = post( cellxgene_response = post(
full_path, full_path, headers=headers, data=request.data,
headers=headers,
data=request.data,
) )
else: else:
raise CellxgeneException( raise CellxgeneException(
@@ -169,9 +168,7 @@ class CacheEntry:
resp_headers[h] = cellxgene_response.headers[h] resp_headers[h] = cellxgene_response.headers[h]
gateway_response = make_response( gateway_response = make_response(
gateway_content, gateway_content, cellxgene_response.status_code, resp_headers,
cellxgene_response.status_code,
resp_headers,
) )
return gateway_response return gateway_response
+1
View File
@@ -22,6 +22,7 @@ from cellxgene_gateway.cellxgene_exception import CellxgeneException
# 3) somedir/dataset_annotations: an annotation directory. The corresponding h5ad must exist, but the directory may not. # 3) somedir/dataset_annotations: an annotation directory. The corresponding h5ad must exist, but the directory may not.
# in this case, pathpart == 'dataset_annotations', dataset == 'somedir/dataset.h5ad' # in this case, pathpart == 'dataset_annotations', dataset == 'somedir/dataset.h5ad'
class CacheKey: class CacheKey:
def __init__(self, pathpart, dataset, annotation_file): def __init__(self, pathpart, dataset, annotation_file):
self.pathpart = pathpart self.pathpart = pathpart
+8 -3
View File
@@ -51,8 +51,13 @@ def create_dir(parent_path, dir_name):
else: else:
os.mkdir(full_path) os.mkdir(full_path)
annotations_suffix = '_annotations'
annotations_suffix = "_annotations"
def make_h5ad(el): def make_h5ad(el):
return el[:-len(annotations_suffix)]+'.h5ad' return el[: -len(annotations_suffix)] + ".h5ad"
def make_annotations(el): def make_annotations(el):
return el[:-5]+annotations_suffix return el[:-5] + annotations_suffix
+24 -7
View File
@@ -14,14 +14,26 @@ import socket
cellxgene_location = os.environ.get("CELLXGENE_LOCATION") cellxgene_location = os.environ.get("CELLXGENE_LOCATION")
cellxgene_data = os.environ.get("CELLXGENE_DATA") cellxgene_data = os.environ.get("CELLXGENE_DATA")
gateway_port = int(os.environ.get("GATEWAY_PORT", "5005")) gateway_port = int(os.environ.get("GATEWAY_PORT", "5005"))
external_host = os.environ.get("EXTERNAL_HOST", os.environ.get("GATEWAY_HOST", f"localhost:{gateway_port}")) external_host = os.environ.get(
external_protocol = os.environ.get("EXTERNAL_PROTOCOL", os.environ.get("GATEWAY_PROTOCOL", "http")) "EXTERNAL_HOST",
os.environ.get("GATEWAY_HOST", f"localhost:{gateway_port}"),
)
external_protocol = os.environ.get(
"EXTERNAL_PROTOCOL", os.environ.get("GATEWAY_PROTOCOL", "http")
)
ip = os.environ.get("GATEWAY_IP") ip = os.environ.get("GATEWAY_IP")
extra_scripts = os.environ.get("GATEWAY_EXTRA_SCRIPTS") extra_scripts = os.environ.get("GATEWAY_EXTRA_SCRIPTS")
ttl = os.environ.get("GATEWAY_TTL") ttl = os.environ.get("GATEWAY_TTL")
enable_upload = os.environ.get("GATEWAY_ENABLE_UPLOAD", "").lower() in ['true', '1'] enable_upload = os.environ.get("GATEWAY_ENABLE_UPLOAD", "").lower() in [
enable_annotations = os.environ.get("GATEWAY_ENABLE_ANNOTATIONS", "").lower() in ['true', '1'] "true",
enable_backed_mode = os.environ.get("GATEWAY_ENABLE_BACKED_MODE", "").lower() in ['true', '1'] "1",
]
enable_annotations = os.environ.get(
"GATEWAY_ENABLE_ANNOTATIONS", ""
).lower() in ["true", "1"]
enable_backed_mode = os.environ.get(
"GATEWAY_ENABLE_BACKED_MODE", ""
).lower() in ["true", "1"]
env_vars = { env_vars = {
"CELLXGENE_LOCATION": cellxgene_location, "CELLXGENE_LOCATION": cellxgene_location,
@@ -40,6 +52,7 @@ optional_env_vars = {
"GATEWAY_ENABLE_BACKED_MODE": enable_backed_mode, "GATEWAY_ENABLE_BACKED_MODE": enable_backed_mode,
} }
def validate(): def validate():
if not all(env_vars.values()): if not all(env_vars.values()):
raise ValueError( raise ValueError(
@@ -58,5 +71,9 @@ def validate():
""" """
) )
else: else:
logging.getLogger("cellxgene_gateway").info(f"Got required env: {env_vars}", ) logging.getLogger("cellxgene_gateway").info(
logging.getLogger("cellxgene_gateway").info(f"Got optional env: {optional_env_vars}") f"Got required env: {env_vars}",
)
logging.getLogger("cellxgene_gateway").info(
f"Got optional env: {optional_env_vars}"
)
+49 -13
View File
@@ -9,7 +9,12 @@
import os import os
from cellxgene_gateway import env from cellxgene_gateway import env
from cellxgene_gateway.dir_util import make_h5ad, make_annotations, annotations_suffix from cellxgene_gateway.dir_util import (
make_h5ad,
make_annotations,
annotations_suffix,
)
def recurse_dir(path): def recurse_dir(path):
if not os.path.exists(path): if not os.path.exists(path):
@@ -18,21 +23,42 @@ def recurse_dir(path):
) )
all_entries = sorted(os.listdir(path)) all_entries = sorted(os.listdir(path))
def is_h5ad(el): def is_h5ad(el):
return el.endswith('.h5ad') and os.path.isfile(os.path.join(path, el)) return el.endswith(".h5ad") and os.path.isfile(os.path.join(path, el))
h5ad_entries = [x for x in all_entries if is_h5ad(x)] h5ad_entries = [x for x in all_entries if is_h5ad(x)]
annotation_dir_entries = [x for x in all_entries if x.endswith(annotations_suffix) and make_h5ad(x) in h5ad_entries] annotation_dir_entries = [
x
for x in all_entries
if x.endswith(annotations_suffix) and make_h5ad(x) in h5ad_entries
]
def list_annotations(el): def list_annotations(el):
full_path = os.path.join(path, el) full_path = os.path.join(path, el)
if not os.path.isdir(full_path): if not os.path.isdir(full_path):
entries = [] entries = []
else: else:
entries = [{ entries = [
"name": x[:-13] if (len(x) > 13 and x[-13] in ['-','_']) else ( {
x[:-4] if x.endswith('.csv') else x), "name": x[:-13]
"path": os.path.join(full_path, x).replace(env.cellxgene_data, ""), if (len(x) > 13 and x[-13] in ["-", "_"])
} for x in sorted(os.listdir(full_path)) if x.endswith('.csv') and os.path.isfile(os.path.join(full_path, x))] else (x[:-4] if x.endswith(".csv") else x),
return [{"name":'new', "class":'new', "path":full_path.replace(env.cellxgene_data, "")}] + entries "path": os.path.join(full_path, x).replace(
env.cellxgene_data, ""
),
}
for x in sorted(os.listdir(full_path))
if x.endswith(".csv")
and os.path.isfile(os.path.join(full_path, x))
]
return [
{
"name": "new",
"class": "new",
"path": full_path.replace(env.cellxgene_data, ""),
}
] + entries
def make_entry(el): def make_entry(el):
full_path = os.path.join(path, el) full_path = os.path.join(path, el)
@@ -63,16 +89,26 @@ def recurse_dir(path):
def render_entries(entries): def render_entries(entries):
return "<ul>" + "\n".join([render_entry(e) for e in entries]) + "</ul>" return "<ul>" + "\n".join([render_entry(e) for e in entries]) + "</ul>"
def get_url(entry): def get_url(entry):
return f"/view/{ entry['path'].lstrip('/') }" return f"/view/{ entry['path'].lstrip('/') }"
def get_class(entry): def get_class(entry):
return f" class='{entry['class']}'" if 'class' in entry else '' return f" class='{entry['class']}'" if "class" in entry else ""
def render_annotations(entry): def render_annotations(entry):
if len(entry['annotations']) > 0: if len(entry["annotations"]) > 0:
return ' | annotations: ' + ", ".join([f"<a href='{get_url(a)}'{get_class(a)}>{a['name']}</a>" for a in entry['annotations']]) return " | annotations: " + ", ".join(
[
f"<a href='{get_url(a)}'{get_class(a)}>{a['name']}</a>"
for a in entry["annotations"]
]
)
else: else:
return '' return ""
def render_entry(entry): def render_entry(entry):
if entry["type"] == "file": if entry["type"] == "file":
+2 -1
View File
@@ -9,6 +9,7 @@
from flask import request from flask import request
def querystring(): def querystring():
qs = request.query_string.decode() qs = request.query_string.decode()
return f'?{qs}' if len(qs) > 0 else '' return f"?{qs}" if len(qs) > 0 else ""
+65 -24
View File
@@ -38,11 +38,15 @@ from cellxgene_gateway.path_util import get_key
app = Flask(__name__) app = Flask(__name__)
def _force_https(app): def _force_https(app):
def wrapper(environ, start_response): def wrapper(environ, start_response):
environ['wsgi.url_scheme'] = env.external_protocol environ["wsgi.url_scheme"] = env.external_protocol
return app(environ, start_response) return app(environ, start_response)
return wrapper return wrapper
app.wsgi_app = _force_https(app.wsgi_app) app.wsgi_app = _force_https(app.wsgi_app)
cache = BackendCache() cache = BackendCache()
@@ -114,6 +118,7 @@ def index():
enable_upload=env.enable_upload, enable_upload=env.enable_upload,
) )
def make_user(): def make_user():
dir_name = request.form["directory"] dir_name = request.form["directory"]
@@ -135,13 +140,17 @@ def upload_file():
upload_dir = request.form["path"] upload_dir = request.form["path"]
full_upload_path = os.path.join(env.cellxgene_data, upload_dir) full_upload_path = os.path.join(env.cellxgene_data, upload_dir)
if is_subdir(full_upload_path, env.cellxgene_data) and os.path.isdir(full_upload_path): if is_subdir(full_upload_path, env.cellxgene_data) and os.path.isdir(
full_upload_path
):
if request.method == "POST": if request.method == "POST":
if "file" in request.files: if "file" in request.files:
f = request.files["file"] f = request.files["file"]
if f and f.filename.endswith(".h5ad"): if f and f.filename.endswith(".h5ad"):
f.save( f.save(
os.path.join(full_upload_path, secure_filename(f.filename)) os.path.join(
full_upload_path, secure_filename(f.filename)
)
) )
return redirect("/filecrawl.html", code=302) return redirect("/filecrawl.html", code=302)
else: else:
@@ -163,15 +172,20 @@ def upload_file():
if env.enable_upload: if env.enable_upload:
app.add_url_rule('/make_user', 'make_user', make_user, methods=["POST"]) app.add_url_rule("/make_user", "make_user", make_user, methods=["POST"])
app.add_url_rule('/make_subdir', 'make_subdir', make_subdir, methods=["POST"]) app.add_url_rule(
app.add_url_rule('/upload_file', 'upload_file', upload_file, methods=["POST"]) "/make_subdir", "make_subdir", make_subdir, methods=["POST"]
)
app.add_url_rule(
"/upload_file", "upload_file", upload_file, methods=["POST"]
)
def set_no_cache(resp): def set_no_cache(resp):
resp.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" resp.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
resp.headers["Pragma"] = "no-cache" resp.headers["Pragma"] = "no-cache"
resp.headers["Expires"] = "0" resp.headers["Expires"] = "0"
resp.headers['Cache-Control'] = 'public, max-age=0' resp.headers["Cache-Control"] = "public, max-age=0"
return resp return resp
@@ -179,19 +193,23 @@ def set_no_cache(resp):
def filecrawl(): def filecrawl():
entries = recurse_dir(env.cellxgene_data) entries = recurse_dir(env.cellxgene_data)
rendered_html = render_entries(entries) rendered_html = render_entries(entries)
resp = make_response(render_template( resp = make_response(
"filecrawl.html", render_template(
extra_scripts=get_extra_scripts(), "filecrawl.html",
rendered_html=rendered_html, extra_scripts=get_extra_scripts(),
)) rendered_html=rendered_html,
)
)
return set_no_cache(resp) return set_no_cache(resp)
@app.route("/filecrawl/<path:path>") @app.route("/filecrawl/<path:path>")
def do_filecrawl(path): def do_filecrawl(path):
filecrawl_path = os.path.join(env.cellxgene_data, path) filecrawl_path = os.path.join(env.cellxgene_data, path)
if not os.path.isdir(filecrawl_path): if not os.path.isdir(filecrawl_path):
raise CellxgeneException( raise CellxgeneException(
"Path is not directory: " + filecrawl_path, status.HTTP_400_BAD_REQUEST "Path is not directory: " + filecrawl_path,
status.HTTP_400_BAD_REQUEST,
) )
entries = recurse_dir(filecrawl_path) entries = recurse_dir(filecrawl_path)
rendered_html = render_entries(entries) rendered_html = render_entries(entries)
@@ -202,11 +220,16 @@ def do_filecrawl(path):
path=path, path=path,
) )
entry_lock = Lock() entry_lock = Lock()
@app.route("/view/<path:path>", methods=["GET", "PUT", "POST"]) @app.route("/view/<path:path>", methods=["GET", "PUT", "POST"])
def do_view(path): def do_view(path):
key = get_key(path) key = get_key(path)
print(f"view path={path}, dataset={key.dataset}, annotation_file= {key.annotation_file}, key={key.pathpart}") print(
f"view path={path}, dataset={key.dataset}, annotation_file= {key.annotation_file}, key={key.pathpart}"
)
with entry_lock: with entry_lock:
match = cache.check_entry(key) match = cache.check_entry(key)
if match is None: if match is None:
@@ -225,16 +248,25 @@ def do_view(path):
def do_GET_status(): def do_GET_status():
return render_template("cache_status.html", entry_list=cache.entry_list) return render_template("cache_status.html", entry_list=cache.entry_list)
@app.route("/cache_status.json", methods=["GET"]) @app.route("/cache_status.json", methods=["GET"])
def do_GET_status_json(): def do_GET_status_json():
return json.dumps({'launchtime':app.launchtime, return json.dumps(
'entry_list':[{ {
'dataset': entry.key.dataset, "launchtime": app.launchtime,
'annotation_file': entry.key.annotation_file, "entry_list": [
'launchtime': entry.launchtime, {
'last_access': entry.timestamp, "dataset": entry.key.dataset,
'status': entry.status "annotation_file": entry.key.annotation_file,
} for entry in cache.entry_list]}) "launchtime": entry.launchtime,
"last_access": entry.timestamp,
"status": entry.status,
}
for entry in cache.entry_list
],
}
)
@app.route("/relaunch/<path:path>", methods=["GET"]) @app.route("/relaunch/<path:path>", methods=["GET"])
def do_relaunch(path): def do_relaunch(path):
@@ -243,7 +275,11 @@ def do_relaunch(path):
if not match is None: if not match is None:
match.terminate() match.terminate()
qs = request.query_string.decode() qs = request.query_string.decode()
return redirect(url_for("do_view", path=path) + (f'?{qs}' if len(qs) > 0 else ''), code=302) return redirect(
url_for("do_view", path=path) + (f"?{qs}" if len(qs) > 0 else ""),
code=302,
)
@app.route("/terminate/<path:path>", methods=["GET"]) @app.route("/terminate/<path:path>", methods=["GET"])
def do_terminate(path): def do_terminate(path):
@@ -253,13 +289,18 @@ def do_terminate(path):
match.terminate() match.terminate()
return redirect(url_for("do_GET_status"), code=302) return redirect(url_for("do_GET_status"), code=302)
@app.route("/metadata/ip_address", methods=["GET"]) @app.route("/metadata/ip_address", methods=["GET"])
def ip_address(): def ip_address():
resp = make_response(env.ip) resp = make_response(env.ip)
return set_no_cache(resp) return set_no_cache(resp)
def main(): def main():
logging.basicConfig(level=logging.INFO, format='%(asctime)s:%(name)s:%(levelname)s:%(message)s') logging.basicConfig(
level=logging.INFO,
format="%(asctime)s:%(name)s:%(levelname)s:%(message)s",
)
env.validate() env.validate()
pruner = PruneProcessCache(cache) pruner = PruneProcessCache(cache)
+18 -6
View File
@@ -16,6 +16,7 @@ from cellxgene_gateway.cellxgene_exception import CellxgeneException
from cellxgene_gateway.dir_util import make_h5ad from cellxgene_gateway.dir_util import make_h5ad
from cellxgene_gateway.cache_key import CacheKey from cellxgene_gateway.cache_key import CacheKey
def get_key(path): def get_key(path):
if path == "/" or path == "": if path == "/" or path == "":
raise CellxgeneException( raise CellxgeneException(
@@ -25,10 +26,10 @@ def get_key(path):
trimmed = path[:-1] if path[-1] == "/" else path trimmed = path[:-1] if path[-1] == "/" else path
try: try:
# valid paths come in three forms: # valid paths come in three forms:
if trimmed.endswith('.h5ad') and data_file_exists(trimmed): if trimmed.endswith(".h5ad") and data_file_exists(trimmed):
# 1) somedir/dataset.h5ad: a dataset # 1) somedir/dataset.h5ad: a dataset
return CacheKey(trimmed, trimmed, None) return CacheKey(trimmed, trimmed, None)
elif trimmed.endswith('.csv'): elif trimmed.endswith(".csv"):
# 2) somedir/dataset_annotations/saldaal1-T5HMVBNV.csv : an actual annotations file. # 2) somedir/dataset_annotations/saldaal1-T5HMVBNV.csv : an actual annotations file.
annotations_dir = os.path.split(trimmed)[0] annotations_dir = os.path.split(trimmed)[0]
@@ -36,22 +37,24 @@ def get_key(path):
if data_file_exists(dataset): if data_file_exists(dataset):
data_dir_ensure(annotations_dir) data_dir_ensure(annotations_dir)
return CacheKey(trimmed, dataset, trimmed) return CacheKey(trimmed, dataset, trimmed)
elif trimmed.endswith('_annotations') and data_dir_exists(trimmed): elif trimmed.endswith("_annotations") and data_dir_exists(trimmed):
# 3) somedir/dataset_annotations: an annotation directory. The corresponding h5ad must exist, but the directory may not. # 3) somedir/dataset_annotations: an annotation directory. The corresponding h5ad must exist, but the directory may not.
dataset = make_h5ad(trimmed) dataset = make_h5ad(trimmed)
if data_file_exists(dataset): if data_file_exists(dataset):
return CacheKey(trimmed, dataset, '') return CacheKey(trimmed, dataset, "")
except CellxgeneException: except CellxgeneException:
pass pass
split = os.path.split(trimmed) split = os.path.split(trimmed)
return get_key(split[0]) return get_key(split[0])
def validate_exists(file_path): def validate_exists(file_path):
if not os.path.exists(file_path): if not os.path.exists(file_path):
raise CellxgeneException( raise CellxgeneException(
"File does not exist: " + file_path, status.HTTP_400_BAD_REQUEST "File does not exist: " + file_path, status.HTTP_400_BAD_REQUEST
) )
def validate_is_file(file_path): def validate_is_file(file_path):
validate_exists(file_path) validate_exists(file_path)
if not os.path.isfile(file_path): if not os.path.isfile(file_path):
@@ -59,6 +62,8 @@ def validate_is_file(file_path):
"Path is not file: " + file_path, status.HTTP_400_BAD_REQUEST "Path is not file: " + file_path, status.HTTP_400_BAD_REQUEST
) )
return return
def validate_is_dir(file_path): def validate_is_dir(file_path):
validate_exists(file_path) validate_exists(file_path)
if not os.path.isdir(file_path): if not os.path.isdir(file_path):
@@ -67,29 +72,36 @@ def validate_is_dir(file_path):
) )
return return
def data_file_exists(dataset): def data_file_exists(dataset):
file_path = os.path.join(env.cellxgene_data, dataset) file_path = os.path.join(env.cellxgene_data, dataset)
validate_is_file(file_path) validate_is_file(file_path)
return True return True
def data_dir_exists(dataset): def data_dir_exists(dataset):
file_path = os.path.join(env.cellxgene_data, dataset) file_path = os.path.join(env.cellxgene_data, dataset)
validate_is_dir(file_path) validate_is_dir(file_path)
return True return True
def data_dir_ensure(dataset): def data_dir_ensure(dataset):
file_path = os.path.join(env.cellxgene_data, dataset) file_path = os.path.join(env.cellxgene_data, dataset)
if not os.path.exists(file_path): if not os.path.exists(file_path):
os.makedirs(file_path) os.makedirs(file_path)
def get_file_path(key): def get_file_path(key):
dataset = key.dataset dataset = key.dataset
file_path = os.path.join(env.cellxgene_data, dataset) file_path = os.path.join(env.cellxgene_data, dataset)
validate_is_file(file_path) validate_is_file(file_path)
return file_path return file_path
def get_annotation_file_path(key): def get_annotation_file_path(key):
if key.annotation_file is None: if key.annotation_file is None:
return None return None
if key.annotation_file == '': if key.annotation_file == "":
return '' return ""
file_path = os.path.join(env.cellxgene_data, key.annotation_file) file_path = os.path.join(env.cellxgene_data, key.annotation_file)
return file_path return file_path
+17 -7
View File
@@ -17,7 +17,7 @@ from cellxgene_gateway.env import ttl
class PruneProcessCache: class PruneProcessCache:
def __init__(self, cache): def __init__(self, cache):
self.cache = cache self.cache = cache
self.expire_seconds = (3600 if ttl is None else int(ttl)) self.expire_seconds = 3600 if ttl is None else int(ttl)
def __call__(self): def __call__(self):
while True: while True:
@@ -27,14 +27,24 @@ class PruneProcessCache:
def prune(self): def prune(self):
timestamp = current_time_stamp() timestamp = current_time_stamp()
cutoff = timestamp - self.expire_seconds cutoff = timestamp - self.expire_seconds
processes_to_delete = [p for p in self.cache.entry_list if p.timestamp < cutoff] processes_to_delete = [
processes_to_keep = [p for p in self.cache.entry_list if not p.timestamp < cutoff] p for p in self.cache.entry_list if p.timestamp < cutoff
]
processes_to_keep = [
p for p in self.cache.entry_list if not p.timestamp < cutoff
]
logger = logging.getLogger("cellxgene_gateway") logger = logging.getLogger("cellxgene_gateway")
logger.debug(f"Cutoff {cutoff} = timestamp {timestamp} - expire seconds {self.expire_seconds} , keeping {processes_to_keep}") logger.debug(
f"Cutoff {cutoff} = timestamp {timestamp} - expire seconds {self.expire_seconds} , keeping {processes_to_keep}"
)
for process in processes_to_delete: for process in processes_to_delete:
try: try:
logger.info(f"pruning process {process.pid} ({process.key.dataset})") logger.info(
f"pruning process {process.pid} ({process.key.dataset})"
)
self.cache.prune(process) self.cache.prune(process)
except Exception: except Exception:
logger.exception("failed to prune process {process.pid} ({process.dataset})") logger.exception(
"failed to prune process {process.pid} ({process.dataset})"
)
+11 -3
View File
@@ -21,10 +21,14 @@ class SubprocessBackend:
def __init__(self): def __init__(self):
pass pass
def create_cmd(self, cellxgene_loc, file_path, port, scripts, annotation_file_path): def create_cmd(
self, cellxgene_loc, file_path, port, scripts, annotation_file_path
):
if enable_annotations and not annotation_file_path is None: if enable_annotations and not annotation_file_path is None:
if annotation_file_path == "": if annotation_file_path == "":
extra_args = f" --annotations-dir {make_annotations(file_path)}" extra_args = (
f" --annotations-dir {make_annotations(file_path)}"
)
else: else:
extra_args = f" --annotations-file {annotation_file_path}" extra_args = f" --annotations-file {annotation_file_path}"
else: else:
@@ -47,7 +51,11 @@ class SubprocessBackend:
def launch(self, cellxgene_loc, scripts, cache_entry): def launch(self, cellxgene_loc, scripts, cache_entry):
cmd = self.create_cmd( cmd = self.create_cmd(
cellxgene_loc, get_file_path(cache_entry.key), cache_entry.port, scripts, get_annotation_file_path(cache_entry.key) cellxgene_loc,
get_file_path(cache_entry.key),
cache_entry.port,
scripts,
get_annotation_file_path(cache_entry.key),
) )
logging.getLogger("cellxgene_gateway").info(f"launching {cmd}") logging.getLogger("cellxgene_gateway").info(f"launching {cmd}")
process = subprocess.Popen( process = subprocess.Popen(
+13 -8
View File
@@ -3,22 +3,25 @@ import codecs
from setuptools import find_packages, setup from setuptools import find_packages, setup
import sys import sys
if sys.version_info < (3,6): if sys.version_info < (3, 6):
sys.exit('Sorry, Python < 3.6 is not supported') sys.exit("Sorry, Python < 3.6 is not supported")
def read(rel_path): def read(rel_path):
here = os.path.abspath(os.path.dirname(__file__)) here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, rel_path), 'r') as fp: with codecs.open(os.path.join(here, rel_path), "r") as fp:
return fp.read() return fp.read()
def get_version(rel_path): def get_version(rel_path):
for line in read(rel_path).splitlines(): for line in read(rel_path).splitlines():
if line.startswith('__version__'): if line.startswith("__version__"):
delim = '"' if '"' in line else "'" delim = '"' if '"' in line else "'"
return line.split(delim)[1] return line.split(delim)[1]
else: else:
raise RuntimeError("Unable to find version string.") raise RuntimeError("Unable to find version string.")
def parse_requirements(): def parse_requirements():
reqs = [] reqs = []
with open("requirements.txt", "r") as f: with open("requirements.txt", "r") as f:
@@ -26,6 +29,7 @@ def parse_requirements():
reqs.append(l.strip("\n")) reqs.append(l.strip("\n"))
return reqs return reqs
with open("README.md", "r") as fh: with open("README.md", "r") as fh:
long_description = fh.read() long_description = fh.read()
@@ -50,13 +54,14 @@ setup(
"cellxgene_gateway": [ "cellxgene_gateway": [
"static/css/homepagestyle.css", "static/css/homepagestyle.css",
"static/nibr.ico", "static/nibr.ico",
"templates/*.html" "templates/*.html",
]}, ]
data_files=[('', ['README.md', 'LICENSE'])], },
data_files=[("", ["README.md", "LICENSE"])],
install_requires=install_reqs, install_requires=install_reqs,
entry_points={ entry_points={
"console_scripts": ["cellxgene-gateway=cellxgene_gateway.gateway:main"] "console_scripts": ["cellxgene-gateway=cellxgene_gateway.gateway:main"]
}, },
classifiers=["Topic :: Scientific/Engineering :: Visualization"], classifiers=["Topic :: Scientific/Engineering :: Visualization"],
python_requires='>=3.6', python_requires=">=3.6",
) )
+32 -29
View File
@@ -2,45 +2,48 @@ import unittest
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, patch
from cellxgene_gateway.filecrawl import render_entry from cellxgene_gateway.filecrawl import render_entry
class TestRenderEntry(unittest.TestCase): class TestRenderEntry(unittest.TestCase):
def test_GIVEN_path_both_slash_THEN_view_has_single_slash(self): def test_GIVEN_path_both_slash_THEN_view_has_single_slash(self):
entry = { entry = {
"path": "/somepath/", "path": "/somepath/",
"name": "entry", "name": "entry",
"type": "file", "type": "file",
"annotations": [], "annotations": [],
"children": [], "children": [],
} }
rendered = render_entry(entry) rendered = render_entry(entry)
self.assertIn('view/somepath', rendered) self.assertIn("view/somepath", rendered)
def test_GIVEN_path_starts_slash_THEN_view_has_single_slash(self): def test_GIVEN_path_starts_slash_THEN_view_has_single_slash(self):
entry = { entry = {
"path": "/somepath", "path": "/somepath",
"name": "entry", "name": "entry",
"type": "file", "type": "file",
"annotations": [], "annotations": [],
"children": [], "children": [],
} }
rendered = render_entry(entry) rendered = render_entry(entry)
self.assertIn('view/somepath', rendered) self.assertIn("view/somepath", rendered)
def test_GIVEN_path_ends_slash_THEN_view_has_single_slash(self): def test_GIVEN_path_ends_slash_THEN_view_has_single_slash(self):
entry = { entry = {
"path": "somepath/", "path": "somepath/",
"name": "entry", "name": "entry",
"type": "file", "type": "file",
"annotations": [], "annotations": [],
"children": [], "children": [],
} }
rendered = render_entry(entry) rendered = render_entry(entry)
self.assertIn('view/somepath', rendered) self.assertIn("view/somepath", rendered)
def test_GIVEN_path_no_slash_THEN_view_has_single_slash(self): def test_GIVEN_path_no_slash_THEN_view_has_single_slash(self):
entry = { entry = {
"path": "somepath", "path": "somepath",
"name": "entry", "name": "entry",
"type": "file", "type": "file",
"annotations": [], "annotations": [],
"children": [], "children": [],
} }
rendered = render_entry(entry) rendered = render_entry(entry)
self.assertIn('view/somepath', rendered) self.assertIn("view/somepath", rendered)
+10 -8
View File
@@ -2,22 +2,24 @@ import unittest
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, patch
from cellxgene_gateway.extra_scripts import get_extra_scripts from cellxgene_gateway.extra_scripts import get_extra_scripts
class TestExtraScripts(unittest.TestCase): class TestExtraScripts(unittest.TestCase):
@patch('cellxgene_gateway.env.extra_scripts', new='["abc","def"]') @patch("cellxgene_gateway.env.extra_scripts", new='["abc","def"]')
def test_GIVEN_two_scripts_THEN_returns_two_strings(self): def test_GIVEN_two_scripts_THEN_returns_two_strings(self):
self.assertEqual(get_extra_scripts(), ['abc', 'def']) self.assertEqual(get_extra_scripts(), ["abc", "def"])
@patch('cellxgene_gateway.env.extra_scripts', new='["abc", "def"]') @patch("cellxgene_gateway.env.extra_scripts", new='["abc", "def"]')
def test_GIVEN_two_scripts_space_THEN_returns_two_strings(self): def test_GIVEN_two_scripts_space_THEN_returns_two_strings(self):
self.assertEqual(get_extra_scripts(), ['abc', 'def']) self.assertEqual(get_extra_scripts(), ["abc", "def"])
@patch('cellxgene_gateway.env.extra_scripts', new=None) @patch("cellxgene_gateway.env.extra_scripts", new=None)
def test_GIVEN_none_THEN_returns_empty_array(self): def test_GIVEN_none_THEN_returns_empty_array(self):
self.assertEqual(get_extra_scripts(), []) self.assertEqual(get_extra_scripts(), [])
@patch('cellxgene_gateway.env.extra_scripts', new='[]') @patch("cellxgene_gateway.env.extra_scripts", new="[]")
def test_GIVEN_empty_string_THEN_returns_empty_array(self): def test_GIVEN_empty_string_THEN_returns_empty_array(self):
self.assertEqual(get_extra_scripts(), []) self.assertEqual(get_extra_scripts(), [])
if __name__ == '__main__':
unittest.main() if __name__ == "__main__":
unittest.main()
+8 -6
View File
@@ -3,11 +3,12 @@ from unittest.mock import MagicMock, patch
from cellxgene_gateway.cache_entry import CacheEntry from cellxgene_gateway.cache_entry import CacheEntry
from cellxgene_gateway.backend_cache import BackendCache from cellxgene_gateway.backend_cache import BackendCache
class TestPruneProcessCache(unittest.TestCase): class TestPruneProcessCache(unittest.TestCase):
@patch('cellxgene_gateway.util.current_time_stamp', new=lambda:0) @patch("cellxgene_gateway.util.current_time_stamp", new=lambda: 0)
@patch('cellxgene_gateway.env.ttl', new='10') @patch("cellxgene_gateway.env.ttl", new="10")
@patch('cellxgene_gateway.cache_entry.CacheEntry') @patch("cellxgene_gateway.cache_entry.CacheEntry")
@patch('cellxgene_gateway.cache_entry.CacheEntry') @patch("cellxgene_gateway.cache_entry.CacheEntry")
def test_GIVEN_one_old_one_new_THEN_prune_old(self, old, new): def test_GIVEN_one_old_one_new_THEN_prune_old(self, old, new):
from cellxgene_gateway.prune_process_cache import PruneProcessCache from cellxgene_gateway.prune_process_cache import PruneProcessCache
@@ -22,5 +23,6 @@ class TestPruneProcessCache(unittest.TestCase):
self.assertEqual(len(cache.entry_list), 1) self.assertEqual(len(cache.entry_list), 1)
self.assertEqual(cache.entry_list[0], new) self.assertEqual(cache.entry_list[0], new)
if __name__ == '__main__':
unittest.main() if __name__ == "__main__":
unittest.main()