For EMCLI and patching automation, there are two scripts used that generate the patch plan property file(s), create the patch plan(s) in OEM, submit them for analyzing and try to submit the plan for deployment.  It is possible to run these without getting into OEM at all, or you can set all the options and create the plan in OEM and then use OEM to make changes once the plan is created in OEM.  The scripts use parameters to establish the type of plan and the options required to create a patch plan of a specific type in OEM that is valid and can be analyzed.

As mentioned, there two scripts: one does GI patching and the other does RDBMS patching. Both scripts are capable of generating both “In Place” or “Out Of Place” patch plans, bypassing a command-line argument for the deployment type, and both scripts are capable of patching 11g or 12c or 13c Oracle software deployments for Grid and RDBMS.

The scripts require command-line arguments to control and setup processing for both RDBMS and Grid patching. The arguments and their position/order are listed below and described.  The scripts are called via the EMCLI interpreter, such as

Examples of calling EMCLI with the scripts and arguments for patching RDBMS:

/emcli @patch_rdbms.py config_search inplace       24412235 DBPTCH 11.2.0.4.160119 
/emcli @patch_rdbms.py config_search outofplace 24412235 DBPTCH 11.2.0.4.160119

Example of calling EMCLI with the scripts and arguments for patching Grid:

/emcli @patch_grid.py config_search inplace       24412235 GIPTCH 
/emcli @patch_grid.py config_search outofplace 24412235 GIPTCH

Command-line arguments used by both scripts:

  • EMCLI script name to be run (either “patch_grid.py” or “patch_rdbms.py”):
    • ./emcli @script_name
  • target list selection and type
    • config_search or group or list of hosts or databases such as a group search or a list of hosts on the command line
  • Deployment type
    • “inplace” or “outoplace”
  • Patch list
    • Either a single patch number, or a comma separated list of patches as one argument
    • 24413234
    • 24413235,2319081
  • Patch plan prefix name
    • prefix for the name of the patch plan in OEM (display name in OEM)
      1. SOEDBPTCH
      2. SOEGIPTCH
  • The scripts will add “_OOP” or “_INP” to the prefix and the date (MM-YY) to the patch plan name
  • Version of targets being patched (optional)
    • optional – may take out depending on patch selection criteria
  1. 2.0.4.7
  2. 1.0.2 (issue with PSU levels for 12c – based install process being used)
    1. OEM does not list correct PSU level for 12c databases
      à do to the way oracle homes are patched and then databases created – 12c issue

The EMCLI script names are:

  • “patch_rdbms.py”
    • this script does 11G or 12c RDBMS patching (only database)
    • this script has the parameters required and serves as an example can do inplace/outplace/emcli @patch_rdbms.py config_search inplace 24412235 SOEDBPTCH 11.2.0.4.160119
      /emcli @patch_rdbms.py config_search outofplace 24412235 SOEDBPTCH 11.2.0.4.160119
  • “patch_grid.py”
    • this script does the GI patching
    • there is a script called “rung” which I use to run the patch script
    • this script has the parameters required

/emcli @patch_grid.py config_search inplace       24412235 SOEGIPTCH
/emcli @patch_grid.py config_search outofplace 24412235 SOEGIPTCH

These scripts produce the text-based property files(seen earlier in this document) that serve as the patch plan input. You can view them in the same directory as the scripts (where they run from) and they are overwritten on each subsequent run so that they may be viewed form run to run or for testing. The scripts generate these files and then submits them to OEM via EMCLI verbs (remember, OEM automation is accomplished using EMCLI Verbs):

patch_grid.py

# script: patch_grid.py
#
# Used fro patching an GI
# Deployment parameters are speific to the deployment for in/out of place RDBMS home patching

from emcli import *
import xml.dom.minidom
import xml.dom.minidom
import sys
import os
import commands
import subprocess
import datetime
import time
import shutil
#from elementtree.ElementTree import ElementTree
from xml.etree import ElementTree as ET

# -------------------------------------------------

dbglevel=3

def log(linestr):
print linestr

def logdbg(linestr):
if dbglevel > 0:
print linestr

def logdbg2(linestr):
if dbglevel > 2:
print linestr

def print_info(res):
logdbg2(' -----------------------------------')
logdbg2(' Results from Target query')
logdbg2(' Number of targets:' + str(len(res.out()['data'])))
logdbg2(' EMCLI Errors :' + res.error())
logdbg2(' EMCLI Exit code :' + str(res.exit_code()))
logdbg2('IsJson :' + str(res.isJson()) )

def get_target_role_info (tgt_name):
l_sql0=""
long_sql = l_sql0
obj = list(sql=long_sql)
return obj

def showpatchplandetails(patch_plan_name):
os.system("./login ; ./emcli show_patch_plan -name=" + patch_plan_name + " -info > " + patch_plan_name + ".xml" )

def loaddict(dictobj,key,value,dictname):
logdbg2(" calling loaddict() add to dictionary--> " + dictname + " object... key-> " + key + " value --> " + value )
if key in dictobj:
logdbg2(" ->" + dictname + " #*** key (" + key + ") exists in " + dictname + " - compare data/append any new data values to existing values" )
existing = dictobj[key]
words = existing.split(";")
logdbg2(" ->" + dictname + " - (test) now testing new value against values in existing value sring (compare each word)" )
addnewvalue = "N"
for word in words:
logdbg2(" ->" + dictname + " - comparing word-> " + word + " to value-> " + value )
if value in word:
addnewvalue = "N"
continue
else:
addnewvalue = "Y"
if addnewvalue == "Y":
logdbg2(" ->" + dictname + " - adding new value to value string ")
dictobj[key] = existing + ";" + value
else:
print " *** key (" + key + ") exists in " + dictname + " - add new key/value entry "
dictobj[key] = value
return dictobj

def gettargetproperties():
# Get a target's property value (returns a string value for the poperty value)
# Return-> {'PROPERTY_VALUE': 'DB12102', 'PROPERTY_NAME': 'DBName'}
sql0="select t.target_name,t.target_type,t.host_name,p.property_name, p.property_value "
sql1="from sysman.mgmt$target t, sysman.mgmt$target_properties p "
sql2="where t.target_guid=p.target_guid "
sql3="and t.target_type IN ('oracle_database','oracle_home','host','has') "
sql4="and ( property_name IN ('AdrBase','AdrHome','CDB','CPUCount','DBDomain','DBName','DBVersion','DataGuardStatus') "
sql5=" or property_name IN ('InstanceName','MachineName','OpenMode','OracleHome','SID','Version','VersionCategory') "
sql6=" or property_name IN ('orcl_gtp_department','orcl_gtp_lifecycle_status','orcl_gtp_target_version','INSTALL_LOCATION') )"
sql7=" or property_name IN ('CRSVersion','CRSVersionCategory','isSiha','NodeName') ) "
#sql4="and property_name='" + prop_name + "'"
long_sql = sql0 + sql1 + sql2 + sql3 + sql4 + sql5 + sql6
logdbg2(" running gettargetproperties() ")
obj = list(sql=long_sql)
logdbg2(" running --> objreturn = list(sql=long_sql) ")
for objline in obj.out()['data']:
logdbg2(" objline-> " + str(objline) )
#retpval = obj['PROPERTY_VALUE']
#retpname = obj['PROPERTY_NAME']
#logdbg2(" gettargetpropertyvalue - retpval->'" + retpval + "' retpname->'" + retpname + "'" )
return obj

def gettargetpropertyvalue (tgt_type, tgt_name, prop_name):
# Get a target's property value
# Return-> {'PROPERTY_VALUE': 'DB12102', 'PROPERTY_NAME': 'DBName'}
#sql0="select t.target_name,t.target_type,t.host_name,p.property_name, p.property_value "
sql0="select p.property_name, p.property_value "
sql1="from sysman.mgmt$target t, sysman.mgmt$target_properties p "
sql2="where t.target_name='" + tgt_name + "' and t.target_guid=p.target_guid "
sql3="and t.target_type='" + tgt_type + "' and property_name='" + prop_name + "'"
long_sql = sql0 + sql1 + sql2 + sql3
logdbg(" running (gettargetpropertyvalue) with type=" + tgt_type + " target=" + tgt_name + " property=" + prop_name )
objreturn = list(sql=long_sql)
logdbg(" ran (gettargetpropertyvalue) returning obj result to calling stateement")
logdbg(" ran (gettargetpropertyvalue) objreturn is type --> " + str(type(objreturn)) )
retpval=""
retpname=""
for obj in objreturn.out()['data']:
retpval = obj['PROPERTY_VALUE']
retpname = obj['PROPERTY_NAME']
logdbg(" gettargetpropertyvalue - retpval->'" + retpval + "' retpname->'" + retpname + "'" )
#return obj
return str(retpval)

def printdict (dobj,name):
cnt=0
logdbg2( " " + name + " **** printing all key-values in dict obj->'" + name + "'")
for key,value in sorted( dobj.iteritems() ):
cnt += 1
cnt2=0
logdbg2( " " + name + "#" + str(cnt) + " = key->'" + key + "' value->'" + value + "'")
logdbg2( " " + name + "#" + str(cnt) + " value->'" + value + "'")
# split the text in 'value'
kwords = key.split(";")
for word in kwords:
cnt2 += 1
logdbg2( " " + name + " -> keysplit#" + str(cnt2) + " -->'" + word + "'")
vwords = value.split(";")
# for each word in the string
for word in vwords:
cnt2 += 1
logdbg2( " " + name + " -> valsplit#" + str(cnt2) + " -->'" + word + "'")
logdbg( " " + name + "\n")

def xloaddict (dobj,key,value):
# Load a dict object
if key in dobj:
logdbg(" *** key (" + key + ") exists in dictionary - append new data to existing value")
existing = dobj[key]
dobj[key] = existing + ";" + value
else:
logdbg( " *** key (" + hostskey + ") exists in dictionary - add new entry with value ")
dobj[key] = value

def parsexml_file(xmlfile):
root = ET.parse(xmlfile)
#root = ET.parse("patchplan.xml").getroot()
#root = ET.parse(xmlfile).getroot()

#Create an iterator
iter = root.getiterator()

# Now Iterate thru XML DOM object
for element in iter:
#First the element tag name
logdbg2( "Element:" + element.tag )
#Next the attributes (available on the instance itself using the Python dictionary protocol
if element.keys():
logdbg2( "\tAttributes:" )
for name, value in element.items():
logdbg2( "\t\tName: '%s', Value: '%s'" %(name, value) )
#Next the child elements and text
logdbg2( "\tChildren:" )
#Text that precedes all child elements (may be None)
if element.text:
text = element.text
text = len(text) > 40 and text[:40] + "..." or text
logdbg2( "\t\tText:" + repr(text) )
if element.getchildren():
#Can also use: "for child in element.getchildren():"
#for child in element:
for child in element.getchildren():
#Child element tag name
logdbg2( "\t\tElement" + child.tag )
#The "tail" on each child element consists of the text
#that comes after it in the parent element content, but
#before its next sibling.
if child.tail:
text = child.tail
text = len(text) > 40 and text[:40] + "..." or text
logdbg2( "\t\tText:" + repr(text) )

def parsexml_string(xmlstr):
root = ET.fromstring(xmlstr)
#root = ET.parse(xmlfile)
#root = ET.parse(xmlfile).getroot()

#Create an iterator
iter = root.getiterator()

# Now Iterate thru XML DOM object
for element in iter:
#First the element tag name
print "Element:", element.tag
#Next the attributes (available on the instance itself using the Python dictionary protocol
if element.keys():
print "\tAttributes:"
for name, value in element.items():
print "\t\tName: '%s', Value: '%s'"%(name, value)
#Next the child elements and text
print "\tChildren:"
#Text that precedes all child elements (may be None)
if element.text:
text = element.text
text = len(text) > 40 and text[:40] + "..." or text
print "\t\tText:", repr(text)
if element.getchildren():
#Can also use: "for child in element.getchildren():"
#for child in element:
for child in element.getchildren():
#Child element tag name
print "\t\tElement", child.tag
#The "tail" on each child element consists of the text
#that comes after it in the parent element content, but
#before its next sibling.
if child.tail:
text = child.tail
text = len(text) > 40 and text[:40] + "..." or text
print "\t\tText:", repr(text)


# ----------------------------------------
# -------- start of Processing -----------
# ----------------------------------------

# Get command line argument list:
# 0) script name to be run
# 1) target list selection type (config_search or group)
# 2) deployment method (inplace or outofplace)
# 3) Patch list (comma separateed)
# 4) PatchPlan Prefix
# 5) PatchPlan Prefix
# 6) Version of platform
# 7) EMD staging directory --> emd_emstagedir


#Set the OMS URL to connect to
set_client_property('EMCLI_OMS_URL','https://dbadeeds.com:7803/em')
set_client_property('EMCLI_TRUSTALL','true')
#Login to the OMS
#login(username='nars',password='Welcome1',force=True)
login(username='SYSMAN',password='Welcome1',force=True)

print '**** Now running emcli_config_search......'
print "Setting variables to be used"

# Command line Args (sys.argv[0] is the script name
targetlistseltype="None"
deploymenttype = "None"
patchlist = "None"
planPrefix="ApplyPatch_"
numberofpatches=0
version_search="None"
emd_emstagedir="/db_backup/oracle/stage"

logdbg( "length of sys.argv[] is -->" + str(len(sys.argv)))

if sys.argv[0] is not None:
targetlistseltype=sys.argv[0]
else:
targetlistseltype="None"

if sys.argv[1] is not None:
deploymenttype = sys.argv[1]
else:
deploymenttype = "OutOfPlace"

if sys.argv[2] is not None:
patchlist = sys.argv[2]
else:
patchlist = "99999900011"

if sys.argv[3] is not None:
planPrefix=sys.argv[3] + "_"
else:
planPrefix="ApplyPatch_"

if sys.argv[4] is not None:
version_search=sys.argv[4]

#patchName=patchlist

print "\nCommand line arguments passed....."
print " --> targetlistseltype=" + targetlistseltype
print " --> deploymenttype=" + deploymenttype
print " --> patchlist=" + str(patchlist)
print " --> planPrefix=" + planPrefix
print " --> version_search=" + version_search

patchlist=patchlist.split(",")
numberofpatches = len(patchlist)
logdbg2 (" patchlist has --> " + str(numberofpatches) + " patches in it")

if numberofpatches > 1:
ptchcnt=0
logdbg2(" patchlist has more than one patch in it...list each patch - numberofpatches -> " + str(numberofpatches) )
for ptch in patchlist:
ptchcnt += 1
logdbg2 ( " patch#" + str(ptchcnt) + " ->'" + ptch + "'")
else:
logdbg(" patchlist has only one patch in it...list each patch - numberofpatches ->" + str(numberofpatches) )
logdbg(" patchlist-->'" + str(patchlist) + "'")


# Arrays used in processing
patch_id = []
release_id = []
platform_id = []
language_id = []
target_type = []

# ----------------------------------------
# -------- Start of Processing -----------
# ----------------------------------------

# Patch searching (if needed)
# ---------------------------

# Search patches for patch details (platform, release_id, pathc_id, language)
#patch_array = search_patches(patch_name=patchName,product="9480",platform="226",type="patch")
#search_patches(patch_name=patchName,product="9480",platform="226",type="patch")
logdbg("Searching for patches in MOS...will search for each patch one at a time-->" + str(patchlist) )

for patchinlist in patchlist:
xmlvalue="xml"
logdbg(" pulling details for patch --> " + patchinlist)
#patch_array = search_patches(patch_name=patchName,product="9480",platform="226",type="patch")
#search_patches(patch_name=patchinlist,platform="226",language="0",'xml')
#search_patches(patch_name=patchinlist,platform='226',language='0')
#print search_patches(patch_name=patchlist,platform='226',language='0')
logdbg(" running OS command (./emcli search_patches) to get patch XML info ")
logdbg(" patch XML file (contains patch details) is --> " + patchinlist + ".xml")
patchretval=os.system("./login ; ./emcli search_patches -patch_name=" + patchinlist + " -platform=226 -language=0 -xml > " + patchinlist + ".xml")
logdbg2(" patchretval --> " + str(patchretval))
#emcli search_patches -patch_name=6880880 -platform=226 -language=0 -xml
#xmlvar="xml"

logdbg2(" finished getting patch details (XML) from Oracle, check file-->" + patchinlist + ".xml")


# Get Sample Patch Metadata (from patch in a plan already)
# -------------------------------------------
#print str(show_patch_plan(name='').out())
#print "Getting Patch plan details"
#pp_xml = show_patch_plan(name=patch_template_name).out()

# Parse plan metadata into XML
# ------------------------------

#print "Parse the patch plan XML"
#patchPlan = xml.dom.minidom.parseString(pp_xml)

# Retrieve metadata for each patch in the sample patch plan
# ----------------------------------------------------------

#print "Retrieve Patch information in the patch tempoate"
#for patchList in patchPlan.getElementsByTagName("patchList"):
# print "Patch list in plan --> " + str(patchList)
# for patch in patchList.getElementsByTagName("patch"):
# patch_id.append(patch.getElementsByTagName("id")[0].toxml().replace("","").replace("",""))
# release_id.append(patch.getElementsByTagName("release_id")[0].toxml().replace("","").replace("",""))
# platform_id.append(patch.getElementsByTagName("platform_id")[0].toxml().replace("","").replace("",""))
# language_id.append(patch.getElementsByTagName("language_id")[0].toxml().replace("","").replace("",""))
# target_type.append(patch.getElementsByTagName("target_type")[0].toxml().replace("","").replace("",""))

# Now we need a target list list (from a config search or other get_targets commands)
#
# Run stored configuration search to get list of databases missing the patch
# Target list must include target_name, host_name and Oracle_home (or get them based on target_name)


print "Run get_targets with a preconfigured configuration search get list of targets"

# Target selection Config_Search

#targets_array = get_targets(config_search='11.2.0.3_SI_DBs_patch_14275605').out()['data']
#targets_array = get_targets(config_search='Test_Config_Search_1').out()['data']
#targets_array = get_targets(target="DG%").out()['data']
#targets_array = get_targets().out()['data']
#targets_array = run_config_search(search_name="TestConfigSearch").out()['data']

# SQL Search - pull all properties or all target types
# nars01

#sql1 = "select t.target_name,t.target_type, t.type_qualifier3, t.type_qualifier4, t.host_name, p.property_name, p.property_value "
#sql2 = "from sysman.mgmt$target t, sysman.mgmt$target_properties p where t.target_guid = p.target_guid and t.target_type IN ('oracle_home','has') "
#sql3 = "and host_name NOT LIKE 'omspr%' order by host_name,target_type,target_name"
#sql4 = ""

sql1 = "select t.target_name,t.target_type, t.type_qualifier3, t.type_qualifier4, t.host_name, p.property_name, p.property_value "
sql2 = " from sysman.mgmt$target t, sysman.mgmt$target_properties p where t.target_guid = p.target_guid and t.target_type IN ('oracle_database','oracle_home','has') "
sql3 = " and host_name LIKE 'soedblcm%' and host_name NOT LIKE 'xxxomrprod%' "
sql4 = " and ( p.property_name IN ('OracleHome','CRSVersion','orcl_gtp_target_version','INSTALL_LOCATION','HOME_TYPE','ORACLE_BASE','INVENTORY') "
sql5 = " OR p.property_name IN ('Version','SID','DBName','DBVersion','DataGuardStatus','InstanceName','OpenMode','MachineName') ) "
sql6 = " order by host_name,target_type,target_name,property_name "

#select distinct t.target_name,t.target_type, t.type_qualifier3, t.type_qualifier4, t.host_name, p.property_name, p.property_value
#from sysman.mgmt$target t, sysman.mgmt$target_properties p
#where t.target_guid = p.target_guid
#and t.target_type in ('has','oracle_database','oracle_home','oracle_dbsys','oracle_listener')
#and host_name like '%%'
#-- and property_name like 'DBV%'
#order by target_name, target_type, property_name;

#sql1 = "select distinct t.target_name,t.target_type, t.type_qualifier3, t.type_qualifier4, t.host_name, p.property_name, p.property_value "
#sql2 = " from sysman.mgmt$target t, sysman.mgmt$target_properties p "
#sql3 = " where t.target_guid = p.target_guid and t.target_type in ('has','oracle_database','oracle_home','oracle_dbsys','oracle_listener') "
#sql4 = " and ( p.property_name IN ('OracleHome','CRSVersion','orcl_gtp_target_version','INSTALL_LOCATION','HOME_TYPE','ORACLE_BASE','INVENTORY') "
#sql5 = " OR p.property_name IN ('Version','SID','DBName','DBVersion','DataGuardStatus','InstanceName','OpenMode','MachineName') ) "
#sql6 = " order by host_name,target_type,target_name,property_name "

longsql = sql1 + sql2 + sql3 + sql4 + sql5 + sql6
logdbg( " longsql -->\n")
logdbg( longsql )
print " *** Now get target list and info via -list with sql"
targets_array = list(sql=longsql)


dbsql1 = "select t.target_name,t.target_type, t.type_qualifier3, t.type_qualifier4, t.host_name, p.property_name, p.property_value "
dbsql2 = " from sysman.mgmt$target t, sysman.mgmt$target_properties p where t.target_guid = p.target_guid and t.target_type IN ('oracle_home','has') "
dbsql3 = " and host_name LIKE 'soedb%' and host_name NOT LIKE 'xxxomrprod%' "
dbsql4 = " and ( p.property_name IN ('OracleHome','CRSVersion','orcl_gtp_target_version','INSTALL_LOCATION','HOME_TYPE','ORACLE_BASE','INVENTORY') "
dbsql5 = " OR p.property_name IN ('Version','SID','DBName','DBVersion','DataGuardStatus','InstanceName','OpenMode','MachineName') ) "
dbsql6 = " order by host_name,target_type,target_name,property_name "

#logdbg(" *** now get databases")
#dblongsql = dbsql1 + dbsql2 + dbsql3 + dbsql4 + dbsql5 + dbsql6
#logdbg( " dblongsql -->\n")
#logdbg( dblongsql )
print " *** Now get target list and info via -list with sql"
#dbs_array = list(sql=longsql)

# Process output from config_search and load into two dictionaries for sorting
# Need to group targets by host/Oracle_home
qcnt=0
hcnt=0
tcnt=0
pcnt=0

vcnt=0
lcnt=0

hdict={}
tdict={}
odict={}
ohdict={}
ghdict={}
pdict={}
dbdict={}
propdict={}
dblist=[]
patchplanlist=[]

# NARS2
print "Loop through target list to build dictonary objects from data pulled from OEM"

for targets in targets_array.out()['data']:
qcnt += 1
vcnt += 1
logdbg( "\n--targetline (#" + str(qcnt) + ") -->'" + str(targets) + "'\n" )
tname = str(targets['TARGET_NAME'])
ttype = str(targets['TARGET_TYPE'])
thost = str(targets['HOST_NAME'])
tpname = str(targets['PROPERTY_NAME'])
topath = str(targets['PROPERTY_NAME'])
tpvalue = str(targets['PROPERTY_VALUE'])
logdbg( "\n#" + str(qcnt) + " - processing(new target) tname-> " + tname + " target_type='" + ttype + " - key data elements below")
logdbg( " --> tname =" + tname)
logdbg( " --> ttype =" + ttype)
logdbg( " --> thost =" + thost )
logdbg( " --> tpname =" + tpname)
logdbg( " --> tpvalue=" + tpvalue)

hvalue = tname
tvalue = tname + ";" + thost

# Set Dictionary Keys
hostskey = str(thost)
targetskey = str(thost) + ";" + str(ttype)
ohkey = str(thost) + ";" + str(ttype) + ";" + str(tpname)
propkey = str(thost) + ";" + str(ttype) + ";" + tname + ";" + str(tpname)
dbkey = str(thost) + ";oracle_database;" + str(tname)

hvalue = str(ttype)
tvalue = str(tname)
ovalue = str(tpvalue)
pvalue = str(tpvalue)
dbvalue = str(tvalue) + ";" + str(pvalue)

logdbg2( " --> hostskey ='" + hostskey + "'")
logdbg2( " --> targetskey='" + targetskey + "'")
logdbg2( " --> propkey ='" + tpname + "'")
logdbg2( " --> dbkey ='" + dbkey + "'")
logdbg2( " --> hvalue='" + hvalue + "'")
logdbg2( " --> tvalue='" + tvalue + "'")
logdbg2( " --> pvalue='" + pvalue + "'")
logdbg2( " --> tpname='" + tpname + "'")
logdbg2( " --> tpvalue='" + tpvalue + "'")
logdbg2( " --> dbvalue='" + dbvalue + "'")

logdbg2( " length of hdict{} --> " + str(len(hdict)))
logdbg2( " length of tdict{} --> " + str(len(tdict)))
logdbg2( " length of pdict{} --> " + str(len(pdict)))
logdbg2( " length of odict{} --> " + str(len(odict)))

# Load host dictionary (hdict)
# ---------------------------------------------

if hostskey in hdict:
logdbg2( " *** key (" + hostskey + ") exists in hict - append new data (hvalue='" + hvalue + "') to existing values")
existing = hdict[hostskey]
logdbg2( " existing-> " + str(existing))
# split the value string
words = existing.split(";")
logdbg2( " length of (words) array ()--> " + str(len(words)) + " existing legnth-->'" + str(len(existing)) + "'")
tmpcnt1=0
# for each word in the string
needtoappend = 0
for word in words:
tmpcnt1 += 1
#if hvalue == word:
if hvalue == word:
logdbg2( " **** #" + str(tmpcnt1) + " hvalue('" + hvalue + "') equals word('" + word + "') - skip appending")
needtoappend = 0
else:
needtoappend = 1
logdbg2( " **** #" + str(tmpcnt1) + " word('" + word + "') not equal hvalue('" + hvalue + "') - adding key to tmpdict")
logdbg2( " **** #" + str(tmpcnt1) + " existing->'" + existing )
if needtoappend == 1:
hdict[hostskey] = existing + ";" + hvalue
logdbg2(" Now print out keys in tmpdict")
else:
logdbg2(" *** keymissing (" + hostskey + ") does not exists in hdict - add entry-->'" + hvalue + "'")
hdict[hostskey] = hvalue

# Load oracle_home dictionary (odict)
# --------------------------------------------------------
if ( ttype == "oracle_home" and tpname == "INSTALL_LOCATION" ):
logdbg2(" -- *** including this row in 'odict')")
# redo key to include physical oracle_home path
ohkey = str(thost) + ";" + str(ttype) + ";" + str(tpvalue)
ovalue = str(tpname) + ";" + str(tpvalue)

if ohkey in odict:
logdbg2( " *** key (" + ohkey + ") exists in hict - append new data (ovalue='" + ovalue + "') to existing values")
existing = odict[ohkey]
logdbg2( " existing-> " + str(existing))
# split the value string
words = existing.split(";")
logdbg2( " length of (words) array ()--> " + str(len(words)) + " existing legnth-->'" + str(len(existing)) + "'")
tmpcnt1=0
# for each word in the string
needtoappend = 0
for word in words:
tmpcnt1 += 1
#if ovalue == word:
if ovalue == word:
logdbg2( " **** #" + str(tmpcnt1) + " ovalue('" + ovalue + "') equals word('" + word + "') - skip appending")
needtoappend = 0
else:
needtoappend = 1
logdbg2( " **** #" + str(tmpcnt1) + " word('" + word + "') not equal ovalue('" + ovalue + "') - adding key to tmpdict")
logdbg2( " **** #" + str(tmpcnt1) + " existing->'" + existing )
if needtoappend == 1:
odict[ohkey] = existing + ";" + ovalue
logdbg2(" Now print out keys in tmpdict")
else:
logdbg2(" *** keymissing (" + ohkey + ") does not exists in odict - add entry-->'" + ovalue + "'")
odict[ohkey] = ovalue

# Load target dictionary (ohdict)
# --------------------------------------------------------
ohkey = str(thost) + ";" + str(tpvalue)
ohvalue = str(tname)

if ohkey in ohdict:
logdbg( " *** key (" + ohkey + ") exists in ohdict - append new data (ohvalue='" + ohvalue + "') to existing values")
existing = ohdict[ohkey]
logdbg( " existing-> " + str(existing))
# split the value string
words = existing.split(";")
logdbg( " length of (words) array ()--> " + str(len(words)) + " existing legnth-->'" + str(len(existing)) + "'")
tmpcnt1=0
# for each word in the string
needtoappend = 0
for word in words:
tmpcnt1 += 1
#if ohvalue == word:
if ohvalue == word:
logdbg( " **** #" + str(tmpcnt1) + " ohvalue('" + ohvalue + "') equals word('" + word + "') - skip appending")
needtoappend = 0
else:
needtoappend = 1
logdbg( " **** #" + str(tmpcnt1) + " word('" + word + "') not equal ohvalue('" + ohvalue + "') - adding key to tmpdict")
logdbg( " **** #" + str(tmpcnt1) + " existing->'" + existing )
if needtoappend == 1:
ohdict[ohkey] = existing + ";" + ohvalue
logdbg(" Now print out keys in tmpdict")
else:
logdbg(" *** keymissing (" + ohkey + ") does not exists in ohdict - add entry-->'" + ohvalue + "'")
ohdict[ohkey] = ohvalue

else:
dummy1=2

# Load target dictionary (tdict)
# ---------------------------------------------------

if targetskey in tdict:
logdbg( " *** key (" + targetskey + ") exists in tdict - append new data (tvalue='" + tvalue + "') to existing values")
existing = tdict[targetskey]
logdbg( " existing-> " + str(existing))
# split the value string
words = existing.split(";")
logdbg( " length of (words) array ()--> " + str(len(words)) + " existing legnth-->'" + str(len(existing)) + "'")
tmpcnt1=0
# for each word in the string
needtoappend = 0
for word in words:
tmpcnt1 += 1
#if tvalue == word:
if tvalue == word:
logdbg( " **** #" + str(tmpcnt1) + " tvalue('" + tvalue + "') equals word('" + word + "') - skip appending")
needtoappend = 0
else:
needtoappend = 1
logdbg( " **** #" + str(tmpcnt1) + " word('" + word + "') not equal tvalue('" + tvalue + "') - adding key to tmpdict")
logdbg( " **** #" + str(tmpcnt1) + " existing->'" + existing )
if needtoappend == 1:
tdict[targetskey] = existing + ";" + tvalue
logdbg(" Now print out keys in tmpdict")
else:
logdbg(" *** keymissing (" + targetskey + ") does not exists in tdict - add entry-->'" + tvalue + "'")
tdict[targetskey] = tvalue

# Load props dictionary (pdict)
# --------------------------------------------------------

if propkey in pdict:
logdbg( " *** key (" + propkey + ") exists in pdict - append new data (pvalue='" + pvalue + "') to existing values")
existing = pdict[propkey]
logdbg( " existing-> " + str(existing))
# split the value string
words = existing.split(";")
logdbg( " length of (words) array ()--> " + str(len(words)) + " existing legnth-->'" + str(len(existing)) + "'")
tmpcnt1=0
# for each word in the string
needtoappend = 0
for word in words:
tmpcnt1 += 1
#if pvalue == word:
if pvalue == word:
logdbg( " **** #" + str(tmpcnt1) + " pvalue('" + pvalue + "') equals word('" + word + "') - skip appending")
needtoappend = 0
else:
needtoappend = 1
logdbg( " **** #" + str(tmpcnt1) + " word('" + word + "') not equal pvalue('" + pvalue + "') - adding key to tmpdict")
logdbg( " **** #" + str(tmpcnt1) + " existing->'" + existing )
if needtoappend == 1:
pdict[propkey] = existing + ";" + pvalue
logdbg(" Now print out keys in tmpdict")
else:
logdbg(" *** keymissing (" + propkey + ") does exists in pdict - add entry-->'" + pvalue + "'")
pdict[propkey] = pvalue

# Load props dictionary (propdict)
# --------------------------------------------------------

logdbg(" *** add new entry to 'propdict' - properties obj for all target by --> ttype;tname;propname = propvalue")
propkey = str(ttype) + ";" + str(tname )+ ";" + str(tpname)
propvalue = str(tpvalue)
logdbg(" adding propkey-> " + propkey + " propvalue-> " + propvalue)
propdict[propkey] = propvalue

# Load props dictionary (dbdict)
# --------------------------------------------------------

if ttype == "oracle_database":
dictname="dbdict"
logdbg(" dbkey--> " + dbkey)
logdbg(" dbvalue--> " + dbvalue)
if dbkey in dbdict:
logdbg( " *** key (" + dbkey + ") exists in dbdict - append new data (dbvalue='" + dbvalue + "') to existing values")
existing = dbdict[dbkey]
logdbg( " existing-> " + str(existing))
# split the value string
words = existing.split(";")
logdbg( " length of (words) array ()--> " + str(len(words)) + " existing legnth-->'" + str(len(existing)) + "'")
tmpcnt1=0
# for each word in the string
needtoappend = 0
for word in words:
tmpcnt1 += 1
#if pvalue == word:
if dbvalue == word:
logdbg( " **** #" + str(tmpcnt1) + " dbvalue('" + dbvalue + "') equals word('" + word + "') - skip appending")
needtoappend = 0
else:
needtoappend = 1
logdbg( " **** #" + str(tmpcnt1) + " word('" + word + "') not equal dbvalue('" + dbvalue + "') - adding key to dbdict")
logdbg( " **** #" + str(tmpcnt1) + " existing->'" + existing )
if needtoappend == 1:
dbdict[dbkey] = existing + ";" + dbvalue
logdbg(" added new data to existing data for value string")
else:
logdbg(" *** keymissing (" + dbkey + ") does not exists in dbdict - add entry-->'" + dbvalue + "'")
dbdict[dbkey] = dbvalue
else:
#logdbg(" skipping adding to dbdict, not an 'oracle_database' target ")
dummy=99

logdbg("\n *********************************************\n")
logdbg("\n now print out dictionary key-values from each\n\n")
logdbg("\n length of hdict{} --> " + str(len(hdict)) )
logdbg("\n length of odict{} --> " + str(len(odict)) )
logdbg("\n length of ohdict{} --> " + str(len(ohdict)) )
logdbg("\n length of tdict{} --> " + str(len(tdict)) )
logdbg("\n length of pdict{} --> " + str(len(pdict)) )
logdbg("\n length of dbdict{} --> " + str(len(dbdict)) )
logdbg("\n length of propdict{} --> " + str(len(propdict)) )
logdbg("\n ************************\n\n")

printdict(propdict,"propdictline")
printdict(dbdict,"dbdictline")
printdict(hdict,"hdictline")
printdict(odict,"odictline")
printdict(ohdict,"ohdictline")
printdict(tdict,"tdictline")
printdict(pdict,"pdict")
print "\n ************************\n\n"

# -----------------------------------------------------
# Now that we have a target list and built the dictionaries to use,
# create the patch_plan: Patch plans are based on target type (oracle_database vs has)
# and whether deployment is In-Place or Out-Of-Place

print "\n *****************************************\n"
print "\n ******* Building Patch Plan(s) ********"

cnt=0
nodeCount = 0
inp_cnt = 0
oop_cnt = 0
#Date
timenow2 = datetime.datetime.now()
#now2=timenow2.strftime("%m-%d-%y_%H:%M")
now2=timenow2.strftime("%Y-%m-%d %H:%M")
now3=timenow2.strftime("%m_%d_%Y")
newfilename="dummy.txt"
f = open(newfilename, mode='w')

print "creating new patch plan properties file (deployment--> " + deploymenttype

if ( deploymenttype == "inplace"):
planName = planPrefix + "INP_" + str(now3)
newfilename = planName
logdbg("deployment type is--> " + deploymenttype + " planName--> " + planName )
logdbg("opening file ('" + newfilename + "') and will write to this property file")
logdbg("adding all patches (patchplanlist) to properties file--> " + newfilename)
patchplanlist.append(str(newfilename))
tcnt=0
for singleplan in patchplanlist:
tcnt += 1
logdbg(" #" + str(tcnt) + " patchplanlist--> " + singleplan)
#f = open('patchplan.txt', mode='w')
f = open(newfilename, mode='w')
# write plan header
f.write("name=" + planName + "\n")
f.write("description=" + planName + " - " + deploymenttype + "\n")
f.write("deployment_date=" + str(now2) + "\n")
f.write("planPrivilegeList=NARS:ADMIN:FULL;SANDEEP NARANI:ADMIN:FULL" + "\n")
f.write("\n")
else:
dummy0=0
planName = planPrefix + "NOT_SET"

print "***Loop through host list and build patch plan file(s) for InPlace / OutOfPlace"
retval=0

try:

# For each host that is a HAS target create a patch element for each patch for each host
# New patch file for each DB - when doing OutOfPlace
# --------------------------------------------------------
logdbg(" --> looping through all targets in 'hdict' to add to patch plan" )

gdb_target=""
fqdn = ""
hostname = ""
finalcnt=0
oraHomeNames=""
GIPathOrig=""

# Series of Loops through hosts, patchlist and DB list
# Loop through hosts
# loop through pathclist
# loop through DB list

for key,value in sorted(hdict.iteritems()):
dblist=[]
logdbg ( " #" + str(cnt) + " = key->'" + key + "'")
logdbg ( " #" + str(cnt) + " value->'" + value + "'" )
cnt += 1
tmpcnt=0
fqdn = str(key)
hostnameparts = key.split(".")
hostnameonlypart = hostnameparts[0]
print " Processing new host-> " + key + " hostnameonly-> " + hostnameonlypart + " - adding to patch plan"
logdbg2(" dblist-> " + str(dblist) )
logdbg2(" fqdn-> " + str(fqdn) )
logdbg2("hostnameonlypart-->'" + hostnameonlypart + " to be used in planName - one for each host")
logdbg2(" hostnameparts-> " + str(hostnameparts) )
logdbg2(" hostnameonlypart-> " + str(hostnameonlypart) )
# if outofplae - each host must be in separate platch plan
print "creating new patch plan properties file"
if ( deploymenttype == "outofplace"):
planName = planPrefix + "OOP_" + str(now3) + "_" + hostnameonlypart
hostnameparts=key.split(".")
hostnameonly=hostnameparts[0]
#newfilename = "gi" + deploymenttype + hostnameonly
newfilename = planName
logdbg (" creating a new patchplan file to add to (patchplanlist)--> " + newfilename)
#patchplanlist.append(str(newfilename))
patchplanlist.append(str(planName))
for singleplan in patchplanlist:
logdbg(" patchplanlist--> " + singleplan)
print "opeing file and startint to write to the properties files"
#f = open('patchplan.txt', mode='w')
f = open(newfilename, mode='w')
# write plan header
f.write("name=" + planName + "\n")
f.write("description=Test GI Patch Plan - Per Node" + "\n")
f.write("deployment_date=" + str(now2) + "\n")
f.write("planPrivilegeList=NARS:ADMIN:FULL;SANDEEP NARANI:ADMIN:FULL" + "\n")
f.write("\n")
else:
dummy0=0

logdbg (" (patchloop)looping through all patches to be applied")
finalcnt = 0
for patchName in patchlist:
tmpcnt += 1
print " patchlist (loop) host(cnt)#" + str(cnt) + " - patch#" + str(tmpcnt)
if deploymenttype == "inplace":
# write info for each target in target list
f.write( "# (hdict & patchlist loop) new key->'" + key + "' - - start of new HAS host" + "\n" )
f.write( "patch." + str(inp_cnt) + ".patch_id=" + str(patchName) + "\n")
f.write( "patch." + str(inp_cnt) + ".release_id=600000000009300\n")
f.write( "patch." + str(inp_cnt) + ".platform_id=226\n")
f.write( "patch." + str(inp_cnt) + ".language_id=0\n")
f.write( "patch." + str(inp_cnt) + ".target_name=has_" + str(key) + "\n")
f.write( "patch." + str(inp_cnt) + ".target_type=has\n")
f.write( "\n")
nodeCount += 1
inp_cnt += 1
else:
# write info for each target in target list
#f.write( "# (hdict & patchlist loop) new key->'" + key + "' - - start of new HAS host" + "\n" )
f.write( "patch." + str(finalcnt) + ".patch_id=" + str(patchName) + "\n")
f.write( "patch." + str(finalcnt) + ".release_id=600000000009300\n")
f.write( "patch." + str(finalcnt) + ".platform_id=226\n")
f.write( "patch." + str(finalcnt) + ".language_id=0\n")
f.write( "patch." + str(finalcnt) + ".target_name=has_" + str(key) + "\n")
f.write( "patch." + str(finalcnt) + ".target_type=has\n")
f.write( "\n")
nodeCount += 1
finalcnt += 1
oop_cnt += 1
logdbg2(" counters used for planName->" + planName + " host->" + fqdn )
logdbg2(" nodeCount--> " + str(nodeCount) )
logdbg2(" finalcnt--> " + str(finalcnt) )
logdbg2(" oop_cnt--> " + str(oop_cnt) )
logdbg2(" inp_cnt--> " + str(inp_cnt) )

logdbg (" now add any databases afected by GI patch to patch list - key-->'" + key + "'")
# Now add each database affected by patchon this node (each database along with HAS)
# Check the key against the hostname
cnt3=0
for key2,value2 in sorted(dbdict.iteritems()):

logdbg ( "\n")
logdbg ( " #" + str(cnt3) + " key2->'" + key2 + "'" + " host(cnt)#" + str(cnt) + " patch#" + str(tmpcnt) )
key2parts = key2.split(";")
keycompare = str(key2parts[0])
db_target = str(key2parts[2])
logdbg(" key2parts --> " + str(key2parts) )
#logdbg(" key2parts[0] --> " + str(key2parts[0]) + " db_target->'" + db_target + "'")
logdbg(" key2parts[0] --> " + str(key2parts[0]) + " db_target->'" + db_target + "'")
#logdbg(" splitting value string into parts....")
logdbg(" get a target property value.....")
retpropval=gettargetpropertyvalue("oracle_database",db_target,"DBName")
db_target_oh=gettargetpropertyvalue("oracle_database",db_target,"OracleHome")
#for val1 in retpropval.out()['data']:
# print " val1 --> " + str(val1)
logdbg(" val1 retpropval -->'" + str(retpropval) + "'" )
logdbg(" val1 db_target_oh -->'" + str(db_target_oh) + "'" )
cnt2=0
vwords = value2.split(";")
#for value in vwords:
# logdbg( " valuesplit#" + str(cnt2) + " --> '" + value + "'")
# cnt2 += 1
logdbg2(" get the DBVersion for the DB to ensure it is correct version")
dbversion = vwords[17]
dbversion_short = dbversion[0:7]
logdbg(" dbversion is --> " + dbversion + " comparing to version_search='" + version_search + "'")
logdbg(" dbversion_short is --> " + dbversion_short )
if str(keycompare) == str(key):
logdbg(" comparing hnostname --> keycommpare='" + keycompare + " to key='" + key + "'")
if dbversion_short in version_search:
logdbg(" dbversion and hostname match....add to patch plan")
logdbg(" host(cnt)#" + str(cnt) + " - patch#" + str(tmpcnt) )
gdb_target = db_target
logdbg(" db_target->'" + db_target + "' gdb_target->'" + gdb_target + "'" )
if deploymenttype == "inplace":
# write info for each target in target list
#f.write( "# (dbdict loop)newkey->'" + key + "' keycompare->'" + keycompare + "' dbversion_short-> '" + dbversion_short + "'" )
#f.write( "\n")
#f.write( "patch." + str(inp_cnt) + ".patch_id=" + str(patchName) + "\n")
#f.write( "patch." + str(inp_cnt) + ".release_id=600000000009300\n")
#f.write( "patch." + str(inp_cnt) + ".platform_id=226\n")
#f.write( "patch." + str(inp_cnt) + ".language_id=0\n")
#f.write( "patch." + str(inp_cnt) + ".target_name=" + str(db_target) + "\n")
#f.write( "patch." + str(inp_cnt) + ".target_type=oracle_database\n")
#f.write( "\n")
nodeCount += 1
inp_cnt += 1
else:
# write info for each target in target list
#f.write( "# (dbdict loop) new key->'" + key + "' keycompare->'" + keycompare + "' dbversion_short-> '" + dbversion_short + "'" )
#f.write( "\n")
#f.write( "patch." + str(finalcnt) + ".patch_id=" + str(patchName) + "\n")
#f.write( "patch." + str(finalcnt) + ".release_id=600000000009300\n")
#f.write( "patch." + str(finalcnt) + ".platform_id=226\n")
#f.write( "patch." + str(finalcnt) + ".language_id=0\n")
#f.write( "patch." + str(finalcnt) + ".target_name=" + str(db_target) + "\n")
#f.write( "patch." + str(finalcnt) + ".target_type=oracle_database\n")
#f.write( "\n")
finalcnt += 1
oop_cnt += 1

logdbg2(" keep array (dblist) with all DBs on this host - adding-->'" + gdb_target + "'")
logdbg2(" (dblist) adding new element (right DB version) -- >'" + gdb_target + "' on host-->'" + key + "'")
if gdb_target in dblist:
logdbg2(" ---> (dblist) element=(" + gdb_target + ") already exists in dblist")
else:
logdbg2(" ---> (dblist) appending new element(" + gdb_target + ") to dblist[]")
dblist.append(str(gdb_target))
logdbg2(" (dblist) arraylist now has--> " + str(len(dblist)) + " elements in it ")
nodeCount += 1
else:
logdbg( " skipping due to DB version not matching.... " + dbversion + " != " + version_search)
else:
logdbg(" key2parts[0]-->'" + str(key2parts[0]) + "' ...skipping...not on host -->'" + str(key) + "'" )
cnt3 += 1
logdbg (" ...done processing (dbdict) and adding all DBs affected by patch on this host")
dbdict_loop_end=0
logdbg (" ...done processing all patchs in patchlist - adding all DBs affected by patch on this host")
patchlist_loop_end=0
logdbg (" ...done processing all patchs in patchlist - adding all DBs affected by patch on this host")
#if deploymenttype == "inplace":
patchlist_loop_end=0

# Add rest of deployment parameter (for out of place here)
if deploymenttype == "outofplace":
#f.write("\n")
#f.write("deploymentOptions.StageLocation=%emd_emstagedir%" + "\n")
f.write("deploymentOptions.StageLocation=" + emd_emstagedir + "\n")
f.write("deploymentOptions.StagePatches=true" + "\n")
f.write("deploymentOptions.isStageLocationShared=false" + "\n")
f.write("deploymentOptions.notify.enabled=true" + "\n")
f.write("deploymentOptions.performAruAnalysis=true" + "\n")
#f.write("deploymentOptions.DISPATCHER_LOC=%emd_emstagedir%" + "\n")
f.write("deploymentOptions.DISPATCHER_LOC=" + emd_emstagedir + "\n")
#f.write("deploymentOptions.ROOT_SCRIPTS_LOC=" + emd_emstagedir + "/SESSION-1482188928807/rootScripts" + "\n")
# Add Creds after creating plan
#f.write("deploymentOptions.DummyCredentialsOHLess=/u01/app/12.1.0.2/grid;HomeCreds_Normal;40D129D2D86470AFE0536E61160A31B8;/u01/app/12.1.0.2/grid;HomeCreds_Priv;3FDAF3EEEB52C01EE0536E61160AFB12")
f.write("deploymentOptions.DummyCredentialsOHLess=/u01/app/12.1.0.2/grid;HostCredsNormal;40D129D2D86470AFE0536E61160A31B8" + "\n")
f.write("deploymentOptions.deploymentProcedure=PATCH_SIHAOOP_12:oracle:true" + "\n")
f.write("deploymentOptions.howToPatchGIRAC.how_to_patch=OutOfPlace" + "\n" )
f.write("deploymentOptions.howToPatchGIRAC.patch_mode=rolling" + "\n")

logdbg(" *** Now write oracle_home specific deployment options to the patch plan file ")
logdbg(" now process all keys in hdict{} --> " + str(len(hdict)) )
#logdbg(" (loop) through dbdict again for all homes affected by GI patch - NARS")
#print " #" + str(cnt4) + " = key->'" + str(key) + "' value->'" + str(value) + "'"
# kwords = key.split(";")
# print " kwords[0] --> " + kwords[0]
# #print " kwords[1] --> " + kwords[1]
ohpathkey=key + ";has;has_" + str(key) + ";OracleHome"
logdbg(" --> key --> " + key)
logdbg(" --> ohpathkey--> " + ohpathkey )
logdbg (" --> now check OracleHome ('" + str(ohpathkey) + "') in pdict{}")
if ohpathkey in pdict:
ohpathvalue = pdict[ohpathkey]
logdbg(" key(" + ohpathkey + ") found in pdict->" + str(key) + " ohpathkey (to lookup SiHIA for has target)--> " + str(ohpathkey) + " Sihia value->" + str(ohpathvalue) )
logdbg(" ")
#f.write("# ----- (each Oracle home)" + "\n")
f.write("deploymentOptions.howToPatchGIRAC.gi_home.source.oh=" + str(ohpathvalue) + "\n")

logdbg2(" ohpathvalue ---> " + str(ohpathvalue) )
ohname=ohdict[key + ";" + str(ohpathvalue)]
ohpathparts = ohpathvalue.split("_")
logdbg2(" --> ohname--> " + ohpathvalue )
logdbg2(" --> ohpathvalue--> " + ohname )
logdbg2( " ohpathparts --> " + str(ohpathparts) )
logdbg2( " ohpathparts[0] --> " + str(ohpathparts[0]) )
pathparts = ohpathvalue.split("/")
logdbg2( " length of pathparts array --> " + str(len(pathparts)) )
logdbg2( " pathparts array --> " + str(pathparts) )
pathpartslength = len(pathparts)
newidx = int(pathpartslength) - 1
logdbg2( " pathpartslength --> " + str(pathpartslength) + " newidx --> " + str(newidx) )
#print " pathpartslength[" + str(len(pathparts) "] --> " + pathparts[pathpartslength]
lastpart = pathparts[newidx]
ohlastpart = lastpart.split("_")
logdbg2( " lastpart arry --> " + str(lastpart) )
logdbg2( " length of lastpart --> " + str(len(lastpart)) )
logdbg2( " length of ohlastpart--> " + str(len(ohlastpart)) )
logdbg2( " ohlastpart ary --> " + str(ohlastpart) )
logdbg2( " now split ohlastpart into more pieces --> " + str(ohlastpart) )
newohpath=""
if len(ohlastpart) == 1:
logdbg(" (if stmt) there is no '_' in the lat part of the path name")
lastname = ohlastpart[0]
newohpath = ohpathvalue + "_1"
logdbg(" newohpath --> " + newohpath)
else:
logdbg2(" (else stmt) need to increment ohpath value - ohlastpart[1] --> " + str(ohlastpart[1]) )
logdbg2(" (else stmt) need to increment ohpath value - ohlastpart[1] --> " + str(ohlastpart[1]) )
#lastvalue = ohlastpart[1]
#logdbg( " lastname--> " + lastname)
#logdbg( " lastvalue--> " + lastvalue)
newhomevalue = int(ohlastpart[1]) + 1
#newhome = "grid" + "_" + str(newhomevalue)
#newohpath = ohlastpart[0] + "_" + str(newhomevalue)
newohpath = str(ohpathparts[0]) + "_" + str(newhomevalue)
logdbg( " newhomevalue--> " + str(newhomevalue) + " newohpath--> " + newohpath)

fullhostname = str(key)
nodenameparts = fullhostname.split(".")
logdbg(" nodenameparts[0] --> " + str(nodenameparts[0]) )
# Get oracle_home target_name from "ohdict" obj
tohnamekey = fqdn + ";" + str(ohpathvalue)
GIPathOrg = str(ohpathvalue)
tohname = ohdict[tohnamekey]
tohname_short = tohname.split("_")
oraHomeNames = str(tohname)
logdbg2(" got oracle_home (or GI) target name - tohnamekey-> " + tohnamekey + " - tohname->" + tohname )
logdbg2(" got oracle_home (or GI) target name - oraHomeNames--> " + str(oraHomeNames) )
logdbg2(" got oracle_home (or GI) target name - tohname_short-> " + str(tohname_short[0]) )

f.write("deploymentOptions.howToPatchGIRAC.gi_home.source.name=" + str(tohname_short[0]) + "\n")
f.write("deploymentOptions.howToPatchGIRAC.gi_home.destination.oh=" + str(newohpath) + "\n")
f.write("deploymentOptions.howToPatchGIRAC.gi_home.destination.name=" + "\n")
#f.write("deploymentOptions.howToPatchGIRAC.gi_home.patch_migrate=true" + "\n")
else:
logdbg(" key->" + str(key) + " ohpathkey (no SiHIA defined for has target)--> " + str(ohpathkey) + " Sihia value->" + str(ohpathvalue) + "...skipping" )

logdbg(" ")
logdbg(" *** processing node --> " + key + " - specific deployment options to the patch plan file - NARS4")

# now loop through all database homes affected (or Databases affected)
logdbg(" *** now loop through all database in (dblist) and find the home affected (or Databases affected) ")
logdbg(" dblist is--> " + str(len(dblist)) + " elements in it")
for dbitem in dblist:
logdbg(" dblist-->" + str(dbitem) )
#
sidcnt=1
cnt4=1
# dblist is an aray
for idb in dblist:
logdbg2(" now write out sidb_home entires to propetties file")
logdbg2(" counters used for sidb_home) for planName->" + planName + " host->" + fqdn )
logdbg2(" nodeCount--> " + str(nodeCount) )
logdbg2(" finalcnt--> " + str(finalcnt) )
logdbg2(" oop_cnt--> " + str(oop_cnt) )
logdbg2(" inp_cnt--> " + str(inp_cnt) )
logdbg2(" cnt4--> " + str(cnt4) )
logdbg2(" sidcnt--> " + str(sidcnt) )
# needs to be a loop around all DBs on this host
logdbg2(" (dblist loop) --> processing dblist (new entry) --> " + idb)
#db_target_oh = gettargetpropertyvalue("oracle_database",gdb_target,"OracleHome")
logdbg2(" (dblist loop) --> getting OracleHome by calling gettargetpropertyvalue ")
db_target_oh = gettargetpropertyvalue("oracle_database",idb,"OracleHome")
logdbg(" (dblist loop) add each affected home to patch plan - per node")
logdbg(" (dblist loop) add each affected home to patch plan - per node")
logdbg(" (dblist loop) howToPatchGIRAC.sidb_home.......section")

# Get oracle_home target_name from "ohdict" obj
tohnamekey = fqdn + ";" + db_target_oh
tohname = ohdict[tohnamekey]
tohname_short = tohname.split("_")
logdbg2(" got oracle_home (RDBMS) target name - tohnamekey-> " + tohnamekey + " - tohname->" + str(tohname) )
logdbg2(" got oracle_home (RDBMS) target name - tohname_short-> " + str(tohname_short) )
logdbg2(" write out sidb_home entries with correct index values")
# testing --> set counters to zero to try to exclude DBs selected
cnt4=0
sidcnt=0
#f.write("deploymentOptions.howToPatchGIRAC.sidb_home." + str(cnt4) + ".source.oh=" + db_target_oh + "\n")
#f.write("deploymentOptions.howToPatchGIRAC.sidb_home." + str(cnt4) + ".source.name=" + str(tohname_short[0]) + "\n")
#f.write("deploymentOptions.howToPatchGIRAC.sidb_home." + str(cnt4) + ".sidb_database." + str(sidcnt) + ".name=" + str(idb) + "\n")
#f.write("deploymentOptions.howToPatchGIRAC.sidb_home." + str(cnt4) + ".sidb_database." + str(sidcnt) + ".patch_migrate=false" + "\n")
#f.write("deploymentOptions.howToPatchGIRAC.sidb_home." + str(cnt4) + ".sidb_database." + str(sidcnt) + ".rendered=true" + "\n")
#f.write("deploymentOptions.howToPatchGIRAC.sidb_home." + str(cnt4) + ".sidb_database." + str(sidcnt) + ".selection_enabled=false" + "\n")
#f.write("\n")
sidcnt += 1
cnt4 += 1
print " now write patch plan footer properties -- > deployments is (deploymenttype=" + deploymenttype + ")"

if deploymenttype == "outofplace":
f.write("deploymentOptions.isDispatcherEnabled=true" + "\n")
f.write("deploymentOptions.isDispatcherLocShared=false" + "\n")
f.write("deploymentOptions.isPatchTargetEditable=true" + "\n")
f.write("deploymentOptions.oraHomeNames=" + oraHomeNames + "\n")
#f.write("deploymentOptions.DummyCredentialsOHLess=" + GIPathOrg + ";HomeCreds_Normal;40D129D2D86470AFE0536E61160A31B8")
#f.write("deploymentOptions.DummyCredentialsOHLess=/u01/app/12.1.0.2/grid;HostCredsNormal;40D129D2D86470AFE0536E61160A31B8" + "\n")
#f.write(";" + GIPathOrg + ";HomeCreds_Priv;3FDAF3EEEB52C01EE0536E61160AFB12" + "\n")
f.close()
logdbg (" ...done processing all hosts in (hdict) and adding to patch plan")
oop_cnt = 0
hdict_loop_end=0

#if deploymenttype == "inplace":
# f.write("deploymentOptions.isDispatcherEnabled=true" + "\n")
# f.write("deploymentOptions.isDispatcherLocShared=false" + "\n")
# f.write("deploymentOptions.isPatchTargetEditable=true" + "\n")

# Now write global deployment options (inplace - consilidated file)
# ------------------------------------------------------
logdbg(" Now write global deployment options to patch plan")

# Based on Deployment type (write different deployment options)
if deploymenttype == "inplace":
logdbg2(" finish writing global deployment options for deploymenttype --> " + deploymenttype)
f.write("\n")
f.write("deploymentOptions.AdvancedOPatchOptions=null" + "\n")
#f.write("deploymentOptions.StageLocation=%emd_emstagedir%" + "\n")
#f.write("deploymentOptions.StageLocation=/db_backup/oracle/stage" + "\n")
f.write("deploymentOptions.StageLocation=" + emd_emstagedir + "\n")
f.write("deploymentOptions.StagePatches=true" + "\n")
f.write("deploymentOptions.isStageLocationShared=false" + "\n")
f.write("deploymentOptions.notify.enabled=true" + "\n")
f.write("deploymentOptions.performAruAnalysis=true" + "\n")
#f.write("deploymentOptions.DISPATCHER_LOC=%emd_emstagedir%" + "\n")
f.write("deploymentOptions.DISPATCHER_LOC=" + emd_emstagedir + "\n")
#f.write("deploymentOptions.deploymentProcedure=PATCH_SIAHAIP_12:oracle:true" + "\n")
logdbg2( " deployments is (deploymenttype=" + deploymenttype + ")" )
f.write("deploymentOptions.deploymentProcedure=PATCH_RESTART_DB12:oracle:true" + "\n")
f.write("deploymentOptions.isDispatcherEnabled=true" + "\n")
f.write("deploymentOptions.isDispatcherLocShared=false" + "\n")
# Close Patch Plan file
logdbg2(" closing the patch plan file for deploymenttype-->" + deploymenttype)
logdbg2 (" finish writing footer to patch plan")
f.close()

# --------------------------------------------------------------------------------------------
# now call the OEM commands to create patch plan and submit patch plan (analyze, preare, deploy)
# -------------------------------------------------------------------------------------------

logdbg("\n ******************************************************")
logdbg(" now call the OEM commands to create patch plan(s) and submit patch plan(s)--> analyze,prepare,deploy)")
logdbg(" ******************************************************")

# Need to cycle through patchplanlist for all patch plans to be submittde

logdbg(" show all available patch plans (in patchplanlist) to be built.....")
for singleplan in patchplanlist:
logdbg(" patchplanlist --> '" + singleplan + "'")


logdbg( " now determine deployment type being used --> " + deploymenttype )

if deploymenttype == "inplace":
# steps for in place
logdbg2(" deploymenttype --> " + deploymenttype )

inputfileinfo="data:" + planName
print "creating a new plan in OEM (" + deploymenttype + ") with this patch planName --> " + planName
print " --> OEM inputfileinfo --> " + inputfileinfo + " for patch planName --> " + planName
logdbg2( " submitting using inputfileinfo --> " + inputfileinfo )

# Create the Patch Plan in OEM by calling EMCLI verb
#retval = create_patch_plan(name=planName, input_file=inputfileinfo,impact_other_targets='add_original_only')
retval = create_patch_plan(name=planName, input_file=inputfileinfo,impact_other_targets='add_all')
logdbg( " *** retval (create_patch_plan) --> " + str(retval) )
print " called --> create_patch_plan(name=" + planName + ", input_file=" + inputfileinfo + ",impact_other_targets='add_all')"

# List patch plan status
logdbg(" get list of all patch plans in OEM and loop through them, deploymenttype --> " + deploymenttype)
# List patch plan status
logdbg (" run -->list_patch_plans(name=" + planName + ")" )
logdbg (" all patch plans created in OEM")
#print list_patch_plans()
print list_patch_plans(name=planName)

# Show patch plan drtails / status
#logdbg(" get list of all patch plans in OEM and loop through them, deploymenttype --> " + deploymenttype)
#showpatchplans = show_patch_plan()

logdbg("\n *************** now suubmiting patch plan data (again after create) *******************\n")

# Set Patch plan data (plan has been created, override defaults with same plan) (this is needed, does not work unless you update the plan data with the same info)
# When create_patch_plan is called OEM overwrites
logdbg(" now set the patch plan parameters again - not sure why needed but is required)")
print " set_patch_plan_data(name=planName,input_file='data:patchplan-rdbms-outofplace.txt',impact_other_targets='add_all')"
retval = set_patch_plan_data(name=planName,input_file=inputfileinfo,impact_other_targets='add_all')
logdbg2( " *** retval (set_path_plan_data) --> " + str(retval) )

# Show patch plan drtails / status
logdbg(" run--> ./emcli show_patch_plan -name='" + planName + "' -info")
#print show_patch_plan(name=planName,'info')
#os.system("./login ; ./emcli show_patch_plan -name=" + planName + " -info > " + planName + ".xml" )
showpatchplandetails(planName)
logdbg2(" show_patch_plan --> " + planName)
logdbg2( show_patch_plan(name=planName) )

logdbg("\n *************** now analyzing patch plans *******************\n")

# Analyze patch plan (tell OEM to run analyze)
print "analyzing patch plan (" + planName + ") for execution (deployment--> " + deploymenttype + ")"
logdbg(" submit_patch_plan(name=" + planName + ",action='analyze')" )
retval = submit_patch_plan(name=planName,action="analyze")
print " *** retval (submit_patch) --> " + str(retval)

# Show patch plan drtails / status - get XML output and parse
logdbg(" run--> ./emcli show_patch_plan -name='" + planName + "' -info")
#print show_patch_plan(name=planName,'info')
#print show_patch_plan(name=planName)

# Loop until analyze complete and then "deploy"
#


else:
# steps for out of place
logdbg2( " deploymenttype --> " + deploymenttype )
logdbg2( " neee to cycle through (patchplanlist) to create each patch plan ")

for singlepatchplan in patchplanlist:
logdbg(" now processing the final patchplanlist (singlepatchplan) entry --> " + singlepatchplan)
planName = singlepatchplan
logdbg2(" patchplanlist (element) --> " + singlepatchplan + " planName --> " + planName)
# copy patch plan file to new name
#os.system("cat " + singlepatchplan)
#os.system('cp ' + singlepatchplan + ' testgipatchplan_oop.txt')
#testfilename = "NARS1"
basefilename = "/db_backup/emcli/gipatchplanoop"
copyfilename = "/db_backup/emcli/" + singlepatchplan
#copyfilename = "testfile1"
#logdbg(" now copy-->'" + copyfilename + "' to -->'" + basefilename + "'")
#shutil.copy (copyfilename,testfilename)
#if os.path.isfile (basefilename): print " file copy Success"
#logdbg(" now run testcopy test script")
#os.system('/db_backup/emcli/testcopy ' + copyfilename + ' ' + basefilename )
#logdbg(" now open file-->'" + copyfilename + "' and read all lines and write to file-->'" + basefilename + "'")
#f1 = open(copyfilename, mode='r')
#f2 = open(basefilename, mode='w')
#Lines=f1.readlines()
#for line in Lines:
# #logdbg(" writing to f2-> " + str(line) )
# f2.write(line)
#f1.close()
#f2.close()

# Create Patch plan using OEM "create_patch_plan" Verb
inputfileinfo="data:" + singlepatchplan
logdbg2(" now call create_patch_plan using new inputfileinfo---> " + inputfileinfo )
#retval = create_patch_plan(name=planName, input_file="data:" + singlepatchplan,impact_other_targets='add_original_only')
retval = create_patch_plan(name=planName, input_file=inputfileinfo,impact_other_targets='add_all')
logdbg2( " *** retval (create_patch_plan) --> " + str(retval) )
print " called --> create_patch_plan(name=" + planName + ", input_file=" + inputfileinfo + ",impact_other_targets='add_all')"

# List patch plan status
logdbg2 (" run -->list_patch_plans(name=" + planName + ")" )
logdbg2 (" all patch plans created in OEM")
logdbg2( list_patch_plans() )
print list_patch_plans(name=planName)

# Show patch plan drtails / status
logdbg(" get list of all patch plans in OEM and loop through them, deploymenttype --> " + deploymenttype)
#showpatchplans = show_patch_plan()

# Set Patch plan data (plan has been created, override defaults with same plan)
logdbg(" now set the patch plan parameters again - not sure why needed but is required)")
logdbg2( "retval = set_patch_plan_data(name=planName,input_file=inputfileinfo,impact_other_targets='add_all') ")
retval = set_patch_plan_data(name=planName,input_file=inputfileinfo,impact_other_targets='add_all')
logdbg2(" *** retval (set_path_plan_data) --> " + str(retval) )

# Show patch plan drtails / status
logdbg2(" run--> ./emcli show_patch_plan -name='" + planName + "' -info")
#print show_patch_plan(name=planName,'info')
#os.system("./login ; ./emcli show_patch_plan -name=" + planName + " -info > " + planName + ".xml" )
showpatchplandetails(planName)
#print show_patch_plan(name=planName)

logdbg("\n *************** now analyzing patch plans *******************\n")

# Analyze patch plan (tell OEM to run analyze)
print "analyzing patch plan--> (" + planName + ") for execution (deployment)"
logdbg(" submit_patch_plan(name=" + planName + ",action='analyze')" )
retval = submit_patch_plan(name=planName,action="analyze")
logdbg2( " *** retval (submit_patch) --> " + str(retval) )

# Show patch plan drtails / status - get XML output and parse
#print show_patch_plan(name=planName)
# Show patch plan drtails / status
logdbg2(" run--> ./emcli show_patch_plan -name='" + planName + "' -info")
#print show_patch_plan(name=planName,'info')
#print show_patch_plan(name=planName)

#print "Getting Patch plan details"
#pp_xml = show_patch_plan(name=patch_template_name).out()

# Parse plan metadata into XML
# ------------------------------
#print "Parse the patch plan XML"
#patchPlan = xml.dom.minidom.parseString(pp_xml)

# Retrieve metadata for each patch in the sample patch plan
# ----------------------------------------------------------

#print "Retrieve Patch information in the patch tempoate"
#for patchList in patchPlan.getElementsByTagName("patchList"):
# print "Patch list in plan --> " + str(patchList)
# for patch in patchList.getElementsByTagName("patch"):
# patch_id.append(patch.getElementsByTagName("id")[0].toxml().replace("","").replace("",""))


logdbg("\n ******* done creating patch plans for ll in patchplanlist *******************\n")
logdbg("\n ******* submitted patch plan for analyze (submit_patch_plan -name=?? -action=analyze *******\n")
# NARS5

# List patch plans status
logdbg2 ("\n run -->list_patch_plans(name=" + planName + ")" )
#print list_patch_plans()
print list_patch_plans(name=planName)

# Now we must loop to wait until analyze phase has run and is successful
logdbg("\n ** Now go into aloop to check plan status, once analyze is successful, patch plan can be deployed")

loopforever = 0
whileloopcnt = 0

while loopforever < 1: whileloopcnt += 1 logdbg2(" (loop) looping and pulling patch plan status --> " + planName + " - until successful or failed whileloopcnt-->" + str(whileloopcnt) )
# get xml status file
showpatchplandetails(planName)
# load xml and parse xml into DOM object
# find status element and check value
logdbg2(" opening XML status file--> " + planName + ".xml - to get patch plan status information")
xmlfilename = planName + ".xml"
parsexml_file(xmlfilename)

# Get plan_status
#
# 86F601C81F3FB8C93A250AE3B3F29098
# SOEGIPTCH_OOP_soedblcm27
# PATCH
# Test GI Patch Plan - Per Node
# 
# 
# 1
# NEVER
# CONFLICT_FREE
# Thu Dec 15 09:43:31 CST 2016
# 1481816611000
# SYSMAN
# Thu Dec 15 09:43:35 CST 2016
# 1481816615000
# SYSMAN
# yes
# FULL
# N
# Database Instance 12.1.0.2.0 (Linux x86-64) 
# 
# 
#

logdbg2 ("\n Now run show_patch_plan -name=planName and save output ")
cmdtoexe="./login ; ./emcli show_patch_plan -name=" + planName + " | grep -i plan_status"
logdbg2(" cmdtoexe-> " + cmdtoexe )
#showplan_retval = os.system("./login ; ./emcli show_patch_plan -name=" + planName + " | grep -i plan_status" )
#showplan_retval = subprocess.check_output(cmdtoexe, shell=True)
status, showplan_retval = commands.getstatusoutput(str(cmdtoexe))
logdbg2(" ---> showplan_retval--> " + str(showplan_retval) )

# List Patch plan details
logdbg2 ("\n run -->list_patch_plans(name=" + planName + ")")
print str( list_patch_plans(name=planName) )

# if success - deploy

# if failed - stop
#logdbg ("deploying patch plan (" + planName + ") for execution (deployment)" )
#logdbg2("submit_patch_plan(name=" + planName + ",action='deploy')" )
#submit_patch_plan(name=planName,action='deploy')
#retval = submit_patch_plan(name=planName,action="deploy")
#print "submit_patch_plan retval--> " + str(retval)
if whileloopcnt > 4:
logdbg2(" (loop) looping ----> end while loop (whileloopcnt --> " + str(whileloopcnt) )
loopforever = 1

except:
print "Unexpected error: ", sys.exc_info()[1]

exit()

patch_rdbms.py

# script: patch_rdbms.py
#
# Used fro patching an RDBMS home
# Deployment parameters are speific to the deployment for in/out of place RDBMS home patching

from emcli import *
import xml.dom.minidom
import xml.dom.minidom
import sys
import os
import datetime
import time
#from elementtree.ElementTree import ElementTree
from xml.etree import ElementTree as ET

dbglevel=3

def log(linestr):
print linestr

def logdbg(linestr):
if dbglevel > 0:
print linestr

def logdbg2(linestr):
if dbglevel > 2:
print linestr

def print_target_details(target):
logdbg("TargetName=" + target['Target Name'] + " TargetType=" + target['Target Type'])

def showpatchplandetails(patch_plan_name):
os.system("./login ; ./emcli show_patch_plan -name=" + patch_plan_name + " -info > " + patch_plan_name + ".xml" )

def print_info(res):
logdbg2(' -----------------------------------')
logdbg2(' Results from Target query')
logdbg2(' Number of targets:' + str(len(res.out()['data'])))
logdbg2(' EMCLI Errors :' + res.error())
logdbg2(' EMCLI Exit code :' + str(res.exit_code()))
logdbg2('IsJson :' + str(res.isJson()) )

def get_target_role_info (tgt_name):
l_sql1=""
long_sql = l_sql1
obj = list(sql=long_sql)
return obj

def display_plan_info (planname):
logdbg("\n")
logdbg( str(list_patch_plans(name=planname)) )
logdbg("\n")

def format(str):
if str is None:
return ""
return str

def loaddict(dictobj,key,value,dictname):
logdbg2(" calling loaddict() add to dictionary--> " + dictname + " object... key-> " + key + " value --> " + value )
if key in dictobj:
logdbg2(" *** key (" + key + ") exists in " + dictname + " - append new data to existing values" )
existing = dictobj[key]
dictobj[key] = existing + ";" + value
else:
print " *** key (" + key + ") exists in " + dictname + " - add new key/value entry "
dictobj[key] = value
return dictobj

def gettargetproperties():
# Get a target's property value (returns a string value for the poperty value)
# Return-> {'PROPERTY_VALUE': 'DB12102', 'PROPERTY_NAME': 'DBName'}
sql0="select t.target_name,t.target_type,t.host_name,p.property_name, p.property_value "
sql1="from sysman.mgmt$target t, sysman.mgmt$target_properties p "
sql2="where t.target_guid=p.target_guid "
sql3="and t.target_type IN ('oracle_database','oracle_home','host','has') "
sql4="and ( property_name IN ('AdrBase','AdrHome','CDB','CPUCount','DBDomain','DBName','DBVersion','DataGuardStatus') "
sql5=" or property_name IN ('InstanceName','MachineName','OpenMode','OracleHome','SID','Version','VersionCategory') "
sql6=" or property_name IN ('orcl_gtp_department','orcl_gtp_lifecycle_status','orcl_gtp_target_version','INSTALL_LOCATION') )"
sql7=" or property_name IN ('CRSVersion','CRSVersionCategory','isSiha','NodeName') ) "
#sql4="and property_name='" + prop_name + "'"
long_sql = sql0 + sql1 + sql2 + sql3 + sql4 + sql5 + sql6
logdbg2(" running gettargetproperties() ")
obj = list(sql=long_sql)
logdbg2(" running --> objreturn = list(sql=long_sql) ")
for objline in obj.out()['data']:
logdbg2(" objline-> " + str(objline) )
#retpval = obj['PROPERTY_VALUE']
#retpname = obj['PROPERTY_NAME']
#logdbg2(" gettargetpropertyvalue - retpval->'" + retpval + "' retpname->'" + retpname + "'" )
return obj

def gettargetpropertyvalue (tgt_type, tgt_name, prop_name):
# Get a target's property value (returns a string value for the poperty value)
# Return-> {'PROPERTY_VALUE': 'DB12102', 'PROPERTY_NAME': 'DBName'}
#sql0="select t.target_name,t.target_type,t.host_name,p.property_name, p.property_value "
sql0="select p.property_name, p.property_value "
sql1="from sysman.mgmt$target t, sysman.mgmt$target_properties p "
sql2="where t.target_name='" + tgt_name + "' and t.target_guid=p.target_guid "
sql3="and t.target_type='" + tgt_type + "' and property_name='" + prop_name + "'"
long_sql = sql0 + sql1 + sql2 + sql3
logdbg2(" running (gettargetpropertyvalue) with type=" + tgt_type + " target=" + tgt_name + " property=" + prop_name )
objreturn = list(sql=long_sql)
logdbg2(" ran (gettargetpropertyvalue) returning obj result to calling stateement")
logdbg2(" ran (gettargetpropertyvalue) objreturn is type --> " + str(type(objreturn)) )
retpval=""
retpname=""
for obj in objreturn.out()['data']:
retpval = obj['PROPERTY_VALUE']
retpname = obj['PROPERTY_NAME']
logdbg2(" gettargetpropertyvalue - retpval->'" + retpval + "' retpname->'" + retpname + "'" )
#return obj
return str(retpval)

def printdict (dobj,name):
cnt=0
logdbg2( " **** printing all key-values in dictionary->'" + name + "'" )
for key,value in sorted( dobj.iteritems() ):
cnt += 1
cnt2=0
logdbg2( " #" + str(cnt) + " = key->'" + key + "' value->'" + value + "'" )
# split the text in 'value'
kwords = key.split(";")
for word in kwords:
cnt2 += 1
logdbg2( " keysplit#" + str(cnt2) + " -->'" + word + "'" )
vwords = value.split(";")
# for each word in the string
for word in vwords:
cnt2 += 1
logdbg2( " valsplit#" + str(cnt2) + " -->'" + word + "'" )
logdbg2( "\n" )

def parsexml_file(xmlfile):
root = ET.parse(xmlfile)
#root = ET.parse("patchplan.xml").getroot()
#root = ET.parse(xmlfile).getroot()

#Create an iterator
iter = root.getiterator()

# Now Iterate thru XML DOM object
for element in iter:
#First the element tag name
logdbg2( "Element:" + element.tag )
#Next the attributes (available on the instance itself using the Python dictionary protocol
if element.keys():
logdbg2( "\tAttributes:" )
for name, value in element.items():
print "\t\tName: '%s' , Value: '%s'"%(name, value)
#Next the child elements and text
logdbg2( "\tChildren:" )
#Text that precedes all child elements (may be None)
if element.text:
text = element.text
text = len(text) > 40 and text[:40] + "..." or text
logdbg2( "\t\tText:" + repr(text) )
if element.getchildren():
#Can also use: "for child in element.getchildren():"
#for child in element:
for child in element.getchildren():
#Child element tag name
logdbg2( "\t\tElement" + child.tag )
#The "tail" on each child element consists of the text
#that comes after it in the parent element content, but
#before its next sibling.
if child.tail:
text = child.tail
text = len(text) > 40 and text[:40] + "..." or text
logdbg2( "\t\tText:" + repr(text) )

def parsexml_string(xmlstr):
root = ET.fromstring(xmlstr)
#root = ET.parse(xmlfile)
#root = ET.parse(xmlfile).getroot()

#Create an iterator
iter = root.getiterator()

# Now Iterate thru XML DOM object
for element in iter:
#First the element tag name
print "Element:", element.tag
#Next the attributes (available on the instance itself using the Python dictionary protocol
if element.keys():
print "\tAttributes:"
for name, value in element.items():
print "\t\tName: '%s', Value: '%s'"%(name, value)
#Next the child elements and text
print "\tChildren:"
#Text that precedes all child elements (may be None)
if element.text:
text = element.text
text = len(text) > 40 and text[:40] + "..." or text
print "\t\tText:", repr(text)
if element.getchildren():
#Can also use: "for child in element.getchildren():"
#for child in element:
for child in element.getchildren():
#Child element tag name
print "\t\tElement", child.tag
#The "tail" on each child element consists of the text
#that comes after it in the parent element content, but
#before its next sibling.
if child.tail:
text = child.tail
text = len(text) > 40 and text[:40] + "..." or text
print "\t\tText:", repr(text)

# ----------------------------------------
# -------- Start of Processing -----------
# ----------------------------------------
#
# Get command line argument list:
# 1) target list selection type (config_search or group)
# 2) deployment method (inplace or outofplace)
# 3) Patch list (comma separateed)
# 4) PatchPlan Prefix
# 5) Version of RDBMS to patch (runs config search on this version)

#Set the OMS URL to connect to
set_client_property('EMCLI_OMS_URL','https://dbadeeds.com:7803/em')
set_client_property('EMCLI_TRUSTALL','true')
#Login to the OMS
login(username='SYSMAN',password='Welcome1',force=True)

print '\n**** Now running emcli_config_search......'
print "Setting variables to be used"

# Variables
SleepTime=20

# Command line Args (sys.argv[0] is the script name
targetlistseltype="None"
deploymenttype = "None"
patchlist = "None"
planPrefix="ApplyPatch_"
version_search="None"
version_category="None"
releaseid="None"

logdbg ( "length of sys.argv[] is -->" + str(len(sys.argv)) )

if sys.argv[0] is not None:
targetlistseltype=sys.argv[0]
else:
targetlistseltype="None"

if sys.argv[1] is not None:
deploymenttype = sys.argv[1]
else:
deploymenttype = "OutOfPlace"

if sys.argv[2] is not None:
patchlist = sys.argv[2]
else:
patchlist = "99999900011"

if sys.argv[3] is not None:
planPrefix=sys.argv[3] + "_"
else:
planPrefix="Ptch_"

if sys.argv[4] is not None:
version_search=sys.argv[4]

patchName=patchlist
print "\nCommand line arguments passed....."
print "targetlistseltype=" + targetlistseltype
print "deploymenttype=" + deploymenttype
print "patchlist=" + patchlist
print "planPrefix=" + planPrefix
print "patchName=" + patchName

if "12.1.0.2" in version_search:
releaseid="600000000009300"
version_category="12cR1"
logdbg( " version search is--> " + version_search + " - set releasse_id to 12c --> " + releaseid)

if "11.2.0.4" in version_search:
releaseid="80112040"
version_category="11gR2"
logdbg( " version search is--> " + version_search + " - set releasse_id to 11g --> " + releaseid )

patchlist=patchlist.split(",")
numberofpatches = len(patchlist)
logdbg2 (" patchlist (passed as command line arg--> " + str(numberofpatches) + " patches in it")

if numberofpatches > 1:
ptchcnt=0
logdbg2(" patchlist has more than one patch in it...list each patch - numberofpatches -> " + str(numberofpatches) )
for ptch in patchlist:
ptchcnt += 1
logdbg2 ( " patch#" + str(ptchcnt) + " ->'" + ptch + "'")
else:
logdbg(" patchlist has only one patch in it...list each patch - numberofpatches ->" + str(numberofpatches) )
logdbg(" patchlist-->'" + str(patchlist) + "'")

# Varables (Sequences/Arrays) used in processing
logdbg(" Create data structures to be used in processing")
patch_id = []
release_id = []
platform_id = []
language_id = []
target_type = []

# ----------------------------------------
# -------- Start of Processing -----------
# ----------------------------------------

# Patch searching (if needed)
# ---------------------------

# Search patches for patch details (platform, release_id, pathc_id, language)
#patch_array = search_patches(patch_name=patchName,product="9480",platform="226",type="patch")
#search_patches(patch_name=patchName,product="9480",platform="226",type="patch")
logdbg("Searching for patches in MOS...will search for each patch one at a time-->" + str(patchlist) )
for patchinlist in patchlist:
patchName = str(patchinlist)
xmlvalue="xml"
logdbg(" pulling details for patch (from patchlist)--> " + patchinlist + " patchName-> " + patchName)
patch_array = search_patches(patch_name=patchName,platform="226",language="0")
logdbg(" patch_array --> " + str(patch_array) )
#search_patches(patch_name=patchinlist,platform="226",language="0",'xml')
#search_patches(patch_name=patchinlist)
#search_patches(patch_name=patchinlist,platform='226',language='0')
logdbg(" running OS command to search for patches to get XML - issue with using -xml in Verb mode")
#os.system("./login ; ./emcli search_patches -patch_name=" + patchinlist + " -platform=226 -language=0 -xml | tee searchpatchptmp.xml" )
os.system("./login ; ./emcli search_patches -patch_name=" + patchinlist + " -platform=226 -language=0 -xml | tee " + patchinlist + ".xml" )

# set releaseid --> patch release_id
#
logdbg (" searching MOS for patch info for patches--> " + str(patchlist) )
# emcli search_patches -patch_name=6880880 -platform=226 -language=0 -xml
#logdbg("\n running search_patches(patch_name=patchlist,platform='226',language='0','xml') ")
#search_patches(patch_name=patchlist,platform="226",language="0")
#patchresults = search_patches(patch_name=patchinlist,platform="226",language="0")
logdbg(" now call 'parsexml_file()' ")
#parsexml_string(patch_array)
patchdetailsfilename = patchinlist + ".xml"
parsexml_file(patchdetailsfilename)

# Get Sample Patch Metadata (from patch in a plan already)

#print str(show_patch_plan(name='').out())
print "Getting Patch plan details as XML"
#pp_xml = show_patch_plan(name=patch_template_name).out()

# Parse plan metadata into XML

print "Parse the patch plan XML"
#patchPlan = xml.dom.minidom.parseString(pp_xml)

# Retrieve metadata for each patch in the sample patch plan

print "Retrieve Patch information in the patch tempoate"
#for patchList in patchPlan.getElementsByTagName("patchList"):
# print "Patch list in plan --> " + str(patchList)
# for patch in patchList.getElementsByTagName("patch"):
# patch_id.append(patch.getElementsByTagName("id")[0].toxml().replace("","").replace("",""))
# release_id.append(patch.getElementsByTagName("release_id")[0].toxml().replace("","").replace("",""))
# platform_id.append(patch.getElementsByTagName("platform_id")[0].toxml().replace("","").replace("",""))
# language_id.append(patch.getElementsByTagName("language_id")[0].toxml().replace("","").replace("",""))
# target_type.append(patch.getElementsByTagName("target_type")[0].toxml().replace("","").replace("",""))

# Now we need a target list list (from a config search or other get_targets commands)
#
# Run stored configuration search to get list of databases missing the patch
# Target list must include target_name, host_name and Oracle_home (or get them based on target_name)

# NARS

print "Run get_targets with a preconfigured configuration search get list of targets"

# Config_Search

#targets_array = get_targets(config_search='11.2.0.3_SI_DBs_patch_14275605').out()['data']
#targets_array = get_targets(config_search='Test_Config_Search_1').out()['data']
#targets_array = get_targets(target="DG%").out()['data']
#targets_array = get_targets().out()['data']
#targets_array = run_config_search(search_name="DBPSUVersionSearch11g").out()['data']

# Load propdict properties for targets
propdict={}
ohdict={}
logdbg(" load 'propdict' with all target properties.....")
prop_array = gettargetproperties()
for lineitem in prop_array.out()['data']:
logdbg2(" lineitem (prop_array)--> " + str(lineitem) )
tname = str(lineitem['TARGET_NAME'])
tname = str(lineitem['TARGET_TYPE'])
thost = str(lineitem['HOST_NAME'])
tproperty = str(lineitem['PROPERTY_NAME'])
tvalue = str(lineitem['PROPERTY_VALUE'])
key = tname + ";" + tproperty
value = tvalue
propdict = loaddict(propdict,key,value,"propdict")
# Load ohdict properties for targets (using prop_array)
ohdict={}
logdbg(" load 'ohdict' with all orcle_homes for each hosts")
logdbg2(" lineitem (prop_array)--> " + str(lineitem) )
if tproperty == "OracleHome":
ohkey = tvalue
ohvalue = tproperty
ohdict = loaddict(ohdict,ohkey,ohvalue,"ohdict")
else:
dummy99=0


# SQL Based Search

logdbg(" preparing SQL with version_search -->'" + version_search + "'")
sql1 = '''
SELECT table1.CM_TARGET_NAME as TARGETNAME ,
table1.BANNER as BANNER ,
table1.HOST_NAME as HOST,
table2.PROPERTY_VALUE as PVALUE2 ,
table3.PROPERTY_VALUE as PVALUE3,
table4.PROPERTY_VALUE as PVALUE4,
table5.PROPERTY_VALUE as PVALUE5 ,
table5.PROPERTY_NAME as PNAME5
FROM CM$MGMT_DB_DBNINSTANCEINFO_ECM table1, CM$EM_TPROPS_ECM_VIEW table2,
CM$EM_TPROPS_ECM_VIEW table3 ,
CM$EM_TPROPS_ECM_VIEW table4 ,
CM$EM_TPROPS_ECM_VIEW table5
WHERE table1.CM_TARGET_TYPE ='oracle_database'
AND ( table1.CM_TARGET_NAME like 'DBSOE%' OR table1.CM_TARGET_NAME like 'XXXTST%' )
AND table1.CM_SNAPSHOT_TYPE='oracle_dbconfig'
AND ( NLS_UPPER(table1.BANNER) LIKE NLS_UPPER('%%%'))
AND ( NLS_UPPER(table1.HOST_NAME) LIKE NLS_UPPER('%%%'))
AND table2.CM_TARGET_GUID = table1.CM_TARGET_GUID
AND table2.CM_SNAPSHOT_TYPE='orcl_tp_config'
AND table2.PROPERTY_NAME ='DBVersion'
AND ( NLS_UPPER(table2.PROPERTY_VALUE) LIKE NLS_UPPER('%%%'))
AND table2.ECM_SNAPSHOT_ID = table3.ECM_SNAPSHOT_ID
AND table3.PROPERTY_NAME ='OracleHome'
AND ( NLS_UPPER(table3.PROPERTY_VALUE) LIKE NLS_UPPER('%%%'))
AND table2.ECM_SNAPSHOT_ID = table4.ECM_SNAPSHOT_ID
AND table4.PROPERTY_NAME ='orcl_gtp_target_version'
'''
sql2 = " AND ( table4.PROPERTY_VALUE = '" + version_search + "')"
sql3 = " AND table2.ECM_SNAPSHOT_ID = table5.ECM_SNAPSHOT_ID AND ( NLS_UPPER(table5.PROPERTY_NAME) LIKE NLS_UPPER('%MachineName%')) "
longsql = sql1 + sql2 +sql3
logdbg( " longsql -->\n" )
logdbg( longsql )

print "Now gettign the target list and info via -list with sql"
targets_array = list(sql=longsql)

# Process output from config_search and load into two dictionaries for sorting
# Need to group targets by host/Oracle_home
hdict={}
tdict={}
odict={}
pdict={}
vcnt=0
lcnt=0

# NARS1
print "Loop through target list.... and a build patch plan file for --> " + deploymenttype

#for targets in targets_array:
for targets in targets_array.out()['data']:
vcnt += 1
print " ** new targetsline is --> " + str(targets)
tname = str(targets['TARGETNAME'])
thost = str(targets['HOST'])
tprop1 = str(targets['BANNER'])
tinstancever = str(targets['PVALUE4'])
tfdqn = str(targets['PVALUE5'])
toraclehomepath= targets['PVALUE3']
tdbver = str(targets['PVALUE2'])
ttargetdesc = targets['BANNER']
print "\n #" + str(vcnt) + " -processing(new target) tname-> " + tname + " vcnt--> " + str(vcnt)
print " --> tname=" + tname
print " --> thost=" + thost
#hvalue = tname + ";" + tfdqn + ";" + toraclehomepath + ";" + thost + ";" + tinstancever
hvalue = tname
tvalue = tname + ";" + tfdqn + ";" + toraclehomepath + ";" + thost + ";" + tinstancever
# Set Dictionary Keys
hostskey = tfdqn + ";" + toraclehomepath
targetskey = str(tname)
print " --> hostskey='" + hostskey + "'"
print " --> targetskey='" + targetskey + "'"
print " --> hvalue='" + hvalue + "'"
print " --> tvalue='" + tvalue + "'"
# NARS2
print " length of hdict{} --> " + str(len(hdict))
print " length of tdict{} --> " + str(len(tdict))
print " adding to dictionary hosts object.... (vcnt is-->" + str(vcnt)
if hostskey in hdict:
print " *** key (" + hostskey + ") exists in hict - append new data to existing values"
existing = hdict[hostskey]
hdict[hostskey] = existing + ";" + tname
else:
print " *** key (" + hostskey + ") exists in hdict - add entry "
hdict[hostskey] = tname
if targetskey in tdict:
print " *** key (" + targetskey + ") exists in tdict - append new data to existing values"
existing = tdict[targetskey]
tdict[targetskey] = existing + ";" + tname
else:
print " *** key(" + targetskey + ") does not exists in tdict - add new entry"
tdict[targetskey] = tvalue
lcnt += 1
print " ----- loop count #" + str(lcnt) + " --------"

print "\n"
logdbg( "length of hdict{} --> " + str(len(hdict)) )
logdbg( "length of tdict{} --> " + str(len(tdict)) )
logdbg( "length of propdict{} --> " + str(len(propdict)) )
logdbg( "length of ohdict{} --> " + str(len(ohdict)) )
logdbg( "")
logdbg2( "now print out key-values from each dictionary object")
printdict(hdict,"hdict")
printdict(tdict,"tdict")
printdict(propdict,"propdict")
printdict(ohdict,"ohdict")


# -----------------------------------------------------
# Now that we have a target list, produce the patch_plan
# Patch plans are based on target type (oracle_database vs has)
# and whether deployment is In-Place or Out-Of-Place

print "\n ****************************\n"
print "\n ******* Building Patch Plan File (header, patchlist per node and oracle home section)"

cnt=0
nodeCount = 0
#Date
timenow2 = datetime.datetime.now()
#now2=timenow2.strftime("%m-%d-%y_%H:%M")
now2=timenow2.strftime("%Y-%m-%d %H:%M")
nicedate=timenow2.strftime("%m_%Y_%H")

if ( deploymenttype == "inplace"):
planName = planPrefix + "INP_" + str(nicedate)
else:
planName = planPrefix + "OOP_" + str(nicedate)

#newfilename = "patchplan-rdbms-" + deploymenttype + ".txt"
newfilename = planName
#f = open('patchplan.txt', mode='w')
f = open(newfilename, mode='w')
# write plan header
f.write("name=" + planName + "\n")
f.write("description=Test Patch Plan" + "\n")
#f.write("deployment_date=" + str(now2) + "\n")
f.write("deployment_date=" + "\n")
f.write("planPrivilegeList=BOBBY CURTIS:ADMIN:FULL;NARS:ADMIN:FULL;PAUL:ADMIN:FULL;SANDEEP NARANI:ADMIN:FULL" + "\n")
f.write("\n")

logdbg( "Loop through target name list.... and build the patch plan file")
retval=0
try:
# NARS3
# For each target create a patch plan containing the patches in the sample patch plan
#for targets in targets_array:
for key,value in sorted(tdict.iteritems()):
logdbg( " #" + str(cnt) + " = key->'" + key + "' value->'" + value + "'")
cnt += 1
logdbg(" new target -->#" + str(cnt) + " -targetline--> " + str(targets) )
tmpcnt=0
logdbg (" (patchloop)looping through all patches to be applied")
for patchName in patchlist:
tmpcnt += 1
logdbg(" host(cnt)#" + str(cnt) + " - patch#" + str(tmpcnt) + " release_id --> " + str(releaseid) )
# write info for each target in target list
f.write( "patch." + str(nodeCount) + ".patch_id=" + str(patchName) + "\n")
f.write( "patch." + str(nodeCount) + ".release_id=" + str(releaseid) + "\n")
f.write( "patch." + str(nodeCount) + ".platform_id=226\n")
f.write( "patch." + str(nodeCount) + ".language_id=0\n")
f.write( "patch." + str(nodeCount) + ".target_name=" + key + "\n")
f.write( "patch." + str(nodeCount) + ".target_type=oracle_database\n")
nodeCount += 1

# Now write global deployment options
logdbg( " *** Now write global deployment options")

f.write("\n")
f.write("deploymentOptions.AdvancedOPatchOptions=null" + "\n")
#f.write("deploymentOptions.StageLocation=%emd_emstagedir%" + "\n")
f.write("deploymentOptions.StageLocation=/db_backup/oracle/stage" + "\n")
f.write("deploymentOptions.StagePatches=true" + "\n")
f.write("deploymentOptions.isStageLocationShared=false" + "\n")
f.write("deploymentOptions.notify.enabled=true" + "\n")
f.write("deploymentOptions.performAruAnalysis=true" + "\n")
#f.write("deploymentOptions.DISPATCHER_LOC=%emd_emstagedir%" + "\n")
f.write("deploymentOptions.DISPATCHER_LOC=/db_backup/oracle/stage" + "\n")

if deploymenttype == "inplace":
f.write("deploymentOptions.cloneAndPatch.selected=false" + "\n")
else:
f.write("deploymentOptions.cloneAndPatch.selected=true" + "\n")

# now write node/oracle_home specific deployment options to the patch plan file - apply to all databases in home
logdbg( " now write node/oracle_home specific deployment options to the patch plan file - apply to all databases in home")
cnt=0
add_once = "N"
for key,value in sorted(hdict.iteritems()):
logdbg( " #" + str(cnt) + " = key->'" + key + "' value->'" + value + "'" )
kwords = key.split(";")
logdbg( " kwords[0] --> " + kwords[0] )
logdbg( " kwords[1] --> " + kwords[1] )
f.write("deploymentOptions.cloneAndPatch.element." + str(cnt) + ".host=" + kwords[0] + "\n")
f.write("deploymentOptions.cloneAndPatch.element." + str(cnt) + ".source.oh=" + kwords[1] + "\n")

# Split out OH path into array and create new path
# -------------------------------------------------
logdbg(" *** Split out OH path to create new path parts")
ohpath = kwords[1]
pathparts = ohpath.split("/")
logdbg( " ohpath --> " + ohpath)
logdbg( " length of pathparts array --> " + str(len(pathparts)) )
logdbg( " pathparts array --> " + str(pathparts) )
pathpartslength = len(pathparts)
newidx = int(pathpartslength) - 1
logdbg( " pathpartslength --> " + str(pathpartslength) + " newidx --> " + str(newidx) )
#print " pathpartslength[" + str(len(pathparts) "] --> " + pathparts[pathpartslength]
lastpart = pathparts[newidx]
ohlastpart = ohpath.split("_")
logdbg( " length of lastpart --> " + str(len(lastpart)) )
logdbg( " ohlastpart ary --> " + str(ohlastpart) )
logdbg( " now split ohlastpart into more pieces --> " + str(ohlastpart) )
lastname = ohlastpart[0]
lastvalue = ohlastpart[1]
logdbg( " lastname--> " + lastname)
logdbg( " lastvalue--> " + lastvalue)
newhomevalue = int(lastvalue) + 1
newhomepath = lastname + "_" + str(newhomevalue)
logdbg( " newhomevalue--> " + str(newhomevalue) + " newhomepath--> " + newhomepath)
fullhostname = str(kwords[0])
nodenameparts = fullhostname.split(".")
logdbg(" nodenameparts[0] --> " + str(nodenameparts[0]) )

# write preferred credentials for all hosts
#if add_once == "N":
# f.write("deploymentOptions.DummyCredentialsOHLess=" + ohpath + ";HomeCreds_Normal;40D129D2D86470AFE0536E61160A31B8;" + ohpath + ";HomeCreds_Priv;3FDAF3EEEB52C01EE0536E61160AFB12" + "\n")
# add_once = "Y"

# Dest OH for inplace should be blank
if deploymenttype == "inplace":
logdbg( " deployment is (deploymenttype=" + deploymenttype + ")")
#f.write("deploymentOptions.cloneAndPatch.element." + str(cnt) + ".destination.oh=" + kwords[1] + "_" + patchName + "\n")
#f.write("deploymentOptions.cloneAndPatch.element." + str(cnt) + ".destination.name=" + "\n")
#f.write("deploymentOptions.cloneAndPatch.element." + str(cnt) + ".destination.oh=" + newhomepath + "\n")
f.write("deploymentOptions.cloneAndPatch.element." + str(cnt) + ".destination.oh=" + "\n")
f.write("deploymentOptions.cloneAndPatch.element." + str(cnt) + ".destination.name=" + "\n")
#f.write("deploymentOptions.cloneAndPatch.element." + str(cnt) + ".destination.name=" + "\n")
else:
logdbg( " deployment is (deploymenttype=" + deploymenttype + ")")
#f.write("deploymentOptions.cloneAndPatch.element." + str(cnt) + ".destination.oh=" + kwords[1] + "_" + patchName + "\n")
f.write("deploymentOptions.cloneAndPatch.element." + str(cnt) + ".destination.oh=" + newhomepath + "\n")
f.write("deploymentOptions.cloneAndPatch.element." + str(cnt) + ".destination.name=OraHome_" + version_category + "_" + str(nodenameparts[0]) + "_dbhome" + "_" + str(newhomevalue) + "\n")
#f.write("deploymentOptions.cloneAndPatch.element." + str(cnt) + ".destination.name=" + "\n")

f.write("deploymentOptions.cloneAndPatch.element." + str(cnt) + ".destination.base=/u01/app/oracle" + "\n")
f.write("deploymentOptions.cloneAndPatch.element." + str(cnt) + ".destination.migrateOnly=false" + "\n")
cnt += 1

# Based on Deployment type (write different deployment options)-if In-Place then, else OutOfPlace
if deploymenttype == "inplace":
print " deployments is (deploymenttype=" + deploymenttype + ")"
f.write("deploymentOptions.deploymentProcedure=PATCH_SADB:oracle:true" + "\n")
f.write("deploymentOptions.isDispatcherEnabled=true" + "\n")
f.write("deploymentOptions.isDispatcherLocShared=false" + "\n")
f.write("deploymentOptions.rollbackMode=false" + "\n")
else:
print " deployments is (deploymenttype=" + deploymenttype + ")"
f.write("deploymentOptions.deploymentProcedure=CLONE_PATCH_SIDB:oracle:true" + "\n")
f.write("deploymentOptions.isDispatcherEnabled=true" + "\n")
f.write("deploymentOptions.isDispatcherLocShared=false" + "\n")

# Close Patch Plan file
f.close()

# now call the OEM commands to create patch plan and submit patch plan (analyze, preare, deploy)

#print "Print out list of existing patch plans.....\n"
#display_plan_info(planName)
#pjob_list=list_patch_plans
#print " pjob_list is of type = " + str(type(pjob_list))
#print " pjob_list --> " + str(pjob_list)
#pjob_list = mapping.get(list_patch_plans())
# split the text in 'value'
#for job in pjob_list:
# print " element-->'" + job

print " *** creating a new patch plan in OEM--> " + planName
inputfileinfo="'data:" + newfilename + "'"

if deploymenttype == "inplace":
inputfileinfo = "data:" + planName
logdbg(" now call create_patch_plan using new inputfileinfo---> " + inputfileinfo + " planName(filename)-> " + planName)
print " plan type is for deploymenttype--> " + deploymenttype
logdbg(" -->create_patch_plan(name=planName,input_file='data:patchplan-rdbms-inplace.txt',impact_other_targets='add_all') ")
retval = create_patch_plan(name=planName,input_file=inputfileinfo,impact_other_targets='add_all')
logdbg(" *** retval (create_patch_plan) --> " + str(retval) )
print " ran --> create_patch_plan(name=planName,input_file=" + inputfileinfo + ",impact_other_targets='add_all')"

# List/Show patch plan status
print " print listing of patch plan"
print list_patch_plans()
#print list_patch_plans(name=planName)
#print show_patch_plan(name=planName)
logdbg(" run --> show_patch_plan(name=" + planName )
patchplanstatus = show_patch_plan(name=planName)
logdbg(" call parsexml_string() to parse XML plan status")
#parsexml_string(patchplanstatus)
#os.system("./login ; ./emcli show_patch_plan -name=" + planName + " -info > " + planName + ".xml" )
showpatchplandetails(planName)

# Set Patch plan data (plan has been created, override defaults with same plan)
logdbg( " set_patch_plan_data(name=planName,input_file=" + inputfileinfo + ",impact_other_targets='add_all')")
#set_patch_plan_data(name=planName,input_file='data:patchplan-rdbms-inplace.txt',impact_other_targets='add_all')
#set_patch_plan_data(name=planName,input_file=inputfileinfo,impact_other_targets='add_all')
logdbg( " ran--> set_patch_plan_data(name=planName,input_file=" + inputfileinfo + ",impact_other_targets='add_all')" )
retval = set_patch_plan_data(name=planName,input_file=inputfileinfo,impact_other_targets='add_all')
logdbg(" *** retval (set_path_plan_data) --> " + str(retval) )
logdbg(" finished creating and updating plan information in OEM" )

else:
inputfileinfo="data:" + planName
logdbg(" (if stmt) plan type is for deploymenttype--> " + deploymenttype + " - NARS4" )
logdbg(" (if stmt) now call create_patch_plan using new inputfileinfo---> " + inputfileinfo + " planName(filename)-> " + planName )
# --->create_patch_plan(name=planName, input_file='data:patchplan-rdbms-outofplace.txt',impact_other_targets='add_original_only')
#retval = create_patch_plan(name=planName, input_file='data:patchplan-rdbms-outofplace.txt',impact_other_targets='add_original_only')
retval = create_patch_plan(name=planName,input_file=inputfileinfo,impact_other_targets='add_original_only')
logdbg( " *** retval (create_patch_plan) --> " + str(retval) )
logdbg(" retval = create_patch_plan(name=planName,input_file=inputfileinfo,impact_other_targets='add_original_only') ")

# List/Show patch plan status
print " print listing of patch plan"
print list_patch_plans()
print list_patch_plans(name=planName)
#print show_patch_plan(name=planName)
showpatchplandetails(planName)

# Set Patch plan data (plan has been created, override defaults with same plan)
logdbg( " set_patch_plan_data(name=planName,input_file=" + inputfileinfo + ",impact_other_targets='add_all')")
#set_patch_plan_data(name=planName,input_file='data:patchplan-rdbms-inplace.txt',impact_other_targets='add_all')
#set_patch_plan_data(name=planName,input_file=inputfileinfo,impact_other_targets='add_all')
logdbg( " ran--> set_patch_plan_data(name=planName,input_file=" + inputfileinfo + ",impact_other_targets='add_all')" )
retval = set_patch_plan_data(name=planName,input_file=inputfileinfo,impact_other_targets='add_original_only')
logdbg(" *** retval (set_path_plan_data) --> " + str(retval) )
logdbg(" finished creating and updating plan information in OEM" )

# Show patch plan drtails / status
logdbg2("show patch plan detaila, for plan--> " + planName)
#print show_patch_plan(name=planName)

# Analyze patch plan - deploy rather than analyze
print "analyzing patch plan (" + planName + ") for execution (deployment-> " + deploymenttype
print "submit_patch_plan(name=" + planName + ",action='analyze') planName--> " + planName
submit_patch_plan(name=planName,action="analyze")
retval = submit_patch_plan(name=planName,action="analyze")
logdbg( " *** retval (submit_patch) --> " + str(retval) )

print " **** sleeping now for --> " + str(SleepTime) + " submitted patch_plan --> " + planName
#time.sleep(SleepTime)

# List patch plan status
print list_patch_plans()
#print list_patch_plans(name=planName)
#display_plan_info(planName)

# Deploy the patch plan - wait until Analyze is complete
#time.sleep(680)
print "deploying patch plan (" + planName + ") for execution (deployment)"
print "submit_patch_plan(name=" + planName + ",action='deploy')"
#submit_patch_plan(name=planName,action="deploy")
#retval = submit_patch_plan(name=planName,action="deploy")
#print "submit_patch_plan retval--> " + str(retval)

# List patch plan status
logdbg( list_patch_plans() )
print list_patch_plans(name=planName)
#display_plan_info(planName)

except:
print "Unexpected error: ", sys.exc_info()[1]

exit()

 

Leave a comment