/
nodestatus.py
executable file
·194 lines (156 loc) · 5.06 KB
/
nodestatus.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
#!/usr/bin/env python
# coding=utf-8
from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler
import logging
import socket
import os
# from subprocess import call
from subprocess import check_output
from linux_metrics import cpu_stat
from linux_metrics import mem_stat
"""
Simple RPC Server to respond to status requests and node commands.
"""
__author__ = 'JustinZimmer'
logging.basicConfig(level=logging.DEBUG)
class RPCServer(SimpleXMLRPCServer):
quit = False
def __init__(self, *args, **kwargs):
self._timedout = False
self.status = 'INIT'
SimpleXMLRPCServer.__init__(self, *args, **kwargs)
def handle_request(self):
self._timedout = False
self.status = "WAITING"
return SimpleXMLRPCServer.handle_request(self)
def handle_timeout(self):
self.status = 'TIMEDOUT'
self._timedout = True
return self.status
def serve_forever(self):
self.quit = False
while not self.quit:
self.handle_request()
def shutdown(self):
self.quit = True
return 1
def timedout(self):
return self._timedout
def serviceStatus(service):
svcStatus = False
if service == "Asterisk":
print "Checking Asterisk..."
try:
asterisk = check_output("service asterisk status", shell=True)
print asterisk
if asterisk.find("is running") != -1:
svcStatus = True
else:
svcStatus = False
except:
svcStatus = False
elif service == "Jboss":
startString = "JBoss (MX MicroKernel) [4.2.2.GA "
"(build: SVNTag=JBoss_4_2_2_GA date=200710221139)] Started in "
logfile = "/var/log/weblog"
svcStatus = False
try:
log = open(logfile, 'r')
# read = mmap.mmap(log.fileno(), 0, access=mmap.ACCESS_READ)
lines = log.readlines()
for elem in lines:
if elem.find(startString) != -1:
svcStatus = True
except:
print "Couldn't open LogFile!"
else:
print "Unrecognized Service: {0}".format(service)
return svcStatus
def callCount():
print "Checking Call Count..."
callCount = 0
try:
asterisk = check_output('asterisk -rx "core show channels"', shell=True)
#print asterisk
if asterisk.find("command not found") != -1:
callCount = -1
else:
lines = asterisk.readlines()
for elem in lines:
if elem.find("active calls") != -1:
callCount = int(elem.split()[0])
except:
callCount = -1
return callCount
def listChannels():
print "Checking Call Count..."
channelList = {}
try:
asterisk = check_output('asterisk -rx "core show channels concise"', shell=True)
#print asterisk
if asterisk.find("command not found") != -1:
channelList = False
else:
lines = asterisk.readlines()
for elem in lines:
if elem.find("Bridge") != -1:
callCount = int(elem.split()[0])
except:
callCount = -1
return callCount
def upTime():
print "Checking Up Time..."
load = 0
try:
upString = check_output('uptime', shell=True)
#print asterisk
loadIndex = upString.find("load average: ")
loadList = upString[loadIndex+14:].strip().split(', ')
load = float(loadList[0])
except:
load = -1
return load
def serverStats():
cpuPercents = cpu_stat.cpu_percents(1)
statDict = {}
statDict["ioWait"] = cpuPercents['iowait']
statDict["system"] = cpuPercents['system']
statDict["idle"] = cpuPercents['idle']
statDict["user"] = cpuPercents['user']
statDict["cpuUsed"] = round(100 - cpuPercents['idle'])
statDict["loadAvg"] = cpu_stat.load_avg()
statDict["memUsed"], statDict["memTot"], _, _, _, _ = mem_stat.mem_stats()
statDict["memFree"] = memTot-memUsed
return statDict
def Shutdown():
logging.debug('Shutting down...')
server.shutdown()
def hostname_resolves(hostname):
try:
socket.gethostbyname(hostname)
return True
except socket.error:
return False
pid = os.getpid()
op = open("/var/run/nodestatus.pid", "w")
op.write("%s" % pid)
op.close()
server = RPCServer(('0.0.0.0', 8787),
SimpleXMLRPCRequestHandler,
logRequests=False,
allow_none=True)
# server.timeout=15 # seconds
server.register_function(serviceStatus, 'checkService')
server.register_function(Shutdown, 'shutdown')
server.register_function(serverStats, 'serverStats')
server.register_function(callCount, 'callCount')
try:
server.serve_forever()
# print '{0} just happened!'.format(server.status)
# print server.status
except Exception, e:
logging.debug('Unexpected Exception: %s', str(e))
# server.status="EXCEPTION: {0}".format(str(e))
# print server.status
except KeyboardInterrupt:
logging.debug("User Aborted!")