-
Notifications
You must be signed in to change notification settings - Fork 16
/
Oracle.py
1855 lines (1642 loc) · 74.8 KB
/
Oracle.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
##################################################################################################
# Name: Oracle.py #
# Author: Randy Johnson #
# Description: This is a Python library for Oracle. It is an attempt to create a library for #
# functions that are common to many DBA scripts. #
# Functions: ChunkString(InStr, Len) #
# CheckPythonVersion() #
# ConvertSize(bytes) #
# DumpConfig(ConfigFile) #
# ErrorCheck(Stdout, ComponentList=['ALL_COMPONENTS']) #
# FormatNumber(s, tSep=',', dSep='.') #
# GetAsmHome(Oratab='/etc/oratab') #
# GetClustername() #
# GetDbState() #
# GetNodes() #
# GetOracleVersion() #
# GetParameter(Parameter) #
# GetPassword(Name, User, Decrypt, PasswdFilename='/home/oracle/dba/etc/.passwd') #
# GetRedologInfo() #
# GetRmanConfig(ConnectString='target /') #
# GetVips() #
# IsExecutable(Filepath) #
# IsReadable(Filepath) #
# LoadFacilities(FacilitiesFile) #
# LoadOratab(Oratab='') #
# LookupError(Error) #
# Olsnodes(Parm='') #
# ParseConnectString(InStr) #
# ParseSqlout(Sqlout, Sqlkey, Colsep) #
# PrintError(Sql, Stdout, ErrorList=[]) #
# ProcessConfig(ConfigFile, Section) #
# RunDgmgrl(DgbCmd, ErrChk=True, ConnectString='/') #
# RunRman(RCV, ErrChk=True, ConnectString='target /') #
# RunSqlplus(Sql, ErrChk=False, ConnectString='/ as sysdba') #
# SetOracleEnv(Sid, Oratab='/etc/oratab') #
# TnsCheck(TnsName) #
# ValidateDate(DateStr) #
# WriteFile(Filename, Text, Append=False) #
# #
# History: #
# #
# Date Ver. Who Change Description #
# ---------- ---- ---------------- ------------------------------------------------------------- #
# 04/06/2012 1.00 Randy Johnson Initial release. #
# 04/24/2012 1.10 Randy Johnson Fixed bug caused when LD_LIBRARY_PATH is not set. #
# 07/10/2014 1.20 Randy Johnson Added a ton of settings and column formatting to RunSqlplus. #
# 02/16/2015 1.30 Randy Johnson Removed ... from the sqlplus SET Header #
# Added the IsExecutable() function for testing files. #
# Heavily modified the GetDbState() function. #
# Renamed the formatStackTrace() function to PythonStackTrace() #
# 03/07/2015 2.00 Randy Johnson Updated print statements for Python 3.4 compatibility. #
# 07/31/2015 2.10 Randy Johnson Added ParstConnectString() function to allow network connect. #
# Added import getpass.getpass() #
# 08/04/2015 2.20 Randy Johnson Added import of strptime. #
# 08/04/2015 2.30 Randy Johnson Modified the SetOracleEnv() function. Now returns null for #
# OracleSid and OracleHome if ORACLE_SID not found in the #
# /etc/oratab file. #
# 08/14/2015 2.31 Randy Johnson Added the -L option to RunSqlplus() so it only tries to logon #
# 1 time. #
# 08/23/2015 2.32 Randy Johnson Minor changes. #
# 09/04/2015 2.33 Randy Johnson Changed GetNodes to return {} in event of failure. Formerly #
# returned ''. #
# 11/07/2015 2.34 Randy Johnson Added GetRmanConfig() #
# changed: Popen([Rman, 'target ', '/'], ... #
# to: Popen([Rman, ConnectString], #
# 11/20/2015 2.35 Randy Johnson PythonStackTrace() repaced with traceback.format_exc() #
# 01/05/2016 2.36 Randy Johnson Added base64 and pickle to the imports when Python verison is #
# >= 3. #
# 07/12/2016 2.37 Randy Johnson Added GetOracleVersion() #
# 07/12/2017 2.38 Randy Johnson Replaced Stdout.strip() with Stdout.rstrip() in RunSqlplus. #
# 08/22/2017 2.39 Randy Johnson ErrorCheck() #
# changed: MatchObj = search(Facility + '-[0-9]+', line) #
# to: MatchObj = search(Facility + '-\d\d\d\d', line) #
# Added ResultSet class. #
# 09/05/2017 2.40 Randy Johnson updated the LoadOratab() function to reduce code and improve #
# efficiency. #
# #
##################################################################################################
# --------------------------------------
# ---- Import Python Modules -----------
# --------------------------------------
import traceback
from datetime import datetime
from getpass import getpass
from math import floor
from math import log
from math import pow
from subprocess import PIPE
from subprocess import Popen
from subprocess import STDOUT
from os import environ
from os import access
from os import path
from os import walk
from os import getpgid
from os import unlink
from os import getpgid
from os import unlink
from os import W_OK as WriteOk
from os import R_OK as ReadOk
from os import X_OK as ExecOk
from os.path import basename
from os.path import isfile
from os.path import join as pathjoin
from re import match
from re import search
from re import IGNORECASE
from re import compile
from sys import exit
from sys import exc_info
from sys import stdout as termout
from sys import version_info
from signal import SIGPIPE
from signal import SIG_DFL
from signal import signal
from time import strptime
from time import sleep
# ------------------------------------------------
# Imports that are conditional on Python Version.
# ------------------------------------------------
if (version_info[0] >= 3):
import pickle
from configparser import SafeConfigParser
from base64 import b64decode
else:
import cPickle as pickle
from ConfigParser import SafeConfigParser
# ------------------------------------------------
# For handling termination in stdout pipe; ex: when you run: oerrdump | head
signal(SIGPIPE, SIG_DFL)
# Set min/max compatible Python versions.
# ----------------------------------------
PyMaxVer = 3.4
PyMinVer = 2.4
# -------------------------------------------------
# ---- Function and Class Definitions ------------
# -------------------------------------------------
# ---------------------------------------------------------------------------
# Clas: ResultSet()
# Desc: Runs a query in sqlplus
# ---------------------------------------------------------------------------
class ResultSet:
def __init__(self, sel):
self.table = []
self.row_count = 0
self.errors = []
self.rc = 0
self.stdout = ''
colsep = '~'
Sql = "set pagesize 0\n"
Sql += "set heading off\n"
Sql += "set lines 32767\n"
Sql += "set feedback off\n"
Sql += "set echo off\n"
Sql += "set colsep '" + colsep + "'\n"
Sql += "\n"
Sql += sel + ';'
(self.rc, self.stdout, self.errors) = RunSqlplus(Sql, True, ConnectString = "/ as sysdba")
if (self.rc == 0):
for row in self.stdout.split('\n'):
columns = map(str.strip,row.split(colsep))
self.table.append(columns)
self.row_count = len(self.table)
else:
self.table.append([])
self.row_count = 0
def print_table(self):
for row in self.table:
print(row)
def get_table(self):
return self.table
def get_row_count(self):
return self.row_count
def get_errors(self):
return self.errors
def get_sqlout(self):
return self.stdout
def get_resultcode(self):
return self.rc
# ---------------------------------------------------------------------------
# End ResultSet()
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Def : GetOracleVersion()
# Desc: Determines the version of the Oracle binaries.
# Args: <none>
# Retn: 0 or exit(1)
# ---------------------------------------------------------------------------
def GetOracleVersion(OracleHome):
Sqlplus = pathjoin(OracleHome, 'bin', 'sqlplus')
# Start Sqlplus and login
Proc = Popen([Sqlplus, '-v'], stdin=PIPE, stdout=PIPE, stderr=STDOUT, shell=False, universal_newlines=True, close_fds=True)
# Fetch the output
Stdout, SqlErr = Proc.communicate()
Stdout = Stdout.strip()
MatchObj = search(r'[0-9][0-9].[0-9].[0-9].[0-9].[0-9]', Stdout)
if (MatchObj):
OracleVersion = MatchObj.group()
else:
OracleVersion = 'unknown'
return(OracleVersion)
# ---------------------------------------------------------------------------
# End GetOracleVersion()
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Def : ChunkString()
# Desc: This function returns Cgen (a generator), using a generator
# comprehension. The generator returns the string sliced, from 0 + a
# multiple of the length of the chunks, to the length of the chunks + a
# multiple of the length of the chunks.
#
# You can iterate over the generator like a list, tuple or string -
# for i in ChunkString(s,n): ,
# or convert it into a list (for instance) with list(generator).
# Generators are more memory efficient than lists because they generator
# their elements as they are needed, not all at once, however they lack
# certain features like indexing.
# Args: 1=String value
# : 2=Length of chunks to return.
# Retn:
# ---------------------------------------------------------------------------
def ChunkString(InStr, Len):
return((InStr[i:i+Len] for i in range(0, len(InStr), Len)))
# ---------------------------------------------------------------------------
# End ChunkString()
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Def : GetRedologInfo()
# Desc: Collects information about online redologs.
# Args: None.
# Retn: RedologDict{Group}...
# ---------------------------------------------------------------------------
def GetRedologInfo():
RedologDict = {}
ErrChk = True
Colsep = '~'
Sqlkey = 'ONLINE_REDOLOG'
Match = compile(r'^' + Sqlkey + '.*')
Sql = "set pages 0\n"
Sql += " SELECT 'ONLINE_REDOLOG' || '" + Colsep + "' ||\n"
Sql += " lg.group# || '" + Colsep + "' ||\n"
Sql += " lg.thread# || '" + Colsep + "' ||\n"
Sql += " lg.sequence# || '" + Colsep + "' ||\n"
Sql += " lg.bytes || '" + Colsep + "' ||\n"
Sql += " lg.blocksize || '" + Colsep + "' ||\n"
Sql += " lg.members || '" + Colsep + "' ||\n"
Sql += " lg.archived || '" + Colsep + "' ||\n"
Sql += " lg.status || '" + Colsep + "' ||\n"
Sql += " lg.first_change# || '" + Colsep + "' ||\n"
Sql += " lg.next_change# || '" + Colsep + "' ||\n"
Sql += " to_char(lg.first_time, 'yyyy-mm-dd hh24:mi:ss') || '" + Colsep + "' ||\n"
Sql += " to_char(lg.next_time, 'yyyy-mm-dd hh24:mi:ss')\n"
Sql += " FROM v$log lg\n"
Sql += "ORDER BY lg.group#;"
# Call RunSqlplus
# ----------------
(rc,Stdout,ErrorList) = RunSqlplus(Sql, ErrChk)
Stdout = Stdout.strip()
if (rc !=0):
print('Failure in call to sqlplus.')
PrintError(Sql, Stdout, ErrorList)
exit(rc)
for line in Stdout.split('\n'):
if (Match.search(line)):
r = line.split(Colsep)
Group = int(r[1])
RedologDict[Group] = {
'thread' : int(r[2]),
'sequence' : int(r[3]),
'bytes' : int(r[4]),
'blocksize' : int(r[5]),
'members' : int(r[6]),
'archived' : r[7],
'log_status' : r[8],
'first_change_num' : int(r[9]),
'next_change_num' : int(r[10]),
'first_time' : r[11],
'next_time' : r[12]
}
Sql = "set pages 0\n"
Sql += " SELECT 'ONLINE_REDOLOG' || '" + Colsep + "' ||\n"
Sql += " lf.group# || '" + Colsep + "' ||\n"
Sql += " lf.member || '" + Colsep + "' ||\n"
Sql += " lf.status || '" + Colsep + "' ||\n"
Sql += " lf.type || '" + Colsep + "' ||\n"
Sql += " lf.is_recovery_dest_file\n"
Sql += " FROM v$logfile lf\n"
Sql += "ORDER BY lf.group#, lf.member;"
# Call RunSqlplus
# ----------------
(rc,Stdout,ErrorList) = RunSqlplus(Sql, ErrChk)
Stdout = Stdout.strip()
if (rc !=0):
print('Failure in call to sqlplus.')
PrintError(Sql, Stdout, ErrorList)
exit(rc)
PrevGroup = ''
MemberList = []
for line in Stdout.split('\n'):
if (Match.search(line)):
r = line.split(Colsep)
Group = int(r[1])
if(Group == PrevGroup):
MemberList.append(r[2])
else:
MemberList = [r[2]]
RedologDict[Group]['logfile_status'] = r[3]
RedologDict[Group]['type'] = r[4]
RedologDict[Group]['is_recovery_dest_file'] = r[5]
RedologDict[Group]['members'] = MemberList
PrevGroup = Group
return(RedologDict)
# ---------------------------------------------------------------------------
# End GetRedologInfo()
# ---------------------------------------------------------------------------
# Def : ConvertSize()
# Desc: Reduces the size of a number from Bytes .. Yeta Bytes
# Args: s = numeric_string
# tSep = thousands_separation_character (default is ',')
# dSep = decimal_separation_character (default is '.')
# Retn: formatted string
#---------------------------------------------------------------------------
def ConvertSize(bytes):
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(floor(log(bytes,1024)))
p = pow(1024,i)
s = round(bytes/p,2)
if (s > 0):
return '%s %s' % (s,size_name[i])
else:
return '0B'
# ---------------------------------------------------------------------------
# End ConvertSize()
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Def : ValidateDate()
# Desc: Validates a string as a valid date format.
# Valid formats inclue:
# 1) YYYY-MM-DD
# 2) YYYY-MM-DD HH24
# 2) YYYY-MM-DD HH24:MI
# 2) YYYY-MM-DD HH24:MI:SS
# Args: String representing a date or datetime.
# Retn: tuple of (True or False, 'D' or DT')
# ---------------------------------------------------------------------------
def ValidateDate(DateStr):
try:
#datetime.strptime(DateStr, '%Y-%m-%d')
strptime(DateStr, '%Y-%m-%d')
return (True, 'YYYY-MM-DD')
except ValueError:
pass
try:
#datetime.strptime(DateStr, '%Y-%m-%d %H')
strptime(DateStr, '%Y-%m-%d %H')
return (True, 'YYYY-MM-DD HH24')
except ValueError:
pass
try:
#datetime.strptime(DateStr, '%Y-%m-%d %H:%M')
strptime(DateStr, '%Y-%m-%d %H:%M')
return (True, 'YYYY-MM-DD HH24:MI')
except ValueError:
pass
try:
#datetime.strptime(DateStr, '%Y-%m-%d %H:%M:%S')
strptime(DateStr, '%Y-%m-%d %H:%M:%S')
return (True, 'YYYY-MM-DD HH24:MI:SS')
except ValueError:
pass
return (False, '')
# ---------------------------------------------------------------------------
# End ValidateDate()
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Def : ParseConnectString()
# Desc: Parses a connect string
# Expected input strings follow:
# 1) tnsname
# 2) username@tnsname
# 3) username/password
# 4) username@tnsname
# 3) username/password@tnsname.
# Args: string representing a complete/partitial connect string.
# Retn: tuple of Username, Password, TnsName
# ---------------------------------------------------------------------------
def ParseConnectString(InStr):
TnsName = ''
Username = ''
Password = ''
ConnStr = ''
if ('@' in InStr and '/' in InStr):
(junk, TnsName) = InStr.split('@')
(Username, Password) = junk.split('/')
else:
if ('@' not in InStr and '/' not in InStr):
TnsName = InStr
else:
if ('@' in InStr and '/' not in InStr):
(Username, TnsName) = InStr.split('@')
if ('/' in InStr and '@' not in InStr):
(Username, Password) = InStr.split('/')
if (Username == ''):
if (version_info[0] >= 3):
Username = input('\nEnter user name: ')
else:
Username = raw_input('\nEnter user name: ')
if (Password == ''):
Password = getpass('\nEnter password: ')
if (Username == '' or Password == '') :
print('Username and password are required when specifying a connect string.')
print('Connect string: %s' % InStr)
exit(1)
# Formulate the connect string.
if (TnsName == ''):
ConnStr = Username + '/' + Password
else:
ConnStr = Username + '/' + Password + '@' + TnsName
if (Username.upper() == 'SYS'):
ConnStr = ConnStr + ' as sysdba'
return(ConnStr)
# ---------------------------------------------------------------------------
# End ParseConnectString()
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Clas: Logger()
# Desc: Tee's print output to a file.
# ---------------------------------------------------------------------------
class Logger(object):
def __init__(self,text):
from sys import stdout
self.logfile = text
self.terminal = stdout
self.log = open(self.logfile, "w")
if (version_info[0] >= 3):
self.encoding = stdout.encoding
self.flush = stdout.flush
self.errors = stdout.errors
def write(self, message):
self.terminal.write(message)
self.log.write(message)
# ---------------------------------------------------------------------------
# End Logger()
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Def : CheckPythonVersion()
# Desc: Checks the version of Python and prints error and exit(1) if not
# within required range.
# Args: rv=requried version
# Retn: 0 or exit(1)
# ---------------------------------------------------------------------------
def CheckPythonVersion():
import sys
v = float(str(sys.version_info[0]) + '.' + str(sys.version_info[1]))
if v >= PyMinVer and v <= PyMaxVer:
return(str(sys.version_info[0]) + '.' + str(sys.version_info[1]) + '.' + str(sys.version_info[2]))
else:
print( "\nError: The version of your Python interpreter (%1.1f) must between %1.1f and %1.1f\n" % (v, PyMinVer, PyMaxVer) )
exit(1)
# ---------------------------------------------------------------------------
# End CheckPythonVersion()
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Sub : TnsCheck()
# Desc: Verifies a tnsping lookup
# Args: ORACLE_SID
# Retn: 0 if successful, 1 if TNS Lookup failed (TNS-03505), >1 Other errors
# ----------------------------------------------------------------------------
def TnsCheck(TnsName):
rc = 0
TnsRc = 0
TnsOut = ''
TnsErr = ''
ErrorStack = []
Tnsping = pathjoin(environ['ORACLE_HOME'], 'bin', 'tnsping')
try:
proc = Popen([Tnsping, TnsName], stdin=PIPE, stdout=PIPE, stderr=STDOUT, shell=False)
(Tnsout, TnsErr) = proc.communicate()
except:
print('\n%s' % traceback.format_exc())
print('tnsping failed: %s (check tnsnames.ora file)' %s )
return(proc.returncode)
Tnsout = Tnsout.strip()
ComponentList = ['network']
(rc, ErrorList) = ErrorCheck(Tnsout, ComponentList)
if (rc != 0):
PrintError(Tnsping + " " + TnsName, Tnsout, ErrorList)
return(rc)
# ---------------------------------------------------------------------------
# End TnsCheck()
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Def : ParseSqlout()
# Desc: Parses sqlplus output and returns a dictionary structure of values.
# Args: Sqlout = stdout from sqlplus
# Sqlkey = record identifier
# Colsep = column delimiter.
# Retn: ValueDict{}
# ---------------------------------------------------------------------------
def ParseSqlout(Sqlout, Sqlkey, Colsep):
ValuesDict = {}
ValuesList = []
i = 0
Match = compile(r'^' + Sqlkey + '.*')
for line in Sqlout.split('\n'):
if (Match.search(line)):
try:
ValuesList = line.split(Colsep)[1:]
i += 1
ValuesDict[i] = ValuesList
exit()
except:
pass
return(ValuesDict)
# ---------------------------------------------------------------------------
# End ParseSqlout()
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Def : WriteFile
# Desc: Creates a text file and writes a string to the file.
# Args: Filename, Text (string to write to file)
# Retn: <none>
# ---------------------------------------------------------------------------
def WriteFile(Filename, Text, Append=False):
try:
if (Append == True):
f = open(Filename, 'a')
else:
f = open(Filename, 'w')
except:
print('Failed to open file for write: %s' % Filename)
exit(1)
f.write(Text)
f.close()
# ---------------------------------------------------------------------------
# End WriteFile()
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Def : DumpConfig()
# Desc: Dumps the configuration file to stdout.
# Args: <none>
# Retn: <none>
# ---------------------------------------------------------------------------
def DumpConfig(ConfigFile):
Config = SafeConfigParser()
# Load the configuration file.
# -----------------------------
if (IsReadable(ConfigFile)):
Config.read(ConfigFile)
ConfigSections = Config.sections()
else:
print('\nConfiguration file does not exist or is not readable: %s' % ConfigFile)
exit(1)
print('\nConfiguration: %s' % ConfigFile)
print('-------------------------------------------------------------------')
print('Sections: %s' % ConfigSections)
print(ConfigSections)
for Section in ConfigSections:
print('\n[%s]' % Section)
for Option in sorted(Config.options(Section)):
try:
Value = Config.get(Section, Option)
except:
print('\n%s' % traceback.format_exc())
print('Error parsing config file. Oracle.py->DumpConfig->ConfigConfig(%s)\n' % ConfigFile)
exit(1)
print('%-40s = %-40s' % (Option, Value))
print
return
# ---------------------------------------------------------------------------
# End DumpConfig()
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Def : ProcessConfig()
# Desc: Loads a dictionary with key/value pairs from the config file.
# Args: ConfigFile = the name of the configuration file, example: mtk.conf
# Section = the section of the config file to process, example: [migration]
# Retn: ConfigDict: dictionary structure of key/values from the section
# specified.
# ---------------------------------------------------------------------------
def ProcessConfig(ConfigFile, Section):
Config = SafeConfigParser()
ConfigDict = {}
# Load the configuration file.
# -----------------------------
if (IsReadable(ConfigFile)):
Config.read(ConfigFile)
else:
print('\nConfiguration file does not exist or is not readable: %s' % ConfigFile)
exit(1)
if (not (Section in Config.sections())):
print('Section not found in configuration file.')
print(' File : %s' % ConfigFile)
print(' Section : %s' % Section)
print('\nCheck configuration file for [%s] section (case sensitive).' % Section)
exit(1)
for Option in sorted(Config.options(Section)):
try:
ConfigDict[Option] = Config.get(Section, Option)
except:
print('\n%s' % traceback.format_exc())
print('\nError parsing config file. Oracle.py->ProcessConfig->ConfigConfig(%s)\n' % ConfigFile)
exit(1)
return(ConfigDict)
# ---------------------------------------------------------------------------
# End ProcessConfig()
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Def : IsExecutable()
# Desc: Verifies that a file is readable and executable.
# Args: Filepath = Fully qualified filename.
# Retn: 1 file is readable and executable by the current user.
# 0 file failed isfile, read or execute check.
# ---------------------------------------------------------------------------
def IsExecutable(Filepath):
if (isfile(Filepath) and access(Filepath, ReadOk) and access(Filepath, ExecOk)):
return True
else:
return False
# ---------------------------------------------------------------------------
# End IsExecutable()
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Def : IsReadable()
# Desc: Verifies that a file is readable.
# Args: Filepath = Fully qualified filename.
# Retn: 1 file is readable by the current user.
# 0 file failed isfile or read check.
# ---------------------------------------------------------------------------
def IsReadable(Filepath):
if (isfile(Filepath) and access(Filepath, ReadOk)):
return True
else:
return False
# ---------------------------------------------------------------------------
# End IsReadable()
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Def : GetParameter()
# Desc: Calls sqlplus and retrieves 1 parameter value.
# Args: Parameter
# Retn: Parameter value
# ---------------------------------------------------------------------------
def GetParameter(Parameter):
ErrChk = True
Sql = ''
Value = ''
Sql += "column value form a500\n"
Sql += "set pages 0\n"
Sql += "set feedback off\n"
Sql += "set echo off\n\n"
Sql += "select value\n"
Sql += " from ( select sv.ksppstvl value\n"
Sql += " from sys.x$ksppi i,\n"
Sql += " sys.x$ksppsv sv\n"
Sql += " where i.indx = sv.indx\n"
Sql += " and i.ksppinm = '" + Parameter.lower() + "');"
# Call RunSqlplus
# ----------------
(rc,Stdout,ErrorList) = RunSqlplus(Sql, ErrChk)
Stdout = Stdout.strip()
Value = Stdout
if (rc !=0):
print('Failure in call to sqlplus.')
PrintError(Sql, Stdout, ErrorList)
exit(rc)
return(Value)
# ---------------------------------------------------------------------------
# End GetParameter()
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Def : GetRmanConfig()
# Desc: Calls rman and retrieves all configuration settings.
# Args: Connection Strin (optional, defaults to 'target /')
# Retn: Config = a list of configuration settings
# ---------------------------------------------------------------------------
def GetRmanConfig(ConnectString='target /'):
ErrChk = True
Rcv = ''
Config = []
Rcv = 'show all;'
# Call Rman
# ----------------
(rc,Stdout,ErrorList) = RunRman(Rcv, ErrChk, ConnectString)
# Parse and print the report
if (Stdout != ''):
for line in Stdout.split('\n'):
if (line.find('CONFIGURE ',0, 10) >= 0):
Config.append(line)
if (rc !=0):
print('Failure in call to rman.')
PrintError(Rcv, Stdout, ErrorList)
exit(rc)
return(Config)
# ---------------------------------------------------------------------------
# End GetRmanConfig()
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Def : GetNodes()
# Desc: Calls olsnodes -n (list node names with node numbers).
# Args: <none>
# Retn: NodeDict[NodeName] : NodeId)
# ---------------------------------------------------------------------------
def GetNodes():
NodeDict = {}
# Setup the ASM environment
# -----------------------------
AsmHome = GetAsmHome()
AsmBin = path.join(AsmHome, 'bin')
Olsnodes = path.join(AsmBin, 'olsnodes')
if (not IsExecutable(Olsnodes)):
print('The following command cannot is not executable:', Olsnodes)
exit(1)
# Execute olsnodes -n
try:
GridProc = Popen([Olsnodes, '-n'], stdin=PIPE, stdout=PIPE, stderr=STDOUT, shell=False, universal_newlines=True, close_fds=True)
except:
print('\n%s' % traceback.format_exc())
print('Error in call to olsnodes -n')
rc = GridProc.wait()
if (rc != 0):
print(rc, Stdout)
return({})
else:
Stdout = GridProc.stdout.readlines()
for line in Stdout:
NodeName = line.split()[0]
NodeId = line.split()[1]
NodeDict[NodeName] = NodeId
return(NodeDict)
# ---------------------------------------------------------------------------
# End GetNodes()
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Def : GetVips()
# Desc: Calls olsnodes -i (print virtual IP address with the node name)
# Args: <none>
# Retn: NodeDict[NodeName] : NodeVip)
# ---------------------------------------------------------------------------
def GetVips():
VipDict = {}
# Setup the ASM environment
# -----------------------------
AsmHome = GetAsmHome()
AsmBin = path.join(AsmHome, 'bin')
Olsnodes = path.join(AsmBin, 'olsnodes')
if (not IsExecutable(Olsnodes)):
print('The following command cannot is not executable:', Olsnodes)
exit(1)
# Execute olsnodes -i
try:
GridProc = Popen([Olsnodes, '-i'], stdin=PIPE, stdout=PIPE, stderr=STDOUT, shell=False, universal_newlines=True, close_fds=True)
except:
print('\n%s' % traceback.format_exc())
print('Error in call to olsnodes -i')
rc = GridProc.wait()
if (rc != 0):
print(rc, Stdout)
return({})
else:
Stdout = GridProc.stdout.readlines()
for line in Stdout:
NodeName = line.split()[0]
NodeVip = line.split()[1]
VipDict[NodeName] = NodeVip
return(VipDict)
# ---------------------------------------------------------------------------
# End GetNodes()
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Def : GetClustername()
# Desc: Calls olsnodes -c (cluster name)
# Args: <none>
# Retn: Clustername
# ---------------------------------------------------------------------------
def GetClustername():
Clustername = ''
# Setup the ASM environment
# -----------------------------
AsmHome = GetAsmHome()
AsmBin = path.join(AsmHome, 'bin')
Olsnodes = path.join(AsmBin, 'olsnodes')
if (not IsExecutable(Olsnodes)):
print('The following command cannot is not executable:', Olsnodes)
exit(1)
# Execute olsnodes -c
try:
GridProc = Popen([Olsnodes, '-c'], stdin=PIPE, stdout=PIPE, stderr=STDOUT, shell=False, universal_newlines=True, close_fds=True)
except:
print('\n%s' % traceback.format_exc())
print('Error in call to olsnodes -c')
rc = GridProc.wait()
if (rc != 0):
print(rc, Stdout)
return('')
else:
Clustername = GridProc.stdout.read()
return(Clustername.strip())
# ---------------------------------------------------------------------------
# End GetClustername()
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Def : Olsnodes()
# Desc: Calls olsnodes and returns stdout.
# Args: <none>
# Retn: stdout
# ---------------------------------------------------------------------------
def Olsnodes(Parm=''):
NodeDict = {}
# Setup the ASM environment
# -----------------------------
AsmHome = GetAsmHome()
AsmBin = path.join(AsmHome, 'bin')
Olsnodes = path.join(AsmBin, 'olsnodes')
if (not IsExecutable(Olsnodes)):
print('The following command cannot is not executable:', Olsnodes)
exit(1)
if (Parm != ''):
Parm = '-' + Parm
try:
GridProc = Popen([Olsnodes, Parm], stdin=PIPE, stdout=PIPE, stderr=STDOUT, shell=False, universal_newlines=True, close_fds=True)
except:
print('\n%s' % traceback.format_exc())
print('Error in call to olsnodes -%s' % Parm)
else:
try:
GridProc = Popen([Olsnodes], stdin=PIPE, stdout=PIPE, stderr=STDOUT, shell=False, universal_newlines=True, close_fds=True)
except:
print('\n%s' % traceback.format_exc())
print('Error in call to olsnodes')
rc = GridProc.wait()
return(rc, Stdout.strip())
# ---------------------------------------------------------------------------
# End GetNodes()
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Def : LoadOratab()
# Desc: Parses the oratab file and returns a dictionary structure of:
# {'dbm' : '/u01/app/oracle/product/11.2.0.3/dbhome_1',
# 'biuat' : '/u01/app/oracle/product/11.2.0.3/dbhome_1',
# ...
# }
# Note** the start/stop flag is parsed but not saved.
# If the fully qualified oratab file name is passed in it is prepended
# to a list of standard locations (/etc/oratab, /var/opt/oracle/oratab)
# This list of oratab locations are then searched in order. The first
# one to be successfully opened will be used.
# Args: Oratab (optional, defaults to '')
# Retn: OratabDict (dictionary object)
# ---------------------------------------------------------------------------
def LoadOratab(Oratab=''):
OraSid = ''
OraHome = ''
OraFlag = ''
OratabDict = {}
OratabList = []
OratabLoc = ['/etc/oratab','/var/opt/oracle/oratab']
# If an oratab file name has been passed in...
if (Oratab != ''):
# If the oratab file name passed in is not already in the list of common locations...
if (not (Oratab in OratabLoc)):
OratabLoc.insert(0, Oratab)
for Oratab in OratabLoc:
if (isfile(Oratab)):
try:
otab = open(Oratab)
break # exit the loop if the file can be opened.
except:
print('\n%s' % traceback.format_exc())
print('\nCannot open oratab file: ' + Oratab + ' for read.')
return {}
# The following replaces the commented code below (###!)
if (otab == ''):