Skip to content
This repository has been archived by the owner on May 20, 2024. It is now read-only.

Commit

Permalink
Update slack notify script for Python 3 (#1448)
Browse files Browse the repository at this point in the history
* Fix Slack notification script for Python 3
* Remove email of stack trace
  • Loading branch information
samdoran authored Oct 12, 2020
1 parent 045af07 commit a6629f4
Showing 1 changed file with 5 additions and 37 deletions.
42 changes: 5 additions & 37 deletions scripts/slack-notice.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@
# Post message to Slack

import argparse
import ConfigParser
import os
import requests

from subprocess import Popen, PIPE
try:
import configparser
except ImportError:
import ConfigParser as configparser


def get_config(args):
Expand All @@ -19,7 +21,7 @@ def get_config(args):
if args.config_file:
config_file_path = args.config_file

ini_file = ConfigParser.ConfigParser()
ini_file = configparser.ConfigParser()
ini_file.read(config_file_path)
return ini_file

Expand All @@ -31,56 +33,22 @@ def parse_args():
parser.add_argument('--message', '-m', type=str, help='Message to post')
parser.add_argument('--config-file', '-f', type=str, help='Path to config file')
parser.add_argument('--user', '-u', type=str, help='User account that runs Ansibullbot')
parser.add_argument('--email-trace', '-e', dest='email_trace', default=False, action='store_true', help='Send an email containing the latest stack trace.')

args = parser.parse_args()
return args


def send_email(email):

# Get the last few lines of the file
with open('/var/log/ansibullbot.log', 'r') as log_file:
log_file.seek(0, 2)
log_length = log_file.tell()
log_file.seek(max(log_length - 4096, 0), 0)
lines = log_file.readlines()

# Return lines before and after the error message
block = []
for i in range(len(lines)):
if 'ERROR Uncaught exception' in lines[i]:
block = lines[max(0, i - 20):min(len(lines), i + 20)]

# Turn the list into a string
message = ''.join(block)

# Send email only if there is a recent stack trace
if len(message) > 0:
print(email)
p = Popen(['mail', '-s', 'Ansibullbot Stack Trace', '-r', 'Ansibullbot<noreply@ansibullbot.eng.ansible.com>', email],
stdin=PIPE,
stdout=PIPE,
stderr=PIPE,
)
p.communicate(input=message)


def main():
args = parse_args()
ini_file = get_config(args)
url = ini_file.get('defaults', 'slack_url')
email = ini_file.get('defaults', 'email')

message = 'Ansibullbot restarted'
if args.message:
message = args.message

requests.post(url, json={'text': message})

if args.email_trace:
send_email(email)


if __name__ == '__main__':
main()

0 comments on commit a6629f4

Please sign in to comment.