core.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. import os
  2. import sys
  3. import yaml
  4. import requests
  5. import shutil
  6. from datetime import date
  7. import csv
  8. import urllib2
  9. import re
  10. import datetime
  11. from shutil import copyfile
  12. from time import gmtime, strftime
  13. import time
  14. import tornado.escape
  15. import tornado.ioloop
  16. import tornado.web
  17. import tornado.autoreload
  18. from tornado.escape import json_decode
  19. from tornado.escape import json_encode
  20. from threading import Timer
  21. import collections
  22. root = os.path.dirname(__file__)
  23. with open("config.yaml", 'r') as stream:
  24. try:
  25. #print(yaml.load(stream))
  26. config = yaml.load(stream)
  27. except yaml.YAMLError as exc:
  28. print(exc)
  29. if config == None:
  30. print("Error: Empty configuration file.")
  31. sys.exit(1)
  32. class RepeatedTimer(object):
  33. def __init__(self, interval, function, *args, **kwargs):
  34. self._timer = None
  35. self.interval = interval
  36. self.function = function
  37. self.args = args
  38. self.kwargs = kwargs
  39. self.is_running = False
  40. self.start()
  41. def _run(self):
  42. self.is_running = False
  43. self.start()
  44. self.function(*self.args, **self.kwargs)
  45. def start(self):
  46. if not self.is_running:
  47. self._timer = Timer(self.interval, self._run)
  48. self._timer.start()
  49. self.is_running = True
  50. def stop(self):
  51. self._timer.cancel()
  52. self.is_running = False
  53. def setInterval(self, interval):
  54. self.interval = interval
  55. def fetchDataADEI():
  56. with open("varname.yaml", 'r') as stream:
  57. try:
  58. #print(yaml.load(stream))
  59. varname = yaml.load(stream)
  60. except yaml.YAMLError as exc:
  61. print(exc)
  62. if varname == None:
  63. print("Error: Empty varname file.")
  64. return
  65. cache_data = {}
  66. curtime = int(time.time())
  67. #time_range = str((curtime-3600)) + "-" + str(curtime)
  68. time_range = str((curtime-1800)) + "-" + str(curtime)
  69. for param in varname:
  70. print param
  71. dest = config['server'] + config['script']
  72. #url = dest + "?" + varname[param] + "&window=-1"
  73. url = dest + "?" + varname[param] + "&window=" + time_range
  74. print url
  75. data = requests.get(url,
  76. auth=(config['username'],
  77. config['password'])).content
  78. #tmp_data = data.content
  79. #print "CHECK THIS"
  80. #print data
  81. last_value = data.split(",")[-1].strip()
  82. try:
  83. print last_value
  84. test_x = float(last_value)
  85. except ValueError:
  86. last_value = ""
  87. print last_value
  88. cache_data[param] = last_value
  89. #current_timestamp = strftime("%Y-%m-%d %H:%M:%S", gmtime())
  90. current_timestamp = strftime("%Y-%m-%d %H:%M:%S")
  91. cache_data['time'] = current_timestamp
  92. with open(".tmp.yaml", 'w') as stream_tmp:
  93. stream_tmp.write(yaml.dump(cache_data, default_flow_style=False))
  94. src_file = os.getcwd() + "/.tmp.yaml"
  95. dst_file = os.getcwd() + "/cache.yaml"
  96. shutil.copy(src_file, dst_file)
  97. print "Start torrenting..."
  98. # it auto-starts, no need of rt.start()
  99. print "Debugging..."
  100. # TODO: Turn off for debug
  101. rt = RepeatedTimer(int(config["polling"]), fetchDataADEI)
  102. class BaseHandler(tornado.web.RequestHandler):
  103. def get_current(self):
  104. return self.get_secure_cookie("user")
  105. class ListHandler(tornado.web.RequestHandler):
  106. def get(self):
  107. with open("cache.yaml", 'r') as stream:
  108. try:
  109. #print(yaml.load(stream))
  110. response = yaml.load(stream)
  111. except yaml.YAMLError as exc:
  112. print(exc)
  113. if response == None:
  114. response = {"error": "No data entry."}
  115. print response
  116. self.write(response)
  117. class StartHandler(tornado.web.RequestHandler):
  118. def get(self):
  119. print "Start fetchData"
  120. rt.start()
  121. class StopHandler(tornado.web.RequestHandler):
  122. def get(self):
  123. print "Stop fetchData"
  124. rt.stop()
  125. class SetTimerHandler(tornado.web.RequestHandler):
  126. def get(self, duration):
  127. print "Set interval"
  128. rt.setInterval(float(duration))
  129. class DesignerHandler(tornado.web.RequestHandler):
  130. @tornado.web.authenticated
  131. def get(self):
  132. print "In designer mode."
  133. with open("cache.yaml", 'r') as stream:
  134. try:
  135. #print(yaml.load(stream))
  136. cache_data = yaml.load(stream)
  137. except yaml.YAMLError as exc:
  138. print(exc)
  139. if cache_data == None:
  140. print("Error: Empty cache data file.")
  141. return
  142. with open("style.yaml", 'r') as stream:
  143. try:
  144. #print(yaml.load(stream))
  145. style_data = yaml.load(stream)
  146. except yaml.YAMLError as exc:
  147. print(exc)
  148. data = {
  149. "cache": cache_data,
  150. "style": style_data
  151. }
  152. self.render('designer.html', data=data)
  153. class VersionHandler(tornado.web.RequestHandler):
  154. def get(self):
  155. response = {'version': '0.0.1',
  156. 'last_build': date.today().isoformat()}
  157. self.write(response)
  158. class BackupHandler(tornado.web.RequestHandler):
  159. def post(self):
  160. backup_dst = os.getcwd() + "/backup/"
  161. fname = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
  162. os.makedirs(backup_dst + fname)
  163. copyfile(os.getcwd() + "/varname.yaml", backup_dst + fname + "/varname.yaml")
  164. copyfile(os.getcwd() + "/style.yaml", backup_dst + fname + "/style.yaml")
  165. #self.write(json.dumps(response))
  166. class SaveHandler(tornado.web.RequestHandler):
  167. def post(self):
  168. print self.request.body
  169. json_obj = json_decode(self.request.body)
  170. print('Post data received')
  171. with open("style.yaml", 'w') as output:
  172. output.write(yaml.safe_dump(json_obj, encoding='utf-8', allow_unicode=True, default_flow_style=False))
  173. response = {"success": "Data entry inserted."}
  174. #self.write(json.dumps(response))
  175. class StatusHandler(tornado.web.RequestHandler):
  176. def get(self):
  177. print "In status mode."
  178. with open("style.yaml", 'r') as stream:
  179. try:
  180. #print(yaml.load(stream))
  181. style_data = yaml.load(stream)
  182. except yaml.YAMLError as exc:
  183. print(exc)
  184. #if style_data == None:
  185. # print("Error: Empty style data file.")
  186. # return
  187. with open("varname.yaml", 'r') as vstream:
  188. try:
  189. #print(yaml.load(stream))
  190. varname_data = yaml.load(vstream)
  191. except yaml.YAMLError as exc:
  192. print(exc)
  193. #if varname_data == None:
  194. # print("Error: Empty varname data file.")
  195. # return
  196. data = {
  197. #"style": style_data,
  198. "varname": varname_data
  199. }
  200. #if "background" in config:
  201. # data["background"] = config["background"]
  202. if "title" in config:
  203. data["title"] = config["title"]
  204. else:
  205. data["title"] = "BORA"
  206. self.render('index.html', data=data)
  207. class AdeiKatrinHandler(tornado.web.RequestHandler):
  208. def get(self, **params):
  209. #print params
  210. sensor_name = str(params["sensor_name"])
  211. """
  212. {'db_group': u'320_KRY_Kryo_4K_CurLead',
  213. 'db_name': u'ControlSystem_CPS',
  214. 'sensor_name': u'320-RTP-8-1103',
  215. 'db_server': u'cscps',
  216. 'control_group': u'320_KRY_Kryo_3K'}
  217. """
  218. if config["type"] != "adei":
  219. print("Error: Wrong handler.")
  220. return
  221. dest = config['server'] + config['script']
  222. query_cmds = []
  223. query_cmds.append("db_server="+str(params['db_server']))
  224. query_cmds.append("db_name="+str(params['db_name']))
  225. query_cmds.append("db_group="+str(params['db_group']))
  226. query_cmds.append("db_mask=all")
  227. query_cmds.append("window=-1")
  228. query = "&".join(query_cmds)
  229. url = dest + "?" + query
  230. #print url
  231. # get the db_masks
  232. # store the query command in varname
  233. data = requests.get(url, auth=(config['username'], config['password']))
  234. cr = data.content
  235. cr = cr.split(",")
  236. print cr, len(cr)
  237. # handling the inconsistency on naming convention
  238. match_token = params['sensor_name']
  239. if params["db_server"] != "lara":
  240. # parameter name stored in ADEI with '-IST_Val' suffix
  241. if "MOD" in params['sensor_name']:
  242. match_token = params['sensor_name'] + "-MODUS_Val"
  243. elif "GRA" in params['sensor_name']:
  244. match_token = params['sensor_name'] + "-GRAD_Val"
  245. elif "RPO" in params['sensor_name']:
  246. match_token = params['sensor_name'] + "-ZUST_Val"
  247. elif "VYS" in params['sensor_name']:
  248. match_token = params['sensor_name'] + "-ZUST_Val"
  249. else:
  250. match_token = params['sensor_name'] + "-IST_Val"
  251. db_mask = None
  252. for i, item in enumerate(cr):
  253. if "[" and "]" in item.strip():
  254. lhs = re.match(r"[^[]*\[([^]]*)\]", item.strip()).groups()[0]
  255. if lhs == params['sensor_name']:
  256. db_mask = i - 1
  257. else:
  258. if item.strip() == match_token:
  259. db_mask = i - 1
  260. if db_mask == None:
  261. response = {"Error": "Cannot find variable on ADEI server."}
  262. self.write(response)
  263. return
  264. query_cmds = []
  265. query_cmds.append("db_server="+str(params['db_server']))
  266. query_cmds.append("db_name="+str(params['db_name']))
  267. query_cmds.append("db_group="+str(params['db_group']))
  268. query_cmds.append("db_mask="+str(db_mask))
  269. query = "&".join(query_cmds)
  270. # column name available
  271. # store in yaml file
  272. with open("varname.yaml", 'r') as stream:
  273. try:
  274. #print(yaml.load(stream))
  275. cache_data = yaml.load(stream)
  276. except yaml.YAMLError as exc:
  277. print(exc)
  278. if cache_data == None:
  279. cache_data = {}
  280. cache_data[sensor_name] = query
  281. else:
  282. if sensor_name not in cache_data:
  283. cache_data[sensor_name] = query
  284. else:
  285. response = {"Error": "Variable already available in varname file."}
  286. self.write(response)
  287. return
  288. with open("varname.yaml", 'w') as output:
  289. output.write(yaml.dump(cache_data, default_flow_style=False))
  290. response = {"success": "Data entry inserted."}
  291. #print match_token, db_mask
  292. self.write(response)
  293. class GetDataHandler(tornado.web.RequestHandler):
  294. def get(self):
  295. with open("cache.yaml", 'r') as stream:
  296. try:
  297. #print(yaml.load(stream))
  298. cache_data = yaml.load(stream)
  299. except yaml.YAMLError as exc:
  300. print(exc)
  301. print("GetData:")
  302. if cache_data == None:
  303. cache_data = {}
  304. print cache_data
  305. self.write(cache_data)
  306. class AuthLoginHandler(BaseHandler):
  307. def get(self):
  308. try:
  309. errormessage = self.get_argument("error")
  310. except:
  311. errormessage = ""
  312. print errormessage
  313. self.render("login.html", errormessage = errormessage)
  314. def check_permission(self, password, username):
  315. if username == config["username"] and password == config["pw_designer"]:
  316. return True
  317. return False
  318. def post(self):
  319. username = self.get_argument("username", "")
  320. password = self.get_argument("password", "")
  321. auth = self.check_permission(password, username)
  322. if auth:
  323. self.set_current_user(username)
  324. print "In designer mode."
  325. with open("cache.yaml", 'r') as stream:
  326. try:
  327. #print(yaml.load(stream))
  328. cache_data = yaml.load(stream)
  329. except yaml.YAMLError as exc:
  330. print(exc)
  331. #if cache_data == None:
  332. # print("Error: Empty cache data file.")
  333. # return
  334. with open("style.yaml", 'r') as stream:
  335. try:
  336. #print(yaml.load(stream))
  337. style_data = yaml.load(stream)
  338. except yaml.YAMLError as exc:
  339. print(exc)
  340. if style_data:
  341. index_data = list(set(cache_data) | set(style_data))
  342. else:
  343. index_data = cache_data
  344. print index_data
  345. data = {
  346. "cache": cache_data,
  347. "style": style_data,
  348. "index": index_data,
  349. }
  350. if "background" in config:
  351. data["background"] = config["background"]
  352. self.render('designer.html', data=data)
  353. else:
  354. error_msg = u"?error=" + tornado.escape.url_escape("Login incorrect")
  355. self.redirect(u"/auth/login/" + error_msg)
  356. def set_current_user(self, user):
  357. if user:
  358. self.set_secure_cookie("user", tornado.escape.json_encode(user))
  359. else:
  360. self.clear_cookie("user")
  361. application = tornado.web.Application([
  362. (r"/auth/login/?", AuthLoginHandler),
  363. (r"/version/?", VersionHandler),
  364. (r"/list/?", ListHandler),
  365. (r"/start/?", StartHandler),
  366. (r"/backup/?", BackupHandler),
  367. (r"/stop/?", StopHandler),
  368. (r"/designer/?", DesignerHandler),
  369. (r"/status/?", StatusHandler),
  370. (r"/save/?", SaveHandler),
  371. (r"/getdata/?", GetDataHandler),
  372. (r"/timer/(?P<duration>[^\/]+)/?", SetTimerHandler),
  373. (r"/add/(?P<db_server>[^\/]+)/?(?P<db_name>[^\/]+)/?(?P<db_group>[^\/]+)/?(?P<sensor_name>[^\/]+)?", AdeiKatrinHandler)
  374. ], debug=True, static_path=os.path.join(root, 'static'), js_path=os.path.join(root, 'js'), login_url="/auth/login", cookie_secret='L8LwECiNRxq2N0N2eGxx9MZlrpmuMEimlydNX/vt1LM=')
  375. if __name__ == "__main__":
  376. application.listen(int(config["port"]))
  377. tornado.autoreload.start()
  378. #tornado.autoreload.watch('myfile')
  379. tornado.ioloop.IOLoop.instance().start()