A helper function which returns a dictionary of minion pools along with
    their matching result sets.
    Useful for developing other "survey style" functions.
    Optionally accepts a "survey_sort=up" or "survey_sort=down" kwargs for
    specifying sort order.
    Because the kwargs namespace of the "salt" and "survey" command are shared,
    the name "survey_sort" was chosen to help avoid option conflicts.

def _get_pool_results(*args, **kwargs):
    '''
    A helper function which returns a dictionary of minion pools along with
    their matching result sets.
    Useful for developing other "survey style" functions.
    Optionally accepts a "survey_sort=up" or "survey_sort=down" kwargs for
    specifying sort order.
    Because the kwargs namespace of the "salt" and "survey" command are shared,
    the name "survey_sort" was chosen to help avoid option conflicts.
    '''
    # TODO: the option "survey.sort=" would be preferred for namespace
    # separation but the kwargs parser for the salt-run command seems to
    # improperly pass the options containing a "." in them for later modules to
    # process. The "_" is used here instead.

    import hashlib

    tgt = args[0]
    cmd = args[1]
    ret = {}

    sort = kwargs.pop('survey_sort', 'down')
    direction = sort != 'up'

    tgt_type = kwargs.pop('tgt_type', 'compound')
    if tgt_type not in ['compound', 'pcre']:
        tgt_type = 'compound'

    kwargs_passthru = dict((k, kwargs[k]) for k in six.iterkeys(kwargs) if not k.startswith('_'))

    client = salt.client.get_local_client(__opts__['conf_file'])
    try:
        minions = client.cmd(tgt, cmd, args[2:], timeout=__opts__['timeout'], tgt_type=tgt_type, kwarg=kwargs_passthru)
    except SaltClientError as client_error:
        print(client_error)
        return ret

    # hash minion return values as a string
    for minion in sorted(minions):
        digest = hashlib.sha256(six.text_type(minions[minion]).encode(__salt_system_encoding__)).hexdigest()
        if digest not in ret:
            ret[digest] = {}
            ret[digest]['pool'] = []
            ret[digest]['result'] = six.text_type(minions[minion])

        ret[digest]['pool'].append(minion)

    sorted_ret = []
    for k in sorted(ret, key=lambda k: len(ret[k]['pool']), reverse=direction):
        # return aggregated results, sorted by size of the hash pool

        sorted_ret.append(ret[k])

    return sorted_ret