This repository has been archived by the owner on Aug 29, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
utils.py
3132 lines (2941 loc) · 127 KB
/
utils.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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#
# $File: utils.py $
# $LastChangedDate$
# $Rev$
#
# This file is part of variant_tools, a software application to annotate,
# summarize, and filter variants for next-gen sequencing ananlysis.
# Please visit http://varianttools.sourceforge.net for details.
#
# Copyright (C) 2004 - 2011 Bo Peng (bpeng@mdanderson.org)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
'''This module provides utility functions and a database engine for sqlite'''
import os
import sys
import glob
import logging
import subprocess
import urllib
import urlparse
import getpass
import time
import tempfile
import tokenize
import cStringIO
import gzip
import copy
import threading
import re
import shlex
import stat
import signal
import random
import shutil
import hashlib
import ConfigParser
import tarfile
import binascii
from collections import namedtuple
from itertools import chain
try:
# not all platforms/installations of python support bz2
import bz2
bz2_support = True
except:
bz2_support = False
try:
if sys.version_info.major == 2:
import cPickle as pickle
import vt_sqlite3_py2 as sqlite3
from cgatools_py2 import CrrFile, Location, Range
from vt_sqlite3_py2 import OperationalError
else:
import pickle
import vt_sqlite3_py3 as sqlite3
from cgatools_py3 import CrrFile, Location, Range
from vt_sqlite3_py3 import OperationalError
except ImportError as e:
sys.exit('Failed to import module ({})\n'
'Please verify if you have installed variant tools successfully (using command '
'"python setup.py install") and you are NOT running command vtools from within '
'the source directory.'.format(e))
try:
# fake import to make this sqlite module bundled by pyinstaller
import _vt_sqlite3_ext
except ImportError as e:
pass
class RuntimeEnvironments(object):
# the following make RuntimeEnvironments a singleton class
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
# *args, **kwargs are not passed to avoid
# DeprecationWarning: object.__new__() takes no parameters
# cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
cls._instance = super(RuntimeEnvironments, cls).__new__(cls) #, *args, **kwargs)
return cls._instance
def __init__(self):
# these options could be set persistently
self.hidden_options = {
'term_width': (None, 'If set to a fix number, assuming a fixed terminal width for'
'outputs. This is used for testing purpose only.')
}
self.persistent_options = {
'logfile_verbosity': ('2', 'Verbosity level of the log file, can be 0 for warning '
'and error only, 1 for general information, or 2 for general and debug information.'),
'verbosity': ('1', 'Default verbosity level (to the standard output) of the project. '
'This option can be set during vtools init where the verbosity level set by option'
' --verbosity will be set as the project default.'),
# 'check_update': (True, 'Automatically check update of variant tools and resources.'),
'sqlite_pragma': ('', 'pragmas for sqlite database that can be used to optimize the '
'performance of database operations.'),
'import_num_of_readers': (2, 'variant tools by default uses two processes to read from '
'input files during multi-process importing (--jobs > 0). You can want to set it '
'to zero if a single process provides better performance or reduces disk traffic.'),
# a temporary directory that is used to store temporary files. Will be
# cleared after project is closed.
'temp_dir': (None, 'Use the specified temporary directory to store temporary files '
'to improve performance (use separate disks for project and temp files), or '
'avoid problems due to insufficient disk space.'),
'treat_missing_as_wildtype': ('False', 'Treat missing values as wildtype alleles for '
'association tests. This option is used when samples are called individuals or '
'in batch so genotypes for some samples are ignored and treated as missing if '
'they consist of all wildtype alleles. This option should be used with caution '
'because it convert real missing genotypes and genotypes removed due to, for '
'example low quality score, to wildtype genotypes.'),
'association_timeout': (None, 'Cancel associate test and return special values '
'when a test lasts more than specified time (in seconds). The default '
'value of this option is None, which stands for no time limit.'),
'associate_num_of_readers': (None, 'Use specified number of processes to read '
'genotype data for association tests. The default value is the minimum of value '
'of option --jobs and 8. Note that a large number of reading processes might '
'lead to degraded performance or errors due to disk access limits.'),
'search_path': ('.;http://vtools.houstonbioinformatics.org/', 'A ;-separated list of '
'directories and URLs that are used to locate annotation database (.ann, .DB), '
'file format (.fmt) and other files. Reset this option allows alternative '
'local or online storage of such files. variant tools will append trailing '
'directories such as annoDB for certain types of data so only root directories '
'should be listed in this search path.'),
'local_resource': ('~/.variant_tools', 'A directory to store variant tools related '
'resources such as reference genomes and annotation database. Files under this '
'directory is usually downloaded automatically upon use, but can also be '
'synchronized directly from http://vtools.houstonbioinformatics.org/.')
}
# a default value
self.command_line = ''
# path to the project cache
self._cache_dir = 'cache'
#
self._local_resource = self.persistent_options['local_resource'][0]
#
self._logfile_verbosity = self.persistent_options['logfile_verbosity'][0]
self._verbosity = self.persistent_options['verbosity'][0]
# self._check_update = self.persistent_options['check_update'][0]
# default sqlite pragma
self._sqlite_pragma = self.persistent_options['sqlite_pragma'][0]
# number of processes used for reader under multi-processing mode
self._import_num_of_readers = self.persistent_options['import_num_of_readers'][0]
# path to a temporary directory, will be allocated automatically.
self._temp_dir = self.persistent_options['temp_dir'][0]
self._proj_temp_dir = self._temp_dir # per project temp directory
# how to handle missing data
self._treat_missing_as_wildtype = self.persistent_options['treat_missing_as_wildtype'][0]
# association test time out
self._association_timeout = self.persistent_options['association_timeout'][0]
# association test number of genotype loaders
self._associate_num_of_readers = self.persistent_options['associate_num_of_readers'][0]
# search path
self._search_path = self.persistent_options['search_path'][0]
# logger
self._logger = None
#
# a list of lock file that will be removed when the project is killed
self._lock_files = []
#
self._term_width = None
#
def lock(self, filename, content=''):
with open(filename, 'w') as lockfile:
lockfile.write(content)
self._lock_files.append(filename)
def unlock(self, filename, content=''):
if filename in self._lock_files:
self._lock_files.remove(filename)
if not os.path.isfile(filename):
return
with open(filename) as lockfile:
if lockfile.read() != content:
raise RuntimeError('Inconsistent lock file. The output file might have been changed by another process.')
try:
os.remove(filename)
except Exception as e:
self._logger.warning('Failed to remove lock file {}: {}'
.format(filename, e))
def unlock_all(self):
for filename in self._lock_files:
try:
os.remove(filename)
except Exception as e:
self._logger.warning('Failed to remove lock file {}: {}'
.format(filename, e))
self._lock_files = []
#
# attribute check_update
#
#def _set_check_update(self, v):
# if v in ['1', True, 'T', 'True', 'Y', 'Yes']:
# self._check_update = True
# else:
# self._check_update = False
#
#check_update = property(lambda self: self._check_update, _set_check_update)
#
# attribute term_width
def _set_term_width(self, v):
try:
self._term_width = int(v)
except:
self._term_width = None
#
term_width = property(lambda self: self._term_width, _set_term_width)
#
# attribute logfile_verbosity
#
def _set_logfile_verbosity(self, v):
if v in ['0', '1', '2']:
self._logfile_verbosity = v
#
logfile_verbosity = property(lambda self: self._logfile_verbosity, _set_logfile_verbosity)
#
#
# attribute verbosity
#
def _set_verbosity(self, v):
if v in ['0', '1', '2']:
self._verbosity = v
#
verbosity = property(lambda self: self._verbosity, _set_verbosity)
#
# attribute pragma
#
def _set_sqlite_pragma(self, pragma):
# 'None' is for backward compatibility
if pragma in [None, 'None', '']:
return
try:
p = pragma.split(',')
#
for item in p:
if '=' not in str(item):
raise ValueError('Invalid pragma {}'.format(item))
self._sqlite_pragma = pragma
except:
sys.stderr.write('Invalid pragma {}\n'.format(pragma))
#
sqlite_pragma = property(lambda self: self._sqlite_pragma.split(',') if self._sqlite_pragma else [],
_set_sqlite_pragma)
#
# attribute import_num_of_readers
#
def _set_import_num_of_readers(self, n):
try:
if n is not None:
int(n) # test if n is an integer
self._import_num_of_readers = str(n)
except:
sys.stderr.write('Failed to set number of readers to {}\n'.format(n))
#
import_num_of_readers = property(lambda self: int(self._import_num_of_readers), _set_import_num_of_readers)
#
# attribute cache_dir, which is not configurable
#
def _set_cache_dir(self, path=None):
if path is not None:
self._cache_dir = path
try:
if not os.path.isdir(self._cache_dir):
os.makedirs(self._cache_dir)
except:
raise RuntimeError('Failed to create cache directory '.format(self._cache_dir))
#
cache_dir = property(lambda self: 'cache', _set_cache_dir)
#
# attribute local_resource
#
def _set_local_resource(self, path=None):
if path is not None:
self._local_resource = path
try:
if not os.path.isdir(os.path.expanduser(self._local_resource)):
sys.stderr.write('Creating local resource directory {}\n'.format(self._local_resource))
os.makedirs(os.path.expanduser(self._local_resource))
except:
raise RuntimeError('Failed to create local resource directory '.format(self._local_resource))
#
local_resource = property(lambda self: os.path.expanduser(self._local_resource), _set_local_resource)
#
# attribute temp_dir
#
def _set_temp_dir(self, path=None):
# user can explicitly set a path ('None' could be saved by a previous version of vtools)
if path not in [None, 'None', '']:
if os.path.isdir(path) and (os.listdir(path) or
(not os.access(path, os.R_OK)) or (not os.access(path, os.W_OK)) or
(os.stat(path).st_mode & stat.S_ISVTX == 512)):
raise ValueError('Cannot set temporary directory to directory {} because '.format(path) + \
'it is not empty or is not writable or deletable. Please clear this directory or use '
'command "vtools admin --set_runtime_option temp_dir=DIR" to set it to another path, '
'or a random path (empty DIR).')
self._temp_dir = path
self._proj_temp_dir = path
# the usual case
if self._temp_dir is None:
self._proj_temp_dir = tempfile.mkdtemp()
try:
if not os.path.isdir(os.path.expanduser(self._proj_temp_dir)):
os.makedirs(os.path.expanduser(self._proj_temp_dir))
except:
sys.stderr.write('Failed to create a temporary directory {}.\n'.format(self._proj_temp_dir))
self._proj_temp_dir = tempfile.mkdtemp()
#
temp_dir = property(lambda self: os.path.expanduser(self._proj_temp_dir), _set_temp_dir)
#
# attribute treat_missing_as_wildtype
def _set_treat_missing_as_wildtype(self, val):
if val in [None, 'None', '0', 'False', 'false', 'FALSE']:
self._treat_missing_as_wildtype = 'False'
elif val in ['1', 'True', 'TRUE', 'true']:
self._treat_missing_as_wildtype = 'True'
else:
sys.stderr.write('Invalid input ({}) for runtime option treat_missing_as_wildtype\n'.format(val))
self._treat_missing_as_wildtype = 'False'
#
treat_missing_as_wildtype = property(lambda self: True if self._treat_missing_as_wildtype == 'True' else False,
_set_treat_missing_as_wildtype)
#
# attribute association_timeout
def _set_association_timeout(self, val):
try:
if val in ['None', None]:
self._association_timeout = None
else:
# test if val can be converted to int
int(val)
self._association_timeout = val
except:
pass
#
association_timeout = property(lambda self: 0 if self._association_timeout is None else int(self._association_timeout), _set_association_timeout)
#
# attribute associate_num_of_readers
def _set_associate_num_of_readers(self, val):
try:
if val in ['None', None]:
self._associate_num_of_readers = None
else:
# test if val can be converted to int
int(val)
self._associate_num_of_readers = val
except:
pass
#
associate_num_of_readers = property(lambda self: 0 if self._associate_num_of_readers is None else int(self._associate_num_of_readers), _set_associate_num_of_readers)
#
# attribute search_path
def _set_search_path(self, val):
if val not in ['None', None]:
self._search_path = val
#
search_path = property(lambda self: self._search_path, _set_search_path)
#
# attribute logger
class ColoredFormatter(logging.Formatter):
# A variant of code found at http://stackoverflow.com/questions/384076/how-can-i-make-the-python-logging-output-to-be-colored
def __init__(self, msg):
logging.Formatter.__init__(self, msg)
self.LEVEL_COLOR = {
'DEBUG': 'BLUE',
'WARNING': 'PURPLE',
'ERROR': 'RED',
'CRITICAL': 'RED_BG',
}
self.COLOR_CODE={
'ENDC':0, # RESET COLOR
'BOLD':1,
'UNDERLINE':4,
'BLINK':5,
'INVERT':7,
'CONCEALD':8,
'STRIKE':9,
'GREY30':90,
'GREY40':2,
'GREY65':37,
'GREY70':97,
'GREY20_BG':40,
'GREY33_BG':100,
'GREY80_BG':47,
'GREY93_BG':107,
'DARK_RED':31,
'RED':91,
'RED_BG':41,
'LIGHT_RED_BG':101,
'DARK_YELLOW':33,
'YELLOW':93,
'YELLOW_BG':43,
'LIGHT_YELLOW_BG':103,
'DARK_BLUE':34,
'BLUE':94,
'BLUE_BG':44,
'LIGHT_BLUE_BG':104,
'DARK_MAGENTA':35,
'PURPLE':95,
'MAGENTA_BG':45,
'LIGHT_PURPLE_BG':105,
'DARK_CYAN':36,
'AUQA':96,
'CYAN_BG':46,
'LIGHT_AUQA_BG':106,
'DARK_GREEN':32,
'GREEN':92,
'GREEN_BG':42,
'LIGHT_GREEN_BG':102,
'BLACK':30,
}
def colorstr(self, astr, color):
return '\033[{}m{}\033[{}m'.format(self.COLOR_CODE[color], astr,
self.COLOR_CODE['ENDC'])
def emphasize(self, msg):
# display text within [[ and ]] in green
# This is done for levelname not in self.LEVEL_COLOR, e.g.
# for info that uses native color. The text will not be
# visible if someone is using a green background
return re.sub(r'\[\[(.*)\]\]', '\033[32m\\1\033[0m', str(msg))
def format(self, record):
record = copy.copy(record)
levelname = record.levelname
record.msg = self.emphasize(record.msg)
if levelname in self.LEVEL_COLOR:
record.levelname = self.colorstr(levelname, self.LEVEL_COLOR[levelname])
record.name = self.colorstr(record.name, 'BOLD')
record.msg = self.colorstr(record.msg, self.LEVEL_COLOR[levelname])
return logging.Formatter.format(self, record)
def _set_logger(self, logfile=None):
# create a logger, but shutdown the previous one
if self._logger is not None:
self._logger.handlers = []
self._logger = logging.getLogger()
self._logger.setLevel(logging.DEBUG)
# output to standard output
cout = logging.StreamHandler()
levels = {
'0': logging.WARNING,
'1': logging.INFO,
'2': logging.DEBUG,
None: logging.INFO
}
#
cout.setLevel(levels[self._verbosity])
cout.setFormatter(self.ColoredFormatter('%(levelname)s: %(message)s'))
self._logger.addHandler(cout)
# output to a log file
if logfile is not None:
ch = logging.FileHandler(logfile.lstrip('>'), mode = ('a' if logfile.startswith('>>') else 'w'))
# NOTE: debug informaiton is always written to the log file
ch.setLevel(levels[self._logfile_verbosity])
ch.setFormatter(logging.Formatter('%(asctime)s: %(levelname)s: %(message)s'))
self._logger.addHandler(ch)
#
logger = property(lambda self: self._logger, _set_logger)
# the singleton object of RuntimeEnvironments
env = RuntimeEnvironments()
# create a default logger without logging to file, this makes sure a logger
# will be usable even when a project is failed to create
env.logger = None
OS_ENV = {x:os.pathsep.join(['.', env.cache_dir, os.environ[x]]) for x in ['PATH', 'LD_LIBRARY_PATH', 'PYTHONPATH', 'PYTHONHOME', 'R_LIBS'] if x in os.environ}
SQL_KEYWORDS = set([
'ADD', 'ALL', 'ALTER', 'ANALYZE', 'AND', 'AS', 'ASC', 'ASENSITIVE', 'BEFORE',
'BETWEEN', 'BIGINT', 'BINARY', 'BLOB', 'BOTH', 'BY', 'CALL', 'CASCADE', 'CASE',
'CHANGE', 'CHAR', 'CHARACTER', 'CHECK', 'COLLATE', 'COLUMN', 'CONDITION',
'CONSTRAINT', 'CONTINUE', 'CONVERT', 'CREATE', 'CROSS', 'CURRENT_DATE',
'CURRENT_TIME', 'CURRENT_TIMESTAMP', 'CURRENT_USER', 'CURSOR', 'DATABASE',
'DATABASES', 'DAY_HOUR', 'DAY_MICROSECOND', 'DAY_MINUTE', 'DAY_SECOND', 'DEC',
'DECIMAL', 'DECLARE', 'DEFAULT', 'DELAYED', 'DELETE', 'DESC',
'DESCRIBE', 'DETERMINISTIC', 'DISTINCT', 'DISTINCTROW', 'DIV', 'DOUBLE',
'DROP', 'DUAL', 'EACH', 'ELSE', 'ELSEIF', 'ENCLOSED', 'ESCAPED', 'EXISTS',
'EXIT', 'EXPLAIN', 'FALSE', 'FETCH', 'FLOAT', 'FLOAT4', 'FLOAT8', 'FOR',
'FORCE', 'FOREIGN', 'FROM', 'FULLTEXT', 'GRANT', 'GROUP', 'HAVING', 'HIGH_PRIORITY',
'HOUR_MICROSECOND', 'HOUR_MINUTE', 'HOUR_SECOND', 'IF', 'IGNORE', 'IN',
'INDEX', 'INFILE', 'INNER', 'INOUT', 'INSENSITIVE', 'INSERT',
'INT', 'INT1', 'INT2', 'INT3', 'INT4', 'INT8', 'INTEGER', 'INTERVAL', 'INTO',
'IS', 'ITERATE', 'JOIN', 'KEY', 'KEYS', 'KILL', 'LEADING', 'LEAVE', 'LEFT',
'LIKE', 'LIMIT', 'LINES', 'LOAD', 'LOCALTIME', 'LOCALTIMESTAMP',
'LOCK', 'LONG', 'LONGBLOB', 'LONGTEXT', 'LOOP', 'LOW_PRIORITY', 'MATCH',
'MEDIUMBLOB', 'MEDIUMINT', 'MEDIUMTEXT', 'MIDDLEINT', 'MINUTE_MICROSECOND',
'MINUTE_SECOND', 'MOD', 'MODIFIES', 'NATURAL', 'NOT', 'NO_WRITE_TO_BINLOG',
'NULL', 'NUMERIC', 'ON', 'OPTIMIZE', 'OPTION', 'OPTIONALLY', 'OR',
'ORDER', 'OUT', 'OUTER', 'OUTFILE', 'PRECISION', 'PRIMARY', 'PROCEDURE',
'PURGE', 'READ', 'READS', 'REAL', 'REFERENCES', 'REGEXP', 'RELEASE',
'RENAME', 'REPEAT', 'REPLACE', 'REQUIRE', 'RESTRICT', 'RETURN',
'REVOKE', 'RIGHT', 'RLIKE', 'SCHEMA', 'SCHEMAS', 'SECOND_MICROSECOND',
'SELECT', 'SENSITIVE', 'SEPARATOR', 'SET', 'SHOW', 'SMALLINT',
'SONAME', 'SPATIAL', 'SPECIFIC', 'SQL', 'SQLEXCEPTION', 'SQLSTATE',
'SQLWARNING', 'SQL_BIG_RESULT', 'SQL_CALC_FOUND_ROWS', 'SQL_SMALL_RESULT',
'SSL', 'STARTING', 'STRAIGHT_JOIN', 'TABLE', 'TERMINATED',
'THEN', 'TINYBLOB', 'TINYINT', 'TINYTEXT', 'TO', 'TRAILING',
'TRIGGER', 'TRUE', 'UNDO', 'UNION', 'UNIQUE', 'UNLOCK', 'UNSIGNED',
'UPDATE', 'USAGE', 'USE', 'USING', 'UTC_DATE', 'UTC_TIME', 'UTC_TIMESTAMP', 'VALUES',
'VARBINARY', 'VARCHAR', 'VARCHARACTER', 'VARYING', 'WHEN', 'WHERE', 'WHILE',
'WITH', 'WRITE', 'XOR', 'YEAR_MONTH', 'ZEROFILL', 'ASENSITIVE', 'CALL', 'CONDITION',
'CONNECTION', 'CONTINUE', 'CURSOR', 'DECLARE', 'DETERMINISTIC', 'EACH',
'ELSEIF', 'EXIT', 'FETCH', 'GOTO', 'INOUT', 'INSENSITIVE', 'ITERATE', 'LABEL', 'LEAVE',
'LOOP', 'MODIFIES', 'OUT', 'READS', 'RELEASE', 'REPEAT', 'RETURN', 'SCHEMA', 'SCHEMAS',
'SENSITIVE', 'SPECIFIC', 'SQL', 'SQLEXCEPTION', 'SQLSTATE', 'SQLWARNING', 'TRIGGER',
'UNDO', 'UPGRADE', 'WHILE', 'ABS', 'ACOS', 'ADDDATE', 'ADDTIME', 'ASCII', 'ASIN',
'ATAN', 'AVG', 'BETWEEN', 'AND', 'BINARY', 'BIN', 'BIT_AND',
'BIT_OR', 'CASE', 'CAST', 'CEIL', 'CHAR', 'CHARSET', 'CONCAT', 'CONV', 'COS', 'COT',
'COUNT', 'DATE', 'DAY', 'DIV', 'EXP', 'IS', 'LIKE', 'MAX', 'MIN', 'MOD', 'MONTH',
'LOG', 'POW', 'SIN', 'SLEEP', 'SORT', 'STD', 'VALUES', 'SUM'
])
def matchName(pattern, name):
#
for char in ('(', ')', '[', ']', '{', '}', '.', '+', '$', '|'):
pattern = pattern.replace(char, '\\' + char)
pattern = pattern.replace('?', '.{1}').replace('*', '.*')
return re.match(pattern, name, re.I)
def validFieldName(name, reserved=[]):
'''Return a valid field name from a name by converting non-alnum
characters with _, and add _ if the name starts with a number. If
the new name is one of reserved, prefix it with _'''
new_name = re.sub('[\W]', '_', name.strip())
if new_name[0].isdigit() or new_name in reserved:
new_name = '_' + new_name
return new_name
def decodeTableName(name):
'''Decode a table to its name that could contain special characters'''
if name.startswith('_'):
return binascii.unhexlify(name[1:].encode('utf-8')).decode('utf-8')
else:
return name
def encodeTableName(name):
'''Get a normalized name for variant table. The returned name is a valid
table name so calling encodeTableName on an encoded name is safe.'''
# if the table name is not ALPHA + ALPHANUM, use an internal name
if name.upper() in SQL_KEYWORDS or not name[0].isalpha() \
or name.startswith('_') or not name.replace('_', '').isalnum():
return '_' + binascii.hexlify(name.encode('utf-8')).decode('utf-8')
else:
return name
def sizeExpr(sz, multiple=1000):
if sz == 0:
sz = +0
SUFFIXES = ["B"] + [i + {1000: "B", 1024: "iB"}[multiple] for i in "KMGTPEZY"]
for suffix in SUFFIXES:
if sz < multiple or suffix == SUFFIXES[-1]:
if suffix == SUFFIXES[0]:
return "%d%s" % (sz, suffix)
else:
return "%.1f%s" % (sz, suffix)
else:
sz /= multiple
#
# Utility functions
#
def lineCount(filename, encoding='UTF-8'):
'''Estimate the number of lines using file size and line size. This
function does not attemp to calculate line count exactly because files
handled by variant tools can be huge. '''
totalSize = os.path.getsize(filename)
if totalSize < 500000:
# small file, read the number of lines directly
if filename.endswith('.gz'):
try:
return len(gzip.open(filename, 'rb').readlines())
# Python 2.7.4 and 3.3.1 have a regression bug that prevents us from opening
# certain types of gzip file (http://bugs.python.org/issue17666).
except TypeError as e:
raise RuntimeError('Failed to open gzipped file {} due to a bug '
'in Python 2.7.4 and 3.3.1. Please use a different version '
'of Python or decompress this file manually.'.format(filename))
elif filename.endswith('.bz2'):
if not bz2_support:
raise ValueError('Direct reading of bz2 files is not supported. Please update your python installation or uncompress the file before processing')
return len(bz2.BZ2File(filename).readlines())
else:
return len(open(filename, 'rb').readlines())
elif filename.endswith('.gz'):
try:
input = gzip.open(filename, 'rb')
input.seek(50000, 0)
content = input.read(500000).decode(encoding)
input.close()
lineCount = len(content.split('\n'))
input.close()
# Python 2.7.4 and 3.3.1 have a regression bug that prevents us from opening
# certain types of gzip file (http://bugs.python.org/issue17666).
except TypeError as e:
raise RuntimeError('Failed to open gzipped file {} due to a bug '
'in Python 2.7.4 and 3.3.1. Please use a different version '
'of Python or decompress this file manually.'.format(filename))
# assuming an arbitrary compression ratio of 5. :-)
return int(lineCount * (5 * totalSize / 500000.))
elif filename.endswith('.bz2'):
if not bz2_support:
raise ValueError('Direct reading of bz2 files is not supported. Please update your python installation or uncompress the file before processing')
input = bz2.BZ2File(filename, 'rb')
input.seek(50000, 0)
content = input.read(500000).decode(encoding)
input.close()
lineCount = len(content.split('\n'))
input.close()
# assuming an arbitrary compression ratio of 5. :-)
return int(lineCount * (5 * totalSize / 500000.))
else:
# only binary mode can accomendate end-relative seeks in python 3.
input = open(filename, 'rb')
# count from the back because they tend to be records
# with consistent size
input.seek(-99000, 2)
content = input.read()
input.close()
lineCount = content.decode(encoding).count('\n')
input.close()
return int(lineCount * (totalSize / 99000.))
class PrettyPrinter:
def __init__(self, delimiter=None, max_width={}, cache_size=200):
''' delimiter: use specified field to separate fields
max_width: a dictionary of {col: max_width} to change long
text to START...END
cache: only use the first cache lines to get column width
'''
self.width = []
self.rows = []
self.max_width = max_width
self.cache_size = cache_size
# if a delimiter is specified, use it
if delimiter is not None:
self.delimiter = delimiter.replace(r'\t', '\t')
self.write = self.direct_print
self.write_rest = self.direct_print_rest
elif max_width:
self.delimiter = '\t'
self.write = self.cached_trim_print
self.write_rest = self.cached_trim_print_rest
else:
self.delimiter = '\t'
self.write = self.cached_print
self.write_rest = self.cached_print_rest
#
# MODE 1: direct print
#
def direct_print(self, data):
'''print data directly using specified delimiter'''
print(self.delimiter.join([x for x in data]))
def direct_print_rest(self):
'''No cache so do nothing'''
pass
#
# MODE 2: cached, trimmed print
#
def cached_trim_print(self, data):
'''Use cache, figure out column width'''
trimmed = {}
for c,m in self.max_width.items():
if len(data[c]) > m:
trimmed[c] = data[c][: m // 3] + '...' + data[c][ - (m - m // 3 - 3):]
if trimmed:
trimmed_data = [x for x in data]
for c,txt in trimmed.items():
trimmed_data[c] = txt
else:
trimmed_data = data
#
self.rows.append(trimmed_data)
if not self.width:
self.width = [len(x) for x in trimmed_data]
else:
self.width = [max(y, len(x)) for y,x in zip(self.width, trimmed_data)]
# cache size exceeds, use collected width and stop checking
if len(self.rows) > self.cache_size:
self.cached_trim_print_rest()
# change print mode
self.write = self.uncached_trim_print
def cached_trim_print_rest(self):
'''Print and clear cache'''
if not self.rows:
return
# do not ljust the last column. This avoids unnecessary spaces
# at the end of each line
self.width[-1] = 0
# print everything in cache
print('\n'.join([
self.delimiter.join(
[col.ljust(width) for col, width in zip(row, self.width)])
for row in self.rows]))
# clear cache
self.rows = []
def uncached_trim_print(self, data):
trimmed = {}
for c,m in self.max_width.items():
if len(data[c]) > m:
trimmed[c] = data[c][: m // 3] + '...' + data[c][ - (m - m // 3 - 3):]
if trimmed:
trimmed_data = [x for x in data]
for c,txt in trimmed.items():
trimmed_data[c] = txt
else:
trimmed_data = data
#
print(self.delimiter.join(
[col.ljust(width) for col, width in zip(trimmed_data, self.width)]))
#
# MODE 3: cached, untrimmed print
#
def cached_print(self, data):
self.rows.append(data)
if not self.width:
self.width = [len(x) for x in data]
else:
self.width = [max(y, len(x)) for y,x in zip(self.width, data)]
# cache size exceeds, use collected width and stop checking
if len(self.rows) > self.cache_size:
self.cached_print_rest()
# change print mode
self.write = self.uncached_trim_print
def cached_print_rest(self):
if not self.rows:
return
# do not ljust the last column. This avoids unnecessary spaces
# at the end of each line
self.width[-1] = 0
print('\n'.join([
self.delimiter.join(
[col.ljust(width) for col, width in zip(row, self.width)])
for row in self.rows]))
self.rows = []
def uncached_print(self, data):
print(self.delimiter.join(
[col.ljust(width) for col, width in zip(data, self.width)]))
def hasCommand(cmd):
try:
fnull = open(os.devnull, 'w')
result = subprocess.Popen(cmd, shell=True, stdout=fnull, stderr=fnull, env=OS_ENV)
result.terminate()
fnull.close()
except OSError:
# command not found
return False
except Exception:
# other error is OK
return True
return True
def runCommand(cmd, instream = None, msg = ''):
if isinstance(cmd, str):
cmd = shlex.split(cmd)
try:
tc = subprocess.Popen(cmd, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE,
env=OS_ENV)
if instream:
if sys.version_info.major == 3:
instream = instream.encode(sys.getdefaultencoding())
out, error = tc.communicate(instream)
else:
out, error = tc.communicate()
if sys.version_info.major == 3:
out = out.decode(sys.getdefaultencoding())
error = error.decode(sys.getdefaultencoding())
if tc.returncode < 0:
raise ValueError ("Command '{0}' was terminated by signal {1}".format(cmd, -tc.returncode))
elif tc.returncode > 0:
raise ValueError ("{0}".format(error))
else:
if error:
msg = "[WARNING] {0}: {1}".format(msg, error)
if env.logger is not None:
env.logger.debug(msg)
else:
sys.stderr.write(msg + '\n')
except OSError as e:
raise OSError ("Execution of command '{0}' failed: {1}".format(cmd, e))
return out
def openFile(filename):
if filename.lower().endswith('.tar.gz') or filename.lower().endswith('.tgz'):
raise RuntimeError('Please decompress {} before reading.'.format(filename))
if filename.lower().endswith('.gz'):
return gzip.open(filename, 'rb')
elif filename.lower().endswith('.bz2'):
return bz2.BZ2File(filename, 'rb')
else:
# text file
# because readline() from gzip.open will be byte, not string, we should return
# binary here in order to process them equally in order for things to work
# correctly under python 3
return open(filename, 'rb')
def typeOfValues(vals):
'''Figure out type of values and return INT, FLOAT or VARCHAR(maxLength)'''
vals = [x for x in vals if x.lower() not in ('na', 'null', 'none', '.', '')]
if len(vals) == 0:
# a good default value?
return 'VARCHAR(255)'
try:
map(int, vals)
return 'INT'
except:
try:
map(float, vals)
return 'FLOAT'
except:
return 'VARCHAR({})'.format(max([len(x) for x in vals]))
def safeMapFloat(x, nan = True):
for i, item in enumerate(x):
try:
x[i] = float(item)
except:
raise
if not nan and x[i] != x[i]:
raise
return x
class delayedAction:
'''Call the passed function with param after a few seconds. It is most often
used to display certain message only if an action takes a long time.
action = delayedAction(env.logger.info, 'This might take a while', 5)
some_action_that_might_take_a_while
del action
if the action finishes very quick, the message will not be displayed.
'''
def __init__(self, func, param, delay=5):
self.timer = threading.Timer(delay, func, (param,))
self.timer.start()
def __del__(self):
self.timer.cancel()
def filesInURL(URL, ext=''):
'''directory listing of a URL'''
fh = urllib.urlopen(URL)
files = []
for line in fh.readlines():
m = re.search('href="(.*){}"'.format(ext), line.decode())
if m:
files.append(m.group(1))
return files
from array import array
try:
from fcntl import ioctl
import termios
except ImportError:
pass
def getTermWidth():
if env.term_width is not None:
return env.term_width
try:
h, w = array('h', ioctl(sys.stderr, termios.TIOCGWINSZ, '\0' * 8))[:2]
return w
except:
return 78
class ProgressBar:
'''A text-based progress bar, it differs from regular progress bar in that
1. it can start from the middle with init count
2. it accept update for successful and failed counts
'''
def __init__(self, message, totalCount = None, initCount=0, initFailedCount=0):
if env.verbosity == '0':
self.update = self.empty
self.curlUpdate = self.empty
self.urllibUpdate = self.empty
self.sqliteUpdate = self.empty
self.outputProgress = self.empty
self.done = self.empty
self.main = ''
self.finished = 0
return
self.main = message
self.main_start_time = time.time()
self.message = self.main
# get terminal width
self.handle_resize()
#
# It appears that resizing window has caused some threads or processes to
# stop silently, leading to for example partially imported data. The reason
# is still unver investigation (might not be related to this) but this feature
# (resize progress bar dynamically) is temporarily removed.
#
#try:
# signal.signal(signal.SIGWINCH, self.handle_resize)
#except:
# # signal only works in main thread, so this might not work in all cases
# pass
# total count, including failed ones
self.count = max(0, initCount)
self.failed_count = max(0, initFailedCount)
# total initial count
self.init_count = initCount
self.init_failed_count = initFailedCount
#
self.finished = 0
self.reset('', totalCount)
def handle_resize(self, signum=None, frame=None):
'Tries to catch resize signals sent from the terminal.'
self.term_width = getTermWidth()
def reset(self, msg='', totalCount = None):
if msg:
self.message = '{} - {}'.format(self.main, msg)
self.finished += self.count
self.count = 0
self.failed_count = 0
self.totalCount = totalCount
self.start_time = None
self.last_time = None
self.outputProgress()
def empty(self, *args, **kwargs):
return
def update(self, count, failed_count=0):
'''completed count jobs, with failed_count failed jobs'''
if failed_count > count:
env.logger.warning('Failed count {} greater than completed count {}.'
.format(failed_count, count))
# if there is error ... just give it a number
failed_count = abs(failed_count)
count = failed_count
# do not update if the diferent is less than 0.1% of the total count.
# this is to avoid excess of calling the time() function
if self.totalCount is not None and (count - self.count) * 1000 < self.totalCount:
return
self.count = count
self.failed_count = failed_count
self.outputProgress()
def curlUpdate(self, total, existing, upload_t, upload_d):
'''Update called from pycurl'''
self.count = existing
self.totalCount = total
self.outputProgress()
def urllibUpdate(self, count, blockSize, totalSize):
'''Update called from urllib'''
self.count = count * blockSize
self.totalCount = totalSize
self.outputProgress()
def sqliteUpdate(self):
self.count += 1
if self.count % 1000 == 0:
self.outputProgress()
def outputProgress(self):
'''Output progress'''
if not self.start_time:
self.start_time = time.time()
self.last_time = self.start_time
cur_time = time.time()
# stop update progress bar more than once per second.
if self.count > 0 and self.count > self.init_count and \