core.py 13 KB

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