forked from oravirt/ansible-oracle-modules
-
Notifications
You must be signed in to change notification settings - Fork 0
/
oracle_datapatch
325 lines (286 loc) · 11.2 KB
/
oracle_datapatch
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
#!/usr/bin/python
# -*- coding: utf-8 -*-
DOCUMENTATION = '''
---
module: oracle_datapatch
short_description: Manage datapatch functionality
description:
- Create/delete a database using dbca
- If a responsefile is available, that will be used. If initparams is defined, those will be attached to the createDatabase command
- If no responsefile is created, the database will be created based on all other parameters
version_added: "2.4.0.0"
options:
oracle_home:
description:
- The home where the database will be created
required: False
aliases: ['oh']
db_name:
description:
- The name of the database
required: True
default: None
aliases: ['db','database_name','name']
output:
description:
- The type of output you want.
- Verbose: stdout of the command
- short: Pre-defined message
required: False
default: short
aliases: ['db','database_name','name']
fail_on_db_not_exist:
description:
- Fail the task if the db does not exist
- If False, continues the play (changed=False)
required: False
default: True
choices: ['True','False']
user:
description:
- Password for the DB user
default: sys
aliases: ['un']
password:
description:
- Password for the DB user
required: True
default: None
aliases: ['pw','password']
hostname:
description:
- The host of the database
required: false
default: localhost
aliases: ['host']
service_name:
description:
- The service_name to connect to (will default to db_name if empty)
required: false
aliases: ['sn']
port:
description:
- The listener port to connect to the database
required: false
default: 1521
notes:
- cx_Oracle needs to be installed
requirements: [ "cx_Oracle" ]
author: Mikael Sandström, [email protected], @oravirt
'''
EXAMPLES = '''
'''
import os
try:
import cx_Oracle
except ImportError:
cx_oracle_exists = False
else:
cx_oracle_exists = True
def get_version(module, msg, oracle_home):
command = '%s/bin/sqlplus -V' % (oracle_home)
(rc, stdout, stderr) = module.run_command(command)
if rc != 0:
msg = 'Error - STDOUT: %s, STDERR: %s, COMMAND: %s' % (stdout, stderr, command)
module.fail_json(msg=msg, changed=False)
else:
return stdout.split(' ')[2][0:4]
# Check if the database exists
def check_db_exists(module, msg, oracle_home, db_name, db_unique_name ):
if gimanaged:
if db_unique_name != None:
checkdb = db_unique_name
else:
checkdb = db_name
command = "%s/bin/srvctl config database -d %s " % (oracle_home, checkdb)
(rc, stdout, stderr) = module.run_command(command)
if rc != 0:
if '%s' % (db_name) in stdout: #<-- db doesn't exist
return False
else:
msg = 'Error: command is %s. stdout is %s' % (command, stdout)
return False
elif 'Database name: %s' % (db_name) in stdout: #<-- Database already exist
return True
else:
existingdbs = []
oratabfile = '/etc/oratab'
if os.path.exists(oratabfile):
with open(oratabfile) as oratab:
for line in oratab:
if line.startswith('#') or line.startswith(' '):
continue
elif re.search(db_name +':', line):
existingdbs.append(line)
if not existingdbs: #<-- db doesn't exist
return False
else:
return True
def run_datapatch(module, msg, hsotname, oracle_home, db_name):
cursor = getconn(module,msg, hostname)
sid_sql = 'select instance_name from v$instance'
sid_ = execute_sql_get(module,msg,cursor,sid_sql)
os.environ['ORACLE_SID'] = sid_[0][0]
if major_version > '11.2':
command = '%s/OPatch/datapatch -verbose -db %s' % (oracle_home, db_name)
(rc, stdout, stderr) = module.run_command(command)
if rc != 0:
msg = 'Error - STDOUT: %s, STDERR: %s, COMMAND: %s' % (stdout, stderr, command)
module.fail_json(msg=msg, changed=False)
else:
checks = ['Patch installation complete' in stdout]
if any(checks):
if output == 'short':
return True
else:
msg = 'STDOUT: %s, COMMAND: %s' % (stdout,command)
module.exit_json(msg=msg, changed=True)
else:
msg = 'STDOUT: %s, COMMAND: %s' % (stdout,command)
module.exit_json(msg=msg, changed=False)
else:
# check_outcome_sql = 'select count(*) from registry$history'
# before = execute_sql_get(module,msg,cursor,check_outcome_sql)
datapatch_sql = '''
connect / as sysdba
@?/rdbms/admin/catbundle.sql psu apply
exit
'''
sqlplus_bin = '%s/bin/sqlplus' % (oracle_home)
p = subprocess.Popen([sqlplus_bin,'/nolog'],stdin=subprocess.PIPE,
stdout=subprocess.PIPE,stderr=subprocess.PIPE)
(stdout,stderr) = p.communicate(datapatch_sql.encode('utf-8'))
rc = p.returncode
if rc != 0:
msg = 'Error - STDOUT: %s, STDERR: %s, COMMAND: %s' % (stdout, stderr, datapatch_sql)
module.fail_json(msg=msg, changed=False)
else:
return True
# after = execute_sql_get(module,msg,cursor,check_outcome_sql)
# if after[0][0] != before[0][0]:
# if output == 'short':
# return True
# else:
# msg = 'STDOUT: %s, sql: %s' % (stdout, datapatch_sql)
# module.exit_json(msg=msg, changed=True)
# else:
# msg = 'No changes applied'
# module.exit_json(msg=msg, changed=False)
def execute_sql_get(module, msg, cursor, sql):
try:
cursor.execute(sql)
result = (cursor.fetchall())
except cx_Oracle.DatabaseError, exc:
error, = exc.args
msg = 'Something went wrong while executing sql_get - %s sql: %s' % (error.message, sql)
module.fail_json(msg=msg, changed=False)
return False
return result
# def execute_sql(module, msg, cursor, sql):
#
# try:
# cursor.execute(sql)
# except cx_Oracle.DatabaseError, exc:
# error, = exc.args
# msg = 'Something went wrong while executing sql - %s sql: %s' % (error.message, sql)
# module.fail_json(msg=msg, changed=False)
# return False
# return True
def getconn(module,msg, hostname):
if not hostname:
hostname = os.uname()[1]
wallet_connect = '/@%s' % service_name
try:
if (not user and not password ): # If neither user or password is supplied, the use of an oracle wallet is assumed
connect = wallet_connect
conn = cx_Oracle.connect(wallet_connect, mode=cx_Oracle.SYSDBA)
elif (user and password ):
dsn = cx_Oracle.makedsn(host=hostname, port=port, service_name=service_name, )
connect = dsn
conn = cx_Oracle.connect(user, password, dsn, mode=cx_Oracle.SYSDBA)
elif (not(user) or not(password)):
module.fail_json(msg='Missing username or password for cx_Oracle')
except cx_Oracle.DatabaseError, exc:
error, = exc.args
msg = 'Could not connect to database - %s, connect descriptor: %s' % (error.message, connect)
module.fail_json(msg=msg, changed=False)
cursor = conn.cursor()
return cursor
def main():
msg = ['']
cursor = None
global gimanaged
global major_version
global user
global password
global service_name
global hostname
global port
global output
module = AnsibleModule(
argument_spec = dict(
oracle_home = dict(default=None, aliases = ['oh']),
db_name = dict(required=True, aliases = ['db','database_name','name']),
db_unique_name = dict(required=False, aliases = ['dbunqn','unique_name']),
fail_on_db_not_exist = dict(default=True, type='bool'),
output = dict(default="short", choices = ["short","verbose"]),
user = dict(default='sys', aliases = ['un']),
password = dict(required=True, no_log=True, aliases = ['pw','password']),
hostname = dict(required=False, default = 'localhost', aliases = ['host']),
service_name = dict(required=False, aliases = ['sn']),
port = dict(required=False, default = 1521),
),
)
oracle_home = module.params["oracle_home"]
db_name = module.params["db_name"]
db_unique_name = module.params["db_unique_name"]
fail_on_db_not_exist = module.params["fail_on_db_not_exist"]
output = module.params["output"]
user = module.params["user"]
password = module.params["password"]
hostname = module.params["hostname"]
service_name = module.params["service_name"]
port = module.params["port"]
#ld_library_path = '%s/lib' % (oracle_home)
if oracle_home is not None:
os.environ['ORACLE_HOME'] = oracle_home
#os.environ['LD_LIBRARY_PATH'] = ld_library_path
elif 'ORACLE_HOME' in os.environ:
oracle_home = os.environ['ORACLE_HOME']
#ld_library_path = os.environ['LD_LIBRARY_PATH']
else:
msg = 'ORACLE_HOME variable not set. Please set it and re-run the command'
module.fail_json(msg=msg, changed=False)
# Decide whether to use srvctl or sqlplus
if os.path.exists('/etc/oracle/olr.loc'):
gimanaged = True
else:
gimanaged = False
if not cx_oracle_exists:
msg = "The cx_Oracle module is required. 'pip install cx_Oracle' should do the trick. If cx_Oracle is installed, make sure ORACLE_HOME & LD_LIBRARY_PATH is set"
module.fail_json(msg=msg)
# Connection details for database
if service_name is not None:
service_name = service_name
elif db_unique_name is not None:
service_name = db_unique_name
else:
service_name = db_name
# Get the Oracle version
major_version = get_version(module,msg,oracle_home)
if check_db_exists(module,msg,oracle_home,db_name,db_unique_name):
if run_datapatch(module,msg,hostname,oracle_home,db_name):
msg = 'Datapatch run successfully for database: %s' % (db_name)
module.exit_json(msg=msg, changed=True)
else:
module.fail_json(msg='datapatch failed in a unhandled way')
else:
if fail_on_db_not_exist:
msg = 'Database %s does not exist' % (db_name)
module.fail_json(msg=msg)
else:
msg = 'Database %s does not exist (so datapatch can not run, obviously), but continuing anyway' % (db_name)
module.exit_json(msg=msg, changed=False)
from ansible.module_utils.basic import *
if __name__ == '__main__':
main()