index.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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. """
  10. from flask import Flask, session, request, redirect, Response
  11. from flask.templating import render_template
  12. from flask_session import Session
  13. import time
  14. import sys
  15. import os
  16. import json
  17. import re
  18. import monitor
  19. import Queue
  20. from utils.transport import *
  21. from utils.workers import ThreadManager, Factory
  22. from utils.ml import ML,AnomalyDetection
  23. import utils.params as SYS_ARGS
  24. import atexit
  25. app = Flask(__name__)
  26. app.config['SECRET_KEY'] = '!h8-[0v8]247-4-360'
  27. #app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX=?RT'
  28. PARAMS = SYS_ARGS.PARAMS
  29. f = open(PARAMS['path'])
  30. CONFIG = json.loads(f.read())
  31. f.close()
  32. #
  33. #
  34. #from threading import Thread, RLock
  35. p = CONFIG['store']['args']
  36. class_read = CONFIG['store']['class']['read']
  37. class_write= CONFIG['store']['class']['write']
  38. factory = DataSourceFactory()
  39. gReader = factory.instance(type=class_read,args=p)
  40. atexit.register(ThreadManager.stop)
  41. @app.route('/get/<id>')
  42. def procs(id):
  43. try:
  44. gReader = factory.instance(type=class_read,args=p)
  45. d = gReader.read()
  46. r = {}
  47. for label in d :
  48. if label not in ['learn'] :
  49. index = len(d[label]) - 1
  50. r[label] = d[label][index]
  51. #for row in r[label] :
  52. #yo = ML.Extract(['status'],row)
  53. #xo = ML.Extract(['cpu_usage','memory_usage'],row)
  54. except Exception, e:
  55. print e
  56. r = []
  57. return json.dumps(r)
  58. """
  59. This function/endpoint will assess n-virtual environments and return the results
  60. @TODO: Should this be stored for future mining (I don't think so but could be wrong)
  61. """
  62. @app.route('/sandbox')
  63. def sandbox():
  64. global CONFIG
  65. if 'sandbox' in CONFIG['monitor']:
  66. #handler = HANDLERS['sandbox']['class']
  67. #conf = HANDLERS['sandbox']['config']
  68. r = []
  69. p = Factory.instance('sandbox',CONFIG)
  70. handler = p['class']
  71. conf = p['config']
  72. for id in conf:
  73. handler.init(conf[id])
  74. r.append (dict(handler.composite(),**{"label":id}))
  75. else:
  76. r = []
  77. return json.dumps(r)
  78. @app.route('/trends')
  79. def trends ():
  80. id = request.args.get('id')
  81. app = request.args.get('app').strip()
  82. p = CONFIG['store']['args']
  83. class_read = CONFIG['store']['class']['read']
  84. gReader = factory.instance(type=class_read,args=p)
  85. r = gReader.read()
  86. if id in r:
  87. r = r[id] #--matrix
  88. series = []
  89. for row in r:
  90. series += [item for item in row if str(item['label'])== app]
  91. if len(series) > 12 :
  92. beg = len(series) - 13
  93. series = series[beg:]
  94. return json.dumps(series)
  95. else:
  96. return "[]"
  97. @app.route('/download',methods=['POST'])
  98. def requirements():
  99. stream = request.form['missing']
  100. stream = "\n".join(json.loads(stream))
  101. headers = {"content-disposition":"attachment; filename=requirements.txt"}
  102. return Response(stream,mimetype='text/plain',headers=headers)
  103. @app.route('/dashboard')
  104. def dashboard():
  105. context = PARAMS['context']
  106. return render_template('dashboard.html',context=context)
  107. """
  108. This function is designed to trigger learning for anomaly detection
  109. @TODO: forward this to a socket i.e non-blocking socket
  110. """
  111. @app.route('/learn')
  112. def learn():
  113. global CONFIG
  114. p = CONFIG['store']['args']
  115. class_read = CONFIG['store']['class']['read']
  116. gReader = factory.instance(type=class_read,args=p)
  117. d = gReader.read()
  118. if 'learn' in d :
  119. logs = d['learn']
  120. del d['learn']
  121. else :
  122. logs = []
  123. r = []
  124. if 'id' in request.args:
  125. id = request.args['id']
  126. d = d[id]
  127. print CONFIG['monitor']['processes']['config'][id]
  128. print (apps)
  129. #apps = list(set(ML.Extract(['label'],d)))
  130. p = AnomalyDetection()
  131. #for row in d :
  132. #xo = ML.Filter('label',app,d)
  133. #info = ML.Filter('label',app,logs)
  134. #value = p.predict(xo,info)
  135. #print app,value
  136. #if value is not None:
  137. # r.append(value)
  138. print r
  139. return json.dumps("[]")
  140. @app.route('/anomalies/status')
  141. def anomalies_status():
  142. pass
  143. @app.route('/anomalies/get')
  144. def anomalies_get():
  145. pass
  146. if __name__== '__main__':
  147. #ThreadManager.start(CONFIG)
  148. app.run(host='0.0.0.0',debug=True,threaded=True)