Advertisement
Guest User

Untitled

a guest
Nov 30th, 2016
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.53 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. import re
  5.  
  6. import flask
  7.  
  8. import settings
  9.  
  10. import pg
  11.  
  12. # some aliasses
  13. request = flask.request
  14. Response = flask.Response
  15. json = flask.json
  16.  
  17. app = flask.Flask(__name__)
  18.  
  19.  
  20. @app.route('/', methods=['POST'])
  21. def receive_mattermost():
  22.     """We only have 1 incoming hook"""
  23.     form = request.form
  24.  
  25.     command = form['command']
  26.     token = form['token']
  27.  
  28.     run_id = form['text']
  29.  
  30.     if run_id is None:
  31.         return ''
  32.     if command == '/runstatus':
  33.         if settings.MATTERMOST_RUNSTATUS_TOKEN:
  34.             if not token == settings.MATTERMOST_RUNSTATUS_TOKEN:
  35.                 app.logger.error('Received wrong token, received [%s]', token)
  36.                 return ''
  37.         resp = get_run_status_json(run_id, False)
  38.     elif command == '/runcheck':
  39.         if settings.MATTERMOST_WHISPER_TOKEN:
  40.             if not token == settings.MATTERMOST_WHISPER_TOKEN:
  41.                 app.logger.error('Received wrong token, received [%s]', token)
  42.                 return ''
  43.         resp = get_run_status(run_id, True)
  44.     else:
  45.         resp = None
  46.     if resp is None:
  47.         return ''
  48.     return resp
  49.  
  50.  
  51. def get_run_status(run_id, whisper):
  52.     resp = execute_pg_req(run_id)
  53.     if resp['percentage_done'] < 0.25:
  54.         color = '#ff5400'
  55.     elif resp['percentage_done'] < 0.5:
  56.         color = '#ff9000'
  57.     elif resp['percentage_done'] < 0.75:
  58.         color = '#ffe400'
  59.     else:
  60.         color = 'good'
  61.     if whisper:
  62.         resp_type = 'ephemeral'
  63.     else:
  64.         resp_type= 'in_channel'
  65.     jresp = json.dumps({'response_type': resp_type,
  66.                         'text': ('#### Run '+ run_id +' status on ' +
  67.                                  settings.user +
  68.                                  '\n| Run duration | Completed | Sources processed | Total Sources | Sources/min | Estimated Remaining time |\n'
  69.                                  '| :----------: | :-------: | :---------------: | :-----------: | :---------: | :----------------------: |\n'
  70.                                  '| ' + resp['run_duration'] + ' | ' + str('%.2f' % (resp['percentage_done'] * 100)) +
  71.                                  '% | ' + str('%.0f' % resp['processed']) + ' | '
  72.                                  '' + str('%.0f' % resp['total_sources']) + ' | ' +
  73.                                  str('%.2f' % resp['sources_per_min']) + ' | ' +
  74.                                  resp['time_remaining_estimate'] + ' |\n'
  75.                                  )
  76.                         })
  77.     return Response(jresp, status=200, mimetype='application/json')
  78.  
  79.  
  80. def get_run_status_json(run_id, whisper):
  81.     resp = execute_pg_req(run_id)
  82.     if whisper:
  83.         resp_type = 'ephemeral'
  84.     else:
  85.         resp_type= 'in_channel'
  86.     if resp['percentage_done'] < 0.25:
  87.         color = '#ff5400'
  88.     elif resp['percentage_done'] < 0.5:
  89.         color = '#ff9000'
  90.     elif resp['percentage_done'] < 0.75:
  91.         color = '#ffe400'
  92.     else:
  93.         color = 'good'
  94.     jresp = json.dumps({'response_type': resp_type,
  95.                         'text': ('Run status on ' + settings.user),
  96.                         'attachments': [
  97.                             {
  98.                                 'color': color,
  99.                                 'pretext': 'Run progress',
  100.                                 'title': ('Run ' + run_id),
  101.                                 'fields': [
  102.                                     {
  103.                                         'title': 'Time since created',
  104.                                         'value': str(resp['run_duration']),
  105.                                         'short': 'true'
  106.                                     },
  107.                                     {
  108.                                         'title': 'Completed',
  109.                                         'value': str('%.2f' % (resp['percentage_done'] * 100)),
  110.                                         'short': 'true'
  111.                                     }
  112.                                 ]
  113.                             },
  114.                             {
  115.                                 'color': '#888888',
  116.                                 'pretext': 'Detailed statistics',
  117.                                 'title': run_id,
  118.                                 'fields': [
  119.                                     {
  120.                                         'title': 'Sources Processed',
  121.                                         'value': str('%.f' % resp['processed']),
  122.                                         'short': 'true'
  123.                                     },
  124.                                     {
  125.                                         'title': 'Total Sources',
  126.                                         'value': str('%.f' % resp['total_sources']),
  127.                                         'short': 'true'
  128.                                     },
  129.                                     {
  130.                                         'title': 'Sources per minute',
  131.                                         'value': str('%.f' % resp['sources_per_min']),
  132.                                         'short': 'true'
  133.                                     },
  134.                                     {
  135.                                         'title': 'Estimated Completion',
  136.                                         'value': str(resp['time_remaining_estimate']),
  137.                                         'short': 'true'
  138.                                     }
  139.                                 ]
  140.                             }
  141.                         ]
  142.                         }
  143.                        )
  144.     print(jresp)
  145.     response = Response(jresp, status=200, mimetype='application/json')
  146.     return response
  147.  
  148.  
  149. def execute_pg_req(runid):
  150.     connection = pg.connect(dbname=settings.db, host=settings.host, port=settings.port, user=settings.user,
  151.                             passwd=settings.passwd)
  152.     query = connection.query('select * from getactiverunstatistics(' + runid + ');')
  153.     speeds = query.dictresult()[0]
  154.     nquery = connection.query('select fname, size from catalog where catalogid=getruncatalogid(' + runid + ')')
  155.     connection.close()
  156.     speeds.update(nquery.dictresult()[0])
  157.     return speeds
  158.  
  159.  
  160. # def search_token(text):
  161. #     """Search in the provided text for a match on the regexp, and return"""
  162. #     match = re.search('(%s)' % settings.TICKET_REGEXP, text)
  163. #     if match:
  164. #         return match.group(0)
  165. #     else:
  166. #         return None
  167.  
  168. if __name__ == '__main__':
  169.     app.run(host='0.0.0.0', debug=True)
  170.  
  171. # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement