-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathlegoo.py
executable file
·1616 lines (1463 loc) · 82 KB
/
legoo.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/python
# Patrick Luo
# innovation week of Mar 25, 2013
# objective: high performance, easy to use and maintain, flexibility to run anywhere on any DB (HIVE and MySQL), etc.
import os, sys, subprocess, inspect
import MySQLdb # MySQL DB module
import ConfigParser # parse mysql ini file
import csv # csv module for csv parsing
import logging
import datetime
from optparse import OptionParser
from time import sleep
from pprint import pprint # pretty print for dictionary etc
import operator
# logging config
logging.basicConfig(
filename = os.path.dirname(os.path.realpath(__file__)) + '/legoo.log', # set log file to legoo directory
format = "%(levelname)-10s:[%(module)s][%(funcName)s][%(asctime)s]:%(message)s",
level = logging.INFO
)
format = logging.Formatter("%(levelname)-10s:[%(module)s][%(funcName)s][%(asctime)s]:%(message)s")
# create a handler for stdout
info_hand = logging.StreamHandler(sys.stdout)
info_hand.setLevel(logging.INFO)
info_hand.setFormatter(format)
# top-level logger print to file
legoo = logging.getLogger("legoo")
legoo.addHandler(info_hand)
# add hive path
hive_path='/usr/lib/hive/lib/py/'
if hive_path not in sys.path:
sys.path.insert(0, hive_path)
trulia_mysql_host = ['bidbs', 'bidbm', 'bedb1', 'maildb-slave', 'db30', 'rodb-dash', 'db9', 'crad103']
def count_lines(**kwargs):
"""return line count for input file
--------------------------------------------------------------------
count_lines(file='/tmp/msa.csv', skip_header='Y')
--------------------------------------------------------------------
"""
debug = kwargs.pop("debug", "N")
if (debug.strip().lower() == 'y'):
pprint(kwargs) # pretty print kwargs
# dictionary initialized with the name=value pairs in the keyword argument list
file = kwargs.pop("file", None)
skip_header = kwargs.pop("skip_header", 'N' ) # flag to skip header
quiet = kwargs.pop("quiet", "N")
if (quiet.strip().lower() == 'y'):
legoo.removeHandler(info_hand) # suppress logging if variable quiet set to Y
if kwargs:
legoo.error("Unsupported configuration options %s" % list(kwargs)) # log error
raise TypeError("[ERROR] Unsupported configuration options %s" % list(kwargs))
p = subprocess.Popen(['wc', '-l', file],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
result, err = p.communicate()
if p.returncode != 0:
raise IOError(err)
num_lines = int(result.strip().split()[0])
# decrement num_lines if need to skip header
if (skip_header.strip().lower() == 'y'):
num_lines = num_lines - 1
legoo.info("[%s] line count ==>> [%s] lines" % (file, num_lines))
return num_lines
def remove_file(**kwargs):
"""remove file
---------------------------------
count_lines(file='/tmp/msa.csv')
---------------------------------
| file = None
| debug = N
"""
debug = kwargs.pop("debug", "N")
if (debug.strip().lower() == 'y'):
pprint(kwargs)
# dictionary initialized with the name=value pairs in the keyword argument list
file = kwargs.pop("file", None)
quiet = kwargs.pop("quiet", "N")
if (quiet.strip().lower() == 'y'):
legoo.removeHandler(info_hand) # suppress logging if variable quiet set to Y
if kwargs:
legoo.error("Unsupported configuration options %s" % list(kwargs)) # log error
raise TypeError("[ERROR] Unsupported configuration options %s" % list(kwargs))
p = subprocess.Popen(['rm', '-f', file],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
result, err = p.communicate()
if p.returncode != 0:
raise IOError(err)
legoo.info('File [%s] removed' % (file))
def count_hive_table_rows (**kwargs):
"""return hive table row count
-----------------------------------------------------------------------------------
count_hive_table_rows(hive_node='namenode2s', hive_db='bi', hive_table='dual')
-----------------------------------------------------------------------------------
"""
# dictionary initialized with the name=value pairs in the keyword argument list
debug = kwargs.pop("debug", "N")
if (debug.strip().lower() == 'y'):
pprint(kwargs) # pretty print kwargs
hive_node = kwargs.pop("hive_node", "namenode2s")
hive_port = kwargs.pop("hive_port", 10000)
hive_db = kwargs.pop("hive_db", "staging")
hive_table = kwargs.pop("hive_table", None)
mapred_job_priority = kwargs.pop("mapred_job_priority", "NORMAL")
quiet = kwargs.pop("quiet", "N")
if (quiet.strip().lower() == 'y'):
legoo.removeHandler(info_hand) # suppress logging if variable quiet set to Y
if kwargs:
legoo.error("Unsupported configuration options %s" % list(kwargs)) # log error
raise TypeError("[ERROR] Unsupported configuration options %s" % list(kwargs))
rs = execute_remote_hive_query( hive_node = hive_node, hive_port = hive_port, \
hive_db = hive_db, mapred_job_priority = mapred_job_priority, \
hive_query = "SELECT count(*) from %s" % (hive_table))
table_rows = rs[0]
legoo.info('[%s] row count ==>> [%s] rows' % (hive_table, table_rows))
return table_rows
def mysql_to_hive(**kwargs):
"""dump [mysql table | mysql query results] to hive
------------------------------------------------------------------------------
mysql_to_hive(mysql_host='bidbs', mysql_table='dim_time', hive_create_table='Y')
------------------------------------------------------------------------------
"""
debug = kwargs.pop("debug", "N")
if (debug.strip().lower() == 'y'):
pprint(kwargs) # pretty print kwargs
# args for mysql_to_csv
mysql_ini = kwargs.pop("mysql_ini", "mysql.ini")
mysql_host = kwargs.pop("mysql_host", "bidbs")
mysql_db = kwargs.pop("mysql_db", "bi")
mysql_user = kwargs.pop("mysql_user", "root")
mysql_quick = kwargs.pop("mysql_quick", "N")
mysql_table = kwargs.pop("mysql_table", None)
mysql_query = kwargs.pop("mysql_query", None)
mysql_password = kwargs.pop("mysql_password", None)
# args for csv_to_mysql
hive_node = kwargs.pop("hive_node", "namenode2s")
hive_port = kwargs.pop("hive_port", 10000)
hive_db = kwargs.pop("hive_db", "staging")
hive_table = kwargs.pop("hive_table", None)
hive_partition = kwargs.pop("hive_partition", None)
hive_ddl = kwargs.pop("hive_ddl", None)
hive_overwrite = kwargs.pop("hive_overwrite", "Y")
hive_create_table = kwargs.pop("hive_create_table", "N")
mapred_job_priority = kwargs.pop("mapred_job_priority", "NORMAL")
csv_dir = kwargs.pop("csv_dir", "/data/tmp/")
csv_file = kwargs.pop("csv_file", None)
csv_delimiter = kwargs.pop("csv_delimiter", 'tab') # default to tab csv_delimiter
remove_carriage_return = kwargs.pop("remove_carriage_return", 'N')
quiet = kwargs.pop("quiet", "N")
if (quiet.strip().lower() == 'y'):
legoo.removeHandler(info_hand) # suppress logging if variable quiet set to Y
if kwargs:
legoo.error("Unsupported configuration options %s" % list(kwargs)) # log error
raise TypeError("[ERROR] Unsupported configuration options %s" % list(kwargs))
# export mysql to csv
csv_file = mysql_to_csv( mysql_ini = mysql_ini, \
mysql_host = mysql_host, \
mysql_db = mysql_db, \
mysql_user = mysql_user, \
mysql_password = mysql_password, \
mysql_quick = mysql_quick, \
mysql_table = mysql_table, \
mysql_query = mysql_query, \
csv_dir = csv_dir, \
csv_file = csv_file, \
quiet = quiet, \
debug = debug)
# load csv to hive
csv_to_hive(hive_node = hive_node, \
hive_port = hive_port, \
hive_db = hive_db, \
hive_create_table = hive_create_table, \
hive_table = hive_table, \
hive_overwrite = hive_overwrite, \
hive_partition = hive_partition, \
hive_ddl = hive_ddl, \
mapred_job_priority = mapred_job_priority, \
csv_file = csv_file, \
csv_delimiter = csv_delimiter, \
remove_carriage_return = remove_carriage_return, \
quiet = quiet, \
debug = debug)
# remove temp files
remove_file(file=csv_file)
# temp files if remove_carriage_return is on
remove_file(file="%s%s" % (csv_file, '2'))
def mysql_to_csv(**kwargs):
"""export [mysql table | query results] to tab delmited csv and return the tsv
-------------------------------------------------------------------------------
mysql_to_csv(mysql_host='bidbs', mysql_table='dim_time')
mysql_to_csv(mysql_host='bidbs', mysql_query='select * from dim_time limit 10')
-------------------------------------------------------------------------------
"""
debug = kwargs.pop("debug", "N")
if (debug.strip().lower() == 'y'):
pprint(kwargs) # pretty print kwargs
# dictionary initialized with the name=value pairs in the keyword argument list
mysql_ini = kwargs.pop("mysql_ini", "mysql.ini")
mysql_host = kwargs.pop("mysql_host", "bidbs")
mysql_db = kwargs.pop("mysql_db", "bi")
mysql_user = kwargs.pop("mysql_user", "root")
mysql_password = kwargs.pop("mysql_password", None)
mysql_quick = kwargs.pop("mysql_quick", "N")
mysql_table = kwargs.pop("mysql_table", None)
mysql_query = kwargs.pop("mysql_query", None)
csv_dir = kwargs.pop("csv_dir", "/data/tmp/")
csv_file = kwargs.pop("csv_file", None)
csv_delimiter = kwargs.pop("csv_delimiter", 'tab') # default to tab csv_delimiter
quiet = kwargs.pop("quiet", "N")
if (quiet.strip().lower() == 'y'):
legoo.removeHandler(info_hand) # suppress logging if variable quiet set to Y
if kwargs:
legoo.error("Unsupported configuration options %s" % list(kwargs)) # log error
raise TypeError("[ERROR] Unsupported configuration options %s" % list(kwargs))
# parse the ini file to pull db variables
config = ConfigParser.ConfigParser()
config.read(os.path.join(os.path.dirname(__file__), mysql_ini))
# extend e mysql.ini if necessary
# set default mysql_user from mysql_ini
if (not mysql_user):
if (mysql_host not in trulia_mysql_host): # adhocdb use a non-standard password and db.
mysql_user = config.get(mysql_host, "user")
else:
mysql_user = config.get('default', "user")
if (not mysql_db):
if (mysql_host not in trulia_mysql_host): # adhocdb use a non-standard password and db.
mysql_db = config.get(mysql_host, "db")
else:
mysql_db = config.get('default', "db")
# set default mysql_password from mysql_ini
if (not mysql_password):
if (mysql_host not in trulia_mysql_host): # adhocdb use a non-standard password and db.
mysql_password = config.get(mysql_host, "password")
else:
mysql_password = config.get('default', "password")
# set default csv
if (not csv_file and not mysql_table ):
csv_file = "%s/tmp_%s.csv" % (csv_dir, os.getpid()) # set a temporary csv file name in
elif (not csv_file and mysql_table ):
csv_file = "%s/%s.csv" % (csv_dir, mysql_table)
if (not mysql_table and not mysql_query):
raise TypeError("[ERROR] Must specify either mysql_table or mysql_query" )
elif (mysql_table and not mysql_query):
mysql_query = "SELECT * FROM %s;" % (mysql_table)
if (mysql_quick and mysql_quick.strip().lower() == 'y'):
mysql_quick = "--quick"
else:
mysql_quick = ""
# mysql -hbidbs bi -e'select * from dim_time limit 10' > /tmp/test.csv
mysql_cmd = "mysql -h%s -u%s -p%s %s %s -e \"%s\" > %s" % \
(mysql_host, mysql_user, mysql_password, mysql_db, mysql_quick, mysql_query, csv_file)
mysql_cmd_without_password = "mysql -h%s -u%s %s %s -e \"%s\" > %s" % \
(mysql_host, mysql_user, mysql_db, mysql_quick, mysql_query, csv_file)
legoo.info("Running mysql export to csv ==>> [%s]" % ( mysql_cmd_without_password))
os.system( mysql_cmd )
if (debug.strip().lower() == 'y'):
# dump sample
csv_dump(csv_file=csv_file, csv_delimiter=csv_delimiter, lines=2)
return csv_file
def csv_to_hive(**kwargs):
"""import csv to to hive table.
1. create hive ddl base on csv header. use octal code for csv_delimiter
2. create hive table
3. upload csv without header to hdfs
4. load csv in hdfs to hive table
note: sqoop is buggy, many mandatory parameters, only run on hive node and other restrictions.
-----------------------------------------------------------------------------------
csv_to_hive(csv_file='/tmp/fact_imp_pdp.csv', csv_delimiter='tab', hive_create_table='Y')
-----------------------------------------------------------------------------------
"""
debug = kwargs.pop("debug", "N")
if (debug.strip().lower() == 'y'):
pprint(kwargs) # pretty print kwargs
# dictionary initialized with the name=value pairs in the keyword argument list
hive_node = kwargs.pop("hive_node", "namenode2s")
hive_port = kwargs.pop("hive_port", 10000)
hive_db = kwargs.pop("hive_db", "staging")
hive_table = kwargs.pop("hive_table", None)
hive_ddl = kwargs.pop("hive_ddl", None)
hive_overwrite = kwargs.pop("hive_overwrite", "Y")
hive_create_table = kwargs.pop("hive_create_table", "N")
hive_partition = kwargs.pop("hive_partition", None)
mapred_job_priority = kwargs.pop("mapred_job_priority", "NORMAL")
csv_file = kwargs.pop("csv_file", None)
csv_header = kwargs.pop("csv_header", "Y")
remove_carriage_return = kwargs.pop("remove_carriage_return", "N")
csv_delimiter = kwargs.pop("csv_delimiter", 'tab') # default to tab csv_delimiter
quiet = kwargs.pop("quiet", "N")
if (quiet.strip().lower() == 'y'):
legoo.removeHandler(info_hand) # suppress logging if variable quiet set to Y
if kwargs:
legoo.error("Unsupported configuration options %s" % list(kwargs)) # log error
raise TypeError("[ERROR] Unsupported configuration options %s" % list(kwargs))
if (not hive_table):
legoo.error("hive_table variable need to specified") # log error
raise TypeError("[ERROR] hive_table variable need to specified")
# if not hive_overwrite, set to append mode
if (hive_overwrite.strip().lower() == 'y'):
hive_overwrite = 'OVERWRITE'
else:
hive_overwrite = 'INTO'
# When input file has no header, create temp file with dummy header
if (csv_header.strip().lower() <> 'y'):
legoo.info("audto generating csv header ...")
temp_file = csv_file + '2'
# read first line of file
with open(csv_file, 'r') as f:
first_line = f.readline()
# autogen column name list
if (csv_delimiter.strip().lower() == 'tab'):
raw_delimiter = '\t'
else:
raw_delimiter = csv_delimiter
header_list = [ 'col_' + str(i) for i in range(len(first_line.split(raw_delimiter)))]
# write header to temp file
with open(temp_file,'w') as f:
wr = csv.writer(f, delimiter=raw_delimiter, quoting=csv.QUOTE_ALL, lineterminator='\n')
wr.writerow(header_list)
cmd_append = 'cat %s >> %s' % (csv_file, temp_file) # cmd to append file
os.system( cmd_append ) # os.system call is easier than subprocess
csv_file = temp_file
csv_header = 'Y'
# chcek table if exists on hive
if (hive_create_table.strip().lower() == 'n'):
execute_remote_hive_query( hive_node = hive_node, hive_port = hive_port, \
hive_db = hive_db, mapred_job_priority = mapred_job_priority, \
hive_query = "desc %s" % (hive_table))
if (hive_partition and hive_create_table.strip().lower() == 'y'):
hive_create_table ='N'
legoo.warning("hive_create_table can not set together with hive_partition. reset hive_create_table = N")
# create hive staging table ddl based on csv header, then create hive staging table
(filename, extension) = os.path.splitext(os.path.basename(csv_file))
hive_staging_table = "tmp_legoo_%s" % (os.getpid())
# replace . with _ in table name
# hive_staging_table = hive_staging_table.replace('.', '_')
# create staging table ddl
(hive_staging_table, hive_ddl) = create_hive_ddl_from_csv(csv_file = csv_file, \
csv_delimiter = csv_delimiter, \
table_name = hive_staging_table, \
quiet = quiet, \
debug = debug)
# drop staging table if exists
execute_remote_hive_query(hive_node = hive_node, hive_port = hive_port, \
hive_db = hive_db, mapred_job_priority = mapred_job_priority, \
quiet = quiet, debug = debug, \
hive_query = "DROP TABLE IF EXISTS %s" % (hive_staging_table))
# create empty table
execute_remote_hive_query( hive_node = hive_node, hive_port = hive_port, \
hive_db = hive_db, mapred_job_priority = mapred_job_priority, \
quiet = quiet, debug = debug, \
hive_query = hive_ddl)
# load csv to hive staging table
csv_to_hive_table(hive_node = hive_node, \
hive_port = hive_port, \
hive_db = hive_db, \
hive_table = hive_staging_table, \
hive_overwrite = hive_overwrite, \
mapred_job_priority = mapred_job_priority, \
csv_file = csv_file, \
csv_delimiter = csv_delimiter, \
csv_header = csv_header, \
remove_carriage_return = remove_carriage_return, \
quiet = quiet, \
debug = debug)
# example: hive_partition="date_int = 20130428"
if (hive_partition):
if (not hive_table):
legoo.error("hive_table need to specified")
raise TypeError("[ERROR] hive_table need to specified")
hive_query = "ALTER TABLE %s DROP IF EXISTS PARTITION (%s)" % (hive_table, hive_partition)
execute_remote_hive_query( hive_node = hive_node, hive_port = hive_port, \
hive_db = hive_db, mapred_job_priority = mapred_job_priority, \
quiet = quiet, debug = debug, \
hive_query = hive_query)
hive_query = "ALTER TABLE %s ADD PARTITION (%s)" % (hive_table, hive_partition)
execute_remote_hive_query( hive_node = hive_node, hive_port = hive_port, \
hive_db = hive_db, mapred_job_priority = mapred_job_priority, \
quiet = quiet, debug = debug, \
hive_query = hive_query)
# load staging table to target table
hive_query = "INSERT OVERWRITE TABLE %s partition (%s) select * from %s" % (hive_table, hive_partition, hive_staging_table)
elif (hive_create_table.strip().lower() == 'y'):
hive_query = "ALTER TABLE %s RENAME TO %s" % (hive_staging_table, hive_table)
elif (hive_create_table.strip().lower() == 'n'):
hive_query = "INSERT %s TABLE %s select * from %s" % (hive_overwrite, hive_table, hive_staging_table)
execute_remote_hive_query( hive_node = hive_node, hive_port = hive_port, \
hive_db = hive_db, mapred_job_priority = mapred_job_priority, \
quiet = quiet, debug = debug, \
hive_query = hive_query)
# drop staging table
hive_query = "DROP TABLE IF EXISTS %s" % (hive_staging_table)
execute_remote_hive_query( hive_node = hive_node, hive_port = hive_port, \
hive_db = hive_db, mapred_job_priority = mapred_job_priority, \
quiet = quiet, debug = debug, \
hive_query = hive_query)
if (hive_partition):
partition_str = "PARTITION (%s)" % hive_partition
else:
partition_str = ""
legoo.info("hive table [%s]:[%s].[%s] %s successfully built" % (hive_node, hive_db, hive_table, partition_str))
# check if temp file exists and remove
try:
temp_file
except NameError:
pass
else:
remove_file(file=temp_file) # remove temp file
def csv_to_hive_table(**kwargs):
"""import csv to to existing hive table.
1. upload csv without header to hdfs
2. load csv from hdfs to target hive table
note:
1. sqoop is slow, buggy, can't handle hive keywords, special character in input, etc
2. Two approaches to load into partition table. first approach is load from table. the other
approach use load infile which is more efficient but input file must have the same format
i.e. file type, csv_delimiter etc as target table definition. To make the tool more elastic and
more fault tolerant, first approach is choosen.
-----------------------------------------------------------------------------------
csv_to_hive_table(csv_file='/tmp/fact_imp_pdp.csv', csv_delimiter='tab', hive_create_table='Y')
-----------------------------------------------------------------------------------
"""
debug = kwargs.pop("debug", "N")
if (debug.strip().lower() == 'y'):
pprint(kwargs) # pretty print kwargs
# dictionary initialized with the name=value pairs in the keyword argument list
hive_node = kwargs.pop("hive_node", "namenode2s")
hive_port = kwargs.pop("hive_port", 10000)
hive_db = kwargs.pop("hive_db", "staging")
hive_table = kwargs.pop("hive_table", None)
hive_overwrite = kwargs.pop("hive_overwrite", "Y")
mapred_job_priority = kwargs.pop("mapred_job_priority", "NORMAL")
csv_file = kwargs.pop("csv_file", None)
csv_header = kwargs.pop("csv_header", "Y")
csv_delimiter = kwargs.pop("csv_delimiter", 'tab') # default to tab csv_delimiter
remove_carriage_return = kwargs.pop("remove_carriage_return", "N")
quiet = kwargs.pop("quiet", "N")
if (quiet.strip().lower() == 'y'):
legoo.removeHandler(info_hand) # suppress logging if variable quiet set to Y
if kwargs:
legoo.error("Unsupported configuration options %s" % list(kwargs)) # log error
raise TypeError("[ERROR] Unsupported configuration options %s" % list(kwargs))
# raise exception if partition specified but table name not specified
if (not hive_table):
legoo.error("Table [%s] must specified!" % (hive_table))
# trulia specific: ssh login to cdh4 cluster namenode2s as user dwr
if (hive_node.strip().lower().split('.')[0] == 'namenode2s'):
ssh_hive_node = 'dwr@' + hive_node
else:
ssh_hive_node = hive_node
# remove the carriage return from input csv file
if (remove_carriage_return.strip().lower() == 'y'):
temp_file = csv_file + '2'
cmd_remove_carriage_return = 'tr -d \'\\r\' < ' + csv_file + ' > ' + temp_file # replace carriage return with #
legoo.info("remove special chracter \\ with # ==>> [%s]" % (cmd_remove_carriage_return))
os.system( cmd_remove_carriage_return ) # os.system call is easier than subprocess
csv_file = temp_file
if (debug.strip().lower() == 'y'):
# dump the first 2 lines to verify
csv_dump(csv_file=csv_file, csv_delimiter=csv_delimiter, lines=2)
hdfs_inpath = "/tmp/" + hive_table # set hdfs_inpath
# hadoop will not overwrite a file - so we'll nuke it ourselves
hdfs_cmd = "ssh %s \'. .bash_profile; hadoop fs -rm %s 2>/dev/null\'" % (ssh_hive_node, hdfs_inpath)
legoo.info("running hdfs clean up ==>> [%s]" % ( hdfs_cmd))
os.system( hdfs_cmd ) # os.system call is easier than subprocess for |
# upload csv to hdfs. - for stdin, skip header
if (csv_header.strip().lower() == 'y'):
skip_header = 2
else:
skip_header = 1
hdfs_cmd = "tail -n +%d %s | ssh %s \'hadoop fs -put - %s\'" % (skip_header, csv_file, ssh_hive_node, hdfs_inpath)
legoo.info("running csv upload to hdfs ==>> [%s]" % ( hdfs_cmd))
os.system( hdfs_cmd ) # os.system call is easier than subprocess for |
# load data inpath '/tmp/fact_imp_pdp.csv' overwrite into table tmp_fact_imp_pdp;
# if not hive_overwrite, set to append mode
# Note that if the target table (or partition) already has a file whose name collides with any of the filenames contained in filepath, then the existing file will be replaced with the new file.
if (hive_overwrite.strip().lower() == 'y'):
hive_overwrite = ' OVERWRITE '
else:
hive_overwrite = ' '
if (csv_delimiter.strip().lower() == 'tab'): csv_delimiter = "\'\\t\'"
hive_load_query = "load data inpath \'%s\' %s into table %s" % (hdfs_inpath, hive_overwrite, hive_table)
execute_remote_hive_query( hive_node = hive_node, hive_port = hive_port, \
hive_db = hive_db, mapred_job_priority = mapred_job_priority, \
quiet = quiet, debug = debug, \
hive_query = hive_load_query)
# verify if table count match csv count
number_rows = count_hive_table_rows(hive_node = hive_node, hive_port = hive_port, \
hive_db = hive_db, mapred_job_priority = mapred_job_priority, \
quiet = quiet, debug = debug, \
hive_table = hive_table)
num_lines = count_lines(file=csv_file, skip_header=csv_header)
if ( int(num_lines) == int(number_rows) ):
legoo.info("file [%s] successfully loaded to hive table [%s]:[%s].[%s]. \n" % \
(csv_file, hive_node, hive_db, hive_table))
else:
legoo.error("file [%s] count not match hive table [%s]:[%s].[%s] count. \n" % \
(csv_file, hive_node, hive_db, hive_table))
raise Exception("[ERROR] file [%s] count not match hive table [%s]:[%s].[%s] count. \n" % \
(csv_file, hive_node, hive_db, hive_table))
def hive_to_mysql( **kwargs ):
"""export [hive table | user defined query ] to csv_file, create mysql table based on csv_file header,
then load csv_file to mysql table
--------------------------------------------------------------------------------------------------
hive_to_mysql(hive_table='fact_imp_pdp', hive_query='select * from bi.fact_imp_pdp limit 1100000')
--------------------------------------------------------------------------------------------------
"""
debug = kwargs.pop("debug", "N")
if (debug.strip().lower() == 'y'):
pprint(kwargs) # pretty print kwargs
# dictionary initialized with the name=value pairs in the keyword argument list
hive_node = kwargs.pop("hive_node", "namenode2s")
hive_db = kwargs.pop("hive_db", "bi")
hive_table = kwargs.pop("hive_table", None)
csv_file = kwargs.pop("csv_file", None)
hive_query = kwargs.pop("hive_query", None)
mapred_job_priority = kwargs.pop("mapred_job_priority", "NORMAL")
mysql_ini = kwargs.pop("mysql_ini", "mysql.ini")
mysql_host = kwargs.pop("mysql_host", "bidbs")
mysql_db = kwargs.pop("mysql_db", "bi_staging")
mysql_user = kwargs.pop("mysql_user", "root")
mysql_password = kwargs.pop("mysql_password", None)
mysql_table = kwargs.pop("mysql_table", None)
mysql_truncate_table = kwargs.pop("mysql_truncate_table", "Y")
csv_delimiter = kwargs.pop("csv_delimiter", 'tab') # default to tab csv_delimiter
csv_optionally_enclosed_by = kwargs.pop("csv_optionally_enclosed_by", None)
max_rows = kwargs.pop("max_rows", None)
mysql_create_table = kwargs.pop("mysql_create_table", "N")
quiet = kwargs.pop("quiet", "N")
if (quiet.strip().lower() == 'y'):
legoo.removeHandler(info_hand) # suppress logging if variable quiet set to Y
if kwargs:
legoo.error("Unsupported configuration options %s" % list(kwargs)) # log error
raise TypeError("[ERROR] Unsupported configuration options %s" % list(kwargs))
# export hive table to csv_file
csv_file = hive_to_csv(hive_node = hive_node, \
hive_db = hive_db, \
hive_table = hive_table, \
mapred_job_priority = mapred_job_priority, \
csv_file = csv_file, \
hive_query = hive_query, \
quiet = quiet, \
debug = debug)
# raw_input('press any key to continue ...')
# dump the first 10 lines to verify
if (debug.strip().lower() == 'y'):
csv_dump(csv_file=csv_file, csv_delimiter='tab', lines=10)
# raw_input('press any key to continue ...')
# import csv to mysql table
csv_to_mysql(mysql_host = mysql_host, \
mysql_db = mysql_db, \
mysql_user = mysql_user, \
mysql_password = mysql_password, \
mysql_table = mysql_table, \
mysql_truncate_table = mysql_truncate_table, \
csv_delimiter = csv_delimiter, \
csv_optionally_enclosed_by = csv_optionally_enclosed_by, \
csv_file = csv_file, \
max_rows = max_rows, \
mysql_create_table = mysql_create_table, \
quiet = quiet, \
debug = debug)
remove_file(file=csv_file) # remove temp file
def hive_to_csv( **kwargs ):
"""export [hive table | user defined hive_query ] to csv.
---------------------------------------------------------------------------------------------------------------
hive_to_csv(hive_table='fact_imp_pdp')
hive_to_csv(csv_file='/tmp/dim_listing.csv',hive_query='select * from bi.fact_imp_pdp limit 1100000',debug='Y')
---------------------------------------------------------------------------------------------------------------
"""
debug = kwargs.pop("debug", "N")
if (debug.strip().lower() == 'y'):
pprint(kwargs) # pretty print kwargs
hive_node = kwargs.pop("hive_node", "namenode2s")
hive_db = kwargs.pop("hive_db", "bi")
hive_table = kwargs.pop("hive_table", None)
hive_query = kwargs.pop("hive_query", None)
mapred_job_priority = kwargs.pop("mapred_job_priority", "NORMAL")
csv_dir = kwargs.pop("csv_dir", "/data/tmp/")
csv_file = kwargs.pop("csv_file", None)
quiet = kwargs.pop("quiet", "N")
if (quiet.strip().lower() == 'y'):
legoo.removeHandler(info_hand) # suppress logging if variable quiet set to Y
if kwargs:
legoo.error("Unsupported configuration options %s" % list(kwargs)) # log error
raise TypeError("[ERROR] Unsupported configuration options %s" % list(kwargs))
# trulia specific: login to cdh4 cluster namenode2s as dwr
if (hive_node.strip().lower().split('.')[0] == 'namenode2s'):
hive_node = 'dwr@' + hive_node
if (not csv_file):
if (not hive_table):
csv_file = csv_dir.strip() + str(os.getpid()).strip() + ".csv" # set default csv
else:
csv_file = csv_dir.strip() + hive_table + ".csv" # set default csv
else:
csv_file = csv_dir.strip() + csv_file.strip() # set default csv
if (not hive_query):
hive_query = "select * from %s.%s" % (hive_db, hive_table) # set default hive_query
# check and set default value for mapred_job_priority
if (mapred_job_priority.strip().upper() in ["VERY_HIGH", "HIGH", "NORMAL", "LOW", "VERY_LOW"]):
mapred_job_priority = mapred_job_priority.strip().upper()
else:
legoo.warning("option mapred_job_priority [%s] must in list [VERY_HIGH, HIGH, NORMAL, LOW, VERY_LOW]. default to NORMAL." % (mapred_job_priority))
mapred_job_priority = "NORMAL"
# hive_query must enclose with quote
hive_query = '\"use %s; set hive.cli.print.header=true; set mapred.job.priority=%s; ' % (hive_db, mapred_job_priority) + hive_query + ';\"'
hive_cmd = 'ssh %s hive -e ' % (hive_node) + hive_query + ' > ' + csv_file
legoo.info("running hive export ...\n[%s]\n" % (hive_cmd))
with open(csv_file, "w") as outfile:
rc = subprocess.call(['ssh', hive_node, 'hive', '-e', hive_query], stdout=outfile)
legoo.info("hive table %s:(%s) exported to %s ..." % (hive_node, hive_query, csv_file))
return csv_file
def csv_to_mysql(**kwargs):
"""create mysql table in target db (bidbs:bi_staging by default) based on csv header then import
csv to mysql table. The other four mysql_host, mysql_db, mysql_truncate_table and debug are optional.
------------------------------------------------------------------------------------------------
csv_to_mysql(csv_file='/tmp/fact_imp_pdp.csv', csv_delimiter='tab', mysql_create_table = 'Y')
------------------------------------------------------------------------------------------------
"""
debug = kwargs.pop("debug", "N")
if (debug.strip().lower() == 'y'):
pprint(kwargs) # pretty print kwargs
# dictionary initialized with the (name, value) pairs in the keyword argument list
mysql_host = kwargs.pop("mysql_host", "bidbs")
mysql_db = kwargs.pop("mysql_db", "bi_staging")
mysql_user = kwargs.pop("mysql_user", None)
mysql_password = kwargs.pop("mysql_password", None)
mysql_create_table = kwargs.pop("mysql_create_table", "N")
mysql_table = kwargs.pop("mysql_table", None)
mysql_truncate_table = kwargs.pop("mysql_truncate_table", "N")
csv_file = kwargs.pop("csv_file", None)
csv_header = kwargs.pop("csv_header", "Y")
csv_delimiter = kwargs.pop("csv_delimiter", 'tab') # default to tab csv_delimiter
csv_optionally_enclosed_by = kwargs.pop("csv_optionally_enclosed_by", None)
max_rows = kwargs.pop("max_rows", None)
quiet = kwargs.pop("quiet", "N")
if (quiet.strip().lower() == 'y'):
legoo.removeHandler(info_hand) # suppress logging if variable quiet set to Y
if kwargs:
legoo.error("Unsupported configuration options %s" % list(kwargs)) # log error
raise TypeError("[ERROR] Unsupported configuration options %s" % list(kwargs))
# check number of lines in csv file
num_lines = count_lines(file=csv_file, skip_header=csv_header)
if (int(num_lines) == 0):
legoo.error("%s is empty!" % (csv_file))
raise TypeError("[ERROR] %s is empty!" % (csv_file))
# create table if mysql_create_table set to Y
if (mysql_create_table.strip().lower() == 'y'):
# create ddl
(mysql_table_name, ddl) = create_mysql_ddl_from_csv(csv_file = csv_file, \
csv_delimiter = csv_delimiter, \
table_name = mysql_table, \
max_rows = max_rows, \
mysql_create_table = mysql_create_table, \
quiet = quiet, \
debug = debug)
# create table
execute_mysql_query(mysql_host = mysql_host, \
mysql_db = mysql_db, \
mysql_user = mysql_user, \
mysql_password = mysql_password, \
mysql_query = ddl, \
quiet = quiet, \
debug = debug)
# set mysql_table to mysql_table_name if not specified
if (not mysql_table):
mysql_table = mysql_table_name
if (mysql_truncate_table.strip().lower() == 'y'):
execute_mysql_query(mysql_host=mysql_host, mysql_db=mysql_db, \
mysql_user=mysql_user, mysql_password=mysql_password, \
mysql_query="TRUNCATE TABLE %s.%s" % (mysql_db, mysql_table), \
quiet = quiet, debug=debug)
# check table row count
mysql_query = "select count(*) from %s.%s;" % (mysql_db, mysql_table)
(affected_rows, number_rows) = execute_mysql_query(mysql_host=mysql_host, mysql_db=mysql_db, \
mysql_user=mysql_user, mysql_password=mysql_password, \
mysql_query=mysql_query, row_count='Y', \
quiet = quiet, debug=debug)
table_count_before_load = number_rows
# load csv into mysql table
csv_to_mysql_table(mysql_host=mysql_host, mysql_db=mysql_db, mysql_user=mysql_user, \
mysql_password=mysql_password, mysql_table=mysql_table, \
csv_file=csv_file, csv_header=csv_header, csv_delimiter=csv_delimiter, \
csv_optionally_enclosed_by=csv_optionally_enclosed_by, \
quiet = quiet, debug=debug)
(affected_rows, number_rows) = execute_mysql_query(mysql_host=mysql_host, mysql_db=mysql_db, \
mysql_user=mysql_user, mysql_password=mysql_password, \
mysql_query=mysql_query, row_count='Y', \
quiet = quiet, debug=debug)
table_count_after_load = number_rows
# delta: diff between table count before load and after load
number_rows = int(table_count_after_load) - int(table_count_before_load)
legoo.info("MySQL table [%s]:[%s].[%s] load count ==>> [%s]" % (mysql_host, mysql_db, mysql_table, number_rows))
# verify the csv line count and table count
if ( int(num_lines) == int(number_rows) ):
legoo.info("file [%s] successfully loaded to mysql table [%s]:[%s].[%s]" % (csv_file, mysql_host, mysql_db, mysql_table))
else:
legoo.error("file [%s] count does not match mysql table [%s]:[%s].[%s] load count" % (csv_file, mysql_host, mysql_db, mysql_table))
raise Exception("[ERROR] file [%s] count does not match mysql table [%s]:[%s].[%s] load count" % (csv_file, mysql_host, mysql_db, mysql_table))
def csv_to_mysql_table(**kwargs):
"""import csv to existing mysql table in target db (bidbs:bi_staging by default) with 5 parameters.
mysql_table is required. The other four mysql_host, mysql_db, mysql_truncate_table and debug are optional.
-----------------------------------------------------------------------------------------------------
csv_to_mysql_table(mysql_table='tmp_table', csv_file='/tmp/hive_bi_dim_listing.csv', csv_delimiter='tab')
-----------------------------------------------------------------------------------------------------
"""
debug = kwargs.pop("debug", "N")
if (debug.strip().lower() == 'y'):
pprint(kwargs) # pretty print kwargs
# dictionary initialized with the name=value pairs in the keyword argument list
mysql_host = kwargs.pop("mysql_host", "bidbs")
mysql_db = kwargs.pop("mysql_db", "bi_staging")
mysql_user = kwargs.pop("mysql_user", None)
mysql_password = kwargs.pop("mysql_password", None)
mysql_table = kwargs.pop("mysql_table", None)
csv_file = kwargs.pop("csv_file", None)
csv_delimiter = kwargs.pop("csv_delimiter", 'tab') # default to tab csv_delimiter
csv_header = kwargs.pop("csv_header", "Y")
csv_optionally_enclosed_by = kwargs.pop("csv_optionally_enclosed_by", None)
quiet = kwargs.pop("quiet", "N")
if (quiet.strip().lower() == 'y'):
legoo.removeHandler(info_hand) # suppress logging if variable quiet set to Y
if kwargs:
legoo.error("Unsupported configuration options %s" % list(kwargs)) # log error
raise TypeError("[ERROR] Unsupported configuration options %s" % list(kwargs)) # raise error and exit
# run mysql dml
if (not mysql_table):
legoo.error("need to specify mysql_table")
raise TypeError("need to specify mysql_table")
# add quote to csv_delimiter
if (csv_delimiter.strip().lower() == 'tab'):
csv_delimiter = '\\t'
# print '%s:csv_delimiter =>>>> [%s]' %(sys._getframe().f_code.co_name, csv_delimiter)
if (csv_optionally_enclosed_by):
enclosed_by = "OPTIONALLY ENCLOSED BY '%s'" % (csv_optionally_enclosed_by)
else:
enclosed_by = ''
if (csv_header.strip().lower() == 'n'):
ignore_line = ''
else:
ignore_line = 'IGNORE 1 LINES'
# if (csv_optionally_enclosed_by = '\"')
mysql_dml = """LOAD DATA LOCAL INFILE '%s'
INTO TABLE %s
FIELDS TERMINATED BY '%s' %s %s""" % (csv_file, mysql_table, csv_delimiter, enclosed_by, ignore_line)
# adhocdb/adhocmaildb cant LOAD DATA using MySQLDB client. it is possible due to older version of MySQL Server
# fall back to less preferred system command
if (mysql_host not in trulia_mysql_host): # adhocdb use a non-standard password and db
mysql_cmd = 'mysql -h%s -u%s -p%s %s -e "%s"' % \
( mysql_host, mysql_user, mysql_password, mysql_db, mysql_dml)
legoo.info("running MySQL command: [%s]" % (mysql_cmd))
os.system( mysql_cmd )
else:
execute_mysql_query(mysql_host=mysql_host, mysql_db=mysql_db, \
mysql_user=mysql_user, mysql_password=mysql_password, \
mysql_query=mysql_dml, \
quiet = quiet, debug=debug)
def execute_remote_hive_query(**kwargs):
"""execute hive query on remote hive node
-------------------------------------------------------
execute_remote_hive_query(hive_query='desc top50_ip;')
-------------------------------------------------------
"""
debug = kwargs.pop("debug", "N")
if (debug.strip().lower() == 'y'):
pprint(kwargs) # pretty print kwargs
# dictionary initialized with the name=value pairs in the keyword argument list
hive_node = kwargs.pop("hive_node", "namenode2s")
hive_port = kwargs.pop("hive_port", 10000)
hive_db = kwargs.pop("hive_db", "staging")
hive_query = kwargs.pop("hive_query", None)
mapred_job_priority = kwargs.pop("mapred_job_priority", "NORMAL")
quiet = kwargs.pop("quiet", "N")
if (quiet.strip().lower() == 'y'):
legoo.removeHandler(info_hand) # suppress logging if variable quiet set to Y
if kwargs:
legoo.error("Unsupported configuration options %s" % list(kwargs)) # log error
raise TypeError("[ERROR] Unsupported configuration options %s" % list(kwargs)) # raise error and exit
# check and set default value for mapred_job_priority
if (mapred_job_priority.strip().upper() in ["VERY_HIGH", "HIGH", "NORMAL", "LOW", "VERY_LOW"]):
mapred_job_priority = mapred_job_priority.strip().upper()
else:
legoo.warning("option mapred_job_priority [%s] must in list [VERY_HIGH, HIGH, NORMAL, LOW, VERY_LOW]. default to NORMAL." % (mapred_job_priority))
mapred_job_priority = "NORMAL"
from hive_service import ThriftHive
from hive_service.ttypes import HiveServerException
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
# hive_query must enclose with quote
hive_query_with_quote = '\"use %s; %s\"' % (hive_db, hive_query)
# print hive_query_with_quote
hive_cmd = 'ssh %s hive -e %s' % (hive_node, hive_query_with_quote)
legoo.info("running hive query on [%s]:[%s] ==>> [%s]" % (hive_node, hive_db, hive_query))
# rc = subprocess.call(['ssh', hive_node, 'hive', '-e', hive_query_with_quote])
result_set = [0]
try:
transport = TSocket.TSocket(hive_node, hive_port)
transport = TTransport.TBufferedTransport(transport)
protocol = TBinaryProtocol.TBinaryProtocol(transport)
client = ThriftHive.Client(protocol)
transport.open()
client.execute("use %s" % (hive_db))
client.execute("set mapred.job.priority=%s" % (mapred_job_priority))
client.execute(hive_query)
# client.execute("desc dim_listing")
# client.execute("select * from dim_listing limit 10")
result_set = client.fetchAll()
transport.close()
return result_set
except Thrift.TException, tx:
raise Exception('[ERROR] %s' % (tx.message))
def execute_mysql_query(**kwargs):
"""return tuple (rows_affected, number_of_rows) after execute mysql query on target db (bidbs:bi_staging by default).
-------------------------------------------------------------------------------------------------
execute_mysql_query(mysql_host='bidbs', mysql_db='bi_staging', mysql_query='select current_date')
-------------------------------------------------------------------------------------------------
"""
debug = kwargs.pop("debug", "N")
if (debug.strip().lower() == 'y'):
pprint(kwargs) # pretty print kwargs
# dictionary initialized with the name=value pairs in the keyword argument list
mysql_ini = kwargs.pop("mysql_ini", "mysql.ini")
mysql_host = kwargs.pop("mysql_host", "bidbs")
mysql_db = kwargs.pop("mysql_db", "bi_staging")
mysql_user = kwargs.pop("mysql_user", None)
mysql_password = kwargs.pop("mysql_password", None)
mysql_query = kwargs.pop("mysql_query", None)
row_count = kwargs.pop("row_count", "N")
quiet = kwargs.pop("quiet", "N")
if (quiet.strip().lower() == 'y'):
legoo.removeHandler(info_hand) # suppress logging if variable quiet set to Y
if kwargs:
legoo.error("Unsupported configuration options %s" % list(kwargs)) # log error
raise TypeError("[ERROR] Unsupported configuration options %s" % list(kwargs)) # raise error and exit
number_of_rows = rows_affected = 0 # set default value
legoo.info("running mysql query on [%s]:[%s] ==>> [%s]" % (mysql_host, mysql_db, mysql_query))
try:
mysql_conn = create_mysql_connection(mysql_ini = mysql_ini, \
mysql_host = mysql_host, \
mysql_db = mysql_db, \
mysql_user = mysql_user, \
mysql_password = mysql_password, \
quiet = quiet, \
debug = debug \
)
cursor = mysql_conn.cursor()
rows_affected = cursor.execute(mysql_query)
if (row_count.strip().lower() == 'y'):
(number_of_rows,)=cursor.fetchone() # used for counts
else:
rs = cursor.fetchall()
if (len(rs) > 0):
pprint(rs)
if (debug.strip().lower() == 'y'):
legoo.info('[%s] rows affected by query [%s].' % (rows_affected, mysql_query))
legoo.info('[INFO] [%s] number of rows returned by query [%s].' % (number_of_rows, mysql_query))
return (rows_affected, number_of_rows)
except MySQLdb.Error as e:
legoo.info('[ERROR] [%s] failed on [%s].[%s]' % ( mysql_query, mysql_host, mysql_db))
legoo.info("[ERROR] %d: %s" % (e.args[0], e.args[1]))
raise
finally:
cursor.close()
mysql_conn.close()
def qa_mysql_table(**kwargs):
debug = kwargs.pop("debug", "N")
if (debug.strip().lower() == 'y'):
pprint(kwargs) # pretty print kwargs
# dictionary initialized with the name=value pairs in the keyword argument list
mysql_ini = kwargs.pop("mysql_ini", "mysql.ini")
mysql_host = kwargs.pop("mysql_host", "bidbs")
mysql_db = kwargs.pop("mysql_db", "bi_staging")
mysql_user = kwargs.pop("mysql_user", None)
mysql_password = kwargs.pop("mysql_password", None)
mysql_query = kwargs.pop("mysql_query", None)
comparison_operator = kwargs.pop("comparison_operator", None)
threshhold_value = kwargs.pop("threshhold_value", None)
quiet = kwargs.pop("quiet", "N")
if (quiet.strip().lower() == 'y'):
legoo.removeHandler(info_hand) # suppress logging if variable quiet set to Y
if kwargs:
legoo.error("Unsupported configuration options %s" % list(kwargs)) # log error
raise TypeError("[ERROR] Unsupported configuration options %s" % list(kwargs)) # raise error and exit
(affected_rows, number_rows) = execute_mysql_query(mysql_host = mysql_host, \
mysql_db = mysql_db, \
mysql_user = mysql_user, \
mysql_password = mysql_password, \
mysql_query = mysql_query, \
row_count = 'Y', \
quiet = quiet, \
debug = debug)
# print "number_rows => [%s]; options.comparison_operator => [%s]; options.threshhold => [%s]" % \ (number_rows, options.comparison_operator, options.threshhold)
if ( (not mysql_query) or (not comparison_operator) or (not threshhold_value)):
legoo.error("option mysql_query, comparison_operator, threshhold_value not all set. must specify all three ... ") # log error
raise TypeError("option mysql_query, comparison_operator, threshhold_value not all set. must specify all three...") # raise error and exit
# build operator dictionary to python built in operator
ops = {"=": operator.eq,
"==": operator.eq,
"!=": operator.ne,
"<>": operator.ne,
"<": operator.lt,
"<=": operator.le,
">": operator.gt,
">=": operator.ge
}
# may the key to the build-in operator
op_func = ops[comparison_operator]
if op_func(int(number_rows), int(threshhold_value)):
legoo.info('[INFO] [%s] passed test: {[%s] [%s] [%s]}' % (mysql_query, number_rows, comparison_operator, threshhold_value))
else: