File size: 2,811 Bytes
8d55ddb | 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 | import websocket
import traceback
import json
import syslog
import time
import socket
class Plugin(object):
def __init__(self, queue):
try:
self.configuration_file = 'conf/{0}.conf'.format(self.__module__)
self.websocket_url = None
self.websocket = None
self.wait_for_retry = 5
self.push_plugins_data_every = 3
self.queue = queue
self.myhostname = self.__identify_myself()
self.__load_configuration()
self.__connect_to_server()
except Exception as e:
syslog.syslog(
syslog.LOG_ERR,
"Exception %s %r" % (e, traceback.format_exc(800))
)
def __load_configuration(self):
with open(self.configuration_file) as f:
self.configuration = json.loads(f.read())
#get self.websocket_url
self.websocket_url = self.configuration['server']['websocket_url']
#get self.wait_for_retry
self.wait_for_retry = self.configuration['server']['wait_for_retry']
#get self.push_plugins_data_every
self.push_plugins_data_every = self.configuration['client']['push_plugins_data_every']
def __identify_myself(self):
if socket.gethostname().find('.') >= 0:
return socket.gethostname()[0:socket.gethostname().find('.')]
else:
return socket.gethostname()
def __connect_to_server(self):
while True:
try:
self.websocket = websocket.create_connection(self.websocket_url)
break
except Exception as e:
time.sleep(self.wait_for_retry)
def __get_queue_data(self):
try:
data = {}
final_structure = {'host': self.myhostname, 'plugins': {}}
while self.queue.qsize():
queue_data = self.queue.get(False)
for key in queue_data:
data[key] = queue_data[key]
if data:
final_structure['plugins'] = data
return final_structure
else:
raise
except:
raise
def __push_data(self):
try:
self.websocket.send(json.dumps(self.__get_queue_data()))
except socket.error, e:
if isinstance(e.args, tuple):
self.__connect_to_server()
except:
pass
def execute(self):
while True:
time.sleep(self.push_plugins_data_every)
try:
self.__push_data()
except Exception as e:
syslog.syslog(
syslog.LOG_ERR,
"Exception %s %r" % (e, traceback.format_exc(800))
)
|