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"])
37 return (datetime.datetime.utcnow() < expires)
39 def remember_headers(url, properties, headers):
40 properties.setdefault(url, {})
41 for h in ("Cache-Control", "ETag", "Expires", "Date", "Content-Length"):
43 properties[url][h] = headers[h]
44 if "Date" not in headers:
45 properties[url]["Date"] = my_formatdate(datetime.datetime.utcnow())
48 def changed(url, properties):
49 req = requests.head(url)
50 remember_headers(url, properties, req.headers)
52 if req.status_code != 200:
53 raise Exception("Got status %s" % req.status_code)
56 if "ETag" in pr and "ETag" in req.headers:
57 if pr["ETag"] == req.headers["ETag"]:
61 def http_to_keep(api, project_uuid, url):
62 r = api.collections().list(filters=[["properties", "exists", url]]).execute()
63 name = urlparse.urlparse(url).path.split("/")[-1]
65 for item in r["items"]:
66 properties = item["properties"]
67 if fresh_cache(url, properties):
69 return "keep:%s/%s" % (item["portable_data_hash"], name)
71 if not changed(url, properties):
72 # ETag didn't change, same content, just update headers
73 api.collections().update(uuid=item["uuid"], body={"collection":{"properties": properties}}).execute()
74 return "keep:%s/%s" % (item["portable_data_hash"], name)
77 req = requests.get(url, stream=True)
79 if req.status_code != 200:
80 raise Exception("Failed to download '%s' got status %s " % (req.status_code, url))
82 remember_headers(url, properties, req.headers)
84 logger.info("Downloading %s (%s bytes)", url, properties[url]["Content-Length"])
86 c = arvados.collection.Collection()
91 with c.open(name, "w") as f:
92 for chunk in req.iter_content(chunk_size=1024):
96 if (now - checkpoint) > 20:
97 bps = (float(count)/float(now - start))
98 logger.info("%2.1f%% complete, %3.2f MiB/s, %1.0f seconds left",
99 float(count * 100) / float(properties[url]["Content-Length"]),
101 (int(properties[url]["Content-Length"])-count)/bps)
104 c.save_new(name="Downloaded from %s" % url, owner_uuid=project_uuid, ensure_unique_name=True)
106 api.collections().update(uuid=c.manifest_locator(), body={"collection":{"properties": properties}}).execute()
108 return "keep:%s/%s" % (c.portable_data_hash(), name)