-
Notifications
You must be signed in to change notification settings - Fork 150
Expand file tree
/
Copy pathmadpack.py
More file actions
executable file
·1593 lines (1400 loc) · 64.8 KB
/
madpack.py
File metadata and controls
executable file
·1593 lines (1400 loc) · 64.8 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
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 python3
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Main Madpack installation executable.
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
import sys
import getpass
import re
import os
import glob
import traceback
import subprocess
import datetime
import tempfile
import shutil
import upgrade_util as uu
from utilities import _write_to_file
from utilities import error_
from utilities import get_dbver
from utilities import get_db_madlib_version
from utilities import get_rev_num
from utilities import info_
from utilities import is_rev_gte
from utilities import remove_comments_from_sql
from utilities import run_query
# Required Python version
py_min_ver = [2, 7]
if list(sys.version_info[:2]) < py_min_ver:
print("ERROR: python version too old ({0}). You need {1} or greater.".
format('.'.join(map(str, sys.version_info[:3])),
'.'.join(map(str, py_min_ver))))
exit(1)
# raw_input isn't defined in Python3.x, whereas input wasn't behaving like raw_input in Python 2.x
# this should make both input and raw_input work in Python 2.x/3.x like the raw_input from Python 2.x
try: input = raw_input
except NameError: raw_input = input
# Find MADlib root directory. This file is installed to
# $MADLIB_ROOT/madpack/madpack.py, so to get $MADLIB_ROOT we need to go
# two levels up in the directory hierarchy. We use (a) os.path.realpath and
# (b) __file__ (instead of sys.argv[0]) because madpack.py could be called
# (a) through a symbolic link and (b) not as the main module.
maddir = os.path.abspath(os.path.dirname(os.path.realpath(__file__)) + "/..") # MADlib root dir
sys.path.append(maddir + "/madpack")
# Import MADlib python modules
import argparse
import configyml
# Some read-only variables
this = os.path.basename(sys.argv[0]) # name of this script
# Default directories
maddir_conf = maddir + "/config" # Config dir
maddir_lib = "libmadlib.so" # C/C++ libraries
# Read the config files
ports = configyml.get_ports(maddir_conf) # object made of Ports.yml
new_madlib_ver = configyml.get_version(maddir_conf) # MADlib OS-level version
portid_list = []
for port in ports:
portid_list.append(port)
SUPPORTED_PORTS = ('postgres', 'greenplum', 'cloudberry')
# Global variables
portid = None # Target port ID (eg: pg90, gp40)
dbver = None # DB version
con_args = {} # DB connection arguments
verbose = None # Verbose flag
keeplogs = None
tmpdir = None
DB_CREATE_OBJECTS = "db_create_objects"
INSTALL_DEV_CHECK = "install_dev_check"
UNIT_TEST = "unit_test"
def _make_dir(dir):
"""
# Create a temp dir
# @param dir temp directory path
"""
if not os.path.isdir(dir):
try:
os.makedirs(dir)
except:
print("ERROR: can not create directory: %s. Check permissions." % dir)
exit(1)
# ------------------------------------------------------------------------------
def _internal_run_query(sql, show_error):
"""
Runs a SQL query on the target platform DB
using the default command-line utility.
Very limited:
- no text output with "new line" characters allowed
@param sql query text to execute
@param show_error displays the SQL error msg
"""
return run_query(sql, con_args, show_error)
# ------------------------------------------------------------------------------
def _get_relative_maddir(maddir, port):
""" Return a relative path version of maddir
GPDB installations have a symlink outside of GPHOME that
links to the current GPHOME. After a DB upgrade, this symlink is updated to
the new GPHOME.
'maddir_lib', which uses the absolute path of GPHOME, is hardcoded into each
madlib function definition. Replacing the GPHOME path with the equivalent
relative path makes it simpler to perform DB upgrades without breaking MADlib.
"""
if port == 'postgres':
# do nothing for postgres
return maddir
# e.g. maddir_lib = $GPHOME/madlib/Versions/1.9/lib/libmadlib.so
# 'madlib' is supposed to be in this path, which is the default folder
# used by GPPKG to install madlib
try:
abs_gphome, tail = maddir.split('madlib/')
except ValueError:
return maddir
# Check outside $GPHOME if there is a symlink to this absolute path
# os.pardir is equivalent to ..
# os.path.normpath removes the extraneous .. from that path
rel_gphome = os.path.normpath(os.path.join(abs_gphome, os.pardir, 'greenplum-db'))
if (os.path.islink(rel_gphome) and
os.path.realpath(rel_gphome) == os.path.realpath(abs_gphome)):
# if the relative link exists and is pointing to current location
return os.path.join(rel_gphome, 'madlib', tail)
else:
return maddir
# ------------------------------------------------------------------------------
def _cleanup_comments_in_sqlfile(output_filename, upgrade):
"""
@brief Remove comments in the sql script, and re-write the file with the
cleaned up script.
"""
if not upgrade:
with open(output_filename, 'r+') as output_filehandle:
full_sql = output_filehandle.read()
full_sql = remove_comments_from_sql(full_sql)
# Re-write the cleaned-up sql to a new file. Python does not let us
# erase all the content of a file and rewrite the same file again.
cleaned_output_filename = output_filename+'.tmp'
with open(cleaned_output_filename, 'w') as output_filehandle:
_write_to_file(output_filehandle, full_sql)
# Move the cleaned output file to the old one.
os.rename(cleaned_output_filename, output_filename)
def _run_m4_and_append(schema, maddir_mod_py, module, sqlfile,
output_filehandle, pre_sql=None):
"""
Function to process a sql file with M4.
"""
# Check if the SQL file exists
if not os.path.isfile(sqlfile):
error_(this, "Missing module SQL file (%s)" % sqlfile, False)
raise ValueError
# Prepare the file using M4
try:
# Add the before SQL
if pre_sql:
output_filehandle.writelines([pre_sql, '\n\n'])
# Find the madpack dir (platform specific or generic)
if os.path.isdir(maddir + "/ports/" + portid + "/" + dbver + "/madpack"):
maddir_madpack = maddir + "/ports/" + portid + "/" + dbver + "/madpack"
else:
maddir_madpack = maddir + "/madpack"
maddir_ext_py = maddir + "/lib/python"
m4args = ['m4',
'-P',
'-DMADLIB_SCHEMA=' + schema,
'-DPLPYTHON_LIBDIR=' + maddir_mod_py,
'-DEXT_PYTHON_LIBDIR=' + maddir_ext_py,
'-DMODULE_PATHNAME=' + maddir_lib,
'-DMADLIB_LIBRARY_PATH=' + madlib_library_path,
'-DMODULE_NAME=' + module,
'-I' + maddir_madpack,
sqlfile]
if ( (portid == 'postgres') &
(is_rev_gte(get_rev_num(dbver), get_rev_num('14.0'))) or
(portid == 'cloudberry') ):
m4args = ['m4',
'-P',
'-DMADLIB_SCHEMA=' + schema,
'-DPLPYTHON_LIBDIR=' + maddir_mod_py,
'-DEXT_PYTHON_LIBDIR=' + maddir_ext_py,
'-DMODULE_PATHNAME=' + maddir_lib,
'-DMADLIB_LIBRARY_PATH=' + madlib_library_path,
'-DMODULE_NAME=' + module,
'-DUSE_COMPATIBLE_ARRAY=TRUE',
'-I' + maddir_madpack,
sqlfile]
info_(this, "> ... parsing: " + " ".join(m4args), verbose)
output_filehandle.flush()
subprocess.call(m4args, stdout=output_filehandle)
except:
error_(this, "Failed executing m4 on %s" % sqlfile, False)
raise Exception
def _run_install_check_sql(schema, maddir_mod_py, module, sqlfile,
tmpfile, logfile, pre_sql):
"""
Run SQL file
@param schema name of the target schema
@param maddir_mod_py name of the module dir with Python code
@param module name of the module
@param sqlfile name of the file to parse
@param tmpfile name of the temp file to run
@param logfile name of the log file (stdout)
@param pre_sql optional SQL to run before executing the file
"""
try:
f = open(tmpfile, 'w')
_run_m4_and_append(schema, maddir_mod_py, module, sqlfile, f, pre_sql)
f.close()
except:
error_(this, "Failed to temp m4 processed file %s." % tmpfile, False)
raise Exception
# Only update function definition
sub_module = ''
# Run the SQL using DB command-line utility
if portid in SUPPORTED_PORTS:
sqlcmd = 'psql'
# Test the DB cmd line utility
std, err = subprocess.Popen(['which', sqlcmd], stdout=subprocess.PIPE,
stderr=subprocess.PIPE).communicate()
if not std:
error_(this, "Command not found: %s" % sqlcmd, True)
runcmd = [sqlcmd, '-a',
'-v', 'ON_ERROR_STOP=1',
'-h', con_args['host'].split(':')[0],
'-p', con_args['host'].split(':')[1],
'-d', con_args['database'],
'-U', con_args['user'],
'--no-password',
'-f', tmpfile]
runenv = os.environ
if 'password' in con_args:
runenv["PGPASSWORD"] = con_args['password']
runenv["PGOPTIONS"] = '-c client_min_messages=notice'
# Open log file
try:
log = open(logfile, 'w')
except:
error_(this, "Cannot create log file: %s" % logfile, False)
raise Exception
# Run the SQL
try:
info_(this, "> ... executing " + tmpfile, verbose)
retval = subprocess.call(runcmd, env=runenv, stdout=log, stderr=log)
except:
error_(this, "Failed executing %s" % tmpfile, False)
raise Exception
finally:
log.close()
return retval
# ------------------------------------------------------------------------------
def _run_sql_file(schema, sqlfile):
"""
Run SQL file
@param schema name of the target schema
@param sqlfile name of the file to parse
"""
# Run the SQL using DB command-line utility
if portid in SUPPORTED_PORTS:
sqlcmd = 'psql'
# Test the DB cmd line utility
std, err = subprocess.Popen(['which', sqlcmd], stdout=subprocess.PIPE,
stderr=subprocess.PIPE).communicate()
if not std:
error_(this, "Command not found: %s" % sqlcmd, True)
runcmd = [sqlcmd, '-a',
'-v', 'ON_ERROR_STOP=1',
'-h', con_args['host'].split(':')[0],
'-p', con_args['host'].split(':')[1],
'-d', con_args['database'],
'-U', con_args['user'],
'--no-password',
'--single-transaction',
'-f', sqlfile]
runenv = os.environ
if 'password' in con_args:
runenv["PGPASSWORD"] = con_args['password']
runenv["PGOPTIONS"] = '-c client_min_messages=notice'
# Open log file
logfile = sqlfile + '.log'
try:
log = open(logfile, 'w')
except:
error_(this, "Cannot create log file: %s" % logfile, False)
raise Exception
# Run the SQL
try:
info_(this, "> ... executing " + sqlfile, verbose)
info_(this, ' '.join(runcmd), verbose)
retval = subprocess.call(runcmd, env=runenv, stdout=log, stderr=log)
except:
error_(this, "Failed executing %s" % sqlfile, False)
raise Exception
finally:
log.close()
# Check the exit status
result = _parse_result_logfile(retval, logfile, sqlfile)
return result
# ------------------------------------------------------------------------------
def _parse_result_logfile(retval, logfile, sql_abspath,
sql_filename=None, module=None, milliseconds=None):
"""
Function to parse the logfile and return if its content indicate a failure
or success.
"""
is_install_check_logfile = bool(sql_filename and module)
# Check the exit status
if retval != 0:
result = 'FAIL'
global keeplogs
keeplogs = True
# Since every single statement in the test file gets logged,
# an empty log file indicates an empty or a failed test
elif os.path.isfile(logfile) and os.path.getsize(logfile) > 0:
result = 'PASS'
# Otherwise
else:
result = 'ERROR'
if is_install_check_logfile:
# Output result
print("TEST CASE RESULT|Module: " + module + \
"|" + os.path.basename(sql_filename) + "|" + result + \
"|Time: %d milliseconds" % (milliseconds))
if result == 'FAIL':
error_(this, "Failed executing %s" % sql_abspath, stop=False)
error_(this, "Check the log at %s" % logfile, stop=False)
return result
def _check_db_port(portid):
"""
Make sure we are connected to the expected DB platform
@param portid expected DB port id - to be validates
"""
# Postgres
try:
row = _internal_run_query("SELECT version() AS version", True)
except:
error_(this, "Cannot validate DB platform type", True)
if row and row[0]['version'].lower().find(portid) >= 0:
if portid == 'postgres':
if row[0]['version'].lower().find('greenplum') < 0:
return True
elif portid == 'greenplum' or portid == 'cloudberry':
return True
return False
# ------------------------------------------------------------------------------
def _print_vers(new_madlib_ver, db_madlib_ver, con_args, schema):
"""
Print version information
@param new_madlib_ver OS-level MADlib version
@param db_madlib_ver DB-level MADlib version
@param con_args database connection arguments
@param schema MADlib schema name
"""
info_(this, "MADlib tools version = %s (%s)" % (str(new_madlib_ver), sys.argv[0]), True)
if con_args:
try:
info_(this, "MADlib database version = %s (host=%s, db=%s, schema=%s)"
% (db_madlib_ver, con_args['host'], con_args['database'], schema), True)
except:
info_(this, "MADlib database version = [Unknown] (host=%s, db=%s, schema=%s)"
% (db_madlib_ver, con_args['host'], con_args['database'], schema), True)
return
# ------------------------------------------------------------------------------
def _plpy_check(py_min_ver):
"""
Check pl/python existence and version
@param py_min_ver min Python version to run MADlib
"""
info_(this, "Testing PL/Python environment...", True)
# Check PL/Python existence
rv = _internal_run_query("SELECT count(*) AS CNT FROM pg_language "
"WHERE lanname = 'plpython3u'", True)
if int(rv[0]['cnt']) > 0:
info_(this, "> PL/Python already installed", verbose)
else:
info_(this, "> PL/Python not installed", verbose)
info_(this, "> Creating language PL/Python...", True)
try:
_internal_run_query("CREATE LANGUAGE plpython3u;", True)
except:
error_(this, """Cannot create language plpython3u. Please check if you
have configured and installed portid (your platform) with
`--with-python` option. Stopping installation...""", False)
raise Exception
# Check PL/Python version
_internal_run_query("DROP FUNCTION IF EXISTS plpy_version_for_madlib();", False)
_internal_run_query("""
CREATE OR REPLACE FUNCTION plpy_version_for_madlib()
RETURNS TEXT AS
$$
import sys
# return '.'.join(str(item) for item in sys.version_info[:3])
return str(sys.version_info[:3]).replace(',','.').replace(' ','').replace(')','').replace('(','')
$$
LANGUAGE plpython3u;
""", True)
rv = _internal_run_query("SELECT plpy_version_for_madlib() AS ver;", True)
python = rv[0]['ver']
py_cur_ver = [int(i) for i in python.split('.')]
if py_cur_ver >= py_min_ver:
info_(this, "> PL/Python version: %s" % python, verbose)
else:
error_(this, "PL/Python version too old: %s. You need %s or greater"
% (python, '.'.join(str(i) for i in py_min_ver)), False)
raise Exception
_internal_run_query("DROP FUNCTION IF EXISTS plpy_version_for_madlib();", False)
info_(this, "> PL/Python environment OK (version: %s)" % python, True)
# ------------------------------------------------------------------------------
def _db_install(schema, is_schema_in_db, filehandle):
"""
Install MADlib
@param schema MADlib schema name
@param is_schema_in_db flag to indicate if schema is already present
@param filehandle file that contains the sql for installation
@param testcase command-line args for a subset of modules
"""
# Create MADlib objects
try:
_db_create_schema(schema, is_schema_in_db, filehandle)
_db_create_objects(schema, filehandle)
except:
error_(this, "Building database objects failed. "
"Before retrying: drop %s schema OR install MADlib into "
"a different schema." % schema, True)
# ------------------------------------------------------------------------------
def _db_upgrade(schema, filehandle, db_madlib_ver):
"""
Upgrade MADlib
@param schema MADlib schema name
@param filehandle Handle to output file
@param db_madlib_ver DB-level MADlib version
"""
if is_rev_gte(get_rev_num(db_madlib_ver), get_rev_num(new_madlib_ver)):
info_(this, "Current MADlib version already up to date.", True)
return 1
if is_rev_gte(get_rev_num('1.9.1'), get_rev_num(db_madlib_ver)):
error_(this, """
MADlib versions prior to v1.10 are not supported for upgrade.
Please try upgrading to v1.10 and then upgrade to this version.
""", True)
return 1
info_(this, "Upgrading MADlib into %s schema..." % schema, True)
info_(this, "\tDetecting dependencies...", True)
info_(this, "\tLoading change list...", True)
ch = uu.ChangeHandler(schema, portid, con_args, maddir, db_madlib_ver, filehandle)
info_(this, "\tDetecting table dependencies...", True)
td = uu.TableDependency(schema, portid, con_args)
info_(this, "\tDetecting view dependencies...", True)
vd = uu.ViewDependency(schema, portid, con_args)
abort = False
if td.has_dependency():
info_(this, "*" * 50, True)
info_(this, "\tFollowing user tables/indexes are dependent on MADlib objects:", True)
info_(this, td.get_dependency_str(), True)
info_(this, "*" * 50, True)
cd_udt = [udt for udt in td.get_depended_udt() if udt in ch.udt]
if len(cd_udt) > 0:
error_(this, """
User has objects dependent on following updated MADlib types!
{0}
These objects need to be dropped before upgrading.
""".format('\n\t\t\t'.join(cd_udt)), False)
# we add special handling for 'linregr_result'
if 'linregr_result' in cd_udt:
info_(this, """Dependency on 'linregr_result' could be due to objects
created from the output of the aggregate 'linregr'.
Please refer to the Linear Regression documentation
<http://madlib.apache.org/docs/latest/group__grp__linreg.html#warning>
for the recommended solution.
""", False)
abort = True
c_udoc = ch.get_udoc_oids()
d_udoc = td.get_depended_udoc_oids()
cd_udoc = [udoc for udoc in d_udoc if udoc in c_udoc]
if len(cd_udoc) > 0:
error_(this, """
User has objects dependent on the following updated MADlib operator classes!
oid={0}
These objects need to be dropped before upgrading.
""".format('\n\t\t\t'.join(cd_udoc)), False)
abort = True
if vd.has_dependency():
info_(this, "*" * 50, True)
info_(this, "\tFollowing user views are dependent on MADlib objects:", True)
info_(this, vd.get_dependency_graph_str(), True)
info_(this, "*" * 50, True)
d_udf = vd.get_depended_func_signature('UDF')
if len(d_udf) > 0:
error_(this, """
User has objects dependent on following updated MADlib functions!
{0}
These objects might fail to work with the updated functions and
need to be dropped before starting upgrade again.
""".format('\n\t\t\t\t\t'.join(d_udf)), False)
abort = True
d_uda = vd.get_depended_func_signature('UDA')
if len(d_uda) > 0:
error_(this, """
User has objects dependent on following updated MADlib aggregates!
{0}
These objects might fail to work with the new aggregates and
need to be dropped before starting upgrade again.
""".format('\n\t\t\t\t\t'.join(d_uda)), False)
abort = True
d_udo = vd.get_depended_opr_oids()
if len(d_udo) > 0:
error_(this, """
User has objects dependent on following updated MADlib operators!
oid={0}
These objects might fail to work with the new operators and
need to be dropped before starting upgrade again.
""".format('\n\t\t\t\t\t'.join(d_udo)), False)
abort = True
if abort:
error_(this, """------- Upgrade aborted. -------
Backup and drop all objects that depend on MADlib before trying upgrade again.
Use madpack reinstall to automatically drop these objects only if appropriate.""", True)
else:
info_(this, "No dependency problem found, continuing to upgrade ...", True)
info_(this, "\tReading existing UDAs/UDTs...", False)
sc = uu.ScriptCleaner(schema, portid, con_args, ch)
info_(this, "Script Cleaner initialized ...", False)
function_drop_str = get_madlib_function_drop_str(schema)
flist = function_drop_str.split("\n\n")
for i in flist:
_internal_run_query(i, True)
operator_drop_str = get_madlib_operator_drop_str(schema)
_internal_run_query(operator_drop_str, True)
ch.drop_changed_udc()
ch.drop_changed_udt() # assume dependent udf for udt does not change
_db_create_objects(schema, filehandle, True, sc)
return 0
# ------------------------------------------------------------------------------
def _db_rename_schema(from_schema, to_schema):
"""
Rename schema
@param from_schema name of the schema to rename
@param to_schema new name for the schema
"""
info_(this, "> Renaming schema %s to %s" % (from_schema, to_schema), True)
try:
_internal_run_query("ALTER SCHEMA %s RENAME TO %s;" % (from_schema, to_schema), True)
except:
error_(this, 'Cannot rename schema. Stopping installation...', False)
raise Exception
# ------------------------------------------------------------------------------
def _db_create_schema(schema, is_schema_in_db, filehandle):
"""
Create schema
@param from_schema name of the schema to rename
@param is_schema_in_db flag to indicate if schema is already present
@param to_schema new name for the schema
"""
if not is_schema_in_db:
_write_to_file(filehandle, "CREATE SCHEMA %s;" % schema)
# ------------------------------------------------------------------------------
def _process_py_sql_files_in_modules(modset, args_dict):
"""
This function executes relevant files from all applicable modules
(either all modules, or specific modules specified as a comma
separated list).
* If the operation is install/dev check, then all the corresponding sql
files are executed.
* If the operation is unit-test, then all corresponding python files
are executed.
* If the operation was from _db_create_objects(), then all the relevant
objects are written to files for execution during install/reinstall/upgrade.
"""
if 'madpack_cmd' in args_dict:
madpack_cmd = args_dict['madpack_cmd']
else:
madpack_cmd = None
if not madpack_cmd:
calling_operation = DB_CREATE_OBJECTS
elif madpack_cmd in ['install-check', 'dev-check']:
calling_operation = INSTALL_DEV_CHECK
elif madpack_cmd == 'unit-test':
calling_operation = UNIT_TEST
else:
error_(this, "Invalid madpack operation: %s" % madpack_cmd, True)
# Perform operations on all modules
for moduleinfo in portspecs['modules']:
# Get the module name
module = moduleinfo['name']
# Skip if doesn't meet specified modules
if modset and module not in modset:
continue
# Find the Python module dir (platform specific or generic)
if os.path.isdir(maddir + "/ports/" + portid + "/" + dbver + "/modules/" + module):
maddir_mod_py = maddir + "/ports/" + portid + "/" + dbver + "/modules"
else:
maddir_mod_py = maddir + "/modules"
# Find the SQL module dir (platform specific or generic)
if os.path.isdir(maddir + "/ports/" + portid + "/modules/" + module):
maddir_mod_sql = maddir + "/ports/" + portid + "/modules"
elif os.path.isdir(maddir + "/modules/" + module):
maddir_mod_sql = maddir + "/modules"
else:
# This was a platform-specific module, for which no default exists.
# We can just skip this module.
continue
# Make a temp dir for log files
cur_tmpdir = tmpdir + "/" + module
_make_dir(cur_tmpdir)
if calling_operation == DB_CREATE_OBJECTS:
info_(this, "> - %s" % module, True)
mask = maddir_mod_sql + '/' + module + '/*.sql_in'
elif calling_operation == INSTALL_DEV_CHECK:
if madpack_cmd == 'install-check':
mask = maddir_mod_sql + '/' + module + '/test/*.ic.sql_in'
else:
mask = maddir_mod_sql + '/' + module + '/test/*.sql_in'
elif calling_operation == UNIT_TEST:
mask = maddir_mod_py + '/' + module + '/test/unit_tests/test_*.py'
else:
error_(this, "Something is wrong, shouldn't be here.", True)
# Loop through all SQL files for this module
source_files = glob.glob(mask)
source_files = [s for s in source_files if '.setup' not in s]
if calling_operation == INSTALL_DEV_CHECK and madpack_cmd != 'install-check':
source_files = [s for s in source_files if '.ic' not in s]
# Do this error check only when running install/reinstall/upgrade
if calling_operation == DB_CREATE_OBJECTS and not source_files:
error_(this, "No files found in: %s" % mask, True)
# Execute all SQL/py files for the module
for src_file in source_files:
algoname = os.path.basename(src_file).split('.')[0]
# run only algo specified
if (modset and modset[module] and
algoname not in modset[module]):
continue
if calling_operation == DB_CREATE_OBJECTS:
_execute_per_module_db_create_obj_algo(
args_dict['schema'],
maddir_mod_py,
module,
src_file,
algoname,
cur_tmpdir,
args_dict['upgrade'],
args_dict['create_obj_handle'],
args_dict['sc'])
elif calling_operation == INSTALL_DEV_CHECK:
# Skip certain tests for GP4.3
if dbver == '4.3ORCA' and module in ['deep_learning', 'kmeans']:
continue
_execute_per_module_install_dev_check_algo(
args_dict['schema'],
args_dict['test_user'],
maddir_mod_py,
module,
src_file,
cur_tmpdir)
elif calling_operation == UNIT_TEST:
_execute_per_module_unit_test_algo(
module,
src_file,
cur_tmpdir)
else:
error_(this, "Something is wrong, shouldn't be here: %s" % src_file, True)
if calling_operation == DB_CREATE_OBJECTS:
shutil.rmtree(cur_tmpdir)
# ------------------------------------------------------------------------------
def _execute_per_module_db_create_obj_algo(schema, maddir_mod_py, module,
sqlfile, algoname, cur_tmpdir,
upgrade, create_obj_handle, sc):
"""
Perform operations that have to be done per module when
_db_create_objects function is invoked
"""
if not upgrade:
_run_m4_and_append(schema, maddir_mod_py, module, sqlfile,
create_obj_handle, None)
else:
tmpfile = cur_tmpdir + '/' + os.path.basename(sqlfile) + '.tmp'
with open(tmpfile, 'w+') as tmphandle:
_run_m4_and_append(schema, maddir_mod_py, module, sqlfile,
tmphandle, None)
processed_sql = sc.cleanup(open(tmpfile).read(), algoname)
_write_to_file(create_obj_handle, processed_sql)
# ------------------------------------------------------------------------------
def _execute_per_module_unit_test_algo(module, pyfile, cur_tmpdir):
"""
Perform opertions that have to be done per module when
unit tests are run
"""
logfile = cur_tmpdir + '/' + os.path.basename(pyfile) + '.log'
try:
log = open(logfile, 'w')
except:
error_(this, "Cannot create log file: %s" % logfile, False)
raise Exception
info_(this, "> ... executing " + pyfile, verbose)
try:
milliseconds = 0
run_start = datetime.datetime.now()
# Run the python unit test file
runcmd = ["python3", pyfile]
# runenv = os.environ
runenv = os.environ.copy()
# GPDB6 python3 support is provided by an additional package.
# To access it, we will have to set environment variables.
if dbver == '6':
gphome = runenv["GPHOME"]
runenv["LD_LIBRARY_PATH"] = "{0}/ext/python3.9/lib:".format(gphome) + runenv["LD_LIBRARY_PATH"]
runenv["PATH"] = "{0}/ext/python3.9/bin:".format(gphome) + runenv["PATH"]
runenv["PYTHONHOME"] = "{0}/ext/python3.9".format(gphome)
runenv["PYTHONPATH"] = "{0}/ext/python3.9/lib".format(gphome)
retval = subprocess.call(runcmd, env=runenv, stdout=log, stderr=log)
run_end = datetime.datetime.now()
milliseconds = round((run_end - run_start).seconds * 1000 +
(run_end - run_start).microseconds / 1000)
except:
error_(this, "Failed executing %s" % pyfile, False)
raise Exception
finally:
log.close()
_parse_result_logfile(retval, logfile, pyfile,
pyfile, module, milliseconds)
# ------------------------------------------------------------------------------
def _execute_per_module_install_dev_check_algo(schema, test_user,
maddir_mod_py, module,
sqlfile, cur_tmpdir):
"""
Perform opertions that have to be done per module when
install-check or dev-check is run
"""
try:
# Prepare test schema
test_schema = "madlib_installcheck_%s" % (module)
_internal_run_query("DROP SCHEMA IF EXISTS %s CASCADE; CREATE SCHEMA %s;" %
(test_schema, test_schema), True)
_internal_run_query("GRANT ALL ON SCHEMA %s TO \"%s\";" %
(test_schema, test_user), True)
# Switch to test user and prepare the search_path
pre_sql = '-- Switch to test user:\n' \
'SET ROLE \"%s\";\n' \
'-- Set SEARCH_PATH for install-check:\n' \
'SET search_path=%s,%s;\n' \
% (test_user, test_schema, schema)
# Set file names
tmpfile = cur_tmpdir + '/' + os.path.basename(sqlfile) + '.tmp'
logfile = cur_tmpdir + '/' + os.path.basename(sqlfile) + '.log'
# If there is no problem with the SQL file
milliseconds = 0
# Run the SQL
run_start = datetime.datetime.now()
retval = _run_install_check_sql(schema, maddir_mod_py,
module, sqlfile, tmpfile,
logfile, pre_sql)
# Runtime evaluation
run_end = datetime.datetime.now()
milliseconds = round((run_end - run_start).seconds * 1000 +
(run_end - run_start).microseconds / 1000)
# Check the exit status
result = _parse_result_logfile(retval, logfile, tmpfile, sqlfile,
module, milliseconds)
finally:
# Cleanup test schema for the module
_internal_run_query("DROP SCHEMA IF EXISTS %s CASCADE;" % (test_schema), True)
# ------------------------------------------------------------------------------
def _db_create_objects(schema, create_obj_handle, upgrade=False, sc=None):
"""
Create MADlib DB objects in the schema
@param schema Name of the target schema
@param create_obj_handle file handle for sql output file
@param upgrade flag to indicate if it's an upgrade operation or not
@param sc ScriptCleaner object
"""
if not upgrade:
# Create MigrationHistory table
try:
_write_to_file(create_obj_handle,
"DROP TABLE IF EXISTS %s.migrationhistory;" % schema)
sql = """CREATE TABLE %s.migrationhistory
(id serial, version varchar(255),
applied timestamp default current_timestamp);
""" % schema
_write_to_file(create_obj_handle, sql)
except:
error_(this, "Cannot create MigrationHistory table", False)
raise Exception
# Stamp the DB installation
try:
_write_to_file(create_obj_handle,
"""INSERT INTO %s.migrationhistory(version)
VALUES('%s');
""" % (schema, str(new_madlib_ver)))
except:
error_(this, "Cannot insert data into %s.migrationhistory table" % schema, False)
raise Exception
try:
_write_to_file(create_obj_handle,
"""SET dynamic_library_path = '%s';
""" % (dynamic_library_path))
except:
error_(this, "Cannot set dynamic_library_path to %s" % dynamic_library_path, False)
raise Exception
# Run migration SQLs
info_(this, "> Preparing objects for the following modules:", True)
# We always create objects for all modules during install/reinstall/upgrade
modset = {}
_process_py_sql_files_in_modules(modset, locals())
# ------------------------------------------------------------------------------
def unescape(string):
"""
Unescape separation characters in connection strings, i.e., remove first
backslash from "\/", "\@", "\:", and "\\".
"""
if string is None:
return None
else:
return re.sub(r'\\(?P<char>[/@:\\])', '\g<char>', string)
# ------------------------------------------------------------------------------
def parseConnectionStr(connectionStr):
"""
@brief Parse connection strings of the form
<tt>[username[/password]@][hostname][:port][/database]</tt>
Separation characters (/@:) and the backslash (\) need to be escaped.
@returns A tuple (username, password, hostname, port, database). Field not
specified will be None.
"""
match = re.search(
r'((?P<user>([^/@:\\]|\\/|\\@|\\:|\\\\)+)' +
r'(/(?P<password>([^/@:\\]|\\/|\\@|\\:|\\\\)*))?@)?' +
r'(?P<host>([^/@:\\]|\\/|\\@|\\:|\\\\)+)?' +
r'(:(?P<port>[0-9]+))?' +
r'(/(?P<database>([^/@:\\]|\\/|\\@|\\:|\\\\)+))?', connectionStr)
return (
unescape(match.group('user')),
unescape(match.group('password')),
unescape(match.group('host')),
match.group('port'),
unescape(match.group('database')))
# ------------------------------------------------------------------------------
def parse_arguments():
parser = argparse.ArgumentParser(
prog="madpack",
description='MADlib package manager (' + str(new_madlib_ver) + ')',
argument_default=False,
formatter_class=argparse.RawTextHelpFormatter,
epilog="""Example:
$ madpack install -s madlib -p greenplum -c gpadmin@mdw:5432/testdb
This will install MADlib objects into a Greenplum database called TESTDB
running on server MDW:5432. Installer will try to login as GPADMIN
and will prompt for password. The target schema will be MADLIB.
$ madpack dev-check
This will run dev-check on all the installed modules in MADlib. Another
similar, but light-weight check, is called install-check.
$ madpack unit-test -t convex,recursive_partitioning/decision_tree
This will run all the unit tests that are defined in the convex module, and
for decision trees in the recursive partitioning module.
The -t option runs tests only for required modules, and can be used similarly
for install-check, dev-check and unit-test.
""")
help_msg = """One of the following options:
install : load MADlib into DB
upgrade : upgrade MADlib
uninstall : uninstall MADlib from DB
reinstall : perform uninstall and install
version : compare and print MADlib version (binaries vs database objects)
install-check : quick test of installed modules
dev-check : more detailed test of installed modules
unit-test : unit tests of installed modules
"""
choice_list = ['install', 'update', 'upgrade', 'uninstall',
'reinstall', 'version', 'install-check',
'dev-check', 'unit-test']
parser.add_argument('command', metavar='COMMAND', nargs=1,
choices=choice_list, help=help_msg)
parser.add_argument(
'-c', '--conn', metavar='CONNSTR', nargs=1, dest='connstr', default=None,
help="""Connection string of the following syntax:
[user[/password]@][host][:port][/database]
If not provided default values will be derived for PostgreSQL and Greenplum:
- user: PGUSER or USER env variable or OS username
- pass: PGPASSWORD env variable or runtime prompt
- host: PGHOST env variable or 'localhost'
- port: PGPORT env variable or '5432'
- db: PGDATABASE env variable or OS username""")
parser.add_argument('-s', '--schema', nargs=1, dest='schema',
metavar='SCHEMA', default='madlib',
help="Target schema for the database objects.")
parser.add_argument('-p', '--platform', nargs=1, dest='platform',
metavar='PLATFORM', choices=portid_list,
help="Target database platform, current choices: " + str(portid_list))
parser.add_argument('-v', '--verbose', dest='verbose',
action="store_true", help="Verbose mode.")
parser.add_argument('-l', '--keeplogs', dest='keeplogs', default=False,
action="store_true", help="Do not remove installation log files.")
parser.add_argument('-d', '--tmpdir', dest='tmpdir', default='/tmp/',
help="Temporary directory location for installation log files.")