Date Created: Mon 08-Nov-2010

Related Document Categories:

Get my WebSphere Application Server course here >> http://www.themiddlewareshop.com/products/


Websphere Jython Server Management Scripts

############################################################
# server-related methods
############################################################

#-------------------------------------------------------------------------------
# check if base or nd environment
#-------------------------------------------------------------------------------

def whatEnv():
"""Returns 'nd' if connected to a dmgr, 'base' if connected to
an unmanaged server, and 'other' if connected to something else
(which shouldn't happen but could)"""
m = "whatEnv:"

# Simpler version - should work whether connected or not
servers = getObjectsOfType('Server')
for server in servers:
servertype = getObjectAttribute(server, 'serverType')
if servertype == 'DEPLOYMENT_MANAGER':
return 'nd' # we have a deployment manager
return 'base' # no deployment manager, must be base

def createServer( nodename, servername, templatename = None, extraArgs = None ):
"""Create new app server, return its object id.
Specify a templatename of 'DeveloperServer' for a development server.
Specify extraArgs as a String in the format '-arg1 value1 -arg2 value2'.
These will be appended to the AdminTask.createApplicationServer call."""

# Append specified args to servername arg
args = ['-name %s' % (servername)]
if templatename:
args.append('-templateName %s' % (templatename))
if extraArgs:
args.append(extraArgs)

AdminTask.createApplicationServer( nodename, '[%s]' % ( ' '.join(args) ) )

return getServerByNodeAndName( nodename, servername )

def getServerByNodeAndName( nodename, servername ):
"""Return config id for a server"""
return getObjectByNodeAndName( nodename, 'Server', servername )

def getWebserverByNodeAndName( nodename, servername ):
"""Return config id for a webserver"""
m = "getWebserverByNodeAndName: "
sop(m,"Entry. nodename=%s servername=%s" % ( nodename, servername ))

# For some unknown reason, this method does not find attribute 'name'. So do it ugly...
# return getObjectByNodeAndName( nodename, 'WebServer', servername )

node_id = getNodeId(nodename)
sop(m,"node_id=%s" % ( node_id ))

search_string = "%s/servers/%s|server.xml#WebServer" % ( nodename, servername )
sop(m,"search_string=%s" % ( search_string ))

server_id_list = _splitlines(AdminConfig.list( "WebServer", node_id ))
for server_id in server_id_list:
sop(m,"server_id=%s" % ( server_id ))
if -1 != server_id.find(search_string):
sop(m,"Exit. Found webserver.")
return server_id
sop(m,"Exit. Did not find webserver.")
return None

def getApplicationServerByNodeAndName( nodename, servername ):
"""Return config id for an application server"""
server_id = getServerByNodeAndName(nodename,servername)
component_ids = AdminConfig.showAttribute(server_id, 'components')[1:-1].split(' ')
for id in component_ids:
i = id.find('#ApplicationServer')
if i != -1:
return id
return None


def getServerIDsForClusters (clusterList):
"""This functions returns the config ID, node name, and server name for the servers in the specified
clusters.

Input:

- clusterList - A list of cluster names. The config IDs for all cluster
members in all of the clusters in the list will be returned. Only unique
config IDs will be returned.

Output:

- A list of lists, where each element in the list is a list which consists of the following items:
- the server's config ID
- the server's node name
- the server's name

If the specified clusters do not exist or if the specified clusters do not contain
any members, an empty list will be returned.
"""

m = 'getServerIDsForClusters:'
sop(m, 'Entering function')

serverIDList = []

sop(m, 'Calling AdminConfig.list to get the list of clusters')
clusters = _splitlines(AdminConfig.list ('ServerCluster'))
sop(m, 'Got list of clusters')

for inClusterName in clusterList:
for cluster in clusters:

sop(m, 'Calling AdminConfig.showAttribute to get the cluster name')
thisClusterName = AdminConfig.showAttribute(cluster, 'name')
sop(m, 'Got cluster name')

if thisClusterName == inClusterName:

sop(m, 'Calling AdminConfig.showAttribute to get the list of members for cluster %s' % thisClusterName)
members = _splitlist(AdminConfig.showAttribute(cluster, 'members'))
sop(m, 'Got list of members for cluster %s' % thisClusterName)

for member in members:

sop(m, 'Calling AdminConfig.showAttribute to get the server name for the cluster member')
serverName = AdminConfig.showAttribute(member, 'memberName')
sop(m, 'Got the server name ("%s") for the cluster member' % serverName)

sop(m, 'Calling AdminConfig.showAttribute to get the node name for cluster member %s' % serverName)
nodeName = AdminConfig.showAttribute(member, 'nodeName')
sop(m, 'Got the node name ("%s") for cluster member %s' % (nodeName, serverName))

sop(m, 'Calling getServerId() with nodeName=%s and serverName=%s' % (nodeName, serverName))
serverID = getServerId(nodeName, serverName)
sop(m, 'Returned from getServerId(). Returned serverID = %s' % serverID)

if serverID != None:
dup = 'false'
for currentServerID in serverIDList:
if currentServerID == serverID:
dup = 'true'
break
#endif
#endfor
if dup == 'false':
serverIDList.append( (serverID, nodeName, serverName) )
sop(m, 'Added config ID for server %s on node %s to output list' % (serverName, nodeName))
#endif
#endif
#endfor
#endif
#endfor
#endfor

sop(m, 'Exiting function')
return serverIDList
#enddef


def getServerIDsForAllAppServers ():
"""This functions returns the config ID, node name, and server name for all application servers
in the cell.

Input:

- None

Output:

- A list of lists, where each element in the list is a list which consists of the following items:
- the server's config ID
- the server's node name
- the server's name

If there are no application servers in the cell, an empty list will be returned.
"""

m = 'getServerIDsForAllAppServers:'
sop(m, 'Entering function')

serverIDList = []

sop(m, 'Calling AdminConfig.list to get the config ID for the cell.')
cell = AdminConfig.list("Cell")
sop(m, 'Got the config ID for the cell.')

sop(m, 'Calling AdminConfig.list to get the list of nodes.')
nodes = _splitlines(AdminConfig.list('Node', cell))
sop(m, 'Got the list of nodes.')

for node in nodes:

sop(m, 'Calling AdminConfig.showAttribute to get the node name')
nodeName = AdminConfig.showAttribute(node, 'name')
sop(m, 'Got the node name ("%s")' % nodeName)

sop(m, 'Calling AdminConfig.list to get the list of servers.')
servers = _splitlines(AdminConfig.list('Server', node))
sop(m, 'Got the list of servers')

for server in servers:

sop(m, 'Calling AdminConfig.showAttribute to get the server name')
serverName = AdminConfig.showAttribute(server, 'name')
sop(m, 'Got server name ("%s")' % serverName)

sop(m, 'Calling AdminConfig.showAttribute to get the server type')
serverType = AdminConfig.showAttribute(server, 'serverType')
sop(m, 'Got server type. Server type for server %s = %s.' % (serverName, serverType))

if serverType == 'APPLICATION_SERVER':
serverIDList.append( (server, nodeName, serverName) )
sop(m, 'Added config ID for server %s on node %s to output list' % (serverName, nodeName))
#endif
#endfor
#endfor

sop(m, 'Exiting function')
return serverIDList
#enddef


def deleteServerByNodeAndName( nodename, servername ):
"""Delete the named server - raises exception on error"""
sid = getServerByNodeAndName( nodename, servername )
if not sid:
raise "Could not find server %s to delete" % servername
AdminTask.deleteServer( '[-serverName %s -nodeName %s ]' % ( servername, nodename ) )

def deleteServersOfType( typeToDelete ):
"""Delete all servers of the given type.
Typical type values are 'APPLICATION_SERVER' and 'PROXY_SERVER'.
Raises exception on error (passes through exception from stopServer())"""
# Go through one node at a time - can't figure out any way to
# find out what node a server is in from the Server or ServerEntry
# object
m = "deleteServersOfType:"
nodes = _splitlines(AdminConfig.list( 'Node' ))
cellname = getCellName()
for node_id in nodes:
nodename = getNodeName(node_id)
serverEntries = _splitlines(AdminConfig.list( 'ServerEntry', node_id ))
for serverEntry in serverEntries:
sName = AdminConfig.showAttribute( serverEntry, "serverName" )
sType = AdminConfig.showAttribute( serverEntry, "serverType" )
if sType == typeToDelete:
sid = AdminConfig.getid( "/Cell:%s/Node:%s/Server:%s/" % ( cellname, nodename, sName ) )
sop(m,"Deleting server %s with sid %s" % ( sName, sid ))
stopServer( nodename, sName )

AdminTask.deleteServer( '[-serverName %s -nodeName %s ]' % ( sName, nodename ) )
else:
sop(m,"Not deleting server %s on node %s - has type %s instead of %s" % (sName,nodename,sType,typeToDelete))

def deleteAllApplicationServers():
"""Delete all application servers - raises exception on error"""
deleteServersOfType( 'APPLICATION_SERVER' )

def deleteAllProxyServers():
"""Delete all proxy servers - raises exception on error"""
deleteServersOfType( "PROXY_SERVER" )

def listAllServersProxiesLast():
"""return a list of all servers, EXCEPT node agents or
deployment managers, as a list of lists, with all proxies at the end of the list.
E.g. [['nodename','proxyname'], ['nodename','proxyname']].
Typical usage:
for (nodename,servername) in listAllServers():
callSomething(nodename,servername)
"""
m = "listAllServersProxiesLast:"
all = listServersOfType(None)
proxies = []
result = []
for (nodename,servername) in all:
stype = getServerType(nodename,servername)
# sometimes, dmgr has no type... who knows why
if stype != None and stype == 'PROXY_SERVER':
#sop(m,"Saving proxy in proxies %s %s" % ( nodename,servername ))
proxies.append( [nodename,servername] )
else:
if stype != None and stype != 'DEPLOYMENT_MANAGER' and stype != 'NODE_AGENT':
#sop(m,"Saving non-proxy in result %s %s" % ( nodename,servername ))
result.append( [nodename,servername] )

for (nodename,servername) in proxies:
#stype = getServerType(nodename,servername)
#sop(m,"listAllServersProxiesLast: Adding proxy to result: nodename=%s/servername=%s: stype=%s" % (nodename,servername,stype))
result.append( [nodename,servername] )

return result

def listAllAppServers():
"""return a list of all servers, EXCEPT node agents,
deployment managers or webservers as a list of lists.
E.g. [['nodename','proxyname'], ['nodename','proxyname']].
Typical usage:
for (nodename,servername) in listAllAppServers():
callSomething(nodename,servername)
"""
m = "listAllAppServers:"
all = listServersOfType(None)
result = []
for (nodename,servername) in all:
stype = getServerType(nodename,servername)
# sometimes, dmgr has no type... who knows why
if stype != None and stype != 'DEPLOYMENT_MANAGER' and stype != 'NODE_AGENT' and stype != 'WEB_SERVER':
#sop(m,"%s/%s: %s" % (nodename,servername,stype))
result.append( [nodename,servername] )
return result

def listAllServers():
"""return a list of all servers, EXCEPT node agents or
deployment managers, as a list of lists.
E.g. [['nodename','proxyname'], ['nodename','proxyname']].
Typical usage:
for (nodename,servername) in listAllServers():
callSomething(nodename,servername)
"""
m = "listAllServers:"
all = listServersOfType(None)
result = []
for (nodename,servername) in all:
stype = getServerType(nodename,servername)
# sometimes, dmgr has no type... who knows why
if stype != None and stype != 'DEPLOYMENT_MANAGER' and stype != 'NODE_AGENT':
#sop(m,"%s/%s: %s" % (nodename,servername,stype))
result.append( [nodename,servername] )
return result

def listServersOfType(typename):
"""return a list of servers of a given type as a list of lists.
E.g. [['nodename','proxyname'], ['nodename','proxyname']].
Typical usage:
for (nodename,servername) in listServersOfType('PROXY_SERVER'):
callSomething(nodename,servername)
Set typename=None to return all servers.
"""
# Go through one node at a time - can't figure out any way to
# find out what node a server is in from the Server or ServerEntry
# object
result = []
node_ids = _splitlines(AdminConfig.list( 'Node' ))
cellname = getCellName()
for node_id in node_ids:
nodename = getNodeName(node_id)
serverEntries = _splitlines(AdminConfig.list( 'ServerEntry', node_id ))
for serverEntry in serverEntries:
sName = AdminConfig.showAttribute( serverEntry, "serverName" )
sType = AdminConfig.showAttribute( serverEntry, "serverType" )
if typename == None or sType == typename:
result.append([nodename, sName])
return result

def getServerType(nodename,servername):
"""Get the type of the given server.
E.g. 'APPLICATION_SERVER' or 'PROXY_SERVER'."""
node_id = getNodeId(nodename)
serverEntries = _splitlines(AdminConfig.list( 'ServerEntry', node_id ))
for serverEntry in serverEntries:
sName = AdminConfig.showAttribute( serverEntry, "serverName" )
if sName == servername:
return AdminConfig.showAttribute( serverEntry, "serverType" )
return None

def listUnclusteredServers():
"""Return a list of app servers that don't belong to clusters, as a list of lists
(see listServersOfType)"""
allServers = listServersOfType('APPLICATION_SERVER')
result = []
for (nodename,servername) in allServers:
server_id = getServerByNodeAndName(nodename,servername)
clusterName = AdminConfig.showAttribute(server_id, 'clusterName')
if clusterName == None:
result.append([nodename,servername])
return result

def startUnclusteredServers():
"""Start servers that aren't part of a cluster - raises exception on error"""
serverlist = listUnclusteredServers()
for (nodename,servername) in serverlist:
startServer(nodename,servername)

def stopUnclusteredServers():
"""Stop servers that aren't part of a cluster - raises exception on error"""
serverlist = listUnclusteredServers()
for (nodename,servername) in serverlist:
stopServer(nodename,servername)

def listProxyServers():
"""return a list of proxy servers as a list of lists.
E.g. [['nodename','proxyname'], ['nodename','proxyname']].
Typical usage:
for (nodename,proxyname) in listProxyServers():
callSomething(nodename,proxyname)
"""
return listServersOfType("PROXY_SERVER")

def startAllProxyServers():
"""start proxies - raises exception on error"""
proxylist = listProxyServers()
for (nodename,proxyname) in proxylist:
startServer(nodename,proxyname)

def stopAllProxyServers():
"""stop proxies - raises exception on error"""
proxylist = listProxyServers()
for (nodename,proxyname) in proxylist:
stopServer(nodename,proxyname)

def stopAllServers(exceptfor=[]):
"""Stop every server, except node agent or deployment manager - raises exception on error
If exceptfor is specified, it's a list of [nodename,servername]s to skip"""
serverlist = listAllServers()
for (nodename,servername) in serverlist:
if [nodename,servername] not in exceptfor:
stopServer(nodename,servername)

def startAllServers(exceptfor=[], waitAfterStartSeconds=0):
"""Start every server, except node agent or deployment manager - raises exception on error.
If exceptfor is specified, it's a list of [nodename,servername]s to skip.
Parameter waitAfterStartSeconds specifies time to wait between starting servers."""
m = "startAllServers: "
serverlist = listAllServersProxiesLast()
for (nodename,servername) in serverlist:
if [nodename,servername] not in exceptfor:
startServer(nodename,servername)
if waitAfterStartSeconds > 0:
sop(m,"Sleeping %i seconds." % ( waitAfterStartSeconds ))
time.sleep(waitAfterStartSeconds)

def isServerRunning(nodename,servername):
"""Returns a boolean to say if the server is running.
Not 100% accurate but should be close - relies on there only being an mbean for
a server if it's running"""
mbean = AdminControl.queryNames('type=Server,node=%s,name=%s,*' % (nodename,servername))
if mbean:
return True
return False

def startWebServer( nodename, servername):
""" Starts the specified webserver """
m = "startWebServer: "
sop(m,"Entry.")
sop(m,"Got arguments: nodename=%s, servername=%s" % (nodename,servername))
mbean = AdminControl.queryNames('WebSphere:type=WebServer,*')
sop(m,mbean)
cell = AdminControl.getCell()
sop(m,cell)
webServerUp = AdminControl.invoke(mbean,'start','[%s %s %s]' % (cell,nodename,servername),'[java.lang.String java.lang.String java.lang.String]')
sop(m,webServerUp)

def stopWebServer( nodename, servername):
""" Stops the specified webserver """
m = "stopWebServer: "
sop(m,"Entry.")
sop(m,"Got arguments: nodename=%s, servername=%s" % (nodename,servername))
mbean = AdminControl.queryNames('WebSphere:type=WebServer,*')
sop(m,mbean)
cell = AdminControl.getCell()
sop(m,cell)
webServerDown = AdminControl.invoke(mbean,'stop','[%s %s %s]' % (cell,nodename,servername),'[java.lang.String java.lang.String java.lang.String]')
sop(m,webServerDown)

# Global variable defines extra time to wait for a server to start, in seconds.
waitForServerStartSecs = 300

def setWaitForServerStartSecs(val):
"""Sets global variable used to wait for servers to start, in seconds."""
global waitForServerStartSecs
waitForServerStartSecs = val

def getWaitForServerStartSecs():
"""Returns the global variable used to wait for servers to start, in seconds."""
global waitForServerStartSecs
return waitForServerStartSecs

def startServer( nodename, servername ):
"""Start the named server - raises exception on error.
Uses global variable waitForServerStartSeconds"""
# Check first if it's already running - if we try to start it
# when it's running, we get an exception and sometimes the
# try/except below doesn't catch it, I don't know why
m = "startServer:"
if isServerRunning(nodename,servername):
sop(m,"server %s,%s is already running" % (nodename,servername))
else:
sop(m,"starting server %s,%s" % (nodename,servername))
try:
sop(m,"startServer(%s,%s)" % ( servername, nodename ))
# optional the 3rd arg is seconds to wait for startup - the default
# is 1200 (according to 6.1 infocenter) e.g. 20 minutes,
# which you'd think would be enough for anybody...
# But it actually doesn't seem to work that way, so put an explicit
# and long wait time.
# But if we put 3600, we get a SOAP timeout... going back
# to 120 for now
AdminControl.startServer( servername, nodename, 120)

# Calculate the number of 15-second cycles to wait, minimum 1.
global waitForServerStartSecs
waitRetries = waitForServerStartSecs / 15
if waitRetries < 1:
waitRetries = 1
retries = 0
while not isServerRunning(nodename,servername) and retries < waitRetries:
sop(m,"server %s,%s not running yet, waiting another 15 secs" % (nodename,servername))
time.sleep(15) # seconds
retries += 1
if not isServerRunning(nodename,servername) :
sop(m,"server %s,%s STILL not running, giving up" % (nodename,servername))
raise Exception("SERVER FAILED TO START %s,%s" % (nodename,servername))

except:
# Fails if server already started - ignore it
( exception, parms, tback ) = sys.exc_info()
if -1 != repr( parms ).find( "already running" ):
return # ignore it
# Some other error? scream and shout
sop(m,"EXCEPTION STARTING SERVER %s" % servername)
sop(m,"Exception=%s\nPARMS=%s" % ( str( exception ), repr( parms ) ))
raise Exception("EXCEPTION STARTING SERVER %s: %s %s" % (servername, str(exception),str(parms)))

def stopServer( nodename, servername, immediate=False ):
"""Stop the named server - raises exception on error"""
m = "stopServer:"
if not isServerRunning(nodename,servername):
sop(m,"server %s,%s is already stopped" % (nodename,servername))
else:
sop(m,"stopping server %s,%s" % (nodename,servername))
try:
if immediate:
AdminControl.stopServer( servername, nodename, 'immediate' )
else:
AdminControl.stopServer( servername, nodename )
except:
# Fails if server not running - ignore it
( exception, parms, tback ) = sys.exc_info()
if -1 != repr( parms ).find( "Unable to locate running server" ):
return # ignore it
# Some other error? scream and shout
sop(m,"EXCEPTION STOPPING SERVER %s" % servername)
sop(m,"Exception=%s\nPARMS=%s" % ( str( exception ), repr( parms ) ))
raise Exception("EXCEPTION STOPPING SERVER %s: %s %s" % (servername, str(exception),str(parms)))

def getApplicationServerCustomProperty(nodename, servername, propname):
"""Return the VALUE of the specified custom property of the application server, or None if there is none by that name."""
server = getApplicationServerByNodeAndName(nodename,servername)
return getObjectCustomProperty(server,propname)

def setApplicationServerCustomProperty( nodename, servername, propname, propvalue ):
"""Sets the specified server setting custom property."""
m = "setApplicationServerCustomProperty:"
sop(m,"Entry. nodename=%s servername=%s propname=%s propvalue=%s" % ( repr(nodename), repr(servername), repr(propname), repr(propvalue), ))

server_id = getApplicationServerByNodeAndName(nodename,servername)
setCustomPropertyOnObject(server_id, propname, propvalue)
sop(m,"Exit.")

def restartServer( nodename, servername, maxwaitseconds, ):
"""Restarts a server or proxy JVM

This is useful to restart standalone servers after they have been configured.
Raises an exception if the server is not already running.
Waits up to the specified max number of seconds for the server to stop and restart.
Returns True or False to indicate whether the server is running"""
m = "restartServer: "
sop(m,"Entry. nodename=%s servername=%s maxwaitseconds=%d" % (nodename, servername, maxwaitseconds, ))

if not isServerRunning( nodename, servername ):
raise m + "ERROR: Server is not already running. nodename=%s servername=%s" % (nodename, servername, )
sop(m,"Server %s is running." % ( servername, ))

# Get the server mbean
serverObjectName = AdminControl.completeObjectName('type=Server,node=%s,process=%s,*' % ( nodename, servername ,))
sop(m,"Invoking restart on server. serverObjectName=%s" % ( serverObjectName, ))

# Restart the server.
AdminControl.invoke(serverObjectName, 'restart')

# Wait up to a max timeout if requested by the caller.
elapsedtimeseconds = 0
if maxwaitseconds > 0:
sleeptimeseconds = 5

# Phase 1 - Wait for server to stop (This can take 30 seconds on a reasonably fast linux intel box)
isRunning = isServerRunning( nodename, servername )
while isRunning and elapsedtimeseconds < maxwaitseconds:
sop(m,"Waiting %d of %d seconds for %s to stop. isRunning=%s" % ( elapsedtimeseconds, maxwaitseconds, servername, isRunning, ))
time.sleep( sleeptimeseconds )
elapsedtimeseconds = elapsedtimeseconds + sleeptimeseconds
isRunning = isServerRunning( nodename, servername )

# Phase 2 - Wait for server to start (This can take another minute)
while not isRunning and elapsedtimeseconds < maxwaitseconds:
sop(m,"Waiting %d of %d seconds for %s to restart. isRunning=%s" % ( elapsedtimeseconds, maxwaitseconds, servername, isRunning, ))
time.sleep( sleeptimeseconds )
elapsedtimeseconds = elapsedtimeseconds + sleeptimeseconds
isRunning = isServerRunning( nodename, servername )

isRunning = isServerRunning( nodename, servername )
sop(m,"Exit. nodename=%s servername=%s maxwaitseconds=%d elapsedtimeseconds=%d Returning isRunning=%s" % (nodename, servername, maxwaitseconds, elapsedtimeseconds, isRunning ))
return isRunning

def extractConfigProperties( nodename, servername, propsfilename, ):
"""Converts the server configuration from xml files to a flat properties file"""
m = "extractConfigProperties:"
# TODO: Figure out how to specify the node name...
arglist = ['-propertiesFileName',propsfilename,'-configData','Server=%s' % ( servername )]
sop(m,"Calling AdminTask.extractConfigProperties() with arglist=%s" % ( arglist ))
return AdminTask.extractConfigProperties( arglist )

def applyConfigProperties( propsfilename, reportfilename ):
""" Converts a flat properties config file into an xml configuration."""
m = "applyConfigProperties:"
argstring = "[-propertiesFileName %s -reportFileName %s]" % ( propsfilename, reportfilename )
sop(m,"Calling AdminTask.applyConfigProperties() with argstring=%s" % ( argstring ))
return AdminTask.applyConfigProperties( argstring )

Get my WebSphere Application Server course here >> http://www.themiddlewareshop.com/products/


Steve Robinson - IBM Champion 2013

About Me

Steve Robinson has been working in IT for over 20 years and has provided solutions for many large-enterprise corporate companies across the world. Steve specialises in Java and Middleware.

In January 2013, I was awarded the prestigous 'IBM Champion' accolade.


  • Linked In
  • Twitter
  • About Me
  • My Blog
  • Contact Me

Read my books?

IBM WebSphere Application Server 8.0 Administration Guide

IBM WebSphere Application Server 8.0 Administration Guide

WebSphere Application Server 7.0 Administration Guide

WebSphere Application Server 7.0 Administration Guide

WebSphere Categories

Other Categories