-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathweb.py
1226 lines (1059 loc) · 47.5 KB
/
web.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
####################################################################
######### Copyright 2016-2017 BigSQL ###########
####################################################################
from flask import Flask, render_template, url_for, request, session, redirect
import os
from flask_triangle import Triangle
from flask_restful import reqparse, abort, Api, Resource
from flask_login import user_logged_in
from flask_security import auth_token_required, auth_required
import json
from Components import Components as pgc
from flask_security import login_required, roles_required, current_user, roles_accepted
# from flask_login import current_user
from flask_mail import Mail
from flask_babel import Babel, gettext
from pgadmin.utils.session import create_session_interface
from pgadmin.model import db, Role, User, Server, ServerGroup, Process, roles_users
from pgadmin.utils.crypto import encrypt, decrypt, pqencryptpassword
from flask_security import Security, SQLAlchemyUserDatastore
from pgadmin.utils.sqliteSessions import SqliteSessionInterface
from pgadmin.utils.driver import get_driver
import config
from config import PG_DEFAULT_DRIVER
from flask_restful import reqparse
from datetime import datetime, timedelta
import dateutil
import hashlib
import time
import pytz
import psutil
from pickle import dumps, loads
import csv
import sqlite3
from werkzeug.contrib.fixers import ProxyFix
parser = reqparse.RequestParser()
#parser.add_argument('data')
import platform
this_uname = str(platform.system())
PGC_HOME = os.getenv("PGC_HOME", "")
PGC_LOGS = os.getenv("PGC_LOGS", "")
config.APP_NAME = "pgDevOps"
config.LOGIN_NAME = "pgDevOps"
application = Flask(__name__)
application.wsgi_app = ProxyFix(application.wsgi_app)
babel = Babel(application)
Triangle(application)
api = Api(application)
application.config.from_object(config)
current_path = os.path.dirname(os.path.realpath(__file__))
reports_path = os.path.join(current_path, "reports")
##########################################################################
# Setup session management
##########################################################################
application.session_interface = SqliteSessionInterface(config.SESSION_DB_PATH)
application.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{0}?timeout={1}'.format(
config.SQLITE_PATH.replace('\\', '/'),
getattr(config, 'SQLITE_TIMEOUT', 500)
)
application.config['WTF_CSRF_ENABLED'] = False
application.config['SECURITY_RECOVERABLE'] = True
application.config['SECURITY_CHANGEABLE'] = True
application.config['SECURITY_REGISTERABLE'] = True
application.config['SECURITY_REGISTER_URL'] = '/register'
application.config['SECURITY_CONFIRMABLE'] = False
application.config['SECURITY_SEND_REGISTER_EMAIL'] = False
application.config['SECURITY_TOKEN_MAX_AGE'] = 600
application.permanent_session_lifetime = timedelta(minutes=10)
db.init_app(application)
Mail(application)
import pgadmin.utils.paths as paths
paths.init_app(application)
#Enviornment variable for restrict api action commands
os.environ['IS_DEVOPS'] = "True"
def before_request():
if not current_user.is_authenticated and request.endpoint == 'security.login' and no_admin_users():
return redirect(url_for('security.register'))
if not current_user.is_authenticated and request.endpoint == 'security.register' and not no_admin_users():
return redirect(url_for('security.login'))
application.before_request(before_request)
from forms import RegisterForm, check_ami
# Setup Flask-Security
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(application, user_datastore, register_form=RegisterForm)
from flask_security.signals import user_registered
is_ami = check_ami()
def no_admin_users():
if not len(User.query.filter(User.roles.any(name='Administrator'), User.active == True).all()) > 0:
return True
return False
@user_registered.connect_via(application)
def on_user_registerd(app, user, confirm_token):
sg = ServerGroup(
user_id=user.id,
name="Servers")
db.session.add(sg)
if is_ami.get('rc') != 2:
session['initial-logged-in'] = True
db.session.commit()
default_user = user_datastore.get_user('[email protected]')
if not len(User.query.filter(User.roles.any(name='Administrator'),User.active==True).all()) > 0 :
if default_user is not None and default_user.has_role('Administrator') and not default_user.active:
db.session.delete(default_user)
db.session.commit()
user_datastore.add_role_to_user(user.email, 'Administrator')
return
user_datastore.add_role_to_user(user.email, 'User')
@user_logged_in.connect_via(application)
def on_user_logged_in(sender, user):
try:
from pgadmin.model import UserPreference, Preferences
bin_pref = Preferences.query.filter_by(
name="pg_bin_dir"
).order_by("id").first()
check_pref = UserPreference.query.filter_by(
pid=bin_pref.id,
uid=user.id
).order_by("pid")
if check_pref.count() > 0:
pass
else:
path = None
for p in ["pg10", "pg96", "pg95", "pg94"]:
bin_path = os.path.join(PGC_HOME, p, "bin")
if os.path.exists(bin_path):
path = bin_path
break
if path:
pref = UserPreference(
pid=bin_pref.id,
uid=user.id,
value=path
)
db.session.add(pref)
db.session.commit()
except Exception as e:
pass
from pgstats import pgstats
application.register_blueprint(pgstats, url_prefix='/pgstats')
from credentials import credentials
application.register_blueprint(credentials, url_prefix='/api/pgc/credentials')
from CloudHandler import cloud
application.register_blueprint(cloud, url_prefix='/api/pgc/instances')
from CloudCreateHandler import _cloud_create
application.register_blueprint(_cloud_create, url_prefix='/api/pgc/create')
from ProvisionHandler import _pgc_provision
application.register_blueprint(_pgc_provision, url_prefix='/api/pgc/provision')
from BackupRestore import _backrest
application.register_blueprint(_backrest, url_prefix='/api/pgc')
from login_controller import _user
application.register_blueprint(_user, url_prefix='/api/login')
from UserHandler import _user_management
application.register_blueprint(_user_management, url_prefix='/api/user')
db_session = db.session
class pgcRestApi(Resource):
@auth_required('token', 'session')
def get(self, arg):
if current_user.has_role("Developer"):
non_admin_cmds = ['list', 'lablist', 'info', 'status', 'register', 'metalist']
if arg.split(" ")[0] in non_admin_cmds:
data = pgc.get_data(arg)
return data
return unauth_handler()
data = pgc.get_data(arg)
return data
api.add_resource(pgcRestApi,
'/api/pgc/<string:arg>')
class checkInitLogin(Resource):
@auth_required('token', 'session')
def get(self):
if is_ami.get('rc') != 2 and session.get('initial-logged-in'):
session['initial-logged-in'] = False
return True
return False
api.add_resource(checkInitLogin,
'/check_init_login')
class pgcUtilRelnotes(Resource):
@auth_required('token', 'session')
def get(self, comp, version=None):
json_dict = {}
v=version
import mistune, util, sys
if version == None:
rel_notes = unicode(str(util.get_relnotes (comp)),sys.getdefaultencoding(),errors='ignore').strip()
else:
rel_notes=unicode(str(util.get_relnotes (comp, version)),sys.getdefaultencoding(),errors='ignore').strip()
json_dict['component'] = comp
json_dict['relnotes'] = mistune.markdown(rel_notes)
# # json_dict['plainText'] = rel_notes
data = json.dumps([json_dict])
return data
api.add_resource(pgcUtilRelnotes, '/api/utilRelnotes/<string:comp>','/api/utilRelnotes/<string:comp>/<string:version>')
class pgcApiHostCmd(Resource):
@auth_required('token', 'session')
@roles_accepted('Administrator', 'User')
def get(self, pgc_cmd, host_name,pwd=None):
password=pwd
pwd_session_name = "{0}_pwd".format(host_name)
if session.get("hostname", "") == host_name:
if not pwd and session.get(pwd_session_name):
password = session.get(pwd_session_name)
else:
session[pwd_session_name] = pwd
elif host_name is None or host_name in ("", "localhost"):
pwd_session_name="localhost_pwd"
if not pwd and session.get(pwd_session_name):
password = session.get(pwd_session_name)
else:
session[pwd_session_name] = pwd
session['hostname'] = host_name
data = pgc.get_data(pgc_cmd, pgc_host=host_name, pwd=password)
if len(data)>0 and data[0].get("pwd_failed"):
if session.get(pwd_session_name):
session.pop(pwd_session_name)
return data
api.add_resource(pgcApiHostCmd,
'/api/hostcmd/<string:pgc_cmd>/<string:host_name>',
'/api/hostcmd/<string:pgc_cmd>/<string:host_name>/<string:pwd>/')
class pgdgCommand(Resource):
@auth_required('token', 'session')
@roles_accepted('Administrator','User')
def get(self, repo_id, pgc_cmd, host=None, pwd=None):
password = pwd
pwd_session_name = "{0}_pwd".format(host)
if session.get("hostname", "") == host:
if not pwd and session.get(pwd_session_name):
password = session.get(pwd_session_name)
else:
session[pwd_session_name] = pwd
elif host is None or host in ("", "localhost"):
pwd_session_name = "localhost_pwd"
if not pwd and session.get("localhost_pwd"):
password = session.get("localhost_pwd")
else:
session['localhost_pwd'] = pwd
data = pgc.get_pgdg_data(repo_id, pgc_cmd, pgc_host=host, pwd=password)
if len(data)>0 and data[0].get("pwd_failed"):
if session.get(pwd_session_name):
session.pop(pwd_session_name)
return data
api.add_resource(pgdgCommand,
'/api/pgdg/<string:repo_id>/<string:pgc_cmd>',
'/api/pgdg/<string:repo_id>/<string:pgc_cmd>/<string:host>',
'/api/pgdg/<string:repo_id>/<string:pgc_cmd>/<string:host>/<string:pwd>')
class pgdgHostCommand(Resource):
@auth_required('token', 'session')
@roles_accepted('Administrator','User')
def get(self, repo_id, pgc_cmd, comp, host=None):
data = pgc.get_pgdg_data(repo_id, pgc_cmd, component=comp, pgc_host=host)
return data
api.add_resource(pgdgHostCommand, '/api/pgdghost/<string:repo_id>/<string:pgc_cmd>/<string:comp>',
'/api/pgdghost/<string:repo_id>/<string:pgc_cmd>/<string:comp>/<string:host>')
class TestConn(Resource):
@auth_required('token', 'session')
@roles_accepted('Administrator', 'User')
def get(self):
username = request.args.get('user')
password = request.args.get('password')
ssh_key = request.args.get('ssh_key')
sudo_pwd = request.args.get('ssh_sudo_pwd')
host = request.args.get('host')
from PgcRemote import PgcRemote
json_dict = {}
try:
remote = PgcRemote(host, username, password=password, ssh_key=ssh_key, sudo_pwd=sudo_pwd)
if not sudo_pwd:
remote.connect()
json_dict['state'] = "success"
json_dict['msg'] = "Testing Connection Successful."
data = json.dumps([json_dict])
remote.disconnect()
except Exception as e:
errmsg = "ERROR: Cannot connect to " + username + "@" + host + " - " + str(e)
json_dict['state'] = "error"
json_dict['msg'] = errmsg
data = json.dumps([json_dict])
return data
api.add_resource(TestConn, '/api/testConn')
from responses import Result, InvalidParameterResult, ServerErrorResult
class TestCloudConnection(Resource):
@auth_required('token', 'session')
def post(self):
payload = request.get_json()['params']
if not set(("cloud_type","credentials")).issubset(payload):
return InvalidParameterResult(errors = ["Both cloud_type and credentials are required"]).http_response()
if payload["cloud_type"] not in ('aws','azure','vmware'):
return InvalidParameterResult(errors=["Possible values for cloud_type are aws/azure/vmware"]).http_response()
pgcCmd = "test-cred --cloud="+payload["cloud_type"]
pgcCmd = pgcCmd + " --credentials \'" + json.dumps(payload["credentials"]) + "\'"
data = pgc.get_cmd_data(pgcCmd)
if len(data) == 0:
return ServerErrorResult().http_response()
if data[0]['state'] != 'info' or data[0]['state'] == 'completed':
return ServerErrorResult(state=data[0]['state'],message=data[0].get('msg')).http_response()
return Result(200,data[0]['state'], data[0]['msg']).http_response()
api.add_resource(TestCloudConnection, '/api/testCloudConn')
class checkUser(Resource):
@auth_required('token', 'session')
@roles_accepted('Administrator', 'User')
def get(self):
host = request.args.get('hostname')
cred_name = request.args.get('cred_name')
import util
cred_info = util.get_credentials_by_name(cred_name)
enc_secret = util.get_value("GLOBAL", "SECRET", "")
enc_key = "{0}{1}".format(enc_secret, cred_info.get("cred_uuid"))
username = cred_info.get("ssh_user")
password= ""
if cred_info.get("ssh_passwd"):
password = decrypt(cred_info.get("ssh_passwd"),enc_key)
ssh_key = ""
if cred_info.get("ssh_key"):
ssh_key = decrypt(cred_info.get("ssh_key"), enc_key)
sudo_pwd = ""
if cred_info.get("ssh_sudo_pwd"):
sudo_pwd = decrypt(cred_info.get("ssh_sudo_pwd"), enc_key)
# username = request.args.get('username')
# password = request.args.get('password')
# ssh_key = request.args.get('ssh_key')
# sudo_pwd = request.args.get('sudo_pwd', None)
from PgcRemote import PgcRemote
json_dict = {}
try:
remote = PgcRemote(host, username, password=password, ssh_key=ssh_key, sudo_pwd=sudo_pwd)
if not sudo_pwd:
remote.connect()
json_dict['state'] = "success"
try:
remote_pgc_path = remote.get_exixting_pgc_path()
for key in remote_pgc_path.keys():
json_dict[key] = remote_pgc_path[key]
except Exception as e:
print (str(e))
pass
data = json.dumps([json_dict])
remote.disconnect()
except Exception as e:
errmsg = "ERROR: Cannot connect to " + username + "@" + host + " - " + str(e)
json_dict['state'] = "error"
json_dict['msg'] = errmsg
data = json.dumps([json_dict])
return data
api.add_resource(checkUser, '/api/checkUser')
class checkHostAccess(Resource):
@auth_required('token', 'session')
@roles_accepted('Administrator', 'User')
def get(self):
host = request.args.get('hostname')
check_sudo_password = request.args.get('pwd')
pgc_host_info = util.get_pgc_host(host)
pgc_host = pgc_host_info.get('host')
ssh_cred_id = pgc_host_info.get('ssh_cred_id')
cred_info = util.get_credentials_by_uuid(ssh_cred_id)
enc_secret = util.get_value("GLOBAL", "SECRET", "")
enc_key = "{0}{1}".format(enc_secret, cred_info.get("cred_uuid"))
pgc_user = cred_info.get("ssh_user")
pgc_passwd= ""
if cred_info.get("ssh_passwd"):
pgc_passwd = decrypt(cred_info.get("ssh_passwd"),enc_key)
pgc_ssh_key = ""
if cred_info.get("ssh_key"):
pgc_ssh_key = decrypt(cred_info.get("ssh_key"), enc_key)
util.update_cred_used(cred_info.get("cred_uuid"))
from PgcRemote import PgcRemote
json_dict = {}
try:
remote = PgcRemote(pgc_host, pgc_user, password=pgc_passwd, ssh_key=pgc_ssh_key, sudo_pwd=check_sudo_password)
remote.connect()
is_sudo = remote.has_root_access()
json_dict['state'] = "success"
json_dict['isSudo'] = is_sudo
data = json.dumps([json_dict])
remote.disconnect()
except Exception as e:
errmsg = "ERROR: Cannot connect to " + username + "@" + host + " - " + str(e)
json_dict['state'] = "error"
json_dict['msg'] = errmsg
data = json.dumps([json_dict])
return data
api.add_resource(checkHostAccess, '/api/checkUserAccess')
class initPGComp(Resource):
@auth_required('token', 'session')
@roles_accepted('Administrator', 'User')
def get(self, host, comp, pgpasswd, username=None, password=None):
from PgcRemote import PgcRemote
json_dict = {}
if password == None or username == None:
import util
pgc_host_info = util.get_pgc_host(host)
ssh_host = pgc_host_info.get('host')
ssh_host_name = pgc_host_info.get('host_name')
ssh_cred_id = pgc_host_info.get('ssh_cred_id')
cred_info = util.get_credentials_by_uuid(ssh_cred_id)
enc_secret = util.get_value("GLOBAL", "SECRET", "")
enc_key = "{0}{1}".format(enc_secret, cred_info.get("cred_uuid"))
ssh_username = cred_info.get("ssh_user")
password= ""
if cred_info.get("ssh_passwd"):
ssh_password = decrypt(cred_info.get("ssh_passwd"),enc_key)
ssh_key = ""
if cred_info.get("ssh_key"):
ssh_key = decrypt(cred_info.get("ssh_key"), enc_key)
sudo_pwd = ""
if cred_info.get("ssh_sudo_pwd"):
sudo_pwd = decrypt(cred_info.get("ssh_sudo_pwd"), enc_key)
is_sudo = pgc_host_info.get('is_sudo')
util.update_cred_used(cred_info.get("cred_uuid"))
try:
remote = PgcRemote(ssh_host, ssh_username, password=ssh_password, ssh_key=ssh_key)
remote.connect()
is_file_added = remote.add_file('/tmp/.pgpass', pgpasswd)
remote.disconnect()
data = pgc.get_data("init", comp, ssh_host_name, '/tmp/.pgpass')
except Exception as e:
errmsg = "ERROR: Cannot connect to " + ssh_username + "@" + ssh_host + " - " + str(e.args[0])
json_dict['state'] = "error"
json_dict['msg'] = errmsg
data = json.dumps([json_dict])
return data
api.add_resource(initPGComp, '/api/initpg/<string:host>/<string:comp>/<string:pgpasswd>','/api/initpg/<string:host>/<string:comp>/<string:pgpasswd>/<string:username>/<string:password>')
class bamUserInfo(Resource):
@auth_required('token', 'session')
def get(self):
userInfo = {}
if current_user.is_authenticated:
userInfo['email'] = current_user.email
userInfo['isAdmin'] = current_user.has_role("Administrator")
email_md5=hashlib.md5( current_user.email.lower() ).hexdigest()
gravtar_url="https://www.gravatar.com/avatar/"+ email_md5 + "?d=retro"
userInfo['gravatarImage']=gravtar_url
return userInfo
api.add_resource(bamUserInfo, '/api/userinfo')
class checkUserRole(Resource):
@auth_required('token', 'session')
def get(self):
result = {}
if current_user.has_role("Developer"):
result['code'] = 1
result['role'] = "Developer"
else:
result['code'] = 0
return result
api.add_resource(checkUserRole, '/api/checkUserRole')
class getRecentReports(Resource):
@auth_required('token', 'session')
def get(self, report_type):
recent_reports_path = os.path.join(reports_path, report_type)
jsonDict = {}
jsonList = []
if os.path.isdir(recent_reports_path):
mtime = lambda f: os.stat(os.path.join(recent_reports_path, f)).st_mtime
sorted_list=sorted(os.listdir(recent_reports_path),
key=mtime, reverse=True)
for d in sorted_list:
if d.endswith(".html"):
jsonDict = {}
html_file_path = os.path.join(recent_reports_path, d)
jsonDict['file']=d
jsonDict["file_link"] = "reports/"+report_type+"/"+d
mtime=os.stat(html_file_path).st_mtime
mdate=datetime.fromtimestamp(mtime).strftime('%Y-%m-%d %H:%M:%S')
jsonDict['mtime']=mdate
jsonList.append(jsonDict)
return {'data':jsonList}
api.add_resource(getRecentReports, '/api/getrecentreports/<string:report_type>')
class CheckConn(Resource):
@auth_required('token', 'session')
@roles_accepted('Administrator', 'User')
def post(self):
result = {}
args = request.json.get('params')
host = args.get('host')
user = args.get('username')
password = args.get('password')
dbname = args.get('dbname')
port = args.get('port')
try:
from PgInstance import PgInstance
remoteConn = PgInstance(str(host),str(user), str(dbname), int(port), str(password))
remoteConn.connect()
remoteConn.close()
result['error'] = 0
result['msg'] = 'Sucessfully Connected.'
return result
except Exception as e:
result['error'] = 1
result['msg'] = str(e)
return result
api.add_resource(CheckConn, '/check_pg_conn')
class GenerateReports(Resource):
@auth_required('token', 'session')
def post(self):
args = request.json['data']
from ProfilerReport import ProfilerReport
try:
plReport = ProfilerReport(args)
report_file = plReport.generateSQLReports(args.get('pgQuery'),
args.get('pgTitle'),
args.get('pgDesc'))
result = {}
result['report_file'] = report_file
result['error'] = 0
except Exception as e:
#import traceback
#print traceback.format_exc()
#print e
result = {}
result['error'] = 1
result['msg'] = str(e)
return result
api.add_resource(GenerateReports, '/api/generate_profiler_reports')
class RemoveReports(Resource):
@auth_required('token', 'session')
def post(self,report_type):
from ProfilerReport import ProfilerReport
try:
recent_reports_path = os.path.join(reports_path, report_type)
for fileName in request.json:
os.remove(os.path.join(recent_reports_path, fileName))
result = {}
result['msg'] = 'success'
result['error'] = 0
except Exception as e:
result = {}
result['error'] = 1
result['msg'] = str(e)
print e
return result
api.add_resource(RemoveReports, '/api/remove_reports/<string:report_type>')
class GetEnvFile(Resource):
@auth_required('token', 'session')
def get(self, comp):
import util
try:
result = dict()
util.read_env_file(comp)
result['PGUSER'] = os.environ['PGUSER']
result['PGDATABASE'] = os.environ['PGDATABASE']
result['PGPORT'] = os.environ['PGPORT']
except Exception as e:
result = {}
result['error'] = 1
result['msg'] = str(e)
return result
api.add_resource(GetEnvFile, '/api/read/env/<string:comp>')
class AddtoMetadata(Resource):
@auth_required('token', 'session')
@roles_accepted('Administrator','User')
def post(self):
def add_to_pginstances(pg_arg):
server_id = None
try:
component_name = pg_arg.get("component")
component_port = pg_arg.get("port", 5432)
component_host = pg_arg.get("host", "localhost")
component_proj = pg_arg.get("project")
component_db = pg_arg.get("db", "postgres")
component_user = pg_arg.get("user", "postgres")
gid = pg_arg.get("gid")
sid = pg_arg.get("sid")
servergroup_id=1
is_rds = pg_arg.get("rds")
is_new =True
discovery_id = "BigSQL PostgreSQL"
if is_rds:
discovery_id = "RDS"
servername = component_name
server_group_name = pg_arg.get("region", "AWS RDS")
rds_serverGroup = ServerGroup.query.filter_by(
user_id=current_user.id,
name=server_group_name
).order_by("id")
if rds_serverGroup.count() > 0:
servergroup = rds_serverGroup.first()
servergroup_id = servergroup.id
else:
try:
sg = ServerGroup(
user_id=current_user.id,
name=server_group_name)
db.session.add(sg)
db.session.commit()
servergroup_id = sg.id
except sqlite3.IntegrityError as e:
err_msg = str(e)
if err_msg.find("UNIQUE constraint failed") >= 0:
rds_serverGroup = ServerGroup.query.filter_by(
user_id=current_user.id,
name=server_group_name
).order_by("id")
if rds_serverGroup.count() > 0:
servergroup = rds_serverGroup.first()
servergroup_id = servergroup.id
else:
print (err_msg)
result = {}
result['error'] = 1
result['msg'] = err_msg
return result
else:
if gid:
servername=component_name
servergroup_id=gid
if sid:
component_server = Server.query.filter_by(
id=sid,
user_id=current_user.id,
).first()
is_new=False
else:
servername = "{0}({1})".format(component_name, component_host)
if component_host in ("localhost", ""):
component_host = "localhost"
servername = "{0}({1})".format(component_name, component_host)
else:
import util
host_info = util.get_pgc_host(component_host)
component_host = host_info.get('host')
if component_host == '':
component_host = pg_arg.get("host", "localhost")
user_id = current_user.id
servergroups = ServerGroup.query.filter_by(
user_id=user_id
).order_by("id")
if servergroups.count() > 0:
servergroup = servergroups.first()
servergroup_id = servergroup.id
else:
sg = ServerGroup(
user_id=current_user.id,
name="Servers")
db.session.add(sg)
db.session.commit()
servergroup_id = sg.id
component_server = Server.query.filter_by(
name=servername,
host=component_host,
servergroup_id=servergroup_id,
port=component_port
).first()
if component_server:
is_new=False
else:
is_new=True
if is_new:
svr = Server(user_id=current_user.id,
servergroup_id=servergroup_id,
name=servername,
host=component_host,
port=component_port,
maintenance_db=component_db,
username=component_user,
ssl_mode='prefer',
comment=component_proj,
discovery_id=discovery_id)
db_session.add(svr)
db_session.commit()
server_id = svr.id
else:
component_server.servergroup_id=servergroup_id
component_server.name=servername
component_server.host=component_host
component_server.port=component_port
component_server.maintenance_db=component_db
component_server.username=component_user
db_session.commit()
except Exception as e:
print ("Failed while adding/updating pg instance in metadata :")
print (str(e))
pass
return server_id
result = {}
result['error'] = 0
args = request.json.get("params")
is_multiple = args.get("multiple")
remote_host = args.get("remotehost")
if is_multiple:
for pg_data in args.get("multiple"):
server_id = add_to_pginstances(pg_data)
else:
if remote_host:
components_list = pgc.get_data("status", pgc_host=remote_host)
for c in components_list:
if c.get("category") == 1 and c.get("state") != "Not Initialized":
comp_args = {}
comp_args['component'] = c.get("component")
comp_args['port'] = c.get("port")
comp_args['host'] = remote_host
server_id = add_to_pginstances(comp_args)
else:
server_id = add_to_pginstances(args)
result['sid'] = server_id
return result
api.add_resource(AddtoMetadata, '/api/add_to_metadata')
class DeleteFromMetadata(Resource):
@auth_required('token', 'session')
@roles_accepted('Administrator', 'User')
def post(self):
args = request.json
gid = args.get('gid')
sid = args.get('sid')
result = {}
servers = Server.query.filter_by(user_id=current_user.id, id=sid)
if servers is None:
result['error'] = 1
result['msg'] = 'The specified server could not be found. Does the user have permission to access the server?'
else:
try:
for s in servers:
get_driver(PG_DEFAULT_DRIVER).delete_manager(s.id)
db.session.delete(s)
db.session.commit()
except Exception as e:
result['error'] = 1
result['msg'] = e.message
return result
result['error'] = 0
result['msg'] = "Server deleted"
return result
api.add_resource(DeleteFromMetadata, '/api/delete_from_metadata')
def get_process_status(process_log_dir,line_count=None):
process_dict = {}
status_file = os.path.join(process_log_dir, "status")
if os.path.exists(status_file):
with open(status_file) as data_file:
data = json.load(data_file)
process_dict = data
err_file = os.path.join(process_log_dir, "err")
out_file = os.path.join(process_log_dir, "out")
exit_code = process_dict.get("exit_code", None)
err_data_content = None
out_data_content = None
process_dict['out_data'] = ""
with open(out_file) as out_data:
if line_count is None:
out_data_content = out_data.readlines()
else:
out_data_content = out_data.readlines()[-line_count:]
line_count = line_count - len(out_data_content)
out_data_content = "".join(out_data_content).replace("\r", "\n").strip()
with open(err_file) as err_data:
if line_count is None:
err_data_content = err_data.readlines()
else:
err_data_content = err_data.readlines()[-line_count:]
err_data_content = "".join(err_data_content).replace("\r", "\n").strip()
if err_data_content and out_data_content:
process_dict['out_data'] = '\n'.join([out_data_content, err_data_content])
elif err_data_content:
process_dict['out_data'] = err_data_content
elif out_data_content:
process_dict['out_data'] = out_data_content
return process_dict
def get_current_time(format='%Y-%m-%d %H:%M:%S.%f %z'):
"""
Generate the current time string in the given format.
"""
return datetime.utcnow().replace(
tzinfo=pytz.utc
).strftime(format)
class pgdgAction(Resource):
@auth_required('token', 'session')
@roles_accepted('Administrator','User')
def post(self):
result = {}
args = request.json
component_name = args.get("component")
component_host = args.get("host","localhost")
pwd=args.get("pwd")
pwd_session_name = "{0}_pwd".format(component_host)
if session.get("hostname", "") == component_host:
if not pwd and session.get(pwd_session_name):
pwd = session.get(pwd_session_name)
session['hostname'] = component_host
if pwd:
session[pwd_session_name] = pwd
repo = args.get("repo")
action = args.get("action")
from detached_process import detached_process
ctime = get_current_time(format='%y%m%d%H%M%S%f')
if action=="register" or action=="unregister":
report_cmd = PGC_HOME + os.sep + "pgc " + action + " REPO " + repo + " -y"
else:
report_cmd = PGC_HOME + os.sep + "pgc repo-pkgs " + repo + " " + action + " " + component_name
if not pwd:
report_cmd = report_cmd + " --no-tty"
isLocal = True
if component_host and component_host != "localhost":
isLocal = False
report_cmd = report_cmd + " --host \"" + component_host + "\""
if this_uname == "Windows":
report_cmd = report_cmd.replace("\\", "\\\\")
process_status = detached_process(report_cmd, ctime, stdin_str=pwd, is_local=isLocal)
result['error']=None
result['status'] =process_status['status']
result['log_dir'] = process_status['log_dir']
result['process_log_id'] = process_status['process_log_id']
result['cmd'] = report_cmd
return result
api.add_resource(pgdgAction, '/api/pgdgAction')
class GenerateBadgerReports(Resource):
@auth_required('token', 'session')
def post(self):
result = {}
args = request.json
log_files=args.get("log_files")
db=args.get("db")
jobs=args.get("jobs")
log_prefix=args.get("log_prefix")
title=args.get("title")
try:
from BadgerReport import BadgerReport
ctime = get_current_time(format='%y%m%d%H%M%S%f')
badgerRpts = BadgerReport()
pid_file_path = os.path.join(config.SESSION_DB_PATH,"process_logs", ctime)
report_file = badgerRpts.generateReports(log_files, db, jobs, log_prefix, title, ctime, pid_file_path)
process_log_dir = report_file['log_dir']
report_status = get_process_status(process_log_dir)
result['pid'] = report_status.get('pid')
result['exit_code'] = report_status.get('exit_code')
result['process_log_id'] = report_file["process_log_id"]
if report_status.get('exit_code') is None:
result['in_progress'] = True
try:
j = Process(
pid=int(report_file["process_log_id"]), command=report_file['cmd'],
logdir=process_log_dir, desc=dumps("pgBadger Report"), user_id=current_user.id,
acknowledge='pgDevOps'
)
db_session.add(j)
db_session.commit()
except Exception as e:
print str(e)
pass
"""bg_process={}
bg_process['process_type'] = "badger"
bg_process['cmd'] = report_file['cmd']
bg_process['file'] = report_file['file']
bg_process['report_file'] = report_file['report_file']
bg_process['process_log_id'] = report_file["process_log_id"]"""
if report_file['error']:
result['error'] = 1
result['msg'] = report_file['error']
else:
result['error'] = 0
result['report_file'] = report_file['file']
report_file_path = os.path.join(reports_path, report_file['file'])
if not os.path.exists(report_file_path):
result['error'] = 1
result['msg'] = "Check the parameters provided."
except Exception as e:
import traceback
result = {}
result['error'] = 1
result['msg'] = str(e)
time.sleep(2)
return result
api.add_resource(GenerateBadgerReports, '/api/generate_badger_reports')