-
Notifications
You must be signed in to change notification settings - Fork 0
/
server_ps.py
executable file
·174 lines (135 loc) · 6.05 KB
/
server_ps.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
# Importing section
import json
import sys
import subprocess
import argparse
import logging
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse
from urllib import parse
from http import HTTPStatus
from tendo.singleton import SingleInstance
from classes.cosmos_interface_v039 import CosmosInterfaceV039
# --------------------------------------------------------------------------- #
# Functions
# --------------------------------------------------------------------------- #
# Handler request
def handler_class(ci_obj, cfg_obj, logger_obj):
class RequestHandler(BaseHTTPRequestHandler):
"""!
Constructor
"""
def __init__(self, *args, **kwargs):
self.ci = ci_obj
self.cfg = cfg_obj
self.logger = logger_obj
self.LOCAL_CMDS = ['/get_tokens_amount', '/getMeasure']
super(RequestHandler, self).__init__(*args, **kwargs)
def do_local_cmd(self, cmd):
result = subprocess.check_output(cmd, shell=True)
decoded_ret = result.decode('UTF-8')
# Build the dataset
res = ''
for elem in decoded_ret:
res = '%s%s' % (res, elem)
return json.loads(res)
def manage_transaction(self, cmd, params):
try:
ci.do_transaction(cmd=cmd, params=params)
return HTTPStatus.OK
except Exception as e:
self.logger.error('EXCEPTION %s' % str(e))
return HTTPStatus.INTERNAL_SERVER_ERROR
def get_tokens_amount(self):
data = ci.get_account_info()
cmd = '%s/bin/%s query account %s' % (self.cfg['cosmos']['goRoot'], '%scli' % self.cfg['cosmos']['app'],
data['address'])
raw_data = subprocess.check_output(cmd, shell=True)
data = json.loads(raw_data.decode('utf-8'))
for coin in data['value']['coins']:
if coin['denom'] == self.cfg['cosmos']['token']:
return json.dumps(coin), HTTPStatus.OK
return None, HTTPStatus.NOT_FOUND
"""!
Catch a GET request
"""
def do_GET(self):
if urlparse(self.path).path in self.LOCAL_CMDS:
if urlparse(self.path).path == '/get_tokens_amount':
data, http_status = self.get_tokens_amount()
elif urlparse(self.path).path == '/getMeasure':
pars = dict(parse.parse_qsl(urlparse(self.path).query))
http_status, data = self.ci.do_query(cmd=urlparse(self.path).path.replace('/', ''), params=pars)
else:
data = None
http_status = HTTPStatus.NOT_FOUND
else:
http_status, data = self.ci.do_query(cmd=urlparse(self.path).path.replace('/', ''), params={})
self.send_response(http_status)
self.logger.info('GET %s?%s HTTP/1.1" %i' % (urlparse(self.path).path, urlparse(self.path).query, http_status))
# send the response
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(bytes(str(data), 'utf8'))
"""!
Catch a POST request
"""
def do_POST(self):
app_cli = '%scli' % cfg['cosmos']['app']
cmd = urlparse(self.path).path.replace('/', '')
if cmd == 'setAdmin':
data = dict(parse.parse_qsl(urlparse(self.path).query))
http_status = self.manage_transaction(cmd, {'address': data['id']})
if cmd == 'meterAccount':
data = dict(parse.parse_qsl(urlparse(self.path).query))
real_cmd = '%s/bin/%s keys show %s' % (self.cfg['cosmos']['goRoot'], app_cli, data['id'])
data_key = self.do_local_cmd(real_cmd)
http_status = self.manage_transaction(cmd, {'meter': data_key['name'], 'account': data_key['address']})
if cmd == 'parameters':
params = dict(parse.parse_qsl(urlparse(self.path).query))
http_status = self.manage_transaction(cmd, params)
if cmd == 'setMeasure':
params = dict(parse.parse_qsl(urlparse(self.path).query))
http_status = self.manage_transaction(cmd, params)
self.send_response(http_status)
logger.info('POST %s?%s HTTP/1.1" %i' % (urlparse(self.path).path, urlparse(self.path).query, http_status))
# send the response
self.send_header('Content-type', 'application/json')
self.end_headers()
# self.wfile.write(bytes(str(data), 'utf8'))
return RequestHandler
# Main
if __name__ == "__main__":
# Check if another instance is already running
try:
singleton = SingleInstance()
except:
sys.exit()
# get input arguments
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('-c', help='configuration file')
arg_parser.add_argument('-l', help='log file')
args = arg_parser.parse_args()
cfg = json.loads(open(args.c).read())
# set logging object
logger = logging.getLogger()
logger.setLevel(logging.INFO)
if not args.l:
log_file = None
else:
log_file = args.l
logger = logging.getLogger()
logging.basicConfig(format='%(asctime)-15s::%(threadName)s::%(levelname)s::%(funcName)s::%(message)s',
level=logging.INFO, filename=log_file)
logger.info('Starting program')
ci = CosmosInterfaceV039(app=cfg['cosmos']['app'], cfg=cfg, logger=logger)
# REST server thread
HandlerClass = handler_class(ci, cfg, logger)
httpd = HTTPServer((cfg['server']['host'], cfg['server']['port']), HandlerClass)
# Try to launch the server
try:
logging.info('Server up on socket %s:%i' % (cfg['server']['host'], cfg['server']['port']))
httpd.serve_forever()
except Exception as e:
logger.error('EXCEPTION: %s' % str(e))
logger.info('Exit program')