index.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. """
  2. This is a RESTful interface implemented using Flask micro framework.
  3. The API is driven by configuration that is organized in terms of the monitoring classes
  4. The API is both restful and websocket/socketio enabled.
  5. We designed the classes to be reusable (and powered by labels):
  6. 'monitoring-type':
  7. 'class':'<class-name>'
  8. 'config':<labeled-class-specific-configuration>'
  9. @TODO:
  10. - In order to make this Saas we need to have the configuration be session driven
  11. - Add socketio, so that each section of the dashboard updates independently
  12. """
  13. from flask import Flask, session, request, redirect, Response
  14. from flask.templating import render_template
  15. from flask_session import Session
  16. import time
  17. import sys
  18. import os
  19. import json
  20. import re
  21. import monitor
  22. import Queue
  23. from utils.transport import *
  24. from utils.workers import ThreadManager, Factory
  25. from utils.ml import ML,AnomalyDetection,AnalyzeAnomaly
  26. import utils.params as SYS_ARGS
  27. import atexit
  28. app = Flask(__name__)
  29. app.config['SECRET_KEY'] = '!h8-[0v8]247-4-360'
  30. #app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX=?RT'
  31. PARAMS = SYS_ARGS.PARAMS
  32. f = open(PARAMS['path'])
  33. CONFIG = json.loads(f.read())
  34. f.close()
  35. #
  36. #
  37. #from threading import Thread, RLock
  38. p = CONFIG['store']['args']
  39. class_read = CONFIG['store']['class']['read']
  40. class_write= CONFIG['store']['class']['write']
  41. factory = DataSourceFactory()
  42. # gReader = factory.instance(type=class_read,args=p)
  43. @app.route('/')
  44. def dashboard():
  45. context = PARAMS['context']
  46. if 'title' in PARAMS :
  47. title = PARAMS['title']
  48. else:
  49. title = 'Dashboard'
  50. apps = []
  51. try:
  52. gReader = factory.instance(type=class_read,args=p)
  53. apps = gReader.view('summary/app_names',key=p['uid'])
  54. except Exception, e:
  55. print (e)
  56. return render_template('dashboard.html',context=context,title=title,app_names=apps)
  57. @app.route('/1/get/nodes')
  58. def get_apps():
  59. """
  60. This function returns the labels of applications for every node registered
  61. @param None
  62. e.g: apps@zulu.org
  63. """
  64. r = []
  65. try:
  66. gReader = factory.instance(type=class_read,args=p)
  67. r = gReader.view('summary/nodes',key=p['uid'])
  68. except Exception,e:
  69. print (e)
  70. return json.dumps(r)
  71. @app.route('/1/get/apps')
  72. def get_apps():
  73. """
  74. This function returns the applications for a given node
  75. @param node identifier e.g: apps@zulu.org
  76. """
  77. r = []
  78. try:
  79. node_id = request.args.get('node')
  80. gReader = factory.instance(type=class_read,args=p)
  81. r = gReader.view('summary/app_names',key=p['uid'])
  82. r = r[node_id]
  83. except Exception,e:
  84. print (e)
  85. return json.dumps(r)
  86. @app.route('/1/get/summary/<id>')
  87. def get_summary(id):
  88. """
  89. This function returns the summary i.e an overall assessment of resource usage
  90. It will pull information out of the user's data-store (database & document) specified in the configuration
  91. @param id {app_resources|app_status|folder_size}
  92. """
  93. r = []
  94. try:
  95. gReader = factory.instance(type=class_read,args=p)
  96. #if id == 'apps_resources' :
  97. # r = gReader.view('summary/app_resources',key=p['uid'])
  98. #else:
  99. # r = gReader.view('summary/folder_size',key=p['uid'])
  100. id='summary/'+id.strip()
  101. print p
  102. print id
  103. r = gReader.view(id,key=p['uid'])
  104. except Exception,e:
  105. print (e)
  106. return json.dumps(r)
  107. @app.route("/1/sys/usage/trend")
  108. def get_usage_trend():
  109. """
  110. This function returns cpu/memory usage for the entire system being monitored. It will return the 24 most recent observations in the logs
  111. @param None
  112. @return {memory_usage:[],cpu_usage:[],app_count:value,memory_available:[]}
  113. """
  114. r = {}
  115. try:
  116. gReader = factory.instance(type=class_read,args=p)
  117. r = gReader.view('summary/resource_usage_trend',key=p['uid'])
  118. except Exception,e:
  119. print (e)
  120. return json.dumps(r)
  121. @app.route("/1/app/usage/trend")
  122. def get_usage_detail():
  123. """
  124. This function returns detailed information about usage per application monitored. It will return the 24 most recent observations in the logs
  125. @param node node identifier e.g: apps@zulu.io
  126. @return {node_x:{app_1:{memory_usage:[],cpu_usage:[]}},...}
  127. """
  128. r = {}
  129. try:
  130. id = request.args.get('node')
  131. gReader = factory.instance(type=class_read,args=p)
  132. r = gReader.view('summary/app_resource_usage_details',key=p['uid'])
  133. r = r[id]
  134. except Exception,e:
  135. print (e)
  136. return json.dumps(r)
  137. @app.route('/1/app/status')
  138. def app_status() :
  139. """
  140. This function aggregates the number of crashes/running/idle instances found in the past 24 log entries
  141. @param nid node identifier e.g: app@zulu.io
  142. @param aid application identifier e.g: kate, firefox, chrome ... specified in the configuraiton
  143. """
  144. r = []
  145. try:
  146. nid = request.args.get('node') # Node identifier
  147. aid = request.args.get('app') # application identifier
  148. gReader = factory.instance(type=class_read,args=p)
  149. r = gReader.view('summary/app_status_details',key=p['uid'])
  150. #
  151. #@TODO: Once the back-end enables the nodes in which the application is running, uncomment the line below
  152. #
  153. r = r[nid][aid]
  154. except Exception,e:
  155. print e
  156. return r
  157. #@app.route('/get/<id>')
  158. #def procs(id):
  159. #try:
  160. #gReader = factory.instance(type=class_read,args=p)
  161. #data = gReader.read()
  162. #ahandler = AnalyzeAnomaly()
  163. #learn = {}
  164. #if 'learn' in data :
  165. #for row in data['learn'] :
  166. #label = row['label']
  167. #learn[label] = row
  168. #r = {}
  169. #for label in data :
  170. #if label not in ['learn','folders'] :
  171. #index = len(data[label]) - 1
  172. #row = data[label][index]
  173. #r[label] = row
  174. ##
  175. ## Let us determine if this is a normal operation or not
  176. ## We will update the status of the information ...
  177. ##
  178. #for row in r[label] :
  179. #index = r[label].index(row)
  180. #if row['label'] in learn:
  181. #id = row['label']
  182. #px = ahandler.predict([row],learn[id])
  183. #if px :
  184. ## row['anomaly'] = px[1]==1
  185. #print ""
  186. #print label,' *** ',index
  187. #row = dict(row,**px)
  188. #r[label][index] =row
  189. ##
  190. ## @TODO:
  191. ## Compile a report here that will be sent to the mailing list
  192. ##
  193. #except Exception, e:
  194. #print e
  195. #r = []
  196. #return json.dumps(r)
  197. """
  198. This function/endpoint will assess n-virtual environments and return the results
  199. @TODO: Should this be stored for future mining (I don't think so but could be wrong)
  200. """
  201. @app.route('/sandbox')
  202. def sandbox():
  203. global CONFIG
  204. if 'sandbox' in CONFIG: #CONFIG['monitor']:
  205. #handler = HANDLERS['sandbox']['class']
  206. #conf = HANDLERS['sandbox']['config']
  207. r = []
  208. # p = Factory.instance('sandbox',CONFIG)
  209. handler = monitor.Sandbox()
  210. conf = CONFIG['sandbox']
  211. for id in conf:
  212. try:
  213. handler.init(conf[id])
  214. r.append (dict(handler.composite(),**{"label":id}))
  215. except Exception,e:
  216. pass
  217. else:
  218. r = []
  219. return json.dumps(r)
  220. #@app.route('/trends')
  221. #def trends ():
  222. #id = request.args.get('id')
  223. #app = request.args.get('app').strip()
  224. #p = CONFIG['store']['args']
  225. #class_read = CONFIG['store']['class']['read']
  226. #gReader = factory.instance(type=class_read,args=p)
  227. #r = gReader.read()
  228. #if id in r:
  229. #r = r[id] #--matrix
  230. #series = []
  231. #for row in r:
  232. #series += [item for item in row if str(item['label'])== app]
  233. #if len(series) > 12 :
  234. #beg = len(series) - 8
  235. #series = series[beg:]
  236. #return json.dumps(series)
  237. #else:
  238. #return "[]"
  239. #@app.route('/download',methods=['POST'])
  240. #def requirements():
  241. #stream = request.form['missing']
  242. #print stream
  243. #stream = "\n".join(json.loads(stream))
  244. #headers = {"content-disposition":"attachment; filename=requirements.txt"}
  245. #return Response(stream,mimetype='text/plain',headers=headers)
  246. @app.route('/dashboard')
  247. def dashboard():
  248. context = PARAMS['context']
  249. if 'title' in PARAMS :
  250. title = PARAMS['title']
  251. else:
  252. title = 'Dashboard'
  253. apps = []
  254. try:
  255. gReader = factory.instance(type=class_read,args=p)
  256. apps = gReader.view('summary/app_names',key=p['uid'])
  257. except Exception, e:
  258. print (e)
  259. return render_template('dashboard.html',context=context,title=title,app_names=apps)
  260. @app.route('/upgrade')
  261. def upgrade():
  262. context = PARAMS['context']
  263. if 'title' in PARAMS :
  264. title = PARAMS['title']
  265. else:
  266. title = 'Upgrade'
  267. return render_template('upgrade.html',context=context,title=title)
  268. @app.route('/user')
  269. def user():
  270. context = PARAMS['context']
  271. if 'title' in PARAMS :
  272. title = PARAMS['title']
  273. else:
  274. title = 'Upgrade'
  275. return render_template('user.html',context=context,title=title)
  276. #"""
  277. #This function is designed to trigger learning for anomaly detection
  278. #@TODO: forward this to a socket i.e non-blocking socket
  279. #"""
  280. #@app.route('/anomalies/get')
  281. #def learn():
  282. #global CONFIG
  283. #p = CONFIG['store']['args']
  284. #class_read = CONFIG['store']['class']['read']
  285. #gReader = factory.instance(type=class_read,args=p)
  286. #d = gReader.read()
  287. #if 'learn' in d :
  288. #info = d['learn']
  289. #del d['learn']
  290. #else :
  291. #info = []
  292. #r = []
  293. #if 'id' in request.args:
  294. #id = request.args['id']
  295. #d = d[id]
  296. #params = {}
  297. #for item in info:
  298. #label = item['label']
  299. #params[label] = item
  300. ##apps = list(set(ML.Extract(['label'],d)))
  301. #r = []
  302. #if params :
  303. ##
  304. ## If we have parameters available
  305. #p = AnomalyDetection()
  306. #apps = params.keys()
  307. #for name in apps :
  308. #if name not in params:
  309. #continue
  310. #_info = params[name]
  311. #try:
  312. #xo = ML.Filter('label',name,d)
  313. #except Exception,e:
  314. #xo = []
  315. ##print name,e
  316. #if len(xo) == 0:
  317. #continue
  318. #xo = [xo[ len(xo) -1]]
  319. #value = p.predict(xo,_info)[0]
  320. #if len(value):
  321. #report = dict(_info,**{'predicton':value})
  322. #r.append(report)
  323. ##print app,value
  324. ##if value is not None:
  325. ## r.append(value)
  326. #return json.dumps(r)
  327. """
  328. This function returns anomalies for a given context or group of processes
  329. The information returned is around precision/recall and f-score and parameters
  330. """
  331. #@app.route('/anomalies/status')
  332. #def anomalies_status():
  333. #global CONFIG
  334. #p = CONFIG['store']['args']
  335. #class_read = CONFIG['store']['class']['read']
  336. #gReader = factory.instance(type=class_read,args=p)
  337. #d = gReader.read()
  338. #if 'learn' in d :
  339. #info = d['learn']
  340. #del d['learn']
  341. #else :
  342. #info = []
  343. #print info
  344. #r = []
  345. #if 'id' in request.args:
  346. #id = request.args['id']
  347. #r = info
  348. #return json.dumps(r)
  349. #@app.route('/folders')
  350. #def get_folders():
  351. #global CONFIG
  352. #p = CONFIG['store']['args']
  353. #class_read = CONFIG['store']['class']['read']
  354. #gReader = factory.instance(type=class_read,args=p)
  355. #d = gReader.read()
  356. #if 'folders' in d:
  357. #d = d['folders']
  358. #hosts = set([row[0]['id'] for row in d])
  359. #m = {}
  360. #for id in hosts:
  361. #for row in d:
  362. #if id == row[0]['id'] :
  363. #m[id] = row
  364. #d = m.values()
  365. #for row in d:
  366. #print row[0]['id']
  367. ## index = len(d) - 1
  368. ## d = d[index]
  369. ## m = {}
  370. ## for row in d :
  371. ## key = row.keys()[0]
  372. ## row = row[key]
  373. ## if key not in m:
  374. ## r.append(row)
  375. ## m[key] = len(r) -1
  376. ## else:
  377. ## index = m[key]
  378. ## r[index] = row
  379. ## d = r
  380. #else:
  381. #d = []
  382. #return json.dumps(d)
  383. if __name__== '__main__':
  384. # ThreadManager.start(CONFIG)
  385. if 'port' not in SYS_ARGS.PARAMS :
  386. SYS_ARGS.PARAMS['port'] = 8484
  387. PORT = int(SYS_ARGS.PARAMS['port'])
  388. app.run(host='0.0.0.0' ,port=PORT,debug=True,threaded=True)