IBM Websphere - wsadmin script for AutoDeployment - websphere

Can you please look into the below issue?
import time
node = AdminConfig.getid('/Node:node111/')
print node
print "sss" +AdminControl.queryNames('WebSphere:type=Server,*')
cell = AdminControl.getCell()
print " Cell name is --> "+ cell
warLoc='/home/test/PA_Test.war'
appName='PA_Test'
cellName=AdminControl.getCell()
print cellName
nodeName=AdminControl.getNode()
print "hello"
print " nodeName is --> "+ nodeName
appManager=AdminControl.queryNames('cell='+cellName+',node=node111,type=ApplicationManager,process=WebSphere_Portal,*')
print appManager
application = AdminConfig.getid("/Deployment:"+appName+"/")
print 'printing application name in next line'
print application
len(application)
print application
len(application)
var1 = len(application)
if var1:
print "Application exists"
print "before uninstall"
AdminApp.uninstall('PA_Test')
print "after uninstall"
AdminConfig.save()
else:
print "Application doesnot exist"
print "Before install"
print AdminApp.install(warLoc,'[-target default -usedefaultbindings -defaultbinding.virtual.host default_host]')
print "Done from My Side"
print "After install"
AdminConfig.save()
time.sleep(30)
AdminControl.invoke(appManager , 'startApplication',appName)
print "The script is completed."
Below is the successful message:
ADMA5016I: Installation of PA_Test.war154ed2178ed started.
ADMA5058I: Application and module versions are validated with versions of deployment targets.
ADMA5005I: The application PA_Test.war154ed2178ed is configured in the WebSphere Application Server repository.
ADMA5005I: The application PA_Test.war154ed2178ed is configured in the WebSphere Application Server repository.
ADMA5081I: The bootstrap address for client module is configured in the WebSphere Application Server repository.
ADMA5053I: The library references for the installed optional package are created.
ADMA5001I: The application binaries are saved in /opt/IBM/WebSphere/wp_profile/wstemp/Script154ed215c59/workspace/cells/inpudingpwmtst1Cell/applications/PA_Test.war154ed2178ed.ear/PA_Test.war154ed2178ed.ear
Now I am able to deploy the war but the file name is getting change to PA_Test.war154ed2178ed.ear but its should actually be PA_Test.ear. Can you please help how to change the current script?

Short answer:
print AdminApp.install(warLoc, [
'-appname', 'PA_Test.ear',
'-target', 'default',
'-usedefaultbindings',
'-defaultbinding.virtual.host', 'default_host'
])
Even shorter one: use WDR.
You'll need an application manifest file PA_Test.wdra:
PA_Test.ear pa.war
target default
usedefaultbindings
defaultbinding.virtual.host default_host
... and Jython script to import this manifest:
alreadyInstalled = 'PA_Test.ear' in AdminApp.list().splitlines()
importApplicationManifest('PA_Test.wdra')
save()
sync()
while AdminApp.isAppReady('PA_Test.ear') != 'true':
time.sleep(10)
if not alreadyInstalled:
for appMgr in queryMBeans(type='ApplicationManager', process='WebSphere_Portal'):
appMgr.startApplication('PA_Test.ear')
Disclosure: I'm a contributor and maintainer of WDR

Related

WebSphere - Map Module to Target through Jython

We have deployed an ear file to our WebSphere instance. By default, all *.jar & *.war modules are mapped to the jvm.
We would like to map all the *.war modules also to the web server.
I have created the below jython script to map the additional modules to the web server:
modules = AdminApp.listModules('${p:appName}', '-server')
splitted = modules.splitlines()
for moduleLine in splitted:
print "Mapping module: " + moduleLine
appName, moduleUri, target = moduleLine.split("#")
print appName
print moduleUri
print target
if moduleUri.find('.war') >= 0:
print "It's a war: " + moduleUri
module, webXml = moduleUri.split("+")
print module
print webXml
AdminApp.edit('${p:appName}', ['-MapModulesToServers', [[module, module + ',' + webXml, target]]])
The above script works when the name of the module is the same name as referenced in the uri. However, in some cases, the web.xml contains another name as 'display name'. When we do a -MapModulesToServers, it seems to look at the display name of the module, not the uri.
For example:
In the WebSphere console, we would have the following line:
Module URI Module type
Demo be.fictive.company.demo.war,WEB-INF/web.xml Web Module
The 'AdminApp.listModules' method is returning the uri name (be.fictive.company.demo.war), whereas I need the name of the module (Demo).
Am I missing something or is there another way to retrieve the module name, so I can use the AdminApp.edit('${p:appName}', ['-MapModulesToServers', [[module, module + ',' + webXml, target]]]) to update the targets?
The administrative scripting console is not available, so I don't see a way to retrieve the commands that have been issued.
You can use the wildcat to match the name of the module. Replace
AdminApp.edit('${p:appName}', ['-MapModulesToServers', [[module, module + ',' + webXml, target]]])
with
AdminApp.edit('${p:appName}', ['-MapModulesToServers', [['.*', module + ',' + webXml, target]]])

Get current restart policy state (nodeRestartState) of AppServer using Jython

I want to get the current restart policy of an AppServer (RUNNING, STOPPED or PREVIOUS) using Jython.
servers = AdminTask.listServers('[-serverType APPLICATION_SERVER]').splitlines()
for server in servers:
print server
print AdminConfig.showAttribute(server, "monitoringPolicy")
break
This gave me an exception that the attribute is invalid:
An exception occurred when executing the file "test.py". Information
about the exception: com.ibm.ws.scripting.ScriptingException:
WASX7080E: Invalid attributes for type "Server" -- "monitoringPolicy".
But I could get the attribute using print AdminConfig.showall(server):
...
[monitoringPolicy [[autoRestart true]
[maximumStartupAttempts 3]
[nodeRestartState STOPPED]
[pingInterval 60]
[pingTimeout 300]]]
...
For me it looks like monitoringPolicy is the key of an array, so that it should be possible to get the restart state with
policy = AdminConfig.showAttribute(server, "monitoringPolicy")
restartState = policy["restartState"] # Should be "STOPPED"
Where is the problem?
Edit
After taking a deeper look in the list output, I saw that I missed a top level property processDefinitions, which is the parent of monitoringPolicy.
pd = AdminConfig.showAttribute(server, "processDefinitions")
print pd
This prints:
[(cells/CnxCell/nodes/CnxNode01/servers/UtilCluster_server1|server.xml#JavaProcessDef_1578492353152)]
But I'm not able to get any of the child propertys from this object:
# TypeError: sequence subscript must be integer or slice
print pd["monitoringPolicy"]
# AttributeError: 'string' object has no attribute 'monitoringPolicy'
print pd.monitoringPolicy
MonitoringPolicy has his own type. This prints the server and the state, so 'RUNNING', 'STOPPED'
servers = AdminTask.listServers('[-serverType APPLICATION_SERVER]').splitlines()
for server in servers:
print(server)
mpol = AdminConfig.list("MonitoringPolicy", server)
print(AdminConfig.showAttribute(mpol, 'nodeRestartState'))

jenkins pipeline function errors with no error

I am using a jenkins pipeline script to make product tests on our machines
the father of all tests looks like this
node('nightly-master') {
stage 'run'
println PRODUCTS
oliTest('win7.nightly.test', 'checkAndWaitForInstalledProduct.py', 'esxi', 'opsi-local-image-prepare', 'opsi-local-image-win7', PRODUCTS)
)
}
PRODUCTS is a textbox variable, enetered at the build start
the function oliTest() is this:
def call(SERVERID, CHECKSCRIPT, VIRTUALIZATION, OLIPREPARE, OLINETBOOT, PRODUCTS){
try {
timeout(time: 5, unit: 'HOURS') {
println SERVERID
println CHECKSCRIPT
println VIRTUALIZATION
println OLIPREPARE
println OLINETBOOT
println PRODUCTS
//oliPrepare(SERVERID, CHECKSCRIPT, VIRTUALIZATION, OLIPREPARE, OLINETBOOT)
oliProd(SERVERID, CHECKSCRIPT, VIRTUALIZATION, PRODUCTS)
oliBackup(SERVERID, CHECKSCRIPT, VIRTUALIZATION)
oliRestore(SERVERID, CHECKSCRIPT, VIRTUALIZATION)
}
} catch(error) {
sh "fab -f /home/adminuser/scripts/${VIRTUALIZATIO}Nfab.py powerOffVm:vmName=${SERVERID}"
sh 'return 1'
}
}
the println values are printed correctly into the jenkins log
as soon as the function oliProd() is called the test fails without any error message at the forr loop in the following block
def call(SERVERID, CHECKSCRIPT, VIRTUALIZATION, PRODUCTS){
stage 'install Products'
println SERVERID
println CHECKSCRIPT
println VIRTUALIZATION
println PRODUCTS
sh " echo ${PRODUCTS}"
sh "echo ${SERVERID}"
sh "for i in ${PRODUCTS}; do opsi-admin -d method setProductActionRequestWithDependencies $i ${SERVERID} setup;done"
}
writing it multi line with '''COMMAND''' exists with an error, because ${SERVERID} is not expanded and left empty
Any suggestions how to make things work??
Cheers
Note that you could use have triple double-quotes instead of triple single-quotes. That would have fixed that simple problem.
However, you really should be doing your iteration in the script code itself, instead of trying to do iteration in the shell.
Jon S suggested to resolve script methods such as "echo" against a reference to the "pipeline object as in oliTest(this, ...) where oliTest declares a Script parameter and passes it along to other methods/instances to be used to resolve echo as scriptObj.echo.
println in "call" method of "vars/foo.groovy" works, but not in method in class

how to set path, when repo is downloaded using gradle

I am using gradle to download the selenium chrome driver from maven
webtestsCompile 'org.seleniumhq.selenium:selenium-chrome-driver:2.32.0'
I am trying to use this directly and I see that I get this error :
Caused by:
java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.chrome.driver system property; for more information, see http://code.google.com/p/selenium/wiki/ChromeDriver. The latest version can be downloaded from http://code.google.com/p/chromedriver/downloads/list
I have looked up a couple of questions from stack-overflow and other places it requires me to set the value of the property webdriver.chrome.driver to the location where I have downloaded with some-thing like this :
System.setProperty("webdriver.chrome.driver", "path to chrome-driver");
I am wondering what is the best way to go about this ?
EDIT 1:
I verified the java.class.path a snippet of this path looks like this :
/home/bhavya/.gradle/caches/artifacts-26/filestore/org.seleniumhq.selenium/selenium-chrome-driver/2.32.0/jar/14a4e8e32a4129c682c67381f5d7bf11f2327e1/selenium-chrome-driver-2.32.0.jar
This looks like the selenium-chrome-driver is present in the java.class.path.
Edit 2 :
I would want the chrome driver to work irrespective of the operating system that I am using, currently I am on a ubuntu box but a lot of this will get tested on a windows box. When I hard coded the value of the webdriver.chrome.driver to the value in EDIT 1, I am facing the following issue :
java.lang.IllegalStateException: The driver is not executable: /home/bhavya/.gradle/caches/artifacts-26/filestore/org.seleniumhq.selenium/selenium-chrome-driver/2.32.0/jar/14a4e8e32a4129c682c67381f5d7bf11f2327e1/selenium-chrome-driver-2.32.0.jar
Edit 3 :
Task within which I am running the test suite --
task webs(type: Test, dependsOn: updateNodeModules) {
testClassesDir = sourceSets.webtests.output.classesDir
classpath = sourceSets.webtests.runtimeClasspath
def javaHomeBin = new File(System.getProperty("java.home"), "bin");
def javaExec = new File(javaHomeBin, "java").getAbsolutePath();
systemProperties['jar.path'] = jar.archivePath
if(project.hasProperty('url')){
println" url passed as variable is $url"
systemProperties["selenium.webdriver.url"] = "$url"
}
systemProperties["selenium.webbrowser.type"] = "firefox"
if(project.hasProperty('browser')){
println "the browser passed is $browser"
systemProperties["selenium.webbrowser.type"] = "$browser"
}
include '**/UserEditControllerWebTest.class'
doFirst {
println " iterator is $it"
def chrome=configurations.testRuntime.find {
it.name.contains("selenium-chrome-driver")
}.path
println " chrome driver path is $chrome"
systemProperties["webdriver.chrome.driver"]= "$chrome"
}
}
Assuming that you need to set this system property for your tests, you can do something like:
test.doFirst {
systemProperty "webdriver.chrome.driver",
classpath.find {
it.name.contains("selenium-chrome-driver")
}.path
}

wsadmin: How to inspect existing resource references?

With $AdminApp view <applicationName> -MapResRefToEJB it is possible to list the resource references defined for a deployed EJB module. However, the result of that command is plain text (that in addition may be localized). To extract that information one would have to parse this text, which is not very convenient. Is there a way to get the same information (i.e. the resources references of an application) in a structured form using $AdminConfig?
The AppManagement MBean provides this data in a structured format (Vector of AppDeploymentTasks). To obtain this data using wsadmin scripting (jython):
import javax.management as mgmt
appName = sys.argv[0]
appMgmt = mgmt.ObjectName(AdminControl.completeObjectName("WebSphere:*,type=AppManagement"))
appInfo = AdminControl.invoke_jmx(appMgmt, "getApplicationInfo", [appName, java.util.Hashtable(), None], ["java.lang.String", "java.util.Hashtable", "java.lang.String"])
for task in appInfo :
if (task.getName() == "MapResRefToEJB") :
resRefs = task.getTaskData()
# skip the first row since it contains the headers
for i in range(1, len(resRefs)) :
resRef = resRefs[i]
print
print "URI:", resRef[4]
print "EJB:", resRef[3]
print "Name:", resRef[5]
print "Type:", resRef[6]
print "JNDI:", resRef[8]

Resources