11162: Set a default cache time of 24 hours for files fetched over http.
[arvados.git] / sdk / cwl / arvados_cwl / http.py
1 import requests
2 import email.utils
3 import time
4 import datetime
5 import re
6 import arvados
7 import arvados.collection
8 import urlparse
9 import logging
10
11 logger = logging.getLogger('arvados.cwl-runner')
12
13 def my_formatdate(dt):
14     return email.utils.formatdate(timeval=time.mktime(now.timetuple()), localtime=False, usegmt=True)
15
16 def my_parsedate(text):
17     return datetime.datetime(*email.utils.parsedate(text)[:6])
18
19 def fresh_cache(url, properties):
20     pr = properties[url]
21     expires = None
22
23     if "Cache-Control" in pr:
24         if re.match(r"immutable", pr["Cache-Control"]):
25             return True
26
27         g = re.match(r"(s-maxage|max-age)=(\d+)", pr["Cache-Control"])
28         if g:
29             expires = my_parsedate(pr["Date"]) + datetime.timedelta(seconds=int(g.group(2)))
30
31     if expires is None and "Expires" in pr:
32         expires = my_parsedate(pr["Expires"])
33
34     if expires is None:
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)
38
39     if not expires:
40         return False
41
42     return (datetime.datetime.utcnow() < expires)
43
44 def remember_headers(url, properties, headers):
45     properties.setdefault(url, {})
46     for h in ("Cache-Control", "ETag", "Expires", "Date", "Content-Length"):
47         if h in headers:
48             properties[url][h] = headers[h]
49     if "Date" not in headers:
50         properties[url]["Date"] = my_formatdate(datetime.datetime.utcnow())
51
52
53 def changed(url, properties):
54     req = requests.head(url)
55     remember_headers(url, properties, req.headers)
56
57     if req.status_code != 200:
58         raise Exception("Got status %s" % req.status_code)
59
60     pr = properties[url]
61     if "ETag" in pr and "ETag" in req.headers:
62         if pr["ETag"] == req.headers["ETag"]:
63             return False
64     return True
65
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]
69
70     for item in r["items"]:
71         properties = item["properties"]
72         if fresh_cache(url, properties):
73             # Do nothing
74             return "keep:%s/%s" % (item["portable_data_hash"], name)
75
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)
80
81     properties = {}
82     req = requests.get(url, stream=True)
83
84     if req.status_code != 200:
85         raise Exception("Failed to download '%s' got status %s " % (req.status_code, url))
86
87     remember_headers(url, properties, req.headers)
88
89     logger.info("Downloading %s (%s bytes)", url, properties[url]["Content-Length"])
90
91     c = arvados.collection.Collection()
92
93     count = 0
94     start = time.time()
95     checkpoint = start
96     with c.open(name, "w") as f:
97         for chunk in req.iter_content(chunk_size=1024):
98             count += len(chunk)
99             f.write(chunk)
100             now = time.time()
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"]),
105                             bps/(1024*1024),
106                             (int(properties[url]["Content-Length"])-count)/bps)
107                 checkpoint = now
108
109     c.save_new(name="Downloaded from %s" % url, owner_uuid=project_uuid, ensure_unique_name=True)
110
111     api.collections().update(uuid=c.manifest_locator(), body={"collection":{"properties": properties}}).execute()
112
113     return "keep:%s/%s" % (c.portable_data_hash(), name)