-
Notifications
You must be signed in to change notification settings - Fork 36
/
data.py
476 lines (366 loc) · 12.5 KB
/
data.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
"""Data-handling tools."""
from .config import get_config
import csv
import errno
import io
import logging
import os
import shutil
import six
import subprocess
import tempfile
import warnings
from zipfile import ZipFile, ZIP_DEFLATED
import botocore
import boto3
import hashlib
import postgres_copy
import psycopg2
from dallinger.compat import open_for_csv
from dallinger.heroku.tools import HerokuApp
from dallinger import db
from dallinger import models
logger = logging.getLogger(__name__)
with warnings.catch_warnings():
warnings.simplefilter(action="ignore", category=FutureWarning)
try:
import odo
import pandas as pd
import tablib
except ImportError:
logger.debug("Failed to import odo, pandas, or tablib.")
table_names = [
"info",
"network",
"node",
"notification",
"participant",
"question",
"transformation",
"transmission",
"vector",
]
def find_experiment_export(app_id):
"""Attempt to find a zipped export of an experiment with the ID provided
and return its path. Returns None if not found.
Search order:
1. local "data" subdirectory
2. user S3 bucket
3. Dallinger S3 bucket
"""
# Check locally first
cwd = os.getcwd()
data_filename = "{}-data.zip".format(app_id)
path_to_data = os.path.join(cwd, "data", data_filename)
if os.path.exists(path_to_data):
try:
Data(path_to_data)
except IOError:
from dallinger import logger
logger.exception(
"Error reading local data file {}, checking remote.".format(
path_to_data
)
)
else:
return path_to_data
# Get remote file instead
path_to_data = os.path.join(tempfile.mkdtemp(), data_filename)
buckets = [user_s3_bucket(), dallinger_s3_bucket()]
for bucket in buckets:
try:
bucket.download_file(data_filename, path_to_data)
except botocore.exceptions.ClientError:
pass
else:
return path_to_data
def load(app_id):
"""Load the data from wherever it is found."""
path_to_data = find_experiment_export(app_id)
if path_to_data is None:
raise IOError("Dataset {} could not be found.".format(app_id))
return Data(path_to_data)
def dump_database(id):
"""Dump the database to a temporary directory."""
tmp_dir = tempfile.mkdtemp()
current_dir = os.getcwd()
os.chdir(tmp_dir)
FNULL = open(os.devnull, "w")
heroku_app = HerokuApp(dallinger_uid=id, output=FNULL)
heroku_app.backup_capture()
heroku_app.backup_download()
for filename in os.listdir(tmp_dir):
if filename.startswith("latest.dump"):
os.rename(filename, "database.dump")
os.chdir(current_dir)
return os.path.join(tmp_dir, "database.dump")
def backup(id):
"""Backup the database to S3."""
filename = dump_database(id)
key = "{}.dump".format(id)
bucket = user_s3_bucket()
bucket.upload_file(filename, key)
return _generate_s3_url(bucket, key)
def registration_key(id):
return "{}.reg".format(id)
def register(id, url=None):
"""Register a UUID key in the global S3 bucket."""
bucket = registration_s3_bucket()
key = registration_key(id)
obj = bucket.Object(key)
obj.put(Body=url or "missing")
return _generate_s3_url(bucket, key)
def is_registered(id):
"""Check if a UUID is already registered"""
bucket = registration_s3_bucket()
key = registration_key(id)
found_keys = set(obj.key for obj in bucket.objects.filter(Prefix=key))
return key in found_keys
def copy_heroku_to_local(id):
"""Copy a Heroku database locally."""
heroku_app = HerokuApp(dallinger_uid=id)
try:
subprocess.call(["dropdb", heroku_app.name])
except Exception:
pass
heroku_app.pg_pull()
def copy_db_to_csv(dsn, path, scrub_pii=False):
"""Copy a local database to a set of CSV files."""
if "postgresql://" in dsn or "postgres://" in dsn:
conn = psycopg2.connect(dsn=dsn)
else:
conn = psycopg2.connect(database=dsn, user="dallinger")
cur = conn.cursor()
for table in table_names:
csv_path = os.path.join(path, "{}.csv".format(table))
with open(csv_path, "w") as f:
sql = "COPY {} TO STDOUT WITH CSV HEADER".format(table)
cur.copy_expert(sql, f)
conn.close()
if scrub_pii:
_scrub_participant_table(path)
# Backwards compatibility for imports
copy_local_to_csv = copy_db_to_csv
def _scrub_participant_table(path_to_data):
"""Scrub PII from the given participant table."""
path = os.path.join(path_to_data, "participant.csv")
with open_for_csv(path, "r") as input, open("{}.0".format(path), "w") as output:
reader = csv.reader(input)
writer = csv.writer(output)
headers = next(reader)
writer.writerow(headers)
for i, row in enumerate(reader):
row[headers.index("worker_id")] = row[headers.index("id")]
row[headers.index("unique_id")] = "{}:{}".format(
row[headers.index("id")], row[headers.index("assignment_id")]
)
writer.writerow(row)
os.rename("{}.0".format(path), path)
def export(id, local=False, scrub_pii=False):
"""Export data from an experiment."""
print("Preparing to export the data...")
if local:
db_uri = db.db_url
else:
db_uri = HerokuApp(id).db_uri
# Create the data package if it doesn't already exist.
subdata_path = os.path.join("data", id, "data")
try:
os.makedirs(subdata_path)
except OSError as e:
if e.errno != errno.EEXIST or not os.path.isdir(subdata_path):
raise
# Copy in the data.
copy_db_to_csv(db_uri, subdata_path, scrub_pii=scrub_pii)
# Copy the experiment code into a code/ subdirectory.
try:
shutil.copyfile(
os.path.join("snapshots", id + "-code.zip"),
os.path.join("data", id, id + "-code.zip"),
)
except Exception:
pass
# Copy in the DATA readme.
# open(os.path.join(id, "README.txt"), "a").close()
# Save the experiment id.
with open(os.path.join("data", id, "experiment_id.md"), "a+") as file:
file.write(id)
# Zip data
src = os.path.join("data", id)
dst = os.path.join("data", id + "-data.zip")
archive_data(id, src, dst)
cwd = os.getcwd()
data_filename = "{}-data.zip".format(id)
path_to_data = os.path.join(cwd, "data", data_filename)
# Backup data on S3 unless run locally
if not local:
bucket = user_s3_bucket()
bucket.upload_file(path_to_data, data_filename)
url = _generate_s3_url(bucket, data_filename)
# Register experiment UUID with dallinger
register(id, url)
return path_to_data
def ingest_zip(path, engine=None):
"""Given a path to a zip file created with `export()`, recreate the
database with the data stored in the included .csv files.
"""
import_order = [
"network",
"participant",
"node",
"info",
"notification",
"question",
"transformation",
"vector",
"transmission",
]
with ZipFile(path, "r") as archive:
filenames = archive.namelist()
for name in import_order:
filename = [f for f in filenames if name in f][0]
model_name = name.capitalize()
model = getattr(models, model_name)
file = archive.open(filename)
if six.PY3:
file = io.TextIOWrapper(file, encoding="utf8", newline="")
ingest_to_model(file, model, engine)
def fix_autoincrement(table_name):
"""Auto-increment pointers are not updated when IDs are set explicitly,
so we manually update the pointer so subsequent inserts work correctly.
"""
db.engine.execute(
"select setval('{0}_id_seq', max(id)) from {0}".format(table_name)
)
def ingest_to_model(file, model, engine=None):
"""Load data from a CSV file handle into storage for a
SQLAlchemy model class.
"""
if engine is None:
engine = db.engine
reader = csv.reader(file)
columns = tuple('"{}"'.format(n) for n in next(reader))
postgres_copy.copy_from(
file, model, engine, columns=columns, format="csv", HEADER=False
)
fix_autoincrement(model.__table__.name)
def archive_data(id, src, dst):
print("Zipping up the package...")
with ZipFile(dst, "w", ZIP_DEFLATED, allowZip64=True) as zf:
for root, dirs, files in os.walk(src):
for file in files:
filename = os.path.join(root, file)
arcname = filename.replace(src, "").lstrip("/")
zf.write(filename, arcname)
shutil.rmtree(src)
print("Done. Data available in {}-data.zip".format(id))
def _get_canonical_aws_user_id(s3):
return s3.meta.client.list_buckets()["Owner"]["ID"]
def _get_or_create_s3_bucket(s3, name):
"""Get an S3 bucket resource after making sure it exists"""
exists = True
try:
s3.meta.client.head_bucket(Bucket=name)
except botocore.exceptions.ClientError as e:
error_code = int(e.response["Error"]["Code"])
if error_code == 404:
exists = False
else:
raise
if not exists:
s3.create_bucket(Bucket=name)
return s3.Bucket(name)
def _generate_s3_url(bucket, key):
return "https://{}.s3.amazonaws.com/{}".format(bucket.name, key)
def user_s3_bucket(canonical_user_id=None):
"""Get the user's S3 bucket."""
s3 = _s3_resource()
if not canonical_user_id:
canonical_user_id = _get_canonical_aws_user_id(s3)
s3_bucket_name = "dallinger-{}".format(
hashlib.sha256(canonical_user_id.encode("utf8")).hexdigest()[0:8]
)
return _get_or_create_s3_bucket(s3, s3_bucket_name)
def dallinger_s3_bucket():
"""The public `dallinger` S3 bucket."""
s3 = _s3_resource(dallinger_region=True)
return s3.Bucket("dallinger")
def registration_s3_bucket():
"""The public write-only `dallinger-registration` S3 bucket."""
s3 = _s3_resource(dallinger_region=True)
return s3.Bucket("dallinger-registrations")
def _s3_resource(dallinger_region=False):
"""A boto3 S3 resource using the AWS keys in the config."""
config = get_config()
if not config.ready:
config.load()
region = "us-east-1" if dallinger_region else config.get("aws_region")
return boto3.resource(
"s3",
region_name=region,
aws_access_key_id=config.get("aws_access_key_id"),
aws_secret_access_key=config.get("aws_secret_access_key"),
)
class Data(object):
"""Dallinger data object."""
def __init__(self, URL):
self.source = URL
if self.source.endswith(".zip"):
input_zip = ZipFile(URL)
tmp_dir = tempfile.mkdtemp()
input_zip.extractall(tmp_dir)
for tab in table_names:
setattr(
self,
"{}s".format(tab),
Table(os.path.join(tmp_dir, "data", "{}.csv".format(tab))),
)
class Table(object):
"""Dallinger data-table object."""
def __init__(self, path):
self.odo_resource = odo.resource(path)
self.tablib_dataset = tablib.Dataset().load(open(path).read(), "csv")
@property
def csv(self):
"""Comma-separated values."""
return self.tablib_dataset.csv
@property
def dict(self):
"""A Python dictionary."""
return self.tablib_dataset.dict[0]
@property
def df(self):
"""A pandas DataFrame."""
return odo.odo(self.odo_resource, pd.DataFrame)
@property
def html(self):
"""An HTML table."""
return self.tablib_dataset.html
@property
def latex(self):
"""A LaTeX table."""
return self.tablib_dataset.latex
@property
def list(self):
"""A Python list."""
return odo.odo(self.odo_resource, list)
@property
def ods(self):
"""An OpenDocument Spreadsheet."""
return self.tablib_dataset.ods
@property
def tsv(self):
"""Tab-separated values."""
return self.tablib_dataset.tsv
@property
def xls(self):
"""Legacy Excel spreadsheet format."""
return self.tablib_dataset.xls
@property
def xlsx(self):
"""Modern Excel spreadsheet format."""
return self.tablib_dataset.xlsx
@property
def yaml(self):
"""YAML."""
return self.tablib_dataset.yaml