-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
259 lines (194 loc) · 7.82 KB
/
server.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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
"""
This is a simple epics server that sends out caget and cainfo data.
It replaces a version written using bottle.py.
This one is supposedly asynchronous .
It does appear to handle multiple requests at once.
"""
import tornado.ioloop
import tornado.web
import tornado.httpserver
import epics
import struct
import socket
import datetime
import time
from lockfile import LockFile
from ca_proto_search import ca_proto_search
PORT = 5068
try:
import simplejson as json
except Exception as err:
print("SIMPLEJSON IMPORT FAILED")
import json
# Archiver machine at CLS
ADDRESSES_VM_ARCHIVER_02 = []
STATUS_STR_LOST = \
'<span style="background-color:red">- LOST -</span>'
STATUS_STR_NEVER_SEEN = \
'<span style="background-color:yellow">NEVER SEEN</span>'
STATUS_STR_ONLINE = \
'<span style="background-color:lawngreen">- ONLINE -</span>'
def make_link_ioc(web_server, web_port, ioc_id, display):
url = f"http://{web_server}:{web_port}/ioc/{ioc_id}"
return f"<a href=""{url}"">{display}</a>"
def make_link_port(web_server, web_port, ioc_id, port):
url = f"http://{web_server}:{web_port}/pv_list?offset=0&kind=port&ioc_id={ioc_id}&key={port}"
return f"<a href=""{url}"">{port}}</a>"
def my_time(timestamp):
result = f"{datetime.datetime.fromtimestamp(timestamp)}"
parts = result.split('.')
return parts[0]
def get_ip_key(ip_addr):
try:
ip_key = struct.unpack("!I", socket.inet_aton(ip_addr))[0]
return int(ip_key)
except Exception as err:
print(f"EXCEPTION: {repr(err)} ip_addr: {repr(ip_addr)}")
def get_host_name(ip_addr, trim_domain=True):
singlequote = "'"
try:
host_name = socket.gethostbyaddr(ip_addr)[0]
if host_name is None:
raise ValueError('gethostbtaddr() returned None')
except Exception as err:
if ip_addr in ADDRESSES_VM_ARCHIVER_02:
host_name = "VM-ARCHIVER-02"
else:
host_name = f"{repr(ip_addr).strip(singlequote)}"
if trim_domain:
host_name = host_name.replace('.clsi.ca', '')
host_name = host_name.replace('.CLSI.CA', '')
host_name = host_name.replace('.corp.lightsource.ca', '')
host_name = host_name.replace('.CORP.LIGHTSOURCE.CA', '')
# print("returning host name: >>%s<<" % host_name)
return host_name
class HandlerMain(tornado.web.RequestHandler):
def get(self):
self.write("""<html>
<head>
<title>CLS EPICS caget/cainfo server</title>
</head>
<body>
<h1>Welcome to Tornado</h1>
<p>This is the CLS EPICS caget/cainfo server<p>
</body>
</html>""")
class HandlerCaGet(tornado.web.RequestHandler):
def get(self, pv_name):
try:
result = epics.caget(pv_name, timeout=1)
except Exception as e:
result = f"Exception: PV {pv_name}: {str(e)}"
print(result)
if result is None:
result = 'EPICS timeout'
else:
try:
result = repr(result).strip("'")
except Exception as err:
result = 'Error'
print(f"CA_GET PV '{pv_name}' --> {result}")
self.write(result)
self.set_header('Access-Control-Allow-Origin', '*')
class HandlerCaInfo(tornado.web.RequestHandler):
def get(self, pv_name):
try:
result = epics.cainfo(pv_name, print_out=False)
lines = result.split('\n')
except Exception as e:
lines = [f"Exception: '{str(e)}' PV: '{pv_name}'"]
if result is None:
lines = ['EPICS Timeout']
print(f"CA_INFO PV '{pv_name}' --> {len(lines)} lines")
json_str = json.dumps(lines)
self.write(json_str)
self.set_header('Access-Control-Allow-Origin', '*')
class HandlerCaProtoSearch(tornado.web.RequestHandler):
def get(self):
# Get the parameters
pv_name = self.get_query_argument('pv_name')
web_server = self.get_query_argument('web_server')
web_port = int(self.get_query_argument('web_port'))
index = int(self.get_query_argument('index'))
last_seen = int(self.get_query_argument('last_seen'))
ioc_id = int(self.get_query_argument('ioc_id'))
port = int(self.get_query_argument('port'))
# print("HandlerCaProtoSearch CALLED!!!", pv_name, ioc_id, port, last_seen, web_server, web_port)
try:
response = ca_proto_search(str(pv_name))
if response is None:
# No response. If if was hosted previously
# Then is is lost. Otherwise it has never been seen
data = {'status_id': '%d_status' % index}
if not ioc_id:
data['status_val'] = STATUS_STR_NEVER_SEEN
else:
data['status_val'] = STATUS_STR_LOST
else:
# Debugging
for item in response:
host_name = get_host_name(item[0])
print(f"POLL PV: {pv_name} host: {host_name} ip_addr: {item[0]} port: {item[1]}")
if len(response) > 1:
duplicate_flag = True
temp = []
for server in response:
# This should use the same algorithm that is used
# in the mapn process response in the PV manager
k = get_ip_key(server[0])
p = server[1]
# IP key, port, ip_Address
temp.append([k, p, server[0]])
temp.sort()
server = temp[0]
ioc_id_polled = server[0]
port_polled = server[1]
ip_addr = server[2]
else:
duplicate_flag = False
server = response[0]
ip_addr = server[0]
port_polled = server[1]
ioc_id_polled = get_ip_key(ip_addr)
data = {
'status_id': '%d_status' % index,
'status_val': STATUS_STR_ONLINE,
'last_seen_id': '%d_last_seen' % index,
'last_seen_val': my_time(time.time())
}
if duplicate_flag or ioc_id != ioc_id_polled:
print(f"ioc_id changed HAD: {ioc_id} GOT: {ioc_id_polled}")
host_name = get_host_name(ip_addr)
server_link = make_link_ioc(web_server, web_port, ioc_id_polled, host_name)
if duplicate_flag:
server_link = f"<span style=""background-color:red"">{server_link}</span>"
data['server_id'] = f"{index}_server",
data['server_val'] = server_link
if port != port_polled:
print(f"port changed HAD: {port} GOT {port_polled}")
port_link = make_link_port(web_server, web_port, ioc_id, port_polled)
data['port_id'] = '%d_port' % index
data['port_val'] = port_link
json_str = json.dumps(data)
except Exception as err:
print(f"EXCEPTION: {str(err)}")
data = {
'status_id': '0_status',
'status_val': f"Exception: {repr(err)}"
}
json_str = json.dumps(data)
self.write(json_str)
self.set_header('Access-Control-Allow-Origin', '*')
def make_app():
return tornado.web.Application([
(r"/", HandlerMain),
(r"/cainfo/(.*)", HandlerCaInfo),
(r"/caget/(.*)", HandlerCaGet),
(r"/casearch", HandlerCaProtoSearch),
])
if __name__ == "__main__":
app = make_app()
server = tornado.httpserver.HTTPServer(app)
server.bind(PORT)
server.start(0)
tornado.ioloop.IOLoop.current().start()