-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathorafacts.py
executable file
·1823 lines (1460 loc) · 69 KB
/
orafacts.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
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# export LD_LIBRARY_PATH=$ORACLE_HOME/lib:$LD_LIBRARY_PATH
#
# Module for Ansible to retrieve Oracle facts from a host.
#
#
# Written by : Cru Ansible Module development team
#
# To use your cutom module pass it in to the playbook using:
# --module-path custom_modules
#
# This module will get Oracle information from an Oracle database server
#
# For programming:
# ansible-playbook clone_database.yml -i cru_inventory --extra-vars="hosts=test_rac source_db_name=fscm9xu dest_db_name=testdb source_host=tlorad01 adupe=ss" --tags "orafacts" --step -vvv
#
# The Data collection to include: (to be checked off when implemented)
# [X] 1) all hosts on the cluster
# [X] 2) listeners being used
# listener home
#
# [X] 3) grid home and version
# [X] 4) database homes and versions
# [ ] 5) ASM or local files
# [ ] if ASM diskgroup names
# [X] 6) tnsnames file location
# [X] 7) database information
# [ ] 8) hugepages information <<== cannot be done with the sudo error we have
# [ ] 9) crsctl version
# [X] 10) srvctl version for each home : srvctl -V
# [ ] 11) log location
# - scan listeners
# - db logs
# [X] 12) lsnrctl info
# [ ] 13) agent_home - i.e. /app/oracle/agent12c/agent_inst
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# [..] various imports
# from ansible.module_utils.basic import AnsibleModule
#
# Last updated August 28, 2017 Sam Kohler
#
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.module_utils.basic import *
from ansible.module_utils.facts import *
from ansible.module_utils._text import to_native
from ansible.module_utils._text import to_text
# from ansible.error import AnsibleError
import commands
import subprocess
import sys
import os
import json
import re # regular expression
# import math
# import time
# import pexpect
# from datetime import datetime, date, time, timedelta
from subprocess import (PIPE, Popen)
# from __builtin__ import any as exists_in # exist_in(word in x for x in mylist)
ANSIBLE_METADATA = {'status': ['stableinterface'],
'supported_by': 'Cru DBA team',
'version': '0.3'}
DOCUMENTATION = '''
---
module: orafacts
short_description: Collect Oracle database metadata on a remote host.
notes: Returned values are then available to use in Ansible.
requirements: [ python2.* ]
author: "DBA Oracle module Team"
'''
EXAMPLES = '''
# for playbooks against one environment
- name: Gather Oracle facts
orafacts:
# Gathers Oracle installation information on target hosts
- name: Gather Oracle facts on destination servers
orafacts:
register: target_host
tags: orafacts
WARNING: These modules can be run with the when: master_node statement.
However, their returned values cannot be referenced later.
'''
debugme = False
host_debug_path = os.path.expanduser("~/.debug.log")
grid_home_root = "/app"
ora_home = ""
global_ora_home = ""
cru_domain = ".ccci.org"
err_msg = ""
v_rec_count = 0
grid_home = ""
err_msg = ""
node_number = ""
node_name = ""
msg = ""
oracle_base = "/app/oracle"
os_path = "PATH=/app/oracle/agent12c/core/12.1.0.3.0/bin:/app/oracle/agent12c/agent_inst/bin:/app/oracle/11.2.0.4/dbhome_1/OPatch:/app/oracle/12.1.0.2/dbhome_1/bin:/usr/lib64/qt-3.3/bin:/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/usr/local/rvm/bin:/opt/dell/srvadmin/bin:/u01/oracle/bin:/u01/oracle/.emergency_space:/app/12.1.0.2/grid/tfa/slorad01/tfa_home/bin"
israc = "UNKNOWN"
spcl_case = ['9'] # ['orcl11g','orcl12c','orcl19']
affirm = ['Y', 'y', 'Yes', 'YES', 'yes', 'True', 'TRUE', 'true', True, 'T', 't']
v_neg = [False, 'F', 'False', 'f']
network_subnet_v4 = "10"
def msgg(add_string):
"""
Add a snippet of information to the return string
"""
global msg
if msg:
msg = msg + add_string
else:
msg = add_string
def debugg(add_string):
"""If debugme is True add this debugging information to the msg to be passed out"""
global debugme
global msg
global host_debug_path
if debugme:
with open(host_debug_path, 'a') as f:
f.write(add_string + '\n')
def run_remote_cmd(cmd_str):
"""execute command on remote host"""
debugg("run_remote_cmd() :: cmd_str={}".format(cmd_str))
try:
p = subprocess.Popen([cmd_str], stdout=PIPE, stderr=PIPE, shell=True)
output, code = p.communicate()
except:
debugg("%s, %s, %s" % (sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))
debugg("run_remote_cmd() :: Error running cmd_str={} on remote".format(cmd_str))
return
debugg("run_cmd() :: returning output = %s" % (str(output)))
if output:
return(output.strip())
else:
return("")
def get_field(fieldnum, vstring):
"""Simple fuction to return a field from a string of items"""
x = 1
for i in vstring.split():
if fieldnum == x:
return i
else:
x += 1
def get_dbhome(local_vdb):
"""Return database home as recorded in /etc/oratab"""
global my_msg
global ora_home
debugg("get_dbhome() starting... with ....local_vdb={}".format(local_vdb or "empty!"))
cmd_str = "cat /etc/oratab | grep -m 1 " + local_vdb + " | grep -o -P '(?<=:).*(?<=:)' | sed 's/\:$//g'"
debugg("get_dbhome() about to run cmd_str={}".format(cmd_str or "empty!"))
try:
process = subprocess.Popen([cmd_str], stdout=PIPE, stderr=PIPE, shell=True)
output, code = process.communicate()
except:
debugg("get_dbhome() ERROR cmd_str={}".format(cmd_str or "empty!"))
my_msg = my_msg + ' Error [1]: srvctl module get_orahome() error - retrieving oracle_home exception: %s' % (sys.exc_info()[0])
my_msg = my_msg + "%s, %s, %s %s" % (sys.exc_info()[0], sys.exc_info()[1], my_msg, sys.exc_info()[2])
raise Exception (my_msg)
ora_home = output.strip()
debugg("get_dbhome()...ora_home={}".format(ora_home or "EMPTY!"))
if not ora_home:
my_msg = "Error processing %s" % (local_vdb or "Empty db string local_vdb ")
my_msg = my_msg + ' Error[2]: srvctl module get_orahome() error - retrieving oracle_home exception: %s' % (sys.exc_info()[0])
my_msg = my_msg + "%s, %s, %s %s" % (sys.exc_info()[0] or "Empty sys.exec_info 0", sys.exc_info()[1] or "Empty sys.exec_info 1", my_msg, sys.exc_info()[2] or "Empty sys.exec_info 2")
raise Exception (my_msg)
return(ora_home)
def get_nth_item(vchar, vfieldnum, vstring): # This can be done with python string.split('<char>')[3]
"""given a character vchar to deliniate a field return field number n from string vstring"""
# ex /app/oracle/12.1.0.2/dbhome_1 return field 4 (12.1.0.2) assume EOL a vchar
letter_counter = 0
vfield_counter = 0
vreturn_item = ""
while vfield_counter < (vfieldnum + 1):
if vstring[letter_counter] == vchar:
vfield_counter += 1
elif vfield_counter >= vfieldnum:
vreturn_item = vreturn_item + vstring[letter_counter]
letter_counter += 1
return(vreturn_item)
def get_node_num():
"""Return current node number to ensure that srvctl is only executed on one node (1)"""
global grid_home
global err_msg
global node_number
global node_name
global msg
tmp_cmd = ""
debugg("get_node_num()...starting...")
if not grid_home:
grid_home = get_gihome()
try:
tmp_cmd = grid_home + "/bin/olsnodes -l -n | awk '{ print $2 }'"
process = subprocess.Popen([tmp_cmd], stdout=PIPE, stderr=PIPE, shell=True)
output, code = process.communicate()
except:
err_msg = err_msg + ' Error: srvctl module get_node_num() error - retrieving node_number excpetion: %s' % (sys.exc_info()[0])
err_msg = err_msg + "%s, %s, %s %s" % (sys.exc_info()[0], sys.exc_info()[1], err_msg, sys.exc_info()[2])
raise Exception (err_msg)
node_number = int(output.strip())
debugg("get_node_num()...exiting...node_number={}".format(str(node_number)))
return(node_number)
def get_nodes(vstring):
"""Return the number of nodes in a RAC cluster and their names
vstring:
plrac1 1 <none>
plrac2 2 <none>
"""
this_node = ""
debugg("get_nodes()...starting....passed parameter={}".format(vstring))
x = 1 # This counter counts node/line numbers
tmp = {}
debugg("get_nodes()...starting nested for loops")
for vline in vstring.split("\n"):
debugg("get_nodes()...for loop #1 ...vline={}".format(vline))
this_node = "node{}".format(str(x))
node_name = vline.split()[0]
tmp.update( { this_node: node_name} )
x += 1
debugg("get_nodes()...exiting...returning={}".format(tmp))
return(tmp)
def get_gihome():
"""
# ways to find grid home fastest to slowest
1.) Find Grid Home from /etc/oratab
2.) Find the Grid Infrastructure home from running processes
3.) if Cluster is not up and running, check install 'oraInst.loc'
** 3 is too slow, do it last
"""
global grid_home_root
global grid_home
debugg("get_gihome()...starting...grid_home={}".format(grid_home or "None"))
if grid_home:
return(grid_home)
# First try /etc/oratab ( fastest ) ============================
cmd_str = "cat /etc/oratab | grep ASM | grep -v '^#' | awk -F: '{ print $2 }'"
try:
grid_dir = run_remote_cmd(cmd_str)
except:
grid_dir = None
if grid_dir:
# /app/19.0.0/grid
grid_home = grid_dir
return(grid_dir)
# Try finding it by running processes: ====================================
cmd_str = "/bin/ps -ef | /bin/grep ocssd.bin | /bin/grep -v grep | /bin/awk '{ print $8 }' | /bin/sed 's/\/bin\/ocssd.bin//g' | /bin/grep -v sed"
try:
grid_dir = run_remote_cmd(cmd_str)
except:
grid_dir = None
# /app/19.0.0/grid/bin
if grid_dir:
grid_home = grid_dir
return(grid_dir)
else:
return(None)
# finally try to construct the grid home:
cmd_str1 = "/bin/find /app -mindepth 1 -maxdepth 1 -type d -name '*[0-9]*' | awk -F/ '{ print $3 }'"
try:
first_dir = run_remote_cmd(cmd_str1)
except:
return(None)
if first_dir:
# 19.0.0
grid_dir = grid_home_root + first_dir + "grid"
if grid_dir:
grid_home = grid_dir
return(grid_dir)
else:
return(None)
def get_installed_ora_homes2():
"""Using OUI installer information get Oracle Homes for a server """
# taken from https://docs.oracle.com/cd/E11857_01/em.111/e12255/oui2_manage_oracle_homes.htm#CJAEHIGJ
# Get inventory location from the Central Inventory pointer file
# Linux location:
try:
cmd_str = "/bin/cat /etc/oraInst.loc | /bin/grep inventory_loc | /bin/cut -d '=' -f 2"
process = subprocess.Popen([cmd_str], stdout=PIPE, stderr=PIPE, shell=True)
output, code = process.communicate()
except:
err_msg = ' get_installed_ora_homes2() retrieving inventory_loc : (%s,%s)' % (sys.exc_info()[0],code)
module.fail_json(msg='ERROR: %s' % (err_msg), changed=False)
inventory_loc = output.strip()
# get oracle homes from the inventory.xml file in the inventory_loc/ContentsXML directory
try:
cmd_str = "/bin/cat " + inventory_loc + "/ContentsXML/inventory.xml | grep OraD | awk -F '=' '{print $3}' | grep -o '.*' | sed 's/\"//g' | awk '{print $1}'"
process = subprocess.Popen([cmd_str], stdout=PIPE, stderr=PIPE, shell=True)
output, code = process.communicate()
except:
err_msg = err_msg + ' get_installed_ora_homes2() retrieving vorahomes : (%s,%s)' % (sys.exc_info()[0],code)
module.fail_json(msg='ERROR: %s' % (err_msg), changed=False)
vorahomes=output.strip().split('\n')
#clean up the output and store results
for item in vorahomes:
if "11" in item:
home11g = item.strip()
elif "12" in item:
home12c = item.strip()
if home12c:
return (home12c)
else:
return (home11g)
def strip_version(vorahome):
"""Strip the oracle version from an oracle_home entry"""
debugg("strip_version().....called with : [ %s ] " % (vorahome))
all_items = vorahome.split("/")
for item in all_items:
if item and item[0].isdigit():
return(item)
return 1
def get_db_home_n_vers(local_db):
"""Using /etc/oratab return the Oracle Home for the database"""
global err_msg
global spcl_case
return_info = {}
# Change sids to db name
if local_db[-1].isdigit() and local_db[-1] not in spcl_case:
local_db = local_db[:-1]
try:
process = subprocess.Popen(["/bin/cat /etc/oratab | /bin/grep -m 1 " + local_db + " | /bin/cut -d ':' -f 2"], stdout=PIPE, stderr=PIPE, shell=True)
output, code = process.communicate()
except:
err_msg = err_msg + " Error: orafacts module get_db_home_n_vers() - retrieving oracle_home and version"
err_msg = err_msg + "%s, %s, %s, %s" % (sys.exc_info()[0], sys.exc_info()[1], err_msg, sys.exc_info()[2])
raise Exception (err_msg)
vhome = output # .strip()
debugg(" get_db_home_n_vers() local_db = %s =>> vhome = %s" % ( local_db, vhome))
if vhome:
debugg(" get_db_home_n_vers() %s has a vhome = %s" % (local_db, vhome))
try:
vversion = get_nth_item("/", 3, vhome) # get_nth_item(vchar, vfieldnum, vstring)
except:
custom_err_msg = " Error[ get_db_home_n_vers() ]: getting oracle_home for database: %s" % (local_db)
custom_err_msg = custom_err_msg + "%s, %s, %s, %s" % (sys.exc_info()[0], sys.exc_info()[1], err_msg, sys.exc_info()[2])
raise Exception (custom_err_msg)
else:
debugg(" get_db_home_n_vers() %s has no vhome" % (local_db))
vhome = get_orahome_procid(local_db)
debugg(" get_db_home_n_vers() called get_orahome_procid() and got back vhome = %s" % (vhome))
if vhome and not 'cannot' in vhome:
vversion = strip_version(vhome)
else:
crs_info = get_crsctl_info(local_db)
return( crs_info )
# exit_msg = "no process running for : %s" % (local_db)
# sys.exit(exit_msg)
return_info = { local_db: {'home':vhome.strip(), 'version': vversion}} # <<== added strip() here
return(return_info)
def get_crsctl_info(db):
""" Given a database that exists in srvctl but no info could be obtained
Try crsctl. It may be in a funky state.
/app/19.0.0/grid/bin/crsctl status resource "ora.tstdb.db"
NAME=ora.tstdb.db
TYPE=ora.database.type
TARGET=ONLINE , OFFLINE
STATE=OFFLINE, OFFLINE
"""
debugg("get_crsctl_info()...starting with db = %s" % (db))
global grid_home
if not is_rac():
return({ db: { 'home': 'unknown', 'version': 'unknown' } })
#{ local_db: {'home':vhome.strip(), 'version': vversion}}
return_info = { db: { } }
if not grid_home:
grid_home = get_gihome()
try:
cmd_str = "%s/bin/crsctl status resource 'ora.%s.db' -f" % (grid_home, db)
output = run_remote_cmd(cmd_str)
except:
return({ db: { 'home': 'unknown', 'version': 'unknown' } } )
debugg("get_crsctl_info() output = %s " % (str(output)))
if not output:
return({ db: { 'home': 'unknown', 'version': 'unknown' } } )
for line in output.split():
debugg("get_crsctl_info() processing line = %s" % (line))
if 'TARGET=' in line:
tmp_tgt = line.split("=")[1].strip()
return_info[db].update( { 'target': tmp_tgt } )
elif 'STATE=' in line:
tmp_state = line.split("=")[1].strip()
return_info[db].update( { 'state': tmp_state, 'state_details': tmp_state } )
elif 'ORACLE_HOME=' in line:
tmp_home = line.split("=")[1].strip()
debugg(" get_crsctl_info() tmp_home = [ %s ] " % (tmp_home))
vversion = strip_version(tmp_home)
return_info[db].update( { 'home': tmp_home, 'version': vversion } )
return(return_info)
def get_ora_homes():
"""Return the different Oracle and Grid homes versions installed on the host. Include opatch versions on the host and cluster name"""
global ora_home
global err_msg
global v_rec_count
global global_ora_home
tmp_nodes = ""
has_changed = False
tempHomes = {}
try:
allhomes = str(commands.getstatusoutput("cat /etc/oratab | grep -o -P '(?<=:).*(?=:)' | sort | uniq | grep -e app")[1])
except:
err_msg = err_msg + ' ERROR: get_ora_homes(): (%s)' % (sys.exc_info()[0])
for newhome in allhomes.split("\n"):
if "grid" in newhome.lower():
# use the path returned above 'newhome' and execute this command to get grid version:
try:
tmpver = str(commands.getstatusoutput(newhome + '/bin/crsctl query crs activeversion'))
except:
err_msg = err_msg + ' ERROR: get_ora_homes() - grid version: (%s)' % (sys.exc_info()[0])
# get everything between '[' and ']' from the string returned.
gver = tmpver[ tmpver.index('[') + 1 : tmpver.index(']') ]
tempHomes.update({'grid': {'version': gver, 'home': newhome}})
# cluster name
try:
clu_name = (os.popen(newhome + "/bin/olsnodes -c").read()).rstrip()
except:
err_msg = err_msg + ' ERROR: get_ora_homes() - cluster name: (%s)' % (sys.exc_info()[0])
tempHomes.update({'cluster_name': clu_name})
if is_rac():
tempHomes.update( {'is_rac': 'True'} )
else:
tempHomes.update( {'is_rac': 'False'} )
# node names in the cluster
try:
cmd_str = "{}/bin/olsnodes -n -i".format(newhome)
debugg("get_ora_homes()..#DB1...cmd_str={}".format(cmd_str))
tmp_nodes = os.popen(cmd_str).read().rstrip()
clu_names = get_nodes(tmp_nodes)
except:
err_msg = err_msg + ' ERROR: get_ora_homes() - node names in cluster: (%s) running cmd_str=%s' % (sys.exc_info()[0], cmd_str)
clu_names="Error unknown"
tempHomes.update({'nodes': clu_names})
debugg("get_ora_homes()..#DB2...tmpHomes={}".format(str(tempHomes)))
for (vkey, vvalue) in clu_names.items():
tempHomes.update({vkey: vvalue})
debugg("get_ora_homes()...#DB3...tmpHomes={}".format(tempHomes))
elif "home" in newhome.lower():
homenum = str(re.search("\d.",newhome).group())
# this command returns : Oracle Database 11g 11.2.0.4.0
try:
dbver = get_field(4, os.popen(newhome + "/OPatch/opatch lsinventory | grep 'Oracle Database'").read())
except:
err_msg = err_msg + ' ERROR: get_ora_homes() - db long version: (%s)' % (sys.exc_info()[0])
# also see what version of opatch is running in each home: opatch version | grep Version
try:
opver = str(commands.getstatusoutput(newhome + "/OPatch/opatch version | grep Version"))
except:
err_msg = err_msg + ' ERROR: get_ora_homes() - OPatch version by ora_home: (%s)' % (sys.exc_info()[0])
try:
srvctl_ver = str(commands.getstatusoutput("export ORACLE_HOME=" + newhome +";" + newhome + "/bin/srvctl -V | awk '{ print $3 }'"))
except:
err_msg = err_msg + ' ERROR: get_ora_homes() - db long version: (%s)' % (sys.exc_info()[0])
tempHomes.update({ homenum + "g": {'home': newhome, 'db_version': dbver, 'opatch_version': opver[opver.find(":")+1:-2], 'srvctl_version': srvctl_ver[5:-2]}})
return (tempHomes)
def oracle_restart_homes():
"""Return the different Oracle and Grid homes versions installed on Oracle Restart hosts"""
global ora_home
global err_msg
global v_rec_count
global global_ora_home
has_changed = False
tempHomes = {}
allhomes = run_command("cat /etc/oratab | grep -o -P '(?<=:).*(?=:)' | sort | uniq | grep -e app")
for newhome in allhomes.split("\n"):
if "grid" in newhome.lower():
tmpver = run_command(newhome + '/bin/crsctl query has softwareversion')
# get everything between '[' and ']' from the string returned.
gver = tmpver[ tmpver.index('[') + 1 : tmpver.index(']') ]
tempHomes.update({'grid': {'version': gver, 'home': newhome}})
elif "home" in newhome.lower():
homenum = str(re.search("\d.",newhome).group())
if int(homenum) <= 12:
homenum = homenum+"g"
else:
homenum = homenum+"c"
opver = run_command('export ORACLE_HOME=' + newhome +';' + newhome + '/OPatch/opatch version | grep Version')[16:]
srvctl_ver = run_command('export ORACLE_HOME=' + newhome +';' + newhome + '/bin/srvctl -V')[16:]
tempHomes.update({ homenum: {'home': newhome, 'opatch_version': opver, 'srvctl_version': srvctl_ver }})
return (tempHomes)
def get_db_status(local_vdb):
"""
Return the status of the database on the node it runs on.
The db name can be passed with, or without the instance number attached.
The return value is only the status of the instance it runs on so the instance numbers is obtained and
is used as an index on this list: ['ONLINE', 'ONLINE'] and that value is returned.
"""
global grid_home
global msg
global debugme
global spcl_case
node_number = ""
err_msg = ""
node_status = []
tmp_cmd = ""
if not grid_home:
grid_home = get_gihome()
if not grid_home:
err_msg = ' Error [1]: orafacts module get_db_status() error - retrieving local_grid_home: %s' % (grid_home)
err_msg = err_msg + "%s, %s, %s %s" % (sys.exc_info()[0], sys.exc_info()[1], err_msg, sys.exc_info()[2])
raise Exception (err_msg)
node_number = int(get_node_num())
if node_number is None:
err_msg = ' Error [2]: orafacts module get_db_status() error - retrieving node_number: %s' % (node_number)
err_msg = err_msg + "%s, %s, %s %s" % (sys.exc_info()[0], sys.exc_info()[1], err_msg, sys.exc_info()[2])
raise Exception (err_msg)
if "ASM" in local_vdb.upper():
tmp_cmd = grid_home + "/bin/crsctl status resource ora.asm | grep STATE"
elif "MGMTDB" in local_vdb.upper():
tmp_cmd = grid_home + "/bin/crsctl status resource ora.mgmtdb | grep STATE"
elif local_vdb[-1].isdigit() and local_vdb[-1] not in spcl_case: # sfk
tmp_cmd = grid_home + "/bin/crsctl status resource ora." + local_vdb[:-1] + ".db | grep STATE"
else:
tmp_cmd = grid_home + "/bin/crsctl status resource ora." + local_vdb + ".db | grep STATE"
try:
process = subprocess.Popen([tmp_cmd], stdout=PIPE, stderr=PIPE, shell=True)
output, code = process.communicate()
except:
err_msg = ' Error [3]: srvctl module get_db_status() error - retrieving oracle_home excpetion: %s' % (sys.exc_info()[0])
err_msg = err_msg + "%s, %s, %s %s" % (sys.exc_info()[0], sys.exc_info()[1], err_msg, sys.exc_info()[2])
raise Exception (err_msg)
node_status=output.strip().split(",") # ['STATE=OFFLINE', ' OFFLINE'] ['STATE=ONLINE on tlorad01', ' ONLINE on tlorad02']
i = 0
for item in node_status:
if "STATE=" in item:
node_status[i]=item.split("=")[1].strip() # splits STATE and OFFLINE and returns status 'OFFLINE'
if "ONLINE" in node_status[i]:
node_status[i] = node_status[i].strip().split(" ")[0].strip().rstrip()
elif "ONLINE" in item:
node_status[i]=item.strip().split(" ")[0].strip().rstrip()
elif "OFFLINE" in item:
node_status[i]=item.strip().rstrip()
i += 1
if len(node_status) > 1:
tmpindx = int(node_number) - 1
elif len(node_status) == 1:
tmpindx = 0
if debugme:
msg = msg + " debug info[101]: get_db_status(%s) called tmp_cmd: %s node_status: %s and status_this_node: %s" % (local_vdb, tmp_cmd, str(node_status), node_status[tmpindx])
if node_number is not None:
try:
status_this_node = node_status[tmpindx]
except:
err_msg = ' Error[4]: orafacts module get_db_status() tmpindx %s items in the node_status list: %s contents: %s node_number: %s excpetion: %s grid_home: %s local_vdb: %s' % (tmpindx, len(node_status), str(node_status), node_number, sys.exc_info()[0], grid_home, local_vdb)
err_msg = err_msg + "%s, %s, %s %s" % (sys.exc_info()[0], sys.exc_info()[1], err_msg, sys.exc_info()[2])
raise Exception (err_msg)
else:
err_msg = ' Error[5]: orafacts module get_db_status() tmpindx %s items in the node_status list %s contents %s node_number %s excpetion: %s grid_home %s local_vdb %s' % (tmpindx, len(node_status), str(node_status), node_number, sys.exc_info()[0], grid_home, local_vdb)
err_msg = err_msg + "exc_info(0) %s exc_info(1) %s err_msg %s exc_info(2) %s" % (sys.exc_info()[0], sys.exc_info()[1], err_msg, sys.exc_info()[2])
raise Exception (err_msg)
return(status_this_node)
def get_meta_data(local_db):
"""Return meta data for a database from crsctl status resource"""
tokenstoget = ['TARGET', 'STATE', 'STATE_DETAILS']
global grid_home
global my_msg
global msg
global spcl_case #sfk
local_ora_home = ""
spcl_state = ""
metadata = {}
debugg("get_meta_data() called from rac_running_homes() with ....local_db:[ %s ]" % (local_db))
if not grid_home:
grid_home = get_gihome()
debugg("get_meta_data() grid_home: %s" % (grid_home))
# get host / node name
tmp_cmd = "/bin/hostname | cut -d. -f1"
debugg("get_meta_data() tmp_cmd #1: %s" % (tmp_cmd))
try:
process = subprocess.Popen([tmp_cmd], stdout=PIPE, stderr=PIPE, shell=True)
output, code = process.communicate()
except:
my_msg = ' Error [1]: srvctl module get_orahome() error - retrieving oracle_home excpetion: %s' % (sys.exc_info()[0])
my_msg = my_msg + "%s, %s, %s %s" % (sys.exc_info()[0], sys.exc_info()[1], my_msg, sys.exc_info()[2])
raise Exception (my_msg)
debugg("get_meta_data() output #1: %s" % (str(output)))
node_name = output.strip()
if 'mgmt' in local_db and node_name[-1:] == "2":
return({})
# the next command takes db name without instance number, so remove it if it exists
if local_db[-1].isdigit() and local_db[-1] not in spcl_case: #sfk
local_db = local_db[:-1]
if 'mgmt' in local_db.lower():
tmp_cmd = grid_home + "/bin/crsctl status resource ora.mgmtdb.db -v -n " + node_name
else:
tmp_cmd = grid_home + "/bin/crsctl status resource ora." + local_db + ".db -v -n " + node_name
debugg("get_meta_data() tmp_cmd #2: %s" % (tmp_cmd))
try:
process = subprocess.Popen([tmp_cmd], stdout=PIPE, stderr=PIPE, shell=True)
output, code = process.communicate()
except:
my_msg = ' Error [1]: srvctl module get_meta_data() output: %s' % (output)
my_msg = my_msg + "%s, %s, %s %s" % (sys.exc_info()[0], sys.exc_info()[1], my_msg, sys.exc_info()[2])
raise Exception (my_msg)
debugg("get_meta_data() output #2: %s" % (str(output)))
if not output and 'mgmt' not in local_db.lower():
try:
local_ora_home = get_orahome_procid(local_db)
if local_ora_home:
spcl_state = get_more_db_info(local_db, local_ora_home)
else:
spcl_state = "UNK"
except:
err_msg = ' Error: get_meta_data(): call to get_more_db_info(): local_db: %s local_ora_home: %s spcl_state: %s' % (local_db, local_ora_home, spcl_state)
err_msg = err_msg + "%s, %s, %s %s" % (sys.exc_info()[0], sys.exc_info()[1], err_msg, sys.exc_info()[2])
debugg("post get_more_db_info()..called with local_db = %s local_ora_home = %s err_msg = %s" % (local_db, local_ora_home, err_msg))
spcl_state = "possibly residual info in srvctl or /etc/oratab entry but no db"
# raise Exception (err_msg)
metadata = {'STATE': spcl_state,'TARGET': 'unknown','STATE_DETAILS': 'unknown', 'status': 'unknown'}
debugg(" metadata = %s" % (str(metadata)))
else:
vhomey = ""
try:
for item in output.split('\n'):
debugg("get_meta_data() item: %s" % (str(item)))
if item:
if "STATE_DETAILS" in item and ',' in item:
# item: STATE_DETAILS=Open,HOME=/app/oracle/12.1.0.2/dbhome_1
# STATE_DETAILS Open,HOME /app/oracle/12.1.0.2/dbhome_1
vkey, vvalue, vhomey = item.split("=")
vvalue = vvalue.split(",")[0].upper()
debugg(" STATE_DETAILS CASE: vkey = %s vvalue = %s vhomey = %s\n" % (vkey, vvalue, vhomey))
metadata[vkey] = vvalue
else:
vkey, vvalue = item.split('=')
vkey = vkey.strip()
vvalue = vvalue.strip()
debugg(" vkey = %s vvalue = %s" % ( vkey, vvalue))
if "STATE=" in vvalue:
vvalue=vvalue.split("=")[1].strip()
if "ONLINE" in vvalue:
vvalue = vvalue.strip().split(" ")[0].strip().rstrip()
elif "ONLINE" in vvalue:
vvalue=vvalue.strip().split(" ")[0].strip().rstrip()
elif "OFFLINE" in vvalue:
vvalue=vvalue.strip().rstrip()
if vkey in tokenstoget:
metadata[vkey] = vvalue
except:
my_msg = "ERROR: srvctl module get_meta_data(%s) error - loading metadata dict: %s" % (local_db, str(metadata))
my_msg = my_msg + "%s, %s, %s %s" % (sys.exc_info()[0], sys.exc_info()[1], my_msg, sys.exc_info()[2])
debugg(my_msg)
raise Exception (my_msg)
debugg(" get_meta_data() exiting for db: %s metadata dictionary contents : %s" % (local_db, str(metadata)))
return(metadata)
def get_more_db_info(vtmpdb, vtmporahome):
"""When database isn't registerd with crsctl (instance in startup nomount for duplication etc.) get actual state of db"""
global node_number
global err_msg
global os_path
dbstate = ""
if not vtmporahome:
return("unknown")
if not node_number:
node_number = get_node_num()
tmpsid = vtmpdb + str(node_number)
tmpsql = "select decode( status, 'STARTED', 'STARTED NOMOUNT', 'MOUNTED', 'STARTED MOUNT','OPEN','OPEN','OPEN MIGRATE', 'OPEN UPGRADE') from v$instance;"
try:
os.environ['ORACLE_HOME'] = vtmporahome
os.environ['ORACLE_SID'] = tmpsid
os.environ['NLS_DATE_FORMAT'] = 'Mon DD YYYY HH24:MI:SS'
os.environ['PATH'] = os_path
os.environ['USER'] = 'oracle'
session = subprocess.Popen(['sqlplus', '-S', '/ as sysdba'],stdin=PIPE,stdout=PIPE,stderr=PIPE)
session.stdin.write(tmpsql)
(stdout,stderr) = session.communicate()
except:
err_msg = ' Error: get_more_db_info() opening session'
err_msg = err_msg + "%s, %s, %s %s" % (sys.exc_info()[0], sys.exc_info()[1], err_msg, sys.exc_info()[2])
raise Exception (err_msg)
dbstate = stdout.split('\n')[3]
return(dbstate)
def rac_running_homes():
"""Return running databases for RAC, their version, oracle_home, pid, status"""
# This function will get all the running databases and the homes they're
# running out of. The pgrep statement was taken from Tanel Poders website. http://blog.tanelpoder.com
global err_msg
global msg
global v_rec_count
global ora_home
global grid_home
global node_number
global spcl_case # sfk
tempstat = ""
tempdb = ""
local_cmd = ""
dbs = {}
meta_data = {}
srvctl_dbs = []
tmp_db_status = ""
spcl_state = ""
debugg("======= rac_running_homes()...starting...")
if not node_number:
node_number = get_node_num()
debugg("rac_running_homes()...node_number = %s" % (node_number))
# Get a list of running instances
try:
# cmd_str = "pgrep -lf _pmon_ | grep -v oracle | grep -v sh | /bin/sed 's/ora_pmon_/ /; s/asm_pmon_/ /' | /bin/grep -v sed"
cmd_str = "ps -ef | grep _pmon_ | /bin/sed 's/ora_pmon_/ /; s/asm_pmon_/ /' | grep -v sed | grep -v grep | awk '{ print $2 \" \" $8}'"
debugg(" cmd_str = %s\n" % (cmd_str))
# vproc = str(commands.getstatusoutput(cmd_str)[1])
vproc = run_remote_cmd(cmd_str)
except:
err_msg = ' Error: rac_running_homes() - pgrep lf pmon: (%s)' % (sys.exc_info()[0])
debugg(err_msg)
return
debugg("rac_running_homes() cmd output \nSTART vproc: \n=========>\n%s \n<======= \n END\n" % (str(vproc)))
# vproc holds : pid db_name ex. (6205 jfpwtest1\n ) in a stack if all running dbs
for vdbproc in vproc.split("\n"):
debugg("rac_running_homes() #1...vdbproc = [ %s ]" % (vdbproc))
vprocid, vdbname = vdbproc.strip().split()
debugg("rac_running_homes() #2...vprocid = %s vdbname = %s" % (vprocid, vdbname))
# get Oracle home the db process is running out of
try:
vhome = str(commands.getstatusoutput("sudo ls -l /proc/" + vprocid + "/exe | awk -F'>' '{ print $2 }' | sed 's/bin\/oracle$//' | sort | uniq"))
except:
err_msg = err_msg + ' Error: rac_running_homes() - vhome: (%s)' % (sys.exc_info()[0])
debugg(" rac_running_homes()...vhome = %s" % (vhome))
# Get the running database version from the Oracle home path that was returned:
if "oracle" in vhome:
vver = vhome[vhome.index("oracle")+7:vhome.index("dbhome")-1]
elif "grid" in vhome:
vver = vhome[vhome.index("app")+4:vhome.index("grid")-1]
debugg(" rac_running_homes()...vver = %s" % (vver))
ora_home = vhome[ vhome.find("/") : -3 ]
debugg(" rac_running_homes()...ora_home = %s" % (ora_home))
if "MGMTDB" in vdbname.upper():
vdbname = "mgmtdb"
tmpdbstatus = get_db_status(vdbname) #<<<<<<<<<<<<<<<<<<<<<
if not tmpdbstatus:
tmpdbstatus = "unknown"
debugg(" rac_running_homes()...tmpdbstatus = %s" % (tmpdbstatus))
# tmpnodenum = int(node_number) - 1
debugg("#1 ............CUTTING.....vdbname = %s" % (vdbname))
if vdbname[-1].isdigit() and vdbname[-1] not in spcl_case:
tmpdbname = vdbname[:-1]
else:
tmpdbname = vdbname
debugg(" rac_running_homes()...tmpdbname = %s ___________ after cutting........." % (tmpdbname))
# get metadata (STATE=OFFLINE, STATE_DETAILS=Instance Shutdown, TARGET=OFFLINE) for each db
if tmpdbname.lower() not in ["mgmtdb", "+asm"] and vdbname.lower() != "grid":
try:
debugg("line #738 tmpdbname = [ %s ] calling get_meta_data()" % (tmpdbname))
metadata = {}
metadata = get_meta_data(tmpdbname)
if metadata:
dbs.update({vdbname: {'home': vhome[ vhome.find("/") - 1 : -3].strip(), 'version': vver, 'pid': vprocid, 'state': metadata['STATE'], 'target': metadata['TARGET'], 'state_details': metadata['STATE_DETAILS'], 'status': tmpdbstatus }} ) #[77]
except:
# err_msg = ' Error: loading dbs dict vdbname: %s home: %s version: %s pid: %s state: %s target: %s state_details: %s status: %s' % (vdbname, vhome[ vhome.find("/") - 1 : -3], vver, vprocid, metadata['STATE'], metadata['TARGET'],metadata['STATE_DETAILS'], tmpdbstatus )
err_msg = 'Error: rac_running_homes() - get_meta_data() : %s ' % (vdbname)
err_msg = err_msg + "%s, %s, %s %s" % (sys.exc_info()[0], sys.exc_info()[1], err_msg, sys.exc_info()[2])
debugg("%s" % (err_msg))
raise Exception (err_msg)
else:
dbs.update({vdbname: {'home': vhome[ vhome.find("/") - 1 : -3].strip(), 'version': vver, 'pid': vprocid, 'status': tmpdbstatus }} )
debugg(" rac_running_homes()...dbs = %s" % (str(dbs)))
# get a list of all databases registered with srvctl to find those offline
local_cmd = ""
tmporahome = get_installed_ora_homes2() # returns the highest ranking home
local_cmd = "export ORACLE_HOME=" + tmporahome + "; " + tmporahome + "/bin/srvctl config"
try:
process = subprocess.Popen([local_cmd], stdout=PIPE, stderr=PIPE, shell=True)
output, code = process.communicate()
except:
err_msg = err_msg + ' Error: srvctl module get_db_status() error - retrieving tmporahome: %s excpetion: %s' % (tmporahome, sys.exc_info()[0])
err_msg = err_msg + "%s, %s, %s %s" % (sys.exc_info()[0], sys.exc_info()[1], err_msg, sys.exc_info()[2])
raise Exception (err_msg)
debugg(" rac_running_homes()...output = %s" % (str(output)))
# put all the srvctl config databases in a list (srvctl_dbs)
for i in output.strip().split("\n"):
if i:
srvctl_dbs.append(i)
debugg(" srvctl_dbs=%s" % (str(srvctl_dbs)))
# databases registered with srvctl but not already listed with running databases. (OFFLINE)
local_cmd = ""
vversion = ""
vdatabase = ""
vnextdb = ""
tmpdbhome = {}
tmpdbstatus = ""
vmetadata={}
for vdatabase in srvctl_dbs:
debugg("for vdatabase=%s in srvctl_dbs")
if is_rac:
vnextdb = vdatabase + str(node_number)
else:
vnextdb = vdatabase
if vnextdb not in dbs:
msg = msg + "srvctl dbs %s" % (vnextdb)
tmpdbhome = get_db_home_n_vers(vnextdb) # return_info = { local_db: {'home':vhome, 'version': vversion}}
tempdbstatus = get_db_status(vnextdb)
vmetadata = get_meta_data(vnextdb)
if vnextdb[-1].isdigit() and vnextdb[-1] not in spcl_case:
dbname = vnextdb[:-1]
else:
dbname = vnextdb