当前位置: 首页>>代码示例>>Python>>正文


Python usix.raise_with_tb函数代码示例

本文整理汇总了Python中spacewalk.common.usix.raise_with_tb函数的典型用法代码示例。如果您正苦于以下问题:Python raise_with_tb函数的具体用法?Python raise_with_tb怎么用?Python raise_with_tb使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了raise_with_tb函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _prepare_guest_kernel_and_ramdisk

def _prepare_guest_kernel_and_ramdisk(config):
    """
    Use PyGrub to extract the kernel and ramdisk from the given disk image.
    """

    disk_image = config.getConfigItem(DomainConfig.DISK_IMAGE_PATH)

    # Use pygrub to extract the initrd and the kernel from the disk image.
    (status, output) = \
        commands.getstatusoutput("%s -q %s" % (PYGRUB, disk_image))
    if status != 0:
        raise VirtualizationException("Error occurred while executing '%s' (status=%d). Output=%s" %
                                      (PYGRUB, status, output))

    # Now analyze the output and extract the names of the new kernel and initrd
    # images from it.
    (pygrub_kernel_path, pygrub_initrd_path) = \
        _extract_image_paths_from_pygrub_output(output)

    # Rename the extracted images to the names we are pointing to in the
    # configuration file.
    runtime_kernel_path = config.getConfigItem(DomainConfig.KERNEL_PATH)
    runtime_initrd_path = config.getConfigItem(DomainConfig.RAMDISK_PATH)

    try:
        os.rename(pygrub_kernel_path, runtime_kernel_path)
        os.rename(pygrub_initrd_path, runtime_initrd_path)
    except OSError:
        oe = sys.exc_info()[1]
        raise_with_tb(VirtualizationException("Error occurred while renaming runtime image paths: %s" % str(oe)),
                      sys.exc_info()[2])
开发者ID:jdobes,项目名称:spacewalk,代码行数:31,代码来源:start_domain.py

示例2: _repodata_taskomatic

    def _repodata_taskomatic(self, file_name):
        log_debug(3, 'repodata', file_name)

        content_type = "application/x-gzip"

        if file_name in ["repomd.xml", "comps.xml"]:
            content_type = "text/xml"
        elif file_name not in ["primary.xml.gz", "other.xml.gz",
                               "filelists.xml.gz", "updateinfo.xml.gz", "Packages.gz"]:
            log_debug(2, "Unknown repomd file requested: %s" % file_name)
            raise rhnFault(6)

        # XXX this won't be repconned or CDNd
        if file_name == "comps.xml":
            return self._repodata_python(file_name)

        file_path = "%s/%s/%s" % (CFG.REPOMD_PATH_PREFIX, self.channelName, file_name)
        rhnFlags.set('Content-Type', content_type)
        try:
            rhnFlags.set('Download-Accelerator-Path', file_path)
            return self._getFile(CFG.REPOMD_CACHE_MOUNT_POINT + "/" + file_path)
        except IOError:
            e = sys.exc_info()[1]
            # For file not found, queue up a regen, and return 404
            if e.errno == 2 and file_name != "comps.xml":
                taskomatic.add_to_repodata_queue(self.channelName,
                                                 "repodata request", file_name, bypass_filters=True)
                rhnSQL.commit()
                # This returns 404 to the client
                raise_with_tb(rhnFault(6), sys.exc_info()[2])
            raise
开发者ID:dewayneHat,项目名称:spacewalk,代码行数:31,代码来源:rhnRepository.py

示例3: getAnyChecksum

    def getAnyChecksum(self, info, username=None, password=None, session=None, is_source=0):
        """ returns checksum info of available packages
            also does an existance check on the filesystem.
        """
        log_debug(3)

        pkg_infos = info.get('packages')
        channels = info.get('channels', [])
        force = info.get('force', 0)
        orgid = info.get('org_id')

        if orgid == 'null':
            null_org = 1
        else:
            null_org = None

        if not session:
            org_id, force = rhnPackageUpload.authenticate(username, password,
                                                          channels=channels,
                                                          null_org=null_org,
                                                          force=force)
        else:
            try:
                org_id, force = rhnPackageUpload.authenticate_session(
                    session, channels=channels, null_org=null_org, force=force)
            except rhnSession.InvalidSessionError:
                raise_with_tb(rhnFault(33), sys.exc_info()[2])
            except rhnSession.ExpiredSessionError:
                raise_with_tb(rhnFault(34), sys.exc_info()[2])

        if is_source:
            ret = self._getSourcePackageChecksum(org_id, pkg_infos)
        else:
            ret = self._getPackageChecksum(org_id, pkg_infos)
        return ret
开发者ID:m47ik,项目名称:uyuni,代码行数:35,代码来源:packages.py

示例4: __getV2

    def __getV2(self, action, dry_run=0):
        """ Fetches queued actions for the clients version 2+. """
        log_debug(3, self.server_id)
        # Get the root dir of this install
        try:
            method = getMethod.getMethod(action['method'],
                                         'server.action')
        except getMethod.GetMethodException:
            Traceback("queue.get V2")
            raise_with_tb(EmptyAction("Could not get a valid method for %s" % (
                action['method'],)), sys.exc_info()[2])
        # Call the method
        result = method(self.server_id, action['id'], dry_run)
        if result is None:
            # None are mapped to the empty list
            result = ()
        elif not isinstance(result, TupleType):
            # Everything other than a tuple is wrapped in a tuple
            result = (result, )

        xmlblob = xmlrpclib.dumps(result, methodname=action['method'])
        log_debug(5, "returning xmlblob for action", xmlblob)
        return {
            'id': action['id'],
            'action': xmlblob,
            'version': action['version'],
        }
开发者ID:BlackSmith,项目名称:spacewalk,代码行数:27,代码来源:queue.py

示例5: token_server_groups

def token_server_groups(server_id, tokens_obj):
    """ Handle server group subscriptions for the registration token """
    assert(isinstance(tokens_obj, ActivationTokens))
    h = rhnSQL.prepare(_query_token_server_groups)
    server_groups = {}
    for token in tokens_obj.tokens:
        token_id = token['token_id']
        h.execute(token_id=token_id)
        while 1:
            row = h.fetchone_dict()
            if not row:
                break
            server_group_id = row['server_group_id']
            server_groups[server_group_id] = row

    # Now try to subscribe server to group
    ret = []
    for server_group_id, sg in server_groups.items():
        log_debug(4, "token server group", sg)

        try:
            join_server_group(server_id, server_group_id)
        except rhnSQL.SQLError:
            e = sys.exc_info()[1]
            log_error("Failed to add server to group", server_id,
                      server_group_id, sg["name"])
            raise_with_tb(rhnFault(80, _("Failed to add server to group %s") %
                           sg["name"]), sys.exc_info()[2])
        else:
            ret.append("Subscribed to server group '%s'" % sg["name"])
    return ret
开发者ID:BlackSmith,项目名称:spacewalk,代码行数:31,代码来源:server_token.py

示例6: start_domain

def start_domain(uuid):
    """
    Boots the domain for the first time after installation is complete.
    """
    # Load the configuration file for this UUID.
    domain = DomainDirectory()
    config = domain.load_config(uuid)

    # Connect to the hypervisor.
    connection = libvirt.open(None)

    # We will attempt to determine if the domain is configured to use a
    # bootloader.  If not, we'll have to explicitly use the kernel and initrd
    # data provided in the config to start the domain.
    try:
        config.getConfigItem(DomainConfig.BOOTLOADER)
    except DomainConfigError:
        dce = sys.exc_info()[1]
        # No bootloader tag present.  Use pygrub to extract the kernel from
        # the disk image if its Xen. For fully virt we dont have pygrub, it
        # directly emulates the BIOS loading the first sector of the boot disk.
        if connection.getType() == 'Xen':
            # This uses pygrub which comes only with xen
            _prepare_guest_kernel_and_ramdisk(config)

    # Now, we'll restart the instance, this time using the re-create XML.
    try:
        domain = connection.createLinux(config.toXML(), 0)
    except Exception:
        e = sys.exc_info()[1]
        raise_with_tb(VirtualizationException("Error occurred while attempting to recreate domain %s: %s" %
                                              (uuid, str(e))), sys.exc_info()[2])
开发者ID:jdobes,项目名称:spacewalk,代码行数:32,代码来源:start_domain.py

示例7: _extract_pstamp_as_release

def _extract_pstamp_as_release(pstamp):
    """
    This function convert a PSTAMP in the format

        nameYYMMDDHHMMSS

    into a release number of the format

        YYYY.MM.DD.HH.MM

    If the PSTAMP is of an unknown format, PStampParseException is raised.
    Otherwise, the release number is returned.
    """

    if pstamp is None:
        raise PStampParseException("PSTAMP is null")

    # Extract the last 12 characters from the pstamp.  This will represent the
    # date and time.
    date_time_stamp = pstamp[-12:]
    if len(date_time_stamp) != 12:
        raise PStampParseException("Date stamp is not 12 characters.")

    # Now break the date/time stamp into a time structure.
    date_time_struct = None
    try:
        date_time_struct = time.strptime(date_time_stamp, "%y%m%d%H%M%S")
    except ValueError:
        ve = sys.exc_info()[1]
        raise_with_tb(PStampParseException("Error parsing date/time: %s" % str(ve)), sys.exc_info()[2])

    # Convert the structure into a string in the release number format.
    release_number = time.strftime("%Y.%m.%d.%H.%M", date_time_struct)

    return release_number
开发者ID:BlackSmith,项目名称:spacewalk,代码行数:35,代码来源:solaris2mpm.py

示例8: _call_function

 def _call_function(self, function, arglist, kwargs={}):
     succeed = 0
     while succeed == 0:
         try:
             ret = function(*arglist, **kwargs)
         except rpclib.InvalidRedirectionError:
             raise
         except xmlrpclib.Fault:
             e = sys.exc_info()[1]
             save_traceback = sys.exc_info()[2]
             try:
                 self._failover()
             except NoMoreServers:
                 f = sys.exc_info()[1]
                 raise_with_tb(e, save_traceback)  #Don't raise the NoMoreServers error, raise the error that triggered the failover.
             continue
         except (error, sslerror, herror, gaierror, timeout):
             e = sys.exc_info()[1]
             save_traceback = sys.exc_info()[2]
             try:
                 self._failover()
             except NoMoreServers:
                 raise_with_tb(e, save_traceback)
             continue
         succeed = 1 #If we get here then the function call eventually succeeded and we don't need to try again.
     return ret
开发者ID:dewayneHat,项目名称:spacewalk,代码行数:26,代码来源:rpc_wrapper.py

示例9: _to_db_timestamp

def _to_db_timestamp(s):
    """Convert common Solaris date convention to a unix timestamp"""

    arr = s.split('.', 2)
    if len(arr) != 3:
        return None
    y, m, d = arr

    try:
        m = int(m)

    except ValueError:
        for i, item in enumerate(_months):
            if m == item:
                break
            else:

                raise_with_tb(Exception("unknown month %s" % arr[0]), sys.exc_info()[2])
            m = i + 1

    d = int(d)
    y = int(y)
    if y < 30:
        y = 2000 + y
    elif y < 100:
        y = 1900 + y

    return time.strftime("%Y-%m-%d %H:%M:%S", (y, m, d, 0, 0, 0, 0, 1, -1))
开发者ID:BlackSmith,项目名称:spacewalk,代码行数:28,代码来源:solaris2mpm.py

示例10: connect

    def connect(self, reconnect=1):
        try:
            dsndata = {
                'dbname': self.database,
                'user': self.username,
                'password': self.password}
            if self.host is not None:
                dsndata['host'] = self.host
                dsndata['port'] = self.port
            if self.sslmode is not None and self.sslmode == 'verify-full' and self.sslrootcert is not None:
                dsndata['sslmode'] = self.sslmode
                dsndata['sslrootcert'] = self.sslrootcert
            elif self.sslmode is not None:
                raise AttributeError("Only sslmode=\"verify-full\" (or None) is supported.")
            if self.sslmode is not None and self.sslrootcert is None:
                raise AttributeError("Attribute sslrootcert needs to be set if sslmode is set.")

            self.dbh = psycopg2.connect(" ".join("%s=%s" % (k, re.escape(str(v))) for k, v in dsndata.items()))

            # convert all DECIMAL types to float (let Python to choose one)
            DEC2INTFLOAT = psycopg2.extensions.new_type(psycopg2._psycopg.DECIMAL.values,
                                                        'DEC2INTFLOAT', decimal2intfloat)
            psycopg2.extensions.register_type(DEC2INTFLOAT)
        except psycopg2.Error:
            e = sys.exc_info()[1]
            if reconnect > 0:
                # Try one more time:
                return self.connect(reconnect=reconnect - 1)

            # Failed reconnect, time to error out:
            raise_with_tb(sql_base.SQLConnectError(
                self.database, e.pgcode, e.pgerror,
                "All attempts to connect to the database failed"), sys.exc_info()[2])
开发者ID:BlackSmith,项目名称:spacewalk,代码行数:33,代码来源:driver_postgresql.py

示例11: load

def load(filename=None, file_obj=None, fd=None):
    """ Loads an MPM and returns its header and its payload """
    if filename is None and file_obj is None and fd is None:
        raise ValueError("No parameters passed")

    if filename is not None:
        f = open(filename)
    elif file_obj is not None:
        f = file_obj
    else:  # fd is not None
        f = os.fdopen(os.dup(fd), "r")

    f.seek(0, 0)

    p = MPM_Package()
    try:
        p.load(f)
    except InvalidPackageError:
        e = sys.exc_info()[1]
        try:
            return load_rpm(f)
        except InvalidPackageError:
            raise_with_tb(e, sys.exc_info()[2])
        except:
            raise_with_tb(e, sys.exc_info()[2])

    return p.header, p.payload_stream
开发者ID:shastah,项目名称:spacewalk,代码行数:27,代码来源:rhn_mpm.py

示例12: check_password

def check_password(username, password, service):
    global __username, __password
    auth = PAM.pam()
    auth.start(service, username, __pam_conv)

    # Save the username and passwords in the globals, the conversation
    # function needs access to them
    __username = username
    __password = password

    try:
        try:
            auth.authenticate()
            auth.acct_mgmt()
        finally:
            # Something to be always executed - cleanup
            __username = __password = None
    except PAM.error:
        e = sys.exc_info()[1]
        resp, code = e.args[:2]
        log_error("Password check failed (%s): %s" % (code, resp))
        return 0
    except:
        raise_with_tb(rhnException('Internal PAM error'), sys.exc_info()[2])
    else:
        # Good password
        return 1
开发者ID:dewayneHat,项目名称:spacewalk,代码行数:27,代码来源:rhnAuthPAM.py

示例13: get

    def get(self, name, modified=None):
        pickled = self.cache.get(name, modified)

        try:
            return cPickle.loads(pickled)
        except cPickle.UnpicklingError:
            raise_with_tb(KeyError(name), sys.exc_info()[2])
开发者ID:dewayneHat,项目名称:spacewalk,代码行数:7,代码来源:rhnCache.py

示例14: management_remove_channel

    def management_remove_channel(self, dict):
        log_debug(1)
        self._get_and_validate_session(dict)

        config_channel = dict.get('config_channel')
        # XXX Validate the namespace

        row = rhnSQL.fetchone_dict(self._query_config_channel_by_label,
                                   org_id=self.org_id, label=config_channel)

        if not row:
            raise rhnFault(4009, "Channel not found")

        delete_call = rhnSQL.Procedure('rhn_config.delete_channel')

        try:
            delete_call(row['id'])
        except rhnSQL.SQLError:
            e = sys.exc_info()[1]
            errno = e.args[0]
            if errno == 2292:
                raise_with_tb(rhnFault(4005, "Cannot remove non-empty channel %s" %
                               config_channel, explain=0), sys.exc_info()[2])
            raise

        log_debug(5, "Removed:", config_channel)
        rhnSQL.commit()
        return ""
开发者ID:BlackSmith,项目名称:spacewalk,代码行数:28,代码来源:rhn_config_management.py

示例15: connect

 def connect(self, reconnect=1):
     log_debug(1, "Connecting to database", self.dbtxt)
     self._fix_environment_vars()
     try:
         self.dbh = self._connect()
     except self.OracleError:
         e = sys.exc_info()[1]
         ret = self._get_oracle_error_info(e)
         if isinstance(ret, usix.StringType):
             raise_with_tb(sql_base.SQLConnectError(self.dbtxt, -1,
                                            "Unable to connect to database", ret), sys.exc_info()[2])
         (errno, errmsg) = ret[:2]
         log_error("Connection attempt failed", errno, errmsg)
         if reconnect:
             # we don't try to reconnect blindly.  We have a list of
             # known "good" failure codes that warrant a reconnect
             # attempt
             if errno in [12547]:  # lost contact
                 return self.connect(reconnect=0)
             err_args = [self.dbtxt, errno, errmsg]
             err_args.extend(list(ret[2:]))
             raise_with_tb(sql_base.SQLConnectError(*err_args), sys.exc_info()[2])
         # else, this is a reconnect attempt
         raise sql_base.SQLConnectError(*(
             [self.dbtxt, errno, errmsg,
              "Attempting Re-Connect to the database failed", ] + ret[2:])).with_traceback(sys.exc_info()[2])
     dbh_id = id(self.dbh)
     # Reset the statement cache for this database connection
     self._cursor_class._cursor_cache[dbh_id] = {}
开发者ID:jiridostal,项目名称:spacewalk,代码行数:29,代码来源:driver_cx_Oracle.py


注:本文中的spacewalk.common.usix.raise_with_tb函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。