Example #1
0
def getChannels(force=None, label_whitelist=None, timeout=None):
    """ return rhnChannelList containing list of channel we are subscribed to """
    cfg = config.initUp2dateConfig()
    global selected_channels
    if not selected_channels and not force:
        selected_channels = rhnChannelList()
        s = rhnserver.RhnServer(timeout=timeout)

        if not up2dateAuth.getSystemId():
            raise up2dateErrors.NoSystemIdError(_("Unable to Locate SystemId"))

        up2dateChannels = s.up2date.listChannels(up2dateAuth.getSystemId())

        for chan in up2dateChannels:
            if label_whitelist and not chan['label'] in label_whitelist:
                continue

            channel = rhnChannel(type = 'up2date', url = config.getServerlURL())
            for key in chan.keys():
                if key == "last_modified":
                    channel['version'] = chan['last_modified']
                else:
                    channel[key] = chan[key]
            selected_channels.addChannel(channel)

    if len(selected_channels.list) == 0:
        raise up2dateErrors.NoChannelsError(_("This system may not be updated until it is associated with a channel."))

    return selected_channels
Example #2
0
def getChannels(force=None, label_whitelist=None, timeout=None):
    """ return rhnChannelList containing list of channel we are subscribed to """
    cfg = config.initUp2dateConfig()
    global selected_channels
    if not selected_channels and not force:
        selected_channels = rhnChannelList()
        s = rhnserver.RhnServer(timeout=timeout)

        if not up2dateAuth.getSystemId():
            raise up2dateErrors.NoSystemIdError(_("Unable to Locate SystemId"))

        up2dateChannels = s.up2date.listChannels(up2dateAuth.getSystemId())

        for chan in up2dateChannels:
            if label_whitelist and not chan['label'] in label_whitelist:
                continue

            channel = rhnChannel(type='up2date', url=config.getServerlURL())
            for key in chan.keys():
                if key == "last_modified":
                    channel['version'] = chan['last_modified']
                else:
                    channel[key] = chan[key]
            selected_channels.addChannel(channel)

    if len(selected_channels.list) == 0:
        raise up2dateErrors.NoChannelsError(
            _("This system may not be updated until it is associated with a channel."
              ))

    return selected_channels
Example #3
0
    def main(self):
        if not up2dateAuth.getSystemId():
            sys.exit(1)

        if not self._testRhnLogin():
            sys.exit(1)

        s = rhnserver.RhnServer()
        if s.capabilities.hasCapability('queue.update_status'):
            status_report = StatusCli.__build_status_report()
            s.queue.update_status(up2dateAuth.getSystemId(), status_report)
Example #4
0
    def main(self):
        if not up2dateAuth.getSystemId():
            sys.exit(1)

        if not self._testRhnLogin():
            sys.exit(1)

        s = rhnserver.RhnServer()
        if s.capabilities.hasCapability('queue.update_status'):
            status_report = StatusCli.__build_status_report()
            s.queue.update_status(up2dateAuth.getSystemId(), status_report)
Example #5
0
    def __get_action(self, status_report):
        try:
            action = self.server.queue.get(up2dateAuth.getSystemId(),
                ACTION_VERSION, status_report)

            return action
        except xmlrpclib.Fault:
            f = sys.exc_info()[1]
            if f.faultCode == -31:
                raise up2dateErrors.InsuffMgmntEntsError(f.faultString), None, sys.exc_info()[2]
            else:
                print "Could not retrieve action item from server %s" % self.server
                print "Error code: %d%s" % (f.faultCode, f.faultString)
            sys.exit(-1)
        # XXX: what if no SSL in socket?
        except socket.sslerror:
            print "ERROR: SSL handshake to %s failed" % self.server
            print """
            This could signal that you are *NOT* talking to a server
            whose certificate was signed by a Certificate Authority
            listed in the %s file or that the
            RHNS-CA-CERT file is invalid.""" % self.rhns_ca_cert
            sys.exit(-1)
        except socket.error:
            print "Could not retrieve action from %s.\n"\
                  "Possible networking problem?" % str(self.server)
            sys.exit(-1)
        except up2dateErrors.ServerCapabilityError:
            print sys.exc_info()[1]
            sys.exit(1)
        except SSL.Error:
            print "ERROR: SSL errors detected"
            print "%s" % sys.exc_info()[1]
            sys.exit(-1)
Example #6
0
def get_available_channels(user, password):
    """ return list of available child channels """
    modified_servers = []
    servers = config.getServerlURL()
    for server in servers:
        scheme, netloc, path, query, fragment = urlparse.urlsplit(server)
        modified_servers.append(urlparse.urlunsplit((scheme, netloc, '/rpc/api', query, fragment)))
    client = rhnserver.RhnServer(serverOverride=modified_servers)
    try:
        key = client.auth.login(user, password)
    except xmlrpclib.Fault:
        exc = sys.exc_info()[1]
        systemExit(1, "Error during client authentication: %s" % exc.faultString)

    system_id = re.sub('^ID-', '', rpclib.xmlrpclib.loads(up2dateAuth.getSystemId())[0][0]['system_id'])
    result = []
    try:
        channels = client.system.listChildChannels(key, int(system_id))
    except xmlrpclib.Fault:
        exc = sys.exc_info()[1]
        systemExit(1, "Error when listing child channels: %s" % exc.faultString)

    for channel in channels:
        if 'LABEL' in channel:
            result.extend([channel['LABEL']])
        else:
            result.extend([channel['label']])
    return result
Example #7
0
 def __query_future_actions(self, time_window):
     try:
         actions = self.server.queue.get_future_actions(up2dateAuth.getSystemId(),
             time_window)
         return actions
     except xmlrpclib.Fault:
         f = sys.exc_info()[1]
         if f.faultCode == -31:
             raise_with_tb(up2dateErrors.InsuffMgmntEntsError(f.faultString))
         else:
             print("Could not retrieve action item from server %s" % self.server)
             print("Error code: %d%s" % (f.faultCode, f.faultString))
         sys.exit(-1)
     # XXX: what if no SSL in socket?
     except SSL.socket_error:
         print("ERROR: SSL handshake to %s failed" % self.server)
         print("""
         This could signal that you are *NOT* talking to a server
         whose certificate was signed by a Certificate Authority
         listed in the %s file or that the
         RHNS-CA-CERT file is invalid.""" % self.rhns_ca_cert)
         sys.exit(-1)
     except socket.error:
         print("Could not retrieve action from %s.\n"\
               "Possible networking problem?" % str(self.server))
         sys.exit(-1)
     except up2dateErrors.ServerCapabilityError:
         print(sys.exc_info()[1])
         sys.exit(1)
     except SSL.Error:
         print("ERROR: SSL errors detected")
         print("%s" % sys.exc_info()[1])
         sys.exit(-1)
Example #8
0
    def submit_response(self, action_id, status, message, data):
        """ Submit a response for an action_id. """

        # get a new server object with fresh headers
        self.server = CheckCli.__get_server()

        try:
            ret = self.server.queue.submit(up2dateAuth.getSystemId(),
                                      action_id, status, message, data)
        except xmlrpclib.Fault:
            f = sys.exc_info()[1]
            print("Could not submit results to server %s" % self.server)
            print("Error code: %d%s" % (f.faultCode, f.faultString))
            sys.exit(-1)
        # XXX: what if no SSL in socket?
        except SSL.socket_error:
            print("ERROR: SSL handshake to %s failed" % self.server)
            print("""
            This could signal that you are *NOT* talking to a server
            whose certificate was signed by a Certificate Authority
            listed in the %s file or that the
            RHNS-CA-CERT file is invalid.""" % self.rhns_ca_cert)
            sys.exit(-1)
        except socket.error:
            print("Could not submit to %s.\n"\
                  "Possible networking problem?" % str(self.server))
            sys.exit(-1)
        return ret
Example #9
0
    def submit_response(self, action_id, status, message, data):
        """ Submit a response for an action_id. """

        # get a new server object with fresh headers
        self.server = CheckCli.__get_server()

        try:
            ret = self.server.queue.submit(up2dateAuth.getSystemId(),
                                           action_id, status, message, data)
        except xmlrpclib.Fault:
            f = sys.exc_info()[1]
            print("Could not submit results to server %s" % self.server)
            print("Error code: %d%s" % (f.faultCode, f.faultString))
            sys.exit(-1)
        # XXX: what if no SSL in socket?
        except SSL.socket_error:
            print("ERROR: SSL handshake to %s failed" % self.server)
            print("""
            This could signal that you are *NOT* talking to a server
            whose certificate was signed by a Certificate Authority
            listed in the %s file or that the
            RHNS-CA-CERT file is invalid.""" % self.rhns_ca_cert)
            sys.exit(-1)
        except socket.error:
            print("Could not submit to %s.\n"\
                  "Possible networking problem?" % str(self.server))
            sys.exit(-1)
        return ret
Example #10
0
def update_count(problem_dir):
    problem_dir = os.path.normpath(os.path.abspath(problem_dir))
    basename = os.path.basename(problem_dir)
    log = up2dateLog.initLog()
    if not (os.path.exists(problem_dir) and os.path.isdir(problem_dir)):
        log.log_me("The specified path [%s] is not a valid directory." %
                   problem_dir)
        return -1

    server = rhnserver.RhnServer()
    if not server.capabilities.hasCapability('abrt'):
        return -1

    systemid = up2dateAuth.getSystemId()
    crash_count_path = os.path.join(problem_dir, 'count')
    if not (os.path.exists(crash_count_path)
            and os.path.isfile(crash_count_path)):
        log.log_me(
            "The problem directory [%s] does not contain any crash count information."
            % problem_dir)
        return 0

    crash_count = _readline(crash_count_path)
    server.abrt.update_crash_count(systemid, basename, crash_count)

    return 1
Example #11
0
    def __get_action(self, status_report):
        try:
            action = self.server.queue.get(up2dateAuth.getSystemId(),
                                           ACTION_VERSION, status_report)

            return action
        except xmlrpclib.Fault:
            f = sys.exc_info()[1]
            if f.faultCode == -31:
                raise up2dateErrors.InsuffMgmntEntsError(
                    f.faultString), None, sys.exc_info()[2]
            else:
                print "Could not retrieve action item from server %s" % self.server
                print "Error code: %d%s" % (f.faultCode, f.faultString)
            sys.exit(-1)
        # XXX: what if no SSL in socket?
        except socket.sslerror:
            print "ERROR: SSL handshake to %s failed" % self.server
            print """
            This could signal that you are *NOT* talking to a server
            whose certificate was signed by a Certificate Authority
            listed in the %s file or that the
            RHNS-CA-CERT file is invalid.""" % self.rhns_ca_cert
            sys.exit(-1)
        except socket.error:
            print "Could not retrieve action from %s.\n"\
                  "Possible networking problem?" % str(self.server)
            sys.exit(-1)
        except up2dateErrors.ServerCapabilityError:
            print sys.exc_info()[1]
            sys.exit(1)
        except SSL.Error:
            print "ERROR: SSL errors detected"
            print "%s" % sys.exc_info()[1]
            sys.exit(-1)
Example #12
0
 def __query_future_actions(self, time_window):
     try:
         actions = self.server.queue.get_future_actions(
             up2dateAuth.getSystemId(), time_window)
         return actions
     except xmlrpclib.Fault:
         f = sys.exc_info()[1]
         if f.faultCode == -31:
             raise_with_tb(up2dateErrors.InsuffMgmntEntsError(
                 f.faultString))
         else:
             print("Could not retrieve action item from server %s" %
                   self.server)
             print("Error code: %d%s" % (f.faultCode, f.faultString))
         sys.exit(-1)
     # XXX: what if no SSL in socket?
     except SSL.socket_error:
         print("ERROR: SSL handshake to %s failed" % self.server)
         print("""
         This could signal that you are *NOT* talking to a server
         whose certificate was signed by a Certificate Authority
         listed in the %s file or that the
         RHNS-CA-CERT file is invalid.""" % self.rhns_ca_cert)
         sys.exit(-1)
     except socket.error:
         print("Could not retrieve action from %s.\n"\
               "Possible networking problem?" % str(self.server))
         sys.exit(-1)
     except up2dateErrors.ServerCapabilityError:
         print(sys.exc_info()[1])
         sys.exit(1)
     except SSL.Error:
         print("ERROR: SSL errors detected")
         print("%s" % sys.exc_info()[1])
         sys.exit(-1)
def updateHardware():
    s = rpcServer.getServer()


    hardwareList = hardware.Hardware()
    s.registration.refresh_hw_profile(up2dateAuth.getSystemId(),
                                          hardwareList)
Example #14
0
    def __init__(self, screen, tui):

        if not rhnreg.registered() or tui.test:
            raise WindowSkipException()

        self.screen = screen
        self.tui = tui
        size = snack._snack.size()

        systemIdXml = rpclib.xmlrpclib.loads(up2dateAuth.getSystemId())
        oldUsername = systemIdXml[0][0]['username']
        oldsystemId = systemIdXml[0][0]['system_id']

        toplevel = snack.GridForm(self.screen, sstr(SYSTEM_ALREADY_SETUP), 1, 2)
        self.bb = snack.ButtonBar(self.screen,
                                  [(sstr(YES_CONT), "next"),
                                   (sstr(NO_CANCEL), "exit")])
        toplevel.add(self.bb, 0, 1, growx = 1)

        tb = snack.Textbox(size[0]-30, size[1]-20,
                            sstr(SYSTEM_ALREADY_REGISTERED + "\n\n"
                            + _("Spacewalk Location:") + " " + convert_url_from_puny(self.tui.serverURL) + "\n"
                            + _("Login:"******" " + oldUsername + "\n"
                            + _("System ID:") + " " + oldsystemId + "\n\n"
                            + SYSTEM_ALREADY_REGISTERED_CONT + "\n"),
                            1, 1)
        toplevel.add(tb, 0, 0, padding = (0, 0, 0, 1))

        self.g = toplevel
Example #15
0
    def __init__(self, screen, tui):

        if not rhnreg.registered() or tui.test:
            raise WindowSkipException()

        self.screen = screen
        self.tui = tui
        size = snack._snack.size()

        systemIdXml = rpclib.xmlrpclib.loads(up2dateAuth.getSystemId())
        oldUsername = systemIdXml[0][0]['username']
        oldsystemId = systemIdXml[0][0]['system_id']

        toplevel = snack.GridForm(self.screen, sstr(SYSTEM_ALREADY_SETUP), 1, 2)
        self.bb = snack.ButtonBar(self.screen,
                                  [(sstr(YES_CONT), "next"),
                                   (sstr(NO_CANCEL), "exit")])
        toplevel.add(self.bb, 0, 1, growx = 1)

        tb = snack.Textbox(size[0]-30, size[1]-20,
                            sstr(SYSTEM_ALREADY_REGISTERED + "\n\n"
                            + _("Spacewalk Location:") + " " + convert_url_from_puny(self.tui.serverURL) + "\n"
                            + _("Login:"******" " + oldUsername + "\n"
                            + _("System ID:") + " " + oldsystemId + "\n\n"
                            + SYSTEM_ALREADY_REGISTERED_CONT + "\n"),
                            1, 1)
        toplevel.add(tb, 0, 0, padding = (0, 0, 0, 1))

        self.g = toplevel
Example #16
0
    def rhn_username(self):
        try:
            cfg = config.initUp2dateConfig()

            return rpclib.xmlrpclib.loads(up2dateAuth.getSystemId())[0][0]['username']
        except:
            # ignore any exception and return an empty username
            return ""
    def is_registered_with_classic(self):
        try:
            sys.path.append('/usr/share/rhn')
            from up2date_client import up2dateAuth
        except ImportError:
            return False

        return up2dateAuth.getSystemId() is not None
Example #18
0
 def rhn_username(self):
     try:
         rhn_username = rpclib.xmlrpclib.loads(
             up2dateAuth.getSystemId())[0][0]['username']
         return rhn_username.encode('utf-8', 'ignore')
     except Exception:
         # ignore any exception and return an empty username
         return ""
    def is_registered_with_classic(self):
        try:
            sys.path.append('/usr/share/rhn')
            from up2date_client import up2dateAuth
        except ImportError:
            return False

        return up2dateAuth.getSystemId() is not None
Example #20
0
    def rhnUsername(self):
        try:
            cfg = config.initUp2dateConfig()

            return rpclib.xmlrpclib.loads(up2dateAuth.getSystemId())[0][0]['username']
        except:
            # ignore any exception and return an empty username
            return ""
Example #21
0
File: redhat.py Project: freyes/sos
 def rhn_username(self):
     try:
         # cfg = config.initUp2dateConfig()
         rhn_username = rpclib.xmlrpclib.loads(
             up2dateAuth.getSystemId())[0][0]['username']
         return rhn_username.encode('utf-8', 'ignore')
     except:
         # ignore any exception and return an empty username
         return ""
Example #22
0
def updatePackageProfile(timeout=None):
    """ get a list of installed packages and send it to rhnServer """
    log = up2dateLog.initLog()
    log.log_me("Updating package profile")
    packages = pkgUtils.getInstalledPackageList(getArch=1)
    s = rhnserver.RhnServer(timeout=timeout)
    if not s.capabilities.hasCapability('xmlrpc.packages.extended_profile', 2):
        # for older satellites and hosted - convert to old format
        packages = convertPackagesFromHashToList(packages)
    s.registration.update_packages(up2dateAuth.getSystemId(), packages)
Example #23
0
def updatePackageProfile(timeout=None):
    """ get a list of installed packages and send it to rhnServer """
    log = up2dateLog.initLog()
    log.log_me("Updating package profile")
    packages = pkgUtils.getInstalledPackageList(getArch=1)
    s = rhnserver.RhnServer(timeout=timeout)
    if not s.capabilities.hasCapability('xmlrpc.packages.extended_profile', 2):
        # for older satellites and hosted - convert to old format
        packages = convertPackagesFromHashToList(packages)
    s.registration.update_packages(up2dateAuth.getSystemId(), packages)
Example #24
0
 def getSolutions(self, unknowns, progressCallback=None, msgCallback=None):
     s = rpcServer.getServer(refreshCallback=self.refreshCallback)
     try:
         tmpRetList = rpcServer.doCall(s.up2date.solveDependencies,
                                       up2dateAuth.getSystemId(), unknowns)
     except rpclib.Fault, f:
         if f.faultCode == -26:
             #raise RpmError(f.faultString + _(", depended on by %s") % unknowns)
             raise up2dateErrors.RpmError(f.faultString)
         else:
             raise up2dateErrors.CommunicationError(f.faultString)
Example #25
0
def get_sys_id():
    sysid_xml = up2dateAuth.getSystemId()

    if not sysid_xml:
        system_exit(1, "Could not get RHN systemid")

    m = search('ID-(?P<sysid>[0-9]+)', sysid_xml)

    if m:
        return m.group('sysid')
    else:
        return
Example #26
0
 def __query_future_actions(self, time_window):
     try:
         actions = self.server.queue.get_future_actions(up2dateAuth.getSystemId(),
             time_window)
         return actions
     except xmlrpclib.Fault, f:
         if f.faultCode == -31:
             raise up2dateErrors.InsuffMgmntEntsError(f.faultString), None, sys.exc_info()[2]
         else:
             print "Could not retrieve action item from server %s" % self.server
             print "Error code: %d%s" % (f.faultCode, f.faultString)
         sys.exit(-1)
Example #27
0
 def __query_future_actions(self, time_window):
     try:
         actions = self.server.queue.get_future_actions(up2dateAuth.getSystemId(),
             time_window)
         return actions
     except xmlrpclib.Fault, f:
         if f.faultCode == -31:
             raise up2dateErrors.InsuffMgmntEntsError(f.faultString), None, sys.exc_info()[2]
         else:
             print "Could not retrieve action item from server %s" % self.server
             print "Error code: %d%s" % (f.faultCode, f.faultString)
         sys.exit(-1)
Example #28
0
def get_sys_id():
    sysid_xml = up2dateAuth.getSystemId()

    if not sysid_xml:
        system_exit(1, "Could not get RHN systemid")

    m = search('ID-(?P<sysid>[0-9]+)', sysid_xml)

    if m:
        return m.group('sysid')
    else:
        return
Example #29
0
 def getSolutions(self, unknowns, progressCallback = None, msgCallback = None):
     s = rpcServer.getServer(refreshCallback=self.refreshCallback)
     try:
         tmpRetList = rpcServer.doCall(s.up2date.solveDependencies,
                                         up2dateAuth.getSystemId(),
                                         unknowns)
     except rpclib.Fault, f:
         if f.faultCode == -26:
             #raise RpmError(f.faultString + _(", depended on by %s") % unknowns)
             raise up2dateErrors.RpmError(f.faultString)
         else:
              raise up2dateErrors.CommunicationError(f.faultString)
Example #30
0
    def submit_response(self, action_id, status, message, data):
        """ Submit a response for an action_id. """

        # get a new server object with fresh headers
        self.server = CheckCli.__get_server()

        try:
            ret = self.server.queue.submit(up2dateAuth.getSystemId(),
                                      action_id, status, message, data)
        except xmlrpclib.Fault, f:
            print "Could not submit results to server %s" % self.server
            print "Error code: %d%s" % (f.faultCode, f.faultString)
            sys.exit(-1)
Example #31
0
    def __get_action(self, status_report):
        try:
            action = self.server.queue.get(up2dateAuth.getSystemId(),
                ACTION_VERSION, status_report)

            return action
        except xmlrpclib.Fault, f:
            if f.faultCode == -31:
                raise up2dateErrors.InsuffMgmntEntsError(f.faultString), None, sys.exc_info()[2]
            else:
                print "Could not retrieve action item from server %s" % self.server
                print "Error code: %d%s" % (f.faultCode, f.faultString)
            sys.exit(-1)
Example #32
0
    def __get_action(self, status_report):
        try:
            action = self.server.queue.get(up2dateAuth.getSystemId(),
                ACTION_VERSION, status_report)

            return action
        except xmlrpclib.Fault, f:
            if f.faultCode == -31:
                raise up2dateErrors.InsuffMgmntEntsError(f.faultString), None, sys.exc_info()[2]
            else:
                print "Could not retrieve action item from server %s" % self.server
                print "Error code: %d%s" % (f.faultCode, f.faultString)
            sys.exit(-1)
Example #33
0
    def submit_response(self, action_id, status, message, data):
        """ Submit a response for an action_id. """

        # get a new server object with fresh headers
        self.server = CheckCli.__get_server()

        try:
            ret = self.server.queue.submit(up2dateAuth.getSystemId(),
                                           action_id, status, message, data)
        except xmlrpclib.Fault, f:
            print "Could not submit results to server %s" % self.server
            print "Error code: %d%s" % (f.faultCode, f.faultString)
            sys.exit(-1)
Example #34
0
    def execute(self):
        """
        Sends all items in the plan to the satellite.
        """
        systemid = up2dateAuth.getSystemId()

        if systemid is None:
            raise NotRegistered("System ID not found.")

        server = rhnserver.RhnServer()

        try:
            server.registration.virt_notify(systemid, self.__items)
        except up2dateErrors.CommunicationError, e:
            log.trace_me()
            log.log_me(e)
Example #35
0
def update(errataidlist, cache_only=None):

    if type(errataidlist) not in [type([]), type(())]:
        errataidlist = [ errataidlist ]

    s = rhnserver.RhnServer()
    if s.capabilities.hasCapability('xmlrpc.errata.patch_names'):
        system_id = up2dateAuth.getSystemId()

        erratas = s.errata.getErrataNamesById(system_id, errataidlist)
        errata_names = [tup[1] for tup in erratas]

        return packages.patch_install(errata_names, cache_only)
    else:
        # see XXX comment in old_update's method definition
        old_update(errataidlist, cache_only)
Example #36
0
    def execute(self):
        """
        Sends all items in the plan to the satellite.
        """
        systemid = up2dateAuth.getSystemId()

        if systemid is None:
            raise NotRegistered("System ID not found.")

        server = rhnserver.RhnServer()

        try:
            server.registration.virt_notify(systemid, self.__items)
        except up2dateErrors.CommunicationError, e:
            log.trace_me()
            log.log_me(e)
Example #37
0
def update(errataidlist, cache_only=None):

    if type(errataidlist) not in [type([]), type(())]:
        errataidlist = [errataidlist]

    s = rhnserver.RhnServer()
    if s.capabilities.hasCapability('xmlrpc.errata.patch_names'):
        system_id = up2dateAuth.getSystemId()

        erratas = s.errata.getErrataNamesById(system_id, errataidlist)
        errata_names = [tup[1] for tup in erratas]

        return packages.patch_install(errata_names, cache_only)
    else:
        # see XXX comment in old_update's method definition
        old_update(errataidlist, cache_only)
Example #38
0
def _upload_results(xccdf_result, results_dir, args):
    errors = ''
    if results_dir:
        server = rhnserver.RhnServer()
        # No need to check capabilities. The server supports detailed results
        # If rhe 'file_size' and 'id' was in supplied in the argument list.
        systemid = up2dateAuth.getSystemId()
        for filename in os.listdir(results_dir):
            path = os.path.join(results_dir, filename)
            if path == xccdf_result.name:
                f = xccdf_result.file
                filename = "xccdf-results.xml"
            else:
                f = open(path, 'rb')
            errors += _upload_file(server, systemid, args, path, filename, f)
            if path != xccdf_result.name:
                f.close()
    return errors
Example #39
0
def _upload_results(xccdf_result, results_dir, args):
    errors = ''
    if results_dir:
        server = rhnserver.RhnServer()
        # No need to check capabilities. The server supports detailed results
        # If rhe 'file_size' and 'id' was in supplied in the argument list.
        systemid = up2dateAuth.getSystemId()
        for filename in os.listdir(results_dir):
            path = os.path.join(results_dir, filename)
            if path == xccdf_result.name:
                f = xccdf_result.file
                filename = "xccdf-results.xml"
            else:
                f = open(path, 'rb')
            errors += _upload_file(server, systemid, args, path, filename, f)
            if path != xccdf_result.name:
                f.close()
    return errors
Example #40
0
def update_client_cert(cache_only=None):
    server = rhnserver.RhnServer()

    if not server.capabilities.hasCapability("registration.update_systemid"):
        return (1, "parent lacks registration.update_systemid capability", {})

    old_system_id = up2dateAuth.getSystemId().strip()
    new_system_id = server.registration.update_systemid(old_system_id).strip()

    if old_system_id == new_system_id:
        return (1, "not updating client certificate: old and new certificates match", {})

    # Write out the new client certificate
    if isinstance(new_system_id, unicode):
        rhnreg.writeSystemId(unicode.encode(new_system_id, "utf-8"))
    else:
        rhnreg.writeSystemId(new_system_id)

    return (0, "client certificate updated", {})
Example #41
0
def update_sources_list():
    sources = sourceslist.SourcesList()
    sw_source = []
    for source in sources.list:
        if source.uri.startswith('spacewalk://'):
            source.set_enabled(False)
            sw_source.append(source)

    if up2dateAuth.getSystemId():
        channels = get_channels()
        if len(channels):
            for source in sw_source:
                sources.remove(source)
            sources.add(type='deb',
                        uri='spacewalk://' + get_server(),
                        dist='channels:',
                        orig_comps=channels,
                        file=get_conf_file())
    sources.save()
def update_client_cert(cache_only=None):
    server = rhnserver.RhnServer()

    if not server.capabilities.hasCapability('registration.update_systemid'):
        return(1, 'parent lacks registration.update_systemid capability', {})

    old_system_id = up2dateAuth.getSystemId().strip()
    new_system_id = server.registration.update_systemid(old_system_id).strip()

    if old_system_id == new_system_id:
        return (1, 'not updating client certificate: old and new certificates match', {})

    # Write out the new client certificate
    if isinstance(new_system_id, unicode):
        rhnreg.writeSystemId(unicode.encode(new_system_id, 'utf-8'))
    else:
        rhnreg.writeSystemId(new_system_id)

    return (0, 'client certificate updated', {})
Example #43
0
def update_client_cert(cache_only=None):
    server = rhnserver.RhnServer()

    if not server.capabilities.hasCapability('registration.update_systemid'):
        return(1, 'parent lacks registration.update_systemid capability', {})

    old_system_id = up2dateAuth.getSystemId().strip()
    new_system_id = server.registration.update_systemid(old_system_id).strip()

    if old_system_id == new_system_id:
        return (1, 'client certificate did not change', {})

    # Write out the new client certificate
    if isinstance(systemid, unicode):
        rhnreg.writeSystemId(unicode.encode(systemid, 'utf-8'))
    else:
        rhnreg.writeSystemId(systemid)

    return (0, 'client certificate updated', {})
Example #44
0
def refresh_list(cache_only=None):
    if cache_only:
        return (0, "no-ops for caching", {})

    # read all hardware in
    hardwareList = hardware.Hardware()

    s = rpcServer.getServer()

    if argVerbose > 1:
        print "Called refresh_hardware"

    try:
        s.registration.refresh_hw_profile(up2dateAuth.getSystemId(),
                                          hardwareList)
    except:
        print "ERROR: sending hardware database for System Profile"
        return (12, "Error refreshing system hardware", {})

    return (0, "hardware list refreshed", {})
Example #45
0
def update_sources_list():
    sources = sourceslist.SourcesList()
    sw_source = []
    for source in sources.list:
        if source.uri.startswith('spacewalk://'):
            source.set_enabled(False)
            sw_source.append(source)

    if up2dateAuth.getSystemId():
        channels = get_channels()
        if len(channels):
            for source in sw_source:
                sources.remove(source)
            sources.add(type='deb',
                        uri='spacewalk://' + get_server(),
                        dist='channels:',
                        orig_comps=channels,
                        file=get_conf_file()
                        )
    sources.save()
Example #46
0
def main():
    if OPTIONS.add:
        subscribeChannels(OPTIONS.channel, OPTIONS.user, OPTIONS.password)
        if OPTIONS.verbose:
            print "Channel(s): %s successfully added" % ', '.join(OPTIONS.channel)
    elif OPTIONS.remove:
        unsubscribeChannels(OPTIONS.channel, OPTIONS.user, OPTIONS.password)
        if OPTIONS.verbose:
            print "Channel(s): %s successfully removed" % ', '.join(OPTIONS.channel)
    elif OPTIONS.list:
        try:
            channels = map(lambda x: x['label'], getChannels().channels())
        except up2dateErrors.NoChannelsError:
            systemExit(1, 'This system is not associated with any channel.')
        channels.sort()
        print '\n'.join(channels)
    else:
        s = rhnserver.RhnServer()
        print s.up2date.listall(up2dateAuth.getSystemId())
        systemExit(3, "ERROR: you may want to specify --add, --remove or --list")
Example #47
0
    def main(self):
        if not up2dateAuth.getSystemId():
            needToRegister = \
                _("You need to register this system by running " \
                "`rhn_register` before using this option")
            print(needToRegister)
            sys.exit(1)

        if not self._testRhnLogin():
            sys.exit(1)

        print(_("Updating package profile..."))
        rhnPackageInfo.updatePackageProfile()

        print(_("Updating hardware profile..."))
        rhnHardware.updateHardware()

        if support is not None:
            print(_("Updating virtualization profile..."))
            support.refresh(True)
Example #48
0
    def main(self):
        if not up2dateAuth.getSystemId():
            needToRegister = \
                _("You need to register this system by running " \
                "`rhn_register` before using this option")
            print(needToRegister)
            sys.exit(1)

        if not self._testRhnLogin():
            sys.exit(1)

        print(_("Updating package profile..."))
        rhnPackageInfo.updatePackageProfile()

        print(_("Updating hardware profile..."))
        rhnHardware.updateHardware()

        if support is not None:
            print(_("Updating virtualization profile..."))
            support.refresh(True)
Example #49
0
def refresh_list(cache_only=None):
    if cache_only:
        return (0, "no-ops for caching", {})

    # read all hardware in
    hardwareList = hardware.Hardware()

    s = rpcServer.getServer()

    if argVerbose > 1:
        print "Called refresh_hardware"

    try:
        s.registration.refresh_hw_profile(up2dateAuth.getSystemId(),
                                          hardwareList)
    except:
        print "ERROR: sending hardware database for System Profile"
        return (12, "Error refreshing system hardware", {})

    return (0, "hardware list refreshed", {})
Example #50
0
def update_count(problem_dir):
    problem_dir = os.path.normpath(os.path.abspath(problem_dir))
    basename = os.path.basename(problem_dir)
    log = up2dateLog.initLog()
    if not (os.path.exists(problem_dir) and os.path.isdir(problem_dir)):
        log.log_me("The specified path [%s] is not a valid directory." % problem_dir)
        return -1

    server = rhnserver.RhnServer()
    if not server.capabilities.hasCapability('abrt'):
        return -1

    systemid = up2dateAuth.getSystemId()
    crash_count_path = os.path.join(problem_dir, 'count')
    if not (os.path.exists(crash_count_path) and os.path.isfile(crash_count_path)):
        log.log_me("The problem directory [%s] does not contain any crash count information." % problem_dir)
        return 0

    crash_count = _readline(crash_count_path)
    server.abrt.update_crash_count(systemid, basename, crash_count)

    return 1
Example #51
0
def update(params, cache_only=None):
    if type(params) == dict:
        errataidlist = params['errata_ids']
        allow_vendor_change = params.get('allow_vendor_change', False)
    else:
        allow_vendor_change = False
        errataidlist = params

    if type(errataidlist) not in [type([]), type(())]:
        errataidlist = [errataidlist]

    s = rhnserver.RhnServer()
    if s.capabilities.hasCapability('xmlrpc.errata.patch_names'):
        system_id = up2dateAuth.getSystemId()

        erratas = s.errata.getErrataNamesById(system_id, errataidlist)
        errata_names = [tup[1] for tup in erratas]

        return packages.patch_install(errata_names, cache_only,
                                      allow_vendor_change)
    else:
        # see XXX comment in old_update's method definition
        old_update(errataidlist, cache_only)
Example #52
0
 def testGetSystemIdBogusLocation(self):
     "Verify that up2dateAuth.getSystemid fails when given an incorrect path"
     self.cfg['systemIdPath'] = "/a/b/c/d/shouldnt/exist/path"
     id = up2dateAuth.getSystemId()
     self.assertEqual(id, None)
Example #53
0
    modified_servers = []
    servers = config.getServerlURL()
    for server in servers:
        scheme, netloc, path, query, fragment = urlparse.urlsplit(server)
        modified_servers.append(
            urlparse.urlunsplit((scheme, netloc, '/rpc/api', query, fragment)))
    client = rhnserver.RhnServer(serverOverride=modified_servers)
    try:
        key = client.auth.login(user, password)
    except xmlrpclib.Fault, exc:
        systemExit(1,
                   "Error during client authentication: %s" % exc.faultString)

    system_id = re.sub(
        '^ID-', '',
        rpclib.xmlrpclib.loads(up2dateAuth.getSystemId())[0][0]['system_id'])
    result = []
    try:
        channels = client.system.listChildChannels(key, int(system_id))
    except xmlrpclib.Fault, exc:
        systemExit(1,
                   "Error when listing child channels: %s" % exc.faultString)

    for channel in channels:
        if 'LABEL' in channel:
            result.extend([channel['LABEL']])
        else:
            result.extend([channel['label']])
    return result

Example #54
0
 def __check_has_system_id():
     """ Retrieve the system_id. This is required. """
     if not up2dateAuth.getSystemId():
         print("ERROR: unable to read system id.")
         sys.exit(-1)
Example #55
0
def report(problem_dir):
    problem_dir = os.path.normpath(os.path.abspath(problem_dir))
    basename = os.path.basename(problem_dir)
    log = up2dateLog.initLog()
    if not (os.path.exists(problem_dir) and os.path.isdir(problem_dir)):
        log.log_me("The specified path [%s] is not a valid directory." % problem_dir)
        return -1

    crash_items = ['analyzer', 'cmdline', 'reason']
    if os.path.exists(os.path.join(problem_dir, 'vmcore')):
        crash_items = ['analyzer', 'vmcore-dmesg.txt']

    for item in crash_items:
        item_path = os.path.join(problem_dir, item)
        if not os.path.exists(item_path):
            log.log_me("Crash directory [%s] is incomplete or invalid" % problem_dir)
            return -1

    server = rhnserver.RhnServer()
    if not server.capabilities.hasCapability('abrt'):
        return -1

    systemid = up2dateAuth.getSystemId()

    # Package information
    pkg_data = {}
    for item in ['package', 'pkg_name', 'pkg_epoch', 'pkg_version', 'pkg_release', 'pkg_arch']:
        pkg_item_path = os.path.join(problem_dir, item)
        if os.path.exists(pkg_item_path):
            filecontent = _readline(pkg_item_path)

            if filecontent:
                pkg_data[item] = filecontent

    # Crash information
    crash_data = {'crash': basename, 'path': problem_dir}
    # Crash count
    crash_count = _readline(os.path.join(problem_dir, 'count'))
    if crash_count:
        crash_data['count'] = crash_count

    # Create record about the crash
    r = server.abrt.create_crash(systemid, crash_data, pkg_data)

    if (r < 0):  # Error creating new crash report
        log.log_me("Error creating new crash report.")
        return -1

    # Upload every particular file in the problem directory to the server
    for i in os.listdir(problem_dir):
        path = os.path.join(problem_dir, i)
        if not os.path.isfile(path):
            continue

        filesize = os.stat(path).st_size

        crash_file_data = {'filename': os.path.basename(i),
                           'path': path,
                           'filesize': filesize,
                           'filecontent': base64.encodestring(bstr("")),
                           'content-encoding': 'base64'}
        if server.abrt.is_crashfile_upload_enabled(systemid) and filesize <= server.abrt.get_crashfile_uploadlimit(systemid):
            f = open(path, 'r')
            try:
                crash_file_data['filecontent'] = base64.encodestring(f.read())
            finally:
                f.close()

        server.abrt.upload_crash_file(systemid, basename, crash_file_data)

    return 1
Example #56
0
def __getErrataInfo(errata_id):
    s = rhnserver.RhnServer()
    return s.errata.getErrataInfo(up2dateAuth.getSystemId(), errata_id)