From 88fc39b1fc4dc5e34f84fe07e78a2cf306068250 Mon Sep 17 00:00:00 2001 From: Erik Johnson Date: Sun, 26 Aug 2018 20:45:57 -0500 Subject: [PATCH] Add DSON outputter We have a renderer, only fair that we also have an outputter. This also fixes the DSON renderer so that that we don't needlessly log a trace-level message about failing to import dson. --- salt/output/dson.py | 74 ++++++++++++++++++++++++++++++++++++++++++ salt/renderers/dson.py | 2 +- 2 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 salt/output/dson.py diff --git a/salt/output/dson.py b/salt/output/dson.py new file mode 100644 index 000000000000..a337a02cf9ba --- /dev/null +++ b/salt/output/dson.py @@ -0,0 +1,74 @@ +# -*- coding: utf-8 -*- +''' +Display return data in DSON format +================================== + +This outputter is intended for demonstration purposes. Information on the DSON +spec can be found `here`__. + +.. __: http://vpzomtrrfrt.github.io/DSON/ + +This outputter requires `Dogeon`__ (installable via pip) + +.. __: https://github.com/soasme/dogeon +''' +from __future__ import absolute_import, print_function, unicode_literals + +# Import python libs +import logging + +# Import 3rd-party libs +try: + import dson +except ImportError: + dson = None + +from salt.ext import six + +log = logging.getLogger(__name__) + + +def __virtual__(): + if dson is None: + return (False, 'The dogeon Python package is not installed') + return True + + +def output(data, **kwargs): # pylint: disable=unused-argument + ''' + Print the output data in JSON + ''' + try: + dump_opts = {'indent': 4, 'default': repr} + + if 'output_indent' in __opts__: + + indent = __opts__.get('output_indent') + sort_keys = False + + if indent == 'pretty': + indent = 4 + sort_keys = True + + elif isinstance(indent, six.integer_types): + if indent >= 0: + indent = indent + else: + indent = None + + dump_opts['indent'] = indent + dump_opts['sort_keys'] = sort_keys + + return dson.dumps(data, **dump_opts) + + except UnicodeDecodeError as exc: + log.error('Unable to serialize output to dson') + return dson.dumps( + {'error': 'Unable to serialize output to DSON', + 'message': six.text_type(exc)} + ) + + except TypeError: + log.debug('An error occurred while outputting DSON', exc_info=True) + # Return valid JSON for unserializable objects + return dson.dumps({}) diff --git a/salt/renderers/dson.py b/salt/renderers/dson.py index a7e1f50303ba..6adf99acf145 100644 --- a/salt/renderers/dson.py +++ b/salt/renderers/dson.py @@ -30,7 +30,7 @@ def __virtual__(): if dson is None: - return False, 'Failed to load: dson module not installed' + return (False, 'The dogeon Python package is not installed') return True