Sunday, May 1, 2011

Basic WebSphere Application Server Administration using wsadmin

This one is not a code snippet, but just some wsadmin commands to perform some basic administration of WebSphere Application Server.

Starting admin app

cd D:\Program Files\IBM\SDP70\runtimes\base_v61\profiles\AppSrv01\bin
wsadmin.bat -username admin -password admin


Install WAR

wsadmin>$AdminApp install "c:/ra/raks/blah.war" {-contextroot /osgi -defaultbinding.virtual.host default_host -usedefaultbindings}
#-Note the 'front slashes' (/) in the path of the war file
#-The extra arguments are passed in {}
wsadmin>$AdminConfig save


Starting application

wsadmin>set appManager [$AdminControl queryNames type=ApplicationManager,*]
wsadmin>$AdminControl invoke $appManager startApplication myApplication


Uninstall App

$AdminApp uninstall appName


Running a Jython wasadmin script

cd D:\Program Files\IBM\SDP70\runtimes\base_v61\profiles\AppSrv01\bin
>wsadmin.bat -lang jython -f c:/installApp.py [script-params]


Getting heapdump of Websphere server

wsadmin>set objectName [$AdminControl queryNames WebSphere:type=JVM,process=,node=,*]
wsadmin>$AdminControl invoke $objectName generateHeapDump


Exporting WebSphere profile configuration as CAR File

wsadmin>$AdminTask exportWasprofile {-archive appsrv01_profile.car}


Importing WebSphere profile configuration from a CAR File

>sftp user@servername:/opt/IBM/WebSphere/AppServer/profiles/AppSrv01/bin/appsrv01_profile.car .
wsadmin>$AdminTask importWasprofile {-archive appsrv01_profile.car}
wsadmin>$AdminConfig save


Finding and cancelling EJB Timer

/opt/IBM/WebSphere/AppServer/profiles/AppSrv01/bin> findEJBTimers.sh server1 -all
Output:
ADMU0116I: Tool information is being logged in file
           /opt/IBM/WebSphere/AppServer/profiles/AppSrv01/logs/server1/EJBTimers.log
ADMU0128I: Starting tool with the AppSrv01 profile
ADMU3100I: Reading configuration for server: server1
Xlib: connection to "localhost:10.0" refused by server
Xlib: PuTTY X11 proxy: MIT-MAGIC-COOKIE-1 data did not match
Realm/Cell Name: 
Username: admin
Password:
EJB Timer : 2552     Expiration: 4/27/11 11:31 AM     Repeating
   EJB    : EAR, Business.jar, SchedulerServiceEJB
   EJB Key: Not Available
   Info   : SchedulerData@4bc84bc8[...]
1 EJB Timer tasks found

Use the timer id from the output (EJB Timer : 2552) and issue this command to cancel the timer.
/opt/IBM/WebSphere/AppServer/profiles/AppSrv01/bin> cancelEJBTimers.sh server1 -timer 2552
Output:
ADMU0116I: Tool information is being logged in file
           /opt/IBM/WebSphere/AppServer/profiles/AppSrv01/logs/server1/EJBTimers.log
ADMU0128I: Starting tool with the AppSrv01 profile
ADMU3100I: Reading configuration for server: server1
Xlib: connection to "localhost:10.0" refused by server
Xlib: PuTTY X11 proxy: MIT-MAGIC-COOKIE-1 data did not match
Realm/Cell Name: 
Username: admin
Password:
EJB Timer : 2552     Expiration: 4/27/11 11:31 AM     Repeating
   EJB    : EAR, Business.jar, SchedulerServiceEJB
   EJB Key: Not Available
   Info   : SchedulerData@4d1d4d1d[...]
1 EJB Timer tasks cancelled

Sunday, December 6, 2009

Install EAR or WAR in WebSphere Application server using wsadmin/Jython

Introduction


This is wsadmin Jython code snippet to install a WAR/EAR file in WebSphere Application Server. The script takes path to the WAR or EAR file and the context root of the web app as the parameter, installs the application on the server and starts the app.

The code was written to install standalone WAR on WebSphere App Server (There is nice big reason why it was not wrapped in an EAR, but that is another story.)

The motivation was the way WAS 6.1 installs standalone WARs when done via wsadmin command prompt. wasadmin picks the war file (say, my-war-file.war) and installes it as my-war-file.warBCBGMAX4234. The weird chars at the end changes every time it is deployed, because of which using command prompt was a pain. After installation the snippet matches the installed war with the list of apps installed using file name and then starts the application.

Disclaimer: The code was tested while installing WAR file only and NOT with EAR. May need some changes in the way context-root is handled for it to work with EAR. This code was written to be run in development environment and not meant for production usage (although with some exception handling and parametrization it can be).

Details

# Jython script to install a EAR or WAR in WebSphere Application Server
#

import sys

#Some Global variables
#WebSphere environment related variables
cellName = 'testvmNode01Cell'
nodeName = 'testvmNode01'
serverName = 'server1'

print '\n\n-------------------------------------------------------------------'
print 'This script will install a EAR/WAR on WebSphere Application Server'
print "\nUsing these WebSphere Defaults:"+"\nCell: "+cellName+"\nNode: "+nodeName+"\nServer: "+serverName
print "\nPass the path to the EAR/WAR and web-app's context-root as parameters. File path should be in this format:"
print "\tc:\\\\osgiapps\\\\war-to-install.war (With double back-slashes)"
print "\nPlease edit the variables in the script if these defaults need to be changed."
print '-------------------------------------------------------------------\n\n'


numberOfArgs = len(sys.argv)
if numberOfArgs < 2:
    print "Usage: installApp.py {file-absolute-path} {context-root}"


else:
    #Get the absolute path of the WAR file and replace \ with /
    filePath1 = str(sys.argv[0])
    contextRoot = str(sys.argv[1])
    filePath1 = filePath1.replace('\\', '/')
    
    #Get the name of the WAR file:
    strAppToInstall = filePath1[filePath1.rfind("/")+1:len(filePath1)];
    print "Installing ", strAppToInstall, " from ", filePath1;
    
    #Uninstall the app if already deployed.
    appToUninstall = ""
    appsBefore = AdminApp.list().split("\n");
    for iApp in appsBefore:    
        if str(iApp).find(strAppToInstall) >= 0:    
            appToUninstall = iApp;
    if appToUninstall:
        print "Uninstalling app: ", appToUninstall
        appToUninstall = str(appToUninstall).strip();
        AdminApp.uninstall(appToUninstall)
        AdminConfig.save();
    
    #Install the app
    print "Installing App: ", strAppToInstall
    AdminApp.install(filePath1, "-contextroot /"+contextRoot+" -defaultbinding.virtual.host default_host -usedefaultbindings");    
    AdminConfig.save();    
    
    #Start the app    
    apps = AdminApp.list().split("\n");    
    theApp = ""    
    for iApp in apps:
        if str(iApp).find(strAppToInstall) >= 0:
            theApp = iApp;
    print "Starting App: ", theApp
    appManager = AdminControl.queryNames('cell='+cellName+',node='+nodeName+',type=ApplicationManager,process='+serverName+',*')
    AdminControl.invoke(appManager, 'startApplication', theApp)
    print "Application installed and started successfuly!"

Monday, June 1, 2009

WebSphere wsadmin script to set up Generic JMS provider

Introduction

This wsadmin Jython script creates a a generic JMS provider and sets up a queue connection factory and queue destination. JCAPS 5.1.x was the message queue used and we were successfully able to connect to it from a web app running on WebSphere Application Server 6.1 using JMS interface. The configuration details here should help if you are trying to set up JCAPS 5.1.x as the message queue and trying to connect to it from WebSphere Application Server 6.1.

Details

# Jython Script to set up JCAPS as the JMS Provider and create the Queues and QCF
#

#Some Global variables
#WebSphere environment related variables
cellName = 'testvmNode01Cell'
nodeName = 'testvmNode01'
serverName = 'server1'
serverURL = '/Cell:'+cellName+'/Node:'+nodeName+'/Server:'+serverName

#JCAPS Configuration related variables
jcapsUserID = "Administrator"
jcapsPwd = "STC"
jcapsHost = "155.54.XX.99"
jcapsPort = "18007"

print '\n\n-------------------------------------------------------------------'
print 'This script will setup JCAPS as one of the JMS provider for WebSphere Application Server'
print "\nUsing these WebSphere Defaults:"+"\nCell: "+cellName+"\nNode: "+nodeName+"\nServer: "+serverName
print "\nUsing these JCAPS defaults:"+"\nHost: "+jcapsHost+"\nPort: "+jcapsPort
print "Please edit the variables in the script if these defaults need to be changed."
print '-------------------------------------------------------------------\n\n'


server = AdminConfig.getid(serverURL)
if server:
 jmsproviderName = 'JCAPSJMSProvider'
 #Remove any existing configuration of JCAPS queue provider.
 print "Removing any existing JMS Provider"
 oldjmsp = AdminConfig.getid(serverURL+'/JMSProvider:'+jmsproviderName) 
 
 if oldjmsp:
  print "Deleting ",oldjmsp
  AdminConfig.remove(oldjmsp);
  AdminConfig.save();
 
 #Create a new JCAPS JMS Provider
 print "Creating JCAPS JMS Provider..." #AdminConfig.required('JMSProvider')

 iContextClass = "com.stc.jms.jndispi.InitialContextFactory"
 qMgrURL = "stcms://"+jcapsHost+":"+jcapsPort
 name = ['name', jmsproviderName]
 extICF = ['externalInitialContextFactory',  iContextClass] 
 extPURL = ['externalProviderURL', qMgrURL] 
 jmspAttrs = [name, extICF, extPURL]
 
 print "Setting up JCAPS JMS provider with these attributes: \n\t",jmspAttrs
 newjmsp = AdminConfig.create('JMSProvider', server, jmspAttrs)

 #Set the custom props
 #Since the newly created JMS provider does not have a custom property list,
 #create a blank property set.
 propSet = AdminConfig.create('J2EEResourcePropertySet', newjmsp, [])

 #Set the user name and password required to connect to JCAPS Q Manager.
 AdminConfig.create('J2EEResourceProperty', propSet, [['name', 'java.naming.security.principal'], ['value', jcapsUserID]])
 AdminConfig.create('J2EEResourceProperty', propSet, [['name', 'java.naming.security.credentials'], ['value', jcapsPwd]])
 
 AdminConfig.save()
 print "Successfuly set up JCAPS as a JMS provider.\n"
 
 #Create QCF
 print "\nCreating Queue Connection Factory..."#,AdminConfig.attributes('GenericJMSConnectionFactory')
 newjmsp = AdminConfig.getid(serverURL+'/JMSProvider:'+jmsproviderName) 
 name = ['name', 'JMSAppenderQCF']
 jndi = ['jndiName', 'jms/JMSAppenderQCF']
 externaljndi = ['externalJNDIName', 'connectionfactories/queueconnectionfactory']
 mqcfAttrs = [name, jndi, externaljndi]
 print "Creating QCF with these configuration: \n\t",mqcfAttrs
 qcf = AdminConfig.create('GenericJMSConnectionFactory', newjmsp, mqcfAttrs)

 #Set some mandatory attributes
 print AdminConfig.create('ConnectionPool', qcf, [], "connectionPool")
 print AdminConfig.create('ConnectionPool', qcf, [], "sessionPool")
 print AdminConfig.create("MappingModule",qcf,[["mappingConfigAlias","DefaultPrincipalMapping"],["authDataAlias",""]])
 
 AdminConfig.save()
 print "Queue Connection Factory created successfuly.\n"
 
 #Create Queue
 print "\nCreating Queue..."
 newjmsp = AdminConfig.getid(serverURL+'/JMSProvider:'+jmsproviderName) 
 qname = ['name', 'JMSAppenderQ']
 qjndi = ['jndiName', 'jms/JMSAppenderQ']
 qexternaljndi = ['externalJNDIName', 'queues/queCSF']
 qtype = ["type","QUEUE"]
 mqAttrs = [qname, qjndi, qexternaljndi, qtype]

 print "Creating Q with these configuration: \n\t",mqAttrs 
 AdminConfig.create('GenericJMSDestination', newjmsp, mqAttrs)
 AdminConfig.save()
 print "Queue created successfuly.\n"
else:
 print "Server not reachable or not configured correctly."

Friday, May 29, 2009

A sample DB2 stored procedure

Introduction

I am not a database guy, but this one time I was cornered into writing a stored procedure on DB2 8.1. Below is the code which was written totally by googling around and painfully walking thru DB2 documentation. I am putting it here just a reference to stored proc syntax and DB2's basic control structs like if-else, while, using cursors etc.

Details

CREATE PROCEDURE SCHEMA_NAME.PROCEDURE1
        (IN VAR_DEPLOY_DESC VARCHAR(500),IN VAR_APP_DESC VARCHAR(100),IN VAR_SOA_LAYER VARCHAR(100),
        IN VAR_EVENT_DESC VARCHAR(500), IN VAR_SHORT_MESS VARCHAR(200), IN VAR_TIME_STP TIMESTAMP,
        IN VAR_STK_TRACE VARCHAR(10000), IN VAR_CONTEXT_THREAD VARCHAR(50),
        IN VAR_EXEC_DESC VARCHAR(500), IN VAR_METHOD_ID VARCHAR(10), IN VAR_PROG_LANG VARCHAR(20),
        IN VAR_REQ_IDENTITY VARCHAR(100), IN VAR_SESSION_ID VARCHAR(100),
        IN VAR_LINE_NO INTEGER)
language SQL

------------------------------------------------------------------------
-- SQL Stored Procedure
------------------------------------------------------------------------

--begin atomic apparently start a transaction. (Not a 100% sure if that what it means)
p1: begin atomic

DECLARE LOOP_COUNTER INTEGER DEFAULT 0;
DECLARE NAME1  VARCHAR(200);
DECLARE VALUE1  VARCHAR(200);
DECLARE cur_deploy_id BIGINT;
DECLARE deploy_id_exists CHAR(1) DEFAULT 'y';
DECLARE cur_event_id BIGINT;

--Cursors are used to hold the results of a select statement
DECLARE cursor1 CURSOR FOR
        SELECT DEPLOYMENT_ID FROM SCHEMA_NAME.RT_DEPLOYMENT WHERE DEPLOYMENT_NAME = VAR_DEPLOY_DESC;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET deploy_id_exists = 'n';
OPEN cursor1;
FETCH cursor1 INTO cur_deploy_id;

--If-else
IF  deploy_id_exists = 'n' THEN
        --Insert a new deploy ID
        insert into SCHEMA_NAME.RT_DEPLOYMENT (DEPLOYMENT_ID, DEPLOYMENT_NAME, APPLICATION_DESC, SOA_LAYER_DESC)
                values (default, VAR_DEPLOY_DESC,  VAR_APP_DESC, VAR_SOA_LAYER);
        set cur_deploy_id = IDENTITY_VAL_LOCAL();
END IF;


INSERT INTO SCHEMA_NAME.RT_EVENT
        (EVENT_ID, EVENT_DESC, SHORT_MESSAGE_DESC, EVENT_TSTP,
        STACK_TRACE_DESC, CONTEXT_THREAD_DESC, EXECUTABLE_DESC, METHOD_ID,
        PROGRAMMING_LANG_DESC, REQUESTING_IDENTITY_DESC, SESSION_ID, LINE_NO)
VALUES (DEFAULT, VAR_EVENT_DESC, VAR_SHORT_MESS, VAR_TIME_STP ,
        VAR_STK_TRACE, VAR_CONTEXT_THREAD, VAR_EXEC_DESC, VAR_EXEC_DESC,
       VAR_PROG_LANG, VAR_REQ_IDENTITY, VAR_SESSION_ID, VAR_LINE_NO );
set cur_event_id =  IDENTITY_VAL_LOCAL();

--While loop
WHILE (LOOP_COUNTER <= 3) DO
    SET NAME1 = 'name';
    SET VALUE1 = 'value';
    SET LOOP_COUNTER = LOOP_COUNTER + 1;
    INSERT INTO SCHEMA_NAME.RT_VALUE (VALUE_ID, EVENT_NAME, EVENT_VALUE) VALUES (DEFAULT, NAME1, VALUE1);
    INSERT INTO SCHEMA_NAME.RT_EVENT_RT_VALUE (EVENT_ID, VALUE_ID) VALUES (cur_event_id, IDENTITY_VAL_LOCAL());
END WHILE;


INSERT INTO SCHEMA_NAME.RT_DEPLOY_RT_EVENT (DEPLOYMENT_ID, EVENT_ID) VALUES ( cur_deploy_id, cur_event_id);

CLOSE cursor1;

END p1