7 import arvados.collection
11 logger = logging.getLogger('arvados.cwl-runner')
13 def my_formatdate(dt):
14 return email.utils.formatdate(timeval=time.mktime(now.timetuple()), localtime=False, usegmt=True)
16 def my_parsedate(text):
17 return datetime.datetime(*email.utils.parsedate(text)[:6])
19 def fresh_cache(url, properties):
23 if "Cache-Control" in pr:
24 if re.match(r"immutable", pr["Cache-Control"]):
27 g = re.match(r"(s-maxage|max-age)=(\d+)", pr["Cache-Control"])
29 expires = my_parsedate(pr["Date"]) + datetime.timedelta(seconds=int(g.group(2)))
31 if expires is None and "Expires" in pr:
32 expires = my_parsedate(pr["Expires"])
35 # Use a default cache time of 24 hours if upstream didn't set
36 # any cache headers, to reduce redundant downloads.
37 expires = my_parsedate(pr["Date"]) + datetime.timedelta(hours=24)
42 return (datetime.datetime.utcnow() < expires)
44 def remember_headers(url, properties, headers):
45 properties.setdefault(url, {})
46 for h in ("Cache-Control", "ETag", "Expires", "Date", "Content-Length"):
48 properties[url][h] = headers[h]
49 if "Date" not in headers:
50 properties[url]["Date"] = my_formatdate(datetime.datetime.utcnow())
53 def changed(url, properties):
54 req = requests.head(url)
55 remember_headers(url, properties, req.headers)
57 if req.status_code != 200:
58 raise Exception("Got status %s" % req.status_code)
61 if "ETag" in pr and "ETag" in req.headers:
62 if pr["ETag"] == req.headers["ETag"]:
66 def http_to_keep(api, project_uuid, url):
67 r = api.collections().list(filters=[["properties", "exists", url]]).execute()
68 name = urlparse.urlparse(url).path.split("/")[-1]
70 for item in r["items"]:
71 properties = item["properties"]
72 if fresh_cache(url, properties):
74 return "keep:%s/%s" % (item["portable_data_hash"], name)
76 if not changed(url, properties):
77 # ETag didn't change, same content, just update headers
78 api.collections().update(uuid=item["uuid"], body={"collection":{"properties": properties}}).execute()
79 return "keep:%s/%s" % (item["portable_data_hash"], name)
82 req = requests.get(url, stream=True)
84 if req.status_code != 200:
85 raise Exception("Failed to download '%s' got status %s " % (req.status_code, url))
87 remember_headers(url, properties, req.headers)
89 logger.info("Downloading %s (%s bytes)", url, properties[url]["Content-Length"])
91 c = arvados.collection.Collection()
96 with c.open(name, "w") as f:
97 for chunk in req.iter_content(chunk_size=1024):
101 if (now - checkpoint) > 20:
102 bps = (float(count)/float(now - start))
103 logger.info("%2.1f%% complete, %3.2f MiB/s, %1.0f seconds left",
104 float(count * 100) / float(properties[url]["Content-Length"]),
106 (int(properties[url]["Content-Length"])-count)/bps)
109 c.save_new(name="Downloaded from %s" % url, owner_uuid=project_uuid, ensure_unique_name=True)
111 api.collections().update(uuid=c.manifest_locator(), body={"collection":{"properties": properties}}).execute()
113 return "keep:%s/%s" % (c.portable_data_hash(), name)