From: Frank Brehm Date: Tue, 12 Feb 2019 14:35:01 +0000 (+0100) Subject: Adding show-env.py and show-env-html.py and lib/webhooks/show_env.py X-Git-Tag: 1.6.4^2~59 X-Git-Url: https://git.uhu-banane.net/?a=commitdiff_plain;h=7a760e98cc4fec36d0d1242630bc41774af323a5;p=pixelpark%2Fpuppetmaster-webhooks.git Adding show-env.py and show-env-html.py and lib/webhooks/show_env.py --- diff --git a/lib/webhooks/show_env.py b/lib/webhooks/show_env.py new file mode 100644 index 0000000..65bd1bf --- /dev/null +++ b/lib/webhooks/show_env.py @@ -0,0 +1,227 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +@author: Frank Brehm +@contact: frank.brehm@pixelpark.com +@copyright: © 2018 by Frank Brehm, Berlin +@summary: The module for the show-env CGI application to show + information about the current environment variables +""" +from __future__ import absolute_import + +# Standard modules +import logging +import json +import datetime +import re +import textwrap +import os +import shutil + +# Third party modules + +# Own modules +from fb_tools.common import pp, is_sequence + +from . import __version__ + +from .base_app import BaseHookError, BaseHookApp, UncriticalHookError + +from .xlate import XLATOR + +LOG = logging.getLogger(__name__) + +_ = XLATOR.gettext +ngettext = XLATOR.ngettext + + +# ============================================================================= +class ShowEnvError(BaseHookError): + + pass + + +# ============================================================================= +class ShowEnvUncriticalError(ShowEnvError, UncriticalHookError): + + pass + + +# ============================================================================= +class ShowEnvApp(BaseHookApp): + """ + Class for the application objects. + """ + + default_terminal_size = (80, 25) + + re_is_number = re.compile(r'^\d+(\.\d+)?$') + + # ------------------------------------------------------------------------- + def __init__( + self, output_type='json', appname=None, base_dir=None, verbose=0, version=__version__): + """Constructor.""" + + description = _('Shows all environment variables and sonme information about Python.') + + self.filters = None + self.max_line_length = self.default_terminal_size[0] + + super(ShowEnvApp, self).__init__( + appname=appname, base_dir=base_dir, verbose=verbose, + version=version, description=description, output_type=output_type) + + self._html_title = _("Environment") + + # ------------------------------------------------------------------------- + def as_dict(self, short=True): + """ + Transforms the elements of the object into a dict + + @return: structure as dict + @rtype: dict + """ + + res = super(ShowEnvApp, self).as_dict(short=short) + + return res + + # ------------------------------------------------------------------------- + def evaluate_config(self, config, yaml_file): + + super(ShowEnvApp, self).evaluate_config(config, yaml_file) + + # ------------------------------------------------------------------------- + def post_init(self): + + super(ShowEnvApp, self).post_init() + self.initialized = False + + self.read_stdin = False + self.no_error_mail = True + + (width, height) = shutil.get_terminal_size(self.default_terminal_size) + if width: + self.max_line_length = width + + self.initialized = True + + # ------------------------------------------------------------------------- + def run_hook(self): + """Main routine.""" + + if self.output_type == 'html': + self.print_out('

{t}

'.format(t=self.html_title)) + elif self.output_type == 'txt': + len_title = len(self.html_title) + self.print_out("\n{}".format(self.html_title)) + self.print_out("#" * len_title) + self.print_out('') + + self.output_env() + + # ------------------------------------------------------------------------- + def output_env(self): + + if self.output_type == 'json': + self.output_env_json() + elif self.output_type == 'html': + self.output_env_html() + else: + self.output_env_txt() + + # ------------------------------------------------------------------------- + def output_env_json(self): + + output_dict = copy.copy(os.environ) + + indent = None + if self.verbose: + indent = 4 + + self.print_out(json.dumps(output_dict, indent=indent, sort_keys=True)) + + # ------------------------------------------------------------------------- + def output_env_html(self): + + self.print_out('

{}

\n\n'.format(_('All environment variables.'))) + self.print_out('') + self.print_out(' ') + self.print_out(' ') + self.print_out(' ') + self.print_out(' '.format(_('Environment name'))) + self.print_out(' '.format(_('Environment value'))) + self.print_out(' ') + self.print_out(' ') + self.print_out(' ') + + line_class = 'even' + nr_envs = 0 + + for env_key in sorted(os.environ.keys(), key=str.lower): + + env_val = os.environ[env_key] + if not self.re_is_number.match(env_val): + env_val = repr(env_val) + + nr_envs += 1 + if nr_envs % 2: + line_class = 'odd' + else: + line_class = 'even' + + out = ' \n' + out += ' \n'.format(env_key) + out += ' \n'.format(lc=line_class, val=env_val) + out += ' ' + self.print_out(out) + + self.print_out(" ") + self.print_out("
{}{}
{}{val}
") + + # ------------------------------------------------------------------------- + def output_env_txt(self): + + sub_title = _('All environment variables.') + len_title = len(sub_title) + self.print_out("\n{}".format(sub_title)) + self.print_out("#" * len_title) + self.print_out('') + + key_title = _('Environment name') + val_title = _('Environment value') + max_key_len = len(key_title) + for env_key in os.environ.keys(): + if len(env_key) > max_key_len: + max_key_len = len(env_key) + + tpl = '{{key:<{}}} │ {{val}}'.format(max_key_len) + if self.verbose > 2: + LOG.debug("Row template:\n{}".format(tpl)) + + self.print_out(tpl.format(key=key_title, val=val_title)) + underline = '─' * (max_key_len + 1) + underline += '┼' + ('─' * (self.max_line_length - max_key_len - 2)) + self.print_out(underline) + + wrapper = textwrap.TextWrapper() + wrapper.width = self.max_line_length - max_key_len - 3 + wrapper.initial_indent = '' + wrapper.subsequent_indent = (' ' * max_key_len) + ' │ ' + + for env_key in sorted(os.environ.keys(), key=str.lower): + env_val = os.environ[env_key] + if not self.re_is_number.match(env_val): + env_val = repr(env_val) + self.print_out(tpl.format(key=env_key, val=wrapper.fill(env_val))) + + self.print_out() + + +# ============================================================================= +if __name__ == "__main__": + + pass + +# ============================================================================= +# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 list diff --git a/show-env-html.py b/show-env-html.py new file mode 100755 index 0000000..44977eb --- /dev/null +++ b/show-env-html.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +# Standard modules +import sys +import logging + +from pathlib import Path + +# own modules: +my_path = Path(__file__) +my_real_path = my_path.resolve() +base_dir = my_real_path.parent +libdir = base_dir.joinpath('lib') + +sys.path.insert(0, str(libdir)) + +from webhooks.show_env import ShowEnvApp + +MY_APPNAME = my_path.stem +LOG = logging.getLogger(MY_APPNAME) + +app = ShowEnvApp(output_type='html', appname=MY_APPNAME, base_dir=base_dir) + +if app.verbose > 2: + LOG.debug("{c} object:\n{o}".format(c=app.__class__.__name__, o=app)) + +app() + +sys.exit(0) + +# vim: ts=4 et diff --git a/show-env.py b/show-env.py new file mode 100755 index 0000000..9a5fc2a --- /dev/null +++ b/show-env.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +# Standard modules +import sys +import logging + +from pathlib import Path + +# own modules: +my_path = Path(__file__) +my_real_path = my_path.resolve() +base_dir = my_real_path.parent +libdir = base_dir.joinpath('lib') + +sys.path.insert(0, str(libdir)) + +from webhooks.show_env import ShowEnvApp + +MY_APPNAME = my_path.stem +LOG = logging.getLogger(MY_APPNAME) + +app = ShowEnvApp(output_type='txt', appname=MY_APPNAME, base_dir=base_dir) + +if app.verbose > 2: + LOG.debug("{c} object:\n{o}".format(c=app.__class__.__name__, o=app)) + +app() + +sys.exit(0) + +# vim: ts=4 et