index.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  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. We designed the classes to be reusable (and powered by labels):
  5. 'monitoring-type':
  6. 'class':'<class-name>'
  7. 'config':<labeled-class-specific-configuration>'
  8. """
  9. from flask import Flask, session, request, redirect, Response
  10. from flask.templating import render_template
  11. from flask_session import Session
  12. import time
  13. import sys
  14. import os
  15. import json
  16. import re
  17. import monitor
  18. import Queue
  19. from utils.transport import *
  20. PARAMS = {'context':''}
  21. if len(sys.argv) > 1:
  22. N = len(sys.argv)
  23. for i in range(1,N):
  24. value = None
  25. if sys.argv[i].startswith('--'):
  26. key = sys.argv[i].replace('-','')
  27. if i + 1 < N:
  28. value = sys.argv[i + 1] = sys.argv[i+1].strip()
  29. if key and value:
  30. PARAMS[key] = value
  31. i += 2
  32. app = Flask(__name__)
  33. f = open(PARAMS['path'])
  34. CONFIG = json.loads(f.read())
  35. HANDLERS= {}
  36. for key in CONFIG['monitor'] :
  37. className = CONFIG['monitor'][key]['class']
  38. ref = "".join(["monitor.",className,"()"])
  39. ref = eval(ref)
  40. HANDLERS[key] = {"class":ref,"config":CONFIG['monitor'][key]["config"]}
  41. f.close()
  42. #
  43. #
  44. from threading import Thread, RLock
  45. p = CONFIG['store']['args']
  46. class_read = CONFIG['store']['class']['read']
  47. class_write= CONFIG['store']['class']['write']
  48. factory = DataSourceFactory()
  49. #gWriter = factory.instance(type='CouchdbWritera',args=p)
  50. #gReader = factory.instance(type='CouchdbReader',args=p)
  51. p['qid'] = HANDLERS['processes']['config'].keys()
  52. gReader = factory.instance(type=class_read,args=p)
  53. gWriter = factory.instance(type=class_write,args=p)
  54. mthread = monitor.Monitor(HANDLERS,gWriter,'processes',)
  55. @app.route('/get/<id>')
  56. def procs(id):
  57. try:
  58. d = gReader.read()
  59. r = {}
  60. for label in d :
  61. index = len(d[label]) - 1
  62. r[label] = d[label][index]
  63. except Exception, e:
  64. print e
  65. r = []
  66. return json.dumps(r)
  67. """
  68. This function/endpoint will assess n-virtual environments and return the results
  69. @TODO: Should this be stored for future mining (I don't think so but could be wrong)
  70. """
  71. @app.route('/sandbox')
  72. def sandbox():
  73. if 'sandbox' in HANDLERS:
  74. handler = HANDLERS['sandbox']['class']
  75. conf = HANDLERS['sandbox']['config']
  76. r = []
  77. for id in conf:
  78. handler.init(conf[id])
  79. r.append (dict(handler.composite(),**{"label":id}))
  80. else:
  81. print 'Oops'
  82. r = []
  83. return json.dumps(r)
  84. @app.route('/trends')
  85. def trends ():
  86. id = request.args.get('id')
  87. app = request.args.get('app').strip()
  88. p = CONFIG['store']['args']
  89. class_read = CONFIG['store']['class']['read']
  90. p['qid'] =[id] #HANDLERS['processes']['config'].keys()
  91. gReader = factory.instance(type=class_read,args=p)
  92. r = gReader.read()
  93. if id in r:
  94. r = r[id] #--matrix
  95. series = []
  96. for row in r:
  97. series += [item for item in row if str(item['label'])== app]
  98. if len(series) > 12 :
  99. beg = len(series) - 13
  100. series = series[beg:]
  101. return json.dumps(series)
  102. else:
  103. return "[]"
  104. @app.route('/download',methods=['POST'])
  105. def requirements():
  106. stream = request.form['missing']
  107. stream = "\n".join(json.loads(stream))
  108. headers = {"content-disposition":"attachment; filename=requirements.txt"}
  109. return Response(stream,mimetype='text/plain',headers=headers)
  110. @app.route('/dashboard')
  111. def dashboard():
  112. context = PARAMS['context']
  113. return render_template('dashboard.html',context=context)
  114. """
  115. This function is designed to trigger learning for anomaly detection
  116. @TODO: forward this to a socket i.e non-blocking socket
  117. """
  118. @app.route('/learn')
  119. def learn():
  120. app = request.args.get('app')
  121. id = request.args.get('id')
  122. p = CONFIG['store']['args']
  123. class_read = CONFIG['store']['class']['read']
  124. p['qid'] =[id] #HANDLERS['processes']['config'].keys()
  125. gReader = factory.instance(type=class_read,args=p)
  126. r = gReader.read()
  127. r = r[id]
  128. r = ML.Filter('label',app,r)
  129. label = ML.Extract(['status'],r)
  130. r = ML.Extract(['cpu_usage','memory_usage'],r)
  131. if __name__== '__main__':
  132. mthread.start()
  133. app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX=?RT'
  134. app.run(host='0.0.0.0',debug=True,threaded=True)