forked from oracle-devrel/oracle-autonomous-database-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtts-backup.py
More file actions
executable file
·2299 lines (1946 loc) · 93.1 KB
/
tts-backup.py
File metadata and controls
executable file
·2299 lines (1946 loc) · 93.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import json
try:
from configparser import ConfigParser
except ImportError:
from ConfigParser import ConfigParser
import string
import glob
import subprocess
import requests
from requests.auth import HTTPBasicAuth
import socket
import tarfile
import shutil
import oci
from urllib.parse import urlparse
import math
import getpass
import functools
from datetime import datetime
import re
print = functools.partial(print, flush=True)
print_stderr = functools.partial(print, file=sys.stderr, flush=True)
# stdin key value
# input : ['DBPASSWORD':'value1','TDE_WALLET_STORE_PASSWORD':'value2','DVREALM_PASSWORD':'value3']
# TODO : Encrypt and Decrypt the password
def parse_stdin_kv(line):
data = {}
line = line.strip("[]")
for item in line.split(","):
if ":" in item:
k, v = item.split(":", 1)
data[k.strip("'").upper()] = v.strip("'")
return data
def secure_input(prompt):
# Interactive shell (e.g., manual input)
if sys.stdin.isatty():
return getpass.getpass(prompt)
# Non-interactive (e.g., piped from echo or file)
else:
return sys.stdin.readline().strip()
def get_tts_tool_version(filename):
"""
Reads the first line of the version file and returns the version number.
Returns 'unknown' if the file is missing.
"""
try:
with open(filename, "r") as f:
first_line = f.readline().strip()
return first_line.split()[0]
except (FileNotFoundError, IndexError):
return "unknown"
# Check if the current Python version meets the minimum requirement.
def check_python_version(min_version):
if sys.version_info < min_version:
raise EnvironmentError(f"This script requires Python version 3.6 or higher.")
# Return the absolute path of the directory containing the script.
def scriptpath():
return os.path.dirname(os.path.realpath(__file__))
def log_start_time():
"""
Logs the start time
"""
start_time = datetime.utcnow()
print(f"Start Time (UTC): {start_time}")
return start_time
def log_end_time(start_time):
"""
Logs the end time
"""
end_time = datetime.utcnow()
elapsed = end_time - start_time
print(f"Complete Time (UTC): {end_time}")
print(f"Elapsed Time: {elapsed}\n")
# Return the single quotes comma-seperated item_list as string
def split_into_lines(items, to_upper=True, chunk_size=10):
"""
Join list of strings into comma-separated lines with line breaks every chunk_size items.
Optionally convert items to uppercase.
Returns:
str: Joined string with commas and newlines.
"""
if to_upper:
item_array = [item.strip().upper() for item in items.split(',') if item.strip()]
else:
item_array = [item.strip() for item in items.split(',') if item.strip()]
chunk_size = 10
chunks = []
for i in range(0, len(item_array), chunk_size):
chunk = item_array[i:i+chunk_size]
chunks.append("'" + "','".join(chunk) + "'")
item_list = ",\n".join(chunks)
return item_list
# Escape '$' in table names for shell safety (TABLE$1 --> TABLE\$1)
def escape_dollar(raw):
tables = []
for tbl in raw.split(','):
tbl = re.sub(r'(?<!\\)\$', r'\$', tbl.strip())
tables.append(tbl)
return ",".join(tables)
class ConsoleLogger:
"""
A class to send Python output simultaneously to the terminal and a log file.
"""
def __init__(self, logfile):
self.logfile = open(logfile, "a", buffering=1)
self.stdout = sys.stdout
self.stderr = sys.stderr
def write(self, data):
self.stdout.write(data)
self.logfile.write(data)
def flush(self):
self.stdout.flush()
self.logfile.flush()
def fileno(self):
return self.stdout.fileno()
class Environment:
"""
A class to load environment variables from a config file (tts-backup-env.txt) and expose them as attributes.
"""
def __init__(self, args, env_file: str):
self.env_file = env_file
self._env = ConfigParser()
self._defaults = {}
# Validate and load environment file
self._validate_env_file()
self._load_arg_variables(args)
self._load_env_variables()
self._preprocess()
def __str__(self):
"""Return a string representation of the loaded environment variables."""
return "\n".join([f"{key}: {value}" for key, value in self.__dict__.items()])
def __getattr__(self,item):
"""Handle missing attributes dynamically."""
if item in self.__dict__:
return self.__dict__[item]
else:
raise AttributeError(f"{item} is not a valid attribute in the environment configuration.")
def _validate_env_file(self):
"""Validate the presence of the environment file."""
if not os.path.isfile(self.env_file):
raise FileNotFoundError(f"Environment file '{self.env_file}' not found.")
def usage(self):
print_stderr("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=")
print_stderr("optional arguments allowed : --IGNORE_NON_FATAL_ERRORS, --JDK8_PATH")
print_stderr("runtime required inputs : DBPASSWORD")
print_stderr("runtime optional inputs : TDE_WALLET_STORE_PASSWORD, DVREALM_PASSWORD")
print_stderr("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=")
print_stderr("Provide inputs during runtime manually - ")
print_stderr(" Usage: python3 " + sys.argv[0] + " [OPTIONS]")
print_stderr(" Example: python3 " + sys.argv[0] + " --IGNORE_NON_FATAL_ERRORS=<True/False> --JDK8_PATH=<path to jdk8> ")
print_stderr("")
print_stderr("Or provide inputs via standard input (e.g., for automation):")
print_stderr(" (TDE and DV applicable):")
print_stderr(" echo -e \"<DBPASSWORD>\\n<TDE_WALLET_STORE_PASSWORD>\\n<DVREALM_PASSWORD>\" | python3 " + sys.argv[0] + " [OPTIONS]")
print_stderr(" (TDE applicable, DV not applicable):")
print_stderr(" echo -e \"<DBPASSWORD>\\n<TDE_WALLET_STORE_PASSWORD>\" | python3 " + sys.argv[0] + " [OPTIONS]")
print_stderr(" (TDE not applicable, DV applicable):")
print_stderr(" echo -e \"<DBPASSWORD>\\n\\n<DVREALM_PASSWORD>\" | python3 " + sys.argv[0] + " [OPTIONS]")
print_stderr(" (TDE and DV not applicable):")
print_stderr(" echo -e \"<DBPASSWORD>\" | python3 " + sys.argv[0] + " [OPTIONS]")
print_stderr("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=")
print_stderr(" ARGUMENTS DESCRIPTION ")
print_stderr("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=")
print_stderr("--IGNORE_NON_FATAL_ERRORS=<optional, provide if required to ignore schema bound object validation errors...>")
print_stderr("--JDK8_PATH=<optional, provide to use jdk8_path to download objstore bucket wallet...>")
print_stderr("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=")
sys.exit(1)
def _load_arg_variables(self, args):
"""Load environment variables from the arguments provided and
set them as class attributes."""
arg_dict = {}
arg_vars = ['IGNORE_NON_FATAL_ERRORS', 'JDK8_PATH']
# Populate arg_dict from given args
for arg in args:
if arg.startswith('--') and '=' in arg:
key, value = arg[2:].split('=', 1)
key = key.strip()
value = value.strip()
if key not in arg_vars:
print(f"Invalid argument key: {key}")
self.usage()
arg_dict[key] = value
else:
print(f"Invalid argument format: {arg}")
self.usage()
for key in arg_vars:
value = arg_dict.get(key)
setattr(self, key, value)
def _load_env_variables(self):
"""Load environment variables from the config file and set them as class attributes."""
self._env.read(self.env_file)
self._defaults = self._env['DEFAULT']
# Define and load required variables
value_fss = self._defaults.get('TTS_FSS_CONFIG', '').strip()
value_objs = self._defaults.get('TTS_BACKUP_URL', '').strip()
if value_fss:
required_vars = [
'PROJECT_NAME', 'DATABASE_NAME',
'HOSTNAME', 'LSNR_PORT', 'DB_SVC_NAME', 'ORAHOME',
'DBUSER', 'TTS_FSS_CONFIG', 'TTS_FSS_MOUNT_DIR',
'FINAL_BACKUP', 'DB_VERSION'
]
elif value_objs:
required_vars = [
'PROJECT_NAME', 'DATABASE_NAME',
'HOSTNAME', 'LSNR_PORT', 'DB_SVC_NAME', 'ORAHOME',
'DBUSER', 'TTS_BACKUP_URL', 'TTS_BUNDLE_URL',
'FINAL_BACKUP', 'DB_VERSION',
'CONFIG_FILE', 'COMPARTMENT_OCID'
]
else:
raise ValueError(f"Missing required environment variables related to file storage service or object storage service.")
for var in required_vars:
value = self._defaults.get(var, '').strip()
if not value:
raise ValueError(f"Missing required environment variable: {var}")
setattr(self, var, value)
# Limit project name to 128 characters
if len(self.PROJECT_NAME) > 128:
print_stderr("PROJECT_NAME exceeds the 128-character limit.")
exit(1)
# Set one varable which defines customer choosen storage type disk ot objs
if value_fss:
setattr(self, 'STORAGE_TYPE', 'FSS')
elif value_objs:
setattr(self, 'STORAGE_TYPE', 'OBJECT_STORAGE')
if value_objs:
if not os.path.isfile(self.CONFIG_FILE):
raise FileNotFoundError(f"CONFIG_FILE path '{self.CONFIG_FILE}' does not exist or is not a file.")
# Read the OCI config file and set fingerprint, user, tenancy, region, and key_file attributes.
oci_config = ConfigParser()
oci_config.read(self.CONFIG_FILE)
if 'DEFAULT' not in oci_config:
raise ValueError(f"OCI config file {self.CONFIG_FILE} missing [DEFAULT] section.")
default_config = oci_config['DEFAULT']
required_oci_keys = ['user', 'fingerprint', 'tenancy', 'region', 'key_file']
for key in required_oci_keys:
value = default_config.get(key, '').strip()
if not value:
raise ValueError(f"Missing required key '{key}' in OCI config file {self.CONFIG_FILE}.")
# Set as USER, FINGERPRINT, TENANCY, REGION, KEY_FILE
setattr(self, key.upper(), value)
# Load optional variables; set to empty if not found
optional_vars = ['SCHEMAS', 'TABLESPACES', 'OCI_INSTALLER_PATH',
'OCI_PROXY_HOST', 'OCI_PROXY_PORT', 'CLUSTER_MODE',
'DRCC_REGION', 'DRY_RUN', 'EXCLUDE_TABLES', 'EXCLUDE_STATISTICS',
'TRANSPORT_TABLES_PROTECTED_BY_REDACTION_POLICIES', 'TRANSPORT_TABLES_PROTECTED_BY_OLS_POLICIES',
'TRANSPORT_DB_PROTECTED_BY_DATABASE_VAULT','DVREALM_USER',
'ZDM_BASED_TRANSPORT']
for var in optional_vars:
value = self._defaults.get(var, '').strip()
if value and (var == 'TABLESPACES' or var == 'SCHEMAS'):
value = value.replace(" ", "")
if value and (var == 'EXCLUDE_TABLES'):
value = escape_dollar(value)
setattr(self, var, value)
if getattr(self, 'ZDM_BASED_TRANSPORT').strip():
# Intialise Runtime Input vars... (ZDM Transport)
stdin_line = sys.stdin.readline().strip()
parsed = parse_stdin_kv(stdin_line) if stdin_line else {}
runtime_vars = ['DBPASSWORD', 'TDE_WALLET_STORE_PASSWORD', 'DVREALM_PASSWORD']
for key in runtime_vars:
if key == "DBPASSWORD":
value = parsed.get("DBPASSWORD", "")
if not value:
print(f"Missing required variable: {key}")
elif key == "TDE_WALLET_STORE_PASSWORD":
value = parsed.get("TDE_WALLET_STORE_PASSWORD", "")
else:
value = parsed.get("DVREALM_PASSWORD", "")
setattr(self, key, value)
else:
# Intialise Runtime Input vars... (NON-ZDM Transport)
runtime_vars = ['DBPASSWORD', 'TDE_WALLET_STORE_PASSWORD']
if getattr(self, 'DVREALM_USER').strip():
runtime_vars.append('DVREALM_PASSWORD')
for key in runtime_vars:
if key == "DBPASSWORD":
value = secure_input(f"Enter database password: ").strip()
if not value:
print(f"Missing required variable: {key}")
self.usage()
elif key == "TDE_WALLET_STORE_PASSWORD":
value = secure_input(
f"Enter TDE wallet store password (optional) \n"
f"Required only if any of the tablespaces are TDE encrypted "
f"(leave empty and press Enter if not applicable): "
).strip()
else:
value = secure_input("Enter Database Vault password: ").strip()
setattr(self, key, value)
# Load optional int variables; set to 0 if not found
numeric_vars = ['PARALLELISM']
for var in numeric_vars:
try:
value = self._defaults.get(var, '').strip()
if not value:
raise ValueError(f"Missing required environment variable: {var}")
else:
setattr(self, var, int(value))
except ValueError as e:
print(f"Value Error for {var}: {e}. Expected an integer.")
# Initialise CPU_COUNT
setattr(self, 'CPU_COUNT', 0)
def _preprocess(self):
"""Perform preprocessing tasks, removing files and setting default values."""
project_dir = getattr(self, 'PROJECT_NAME')
project_dir_path = os.path.join(scriptpath(), project_dir)
setattr(self, 'PROJECT_DIR_PATH', project_dir_path)
# Set default values
setattr(self, 'BACKUP_LEVEL', 0)
setattr(self, 'INCR_SCN', 0)
setattr(self, 'FINAL_BACKUP', getattr(self, 'FINAL_BACKUP', 'FALSE') or 'FALSE')
setattr(self, 'TRANSPORT_TABLES_PROTECTED_BY_REDACTION_POLICIES', getattr(self, 'TRANSPORT_TABLES_PROTECTED_BY_REDACTION_POLICIES', 'FALSE') or 'FALSE')
setattr(self, 'TRANSPORT_TABLES_PROTECTED_BY_OLS_POLICIES', getattr(self, 'TRANSPORT_TABLES_PROTECTED_BY_OLS_POLICIES', 'FALSE') or 'FALSE')
setattr(self, 'TRANSPORT_DB_PROTECTED_BY_DATABASE_VAULT', getattr(self, 'TRANSPORT_DB_PROTECTED_BY_DATABASE_VAULT', 'FALSE') or 'FALSE')
setattr(self, 'ZDM_BASED_TRANSPORT', getattr(self, 'ZDM_BASED_TRANSPORT', 'FALSE') or 'FALSE')
final_backup = getattr(self, 'FINAL_BACKUP').strip().upper()
if final_backup not in ['TRUE', 'FALSE']:
raise ValueError(f"FINAL_BACKUP value should be one of ['TRUE' , 'FALSE' , 'true' , 'false'] but value is {final_backup}.")
#todo for redaction and ols
redaction_policies = getattr(self, 'TRANSPORT_TABLES_PROTECTED_BY_REDACTION_POLICIES').strip().upper()
if redaction_policies not in ['TRUE', 'FALSE']:
raise ValueError(f"TRANSPORT_TABLES_PROTECTED_BY_REDACTION_POLICIES value should be one of ['TRUE' , 'FALSE' , 'true' , 'false'] but value is {redaction_policies}.")
ols_policies = getattr(self, 'TRANSPORT_TABLES_PROTECTED_BY_OLS_POLICIES').strip().upper()
if ols_policies not in ['TRUE', 'FALSE']:
raise ValueError(f"TRANSPORT_TABLES_PROTECTED_BY_OLS_POLICIES value should be one of ['TRUE' , 'FALSE' , 'true' , 'false'] but value is {ols_policies}.")
dvops_protection = getattr(self, 'TRANSPORT_DB_PROTECTED_BY_DATABASE_VAULT').strip().upper()
if dvops_protection not in ['TRUE', 'FALSE']:
raise ValueError(f"TRANSPORT_DB_PROTECTED_BY_DATABASE_VAULT value should be one of ['TRUE' , 'FALSE' , 'true' , 'false'] but value is {dvops_protection}.")
zdm_transport = getattr(self, 'ZDM_BASED_TRANSPORT').strip().upper()
if zdm_transport not in ['TRUE', 'FALSE']:
raise ValueError(f"ZDM_BASED_TRANSPORT value should be one of ['TRUE' , 'FALSE' , 'true' , 'false'] but value is {zdm_transport}.")
db_version = getattr(self, 'DB_VERSION').strip().lower()
if db_version not in ['11g', '12c', '19c', '23ai']:
raise ValueError(f"DB_VERSION value should be one of ['11g', '12c', '19c', '23ai'] but value is {db_version}.")
setattr(self, 'CLUSTER_MODE', getattr(self, 'CLUSTER_MODE', 'TRUE') or 'TRUE')
cluser_mode = getattr(self, 'CLUSTER_MODE').strip().upper()
if cluser_mode not in ['TRUE', 'FALSE']:
raise ValueError(f"CLUSTER_MODE value should be one of ['TRUE' , 'FALSE' , 'true' , 'false'] but value is {cluser_mode}.")
# Set optional var's
opt_vars = ['DRCC_REGION', 'DRY_RUN', 'EXCLUDE_STATISTICS']
for var in opt_vars:
setattr(self, var, getattr(self, var, 'FALSE') or 'FALSE')
value = getattr(self, var).strip().upper()
if value not in ['TRUE', 'FALSE']:
raise ValueError(f"{var} value should be one of ['TRUE' , 'FALSE' , 'true' , 'false'] but value is {value}.")
# Other default settings
setattr(self, 'OCI_INSTALLER_PATH', getattr(self, 'OCI_INSTALLER_PATH', '') or scriptpath())
setattr(self, 'TTS_WALLET_CRED_ALIAS', '')
setattr(self, 'TTS_DIR_NAME', 'TTS_DUMP_DIR')
setattr(self, 'TDE_KEYS_FILE', "tde_keys.exp")
setattr(self, 'NEXT_SCN', 0)
setattr(self, 'MAX_CHANNELS', 200)
setattr(self, 'RMAN_LOGFILES', [])
# Create project manifest JSON file
self._create_manifest_file()
# Create directories and bundle files
self._setup_backup_directories()
# Setup log file to send all Python output to console and log file in real-time
self._setup_log_file()
#create directories needed if the storage type is fss
if getattr(self, 'STORAGE_TYPE') == "FSS":
path = os.path.join(getattr(self, 'TTS_FSS_MOUNT_DIR'), getattr(self,'PROJECT_NAME'))
os.makedirs(path, exist_ok=True)
os.makedirs(f"{path}/datafile", exist_ok=True)
os.makedirs(f"{path}/metadata", exist_ok=True)
def _create_manifest_file(self):
"""Create or load the project manifest file."""
# Retrieve project directory path
project_dir_path = getattr(self, 'PROJECT_DIR_PATH')
if project_dir_path and not os.path.exists(project_dir_path):
os.makedirs(project_dir_path)
print(f"Created project directory: {project_dir_path} \n")
# No need for manifest json in case of dry run
if getattr(self, 'DRY_RUN').strip().upper() == "TRUE":
print(f"DRY_RUN : Skipping Create/Load of project manifest file...\n")
return
# Load project manifest JSON file and process it if already exists
tts_project_file = os.path.join(project_dir_path, f"{getattr(self, 'PROJECT_NAME')}.json")
setattr(self, 'TTS_PROJECT_FILE', tts_project_file)
# Create a new manifest file if it doesn't exist
if not os.path.isfile(tts_project_file):
project_data = {
"project_name": getattr(self, 'PROJECT_NAME'),
"backup_level": getattr(self, 'BACKUP_LEVEL'),
"incr_scn": getattr(self, 'INCR_SCN')
}
with open(tts_project_file, 'w') as f:
json.dump(project_data, f, indent=2)
print(f"Created project manifest file: {tts_project_file} \n")
else:
# Load existing backup level and incr_scn from the manifest file
with open(tts_project_file, 'r') as f:
project_data = json.load(f)
setattr(self, 'BACKUP_LEVEL', project_data.get('backup_level'))
setattr(self, 'INCR_SCN', project_data.get('incr_scn'))
setattr(self, 'level0_tablespaces', project_data.get('tablespaces'))
print((f"Loaded existing project manifest file: {tts_project_file} \n"))
def _setup_backup_directories(self):
"""Set up backup directories and bundle files."""
# Create project directory based on backup level
project_dir_path = getattr(self, 'PROJECT_DIR_PATH')
if getattr(self, 'DRY_RUN').strip().upper() == "TRUE":
tts_dir_path = os.path.join(project_dir_path, f"{getattr(self, 'PROJECT_NAME')}_LEVEL_{getattr(self, 'BACKUP_LEVEL')}_DRY_RUN")
else:
tts_dir_path = os.path.join(project_dir_path, f"{getattr(self, 'PROJECT_NAME')}_LEVEL_{getattr(self, 'BACKUP_LEVEL')}")
# Check if the directory exists
if os.path.exists(tts_dir_path):
failed_dir = f"{tts_dir_path}_FAILED"
# Ensure the failed directory name is unique to avoid overwriting old failures
counter = 1
while os.path.exists(failed_dir):
failed_dir = f"{tts_dir_path}_FAILED_{counter}"
counter += 1
# Move the directory
shutil.move(tts_dir_path, failed_dir)
print(f"Moved existing failed directory '{tts_dir_path}' to '{failed_dir}'")
# Create bundle file for transport of backup files
if getattr(self, 'DRY_RUN').strip().upper() == "TRUE":
bundle_file_name = f"{getattr(self, 'PROJECT_NAME')}_LEVEL_{getattr(self, 'BACKUP_LEVEL')}_DRY_RUN.tgz"
else:
bundle_file_name = f"{getattr(self, 'PROJECT_NAME')}_LEVEL_{getattr(self, 'BACKUP_LEVEL')}.tgz"
tts_bundle_file = os.path.join(project_dir_path, bundle_file_name)
if os.path.isfile(tts_bundle_file):
now = subprocess.check_output("date +%d-%b-%Y_%H_%M_%S", shell=True).decode().strip()
if getattr(self, 'DRY_RUN').strip().upper() == "TRUE":
bundle_file_name = f"{getattr(self, 'PROJECT_NAME')}_LEVEL_{getattr(self, 'BACKUP_LEVEL')}_DRY_RUN_{now}.tgz"
else:
bundle_file_name = f"{getattr(self, 'PROJECT_NAME')}_LEVEL_{getattr(self, 'BACKUP_LEVEL')}_{now}.tgz"
tts_bundle_file = os.path.join(os.path.dirname(tts_dir_path), bundle_file_name)
if getattr(self, 'DRY_RUN').strip().upper() == "TRUE":
tts_dir_path = os.path.join(project_dir_path, f"{getattr(self, 'PROJECT_NAME')}_LEVEL_{getattr(self, 'BACKUP_LEVEL')}_DRY_RUN_{now}")
else:
tts_dir_path = os.path.join(project_dir_path, f"{getattr(self, 'PROJECT_NAME')}_LEVEL_{getattr(self, 'BACKUP_LEVEL')}_{now}")
os.makedirs(tts_dir_path, exist_ok=True)
setattr(self, 'TTS_DIR_PATH', tts_dir_path)
print(f"Created project directory with backup level {getattr(self, 'BACKUP_LEVEL')} : {tts_dir_path}.")
setattr(self, 'BUNDLE_FILE_NAME', bundle_file_name)
setattr(self, 'TTS_BUNDLE_FILE', tts_bundle_file)
def _setup_log_file(self):
"""Set up log file"""
project_dir_path = getattr(self, 'PROJECT_DIR_PATH')
if getattr(self, 'DRY_RUN').strip().upper() == "TRUE":
log_file_name = f"{getattr(self, 'PROJECT_NAME')}_LEVEL_{getattr(self, 'BACKUP_LEVEL')}_DRY_RUN.log"
else:
log_file_name = f"{getattr(self, 'PROJECT_NAME')}_LEVEL_{getattr(self, 'BACKUP_LEVEL')}.log"
log_file_path = os.path.join(project_dir_path, log_file_name)
if os.path.isfile(log_file_path):
now = subprocess.check_output("date +%d-%b-%Y_%H_%M_%S", shell=True).decode().strip()
if getattr(self, 'DRY_RUN').strip().upper() == "TRUE":
log_file_name = f"{getattr(self, 'PROJECT_NAME')}_LEVEL_{getattr(self, 'BACKUP_LEVEL')}_DRY_RUN_{now}.log"
else:
log_file_name = f"{getattr(self, 'PROJECT_NAME')}_LEVEL_{getattr(self, 'BACKUP_LEVEL')}_{now}.log"
log_file_path = os.path.join(project_dir_path, log_file_name)
setattr(self, 'TTS_LOG_FILE', log_file_name)
log_output = ConsoleLogger(log_file_path)
sys.stdout = log_output
sys.stderr = log_output
class SqlPlus:
"""
A class to run SQL commands using Oracle's SQL*Plus command-line tool.
"""
def __init__(self, dbuser, dbpassword, hostname, port, service_name, orahome):
"""Initialize with database connection details."""
self.dbuser = dbuser
self.dbpassword = dbpassword
self.hostname = hostname
self.port = port
self.service_name = service_name
self.orahome = orahome
if not os.path.isdir(self.orahome):
raise ValueError(f"Invalid ORAHOME/ORACLE_HOME directory: {self.orahome}")
self.sqlplus_path = os.path.join(self.orahome, "bin", "sqlplus")
if not os.path.isfile(self.sqlplus_path):
raise FileNotFoundError(f"SQL*Plus not found at {self.sqlplus_path}")
def run_sql(self, sql_script, log_file=None, dv_user=False):
"""Build the SQL*Plus command string."""
if dv_user:
conn_string = f"{self.dbuser}/{self.dbpassword}@{self.hostname}:{self.port}/{self.service_name}"
else:
conn_string = f"{self.dbuser}/{self.dbpassword}@{self.hostname}:{self.port}/{self.service_name} as SYSDBA"
command = f'{self.orahome}/bin/sqlplus -s "{conn_string}" << EOF\n'
command += "whenever sqlerror exit 1;\n"
command += "set heading off\nset feedback off\nset pagesize 0\nset serveroutput on\n"
if log_file:
command += f"spool {log_file};\n"
if not sql_script.strip():
raise ValueError("Empty SQL query provided.")
command += sql_script
if log_file:
command += "\nspool off;"
command += "\nEOF"
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
stdout, stderr = process.communicate()
# Check for ORA- errors even if returncode is 0
failed = False
for line in stdout.splitlines():
if "ORA-" in line or "SP2-" in line:
print(f"[SQL*Plus ERROR] {line.strip()}")
failed = True
if process.returncode != 0 or failed:
print("SQL execution failed with the following details:\n")
if stdout.strip():
print(f"STDOUT (SQL*Plus Output):\n {stdout.strip()}\n")
if stderr.strip():
print(f"STDERR (Additional Errors):\n {stderr.strip()}\n")
return False
return True
class TTS_SRC_RUN_VALIDATIONS:
"""
A class to run schema and tablespace validations for transportable tablespaces.
"""
def __init__(self, env):
self._env = env
self._sqlplus = SqlPlus(
dbuser=self._env.DBUSER,
dbpassword=self._env.DBPASSWORD,
hostname=self._env.HOSTNAME,
port=self._env.LSNR_PORT,
service_name=self._env.DB_SVC_NAME,
orahome=self._env.ORAHOME
)
self.log_file = os.path.join(self._env.TTS_DIR_PATH, f"{self._env.PROJECT_NAME}_validate.log")
def _get_tablespaces(self, template):
"""Return all tablespaces if not given"""
if self._env.TABLESPACES:
return self._env.TABLESPACES
print(f"Tablespaces not provided. Fetching all tablespaces...")
try:
_log_file = os.path.join(self._env.TTS_DIR_PATH, f"{self._env.PROJECT_NAME}_get_tablespaces.log")
if not self._sqlplus.run_sql(template.get('get_tablespaces'), _log_file):
raise ValueError(f"Failed to fetch user tablespaces.")
# Read the log file to get the SQL*Plus output
with open(_log_file, "r") as file:
lines = file.readlines()
tbs = [line.strip().upper() for line in lines if line.strip()]
self._env.TABLESPACES = ",".join(tbs)
return self._env.TABLESPACES
except Exception as e:
print(f"Error while fetching tablespaces : {e}")
raise
def _get_schemas(self, template, user_type=None):
"""Return Local/Common users"""
if user_type == "local":
if self._env.DB_VERSION == '11g':
sql_script = template.get('get_local_schemas_dbversion_11g')
else:
sql_script = template.get('get_local_schemas')
elif user_type == "common":
if self._env.DB_VERSION == '11g':
sql_script = template.get('get_common_schemas_dbversion_11g')
else:
sql_script = template.get('get_common_schemas')
elif user_type == "required":
ts_list = split_into_lines(self._env.TABLESPACES)
if self._env.DB_VERSION == '11g':
l_user_list_clause = "username not in ('SYS','SYSTEM')"
else:
l_user_list_clause = "username not in ('SYS','SYSTEM') and common='NO'"
Configuration.substitutions = {
'ts_list': ts_list.upper(),
'l_user_list_clause': l_user_list_clause,
}
if not self._env.SCHEMAS:
sql_script = template.get('owners_and_grantee_in_tablespaces')
else:
sql_script = template.get('owners_in_tablespaces')
else:
if not self._env.SCHEMAS:
print("No schemas provided. Returning a list of required users.")
self._env.SCHEMAS = self._get_schemas(template, "required")
return self._env.SCHEMAS
print(f"Fetching {user_type} users...")
try:
_log_file = os.path.join(self._env.TTS_DIR_PATH, f"{self._env.PROJECT_NAME}_get_{user_type}_schemas.log")
if not self._sqlplus.run_sql(sql_script, _log_file):
raise ValueError(f"Failed to fetch {user_type} users.")
# Read the log file to get the SQL*Plus output
with open(_log_file, "r") as file:
lines = file.readlines()
users = [line.strip().upper() for line in lines if line.strip()]
return ",".join(users)
except Exception as e:
print(f"Error while fetching {user_type} users: {e}")
raise
def _validate_schemas(self, template):
"""Validate schemas"""
print("Validating schemas...")
# Validate schemas for common users
common_users = self._get_schemas(template, "common")
required_schemas = self._get_schemas(template, "required")
sc_list = split_into_lines(self._env.SCHEMAS)
exc_tbl_list = split_into_lines(self._env.EXCLUDE_TABLES, False)
exc_tbl_filter = f"and table_name not in ({exc_tbl_list})" if exc_tbl_list.strip() else ""
_log_file = os.path.join(self._env.TTS_DIR_PATH, f"{self._env.PROJECT_NAME}_schema_validations.log")
for schema in self._env.SCHEMAS.split(','):
Configuration.substitutions = {
'schema': schema.upper(),
'exc_tbl_filter': exc_tbl_filter,
'dry_run': self._env.DRY_RUN.strip().upper(),
}
if schema.upper() in common_users.split(','):
err_msg = f"Schema validation failed: {schema} is a common user. Common users are not allowed to transport."
if self._env.DRY_RUN.strip().upper() == "TRUE":
print(err_msg)
else:
raise ValueError(err_msg)
if not self._sqlplus.run_sql(template.get('validate_schemas'), _log_file):
print(f"Schema {schema.upper()} validations failed. \n")
self._print_log_and_exit(_log_file)
if os.path.isfile(_log_file) and os.path.getsize(_log_file) > 0:
self._print_log_and_exit(_log_file, 0)
for schema in required_schemas.split(','):
if schema.upper() in common_users.split(','):
err_msg = f"Schema validation failed: {schema} is a required schema to transport and is a common user. Common users are not allowed to transport. Please update TABLESPACES list in the env."
if self._env.DRY_RUN.strip().upper() == "TRUE":
print(err_msg)
else:
raise ValueError(err_msg)
if schema.upper() not in sc_list:
err_msg = f"Schema validation failed: {schema} is a required schema to transport."
if self._env.DRY_RUN.strip().upper() == "TRUE":
print(err_msg)
else:
raise ValueError(err_msg)
def _validate_tablespaces(self, template):
"""Tablespace validation"""
print("Validating tablespaces...")
if self._env.BACKUP_LEVEL != 0:
print("Check if tablespace list is changed during incremental backups")
self._validate_tablespaces_list()
ts_array = self._env.TABLESPACES.split(',')
ts_list = split_into_lines(self._env.TABLESPACES)
ts_count = len(ts_array)
sc_list = split_into_lines(self._env.SCHEMAS)
exc_tbl_list = split_into_lines(self._env.EXCLUDE_TABLES, False)
print("Finding plsql objects that are not transported due to owner not in transport list")
self._run_object_validation(template, ts_list, sc_list)
Configuration.substitutions = {
'ts_list': ts_list.upper(),
'final_backup': self._env.FINAL_BACKUP.upper(),
}
if not self._sqlplus.run_sql(template.get('purge_dba_recyclebin')):
print(f"Validation failed: Found BIN$ objects in one or more tablespaces from tbs list..\n")
print(f"'Please purge dba_recyclebin to avoid move failures at ADBS'")
for tablespace in ts_array:
tablespace = tablespace.strip().upper()
print(f"Validate if tablespace {tablespace} is ready for transport...")
self._run_tablespace_validation_script(template, tablespace, sc_list, exc_tbl_list)
if os.path.isfile(self.log_file) and os.path.getsize(self.log_file) > 0:
print(f"Tablespace validations failed.")
self._print_log_and_exit(self.log_file, 0)
if self._env.DB_VERSION == '11g':
ts_list = "'{}'".format(",".join(self._env.TABLESPACES.split(',')))
Configuration.substitutions = {
'ts_list': ts_list
}
if not self._sqlplus.run_sql(template.get('validate_tablespaces_dbversion_11g'), f"{self.log_file} append"):
print(f"Tablespace validations failed. Please review {self.log_file} for details\n")
self._print_log_and_exit(self.log_file)
if os.path.isfile(self.log_file) and os.path.getsize(self.log_file) > 0:
print(f"Tablespace validations failed.")
self._print_log_and_exit(self.log_file, 0)
def _run_object_validation(self, template, ts_list, sc_list):
"""Run SQL object validation for all tablespaces."""
if self._env.DB_VERSION == '11g':
l_user_list_clause = "and username not in ('SYS','SYSTEM')"
else:
l_user_list_clause = "and username not in ('SYS','SYSTEM') and common='NO'"
Configuration.substitutions = {
'sc_list': sc_list.upper(),
'ts_list': ts_list.upper(),
'l_user_list_clause': l_user_list_clause,
}
if self._env.DRY_RUN.strip().upper() == "TRUE":
_log_file = os.path.join(self._env.PROJECT_DIR_PATH, f"{self._env.PROJECT_NAME}_LEVEL_{self._env.BACKUP_LEVEL}_dry_run_object_validations.log")
else:
_log_file = os.path.join(self._env.PROJECT_DIR_PATH, f"{self._env.PROJECT_NAME}_LEVEL_{self._env.BACKUP_LEVEL}_object_validations.log")
if not self._sqlplus.run_sql(template.get('object_validation'), _log_file):
print(f"\n Object validations failed. Please review:")
print(f"{_log_file}\n")
raise RuntimeError(f"Failed to run object validations on tablespaces.")
print(f"Object validations complete.\n")
if os.path.isfile(_log_file) and os.path.getsize(_log_file) > 0:
print(f" Please review: {_log_file}\n")
print("This file contains a list of database objects that will NOT be transported.\n")
if self._env.IGNORE_NON_FATAL_ERRORS and self._env.IGNORE_NON_FATAL_ERRORS.upper() == 'TRUE':
print("Errors Ignored proceeding...\n")
else:
print("Please run with option --IGNORE_NON_FATAL_ERRORS=TRUE to ignore non fatal errors...\n")
print("IGNORE_NON_FATAL_ERRORS option not provided, exiting...")
print(f" Review: {_log_file}\n")
if self._env.DRY_RUN.strip().upper() == "FALSE":
sys.exit(1)
def _validate_tablespaces_list(self):
ts_array = self._env.TABLESPACES.split(',')
level0_ts_array = self._env.level0_tablespaces
ts_set = {ts.strip().upper() for ts in ts_array if ts.strip()}
level0_ts_set = {ts.strip().upper() for ts in level0_ts_array if ts.strip()}
missing_ts = sorted(level0_ts_set - ts_set)
new_ts = sorted(ts_set - level0_ts_set)
if not missing_ts and not new_ts:
return
if missing_ts:
print(f"Missing tablespaces from level_{self._env.BACKUP_LEVEL}_backup: {missing_ts}")
if new_ts:
print(f"New tablespaces added in level_{self._env.BACKUP_LEVEL}_backup: {new_ts}")
print(
"WARNING: The tablespace list specified during the level 0 backup must not be altered.")
print(f"Proceeding with the list specified during level 0: {level0_ts_set}")
self._env.TABLESPACES = ",".join(level0_ts_array)
def _run_tablespace_validation_script(self, template, tablespace, sc_list, exc_tbl_list):
"""Run SQL validation for a single tablespace."""
exc_tbl_filter = f"and t.table_name not in ({exc_tbl_list})" if exc_tbl_list.strip() else ""
exc_tbl_filter_seg = f"and c.table_name not in ({exc_tbl_list})" if exc_tbl_list.strip() else ""
exc_tbl_filter_dt = f"and atc.table_name not in ({exc_tbl_list})" if exc_tbl_list.strip() else ""
Configuration.substitutions = {
'tablespace': tablespace.upper(),
'final_backup': self._env.FINAL_BACKUP.upper(),
'sc_list': sc_list.upper(),
'exc_tbl_filter': exc_tbl_filter,
'exc_tbl_filter_seg': exc_tbl_filter_seg,
'exc_tbl_filter_dt': exc_tbl_filter_dt,
'dry_run': self._env.DRY_RUN.strip().upper(),
}
if not self._sqlplus.run_sql(template.get('validate_tablespaces'), self.log_file):
print(f"Tablespace {tablespace} validations failed. \n")
self._print_log_and_exit(self.log_file, 0 if self._env.DRY_RUN.strip().upper() == "TRUE" else 1)
def _validate_tablespace_count(self, ts_list, ts_count):
"""Validate that the number of tablespaces does not exceed limits."""
print("Validating tablespaces count...")
# check if tablespaces count will exceed 30 on ADWCS
# ADWCS will have 5 necessary tablespaces (SYSTEM, SYSAUX, UNDO, TEMP, DATA)
# ADWCS might have 2 more tablespace (SAMPLESCHEMA, DBFS_DATA)
# ADWCS will create one datafile for each of the transported tablespaces
# Maximum number of tablespaces that can be transported is (30 - 7 = 23)
if self._env.DRCC_REGION.upper() == 'TRUE':
# DRCC regions we allow tablespace limit upto 100
# 100 - 7 (default) = 93
ts_limit = 93
else:
# NON DRCC regions we allow tablespace limit upto 30
# 30 - 7 (default) = 23
ts_limit = 23
if ts_count > ts_limit:
print(f"Tablespaces count validation failed. \n")
print(f"ERROR : Total number of specified tablespaces are : {ts_count}. Max allowed tablespace count of 30 will be exceeded in ADWCS.")
if self._env.DRY_RUN.strip().upper() == "FALSE":
exit(1)
def _validate_redaction_policies(self, template):
"""Redaction Policy validation"""
print("Validating Redaction policies...")
sc_list = split_into_lines(self._env.SCHEMAS)
Configuration.substitutions = {
'sc_list': sc_list.upper(),
}
log_file = os.path.join(self._env.TTS_DIR_PATH, f"{self._env.PROJECT_NAME}_redaction.log")
if not self._sqlplus.run_sql(template.get('validate_redaction_policies'), log_file):
print("Redaction Policies validation failed. \n")
self._print_log_and_exit(log_file)
with open(log_file, 'r') as log:
redaction_pls = log.read().strip()
if redaction_pls and self._env.TRANSPORT_TABLES_PROTECTED_BY_REDACTION_POLICIES.upper() == "FALSE":
print("Redaction Policies found in the database. You have to create the redaction policies in ADB-S database. Redacted data will be unprotected in ADB-S database otherwise. \n")
print(f"[ERROR] Please provide consent to transport tables protected by redaction policies by specifying TRANSPORT_TABLES_PROTECTED_BY_REDACTION_POLICIES=TRUE. Redaction policies found are : {redaction_pls}")
if self._env.DRY_RUN.strip().upper() == "FALSE":
exit(1)
return redaction_pls
def _validate_ols_policies(self, template):
"""OLS Policies validation"""
print("Validating OLS policies...")
sc_list = split_into_lines(self._env.SCHEMAS)
Configuration.substitutions = {
'sc_list': sc_list.upper(),
}
log_file = os.path.join(self._env.TTS_DIR_PATH, f"{self._env.PROJECT_NAME}_ols.log")
if not self._sqlplus.run_sql(template.get('validate_ols_policies'), log_file):
print("OLS Policies validation failed. \n")
self._print_log_and_exit(log_file)
with open(log_file, 'r') as log:
ols_pls = log.read().strip()
if ols_pls and self._env.TRANSPORT_TABLES_PROTECTED_BY_OLS_POLICIES.upper() == "FALSE":
print("OLS Policies found in the database. You have to create the OLS policies in ADB-S database. Data protected by OLS will be unprotected in ADB-S otherwise.\n")
print(f"[ERROR] Please provide consent to transport tables protected by OLS policies by specifying TRANSPORT_TABLES_PROTECTED_BY_OLS_POLICIES=TRUE. OLS policies found are : {ols_pls}")
if self._env.DRY_RUN.strip().upper() == "FALSE":
exit(1)
return ols_pls
def _validate_dvrealm(self, template):
"""DVREALM validation"""
print("Checking Database Vault protection...")
log_file = os.path.join(self._env.TTS_DIR_PATH, f"{self._env.PROJECT_NAME}_dvops.log")
if not self._sqlplus.run_sql(template.get('validate_dvops_protection'), log_file):
print("Database Vault protection check failed. \n")
self._print_log_and_exit(log_file)
with open(log_file, 'r') as log:
dvops_cnt = log.read().strip()
if int(dvops_cnt) > 0 and self._env.TRANSPORT_DB_PROTECTED_BY_DATABASE_VAULT.upper() == "FALSE":
print("Database Vault protection is enabled in the database. You have to re-enable database vault protection on the ADB-S database. Transported data will be unprotected otherwise \n")
print("[ERROR] Please provide consent to transport Database Vault protected database by specifying TRANSPORT_DB_PROTECTED_BY_DATABASE_VAULT=TRUE.")
if self._env.DRY_RUN.strip().upper() == "FALSE":
exit(1)
print("Checking Database Vault realms...")
log_file = os.path.join(self._env.TTS_DIR_PATH, f"{self._env.PROJECT_NAME}_dvrealm.log")
if not self._sqlplus.run_sql(template.get('validate_dvrealm_policies'), log_file):
print("Unable to check Database Vault realms. \n")
self._print_log_and_exit(log_file)
with open(log_file, 'r') as log:
dvrealm_output = log.read().strip()
dvrealm_array = dvrealm_output.split(',')
is_dv_enabled = all(int(x) > 0 for x in dvrealm_array[:3])
if is_dv_enabled:
if not self._env.DVREALM_USER.strip() or not self._env.DVREALM_PASSWORD.strip():
print("[ERROR] Database Vault is enabled in the database. Please provide inputs for DVREALM_USER and DVREALM_PASSWORD.")
if self._env.DRY_RUN.strip().upper() == "FALSE":
exit(1)
print("Validating of schemas protected by Database Vault realms...")
sqlplus = SqlPlus(
self._env.DVREALM_USER,
self._env.DVREALM_PASSWORD,
self._env.HOSTNAME,
self._env.LSNR_PORT,
self._env.DB_SVC_NAME,
self._env.ORAHOME
)
log_file = os.path.join(self._env.TTS_DIR_PATH, f"{self._env.PROJECT_NAME}_dvschemas.log")
if not sqlplus.run_sql(template.get('get_dv_protected_schemas'), log_file, True):
print("Unable to check schemas protected by Database Vault realms \n")
self._print_log_and_exit(log_file)
with open(log_file, 'r') as log:
dvschemas_output = log.read().strip()
print(dvschemas_output)
if int(dvschemas_output) == 0:
print("[ERROR]Please authorize sys as an Data Pump user to transport the Database Vault protected schemas and retry the export\n")
if self._env.DRY_RUN.strip().upper() == "FALSE":
exit(1)
def _print_log_and_exit(self, _log_file, _exit=1):
"""Print log contents and exit."""
with open(_log_file, 'r') as log:
print(log.read())
if _exit == 1:
exit(1)
class TTS_SRC_CHECK_STORAGE_BUCKETS:
"""
Class to check if storage bucket exists
"""