Hi I need to know if the application is running partially. using the following command I am able to get info if the application is running.
serverstatus = AdminControl.completeObjectName('type=Application,name='+n1+',*')
print serverstatus
Is there any other was to check if the current status of application is partially running.??
Regards
Snehan Solomon
In order to accurately determine whether the application is partially started/stopped, you must first determine the deployment targets against which the application is deployed, and then determine whether or not the application is running on that server:
def isApplicationRunning(applicationName, serverName, nodeName) :
return AdminControl.completeObjectName("type=Application,name=%s,process=%s,node=%s,*" % (applicationName, serverName, nodeName)) != ""
def printApplicationStatus(applicationName) :
servers = started = 0
targets = AdminApplication.getAppDeploymentTarget(applicationName)
for target in targets :
type = AdminConfig.getObjectType(target)
if (type == "ClusteredTarget") :
clusterName = AdminConfig.showAttribute(target, "name")
members = AdminUtilities.convertToList(AdminConfig.getid("/ServerCluster:%s/ClusterMember:/" % clusterName))
for member in members :
serverName = AdminConfig.showAttribute(target, "name")
nodeName = AdminConfig.showAttribute(member, "nodeName")
started += isApplicationRunning(applicationName, serverName, nodeName)
servers += 1
elif (type == "ServerTarget") :
serverName = AdminConfig.showAttribute(target, "name")
nodeName = AdminConfig.showAttribute(target, "nodeName")
started += isApplicationRunning(applicationName, serverName, nodeName)
servers += 1
if (started == 0) :
print "The application [%s] is NOT RUNNING." % applicationName
elif (started != servers) :
print "The application [%s] is PARTIALLY RUNNING." % applicationName
else :
print "The application [%s] is RUNNING." % applicationName
if (__name__ == "__main__"):
printApplicationStatus(sys.argv[0]);
Note that the AdminApplication script library only exists for WAS 7+, so if you are running an older version, you will need to obtain the deployment targets yourself.
I was able to get the partial status of application based on the number of nodes. I just hardcoded the number of nodes and then compared them against the number of MBeans they returned.
import sys
appName = sys.argv[0]
appCount=0
nodeCount=2
appMBeans = AdminControl.queryNames('type=Application,name='+appName+',*').split("\n")
for mbean in appMBeans:
if mbean != "":
appCount=appCount+1
print "Count of Applications is %s" %(appCount)
if appCount == 0:
print "----!!!ALERT!!!!---- The Application "+appName+" is Not Running"
elif appCount > 0 and appCount < nodeCount:
print "----!!!ALERT!!!!---- The Application "+appName+" is Partially Running"
elif appCount == nodeCount:
print "The Application "+appName+" is Running"
Related
Hi I am trying to run a schedule script, not via lambda but from a pc or onsite schedule job - maybe every 10 mins or so to check all my ec2 instances are failing any system/instance status checks. If it fails then send email of the ec2 instance that failing - just send the name. Do not reboot
so here is what i have
import boto3
import smtplib
region_name='us-west-1'
#ec2_client = boto3.client('ec2')
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
#response = ec2_client.describe_instance_status(IncludeAllInstances = True)
client = boto3.client("ec2")
clientsns = boto3.client("sns")
#response = clientsns.create_topic
status = client.describe_instance_status(IncludeAllInstances = True)
#for instance in response['InstanceStatuses']:
# instance_id = instance['InstanceId']
# system_status = instance['SystemStatus']
# instance_status = instance['InstanceStatus']
# print (instance_id, system_status, instance_status)
for i in status["InstanceStatuses"]:
print("AvailabilityZone :", i["AvailabilityZone"])
print("InstanceId :", i["InstanceId"])
print("InstanceState :", i["InstanceState"])
print("InstanceStatus", i["InstanceStatus"])
print("SystemStatus", i["SystemStatus"])
in_status = i['InstanceStatus']['Details'][0]['Status']
sys_status = i['SystemStatus']['Details'][0]['Status']
msg1 = 'The following instances failed status checks, i[{InstanceId}]'
msg2 = 'All Instances passed System/instance checks!'
# check statuses
if ((in_status != 'passed') or (sys_status != 'passed')):
print(bcolors.WARNING + 'Reboot required for', i["InstanceId"] + bcolors.ENDC)
clientsns.publish(TopicArn='arn:aws:sns:us-west-1:462518063038:test',Message=msg1)
else:
print('All Instances passed System/instance checks!')
clientsns.publish(TopicArn='arn:aws:sns:us-west-1:462518063038:test',Message=msg2)
The problem I have is its sending one message per instance. I just wwant to sent one email for all instances. any idea?
Thank you
I have used this website over a hundred times and it has helped me so much with my coding (in python, arduino, terminal commands and Window's prompt). I thought I would put up some knowledge that I found, for things that Stack overflow could not help me with but my be helpful for others in a similar situation. So have a look at the code below. I hope if helps people with creating their own backup code. I am most proud with the "while '\r\n' in output" part of the below code. :
output = child0.readline()
while '\r\n' in output:
msg.log(output.replace('\r\n', ''), logMode + 's')
output = child0.readline()
This helps find the EOF when the program has finished running. Hence you can output the terminal program's output as the program is running.
I will be adding a Windows version to this code too. Possibly with robocopy.
Any questions with the below code, please do not hesitate to ask. NB: I changed people's names and removed my username and passwords.
#!/usr/bin/python
# Written by irishcream24, amateur coder
import subprocess
import sys
import os.path
import logAndError # my own library to handle errors and log events
from inspect import currentframe as CF # help with logging
from inspect import getframeinfo as GFI # help with logging
import threading
import fcntl
import pexpect
import time
import socket
import time as t
from sys import platform
if platform == "win32":
import msvcrt
portSearch = "Uno"
portResultPosition = 1
elif platform == "darwin":
portSearch = "usb"
portResultPosition = 0
else:
print 'Unknown operating system'
print 'Ending Program...'
sys.exit()
# Check if another instance of the program is running, if so, then stop second.
pid_file = 'program.pid'
fp = open(pid_file, 'w')
try:
fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
# another instance is running
print "Program already running, stopping the second instance..."
sys.exit(1)
# Determine where main program files are stored
directory = os.path.dirname(os.path.realpath(__file__))
# To print stderr to both screen and file
errCounter = 0
exitFlag = [0]
class tee:
def __init__(self, _fd1, _fd2):
self.fd1 = _fd1
self.fd2 = _fd2
def __del__(self):
if self.fd1 != sys.stdout and self.fd1 != sys.stderr :
self.fd1.close()
if self.fd2 != sys.stdout and self.fd2 != sys.stderr :
self.fd2.close()
def write(self, text):
global errCounter
global exitFlag
if errCounter == 0:
self.fd1.write('%s: ' %t.strftime("%d/%m/%y %H:%M"))
self.fd2.write('%s: ' %t.strftime("%d/%m/%y %H:%M"))
errCounter = 1
exitFlag[0] = 1
self.fd1.write(text)
self.fd2.write(text)
def flush(self):
self.fd1.flush()
self.fd2.flush()
# Error and log handling
errMode = 'pf' # p = print to screen, f = print to file, e = end program
errorFileAddress = '%s/errorFile.txt' %directory
outputlog = open(errorFileAddress, "a")
sys.stderr = tee(sys.stderr, outputlog)
logFileAddress = '%s/log.txt' %directory
logMode = 'pf' # p = print to screen, f = print to file
msg = logAndError.logAndError(errorFileAddress, logFileAddress)
# Set computer to be backed up
sourceComputer = 'DebbieMac'
try:
sourceComputer = sys.argv[1]
except:
print 'No source argument given.'
if sourceComputer == 'SamMac' or sourceComputer == 'DebbieMac' or sourceComputer == 'mediaCentre' or sourceComputer == 'garageComputer':
pass
else:
msg.error('incorrect source computer supplied!', errMode, GFI(CF()).lineno, exitFlag)
sys.exit()
# Source and destination setup
backupRoute = 'network'
try:
backupRoute = sys.argv[2]
except:
print 'No back up route argument given.'
if backupRoute == 'network' or backupRoute == 'direct' or backupRoute == 'testNetwork' or backupRoute == 'testDirect':
pass
else:
msg.error('incorrect backup route supplied!', errMode, GFI(CF()).lineno, exitFlag)
sys.exit()
# Source, destination and exclude dictionaries
v = {
'SamMac network source' : '/Users/SamJones',
'SamMac network destination' : '/Volumes/Seagate/Sam_macbook_backup/Backups',
'SamMac direct source' : '/Users/SamJones',
'SamMac direct destination' : '/Volumes/Seagate\ Backup\ Plus\ Drive/Sam_macbook_backup/Backups',
'SamMac testNetwork source' : '/Users/SamJones/Documents/Arduino/arduino_sketches-master',
'SamMac testNetwork destination' : '/Volumes/Seagate/Sam_macbook_backup/Arduino',
'SamMac exclude' : ['.*', '.Trash', 'Library', 'Pictures'],
'DebbieMac network source' : '/Users/DebbieJones',
'DebbieMac network destination' : '/Volumes/Seagate/Debbie_macbook_backup/Backups',
'DebbieMac direct source' : '/Users/DebbieJones',
'DebbieMac direct destination' : '/Volumes/Seagate\ Backup\ Plus\ Drive/Debbie_macbook_backup/Backups',
'DebbieMac testNetwork source': '/Users/DebbieJones/testFolder',
'DebbieMac testNetwork destination' : '/Volumes/Seagate/Debbie_macbook_backup',
'DebbieMac testDirect source' : '/Users/DebbieJones/testFolder',
'DebbieMac testDirect destination' : '/Volumes/Seagate\ Backup\ Plus\ Drive/Debbie_macbook_backup',
'DebbieMac exclude' : ['.*', '.Trash', 'Library', 'Pictures']
}
# Main threading code
class mainThreadClass(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
PIDMessage = 'Starting backup PID: %s'%os.getpid()
msg.log(PIDMessage, logMode)
mainThread()
msg.log('Process completed successfully\n', logMode)
def mainThread():
if platform == "win32":
pass
elif platform == "darwin":
if 'network' in backupRoute:
# Connect to SeagateBackup
if os.path.ismount('/Volumes/Seagate') == False:
msg.log('Mounting Seagate Backup Hub', logMode)
commandM = 'mount volume'
smbPoint = '"smb://username:password#mediacentre/Seagate"'
childM = pexpect.spawn("%s '%s %s'" %('osascript -e', commandM, smbPoint), timeout = None)
childM.expect(pexpect.EOF)
else:
msg.log('Seagate already mounted', logMode)
# Use rsync to backup files
commandR = 'rsync -avb '
for s in v['%s exclude' %sourceComputer]:
commandR = commandR + "--exclude '%s' " %s
commandR = commandR + '--delete --backup-dir="../PreviousBackups/%s" ' %time.strftime("%d-%m-%y %H%M")
commandR = commandR + '%s %s' %(v['%s %s source' %(sourceComputer, backupRoute)], v['%s %s destination' %(sourceComputer, backupRoute)])
msg.log(commandR, logMode)
msg.log('Running rsync...rsync output below', logMode)
child0 = pexpect.spawn(commandR, timeout = None)
# Handling command output
# If no '\r\n' in readline() output, then EOF reached
output = child0.readline()
while '\r\n' in output:
msg.log(output.replace('\r\n', ''), logMode + 's')
output = child0.readline()
return
if __name__ == '__main__':
# Create new threads
threadMain = mainThreadClass()
# Start new Threads
threadMain.start()
logAndError.py
# to handle errors
import time
import sys
import threading
class logAndError:
def __init__(self, errorAddress, logAddress):
self.errorAddress = errorAddress
self.logAddress = logAddress
self.lock = threading.RLock()
def error(self, message, errMode, lineNumber=None, exitFlag=[0]):
message = '%s: %s' %(time.strftime("%d/%m/%y %H:%M"), message)
# p = print to screen, f = print to file, e = end program
if 'p' in errMode:
print message
if 'f' in errMode and 'e' not in errMode:
errorFile = open(self.errorAddress, 'a')
errorFile.write('%s\n' %message)
errorFile.close()
return
def log(self, logmsg, logMode):
with self.lock:
logmsg2 = '%s: %s' %(time.strftime("%d/%m/%y %H:%M"), logmsg)
if 'p' in logMode:
# s = simple (no date stamp)
if 's' in logMode:
print logmsg
else:
print logmsg2
if 'f' in logMode:
if 's' in logMode:
logFile = open(self.logAddress, 'a')
logFile.write('%s\n' %logmsg)
logFile.close()
else:
logFile = open(self.logAddress, 'a')
logFile.write('%s\n' %logmsg2)
logFile.close()
return
When LLDB triggers breakpoint X, is there a command that will disable or remove X and then continue?
That's an interesting idea. There's no built in command to do this in lldb but it would be easy to implement as a user-defined command written in Python. SBThread::GetStopReason() will be eStopReasonBreakpoint if that thread stopped because of a breakpoint. SBThread::GetStopReasonDataCount() will return 2 -- indicating that the breakpoint id and location id are available. SBThread::GetStopReasonDataAtIndex(0) will give you the breakpoint ID, SBThread::GetStopReasonDataAtIndex(1) will give you the location ID. (a single user-specified breakpoint may resolve to multiple locations. e.g. an inlined function, or a function name that occurs in multiple libraries in a single program.)
Here's a quick & dirty example of a python command that does this. I put this in ~/lldb where I save my lldb user-defined commands and then in my ~/.lldbinit file I have a line like command script import ~/lldb/disthis.py.
In use, it looks like this:
% lldb a.out
(lldb) target create "a.out"
Current executable set to 'a.out' (x86_64).
(lldb) br s -n main
Breakpoint 1: where = a.out`main + 15 at a.c:4, address = 0x0000000100000f4f
(lldb) r
Process 67487 launched: '/private/tmp/a.out' (x86_64)
Process 67487 stopped
* thread #1: tid = 0x290c51, 0x0000000100000f4f a.out`main + 15 at a.c:4, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
#0: 0x0000000100000f4f a.out`main + 15 at a.c:4
1 #include <stdio.h>
2 int main()
3 {
-> 4 puts ("HI");
5 puts ("HI");
6 }
(lldb) com scr imp ~/lldb/disthis.py
(lldb) disthis
Breakpoint 1.1 disabled.
(lldb) br li
Current breakpoints:
1: name = 'main', locations = 1
1.1: where = a.out`main + 15 at a.c:4, address = 0x0000000100000f4f, unresolved, hit count = 1 Options: disabled
(lldb)
Pretty straightforward.
# import this into lldb with a command like
# command script import disthis.py
import lldb
def disthis(debugger, command, *args):
"""Usage: disthis
Disables the breakpoint the currently selected thread is stopped at."""
target = None
thread = None
if len(args) == 2:
# Old lldb invocation style
result = args[0]
if debugger and debugger.GetSelectedTarget() and debugger.GetSelectedTarget().GetProcess():
target = debugger.GetSelectedTarget()
process = target.GetProcess()
thread = process.GetSelectedThread()
elif len(args) == 3:
# New (2015 & later) lldb invocation style where we're given the execution context
exe_ctx = args[0]
result = args[1]
target = exe_ctx.GetTarget()
thread = exe_ctx.GetThread()
else:
print "Unknown python function invocation from lldb."
return
if thread == None:
print >>result, "error: process is not paused, or has not been started yet."
result.SetStatus (lldb.eReturnStatusFailed)
return
if thread.GetStopReason() != lldb.eStopReasonBreakpoint:
print >>result, "error: not stopped at a breakpoint."
result.SetStatus (lldb.eReturnStatusFailed)
return
if thread.GetStopReasonDataCount() != 2:
print >>result, "error: Unexpected number of StopReasonData returned, expected 2, got %d" % thread.GetStopReasonDataCount()
result.SetStatus (lldb.eReturnStatusFailed)
return
break_num = thread.GetStopReasonDataAtIndex(0)
location_num = thread.GetStopReasonDataAtIndex(1)
if break_num == 0 or location_num == 0:
print >>result, "error: Got invalid breakpoint number or location number"
result.SetStatus (lldb.eReturnStatusFailed)
return
bkpt = target.FindBreakpointByID (break_num)
if location_num > bkpt.GetNumLocations():
print >>result, "error: Invalid location number"
result.SetStatus (lldb.eReturnStatusFailed)
return
bkpt_loc = bkpt.GetLocationAtIndex(location_num - 1)
if bkpt_loc.IsValid() != True:
print >>result, "error: Got invalid BreakpointLocation"
result.SetStatus (lldb.eReturnStatusFailed)
return
bkpt_loc.SetEnabled(False)
print >>result, "Breakpoint %d.%d disabled." % (break_num, location_num)
return
def __lldb_init_module (debugger, dict):
debugger.HandleCommand('command script add -f %s.disthis disthis' % __name__)
I'm working on a Windows 8 mock-up OS for Computercraft, and my log in system isn't working. I have been trying to figure it out for the past hour or so and it's really frustrating.
Here's the log in code:
-- Log-in and User Definition Service
--- Variables
userExists = fs.exists("/Users/.config/userConfig.cfg")
termx, termy = term.getSize()
halfx = math.floor(termx*0.5)
halfy = math.floor(termy*0.5)
prompt = "Welcome"
uprompt = "Username: "
pprompt = "Password: "
userConfig = fs.open("/Users/.config/userConfig.cfg", "r")
edituserConfig = fs.open("/Users/.config/userConfig.cfg", "w")
--- Functions
function login(user)
if user == "admin" then
term.setCursorPos(1,1)
term.setTextColor(256)
print (user)
elseif user == "guest" then
print (user)
else
print ("nil")
end
end
function userCheck()
if userExists == true then
term.clear()
term.setBackgroundColor(8)
term.setCursorPos(halfx-0.5*#prompt, halfy - 4)
term.clear()
print (prompt)
term.setCursorPos((halfx-#uprompt), (halfy - 2))
write (uprompt)
term.setCursorPos((halfx-#uprompt), (halfy - 1))
write (pprompt)
term.setCursorPos((halfx), (halfy - 2))
upin = read()
term.setCursorPos((halfx), (halfy - 1))
ppin = read("*")
if upin == userConfig.readLine(21) and ppin == userConfig.readLine(24) then
print ("ADMIN")
elseif upin == userConfig.readLine(33) and ppin == userConfig.readLine(36) then
login("guest")
end
elseif userExists == false then
elseif userExists == nil then
end
end
--- Main
userCheck()
userConfig.cfg:
-- Format as follows:
--
-- (name):
--
-- (prop):
-- "(value)"
--
-- (prop):
-- "(value)"
--
-- (prop):
-- "(value)"
--
--
-- (name):
-- [etc.]
Admin:
user:
"Admin"
pass:
"admin"
auth:
"1"
Guest:
user:
"Admin"
pass:
nil
auth:
"0"
Root:
user:
nil
pass:
nil
auth:
"2"
readLine does not accept arguments and only reads the next line. Your best bet would be to use tables and textutils.serialize to write it all to a file and then when reading use textutils.unserialize to have it inside a table.
Admin:
user:
"Admin"
pass:
"admin"
auth:
"1"
Can be written inside a table such as
{
Admin = {
user = "Admin"
pass = "admin"
auth = "1"
}
Guest = {
user = "Admin"
pass = nil
auth = "0"
}
}
This would work much in the way that you want, and allows for more variability as well as expansion. Of course to read from it is a different story, and i would use a function to find and send either the auth code back, or nil if it didn't work.
Such as
local function findUsers(username,password)
--This will read the file and put all it's data inside a table, and then close it.
local file = fs.open("userConfig.cfg","r")
local userRanks = textutils.unserialize(file.readAll())
file.close()
--To read all the data in a table, i'm going to do this.
for a,v in pairs(userRanks) do
if type(v) == "table" then
if userRanks[a].user == username and userRanks[a].pass == password then
return userRanks[a].auth
end
end
end
--[[If we look through the entire file table, and the username and password aren't the same
as on file, then we say we couldn't find it by returning nil]]--
return nil
end
Now for your input area all you have to do is when they input the username and password just call this afterwards, also if allows you to have the auth code
local auth = findUsers(upin,ppin)
--If they inputted an actual username and password
if auth ~= nil then
--If the auth code from the rank is "1"
if auth == "1" then
--Do whatever stuff you want
elseif auth == "2" then
--Do whatever other stuff for this auth code
end
elseif auth == nil then
print("Oh no you inputted an invalid username and/or password, please try again!"
end
To expand on Dragon53535's answer:
Here's a quick routine I threw together that reads a file into a table:
local function fileToTable(path)
-- first we make sure that the path can be opened
assert(fs.exists(path), path..' does not exist!')
assert(not fs.isDir(path), path..' is a directory!')
local tSrc = {}
local inFile = fs.open(path, 'r')
-- we set line to a non-nil value
local line = ''
-- we continue the loop until line is nil
while line do
-- we read a line from the file
line = inFile.readLine()
-- now we save the value of line to our table
-- line will be nil at EOF
tSrc[#tSrc+1] = line
end
inFile.close()
return tSrc
end
After running userConfig = fileToTable('/Users/.config/userConfig.cfg'), you'd replace something like userConfig.readLine(24) with userConfig[24].
Alternatively, you could check out CC's implementation of the io library. It's a standard Lua library (though in CC it's an fs wrapper), so code can be moved more easily out of CC.
In particular, io.lines() would be helpful here.
The above code rewritten to use io.lines:
local function fileToTable(path)
-- first we make sure that the path can be opened
assert(fs.exists(path), path..' does not exist!')
assert(not fs.isDir(path), path..' is a directory!')
local tSrc = {}
-- iterate over file
-- io.lines is neat, since it opens and closes the file automatically
for line in io.lines(path) do
tSrc[#tSrc+1] = line
end
return tSrc
end
As you can see, this is much smaller (only 9 lines of code!) and more manageable. The reason it's not my preferred solution in CC is that io sits on top of fs, so it's probably better to remove the middleman.
Hope this helps.
I am looking for a jython script that does the following:
Servers > application servers > server1 > Ports > WC_default > (set) port=8080.
enviornment > virtaul hosts > deault_host > host aliases > [if there is an entry with host name==*, then port = 8080]
Thank you very much.
Use the following code as a starting point:
serverEntries = AdminConfig.list('ServerEntry', AdminConfig.getid('/Node:' + nodeName + '/')).split(java.lang.System.getProperty('line.separator'))
for serverEntry in serverEntries:
if AdminConfig.showAttribute(serverEntry, "serverName") == 'server1':
sepString = AdminConfig.showAttribute(serverEntry, "specialEndpoints")
sepList = sepString[1:len(sepString)-1].split(" ")
for specialEndPoint in sepList:
endPointNm = AdminConfig.showAttribute(specialEndPoint, "endPointName")
if endPointNm == "WC_defaulthost":
ePoint = AdminConfig.showAttribute(specialEndPoint, "endPoint")
# at this point you probably want to do a resetAttribute instead of showAttribute
defaultHostPort = AdminConfig.showAttribute(ePoint, "port")
break
for hostAlias in AdminConfig.getid('/Cell:' + cellName + '/VirtualHost:default_host/HostAlias:/').split(java.lang.System.getProperty('line.separator')):
if AdminConfig.showAttribute(hostAlias, 'port') == defaultHostPort:
print "Deleting host alias for port " + defaultHostPort
AdminConfig.remove(hostAlias)
AdminConfig.create('HostAlias', AdminConfig.getid('/Cell:' + cellName + '/VirtualHost:default_host/'), [['hostname', '*'],['port', defaultHostPort]])