#!/usr/bin/python
#-*- coding: utf-8 -*-
import platform
import subprocess as sp
import signal
import uuid
import os
from threading import Thread
import socket
global command
command = {0:"GetSystemSpec",1:"openNpdsDisplay",2:"GetMAC",3:"showIpCOnfig",4:"NpdsMonitorInit",
5:"closeNpdsDisplay",6:"shutdownComputer",7:"closeIpConfig",8:"recvBkgndBmp",9:"updateAppFile",10:"areYouAlive",11:"npdsDisplayManagerAlive",12:"PdhQuery"}
global errno
errno = -1
#for pdhMessage.
global lastRecv,lastSend,pdhMessage,curtime
lastRecv = 0
lastSend = 0
curtime = 0
pdhMessage={"cpuUsage":0,"npdsStatus":0,"npdsUsage":0,"netAddr":"0","netBadnWidth":0,"netRecv":0,"netSend":0}
class SageDeamon:
def __init__(self,ip,tcpport,udpport,size,connCnt):
self.ip =ip
self.tcpport = tcpport
self.udpport = udpport
self.size = size
self.connCnt = connCnt
self.hashCallbackFunction = {}
self.hashInComingMessages = {}
self.hashOutgoingMessages = {}
#register all the callback functions.
self.registerCallbackFunction(0,self.getSystemSpec)
self.registerCallbackFunction(1,self.openNpdsDisplay)
self.registerCallbackFunction(2,self.getMAC)
self.registerCallbackFunction(3,self.showIpConfig)
self.registerCallbackFunction(4,self.npdsMonitorInit)
self.registerCallbackFunction(5,self.closeNpdsDisplay)
self.registerCallbackFunction(6,self.shutdownComputer)
self.registerCallbackFunction(7,self.closeIpConfig)
self.registerCallbackFunction(8,self.recvBkgndBmp)
self.registerCallbackFunction(9,self.updateAppFile)
self.registerCallbackFunction(10,self.isDaemonAlive)
self.registerCallbackFunction(11,self.isNpdsAlive)
self.registerCallbackFunction(12,self.pdhQuery)
def tcp_init(self):
self.tcpsocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.tcpsocket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
self.tcpsocket.bind((self.ip,self.tcpport))
self.tcpsocket.listen(self.connCnt)
def udp_init(self):
self.udpsocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
self.udpsocket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
self.udpsocket.bind((self.ip,self.udpport))
def tcp_run(self,conn):
#actually,this loop will only run one time.
while True:
print 'in tcp_run'
data = conn.recv(self.size).strip('\0')
if not data:
break
#print 'data recv is:',data
#caution:the data is not only mesage str,but also include some datas.
code,data = self.getMessageCodeData(data)
#print 'code is:',code
#print 'data is:',data
ret_data=self.onMessage(code,data,conn)
#print 'ret_data is:',ret_data
if not ret_data:
conn.send('\0')
else:
conn.send(ret_data+'\0')
#close connection,because fsManager only connection one time.
break
conn.close()
def tcp_server(self):
while True:
#print 'in tcp_server:'
conn,address = self.tcpsocket.accept()
#print 'address is:',address
#print 'after accept'
self.tcp_run(conn)
def udp_server(self):
while True:
#print 'in udp_server:'
#actually,it's one time thing.
data,address = self.udpsocket.recvfrom(self.size)
#print 'udp_data recv is:',data
#caution:the data is not only mesage str,but also include some datas.
code,data = self.getMessageCodeData(data)
#print 'udp_data code is',code
#print 'udp_data data is',data
ret_data = self.onMessage(code,data,self.udpsocket)
#print 'udp_data ret_data is',ret_data
if not ret_data:
ret_data = '\0'
self.udpsocket.sendto(ret_data,address)
def getMessageCodeData(self,data):
global command
global errno
for code,order in command.items():
index = data.lower().find(order.lower())
#print 'index is:',index
if index == 0:
return code,data[len(order):].strip()
elif index >0:
return code,data.strip()
else:
continue
else:
return errno,errno
def onMessage(self,code,data,conn):
if code in self.hashCallbackFunction:
return self.hashCallbackFunction[code](data,conn)
def registerCallbackFunction(self,msgID,function):
self.hashCallbackFunction[msgID] = function
def getSystemSpec(self,data,conn):
sysverion = platform.system().lower()
if sysversion == 'linux':
ret_data = "linux"
elif sysversion == 'windows':
ret_data = "win32"
else:
ret_data = sysversion
return ret_data
def openNpdsDisplay(self,data,conn):
global pdhMessage
app = os.environ.get('SAGE_DIRECTORY')+'/bin/sageDisplayManager'
args = data.split()
args.insert(0,app)
print 'args is:',args
sp.Popen(args)
pdhMessage["npdsStatus"] = 1
return "openNpdsDisplayRet"
def getMAC(self,data,conn):
print 'in function getMac'
node=uuid.getnode()
mac = uuid.UUID(int=node).hex[-12:]
mac = mac[:-10]+"-"+mac[-10:-8]+"-"+mac[-8:-6]+"-"+mac[-6:-4]+"-"+mac[-4:-2]+"-"+mac[-2:]
return 'GetMACResult'+mac
def showIpConfig(self,data,conn):
cmd_args = 'ifconfig eth0'
proc_eth0 = sp.Popen(cmd_args.split(),stdout=sp.PIPE)
proc_eth0.wait()
ret_data = proc_eth0.stdout.readlines()
#get the data.about RX bytes,and TX bytes.
ip_addr = ret_data[1].split(':')[1].split()[0]
args = "showip " + ip_addr
self.child = sp.Popen(args.split())
pass
def npdsMonitorInit(self,data,conn):
pass
def closeNpdsDisplay(self,data,conn):
pass
def shutdownComputer(self,data,conn):
os.system('poweroff')
def closeIpConfig(self,data,conn):
print 'closeIpConfig-------'
self.child.kill()
pass
def recvBkgndBmp(self,data,conn):
index = data.find('\0')
length = 0
f = open("background.bmp",'wb')
if index == -1 :
filesize = int(data.strip())
else:
filesize = int(data[:index].strip())
length = len(data[index+1:].strip())
file_data = data[index+1:]
f.write(file_data)
#print 'filesize is:',filesize
while length < filesize:
data = conn.recv(self.size)
#print 'len(data) is:',len(data)
f.write(data)
length += len(data)
#print 'length is:',length
f.close()
return "recvBkgndBmpRet:ok"
def updateAppFile(self,data,conn):
index = data.find('\0')
#print 'in updateAppFile,index is:',index
control_data = data[:index]
file_data = data[index+1:]
data_list = control_data.split(',')
filename,filesize = data_list[1],data_list[2]
filename=filename.strip('\0')
filesize=int(filesize.strip('\0'))
#print 'filename=%s,filesize=%s' % (filename,filesize)
f = open(filename,'wb+')
length = len(file_data)
#print 'file data is:',file_data
#print 'file len is:',length
if length > 0 :
f.write(file_data)
while length < filesize:
data = conn.recv(self.size)
f.write(data)
length += len(data)
f.close()
return "updateAppFileRet:ok"
def _pdhQuery(self):
global pdhMessage,lastRecv,lastSend,curtime
#get current time.
proc_time = sp.Popen('cat /proc/uptime'.split(),stdout=sp.PIPE)
proc_time.wait()
ret_data=proc_time.stdout.readlines()
newtime = int(float(ret_data[0].split()[0]))
#get eth0 msg.
cmd_args = 'ifconfig eth0'
proc_eth0 = sp.Popen(cmd_args.split(),stdout=sp.PIPE)
proc_eth0.wait()
ret_data = proc_eth0.stdout.readlines()
#get the data.about RX bytes,and TX bytes.
rx_bytes = int(ret_data[-2].split(':')[1].split()[0])
tx_bytes = int(ret_data[-2].split(':')[2].split()[0])
pdhMessage["netAddr"] = ret_data[ 1].split(':')[1].split()[0]
pdhMessage["netRecv"] = (rx_bytes -lastRecv)/(newtime-curtime)
pdhMessage["netSend"] = (tx_bytes -lastSend)/(newtime-curtime)
pdhMessage["netBadnWidth"] = pdhMessage['netRecv']+pdhMessage['netSend']
lastRecv = rx_bytes
lastSend = tx_bytes
curtime = newtime
#get cpu usage.
cmd_args = "top -n 1 -b"
proc_cpu = sp.Popen(cmd_args.split(),stdout=sp.PIPE)
proc_cpu.wait()
ret_data = proc_cpu.stdout.readlines()
import re
cpu_usage=re.findall('\d+.\d+',ret_data[2])
pdhMessage["cpuUsage"] = int(float(cpu_usage[0]) +float(cpu_usage[1]))+1
#get npds status and cpu usage.
for line in ret_data[7:]:
#print '-----in query,string is:',line
if(line and -1 != line.find('sageDisplay')):
#print '-----in query,in if.'
pdhMessage["npdsUsage"] = int(float(line.strip().split()[8]))+1
pdhMessage["npdsStatus"]= 1
break
else:
#print '-----in query,in else,out for'
pdhMessage["npdsUsage"] = 0
pdhMessage["npdsStatus"]= 0
def pdhQuery(self,data,conn):
import re
recv_head = re.findall('seq:\d+',data)[0]
#print 'recv_head is:',recv_head
try:
#because,keep alive heart package,make it's invoked,so this not necessary.
self._pdhQuery()
global pdhMessage
#print 'pdhMessage is:',pdhMessage
return recv_head+',PdhQueryRet,result:ok,cpuUsage:%(cpuUsage)d,npdsStatus:%(npdsStatus)d,npdsUsage:%(npdsUsage)d,netAddr:%(netAddr)s,netBadnWidth:%(netBadnWidth)d,netRecv:%(netRecv)d,netSend:%(netSend)d' % pdhMessage
except:
return recv_head+'Ret,result:failed'
def isDaemonAlive(self,data,conn):
return "yes"
def isNpdsAlive(self,data,conn):
self._pdhQuery()
global pdhMessage
#print 'now,pdhMessage is:',pdhMessage
if pdhMessage["npdsStatus"] == 0 :
return "no"
else:
return "yes"
if __name__ == '__main__':
newpid = os.fork()
if newpid == 0 :
deamon = SageDeamon("",20014,20015,1024000,50)
deamon.tcp_init()
deamon.tcp_server()
else:
newpid = os.fork()
if newpid == 0 :
deamon = SageDeamon("",20014,20015,1024000,50)
deamon.udp_init()
deamon.udp_server()
else:
pass
os.wait()