-
Notifications
You must be signed in to change notification settings - Fork 0
/
dccm.py
2021 lines (1755 loc) · 104 KB
/
dccm.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
"""Database Client Connection Manager"""
import libm.dccm_m as mod
# Control
import oracledb as odb
import tkinter as tk
from tkinter import filedialog as fd
import customtkinter as ctk
from libv import dccm_v as vew
from pathlib import Path
import json
import sqlite3
import platform
import pyfiglet
import pyperclip
import os
import sys
from os.path import exists
from os.path import expanduser
from zipfile import ZipFile
from libv.ora_cx_dialog import OraConnectionMaintenanceDialog
import lib.cbtk_kit as cbtk
# from tkfontawesome import icon_to_image
import re
import socket
import subprocess
import oci
from oci.config import from_file
import shutil
from shutil import which
import base64
from CTkMessagebox import CTkMessagebox
__title__ = mod.__title__
__author__ = 'Clive Bostock'
__version__ = mod.__version__
ENCODING = 'utf-8'
# Constants
HEADING1 = 'Roboto 16'
HEADING2 = 'Roboto 14'
HEADING3 = 'Roboto 12'
HEADING4 = 'Roboto 11'
HEADING_UL = 'Roboto 11 underline'
HEADING_UL = 'Roboto 11 underline'
REGULAR_TEXT = 'Roboto 10'
SMALL_TEXT = 'Roboto 7'
TOOLTIP_DELAY = 1
try:
tns_admin = Path(os.environ["TNS_ADMIN"])
except KeyError:
tns_admin = None
try:
oracle_home = Path(os.environ["ORACLE_HOME"])
except KeyError:
oracle_home = None
if tns_admin is None and oracle_home is not None:
tns_admin = oracle_home / 'network/admin'
prog_path = os.path.realpath(__file__)
prog = os.path.basename(__file__)
app_home = Path(os.path.dirname(os.path.realpath(__file__)))
# Get the data location, required for the config file etc
data_location = mod.data_location
images_location = mod.images_location
temp_location = mod.temp_location
# The temp_tns_admin folder is reserved for unpacking wallets, so that
# python-oracledb can be used to test database connections.
temp_tns_admin = temp_location / 'tns_admin'
themes_location = mod.themes_location
# Set the default export file names for connection and settings exports respectively.
base_prog = prog.replace(".py", "")
connection_export_default = f'{base_prog}_exp.json'
settings_export_default = f'{base_prog}_preferences_backup.json'
if not exists(temp_location):
os.mkdir(temp_location)
if not exists(temp_tns_admin):
os.mkdir(temp_tns_admin)
b_prog = prog.replace(".py", "")
db_file = mod.db_file
def command_found(command: str):
"""Check whether command is on the PATH O/S variable or that it can be found directly.
:param command: (str) Command or pathname to a command
:return: bool
"""
# If this is a full-blown command, with arguments, separate out the command.
cmd = command.split(' ')[0]
cmd = cmd.strip()
if cmd == 'start':
operating_system = platform.system()
if operating_system == 'Windows':
return True
if exists(cmd):
return True
return which(cmd) is not None
def dict_substitutions(string: str, dictionary: dict, none_substitution: str = ''):
"""The dict_substitutions function, accepts a string, which includes substitution placeholders (strings enclosed
by 2 # characters) along with a dictionary of values. It scans the keys of the dictionary, and we assume that at
least one of these is included as a substitution string in the string supplied, It replaces the delimited string
with the corresponding value from the dictionary.
:param string: String which includes substitution placeholders.
:param dictionary: Dictionary used to match substitution placeholders and source the substitution values.
:return: substituted (edited) string
:param none_substitution: str"""
for variable in dictionary.keys():
substitution_string = str(dictionary[variable])
if substitution_string == 'None':
substitution_string = none_substitution
string = string.replace(f'#{variable}#', substitution_string)
return string
def system_id():
operating_system = platform.system()
if operating_system == 'Darwin':
command = "ioreg -d2 -c IOPlatformExpertDevice"
ioreg_cmd = subprocess.run(["ioreg", "-d2", "-c", "IOPlatformExpertDevice"],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# awk -F\" '/IOPlatformUUID/{print $(NF-1)}'
awk_cmd = subprocess.run(["awk", '-F\"', "'/IOPlatformUUID/{print $(NF-1)}'"],
input=ioreg_cmd.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
system_uid = awk_cmd.stdout.decode()
elif operating_system == 'Windows':
# wmic path win32_computersystemproduct get UUID
wmic_cmd = subprocess.run(["wmic", "path", "win32_computersystemproduct", "get", "UUID"],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
system_uid = str(wmic_cmd.stdout.decode())
system_uid = system_uid.replace('UUID ', '').replace('\r', '').replace('\n', '').replace(' ', '')
elif operating_system == 'Linux':
cat_cmd = subprocess.run(["cat", "/etc/machine-id"],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
system_uid = cat_cmd.stdout.decode()
else:
system_uid = '&8*00ae0)19GfsBEAFA987612'
return system_uid
def oci_secret(config_file_pathname: Path, oci_profile: str, secret_id: str):
"""The oci_secret function, accepts the pathname to the user's OCI config file, along with the OCI Profile,
and a secret OCID, required to retrieve the secret (password) from an OCI vault.
:param config_file_pathname: User's OCI config file pathname.
:param oci_profile: User's OCI profile (entry in the config file)
:param secret_id: The OCID associated with the required secret.
:return: A string - the secret/password."""
config = from_file(file_location=config_file_pathname, profile_name=oci_profile)
secrets_client = oci.secrets.SecretsClient(config)
secret_base64 = secrets_client.get_secret_bundle(secret_id).data.secret_bundle_content
secret = secret_base64.__getattribute__("content")
content_type = secret_base64.__getattribute__("content_type")
if content_type == "BASE64":
# Include a decode, otherwise we get a byte string, which upsets oracledb.
return base64.b64decode(secret).decode()
else:
return secret
def port_is_open(host: str, port_number: int):
"""Function to check port, to see whether it is open. We can use this to check,
whether a database host is reachable.
:param host: Host / IP Address of the database listener (localhost for ssh tunnelling).
:param port_number: The port used to access the database (listener or local ssh port).
:return: Returns boolean True if the server is accessible via the specified port."""
# Create a new socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if host == 'localhost':
host = '127.0.0.1'
# Attempt to connect to the given host and port
try:
if sock.connect_ex((host, port_number)) == 0:
return True
else:
return False
except socket.gaierror:
# print(f'ERROR: Socket error: socket.gaierror: {host} / {port_number}')
return False
# Close the connection
sock.close()
def dump_preferences(db_file_path: Path):
"""The dump_preferences function is here for debugging purposes."""
db_conn = sqlite3.connect(db_file_path)
cur = db_conn.cursor()
cur.execute("select preference_name, "
"preference_value, "
"preference_attr1, "
"preference_attr2, "
"preference_attr3, "
"preference_attr4, "
"preference_attr5 "
"from preferences;")
preferences = cur.fetchall()
db_conn.close()
print(f'DBG: Preferences dump: {preferences}')
def backup_preferences(save_file_name: Path):
"""The backup_preferences function, creates a JSON file containing all user preferences, including anyfInitial Di
SSH tunnelling templates etc, created by the user."""
prefs_list = mod.preferences_dict_list(db_file_path=db_file)
entry_count = len(prefs_list)
feedback = []
feedback.append(f'Starting preferences backup to {save_file_name}.')
feedback.append(f'Exporting {entry_count} preference rows.')
# os.chdir(app_home)
try:
with open(save_file_name, "w") as f:
json.dump(prefs_list, f, indent=2)
feedback.append(f'Export complete.')
except IOError:
feedback = f'Failed to write file {save_file_name} - possible a permissions or free space issue.'
return feedback
def restore_preferences(restore_file_name: Path):
"""The restore_preferences function, reads a JSON preferences backup file, containing user
preferences. It then updates them to the DCCM database preferences table."""
with open(restore_file_name) as json_file:
try:
import_json = json.load(json_file)
except ValueError:
print(f'The file, "{restore_file_name}", does not appear to be a valid '
f'export file (JSON parse error).')
exit(1)
except IOError:
feedback = f'Failed to read file {restore_file_name} - possible permissions issue.'
entry_count = len(import_json)
feedback = [f'Starting preferences restore from {restore_file_name}.', f'Restoring {entry_count} preference rows.']
for row in import_json:
scope = row["scope"]
preference_name = row["preference_name"]
preference_value = row["preference_value"]
pref_row = mod.preference_row(db_file_path=db_file, scope=scope,
preference_name=preference_name)
pref_row["preference_value"] = preference_value
mod.upsert_preference(db_file_path=db_file, preference_row_dict=pref_row)
feedback.append(f'Restore complete.')
return feedback
def test_db_connection(username: str, password: str, connect_string: str, wallet_pathname: str = ''):
"""Accept a database connect string and credentials, and test a database connection. We optionally accept a wallet,
in which case we unpack it and make a call to init_oracle_client, to set a temporary TNS Admin location, for the
purposes of the test."""
if wallet_pathname:
unpack_wallet(wallet_pathname)
# init_oracle_client can only be called once per program session,
# otherwise we get:
# cx_Oracle.ProgrammingError: Oracle Client library has already been initialized
try:
odb.init_oracle_client(config_dir=str(temp_tns_admin))
except odb.ProgrammingError:
pass
try:
connection = odb.connect(user=username, password=password,
dsn=connect_string, encoding="UTF-8")
except odb.DatabaseError as db_error:
return 'Connection failed: ' + str(db_error)
connection.close()
return 'Connection succeeded!'
def unpack_wallet(wallet_pathname: Path):
""""The unpack_wallet function, is provided for testing the database connections via a cloud wallet. In
such cases the wallet must be unpacked for use by python-oracledb.
The wallet is unpacked to the program's temp TNS admin directory, defined by temp_tns_admin.
:param wallet_pathname: Path
"""
with ZipFile(wallet_pathname, 'r') as zip_ref:
zip_ref.extractall(temp_tns_admin)
# We now need to edit the temporary sqlnet.ora file, to reflect our temporary config dir:
sqlnet = Path(f'{temp_tns_admin}/sqlnet.ora').read_text()
sqlnet = sqlnet.replace('DIRECTORY="?/network/admin"', f'DIRECTORY="{temp_tns_admin}"')
with open(f'{temp_tns_admin}/sqlnet.ora', 'w') as f:
f.write(sqlnet)
def purge_temp_tns_admin():
"""The purge_temp_location function, clears down the contents of the DCCM temp_location/tns_admin folder."""
try:
shutil.rmtree(temp_tns_admin, ignore_errors=False, onerror=None)
except FileNotFoundError:
# We found no files to delete, so do nothing.
pass
class DCCMControl():
"""Class to instantiate our DCCM controller."""
def __init__(self, application_home: Path, db_file_path: Path, *args, **kwargs):
super().__init__(*args, **kwargs)
self.app_home = application_home
self.app_images = self.app_home / 'images'
self.app_configs = self.app_home / 'config'
self.etc = self.app_home / 'etc'
self.db_file_path = db_file_path
self.wallet_pathname = ''
self.import_pathname = None
self.import_json = None
self.connect_strings = []
self.client_launch_directory = Path(os.getcwd())
self.mvc_module = mod.DCCMModule(app_home=app_home, db_file_path=db_file_path)
self.app_theme = self.mvc_module.app_theme()
self.app_appearance_mode = self.mvc_module.app_appearance_mode()
self.enable_tooltips = self.mvc_module.tooltips_enabled()
self.default_wallet_directory = mod.preference(db_file_path=db_file_path,
scope="preference",
preference_name="default_wallet_directory")
self.oci_config = mod.preference(db_file_path=db_file_path,
scope="preference",
preference_name="oci_config")
self.enable_ancillary_ssh_window = mod.preference(db_file_path=db_file,
scope='preference',
preference_name='enable_ancillary_ssh_window')
if self.enable_ancillary_ssh_window is None:
self.enable_ancillary_ssh_window = 0
else:
self.enable_ancillary_ssh_window = int(self.enable_ancillary_ssh_window)
self.default_connection_type = self.mvc_module.default_connection_type
self.client_tools_name_list = self.mvc_module.client_tools_name_list()
self.ROOT_WIDTH = 520
self.ROOT_HEIGHT = 580
ctk.set_appearance_mode(self.app_appearance_mode) # Modes: "System" (standard), "Dark", "Light"
ctk.set_default_color_theme(str(themes_location / f'{self.app_theme}.json'))
self.root_win = vew.DCCMView(mvc_controller=self)
self.app_themes_list = self.root_win.app_themes_list()
self.root_win.iconbitmap = images_location / 'dccm.ico'
# self.root_win.attributes("-alpha", 0.892)
position_geometry = self.retrieve_geometry(window_name='control_panel')
self.root_win.geometry(position_geometry)
self.root_win.geometry(f'{self.ROOT_WIDTH}x{self.ROOT_HEIGHT}')
self.root_win.launch_in_gui_mode()
self.update_opm_connections()
self.status_bar = cbtk.CBtkStatusBar(master=self.root_win)
self.root_win.bind("<Configure>", self.status_bar.auto_size_status_bar)
self.root_win.enable_tool_tips = True
self.root_win.mainloop()
def banner_colours(self):
return self.mvc_module.colour_list()
def banner_options(self):
return self.mvc_module.banner_options()
def connection_type_list(self):
"""The connection_type_list method acts as a broker, to obtain connection/management types from the module
class. These are used to present details via the view class.
:return: list"""
return self.mvc_module.connection_type_list()
def default_connection(self):
"""The default_connection method acts as a broker, to obtain default connection from the module class. This
is used to present details via the view class.
:return: str"""
return self.mvc_module.default_connection()
def connections_dict(self):
"""The connections_dict method acts as a broker, to obtain a dictionary of connections from the module class.
This is used to present details via the view class.
:return: dict"""
return self.mvc_module.connections_dict()
def connection_record(self, connection_identifier: str):
"""The connection_record method acts as a broker, to obtain a dictionary associated with the presented
connection identifier, from the module class. This is used to present details via the view class.
:param connection_identifier:
:return: dict"""
return self.mvc_module.connection_record(connection_identifier=connection_identifier)
def launch_in_command_mode(self, connection_identifier: str, sql_script_nane: str = None):
"""As the name suggests, the launch_in_command_mode method, launches DCCM in command line mode."""
connection_name = connection_identifier
connection_record = self.mvc_module.connection_record(connection_identifier=connection_name)
if connection_record is None:
print(f'Invalid connection identifier: "{connection_identifier}"')
exit(1)
wallet_location = connection_record["wallet_location"]
if connection_record["wallet_required_yn"] == "Y":
if not exists(wallet_location):
print(f'The associated wallet, {wallet_location}, for the "{connection_name}", cannot be found. '
f'Please rectify and try again.')
return
hostname, port_number = self.mvc_module.resolve_connect_host_port(connection_name)
if connection_record["wallet_required_yn"] == "Y":
if not port_is_open(host=hostname,
port_number=port_number):
print(
f'Database server cannot be reached via host "{hostname}" on port {port_number}.\nThe connection may '
f"require ssh tunnel, VPN, Listener startup etc, to be established.")
return
else:
if not port_is_open(host=hostname,
port_number=int(port_number)):
print(
f'{prog}: Database server cannot be reached via host "{hostname}" on port {port_number}.\n'
f'Ensure that there are no network connectivity issues and that the database, and database listener'
f" are started.")
return
return_status, client_command = self.mvc_module.formulate_connection_launch(
connection_identifier=connection_name,
mode="command",
script_name=sql_script_nane)
if return_status:
print(return_status)
exit(1)
# input(f'Press ENTER to continue...\c')
connection_text_colour = connection_record["connection_text_colour"]
colour_sequence = self.mvc_module.color_code(colour=connection_text_colour)
colour_off = self.mvc_module.color_code(colour='None')
connection_banner = connection_record["connection_banner"]
if connection_banner is None:
connection_banner = ''
if connection_banner and connection_banner != 'None':
ascii_banner = pyfiglet.figlet_format(connection_banner)
print(f'{colour_sequence}{ascii_banner}{colour_off}')
connection_message = connection_record["connection_message"]
if connection_message:
print(f'{colour_sequence}{connection_message}{colour_off}')
# For some reason, this flush call is only required for GIT bash.
sys.stdout.flush()
status = os.system(client_command)
if status:
print(f'Client command, "{client_command}", returned with a status of: {status}')
def launch_in_plugin_mode(self, connection_identifier: str):
"""The launch_in_plugin_mode method, launches DCCM in command line plugin mode. This mode is a little like
the "command" mode, except that it expects input to be piped in from stdin.
:param connection_identifier:
:return: None"""
connection_name = connection_identifier
connection_record = self.mvc_module.connection_record(connection_identifier=connection_name)
hostname, port_number = self.mvc_module.resolve_connect_host_port(connection_name)
if connection_record["wallet_required_yn"] == "Y":
if not port_is_open(host=hostname,
port_number=port_number):
try:
ip = socket.gethostbyname(hostname)
except socket.gaierror:
ip = 'Unresolved IP'
print(f"Database server, {hostname} ({ip}), cannot be reached via port {port_number}.\nThe connection "
f"may require ssh tunnel, VPN, Listener startup etc, to be established.")
return
else:
if not port_is_open(host=hostname,
port_number=int(port_number)):
try:
ip = socket.gethostbyname(hostname)
except socket.gaierror:
ip = 'Unresolved IP'
print(
f"{prog}: Database server, {hostname} ({ip}), cannot be reached on port {port_number}.\nEnsure that "
f"there are no network connectivity issues and that the database, and database listener "
f"are started.")
return
# print(f'{prog}: Launching "{connection_name}" connection...')
script = []
try:
for line in sys.stdin:
script.append(line)
except KeyboardInterrupt:
sys.stdout.flush()
with open('dccm.buf', 'w') as b:
for line in script:
b.write(f'{line}')
return_status, client_command = self.mvc_module.formulate_connection_launch(
connection_identifier=connection_name,
mode="plugin",
script_name='dccm.buf')
if return_status:
print(return_status)
exit(1)
status = os.system(client_command)
if status:
print(f"Client returned with a status of: {status}")
def database_type_descriptors(self):
"""The database_type_descriptors method acts as a broker, to obtain a list of supported database types
from the module class. This is used to present details via the view class object."""
return self.mvc_module.valid_database_types
def connection_type_descriptors(self):
"""The connection_type_descriptors function acts as a broker, to obtain a list of supported database
connection/management types from the module class. This is used to present details via the view class object."""
return self.mvc_module.connection_type_list()
def launch_client_connection(self, connection_name: str = None):
"""The launch_client_connection method, marshals the required details, required to launch a client tool
via a terminal window. The function leans on the module class to pull much of the detail together. Once
the command is formulated, it is executed directly by launch_client_connection."""
if connection_name is None:
connection_name = self.root_win.opm_connections.get()
connection_record = self.mvc_module.connection_record(connection_identifier=connection_name)
start_directory = connection_record["start_directory"]
wallet_location = Path(connection_record["wallet_location"])
if start_directory is not None:
if exists(start_directory):
os.chdir(start_directory)
else:
confirm = CTkMessagebox(master=self.root_win,
title='Action Required',
message=f'The start directory, {start_directory}, for the '
f'"{connection_name}", does not '
f'exist. Please rectify and try again.',
option_1='OK')
if confirm.get() == 'OK':
return
if connection_record["wallet_required_yn"] == "Y":
if not exists(wallet_location):
confirm = CTkMessagebox(master=self.root_win,
title='Action Required',
message=f'The associated wallet, {wallet_location}, for the '
f'"{connection_name}", cannot be found. '
f'Please rectify and try again.',
option_1='OK')
if confirm.get() == 'OK':
return
hostname, port_number = self.mvc_module.resolve_connect_host_port(connection_name)
if connection_record["wallet_required_yn"] == "Y":
connect_string_record = self.mvc_module.connection_wallet_connect_string_dict(
connection_identifier=connection_name)
if not port_is_open(host=connect_string_record["host"],
port_number=int(connect_string_record["listener_port"])):
try:
ip = socket.gethostbyname(hostname)
except socket.gaierror:
ip = 'Unresolved IP'
confirm = CTkMessagebox(master=self.root_win,
title='Action Required',
message=f"Database server, {hostname} ({ip}), cannot be reached on port "
f"{port_number}. The connection may require ssh tunnel, VPN etc, "
f"to be established.",
option_1='OK')
if confirm.get() == 'OK':
return
else:
if hostname is None or port_number is None:
confirm = CTkMessagebox(master=self.root_win,
title='Action Required',
message=f"The selected connection, \"{connection_name}\", is no longer "
f"valid. Possibly caused by an associated tnsnames.ora file entry, "
f"which has been deleted, since this connection was created.",
option_1='OK')
if confirm.get() == 'OK':
return
if not port_is_open(host=hostname,
port_number=int(port_number)):
try:
ip = socket.gethostbyname(hostname)
except socket.gaierror:
ip = 'Unresolved IP'
confirm = CTkMessagebox(master=self.root_win,
title='Action Required',
message=f"Database server, {hostname} ({ip}), cannot be reached on port "
f"{port_number}. Ensure that there are no network connectivity "
"issues and that the database, and database listener are "
"started.",
option_1='OK')
if confirm.get() == 'OK':
return
return_status, client_command = self.mvc_module.formulate_connection_launch(
connection_identifier=connection_name)
if return_status:
confirm = CTkMessagebox(master=self.root_win,
title='Action Required',
message=f'{return_status}',
option_1='OK')
if confirm.get() == 'OK':
return
status = os.system(client_command)
if status:
confirm = CTkMessagebox(master=self.root_win,
title='Action Required',
message=f'Client command, "{client_command}", returned with a status of: '
f'{status}',
option_1='OK')
if confirm.get() == 'OK':
return
def launch_mod_connection(self):
"""The launch_mod_connection method, lunches the maintain_connection method in "Modify" mode. This creates
the CTkTopLevel, used to update an existing connection record."""
self.conn_maintenance = OraConnectionMaintenanceDialog(controller=self, operation='Modify')
self.conn_maintenance.swt_mod_wallet_required.configure(command=lambda conn_maintenance=self.conn_maintenance:
self.toggle_mod_wallet_display(conn_maintenance=conn_maintenance))
self.present_connection_details()
self.conn_maintenance.ent_mod_connection_identifier.configure(state=tk.DISABLED)
self.toggle_mod_tunnel_widgets()
def launch_new_connection(self):
"""The launch_mod_connection method, lunches the maintain_connection method in "Add New" mode. This creates
the CTkTopLevel, used to create a new connection record."""
self.wallet_pathname = ''
self.client_launch_directory = ''
self.conn_maintenance = OraConnectionMaintenanceDialog(controller=self, operation='Add New')
self.toggle_mod_tunnel_widgets()
def launch_ssh_tunnel(self, connection_id: str = None):
"""The launch_ssh_tunnel method, marshals the required details, required to launch a terminal window, with
the command required to forge an ssh tunnel for a specified connection id. The function leans on the module
class to pull much of the detail together. Once the command is formulated, it is executed directly by
launch_client_connection."""
if connection_id is None:
connection_id = self.root_win.opm_connections.get()
status_text, ssh_command = self.mvc_module.formulate_ssh_launch(connection_id=connection_id, mode='gui')
if status_text:
confirm = CTkMessagebox(master=self.root_win,
title='Action Required',
message=status_text,
option_1='OK')
if confirm.get() == 'OK':
return
status = os.system(ssh_command)
if status:
print(f'Client command, "{ssh_command}", returned with a status of: {status}')
def preview_launch_command(self):
connection_name = self.root_win.opm_connections.get()
return_status, client_command = self.mvc_module.formulate_connection_launch(
connection_identifier=connection_name,
mode="command")
if return_status:
confirm = CTkMessagebox(title='Confirm Action',
message=return_status,
options=['OK'],
master=self.root_win)
if confirm == 'OK':
return
else:
pyperclip.copy(client_command)
self.status_bar.set_status_text(
status_text='Command copied to clipboard.')
def resolve_connect_host_port(self, connection_name: str):
"""The resolve_connect_host_port method acts as a broker, to obtain a tuple of host, port, required by the
specified connection id. This is used to check connectivity as well as present details via the view class
object."""
host, port = self.mvc_module.resolve_connect_host_port(connection_name=connection_name)
return host, port
def retrieve_geometry(self, window_name: str):
"""The retrieve_geometry method acts as a broker, to obtain a string containing the previously saved window
geometry, of the specified window_name (name). This provided by the module class. This is primarily used
to control window positioning, upon subsequent program / window launches.
:param window_name (str): The window category - root, or toplevel
:return geometry (str)"""
geometry = self.mvc_module.retrieve_geometry(window_name=window_name)
return geometry
def set_ssh_button_state(self):
"""The set_ssh_button_state method, controls the 'Establish SSH Tunnel' button state associated with the
selected connection on the root window.. If ssh is not required for the current connection, then we disable
the button."""
connection_id = self.root_win.opm_connections.get()
connection_record = self.connection_record(connection_identifier=connection_id)
# Connection record is None at this stage, if there is no preferred connection.
if connection_record is None:
self.root_win.btn_launch_ssh.configure(state=tk.DISABLED)
self.root_win.file_menu.entryconfig('Establish SSH Tunnel', state="disabled")
elif connection_record["ssh_tunnel_required_yn"] == "N":
self.root_win.btn_launch_ssh.configure(state=tk.DISABLED)
self.root_win.file_menu.entryconfig('Establish SSH Tunnel', state="disabled")
else:
self.root_win.btn_launch_ssh.configure(state=tk.NORMAL)
self.root_win.file_menu.entryconfig('Establish SSH Tunnel', state="normal")
def toggle_mod_cloud_widgets(self, event=None):
"""The toggle_mod_cloud_widgets method, is called when the "connection/management type" selector changes. It
is responsible for showing / hiding / re-presenting OCI Vault related widgets."""
connection_type = self.conn_maintenance.opm_mod_connection_type.get()
if connection_type == 'OCI Vault':
self.conn_maintenance.show_vault_mod_widgets()
self.conn_maintenance.lbl_mod_ocid.configure(text='Cloud Secret OCID:')
else:
self.conn_maintenance.hide_vault_mod_widgets()
self.conn_maintenance.cmo_mod_connect_string.configure(values=self.mvc_module.tns_names_alias_list())
self.conn_maintenance.lbl_mod_ocid.configure(text='Password:')
self.toggle_mod_wallet_display(conn_maintenance=self.conn_maintenance)
# TODO: Check why we are grabbing the connection name from the root window - maybe we shouldn't when adding new
connection_identifier = self.root_win.opm_connections.get()
wallet_required = self.conn_maintenance.tk_mod_wallet_required.get()
if wallet_required and self.wallet_pathname and self.root_win.ent_mod_db_account_name.get():
connect_list = self.mvc_module.wallet_connect_string_list(connection_identifier=connection_identifier)
self.root_win.cmo_mod_connect_string.configure(values=connect_list)
def wallet_connect_string_list(self, connection_identifier: str):
return self.mvc_module.wallet_connect_string_list(connection_identifier=connection_identifier)
def update_opm_connections(self):
"""The update_opm_connections function, updates the connections' widget, following the addition/deletion of
connection entries."""
connections = self.mvc_module.connection_identifiers_list()
self.root_win.update_opm_connections(connections)
def save_geometry(self, window_name: str, geometry: str):
"""The save_geometry method acts as a broker, to save a string of the window geometry, for the
specified window_name (name). Handing this over to the module class. This is primarily used to control
window positioning, upon subsequent program / window launches."""
self.mvc_module.save_geometry(window_name=window_name, geometry=geometry)
def save_preferences(self):
"""The save_preference method acts as a broker, to obtain the widget selections/entries in from the
preferences window, amd submit them to the module class, to be saved to the DCCM database."""
self.app_theme = self.preferences.opm_app_theme.get()
self.app_appearance_mode = self.preferences.tk_appearance_mode_var.get()
ctk.set_appearance_mode(
self.app_appearance_mode)
cbtk.CBtkStatusBar.update_widgets_mode()
self.status_bar.update_text_colour()
self.enable_tooltips = self.preferences.swt_enable_tooltips.get()
self.enable_ancillary_ssh_window = self.preferences.swt_enable_ancillary_ssh_window.get()
preferences_dict = {"app_theme": self.app_theme,
"app_appearance_mode": self.app_appearance_mode,
"enable_tooltips": self.enable_tooltips,
"default_wallet_directory": self.default_wallet_directory,
"oci_config": self.oci_config,
"enable_ancillary_ssh_window": self.enable_ancillary_ssh_window}
self.mvc_module.save_preferences(preferences=preferences_dict)
self.status_bar.set_status_text(
status_text='Preferences saved!')
def root_delete_connection(self):
"""The mod_delete_connection function, obtains the currently selected connection name, from the root window,
and asks for confirmation, before deleting it from the DCCM database. This function is called from the
root window, or from the menu."""
connection_name = self.root_win.opm_connections.get()
confirm = CTkMessagebox(title='Confirm Action',
message=f'Are you sure you wish to delete the "{connection_name}" entry?',
options=['Yes', 'No'],
master=self.root_win)
if confirm == 'No':
return
self.mvc_module.mod_delete_connection(connection_identifier=connection_name)
self.update_opm_connections()
connections_list = self.mvc_module.connection_identifiers_list()
default_connection = self.mvc_module.default_connection()
if default_connection:
self.root_win.opm_connections.set(default_connection)
else:
self.root_win.opm_connections.set(connections_list[0])
self.status_bar.set_status_text(
status_text=f'Database connection, "{connection_name}", deleted.')
def set_connection_as_current(self):
"""When invoked, the set_connection_as_current method, determines the currently selected connection in the
application root window, and sets it as the default connection in the user preferences. The selected
connection also becomes the default selection in subsequent application launches. With the default set, and
when running in non-GUI mode, the default connection is assumed when the -c / --connection-identifier flag is
not specified."""
prev_current = self.default_connection()
connection_name = self.root_win.opm_connections.get()
connection_row = mod.preference_row(db_file_path=db_file, scope='preference',
preference_name='default_connection')
connection_row["preference_value"] = connection_name
mod.upsert_preference(db_file_path=self.db_file_path, preference_row_dict=connection_row)
default_connection = f'Default: {connection_name}'
self.root_win.lbl_default_connection.configure(text=default_connection)
self.root_win.btn_set_current.configure(state=tk.DISABLED)
self.root_win.file_menu.entryconfig('Set as Default', state="disabled")
self.status_bar.set_status_text(
status_text=f'Default working connection, now set to: {connection_name}.')
def selected_connection_record(self):
"""The selected_connection_record method, queries the connections selection widget from the root window, and
and returns the associated connection record, via the module class."""
connection_identifier = self.root_win.opm_connections.get()
connection_record = self.mvc_module.connection_record(connection_identifier=connection_identifier)
return connection_record
def display_connection_attributes(self, event=None):
"""The display_connection_attributes method, is used to query the connection record associated with the
connection selected on the root window. It then goes on to have the main record details, displayed in the
Connection Details frame."""
default_connection = self.default_connection()
connection_identifier = self.root_win.opm_connections.get()
connection_record = self.selected_connection_record()
self.root_win.frm_connection_type.grid()
self.root_win.frm_root_database_account.grid()
self.root_win.frm_root_connect_string.grid()
self.root_win.frm_root_client_tool.grid()
self.root_win.frm_root_initial_dir.grid()
self.root_win.frm_root_ssh_tunnel.grid()
self.root_win.lbl_root_connection_type.grid()
self.root_win.lbl_root_database_account.grid()
self.root_win.lbl_root_connect_string.grid()
self.root_win.lbl_root_client_tool.grid()
self.root_win.lbl_root_initial_dir.grid()
self.root_win.lbl_root_ssh_tunnel.grid()
if connection_record:
connect_string = connection_record["connect_string"]
if len(connect_string) > 60:
connect_string = connect_string[:60] + '...'
max_len = max(len(connection_record["db_account_name"]), len(connect_string))
self.root_win.geometry(f'{int(self.ROOT_WIDTH) + (3 * max_len)}x{self.ROOT_HEIGHT}')
if connection_identifier != '-- Connections --':
self.root_win.btn_modify.configure(state=tk.NORMAL)
self.root_win.btn_delete.configure(state=tk.NORMAL)
self.root_win.btn_launch_client.configure(state=tk.NORMAL)
self.root_win.file_menu.entryconfig('Modify Connection', state="normal")
self.root_win.file_menu.entryconfig('Delete Connection', state="normal")
self.root_win.file_menu.entryconfig('Launch Connection', state="normal")
self.root_win.file_menu.entryconfig('Copy Command', state="normal")
if default_connection is None:
default_connection = ''
if default_connection == connection_identifier:
self.root_win.btn_set_current.configure(state=tk.DISABLED)
self.root_win.file_menu.entryconfig('Set as Default', state="disabled")
elif connection_identifier == '-- Connections --':
self.root_win.btn_set_current.configure(state=tk.DISABLED)
self.root_win.file_menu.entryconfig('Set as Default', state="disabled")
else:
self.root_win.btn_set_current.configure(state=tk.NORMAL)
self.root_win.file_menu.entryconfig('Set as Default', state="normal")
if connection_record:
self.root_win.lbl_root_connection_type_disp.configure(
text=f'{connection_record["database_type"]} / {connection_record["connection_type"]}')
self.root_win.lbl_root_database_account_disp.configure(
text=f'{connection_record["db_account_name"]}')
connect_string = connection_record["connect_string"]
if len(connect_string) > 30:
connect_string = connect_string[:60] + '...'
self.root_win.lbl_root_connect_string_disp.configure(
text=f'{connect_string}')
self.root_win.lbl_root_client_tool_disp.configure(
text=f'{connection_record["client_tool"]}')
self.root_win.lbl_root_initial_dir_disp.configure(
text=f'{connection_record["start_directory"]}')
if connection_record["ssh_tunnel_code"]:
ssh_connection_disp = connection_record["ssh_tunnel_code"]
else:
ssh_connection_disp = 'Not configured.'
self.root_win.lbl_root_ssh_tunnel_disp.configure(text=ssh_connection_disp)
self.set_ssh_button_state()
def launch_preferences(self):
"""Launch the export connections dialog (CTkToplevel)."""
self.preferences = vew.Preferences(controller=self)
def modify_connection(self):
"""The modify_connection method, is the first stage of call in updating/inserting connection details from
the connections maintenance window. It performs some basic validation, via the module class object, ensuring
that there isn't already a connection of the same identifier."""
connection_identifier = self.conn_maintenance.ent_mod_connection_identifier.get()
check_exists = self.mvc_module.connection_record(connection_identifier)
if check_exists and self.root_win.maintain_operation == 'Add New':
confirm = CTkMessagebox(title='Action Required',
message=f'A connection, "{connection_identifier}", already exists. Please '
f'choose another name or cancel.',
option_1='OK',
master=self.conn_maintenance.top_mod_connection)
return
oci_config = mod.preference(db_file_path=self.db_file_path, scope='preference',
preference_name='oci_config')
if not oci_config and self.conn_maintenance.opm_mod_connection_type.get() == 'OCI Vault':
confirm = CTkMessagebox(title='Action Required',
message=f'To use the "OCI Vault" Management Type, you must first set your '
f'OCI Config Locn (directory) in Tools / Preferences',
option_1='OK',
master=self.conn_maintenance.top_mod_connection)
return
# Now Insert (if Add New and doesn't exist already) or Update the record
self.upsert_connection()
self.display_connection_attributes()
def validate_mod_entries(self):
"""Validate a connections row. We create a dictionary, which reflects the table column names and their
value assignments. This method is called from the modify_connection method. If validations are successful,
we return a tuple of status message and connections table record. The status message is empty of there are
no errors detected."""
if self.wallet_pathname is None:
self.wallet_pathname = ''
connections_record = {}
# We don't presently deal with the description.
connections_record["description"] = ''
connections_record["database_type"] = self.conn_maintenance.opm_mod_database_type.get()
self.conn_maintenance.ent_mod_connection_identifier.configure(state=tk.NORMAL)
connections_record["connection_identifier"] = self.conn_maintenance.ent_mod_connection_identifier.get().strip()
connections_record["connection_type"] = self.conn_maintenance.opm_mod_connection_type.get()
connections_record["db_account_name"] = self.conn_maintenance.ent_mod_db_account_name.get().strip()
connections_record["connect_string"] = self.conn_maintenance.cmo_mod_connect_string.get().strip()
connections_record["oci_profile"] = self.conn_maintenance.cmo_mod_oci_profile.get().strip()
connections_record["ocid"] = self.conn_maintenance.ent_mod_ocid.get().strip()
connections_record["wallet_required_yn"] = self.conn_maintenance.swt_mod_wallet_required.get()
connections_record["connection_banner"] = self.conn_maintenance.opm_mod_connection_banner.get()
connections_record["connection_message"] = self.conn_maintenance.tk_mod_connection_message.get()
connections_record["connection_text_colour"] = self.conn_maintenance.opm_mod_connection_text_colour.get()
status_text = ''
if not connections_record["connection_identifier"]:
status_text = 'You must enter a Connection Id.'
return status_text, connections_record
if not connections_record["db_account_name"]:
status_text = 'You must enter a database Username.'
return status_text, connections_record
if not connections_record["ocid"] and connections_record["connection_type"] == 'OCI Vault':
status_text = 'You must enter an OCID for an "OCI Vault" managed connection.'
self.conn_maintenance.mod_status_bar.set_status_text(
status_text=status_text)
return status_text, connections_record
if not connections_record["ocid"] and connections_record["connection_type"] == 'Legacy':
status_text = 'Please enter a password for the connection.'
self.conn_maintenance.mod_status_bar.set_status_text(
status_text=status_text)
return status_text, connections_record
if not connections_record["connect_string"]: