-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
104 lines (85 loc) · 3.27 KB
/
main.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
import os
import signal
import logging
import datetime
import time
from logging.handlers import RotatingFileHandler
logger = logging.getLogger("wssample")
# Get hold of the configuration file (package_config.ini)
moduledir = os.path.abspath(os.path.dirname(__file__))
BASEDIR = os.getenv("CAF_APP_PATH", moduledir)
# If we are not running with CAF, use the BASEDIR to get cfg file
tcfg = os.path.join(BASEDIR, "package_config.ini")
CONFIG_FILE = os.getenv("CAF_APP_CONFIG_FILE", tcfg)
def setup_logging(cfg):
"""
Setup logging for the current module and dependent libraries based on
values available in config.
"""
# set a format which is simpler for console use
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
# Set log level based on what is defined in package_config.ini file
loglevel = cfg.getint("logging", "log_level")
logger.setLevel(loglevel)
# Create a console handler only if console logging is enabled
ce = cfg.getboolean("logging", "console")
if ce:
console = logging.StreamHandler()
console.setLevel(loglevel)
console.setFormatter(formatter)
# add the handler to the root logger
logger.addHandler(console)
# The default is to use a Rotating File Handler
log_file_dir = os.getenv("CAF_APP_LOG_DIR", "/tmp")
log_file_path = os.path.join(log_file_dir, "wssample.log")
# Lets cap the file at 1MB and keep 3 backups
rfh = RotatingFileHandler(log_file_path, maxBytes=1024*1024, backupCount=3)
rfh.setLevel(loglevel)
rfh.setFormatter(formatter)
logger.addHandler(rfh)
# Gracefully handle SIGTERM and SIGINT
def handle_signal(signum, stack):
logger.info('Received Signal: %s', signum)
# Raise a KeyboardInterrupt so that the main loop catches this and shuts down
raise KeyboardInterrupt
signal.signal(signal.SIGTERM, handle_signal)
signal.signal(signal.SIGINT, handle_signal)
if __name__ == '__main__':
from ConfigParser import SafeConfigParser
from websocket import create_connection
cfg = SafeConfigParser()
cfg.read(CONFIG_FILE)
setup_logging(cfg)
ws = None
def terminate_self():
logger.info("Stopping the application")
try:
if ws:
ws.close()
except Exception as ex:
logger.exception("Error stopping the app gracefully.")
logger.info("Killing self..")
os.kill(os.getpid(), 9)
wsserver = cfg.get("ws","server", None)
try:
ws = create_connection(wsserver)
except Exception as ex:
ws = None
logger.exception("Error creating a websocket connection to %s" % wsserver)
terminate_self()
while True:
try:
msg = "Current date and time is : %s" % str(datetime.datetime.now())
logger.info("Sending Message: %s" % msg)
ws.send(msg)
logger.debug("\t > Sent")
logger.debug("\t < Receiving...")
result = ws.recv()
logger.info("Received '%s'" % result)
logger.info("Sleeping for 5 seconds..")
time.sleep(5)
except KeyboardInterrupt:
terminate_self()
except Exception as ex:
logger.exception("Caught exception! Terminating..")
terminate_self()