-
Notifications
You must be signed in to change notification settings - Fork 4
/
fix_ungzipped.py
executable file
·199 lines (167 loc) · 5.74 KB
/
fix_ungzipped.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
#!/usr/bin/env python
import os, shutil, shlex, sys, subprocess, logging, re, json, urlparse, requests, time, gzip
import magic, mimetypes, hashlib
EPILOG = '''Notes:
Examples:
%(prog)s
'''
KEYFILE = os.path.expanduser("~/keypairs.json")
S3_BUCKET = "encode-files"
def get_args():
import argparse
parser = argparse.ArgumentParser(
description=__doc__, epilog=EPILOG,
formatter_class=argparse.RawDescriptionHelpFormatter)
#parser.add_argument('infile', nargs='?', type=argparse.FileType('r'), default=sys.stdin)
parser.add_argument('--debug', help="Print debug messages", default=False, action='store_true')
parser.add_argument('--key', help="The keypair identifier from the keyfile. Default is --key=default",
default='default')
parser.add_argument('--dryrun', help="Do everything except make changes", default=False, action='store_true')
args = parser.parse_args()
if args.debug:
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
else: #use the defaulf logging level
logging.basicConfig(format='%(levelname)s:%(message)s')
return args
def processkey(key):
if key:
keysf = open(KEYFILE,'r')
keys_json_string = keysf.read()
keysf.close()
keys = json.loads(keys_json_string)
key_dict = keys[key]
else:
key_dict = {}
AUTHID = key_dict.get('key')
AUTHPW = key_dict.get('secret')
if key:
SERVER = key_dict.get('server')
else:
SERVER = DEFAULT_SERVER
if not SERVER.endswith("/"):
SERVER += "/"
return (AUTHID,AUTHPW,SERVER)
def encoded_get(url, headers={'accept': 'application/json'}, **kwargs):
#url = urlparse.urljoin(url,'?format=json&frame=embedded&datastore=database')
for count in range(5):
try:
r = requests.get(url, headers=headers, **kwargs)
except requests.ConnectionError:
continue
else:
return r
def encoded_patch(url, headers={'content-type': 'application/json', 'accept': 'application/json'}, **kwargs):
for count in range(5):
try:
r = requests.patch(url, headers=headers, **kwargs)
except requests.ConnectionError:
continue
else:
return r
def gzip_and_post(f_obj, original_path, server, keypair):
ungzipped_md5 = hashlib.md5()
with open(original_path, 'rb') as f:
for chunk in iter(lambda: f.read(1024*1024), ''):
ungzipped_md5.update(chunk)
work_path = os.path.join('/external/encode/fix_ungzipped',original_path.lstrip('/'))
#print "Copying %s to %s" %(original_path, work_path)
work_dir = os.path.dirname(work_path)
if not os.path.exists(work_dir):
os.makedirs(work_dir)
shutil.copyfile(original_path, work_path)
ungzipped_name = work_path.rpartition('.gz')[0]
#print "Renaming %s to %s" %(work_path,ungzipped_name)
os.rename(work_path,ungzipped_name)
try:
print "Gzipping",
subprocess.check_call(['gzip', '-n', ungzipped_name])
except subprocess.CalledProcessError as e:
print "Gzip failed :%s" %(e)
return
else:
print "complete"
gzipped_md5 = hashlib.md5()
with open(work_path, 'rb') as f:
for chunk in iter(lambda: f.read(1024*1024), ''):
gzipped_md5.update(chunk)
#print "Uploading %s" %(work_path)
params = {'soft': True}
url = urlparse.urljoin(server,f_obj.get('href'))
r = encoded_get(url, auth=keypair, params=params)
try:
r.raise_for_status
except:
print "GET soft redirect failed: %s %s" %(r.status_code, r.reason)
print r.text
return
full_url = r.json()['location']
s3_filename = urlparse.urlparse(full_url).path
s3_path = S3_BUCKET + s3_filename
#print work_path, s3_path
try:
out = subprocess.check_output(shlex.split("aws s3 cp %s s3://%s --profile encode-prod" %(work_path, s3_path)))
print out.rstrip()
except subprocess.CalledProcessError as e:
print("Upload failed with exit code %d" % e.returncode)
return
print "Patching %s" %(f_obj.get('accession'))
patch_data = {
"file_size": os.path.getsize(work_path),
"md5sum": gzipped_md5.hexdigest()
}
uri = "/files/%s" %(f_obj.get('accession'))
url = urlparse.urljoin(server,uri)
r = encoded_patch(url, auth=keypair, data=json.dumps(patch_data))
try:
r.raise_for_status
except:
print "PATCH failed: %s %s" %(r.status_code, r.reason)
print r.text
return
def main():
global args
args = get_args()
authid, authpw, server = processkey(args.key)
keypair = (authid,authpw)
#file_formats = ['bed'] #this should pull from the file object schema file_format_file_extension
file_formats = ['bed_narrowPeak'] #this should pull from the file object schema file_format_file_extension
for file_format in file_formats:
print file_format,
query = '/search/?type=file&file_format=%s&frame=embedded&limit=all' %(file_format)
url = urlparse.urljoin(server,query)
print url
response = encoded_get(url,auth=keypair)
response.raise_for_status()
files = response.json()['@graph']
print "found %d files total." %(len(files))
#for f_obj in [f for f in files if f.get('accession') == 'ENCFF915YMM']: #.bed.gz E3 from Ren
#for f_obj in [f for f in files if f.get('accession') in ['ENCFF002END', 'ENCFF915YMM']]:
for f_obj in files:
url = urlparse.urljoin(server,f_obj.get('href'))
r = encoded_get(url, auth=keypair, allow_redirects=True, stream=True)
try:
r.raise_for_status
except:
print '%s href does not resolve' %(f_obj.get('accession'))
continue
s3_url = r.url
r.close()
o = urlparse.urlparse(s3_url)
mahout_prefix = "/external/encode/s3/encode-files/"
path = mahout_prefix.rstrip('/') + o.path
try:
magic_number = open(path,'rb').read(2)
except IOError as e:
print e
continue
else:
is_gzipped = magic_number == b'\x1f\x8b'
if not is_gzipped:
if magic_number == 'ch':
print "%s not gzipped" %(path)
if not args.dryrun:
gzip_and_post(f_obj, path, server, keypair)
else:
print "%s not gzipped and does not start with ch" %(path)
if __name__ == '__main__':
main()