Get Ubuntu release codename from sentry unit.

        :param sentry_unit: amulet sentry/service unit pointer
        :returns: list of strings - release codename, failure message
544358
def get_ubuntu_release_from_sentry(self, sentry_unit):
        
        msg = None
        cmd = 'lsb_release -cs'
        release, code = sentry_unit.run(cmd)
        if code == 0:
            self.log.debug('{} lsb_release: {}'.format(
                sentry_unit.info['unit_name'], release))
        else:
            msg = ('{} `{}` returned {} '
                   '{}'.format(sentry_unit.info['unit_name'],
                               cmd, release, code))
        if release not in self.ubuntu_releases:
            msg = ("Release ({}) not found in Ubuntu releases "
                   "({})".format(release, self.ubuntu_releases))
        return release, msg
7893
def as_tuple(ireq):
    

    if not is_pinned_requirement(ireq):
        raise TypeError("Expected a pinned InstallRequirement, got {}".format(ireq))

    name = key_from_req(ireq.req)
    version = first(ireq.specifier._specs)._spec[1]
    extras = tuple(sorted(ireq.extras))
    return name, version, extras
979117
def wstatus_to_str(status):
    
    if os.WIFEXITED(status):
        return 'exited with return code %d' % (os.WEXITSTATUS(status),)
    if os.WIFSIGNALED(status):
        n = os.WTERMSIG(status)
        return 'exited due to signal %d (%s)' % (n, SIGNAL_BY_NUM.get(n))
    if os.WIFSTOPPED(status):
        n = os.WSTOPSIG(status)
        return 'stopped due to signal %d (%s)' % (n, SIGNAL_BY_NUM.get(n))
    return 'unknown wait status (%d)' % (status,)
1160694
def get_release_id(self, package_name: str, version: str) -> bytes:
        
        validate_package_name(package_name)
        validate_package_version(version)
        self._validate_set_registry()
        return self.registry._get_release_id(package_name, version)
1037388
def _get_release_params():
    """"""
    release_name = request.form.get('release_name')
    utils.jsonify_assert(release_name, 'release_name required')
    release_number = request.form.get('release_number', type=int)
    utils.jsonify_assert(release_number is not None, 'release_number required')
    return release_name, release_number
106894
def _os_release_info(self):
        
        if os.path.isfile(self.os_release_file):
            with open(self.os_release_file) as release_file:
                return self._parse_os_release_content(release_file)
        return {}
34929
def validate_unit_process_ids(self, expected, actual):
        """"""
        self.log.debug('Checking units for running processes...')
        self.log.debug('Expected PIDs: {}'.format(expected))
        self.log.debug('Actual PIDs: {}'.format(actual))

        if len(actual) != len(expected):
            return ('Unit count mismatch.  expected, actual: {}, '
                    '{} '.format(len(expected), len(actual)))

        for (e_sentry, e_proc_names) in six.iteritems(expected):
            e_sentry_name = e_sentry.info['unit_name']
            if e_sentry in actual.keys():
                a_proc_names = actual[e_sentry]
            else:
                return ('Expected sentry ({}) not found in actual dict data.'
                        '{}'.format(e_sentry_name, e_sentry))

            if len(e_proc_names.keys()) != len(a_proc_names.keys()):
                return ('Process name count mismatch.  expected, actual: {}, '
                        '{}'.format(len(expected), len(actual)))

            for (e_proc_name, e_pids), (a_proc_name, a_pids) in \
                    zip(e_proc_names.items(), a_proc_names.items()):
                if e_proc_name != a_proc_name:
                    return ('Process name mismatch.  expected, actual: {}, '
                            '{}'.format(e_proc_name, a_proc_name))

                a_pids_length = len(a_pids)
                fail_msg = ('PID count mismatch. {} ({}) expected, actual: '
                            '{}, {} ({})'.format(e_sentry_name, e_proc_name,
                                                 e_pids, a_pids_length,
                                                 a_pids))

                # If expected is a list, ensure at least one PID quantity match
                if isinstance(e_pids, list) and \
                        a_pids_length not in e_pids:
                    return fail_msg
                # If expected is not bool and not list,
                # ensure PID quantities match
                elif not isinstance(e_pids, bool) and \
                        not isinstance(e_pids, list) and \
                        a_pids_length != e_pids:
                    return fail_msg
                # If expected is bool True, ensure 1 or more PIDs exist
                elif isinstance(e_pids, bool) and \
                        e_pids is True and a_pids_length < 1:
                    return fail_msg
                # If expected is bool False, ensure 0 PIDs exist
                elif isinstance(e_pids, bool) and \
                        e_pids is False and a_pids_length != 0:
                    return fail_msg
                else:
                    self.log.debug('PID check OK: {} {} {}: '
                                   '{}'.format(e_sentry_name, e_proc_name,
                                               e_pids, a_pids))
        return None
1222267
def get_unit_id(unit_name):
    
    unit_name = unit_name.lower()
    attribute = 'uniqueIdentifier'
    response = LDAP_search(
        pattern_search='(cn={})'.format(unit_name),
        attribute=attribute
    )

    unit_id = ""
    try:
        for element in response:
            if 'dn' in element and element['dn'].startswith('ou={},'.format(unit_name)):
                unit_id = element['attributes'][attribute][0]
    except Exception:
        raise EpflLdapException("The unit named '{}' was not found".format(unit_name))
    finally:
        if not unit_id:
            raise EpflLdapException("The unit named '{}' was not found".format(unit_name))

    return unit_id
667970
def send_exception_to_sentry(self, exc_info):
        
        if not self.sentry_client:
            LOGGER.debug('No sentry_client, aborting')
            return

        message = dict(self.active_message)
        try:
            duration = math.ceil(time.time() - self.delivery_time) * 1000
        except TypeError:
            duration = 0
        kwargs = {'extra': {
                      'consumer_name': self.consumer_name,
                      'env': dict(os.environ),
                      'message': message},
                  'time_spent': duration}
        LOGGER.debug('Sending exception to sentry: %r', kwargs)
        self.sentry_client.captureException(exc_info, **kwargs)
1299352
async def vcx_messages_download(status: str = None, uids: str = None, pw_dids: str = None) -> str:
    
    logger = logging.getLogger(__name__)

    if not hasattr(vcx_messages_download, "cb"):
        logger.debug("vcx_messages_download: Creating callback")
        vcx_messages_download.cb = create_cb(CFUNCTYPE(None, c_uint32, c_uint32, c_char_p))

    if status:
        c_status = c_char_p(status.encode('utf-8'))
    else:
        c_status = None

    if uids:
        c_uids = c_char_p(uids.encode('utf-8'))
    else:
        c_uids = None

    if pw_dids:
        c_pw_dids = c_char_p(pw_dids.encode('utf-8'))
    else:
        c_pw_dids = None

    result = await do_call('vcx_messages_download',
                           c_status,
                           c_uids,
                           c_pw_dids,
                           vcx_messages_download.cb)

    logger.debug("vcx_messages_download completed")
    return result
168823
def validate_rmq_ssl_disabled_units(self, sentry_units):
        
        for sentry_unit in sentry_units:
            if self.rmq_ssl_is_enabled_on_unit(sentry_unit):
                return ('Unexpected condition:  ssl is enabled on unit '
                        '({})'.format(sentry_unit.info['unit_name']))
        return None
716212
def _check_available(name):
    '''
    
    '''
    _status = _systemctl_status(name)
    sd_version = salt.utils.systemd.version(__context__)
    if sd_version is not None and sd_version >= 231:
        # systemd 231 changed the output of "systemctl status" for unknown
        # services, and also made it return an exit status of 4. If we are on
        # a new enough version, check the retcode, otherwise fall back to
        # parsing the "systemctl status" output.
        # See: https://github.com/systemd/systemd/pull/3385
        # Also: https://github.com/systemd/systemd/commit/3dced37
        return 0 <= _status['retcode'] < 4

    out = _status['stdout'].lower()
    if 'could not be found' in out:
        # Catch cases where the systemd version is < 231 but the return code
        # and output changes have been backported (e.g. RHEL 7.3).
        return False

    for line in salt.utils.itertools.split(out, '\n'):
        match = re.match(r'\s+loaded:\s+(\S+)', line)
        if match:
            ret = match.group(1) != 'not-found'
            break
    else:
        raise CommandExecutionError(
            'Failed to get information on unit \'%s\'' % name
        )
    return ret
1193755
def _get_codename(self, pathname, basename):
        
        file_py  = pathname + ".py"
        file_pyc = pathname + ".pyc"
        file_pyo = pathname + ".pyo"
        if os.path.isfile(file_pyo) and \
                            os.stat(file_pyo).st_mtime >= os.stat(file_py).st_mtime:
            fname = file_pyo    # Use .pyo file
        elif not os.path.isfile(file_pyc) or \
             os.stat(file_pyc).st_mtime < os.stat(file_py).st_mtime:
            import py_compile
            if self.debug:
                print("Compiling", file_py)
            try:
                py_compile.compile(file_py, file_pyc, None, True)
            except py_compile.PyCompileError as err:
                print(err.msg)
            fname = file_pyc
        else:
            fname = file_pyc
        archivename = os.path.split(fname)[1]
        if basename:
            archivename = "%s/%s" % (basename, archivename)
        return (fname, archivename)
277451
def getCodecList(self):
        
        if self.checkVersion('1.4'):
            cmd = "core show codecs"
        else:
            cmd = "show codecs"
        cmdresp = self.executeCommand(cmd)
        info_dict = {}
        for line in cmdresp.splitlines():
            mobj = re.match('\s*(\d+)\s+\((.+)\)\s+\((.+)\)\s+(\w+)\s+(\w+)\s+\((.+)\)$',
                            line)
            if mobj:
                info_dict[mobj.group(5)] = (mobj.group(4), mobj.group(6))
        return info_dict
202217
def get_swift_codename(version):
    ''''''
    codenames = [k for k, v in six.iteritems(SWIFT_CODENAMES) if version in v]

    if len(codenames) > 1:
        # If more than one release codename contains this version we determine
        # the actual codename based on the highest available install source.
        for codename in reversed(codenames):
            releases = UBUNTU_OPENSTACK_RELEASE
            release = [k for k, v in six.iteritems(releases) if codename in v]
            ret = subprocess.check_output(['apt-cache', 'policy', 'swift'])
            if six.PY3:
                ret = ret.decode('UTF-8')
            if codename in ret or release[0] in ret:
                return codename
    elif len(codenames) == 1:
        return codenames[0]

    # NOTE: fallback - attempt to match with just major.minor version
    match = re.match(r'^(\d+)\.(\d+)', version)
    if match:
        major_minor_version = match.group(0)
        for codename, versions in six.iteritems(SWIFT_CODENAMES):
            for release_version in versions:
                if release_version.startswith(major_minor_version):
                    return codename

    return None
166809
def get_ceph_pools(self, sentry_unit):
        """"""
        pools = {}
        cmd = 'sudo ceph osd lspools'
        output, code = sentry_unit.run(cmd)
        if code != 0:
            msg = ('{} `{}` returned {} '
                   '{}'.format(sentry_unit.info['unit_name'],
                               cmd, code, output))
            amulet.raise_status(amulet.FAIL, msg=msg)

        # For mimic ceph osd lspools output
        output = output.replace("\n", ",")

        # Example output: 0 data,1 metadata,2 rbd,3 cinder,4 glance,
        for pool in str(output).split(','):
            pool_id_name = pool.split(' ')
            if len(pool_id_name) == 2:
                pool_id = pool_id_name[0]
                pool_name = pool_id_name[1]
                pools[pool_name] = int(pool_id)

        self.log.debug('Pools on {}: {}'.format(sentry_unit.info['unit_name'],
                                                pools))
        return pools
678315
def sentry_feature(app):
    

    # get keys
    sentry_public_key = app.config.get('SENTRY_PUBLIC_KEY')
    sentry_project_id = app.config.get('SENTRY_PROJECT_ID')
    if not sentry_public_key or not sentry_project_id:
        return

    # prepare dsn
    dsn = 'https://{key}@sentry.io/{project_id}'
    dsn = dsn.format(key=sentry_public_key, project_id=sentry_project_id)

    # init sentry
    sentry.init_app(app=app, dsn=dsn)