Exemplo n.º 1
0
    def entitle(self, server_id, history, virt_type=None):
        """
        Entitle a server according to the entitlements we have configured.
        """
        log_debug(3, self.entitlements)

        # check for bootstrap_entitled and unentitle first
        cur = check_entitlement(server_id, True)
        if cur and 'bootstrap_entitled' in cur:
            remove_ent = rhnSQL.Procedure(
                "rhn_entitlements.remove_server_entitlement")
            remove_ent(server_id, "bootstrap_entitled")

        entitle_server = rhnSQL.Procedure("rhn_entitlements.entitle_server")
        # TODO: entitle_server calls can_entitle_server, so we're doing this
        # twice for each successful call. Is it necessary for external error
        # handling or can we ditch it?
        can_entitle_server = rhnSQL.Function(
            "rhn_entitlements.can_entitle_server", rhnSQL.types.NUMBER())

        can_ent = None

        history["entitlement"] = ""

        for entitlement in self.entitlements:
            if virt_type is not None and entitlement[0] == VIRT_ENT_LABEL:
                continue

            try:
                can_ent = can_entitle_server(server_id, entitlement[0])
            except rhnSQL.SQLSchemaError:
                e = sys.exc_info()[1]
                can_ent = 0

            try:
                # bugzilla #160077, skip attempting to entitle if we cant
                if can_ent:
                    entitle_server(server_id, entitlement[0])
            except rhnSQL.SQLSchemaError:
                e = sys.exc_info()[1]
                log_error("Token failed to entitle server", server_id,
                          self.get_names(), entitlement[0], e.errmsg)
                #No idea what error may be here...
                raise_with_tb(rhnFault(90, e.errmsg), sys.exc_info()[2])
            except rhnSQL.SQLError:
                e = sys.exc_info()[1]
                log_error("Token failed to entitle server", server_id,
                          self.get_names(), entitlement[0], e.args)
                raise_with_tb(rhnFault(90, str(e)), sys.exc_info()[2])
            else:
                history[
                    "entitlement"] = "Entitled as a %s member" % entitlement[1]
Exemplo n.º 2
0
 def __init__(self, sysid, name=None, data=None):
     machine_id = data.get(
         "machine_id") if data and "machine_id" in data else None
     if not name:
         name = "unknown"
     log_debug(4, "updating machine_id", sysid, name, machine_id)
     existing_srv_id = self.__check_if_machine_id_exists(machine_id)
     if not existing_srv_id or existing_srv_id == sysid:
         s_update = rhnSQL.prepare("""
                     UPDATE rhnServer
                        SET machine_id = :machine_id
                     WHERE id = :server_id
                     """)
         s_update.execute(machine_id=machine_id, server_id=sysid)
     else:
         # this indicate a forced re-registration and we need to remove the old rhnServer
         log_debug(
             0,
             "Found duplicate server. Re-registration expected. Deleting existing: ",
             existing_srv_id)
         delete_server = rhnSQL.Procedure("delete_server")
         try:
             delete_server(existing_srv_id)
         except rhnSQL.SQLError:
             log_error("Error deleting server: %s" % existing_srv_id)
Exemplo n.º 3
0
    def entitle(self, server_id, history, virt_type=None):
        """
        Entitle a server according to the entitlements we have configured.
        """
        log_debug(3, self.entitlements)

        entitle_server = rhnSQL.Procedure("rhn_entitlements.entitle_server")
        # TODO: entitle_server calls can_entitle_server, so we're doing this
        # twice for each successful call. Is it necessary for external error
        # handling or can we ditch it?
        can_entitle_server = rhnSQL.Function(
            "rhn_entitlements.can_entitle_server", rhnSQL.types.NUMBER())

        can_ent = None

        history["entitlement"] = ""

        # Do a quick check to see if both virt entitlements are present. (i.e.
        # activation keys stacked together) If so, give preference to the more
        # powerful virtualization platform and remove the regular virt
        # entitlement from the list.
        found_virt = False
        found_virt_platform = False
        for entitlement in self.entitlements:
            if entitlement[0] == VIRT_ENT_LABEL:
                found_virt = True
            elif entitlement[0] == VIRT_PLATFORM_ENT_LABEL:
                found_virt_platform = True

        for entitlement in self.entitlements:
            if virt_type is not None and entitlement[0] in \
                    (VIRT_ENT_LABEL, VIRT_PLATFORM_ENT_LABEL):
                continue

            # If both virt entitlements are present, skip the least powerful:
            if found_virt and found_virt_platform and entitlement[0] == VIRT_ENT_LABEL:
                log_debug(1, "Virtualization and Virtualization Platform " +
                          "entitlements both present.")
                log_debug(1, "Skipping Virtualization.")
                continue

            try:
                can_ent = can_entitle_server(server_id, entitlement[0])
            except rhnSQL.SQLSchemaError, e:
                can_ent = 0

            try:
                # bugzilla #160077, skip attempting to entitle if we cant
                if can_ent:
                    entitle_server(server_id, entitlement[0])
            except rhnSQL.SQLSchemaError, e:
                log_error("Token failed to entitle server", server_id,
                          self.get_names(), entitlement[0], e.errmsg)
                if e.errno == 20220:
                    # ORA-20220: (servergroup_max_members) - Server group membership
                    # cannot exceed maximum membership
                    raise rhnFault(91,
                                   _("Registration failed: RHN Software service entitlements exhausted: %s") % entitlement[0]), None, sys.exc_info()[2]
                # No idea what error may be here...
                raise rhnFault(90, e.errmsg), None, sys.exc_info()[2]
Exemplo n.º 4
0
def get(name, modified=None, raw=None, compressed=None):
    # Check to see if the entry is in the database, with the right version
    h = _fetch_cursor(key=name, modified=modified)

    row = h.fetchone_dict()

    if not row:
        # Key not found
        return None

    if modified and row['delta'] != 0:
        # Different version
        log_debug(4, "database cache: different version")
        return None

    if modified is None:
        # The caller doesn't care about the modified time, but we do, since we
        # want to fetch the same version from the disk cache
        modified = row['modified']

    if rhnCache.has_key(name, modified):
        # We have the value
        log_debug(4, "Filesystem cache HIT")
        return rhnCache.get(name, modified=modified, raw=raw)

    log_debug(4, "Filesystem cache MISS")

    # The disk cache doesn't have this key at all, or it's a modified value
    # Fetch the value from the database

    v = row['value']
    # Update the accessed field
    rhnSQL.Procedure("rhn_cache_update_accessed")(name)

    if compressed:
        io = cStringIO.StringIO()

        io.write(rhnSQL.read_lob(v))
        io.seek(0, 0)

        # XXX For about 40M of compressed data sometimes we get:
        # zlib.error: Error -3 while decompressing: incomplete dynamic bit lengths tree
        v = gzip.GzipFile(None, "r", 0, io)

    try:
        data = v.read()
    except (ValueError, IOError, gzip.zlib.error) as e:
        # XXX poking at gzip.zlib may not be that well-advised
        log_error("rhnDatabaseCache: gzip error for key %s: %s" % (name, e))
        # Ignore this entry in the database cache, it has invalid data
        return None

    # We store the data in the database cache, in raw format
    rhnCache.set(name, data, modified=modified, raw=1)

    # Unpickle the data, unless raw access was requested
    if not raw:
        return cPickle.loads(data)

    return data
Exemplo n.º 5
0
    def management_remove_file(self, dict):
        log_debug(1)
        self._get_and_validate_session(dict)

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

        row = rhnSQL.fetchone_dict(self._query_lookup_config_file_by_channel,
                                   org_id=self.org_id,
                                   config_channel=config_channel,
                                   path=path)
        if not row:
            raise rhnFault(4011,
                           "File %s does not exist in channel %s" %
                           (path, config_channel),
                           explain=0)

        config_file_id = row['id']

        delete_call = rhnSQL.Procedure("rhn_config.delete_file")
        delete_call(config_file_id)

        rhnSQL.commit()

        return {}
Exemplo n.º 6
0
    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:
            errno = e.args[0]
            if errno == 2292:
                raise rhnFault(4005,
                               "Cannot remove non-empty channel %s" %
                               config_channel,
                               explain=0), None, sys.exc_info()[2]
            raise
Exemplo n.º 7
0
def __unsubscribeServers(labels):
    sql = """
        select distinct sc.server_id as server_id, C.id as channel_id, c.parent_channel, c.label
        from rhnChannel c inner join
             rhnServerChannel sc on c.id = sc.channel_id
        where c.label in (%s) order by C.parent_channel
    """
    params, bind_params = _bind_many(labels)
    bind_params = ', '.join(bind_params)
    h = rhnSQL.prepare(sql % (bind_params))
    h.execute(**params)
    server_channel_list = h.fetchall_dict()

    channel_counts = {}
    for i in server_channel_list:
        if i['label'] in channel_counts:
            channel_counts[i['label']] = channel_counts[i['label']] + 1
        else:
            channel_counts[i['label']] = 1
    print("\nThe following channels will have their systems unsubscribed:")
    channel_list = channel_counts.keys()
    channel_list.sort()
    for i in channel_list:
        print("%-40s %-8s" % (i, channel_counts[i]))

    pb = ProgressBar(prompt='Unsubscribing:    ', endTag=' - complete',
                     finalSize=len(server_channel_list), finalBarLength=40, stream=sys.stdout)
    pb.printAll(1)

    unsubscribe_server_proc = rhnSQL.Procedure("rhn_channel.unsubscribe_server")
    for i in server_channel_list:
        unsubscribe_server_proc(i['server_id'], i['channel_id'])
        pb.addTo(1)
        pb.printIncrement()
    pb.printComplete()
Exemplo n.º 8
0
    def _entitle(self, entitlement):
        system_entitlements = server_lib.check_entitlement(self.server["id"])
        system_entitlements = system_entitlements.keys()

        if entitlement not in system_entitlements:
            entitle_server = rhnSQL.Procedure("rhn_entitlements.entitle_server")
            entitle_server(self.server['id'], entitlement)
Exemplo n.º 9
0
    def entitle(self, server_id, history, virt_type=None):
        """
        Entitle a server according to the entitlements we have configured.
        """
        log_debug(3, self.entitlements)

        entitle_server = rhnSQL.Procedure("rhn_entitlements.entitle_server")
        # TODO: entitle_server calls can_entitle_server, so we're doing this
        # twice for each successful call. Is it necessary for external error
        # handling or can we ditch it?
        can_entitle_server = rhnSQL.Function(
            "rhn_entitlements.can_entitle_server", rhnSQL.types.NUMBER())

        can_ent = None

        history["entitlement"] = ""

        for entitlement in self.entitlements:
            if virt_type is not None and entitlement[0] == VIRT_ENT_LABEL:
                continue

            try:
                can_ent = can_entitle_server(server_id, entitlement[0])
            except rhnSQL.SQLSchemaError, e:
                can_ent = 0

            try:
                # bugzilla #160077, skip attempting to entitle if we cant
                if can_ent:
                    entitle_server(server_id, entitlement[0])
            except rhnSQL.SQLSchemaError, e:
                log_error("Token failed to entitle server", server_id,
                          self.get_names(), entitlement[0], e.errmsg)
                #No idea what error may be here...
                raise rhnFault(90, e.errmsg), None, sys.exc_info()[2]
Exemplo n.º 10
0
def delete_guests(server_id):
    """
    Callback used after a successful kickstart to remove any guest virtual
    instances, as well as their associated servers.
    """
    # First delete all the guest server objects:
    h = rhnSQL.prepare(_query_lookup_guests_for_host)
    h.execute(server_id=server_id)
    delete_server = rhnSQL.Procedure("delete_server")
    log_debug(4, "Deleting guests")
    while 1:
        row = h.fetchone_dict()
        if not row:
            break
        guest_id = row['virtual_system_id']
        log_debug(4, 'Deleting guest server: %s' % guest_id)
        try:
            if guest_id is not None:
                delete_server(guest_id)
        except rhnSQL.SQLError:
            log_error("Error deleting server: %s" % guest_id)

    # Finally delete all the virtual instances:
    log_debug(4, "Deleting all virtual instances for host")
    h = rhnSQL.prepare(_query_delete_virtual_instances)
    h.execute(server_id=server_id)

    # Commit all changes:
    try:
        rhnSQL.commit()
    except rhnSQL.SQLError:
        e = sys.exc_info()[1]
        log_error("Error committing transaction: %s" % e)
        rhnSQL.rollback()
Exemplo n.º 11
0
def create_new_org(username, password):
    f = rhnSQL.Procedure('create_new_org')

    username = rhnSQL.types.STRING(username)
    password = rhnSQL.types.STRING(password)
    ncl = rhnSQL.types.NUMBER

    ret = f(username, password, ncl())
    return int(ret[2])
Exemplo n.º 12
0
def update_errata_cache(server_id):
    """ Queue an update the the server's errata cache. This queues for
        Taskomatic instead of doing it in-line because updating many servers
        at once was problematic and lead to unresponsive Satellite and
        incorrectly reporting failed actions when they did not fail (see
        bz 1119460).
    """
    log_debug(2, "Queueing the errata cache update", server_id)
    update_needed_cache = rhnSQL.Procedure("queue_server")
    update_needed_cache(server_id, 0)
Exemplo n.º 13
0
def update_errata_cache(server_id):
    """ Function that updates rhnServerNeededPackageCache by deltas (as opposed to
        calling queue_server which removes the old entries and inserts new ones).
        It now also updates rhnServerNeededErrataCache, but as the entries there
        are a subset of rhnServerNeededPackageCache's entries, it still gives
        statistics regarding only rhnServerNeededPackageCache.
    """
    log_debug(2, "Updating the errata cache", server_id)
    update_needed_cache = rhnSQL.Procedure("rhn_server.update_needed_cache")
    update_needed_cache(server_id)
Exemplo n.º 14
0
def update_channel_family_counts():
    update_family_counts_proc = rhnSQL.Procedure("rhn_channel.update_family_counts")
    h = rhnSQL.prepare(_query_private_families)
    h.execute()
    while 1:
        row = h.fetchone_dict()
        if not row:
            break
        update_family_counts_proc(row['channel_family_id'], row['org_id'])

    rhnSQL.commit()
Exemplo n.º 15
0
 def entitle(self, server_id, history, virt_type=None):
     for ent in self.remove_entitlements:
         unentitle_server = rhnSQL.Procedure(
             "rhn_entitlements.remove_server_entitlement")
         try:
             unentitle_server(server_id, ent)
         except rhnSQL.SQLSchemaError, e:
             log_error("Failed to unentitle server", server_id, ent,
                       e.errmsg)
             raise rhnFault(90, e.errmsg), None, sys.exc_info()[2]
         except rhnSQL.SQLError, e:
             log_error("Failed to unentitle server", server_id, ent, e.args)
             raise rhnFault(90, str(e)), None, sys.exc_info()[2]
Exemplo n.º 16
0
def push_monitoring_configs(org_id):
    push_configs_proc = rhnSQL.Procedure("rhn_install_org_satellites")

    h = rhnSQL.prepare(_query_get_sat_clusters)
    h.execute(customer_id=org_id)
    rows = h.fetchall_dict()
    if not rows:
        #since we've not found any scouts, just do nothing
        pass
    else:
        for row in rows:
            push_configs_proc(org_id, row['recid'], '1')

        print "Pushing scout configs to all monitoring scouts"
Exemplo n.º 17
0
    def entitle(self, server_id, history, virt_type=None):
        for ent in self.remove_entitlements:
            unentitle_server = rhnSQL.Procedure(
                "rhn_entitlements.remove_server_entitlement")
            try:
                unentitle_server(server_id, ent)
            except rhnSQL.SQLSchemaError:
                e = sys.exc_info()[1]
                log_error("Failed to unentitle server", server_id, ent,
                          e.errmsg)
                raise_with_tb(rhnFault(90, e.errmsg), sys.exc_info()[2])
            except rhnSQL.SQLError:
                e = sys.exc_info()[1]
                log_error("Failed to unentitle server", server_id, ent, e.args)
                raise_with_tb(rhnFault(90, str(e)), sys.exc_info()[2])

        # Call parent method:
        ReRegistrationToken.entitle(self, server_id, history, virt_type)
Exemplo n.º 18
0
def create_new_user(org_id=None, username=None, password=None, roles=None):
    "Create a new user"
    if org_id is None:
        org_id = create_new_org()
    else:
        org_id = lookup_org_id(org_id)

    if username is None:
        username = "******" % time.time()
    if password is None:
        password = "******" % time.time()
    if roles is None:
        roles = []

    u = rhnUser.User(username, password)
    u.set_org_id(org_id)
    u.save()
    # The password is scrambled now - re-set it
    u.contact['password'] = password
    u.save()
    user_id = u.getid()

    # Set roles
    h = rhnSQL.prepare("""
        select ug.id
          from rhnUserGroupType ugt, rhnUserGroup ug
         where ug.org_id = :org_id
           and ug.group_type = ugt.id
           and ugt.label = :role
    """)
    create_ugm = rhnSQL.Procedure("rhn_user.add_to_usergroup")
    for role in roles:
        h.execute(org_id=org_id, role=role)
        row = h.fetchone_dict()
        if not row:
            raise InvalidRoleError(org_id, role)

        user_group_id = row['id']
        create_ugm(user_id, user_group_id)

    rhnSQL.commit()

    return u
Exemplo n.º 19
0
    def __remove_errata(self, errata_id, advisory):
        """ Remove an errata. """

        channel_ids = errata_helper.channelsWithErrata(errata_id)

        for channel_id in channel_ids:
            _printLog("Removing '{0}' patch from channel '{1}'".format(advisory, channel_id))

            # delete errata from channel
            errata_helper.deleteChannelErrata(errata_id, channel_id)

            # Update the errata/package cache for the servers
            # use procedure rhn_channel.update_needed_cache(channel_id)
            log_debug(2, "Update Server Cache for channel '{0}'".format(channel_id))
            rhnSQL.commit()
            update_needed_cache = rhnSQL.Procedure("rhn_channel.update_needed_cache")
            update_needed_cache(channel_id)
            rhnSQL.commit()

        errata_helper.deleteErrata(errata_id)
Exemplo n.º 20
0
def create_first_org(owner):
    """ create first org_id if needed
        Always returns the org_id
        Will not commit
    """

    try:
        return get_org_id()
    except NoOrgIdError:
        # gotta create one first org then
        p = rhnSQL.Procedure("create_first_org")
        # copying logic from validate-sat-cert.pl
        # I.e., setting their org_id password to the pid cubed.
        #       That password is not used by anything.
        pword = str(long(os.getpid())**3)
        # do it!
        p(owner, pword)
        # Now create the first private channel family
        create_first_private_chan_family()
        verify_family_permissions()
    return get_org_id()
Exemplo n.º 21
0
 def create_perm_cache(self):
     log_debug(4)
     create_perms = rhnSQL.Procedure("rhn_cache.update_perms_for_server")
     create_perms(self.server['id'])
Exemplo n.º 22
0
def token_channels(server, server_arch, tokens_obj):
    """ Handle channel subscriptions for the registration token """
    assert(isinstance(tokens_obj, ActivationTokens))

    server_id, server_arch_id = server['id'], server['server_arch_id']

    # what channels are associated with this token (filter only those
    # compatible with this server)
    h = rhnSQL.prepare("""
    select
        rtc.channel_id id, c.name, c.label, c.parent_channel
    from
        rhnRegTokenChannels rtc,
        rhnChannel c,
        rhnServerChannelArchCompat scac
    where rtc.token_id = :token_id
        and rtc.channel_id = c.id
        and c.channel_arch_id = scac.channel_arch_id
        and scac.server_arch_id = :server_arch_id
    """)

    chash = {}
    base_channel_token = None
    base_channel_id = None

    for token in tokens_obj.tokens:
        token_id = token['token_id']
        h.execute(token_id=token_id, server_arch_id=server_arch_id)
        while 1:
            row = h.fetchone_dict()
            if not row:
                break
            channel_id = row['id']
            chash[channel_id] = row
            if row['parent_channel'] is not None:
                # Not a base channel
                continue

            # We only allow for one base channel
            if base_channel_id is not None and channel_id != base_channel_id:
                # Base channels conflict - are they coming from the same
                # token?
                if base_channel_token == token:
                    log_error("Token has multiple base channels", token_id,
                              base_channel_id)
                    raise rhnFault(62,
                                   _("Token `%s' has more than one base channel assigned")
                                   % token['note'])
                raise rhnFault(63, _("Conflicting base channels"))
            base_channel_id = channel_id
            base_channel_token = token

    bc = chash.get(base_channel_id)
    log_debug(4, "base channel", bc)

    # get the base channel for this server
    # Note that we are hitting this codepath after newserver.__save() has been
    # run, which means we've already chosen a base channel
    # from rhnDistChannelMap
    sbc = rhnChannel.get_base_channel(server_id, none_ok=1)

    # prepare the return value
    ret = []

    # now try to figure out which base channel we prefer
    if bc is None:
        if sbc is None:
            # we need at least one base channel definition
            log_error("Server has invalid release and "
                      "token contains no base channels", server_id,
                      tokens_obj.tokens)
            ret.append("System registered without a base channel")
            ret.append("Unsupported release-architecture combination "
                       "(%s, %s)" % (server["release"], server_arch))
            return ret
    else:  # do we need to drop the one from sbc?
        if sbc and sbc["id"] != bc["id"]:  # we need to prefer the token one
            # unsubscribe from old channel(s)
            rhnChannel.unsubscribe_all_channels(server_id)
            sbc = None  # force true on the next test
        if sbc is None:
            # no base channel subscription at this point
            try:
                rhnChannel._subscribe_sql(server_id, bc["id"], commit=0)
            except rhnChannel.SubscriptionCountExceeded:
                ret.append("System registered without a base channel: "
                           "subscription count exceeded for channel %s (%s)" %
                           (bc["name"], bc["label"]))
                return ret

            ret.append("Subscribed to base channel '%s' (%s)" % (
                bc["name"], bc["label"]))
            sbc = bc

    # attempt to subscribe all non-base channels associated with this
    # token
    subscribe_channel = rhnSQL.Procedure("rhn_channel.subscribe_server")
    # Use a set here to ensure uniqueness of the
    # channel family ids used in the loop below.
    channel_family_ids = set()

    for c in filter(lambda a: a["parent_channel"], chash.values()):
        # make sure this channel has the right parent
        if str(c["parent_channel"]) != str(sbc["id"]):
            ret.append("NOT subscribed to channel '%s' "
                       "(not a child of '%s')" % (
                           c["name"], sbc["name"]))
            continue
        try:
            # don't run the EC yet
            # XXX: test return code when this one will start returning
            # a status
            subscribe_channel(server_id, c["id"], 0, None, 0)
            child = rhnChannel.Channel()
            child.load_by_id(c["id"])
            child._load_channel_families()
            cfamid = child._channel_families[0]
            channel_family_ids.add(cfamid)
        except rhnSQL.SQLError, e:
            log_error("Failed channel subscription", server_id,
                      c["id"], c["label"], c["name"])
            ret.append("FAILED to subscribe to channel '%s'" % c["name"])
        else:
            ret.append("Subscribed to channel '%s'" % c["name"])
Exemplo n.º 23
0
            child = rhnChannel.Channel()
            child.load_by_id(c["id"])
            child._load_channel_families()
            cfamid = child._channel_families[0]
            channel_family_ids.add(cfamid)
        except rhnSQL.SQLError, e:
            log_error("Failed channel subscription", server_id,
                      c["id"], c["label"], c["name"])
            ret.append("FAILED to subscribe to channel '%s'" % c["name"])
        else:
            ret.append("Subscribed to channel '%s'" % c["name"])

    log_debug(5, "cf ids: %s" % str(channel_family_ids))
    log_debug(5, "Server org_id: %s" % str(server['org_id']))
    #rhn_channel.update_family_counts(channel_family_id_val, server_org_id_val)
    update_family_counts = rhnSQL.Procedure("rhn_channel.update_family_counts")
    for famid in channel_family_ids:
        # Update the channel family counts separately at the end here
        # instead of in the loop above.  If you have an activation key
        # with lots of custom child channels you can end up repeatedly
        # updating the same channel family counts over and over and over
        # even thou you really only need todo it once.
        log_debug(5, "calling update fam counts: %s" % famid)
        update_family_counts(famid, server['org_id'])

    return ret

_query_token_server_groups = rhnSQL.Statement("""
    select rtg.server_group_id, sg.name
      from rhnRegTokenGroups rtg, rhnServerGroup sg
     where rtg.token_id = :token_id
Exemplo n.º 24
0
def grant_entitlements(org_id, entitlement, quantity):
    activate_system_entitlement = rhnSQL.Procedure(
        "rhn_entitlements.activate_system_entitlement")

    activate_system_entitlement(org_id, entitlement, quantity)
Exemplo n.º 25
0
def create_new_user(org_id=None,
                    username=None,
                    password=None,
                    roles=None,
                    encrypt_password=False):
    "Create a new user"
    if org_id is None:
        org_id = create_new_org()
    else:
        org_id = lookup_org_id(org_id)

    if username is None:
        username = "******" % time.time()
    if password is None:
        password = "******" % time.time()
    if encrypt_password:
        password = rhnUser.encrypt_password(password)
    if roles is None:
        roles = []

    login = username
    oracle_contact_id = None
    prefix = "Mr."
    first_names = "First Name %3.f" % time.time()
    last_name = "Last Name %3.f" % time.time()
    genqual = None
    parent_company = None
    company = "ACME"
    title = ""
    phone = ""
    fax = ""
    email = "*****@*****.**" % username
    pin = 0
    first_names_ol = " "
    last_name_ol = " "
    address1 = " "
    address2 = " "
    address3 = " "
    city = " "
    state = " "
    zip_code = " "
    country = " "
    alt_first_names = None
    alt_last_name = None
    contact_call = "N"
    contact_mail = "N"
    contact_email = "N"
    contact_fax = "N"

    f = rhnSQL.Function('create_new_user', rhnSQL.types.NUMBER())
    ret = f(org_id, login, password, oracle_contact_id, prefix, first_names,
            last_name, genqual, parent_company, company, title, phone, fax,
            email, pin, first_names_ol, last_name_ol, address1, address2,
            address3, city, state, zip_code, country, alt_first_names,
            alt_last_name, contact_call, contact_mail, contact_email,
            contact_fax)

    u = rhnUser.search(username)

    if u is None:
        raise Exception("Couldn't create the new user - user not found")

    # Set roles
    h = rhnSQL.prepare("""
        select ug.id
          from rhnUserGroupType ugt, rhnUserGroup ug
         where ug.org_id = :org_id
           and ug.group_type = ugt.id
           and ugt.label = :role
    """)
    create_ugm = rhnSQL.Procedure("rhn_user.add_to_usergroup")
    for role in roles:
        h.execute(org_id=org_id, role=role)
        row = h.fetchone_dict()
        if not row:
            raise InvalidRoleError(org_id, role)

        user_group_id = row['id']
        create_ugm(u.getid(), user_group_id)

    return u
Exemplo n.º 26
0
#
# Copyright (c) 2008--2010 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#

from spacewalk.server import rhnSQL

rhnSQL.initDB("rhnuser/rhnuser@webdev")

p = rhnSQL.Procedure("rhn_channel.subscribe_server")

try:
    p(1003486745, 33)
except:
    rhnSQL.rollback()
    raise

rhnSQL.rollback()
Exemplo n.º 27
0
def snapshot_server(server_id, reason):
    if CFG.ENABLE_SNAPSHOTS:
        return rhnSQL.Procedure("rhn_server.snapshot_server")(server_id,
                                                              reason)
Exemplo n.º 28
0
    def __init__(self, hw=None, guest=None):
        log_debug(4, hw, guest)
        if not hw or "identifier" not in hw or not guest:
            # incomplete data
            log_debug(1, "incomplete data")
            return
        host = rhnSQL.Row("rhnServer", "digital_server_id")
        host.load(hw['identifier'])
        hid = host.get('id')
        guest.user = rhnUser.User("", "")
        guest.user.reload(guest.server['creator_id'])
        guestid = guest.getid()
        if not hid:
            # create a new host entry
            host = server_class.Server(guest.user, hw.get('arch'))
            host.server["name"] = hw.get('name')
            host.server["os"] = hw.get('os')
            host.server["release"] = hw.get('type')
            host.server["last_boot"] = time.time()
            host.default_description()
            host.virt_type = rhnVirtualization.VirtualizationType.FULLY
            host.virt_uuid = None
            fake_token = False
            if not rhnFlags.test("registration_token"):
                # we need to fake it
                rhnFlags.set("registration_token", 'fake')
                fake_token = True
            host.save(1, None)
            host.server["digital_server_id"] = hw['identifier']
            entitle_server = rhnSQL.Procedure(
                "rhn_entitlements.entitle_server")
            entitle_server(host.getid(), 'foreign_entitled')
            host.save(1, None)
            if fake_token:
                rhnFlags.set("registration_token", None)

            hid = host.getid()
            host.reload(hid)
            log_debug(4, "New host created: ", host)
        else:
            host = server_class.Server(None)
            host.reload(hid)
            host.checkin(commit=0)
            log_debug(4, "Found host: ", host)
        host.reload_hardware()
        hostcpu = host.hardware_by_class(CPUDevice)
        if hostcpu and len(hostcpu) > 0:
            hostcpu = hostcpu[0].data
        else:
            hostcpu = None
        if not hostcpu or str(hostcpu.get('nrsocket')) != hw.get('total_ifls'):
            # update only if the number has changed
            log_debug(1, "update host cpu:", hw.get('total_ifls'))
            cpu = {
                'class': 'CPU',
                'desc': 'Processor',
                'count': hw.get('total_ifls'),
                'model_ver': '',
                'speed': '0',
                'cache': '',
                'model_number': '',
                'bogomips': '',
                'socket_count': hw.get('total_ifls'),
                'platform': hw.get('arch'),
                'other': '',
                'model_rev': '',
                'model': hw.get('arch'),
                'type': hw.get('type')
            }
            host.delete_hardware()
            host.add_hardware(cpu)
            host.save_hardware()

        h = rhnSQL.prepare("""
            select host_system_id
              from rhnVirtualInstance
             where virtual_system_id = :guestid""")
        h.execute(guestid=guestid)
        row = h.fetchone_dict()
        if not row or not row['host_system_id']:
            self._insert_virtual_instance(hid, None, fakeuuid=False)
            self._insert_virtual_instance(hid, guestid, fakeuuid=True)
        elif row['host_system_id'] != hid:
            log_debug(4, "update_virtual_instance", hid, guestid)
            q_update = rhnSQL.prepare("""
                UPDATE rhnVirtualInstance
                   SET host_system_id = :host_id
                 WHERE virtual_system_id = :guest_id
                   AND host_system_id = :old_host_id
            """)
            q_update.execute(host_id=hid,
                             guest_id=guestid,
                             old_host_id=row['host_system_id'])
Exemplo n.º 29
0
#
# Copyright (c) 2008--2016 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#

from spacewalk.server import rhnSQL

rhnSQL.initDB('rhnuser/rhnuser@phx')

counter = 0
while 1:
    #p = rhnSQL.Procedure('rhn_entitlements.get_server_entitlement')
    p = rhnSQL.Procedure('rhn_entitlements.upgrade_server')
    ret = p(1000102174)
    print((counter, ret))
    counter = counter + 1
    # if counter > 700:
    #    time.sleep(.5)
Exemplo n.º 30
0
    def change_base_channel(self, new_rel, suse_products=None):
        log_debug(3, self.server["id"], new_rel)
        old_rel = self.server["release"]
        current_channels = rhnChannel.channels_for_server(self.server["id"])
        # Extract the base channel off of
        old_base = [x for x in current_channels if not x['parent_channel']]

        # Quick sanity check
        base_channels_count = len(old_base)
        if base_channels_count == 1:
            old_base = old_base[0]
        elif base_channels_count == 0:
            old_base = None
        else:
            raise rhnException(
                "Server %s subscribed to multiple base channels" %
                (self.server["id"], ))

        # bz 442355
        # Leave custom base channels alone, don't alter any of the channel subscriptions
        if not CFG.RESET_BASE_CHANNEL and old_base and rhnChannel.isCustomChannel(
                old_base["id"]):
            log_debug(
                3,
                "Custom base channel detected, will not alter channel subscriptions"
            )
            self.server["release"] = new_rel
            self.server.save()
            msg = """The SUSE Manager Update Agent has detected a
            change in the base version of the operating system running
            on your system, additionally you are subscribed to a custom
            channel as your base channel.  Due to this configuration
            your channel subscriptions will not be altered.
            """
            self.add_history(
                "Updated system release from %s to %s" % (old_rel, new_rel),
                msg)
            self.save_history_byid(self.server["id"])
            return 1

        s = rhnChannel.LiteServer().init_from_server(self)
        s.release = new_rel
        s.arch = self.archname
        if suse_products:
            s.suse_products = suse_products
        # Let get_server_channels deal with the errors and raise rhnFault
        target_channels = rhnChannel.guess_channels_for_server(s, none_ok=True)
        if target_channels:
            target_base = [
                x for x in target_channels if not x['parent_channel']
            ][0]
        else:
            target_base = None

        channels_to_subscribe = []
        channels_to_unsubscribe = []
        if old_base and target_base and old_base['id'] == target_base['id']:
            # Same base channel. Preserve the currently subscribed child
            # channels, just add the ones that are missing
            hash = {}
            for c in current_channels:
                hash[c['id']] = c

            for c in target_channels:
                channel_id = c['id']
                if channel_id in hash:
                    # Already subscribed to this one
                    del hash[channel_id]
                    continue
                # Have to subscribe to this one
                channels_to_subscribe.append(c)

            # We don't want to lose subscriptions to prior channels, so don't
            # do anything with hash.values()
        else:
            # Different base channel
            channels_to_unsubscribe = current_channels
            channels_to_subscribe = target_channels

        rhnSQL.transaction("change_base_channel")
        self.server["release"] = new_rel
        self.server.save()
        if not (channels_to_subscribe or channels_to_unsubscribe):
            # Nothing to do, just add the history entry
            self.add_history("Updated system release from %s to %s" %
                             (old_rel, new_rel))
            self.save_history_byid(self.server["id"])
            return 1

        # XXX: need a way to preserve existing subscriptions to
        # families so we can restore access to non-public ones.

        rhnChannel.unsubscribe_channels(self.server["id"],
                                        channels_to_unsubscribe)
        rhnChannel.subscribe_channels(self.server["id"], channels_to_subscribe)
        # now that we changed, recompute the errata cache for this one
        rhnSQL.Procedure("queue_server")(self.server["id"])
        # Make a history note
        sub_channels = rhnChannel.channels_for_server(self.server["id"])
        if sub_channels:
            channel_list = [a["name"] for a in sub_channels]
            msg = """The SUSE Manager Update Agent has detected a
            change in the base version of the operating system running
            on your system and has updated your channel subscriptions
            to reflect that.
            Your server has been automatically subscribed to the following
            channels:\n%s\n""" % (string.join(channel_list, "\n"), )
        else:
            msg = """*** ERROR: ***
            While trying to subscribe this server to software channels:
            There are no channels serving release %s""" % new_rel
        self.add_history(
            "Updated system release from %s to %s" % (old_rel, new_rel), msg)
        self.save_history_byid(self.server["id"])
        return 1