DyComponentSoketAgent.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import socket
  2. from component_controler import *
  3. import time
  4. '''
  5. '{components_name:[gate1,gate2],' \
  6. 'action:"start/stop/sendcommand"'
  7. '''
  8. class SocketServer(object):
  9. def getmyipaddr(self,type):
  10. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  11. if type == 'wan':
  12. s.connect(('114.114.114.114', 0))
  13. if type == 'lan':
  14. s.connect(('192.168.4.1', 0))
  15. myip = s.getsockname()[0]
  16. return myip
  17. def socketbase(self):
  18. self.sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  19. myip = self.getmyipaddr('lan')
  20. self.sock.bind((myip,19166))
  21. self.sock.listen(5)
  22. while True:
  23. self.connection,address = self.sock.accept()
  24. try:
  25. self.connection.settimeout(5)
  26. self.data = self.connection.recv(1024)
  27. self.getcmd = self.getcommand()
  28. if not self.getcmd:
  29. self.result = 'not enough segments '
  30. else:
  31. self.execute_command()
  32. self.returndata()
  33. except Exception,e:
  34. print e
  35. pass
  36. def getcommand(self):
  37. self.data = eval(self.data)
  38. if self.data.get('components_name') and self.data.get('action'):
  39. self.components_name = self.data['components_name']
  40. self.action = self.data['action']
  41. return True
  42. else:
  43. return False
  44. def execute_command(self):
  45. for component_name in self.components_name:
  46. component = Action(component_name)
  47. if self.action == 'restart':
  48. self.result = component.stop()
  49. time.sleep(1)
  50. self.result += '\n'+ component.start()
  51. elif self.action == 'stop':
  52. self.result = component.stop()
  53. elif self.action == 'start':
  54. self.result = component.start()
  55. else:
  56. self.result = component.sendcmd(self.action)
  57. def returndata(self):
  58. self.connection.send(self.result)
  59. self.connection.close()
  60. if __name__ == '__main__':
  61. sockserver = SocketServer()
  62. sockserver.socketbase()