From 07a59331c812d0d09774ce77bdf2aa258e6ca21a Mon Sep 17 00:00:00 2001 From: Frank Brehm Date: Fri, 7 Sep 2018 15:52:29 +0200 Subject: [PATCH] Finishing generating Mails --- lib/webhooks/__init__.py | 2 +- lib/webhooks/base_app.py | 87 +++++++++++++++++++++++++++--- lib/webhooks/get_module_changes.py | 17 +++++- 3 files changed, 98 insertions(+), 8 deletions(-) diff --git a/lib/webhooks/__init__.py b/lib/webhooks/__init__.py index 19b0251..be3f767 100644 --- a/lib/webhooks/__init__.py +++ b/lib/webhooks/__init__.py @@ -1,6 +1,6 @@ #!/bin/env python3 # -*- coding: utf-8 -*- -__version__ = '0.12.5' +__version__ = '0.12.6' # vim: ts=4 et list diff --git a/lib/webhooks/base_app.py b/lib/webhooks/base_app.py index 3944362..acf8061 100644 --- a/lib/webhooks/base_app.py +++ b/lib/webhooks/base_app.py @@ -22,6 +22,8 @@ import io import cgi import textwrap import copy +import socket +import pwd from email.message import EmailMessage @@ -47,7 +49,8 @@ __version__ = webhooks.__version__ LOG = logging.getLogger(__name__) DEFAULT_FROM_EMAIL = 'puppetmaster@pixelpark.com' -DEFAULT_FROM_SENDER = 'Puppetmaster <{}>'.format(DEFAULT_FROM_EMAIL) +DEFAULT_FROM_SENDER = 'Puppetmaster at {h} <{a}>'.format( + h=socket.gethostname(), a=DEFAULT_FROM_EMAIL) DEFAULT_TO_EMAIL = 'puppet@pixelpark.com' DEFAULT_TO_SENDER = 'Puppet <{}>'.format(DEFAULT_TO_EMAIL) @@ -92,6 +95,8 @@ class BaseHookApp(BaseObject): default_output_type = 'txt' default_mime_type = valid_output_types[default_output_type] + re_selbstlaut = re.compile(r'^[ieaouy]', re.IGNORECASE) + open_args = {} if six.PY3: open_args = { @@ -117,6 +122,8 @@ class BaseHookApp(BaseObject): self._html_title = None self._no_error_mail = False self._cachefile = self.default_cachefile_stem + self._mail_subject = None + self._mail_headline = None if not hasattr(self, '_output_type'): self._output_type = self.default_output_type @@ -160,6 +167,13 @@ class BaseHookApp(BaseObject): self.mail_cc_addresses = [self.default_email,] self.sender_address = DEFAULT_FROM_SENDER + try: + pwd_info = pwd.getpwuid(os.geteuid()) + self.sender_address = "{u} at {h} <{a}>".format( + u=pwd_info.pw_name, h=socket.gethostname(), a=DEFAULT_FROM_EMAIL) + except Exception as e: + sys.stderr.write("\n{cn}: {e}\n\n".format(cn=e.__class__.__name__, e=e)) + self._log_directory = os.sep + os.path.join('var', 'log', 'webhooks') self.do_arg_parser() @@ -225,6 +239,44 @@ class BaseHookApp(BaseObject): return self._html_title return self.appname + # ----------------------------------------------------------- + @property + def mail_subject(self): + """The subject to use for sending the mail.""" + return self._mail_subject + + @mail_subject.setter + def mail_subject(self, value): + if not to_bool(value): + self._mail_subject = None + return + + val = str(value).strip() + if val == '': + self._mail_subject = None + return + + self._mail_subject = val + + # ----------------------------------------------------------- + @property + def mail_headline(self): + """The subject to use for sending the mail.""" + return self._mail_headline + + @mail_headline.setter + def mail_headline(self, value): + if not to_bool(value): + self._mail_headline = None + return + + val = str(value).strip() + if val == '': + self._mail_headline = None + return + + self._mail_headline = val + # ----------------------------------------------------------- @property def log_directory(self): @@ -317,6 +369,8 @@ class BaseHookApp(BaseObject): res['no_error_mail'] = self.no_error_mail res['open_args'] = self.open_args res['main_branches'] = copy.copy(self.main_branches) + res['mail_subject'] = self.mail_subject + res['mail_headline'] = self.mail_headline return res @@ -399,6 +453,9 @@ class BaseHookApp(BaseObject): arg_parser.print_usage(sys.stdout) sys.exit(0) + if self.cmdline_args.no_error_mail: + self.no_error_mail = True + if self.cmdline_args.data_dir: path = self.cmdline_args.data_dir if not os.path.isabs(path): @@ -530,6 +587,9 @@ class BaseHookApp(BaseObject): if 'default_email' in config and config['default_email']: self.default_email = config['default_email'] + if 'sender_address' in config and config['sender_address']: + self.sender_address = config['sender_address'] + if 'smtp_server' in config and config['smtp_server'].strip(): self.smtp_server = config['smtp_server'].strip() @@ -697,18 +757,28 @@ class BaseHookApp(BaseObject): if self.pre_run(): self.run() except BaseHookError as e: - msg = "Got a {n} performing {a}: {e}".format( - n=e.__class__.__name__, a=self.appname, e=e) + cn = e.__class__.__name__ + n = '' + if self.re_selbstlaut.match(cn): + n = 'n' + msg = "Got a{n} {cn} performing {a}: {e}".format(n=n, cn=cn, a=self.appname, e=e) self.error_data.append(msg) LOG.error(msg) except Exception as e: - msg = "Got a {n} performing {a}: {e}".format( - n=e.__class__.__name__, a=self.appname, e=e) + cn = e.__class__.__name__ + n = '' + if self.re_selbstlaut.match(cn): + n = 'n' + msg = "Got a{n} {cn} performing {a}: {e}".format(n=n, cn=cn, a=self.appname, e=e) msg += "\n\nTraceback:\n{}".format(traceback.format_exc()) self.error_data.append(msg) LOG.error(msg) except Exception as e: - msg = "Got a {n} reading input data as JSON: {e}".format(n=e.__class__.__name__, e=e) + cn = e.__class__.__name__ + n = '' + if self.re_selbstlaut.match(cn): + n = 'n' + msg = "Got a{n} {cn} reading input data as JSON: {e}".format(n=n, cn=cn, e=e) msg += "\nInput data: {!r}".format(self.data) LOG.error(msg) self.error_data.append(msg) @@ -864,6 +934,7 @@ class BaseHookApp(BaseObject): if len(self.error_data) > 1: s = 's' + if project: body = 'Error{s} while processing {p!r} project:\n\n'.format( s=s, p=project) @@ -874,6 +945,10 @@ class BaseHookApp(BaseObject): s=s, a=self.appname) subject = 'Puppetmaster error{s} processing {a!r}'.format( s=s, a=self.appname) + if self.mail_subject: + subject = self.mail_subject + if self.mail_headline: + body = self.mail_headline + '\n\n' body += '\n'.join(self.error_data) body += '\n\nCheers\nPuppetmaster' msg.set_content(body) diff --git a/lib/webhooks/get_module_changes.py b/lib/webhooks/get_module_changes.py index 24a61c0..7f7f0ef 100644 --- a/lib/webhooks/get_module_changes.py +++ b/lib/webhooks/get_module_changes.py @@ -21,6 +21,7 @@ import grp import errno import sys import re +import time from operator import itemgetter @@ -160,7 +161,7 @@ class GetModuleChangesApp(BaseHookApp): def post_init(self): self.read_stdin = False - self.no_error_mail = True + #self.no_error_mail = True self.initialized = True @@ -244,12 +245,24 @@ class GetModuleChangesApp(BaseHookApp): # ------------------------------------------------------------------------- def generate_version_msgs(self, version_infos): + self.mail_subject = ( + "Check for newer versions of Puppet modules in environment {!r}").format( + self.environment) + + self.mail_headline = ( + "Results of checking for newer versions of Puppet modules " + "in environment {!r}:").format(self.environment) + + dt = datetime.datetime.fromtimestamp(time.time(), tz=self.tz) + dt_str = dt.strftime('%Y-%m-%d %H:%M:%S %Z') + if not version_infos: msg = ( "Didn't found any modules in environment {!r} with a\n" "newer version on Puppet Forge.\n\n:-D" ).format(self.environment) self.error_data.append(msg) + self.error_data.append("\nChecked at: {}".format(dt_str)) return s = '' @@ -306,6 +319,8 @@ class GetModuleChangesApp(BaseHookApp): forge_version=str(version_info['forge_version']) )) + self.error_data.append("\nChecked at: {}".format(dt_str)) + # ============================================================================= if __name__ == "__main__": -- 2.39.5