diff --git a/fih.py b/fih.py index b4a4958..fb065b4 100644 --- a/fih.py +++ b/fih.py @@ -3,6 +3,16 @@ from flask import Flask, request import os import incident import datetime +import subprocess +import re + + +def strip_ansi( text, escape = re.compile( r'\x1B\[[0-?]*[ -/]*[@-~]' ) ): + return escape.sub( '', text ) + +def strip_progress( text, escape = re.compile( r'\r[^\n]*\n' ) ): + return escape.sub( '', text ) + app = Flask( __name__ ) app.config.from_envvar( 'FIH_SETTINGS' ) @@ -96,9 +106,70 @@ Again, after setting the headline status you must: **@FIH PUBLISH** return "Invalid command token." @app.route( '/mattermost/fih', methods = [ 'POST' ] ) -def mattermost_fig(): - print( repr( request.form ) ) - return "Whaaat?" +def mattermost_fih(): + # text: @FIH PUBLISH + # file_ids: + # user_name: marek + # trigger_word: @FIH + # channel_name: incident201806158693 + # timestamp: 1529100914 + # channel_id: zq61mk8ig7rmibtbyqf4babhfr + # team_id: 3woo8mbjrbb1in53xwdzi4ynqh + # token: nn54y4ozbtnzb8pri3c4gdhbce + # user_id: ko3uxmend7ne8ger4uw9mxkt1o + # team_domain: faelix + # post_id: 8cxn8yeyepyczcfbazdsd1bonw + + if request.form[ 'token' ] in app.config[ 'MATTERMOST_WEBHOOK_TOKENS' ]: + cmd = request.form[ 'text' ].strip().split()[ 1 ].upper() + + app.mm.posts.create_post( options = { 'channel_id': request.form[ 'channel_id' ], + 'message': "Executing " + cmd + "...", + } ) + + if cmd == "PUBLISH": + for push_to in app.config[ "GROW_DEPLOY_TO" ]: + cmdline = app.config[ "GROW_BIN" ] + " deploy -f " + push_to + results = "`" + cmdline + "`:\n\n```\n" + + process = subprocess.Popen( cmdline, shell = True, cwd = app.config[ "STATUS_ROOT" ], stdout = subprocess.PIPE, stderr = subprocess.PIPE ) + + results += strip_progress( strip_ansi( process.stdout.read().decode( 'ascii', 'ignore' ) ) ).replace( "```", "` ` `" ) + results += "```\n" + stderr = strip_progress( strip_ansi( process.stderr.read().decode( 'ascii', 'ignore' ) ) ) + if stderr: + results += "\n\n```\n" + stderr.replace( "```", "` ` `" ) + "```\n" + + app.mm.posts.create_post( options = { 'channel_id': request.form[ 'channel_id' ], + 'message': results, + } ) + + elif cmd == "START": + pass + elif cmd == "ETR": + pass + elif cmd == "RESOLVED": + pass + elif cmd == "CLOSED": + pass + elif cmd == "TIMELINE": + pass + elif cmd == "INCIDENT": + pass + elif cmd == "DEGRADED": + pass + elif cmd == "MAINTENANCE": + pass + elif cmd == "NOTICE": + pass + elif cmd == "OK": + pass + else: + return "WTF command?" + + return "OK" + else: + return "Invalid command token." @app.route( '/' ) def hello_world():