Repository navigation
Expand file tree
/
Copy pathgetref
More file actions
307 lines (276 loc) · 9.43 KB
/
Copy pathgetref
File metadata and controls
307 lines (276 loc) · 9.43 KB
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
#!/usr/bin/env python
# Copyright (C) 2010 Ion Torrent Systems, Inc. All Rights Reserved
import os
import sys
import readline
import shutil
import tarfile
import urllib2
import hashlib
import getopt
import updateref
from subprocess import *
URL = 'http://updates.iontorrent.com/reference/'
LIST_NAME = 'LibraryList.txt'
VER_NAME = 'VersionList.txt'
LIBS = []
COMPLETION = {}
HELP_MESSAGE = """
Usage:
getref human_genome_reflib.tar
getref -r "/mnt/nas/results/referenceLibrary" human_genome_reflib.tar
getref -p "/mnt/nas/pgm_data/PGM_config"
-h, --help display this message
-r, --reflib_dir root directory of reference library
-p, --pgm_dir PGM config directory
-n, --reflist-name reference list name, i.e. reference_list.txt
-u, --ref-url URL to download reference library
"""
def usage():
"""print help doc"""
doc="""
Usage:
Type a few letters and hit 'Tab' key. The name of the reference
library will be completed for you. Hit 'Enter' key to start the
installation process.
To see the list of available libraries, leave the field blank
and hit 'Enter' key.
Control-C will abort the installation process at any given point.
"""
print(doc)
def get_md5(f, block_size=2**10):
"""calculate MD5 checksum on block_size at a time"""
md5 = hashlib.md5()
while True:
data_block = f.read(block_size)
if not data_block:
break
md5.update(data_block)
return md5.hexdigest()
def verify_checksum(tar_name, checksum):
"""compare the checksum of tar_name against checksum"""
f = open(tar_name, 'rb')
tar_checksum = get_md5(f)
if tar_checksum == checksum:
return True
else:
return False
def check_permission(lib_loc):
"""check for existance and permission of lib_loc"""
if not os.path.isdir(lib_loc):
try:
print("Creating %s" %(lib_loc))
os.umask(0000)
os.makedirs(lib_loc)
except OSError:
print("Failed to create %s" %(lib_loc))
isOkay = os.access(lib_loc, os.W_OK)
if isOkay is False:
print("Do not have permission to install library.")
prog_name = os.path.basename(sys.argv[0])
print("\nTry:\n\tsudo %s" %(prog_name))
sys.exit(0)
def install_lib(tar_file, ref_lib_loc):
"""untar the tar_file at ref_lib_loc"""
if tarfile.is_tarfile(tar_file):
tar = tarfile.open(tar_file, 'r')
if tar.getmembers():
tar.extractall(ref_lib_loc)
lib_name = tar_file.rstrip(".tar")
print('%s is installed in %s' %(lib_name, ref_lib_loc))
else:
print('%s is empty. Installation has failed.' %(tar_file))
tar.close()
else:
print('%s is not a tar file. Installation has failed.' %(tar_file))
def wget(url, tar_file):
"""check the tar_file and download it if needed"""
if os.path.isfile(tar_file):
print("%s exists." %(tar_file))
exit_stat = 0
to_del_tar = False
return exit_stat,to_del_tar
else:
full_url = "%s/%s" %(url.rstrip('/'), tar_file)
exit_stat = call(['wget', full_url])
to_del_tar = True
return exit_stat,to_del_tar
def update_reference_list(lib_loc, pgm_loc, fname):
"""update reference_list.txt with newly installed shortname"""
try:
while True:
lib_format = select_format()
if lib_format is not None:
break
updateref.main(lib_format, lib_loc, pgm_loc, fname)
except KeyboardInterrupt:
print("%s under %s is not updated." %(fname, pgm_loc))
sys.exit(0)
def file_opener(file_str):
"""now is url opener. will be a more generic ones"""
req = urllib2.Request(file_str)
opener = urllib2.build_opener()
try:
listLibs = opener.open(req)
return listLibs
except (urllib2.HTTPError):
print("%s does not exist." %(file_str))
sys.exit(0)
def get_reflibs(list_loc):
"""get list of reference library for download"""
d = {}
listLibs = file_opener(list_loc)
for lib in listLibs.readlines():
(md5,gname) = lib.split()
d[gname] = md5
LIBS.append(gname)
listLibs.close()
if not LIBS:
print("No library available at %s" %(URL))
sys.exit(0)
else:
return d
def get_lib_format(list_loc):
"""get list of TMAP versions"""
l = []
listVersions = file_opener(list_loc)
for version in listVersions.readlines():
l.append(version.rstrip())
return l
def completer(text, state):
"""complete items in reflibs"""
try:
matches = COMPLETION[text]
except KeyError:
matches = [reflib for reflib in LIBS
if text.upper() in reflib.upper()]
COMPLETION[text] = matches
try:
return matches[state]
except IndexError:
return None
def get_lib_name(reflib_dict):
"""get library name from user"""
usage()
readline.set_completer(completer)
readline.parse_and_bind('tab: menu-complete')
try:
while True:
lib_name = raw_input('\nType the name of library: ')
if lib_name and not reflib_dict.has_key(lib_name):
print("\n\t'%s' library is not available for download.\n" %(lib_name))
lib_name = None
if not lib_name:
print('\nPlease select from this list of available libraries:')
for reflib in reflib_dict.iterkeys():
print(" - %s" %(reflib))
print('Control-C to exit the installation')
else:
break
except KeyboardInterrupt:
print("\n\nThe library installation is aborted.")
sys.exit(0)
return lib_name
def get_tmap_lib(tmap_version):
"""get TMAP library URL"""
ref_url = os.path.join(URL, tmap_version)
list_loc = os.path.join(ref_url, LIST_NAME)
reflib_dict = get_reflibs(list_loc)
lib_name = get_lib_name(reflib_dict)
tar_file = '%s.tar' %(lib_name)
return reflib_dict, ref_url,tar_file,lib_name
def select_format():
"""docstring for select_format"""
format_loc = os.path.join(URL, VER_NAME)
listFormat = get_lib_format(format_loc)
idx = 1
print("Please select the format of the reference library:")
for format in listFormat:
print("%d: %s" %(idx, format))
idx += 1
print("Control-C to abort to process.")
format_idx = raw_input('Type the number to select format: ')
if format_idx.isdigit():
format_idx = int(format_idx) - 1
if format_idx < 0 or format_idx >= len(listFormat):
print('please select a number between 1 and %d' %(len(listFormat)))
return None
else:
print('Please select a number instead.')
return None
return listFormat[format_idx]
def get_lib_url():
"""docstring for get_lib_url"""
try:
while True:
lib_format = select_format()
if lib_format is not None:
break
return get_tmap_lib(lib_format)
except KeyboardInterrupt:
print("The installation is aborted.")
sys.exit(0)
def main(lib_loc, pgm_loc, reflist_name):
reflib_dict, ref_url, tar_file, lib_name = get_lib_url()
exit_stat,to_del_tar = wget(ref_url, tar_file)
if exit_stat == 0:
# successful
isGood = verify_checksum(tar_file, reflib_dict[lib_name])
if isGood:
install_lib(tar_file, lib_loc)
update_reference_list(lib_loc, pgm_loc, reflist_name)
else:
print('checksum did not match. %s is not installed.' %(lib_name))
to_del_tar = True
elif exit_s
65BA
tat == 4:
# host not found
to_del_tar = False
print("%s can not be reach." %(ref_url))
elif exit_stat == 8:
# file not found
to_del_tar = False
print("%s is not found on %s." %(tar_file, ref_url))
if to_del_tar:
os.remove(tar_file)
if __name__ == "__main__":
try:
opts, args = getopt.getopt(sys.argv[1:], "hr:p:n:u:",
["help", "reflib-dir=", "pgm-dir=", "reflist-name=", "ref-url="])
except getopt.GetoptError, msg:
print(str(msg))
sys.exit(2)
# option processing
lib_loc = '/results/referenceLibrary/'
pgm_loc = updateref.PGM_DIR
reflist_name = updateref.REF_LIST_TXT
lib_format = updateref.LIB_FORMAT
for option, value in opts:
if option in ("-h", "--help"):
print(HELP_MESSAGE)
sys.exit(0)
if option in ("-r", "--reflib-dir"):
lib_loc = value
if option in ("-p", "--pgm-dir"):
pgm_loc = value
if option in ("-n", "--reflist-name"):
reflist_name = value
if option in ("-u", "--ref-url"):
URL = value
check_permission(lib_loc)
if args:
# install from local file system
for tar_file in args:
if tar_file.endswith('.tar'):
tar_name = tar_file.rstrip('.tar')
else:
tar_name = tar_file
tar_file = "%s.tar" %(tar_file)
if os.path.isfile(tar_file):
print("Installing %s in %s" %(tar_file, lib_loc))
install_lib(tar_file, lib_loc)
else:
print("%s is not available." %(tar_file))
updateref.main(lib_format, lib_loc, pgm_loc, reflist_name)
else:
# install from web
main(lib_loc, pgm_loc, reflist_name)