core.py 14 KB

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