-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathdrs_lib.py
1630 lines (1362 loc) · 71.6 KB
/
drs_lib.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
# -*- coding: utf-8 -*-
"""
MAA DR Setup (DRS) library
This file contains classes and libraries used by the DRS framework.
"""
__author__ = "Oracle "
__version__ = '19.0'
__copyright__ = """ Copyright (c) 2022 Oracle and/or its affiliates. Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/ """
try:
import os
except ImportError:
print("ERROR: Could not import python's os module")
os = None
exit(-1)
try:
import time
except ImportError:
print("ERROR: Could not import python's time module")
time = None
exit(-1)
try:
from datetime import datetime
except ImportError:
print("ERROR: Could not import python's datetime module")
datetime = None
exit(-1)
try:
from random import choice
from string import ascii_uppercase
except ImportError:
print("ERROR: Could not import python's datetime module")
choice = None
ascii_uppercase = None
exit(-1)
try:
from fabric import Connection
except ImportError:
print("ERROR: Could not import python's fabric.Connection module")
Connection = None
exit(-1)
try:
from datetime import datetime
except ImportError:
print("ERROR: Could not import python's datetime module")
datetime = None
exit(-1)
try:
import re
except ImportError:
print("ERROR: Could not import python's re module")
re = None
exit(-1)
try:
import logging
except ImportError:
print("ERROR: Could not import python's logging module")
logging = None
exit(-1)
try:
import yaml
except ImportError:
print("ERROR: Could not import python's yaml module")
yaml = None
exit(-1)
try:
from drs_config import DRS_CONFIG as CONFIG
except ImportError:
print("ERROR: Could not import DRS drs_config module")
CONFIG = None
exit(-1)
try:
from drs_const import DRS_CONSTANTS as CONSTANT
except ImportError:
print("ERROR: Could not import DRS_CONSTANTS from drs_const module")
CONSTANT = None
exit(-1)
#
# DRSLogger
#
class DRSLogger(object):
"""
Logger object which implements logging to file and stdout (if required).
"""
def __init__(self, log_filename):
"""
Initializes a DRSBase object
:param: log_filename: The full path & name of logfile to use for logging
:return: A DRSBase object with logging initialized
"""
self.logger = None
self.setup_logger(log_filename)
self.id = "[{}::{}]".format(type(self).__name__, id(self))
self.logger.debug("Created object " + self.id)
def setup_logger(self, log_filename):
"""
Sets up logging
:param log_filename: full path & name of logfile to use
:return: None
"""
logging.basicConfig(
level=CONSTANT.DRS_LOGGING_DEFAULT_LOG_LEVEL,
format=CONSTANT.DRS_LOGFILE_STATEMENT_FORMAT,
handlers=[logging.FileHandler(log_filename)])
self.logger = logging.getLogger()
def get_logger(self):
"""
Returns the logging object
:return: logger (python logger object)
"""
return self.logger
#
# DRSConfiguration
#
class DRSConfiguration(object):
"""
Implements YAML configuration file parsing for DRS
"""
def __init__(self, drs_config_file):
"""
Initializes a DRSConfiguration object
:param drs_config_file: The configuration file to read configuration from
:return: An initialized DRSConfiguration object for managing user configuration
"""
self.logger = logging.getLogger(self.__class__.__name__)
self.drs_config_file = drs_config_file
self.config_dict = dict()
self.id = "[{}::{}]".format(type(self).__name__, id(self))
self.logger.debug("Created object " + self.id)
self.load_configuration()
def load_configuration(self):
"""
Read master configuration from configuration file
:return: None
"""
self.config_dict.clear()
self.logger.info("Loading configuration from config file: " + self.drs_config_file)
with open(self.drs_config_file, 'r') as f:
self.config_dict = yaml.load(f, Loader=yaml.BaseLoader) # need to use BaseLoader to get strings by default
def print_configuration_to_logfile(self):
"""
Prints the loaded configuration
:return:
"""
# self.logger.info("Printing configuration to logfile: " + self.logger.handlers[0].baseFilename)
self.logger.debug("Printing configuration to logfile")
print_dict = self.__clean_config_dict(self.config_dict)
if len(print_dict) > 0:
# print(yaml.dump(print_dict, indent=4, sort_keys=False))
self.logger.debug("\n\n" + yaml.dump(print_dict, indent=4, sort_keys=False))
def get_configuration_dict(self):
"""
Return the configuration as a python dictionary
:return: config_dict (dict)
"""
return self.config_dict
def __clean_config_dict(self, unclean_dict):
"""
This method erases all clear-text passwords from a dictionary and returns a copy
Usually used before printing the config in order to sanitize & remove secure info
:return: unclean_dict: A config dictionary with all passwords erases
"""
for key, value in unclean_dict.items():
if isinstance(value, dict):
self.__clean_config_dict(value)
else:
if "password" in key:
unclean_dict[key] = '********'
return unclean_dict
#
# DRSHost
#
class DRSHost(object):
"""
Implements host object that internally use Fabric-based connection services.
"""
def __init__(self):
"""
Initializes a DRSHost object
:return: An initialized DRSHost object
"""
self.logger = logging.getLogger(self.__class__.__name__)
self.fab_conn = None
self.host_ip = None
self.user_name = None
self.key_file = None
self.id = "[{}::{}]".format(type(self).__name__, id(self))
self.logger.debug("Created object " + self.id)
def is_connected(self):
"""
Checks if host connection is active/open
:return: True if connected, else False
"""
if self.fab_conn is not None and self.fab_conn.is_connected:
self.logger.debug("Connection to host [{}] IS open/active".format(self.host_ip))
return True
else:
self.logger.debug("Connection to host [{}] is NOT open/active".format(self.host_ip))
return False
def connect_host(self, host_ip, user_name, key_file):
"""
Open a SSH connection to host
:param host_ip: The IP address of the host
:param user_name: The user name to use when connecting
:param key_file: full path & name of SSH auth key file
:return: None
"""
self.host_ip = host_ip
self.user_name = user_name
self.key_file = key_file
if self.is_connected() is not True:
self.logger.info("Connecting to host [{}] as user [{}]".format(host_ip, user_name))
# Changed key_file to list to avoid fabric issue #2007
self.fab_conn = Connection(host=self.host_ip, user=self.user_name, connect_timeout=30,
connect_kwargs={"key_filename": self.key_file.split()})
self.fab_conn.open()
self.logger.info("Connected to host [{}] as user [{}]".format(host_ip, user_name))
else:
self.logger.warning(
"WARNING: Already connected to host [{}] as user [{}]".format(self.host_ip, self.user_name))
def disconnect_host(self):
"""
Close connection to host
:return: None
"""
if self.is_connected() is True:
self.fab_conn.close()
self.logger.debug("Successfully disconnected from host [{}]".format(self.host_ip))
else:
self.logger.warning("WARNING: Not connected to host [{}] as user [{}]".format(self.host_ip, self.user_name))
self.host_ip = None
self.user_name = None
self.key_file = None
def execute_host_cmd_sudo_user(self, cmd, user_name, warn=False):
"""
Executes specified command on connected host
:param cmd: Command to execute
:param user_name: The user_name to use when executing 'cmd'
:return: The output of the command
"""
fmt_cmd = CONSTANT.DRS_CMD_EXECUTE_SUDO_SU_CMD_FMT.format(user_name, cmd)
#self.logger.debug("Executing cmd [{}] as user [{}] with warn [{}] on host [{}]".format(fmt_cmd, user_name, warn, self.host_ip))
secure_cmd = cmd.replace(CONFIG.DB_PRIM.sysdba_password, "******")
secure_cmd = secure_cmd.replace(CONFIG.WLS_PRIM.wlsadm_password, "******")
self.logger.debug(
"Executing cmd [{}] as user [{}] with warn [{}] on host [{}]".format(secure_cmd, user_name, warn,
self.host_ip))
# r = self.fab_conn.run(fmt_cmd, pty=True, hide=True)
# r = self.fab_conn.run(fmt_cmd, pty=False, echo=True)
r = self.fab_conn.run(fmt_cmd, pty=False, warn=warn)
self.logger.debug("Sudo user [{}] command output = {}".format(user_name, r.stdout.strip()))
return r
def execute_host_cmd_sudo_user_pty(self, cmd, user_name, warn=False):
# For bug 33748539 (not used)
"""
Executes specified command on connected host
:param cmd: Command to execute
:param user_name: The user_name to use when executing 'cmd'
:return: The output of the command
"""
fmt_cmd = CONSTANT.DRS_CMD_EXECUTE_SUDO_SU_CMD_FMT.format(user_name, cmd)
# self.logger.debug("Executing cmd [{}] as user [{}] with warn [{}] on host [{}]".format(fmt_cmd, user_name, warn, self.host_ip))
secure_cmd = cmd.replace(CONFIG.DB_PRIM.sysdba_password, "******")
secure_cmd = secure_cmd.replace(CONFIG.WLS_PRIM.wlsadm_password, "******")
self.logger.debug(
"SECURED Executing cmd [{}] as user [{}] with warn [{}] on host [{}]".format(secure_cmd, user_name, warn,
self.host_ip))
# r = self.fab_conn.run(fmt_cmd, pty=True, hide=True)
# r = self.fab_conn.run(fmt_cmd, pty=False, echo=True)
r = self.fab_conn.run(fmt_cmd, pty=True)
self.logger.debug("Sudo user [{}] command output = {}".format(user_name, r.stdout.strip()))
return r
def execute_host_cmd_sudo_root(self, cmd):
"""
Executes sudo command on connected host (uses 'sudo cmd')
:param cmd: Command to execute
:return: The output of the command
"""
fmt_cmd = CONSTANT.DRS_CMD_EXECUTE_SUDO_CMD_ONLY_FMT.format(cmd)
#self.logger.debug("Executing sudo cmd [{}] on host [{}]".format(fmt_cmd, self.host_ip))
secure_cmd = cmd.replace(CONFIG.DB_PRIM.sysdba_password, "******")
secure_cmd = secure_cmd.replace(CONFIG.WLS_PRIM.wlsadm_password, "******")
self.logger.debug("Executing sudo cmd [{}] on host [{}]".format(secure_cmd, self.host_ip))
# r = self.fab_conn.run(fmt_cmd, pty=True, hide=True)
# r = self.fab_conn.run(fmt_cmd, pty=False, echo=True)
r = self.fab_conn.run(fmt_cmd, pty=False)
self.logger.debug("Sudo command output = {}".format(r.stdout.strip()))
return r
def copy_local_file_to_host(self, local_file, remote_file):
"""
Copy a local file to a remote file on this host
:param local_file: full path & name of the local file to copy
:param remote_file: the remote file name to copy the local file to
(NOTE: this is the complete path , not just the remote directory name)
:return:
"""
self.logger.debug("Copying local file [{}] to remote file [{}:{}]".
format(local_file, self.host_ip, remote_file))
self.fab_conn.put(local_file, remote=remote_file)
def copy_remote_file_from_host(self, remote_file, local_file):
"""
Copy a file from a remote directory on this host to a local dir
:param remote_file: full path & name of the remote file to copy
:param local_file: full path & name of the local file to copy
(note: this is NOT just the local dir, but actual dir + filename to use)
:return: The full path to the local copied file
"""
self.logger.debug("Copying remote file [{}:{}] to local file [{}]".
format(self.host_ip, remote_file, local_file))
self.fab_conn.get(remote_file, local_file)
return local_file
def delete_remote_file_from_host(self, remote_file, user_name):
"""
Delete a file from a remote directory on this host
:param remote_file: full path & name of the remote file to copy
:param user_name: user who owns file to be deleted
:return: The command result
"""
self.logger.debug("Deleting remote file [{}:{}] as user[{}]".format(self.host_ip, remote_file, user_name))
remote_cmd = CONSTANT.DRS_CMD_OPC_RM_FILE.format(remote_file)
return self.execute_host_cmd_sudo_user(remote_cmd, user_name)
def backup_remote_file_on_host(self, remote_file):
"""
Save a backup of a remote file on that host. Typically used before modifying that file.
:param remote_file: full path & name of the remote file to backup
:return: The full path and name of the remote backup file
"""
save_as = remote_file + '.backup.' + DRSUtil.generate_unique_filename()
self.logger.debug("Backing up remote file [{}] to [{}] on host [{}]".
format(remote_file, save_as, self.host_ip))
remote_cmd = CONSTANT.DRS_CMD_OPC_BACKUP_FILE.format(remote_file, save_as)
return self.execute_host_cmd_sudo_root(remote_cmd)
def execute_internal_script_on_host(self, interpreter, script_name, script_params_list, deps_list, user_name,
oraenv=True, warn=False):
"""
Executes script on this host object (typically a remote host)
NOTE: Only works (for now) for executing scripts as user "oracle" on remote host
:param interpreter: Script interpreter (e.g. '/bin/sh', 'python', '/u01/oracle/common/bin/wlst.sh', etc.)
:param script_name: the name of the script to execute
:param script_params_list: an list of params to pass to the script (Optional. Can be 'None')
:param deps_list: a list of dependency scripts used by the primary script (Optional. Can be 'None')
:param user_name: The user name to use when executing the script (e.g. sudo su - user_name).
NOTE: The 'exec_user_name' is only used to execute the script, however we must use a different
user name ('opc') to stage/delete the script.
:param oraenv: Whether to source oraenv before executing command ('True' if not specified)
:return: The output of the script execution
"""
remote_staging_dir = '/tmp/' + DRSUtil.generate_unique_filename()
remote_script_path = remote_staging_dir + '/' + script_name
# Create staging directory on host
remote_cmd = CONSTANT.DRS_CMD_OPC_MKDIR.format(remote_staging_dir)
mkdir_result = self.execute_host_cmd_sudo_user(remote_cmd, self.user_name, warn)
self.logger.debug("Create directory (mkdir) result = {}".format(mkdir_result.stdout.strip()))
if script_params_list is not None:
assert(isinstance(script_params_list, (list,))) # make sure this is a list
param_string = ' '.join(list(script_params_list))
remote_script_path += ' '
remote_script_path += param_string
# Stage script file on host
self.copy_local_file_to_host(CONSTANT.DRS_INTERNAL_SCRIPT_DIR + '/' + script_name,
remote_staging_dir + '/' + script_name)
# Stage dependency files on host
if deps_list is not None:
for dep in deps_list:
self.copy_local_file_to_host(CONSTANT.DRS_INTERNAL_SCRIPT_DIR + '/' + dep,
remote_staging_dir + '/' + dep)
#v19
remote_cmd = CONSTANT.DRS_CMD_SUDO_CHMOD.format('744', remote_staging_dir + '/' + dep)
chmod_result = self.execute_host_cmd_sudo_root(remote_cmd)
self.logger.debug("Permissions change (chmod) result = {}".format(chmod_result.stdout.strip()))
# Modify remote directory ownership and permissions if necessary
if user_name != self.user_name:
self.logger.debug(
"Changing remote dir [{}] ownership from [{}] to [{}]".format(remote_staging_dir, self.user_name,
user_name))
remote_cmd = CONSTANT.DRS_CMD_SUDO_CHOWN.format(user_name, remote_staging_dir)
chown_result = self.execute_host_cmd_sudo_root(remote_cmd)
self.logger.debug("Dir ownership change (chown) result = {}".format(chown_result.stdout.strip()))
# Execute staged remote script
# Note that we are using a different user name for execution vs the one used to stage & delete
remote_cmd = CONSTANT.DRS_CMD_EXECUTE_SCRIPT_FMT.format(remote_staging_dir, interpreter, remote_script_path)
script_output = self.execute_host_cmd_sudo_user(remote_cmd, user_name, warn)
self.logger.debug("Script output/result = {}".format(script_output))
# Delete staged remote directory & all it's contents
remote_cmd = CONSTANT.DRS_CMD_OPC_RMDIR.format(remote_staging_dir)
rmdir_result = self.execute_host_cmd_sudo_root(remote_cmd)
self.logger.debug("Delete directory (rmdir) result = {}".format(rmdir_result.stdout.strip()))
"""
# Delete staged dependencies
if deps_list is not None:
for dep in deps_list:
remote_script_path = remote_staging_dir + '/' + dep
remote_cmd = CONSTANT.DRS_CMD_OPC_RM_FILE.format(remote_script_path)
del_result = self.execute_host_cmd_sudo_user(remote_cmd, self.user_name)
self.logger.debug("Delete file result = ".format(del_result.stdout.strip()))
"""
return script_output
def get_host_osinfo(self):
"""
Gets the full hostname and local IP address for this host using internal script
:return: The full hostname (e.g. soahost2.sub0123456.soacsdrvcn.oraclevcn.com)
The local (private) IP of the host (e.g. 10.0.0.4)
"""
result = self.execute_internal_script_on_host(CONSTANT.DRS_SCRIPT_INTERPRETER_SH,
CONSTANT.DRS_SCRIPT_HOST_GET_OSINFO,
None, None, self.user_name, oraenv=False)
rxp = r"FULL_HOSTNAME=(.*)"
p = re.search(rxp, result.stdout)
if p is not None:
full_hostname = p.group(1)
else:
self.logger.error("ERROR: FAILED to extract hostname. Output = \n{}".format(result.stdout))
raise Exception("ERROR: FAILED to extract hostname.")
self.logger.debug("Extracted Hostname = {}".format(full_hostname))
rxp = r"IP_ADDRESS=(.*)"
p = re.search(rxp, result.stdout)
if p is not None:
ip_address = p.group(1)
else:
self.logger.error("ERROR: FAILED to extract IP address. Output = \n{}".format(result.stdout))
raise Exception("ERROR: FAILED to extract IP address")
self.logger.debug("Extracted IP Address = {}".format(ip_address))
rxp = r"OS_VERSION=(.*)"
p = re.search(rxp, result.stdout)
if p is not None:
os_version = p.group(1)
else:
self.logger.error("ERROR: FAILED to extract OS version. Output = \n{}".format(result.stdout))
raise Exception("ERROR: FAILED to extract OS version.")
self.logger.debug("Extracted OS version = {}".format(os_version))
return full_hostname, ip_address, os_version
def reboot_host(self, timeout=660):
"""
Reboot the specified host and wait for 'timeout' seconds to log back in and verify that reboot succeeded.
:param timeout: Time to wait (in seconds) for reboot. Default is 11 minutes (660 seconds).
:return: True - if host reboot succeeded.
:raises: Exception if the reboot failed.
"""
self.logger.info("Rebooting host [{}]".format(self.host_ip))
reboot_cmd = '/usr/sbin/shutdown -r +0' # reboot immediately
time_left = timeout
# result = self.fab_conn.sudo(reboot_cmd, pty=True)
result = self.execute_host_cmd_sudo_root(reboot_cmd)
self.logger.debug("Command output = " + result.stdout)
# wait for node to reboot
while self.is_connected() is True:
self.logger.info("Still connected to host")
time.sleep(2)
self.logger.info("Disconnected from host. Reboot was successful.")
while time_left > 0:
try:
self.logger.info("Checking if host [{}] is UP after reboot...".format(self.host_ip))
time.sleep(10)
self.connect_host(self.host_ip, self.user_name, self.key_file)
if self.is_connected():
self.logger.info("Host [{}] has rebooted and is back online".format(self.host_ip))
return True
else:
self.logger.info("Host [{}] has not yet rebooted".format(self.host_ip))
except Exception as e:
# Note: The exceptions we catch here are usually non-fatal because the connection attempt times out
# We just log the exception and keep going until we've exhausted our entire login timeout
reason = str(e)
self.logger.info("Caught exception. Reason = [{}]".format(reason))
time_left -= 30
self.logger.info("Login attempt failed. Total retry time left = [{}]".format(time_left))
raise Exception("ERROR: TIMEOUT! FAILED to reconnect to rebooted host [{}] after [{}] seconds".
format(self.host_ip, timeout))
#
# DRSDatabase
#
class DRSDatabase(object):
"""
Models an Oracle database object
NOTE: The reason we are adding an extra encapsulation layer of host functions above the DRSHost object
is because in the future we may need to deal with the "any host" situation instead of only one host
If/when that becomes true, the user of the DRSDatabase object does not have to worry about which
host to use.
"""
def __init__(self):
"""
Initializes a DRSDatabase object
:return: An initialized DRSDatabase object
"""
self.logger = logging.getLogger(self.__class__.__name__)
self.host_list = list()
self.host_list.append(DRSHost())
self.id = "[{}::{}]".format(type(self).__name__, id(self))
self.logger.debug("Created object " + self.id)
def is_host_connected(self):
"""
Checks if DB host connection is active/open
:return: True if connected, else False
"""
host = self.__get_valid_host()
return host.is_connected()
def connect_host(self, host_ip, user_name, key_file):
"""
Connect to the database host
:param host_ip: host IP address
:param user_name: user name
:param key_file: full path & name of SSH auth key file
:return: None
"""
host = self.__get_valid_host()
return host.connect_host(host_ip, user_name, key_file)
def disconnect_host(self):
"""
Disconnect from the database host
:return: None
"""
host = self.__get_valid_host()
return host.disconnect_host()
def execute_host_cmd(self, cmd, user_name):
"""
Executes specified command on database host
:param cmd: Command to execute
:param user_name: user name to use when executing cmd
:return: The output of the command
"""
host = self.__get_valid_host()
return host.execute_host_cmd_sudo_user(cmd, user_name)
def execute_host_cmd_pty(self, cmd, user_name):
# For Bug 33748539 (not used)
"""
Executes specified command on database host
:param cmd: Command to execute
:param user_name: user name to use when executing cmd
:return: The output of the command
"""
host = self.__get_valid_host()
return host.execute_host_cmd_sudo_user_pty(cmd, user_name)
def copy_local_file_to_db_host(self, local_file, remote_file):
"""
Copy a local file (usually a script) to the DB host
:param local_file: full path & name of the local file to copy
:param remote_file: full path & name of the remote file to copy to
:return: The output from the executed script
"""
host = self.__get_valid_host()
return host.copy_local_file_to_host(local_file, remote_file)
def execute_internal_script_on_host(self, interpreter, script_name, params, deps, exec_user_name, oraenv, warn=False):
"""
Wrapper that stages and executes internal script on DB host
:param interpreter: Script interpreter
:param script_name: Name of internal script
:param params: list of params to pass to internal script
:param deps: list of dependencies for internal script
:param exec_user_name: user name to use when executing script
:param oraenv: Whether to source oraenv before executing command ('False' if not specified)
:return: Output from executed script
"""
host = self.__get_valid_host()
return host.execute_internal_script_on_host(interpreter, script_name, params, deps, exec_user_name, oraenv, warn)
def get_is_db_rac(self, user_name):
"""
Gets the RAC (cluster) setting for the DB
:param user_name: user name to use when executing script
:return: The output of the command
"""
result = self.execute_internal_script_on_host(CONSTANT.DRS_SCRIPT_INTERPRETER_SH,
CONSTANT.DRS_SCRIPT_DB_CHECK_IF_RAC,
None, None, user_name, oraenv=True)
is_db_rac = result.stdout.strip()
self.logger.info("Got database RAC cluster setting = {}".format(is_db_rac))
return is_db_rac
def get_db_name(self, user_name):
"""
Gets the name of the database ('db_name')
:param user_name: user name to use when executing script
:return: The output of the command
"""
result = self.execute_internal_script_on_host(CONSTANT.DRS_SCRIPT_INTERPRETER_SH,
CONSTANT.DRS_SCRIPT_DB_SELECT_DB_NAME,
None, None, user_name, oraenv=True)
db_name = result.stdout.strip()
self.logger.info("Got database name = {}".format(db_name))
return db_name
def get_db_unique_name(self, exec_user_name):
"""
Gets the unique name of the database ('db_unique_name')
:param exec_user_name: user name to use when executing script
:return: The output of the command
"""
result = self.execute_internal_script_on_host(CONSTANT.DRS_SCRIPT_INTERPRETER_SH,
CONSTANT.DRS_SCRIPT_DB_SELECT_DB_UNIQUE_NAME,
None, None, exec_user_name, oraenv=True)
db_unique_name = result.stdout.strip()
self.logger.info("Got database unique name = {}".format(db_unique_name))
return db_unique_name
def verify_data_guard_config(self, DB_CONFIG, db_name, exec_user_name, expected_role, attempts_left=1):
"""
Verifies that the Data Guard (DG) configuration is correct and the database name passed in
matches with the expected role in DG configuration output. Also makes sure there are no other
DG config errors.
:param db_name: The name of the database in the DG config
:param exec_user_name: user name to use when executing script
:param expected_role: The expected role/state of the database
:param attempts_left: The number of attempts to try to get a SUCCESS result
:return: True if the DG configuration is as expected, raises Exception otherwise
"""
# NOTE: We've implemented a repeat loop here because sometimes the DB status does not show SUCCESS
# immediately after a role change. It can take up to 15-20 minutes for WARNINGS to go away. So we sleep
# and retry for specified count
params_list = [DB_CONFIG.sysdba_password]
sleep_interval = 180 # seconds
assert attempts_left > 0
while attempts_left > 0:
attempts_left -= 1
result = self.execute_internal_script_on_host(CONSTANT.DRS_SCRIPT_INTERPRETER_SH,
CONSTANT.DRS_SCRIPT_DG_SHOW_CONFIGURATION,
params_list, None, exec_user_name, oraenv=True)
dg_output = result.stdout.strip()
self.logger.debug("Data Guard command output = {}".format(dg_output))
# Verify that specified DB name in DGMGRL output matches the expected role
pattern = CONSTANT.DRS_REGEXP_DG_ROLE_DB_NAME.format(db_name, expected_role)
found = DRSUtil.search_text(pattern, dg_output, ignore_case=True)
if found is not True:
raise Exception("ERROR: FAILED to verify that database [{}] current role is [{}]".
format(db_name, expected_role))
else:
self.logger.info("Verified successfully that database [{}] has current role [{}]".
format(db_name, expected_role))
self.logger.debug("Data Guard output from script [{}] = \n[{}]".format(
CONSTANT.DRS_SCRIPT_DG_SHOW_CONFIGURATION, dg_output))
# Verify that we see "SUCCESS" string in the output (i.e. "Configuration Status: SUCCESS")
pattern = CONSTANT.DRS_REGEXP_DG_CONFIG_STATUS.format("SUCCESS")
found = DRSUtil.search_text(pattern, dg_output)
if found is not True:
if attempts_left == 0:
self.logger.error("ERROR: DGMGRL configuration output does NOT show SUCCESS\n{}".format(dg_output))
raise Exception("ERROR: DGMGRL configuration output does NOT show SUCCESS")
else:
self.logger.warning("Data Guard output from script [{}] = \n[{}]".format(
CONSTANT.DRS_SCRIPT_DG_SHOW_CONFIGURATION, dg_output))
self.logger.warning("WARNING: DGMGRL configuration output does not show SUCCESS. ")
self.logger.warning("Will re-check again after sleeping for [{}] seconds. [{}] retries left.".
format(sleep_interval, attempts_left))
time.sleep(sleep_interval)
else:
self.logger.info("DGMGRL configuration output shows SUCCESS".format(db_name))
break
return True
def convert_to_physical_standby(self, DB_PRIM, DB_STBY, exec_user_name):
"""
Convert the database to a physical database
:param DB_PRIM: The primary DB config
:param DB_STBY: The standby DB config
:param exec_user_name: user name to use when executing script
:return: True if the DG conversion to physical standby succeeded
:raises: raises Exception on errors
"""
params_list = [DB_PRIM.sysdba_password, DB_PRIM.db_unique_name, DB_STBY.db_unique_name]
result = self.execute_internal_script_on_host(CONSTANT.DRS_SCRIPT_INTERPRETER_SH,
CONSTANT.DRS_SCRIPT_DG_CONVERT_DB_TO_PHYSICAL_STANDBY,
params_list, None, exec_user_name, oraenv=True)
dg_output = result.stdout.strip()
self.logger.debug("Data Guard command output = ".format(dg_output))
# Verify that DB was converted successfully
pattern = CONSTANT.DRS_REGEXP_DG_CONVERT_PHYSICAL_STANDBY.format(DB_STBY.db_unique_name)
found = DRSUtil.search_text(pattern, dg_output, ignore_case=True)
if found is not True:
self.logger.error("ERROR: FAILED to convert database [{}] to PHYSICAL STANDBY. Data Guard Output = {}".
format(DB_STBY.db_unique_name, dg_output))
raise Exception("ERROR: FAILED to convert database to PHYSICAL STANDBY")
else:
self.logger.debug("Data Guard output from script [{}] = \n[{}]".format(
CONSTANT.DRS_SCRIPT_DG_CONVERT_DB_TO_PHYSICAL_STANDBY, dg_output))
self.logger.info("Successfully converted database [{}] to PHYSICAL STANDBY".format(DB_STBY.db_unique_name))
return True
def convert_to_snapshot_standby(self, DB_PRIM, DB_STBY, exec_user_name):
"""
Convert the standby database to a snapshot standby database
:param DB_PRIM: The primary DB config
:param DB_STBY: The standby DB config
:param exec_user_name: user name to use when executing script
:return: True if the DG conversion to snapshot standby succeeded
:raises: raises Exception on errors
"""
params_list = [DB_PRIM.sysdba_password, DB_PRIM.db_unique_name, DB_STBY.db_unique_name]
result = self.execute_internal_script_on_host(CONSTANT.DRS_SCRIPT_INTERPRETER_SH,
CONSTANT.DRS_SCRIPT_DG_CONVERT_DB_TO_SNAPSHOT_STANDBY,
params_list, None, exec_user_name, oraenv=True)
dg_output = result.stdout.strip()
self.logger.debug("Data Guard command output = ".format(dg_output))
# Verify that DB was converted successfully
pattern = CONSTANT.DRS_REGEXP_DG_CONVERT_SNAPSHOT_STANDBY.format(DB_STBY.db_unique_name)
found = DRSUtil.search_text(pattern, dg_output, ignore_case=True)
if found is not True:
self.logger.error("ERROR: FAILED to convert database [{}] to SNAPSHOT STANDBY. Data Guard Output = {}".
format(DB_STBY.db_unique_name, dg_output))
raise Exception("ERROR: FAILED to convert database to SNAPSHOT STANDBY")
else:
self.logger.debug("Data Guard output from script [{}] = \n[{}]".format(
CONSTANT.DRS_SCRIPT_DG_CONVERT_DB_TO_PHYSICAL_STANDBY, dg_output))
self.logger.info("Successfully converted database [{}] to SNAPSHOT STANDBY".format(DB_STBY.db_unique_name))
return True
def switchover_to_standby(self, DB_PRIM, DB_STBY, exec_user_name):
"""
Switchover to the standby database
:param DB_PRIM: The primary DB config
:param DB_STBY: The standby DB config
:param exec_user_name: user name to use when executing script
:return: True if the DB switchover succeeded
:raises: raises Exception on errors
"""
params_list = [DB_PRIM.sysdba_password, DB_PRIM.db_unique_name, DB_STBY.db_unique_name]
result = self.execute_internal_script_on_host(CONSTANT.DRS_SCRIPT_INTERPRETER_SH,
CONSTANT.DRS_SCRIPT_DG_SWITCHOVER_DB,
params_list, None, exec_user_name, oraenv=True)
dg_output = result.stdout.strip()
self.logger.debug("Data Guard command output = {}".format(dg_output))
# Verify that DB switchover was successful
pattern = CONSTANT.DRS_REGEXP_DG_SWITCHOVER_DB.format(DB_STBY.db_unique_name)
found = DRSUtil.search_text(pattern, dg_output, ignore_case=True)
if found is not True:
self.logger.error("ERROR: FAILED to switchover database to [{}]. Data Guard Output = {}".
format(DB_STBY.db_unique_name, dg_output))
raise Exception("ERROR: FAILED to switchover database")
else:
self.logger.info("Switchover database successful. New primary DB is [{}]".format(DB_STBY.db_unique_name))
self.logger.debug("Data Guard output from script [{}] = \n[{}]".format(
CONSTANT.DRS_SCRIPT_DG_SWITCHOVER_DB, dg_output))
return True
def __get_valid_host(self):
"""
Internal method that returns a valid host that is up and can be used to execute commands
NOTE: For now we assume that the first host (0th entry in self.host_list) is always Up & valid to return
Eventually we may need to fix this where there could be multiple hosts in a RAC cluster and some may be down
:return: DRSHost object
"""
return self.host_list[0]
# TODO: Find and return the correct host if this is a RAC cluster and some hosts are down
#
# DRSWls
#
class DRSWls(object):
"""
Models a WebLogic Server object
NOTE: The reason we are adding an extra encapsulation layer of host functions above the DRSHost object
is because in the future we may need to deal with the "any host" situation instead of only one host
If/when that becomes true, the user of the DRSWls object does not have to worry about which
host to use.
"""
def __init__(self):
"""
Initializes a DRSWls object
:return: An initialized DRSWls object
"""
self.logger = logging.getLogger(self.__class__.__name__)
self.host_list = list()
self.host_list.append(DRSHost())
self.id = "[{}::{}]".format(type(self).__name__, id(self))
self.logger.debug("Created object " + self.id)
def is_host_connected(self):
"""
Checks if WLS host connection is active/open
:return: True if connected, else False
"""
host = self.__get_valid_host()
return host.is_connected()
def connect_host(self, host_ip, user_name, key_file):
"""
Connect to the WLS host
:param host_ip: host IP address
:param user_name: user name
:param key_file: full path & name of SSH auth key file
:return: None
"""
host = self.__get_valid_host()
return host.connect_host(host_ip, user_name, key_file)
def disconnect_host(self):
"""
Disconnect from the WLS host
:return: None
"""
host = self.__get_valid_host()
return host.disconnect_host()
def execute_host_cmd(self, cmd, user_name):
"""
Executes specified command on WLS host
:param cmd: Command to execute
:param user_name: user name to use when executing cmd
:return: The output of the command
"""
host = self.__get_valid_host()
return host.execute_host_cmd_sudo_user(cmd, user_name)
def copy_local_file_to_wls_host(self, local_file, remote_file):
"""
Copy a local file (usually a script) to the WLS host
:param local_file: full path & name of the local file to copy
:param remote_file: full path & name of the remote file to copy to
:return: The output from the executed script
"""
host = self.__get_valid_host()
return host.copy_local_file_to_host(local_file, remote_file)
def copy_remote_file_from_host(self, remote_file, local_dir, user_name):
"""
Copy a file from a remote directory on this WLS host to a local dir
:param remote_file: full path & name of the remote file to copy
:param local_dir: the local directory to copy the file to
:param user_name: user name who owns remote file
:return: The full path to the copied local file
"""
host = self.__get_valid_host()
return host.copy_remote_file_from_host(remote_file, local_dir, user_name)
def execute_internal_script_on_host(self, interpreter, script_name, params, deps, user_name, oraenv, warn=False):
"""
Wrapper that stages and executes internal script on WLS host
:param interpreter: Script interpreter
:param script_name: Name of internal script
:param params: List of params to pass to internal script
:param deps: list of dependencies for internal script
:param user_name: user name to use when executing script
:param oraenv: Whether to source oraenv before executing command ('False' if not specified)
:return: Output from executed script
"""
host = self.__get_valid_host()
return host.execute_internal_script_on_host(interpreter, script_name, params, deps, user_name, oraenv, warn)
def get_wls_domain_home(self, user_name):
"""
Gets the WLS domain home using internal script
:param user_name: user name who installed/owns the WLS domain
:return: The domain home (e.g. /u01/data/domain/wls_home)
"""
result = self.execute_internal_script_on_host(CONSTANT.DRS_SCRIPT_INTERPRETER_SH,