Пример #1
0
    def test_new_server_token_2(self):
        "Test registration with token that specifies a base channel"

        # FIXME: the test fails because there's no channel associated with the
        # freshly created Server: rhnServerChannel is not populated by the
        # registration code.

        u, _ = self._create_new_user()
        org_id = u.contact['org_id']
        base_channel = 'rhel-i386-as-3'
        entitlements = self._entitlements
        os_release = "2.1as"

        t = misc_functions.create_activation_key(
            org_id=u.contact['org_id'],
            entitlement_level=entitlements,
            user_id=u.getid(),
            channels=[base_channel],
            release=os_release)

        token = t.get_token()

        params = build_new_system_params_with_token(token=token,
                                                    os_release=os_release)

        system_id = register_new_system(params)
        rhnSQL.commit()

        s = rhnServer.get(system_id)
        self.assertNotEqual(s, None)

        server_id = s.getid()
        channels = rhnChannel.channels_for_server(server_id)
        self.assertEqual(len(channels), 1)
        self.assertEqual(channels[0]['label'], base_channel)
    def test_new_server_token_2(self):
        "Test registration with token that specifies a base channel"

        # FIXME: the test fails because there's no channel associated with the
        # freshly created Server: rhnServerChannel is not populated by the
        # registration code.

        u, _ = self._create_new_user()
        org_id = u.contact['org_id']
        base_channel = 'rhel-i386-as-3'
        entitlements = self._entitlements
        os_release = "2.1as"

        t = misc_functions.create_activation_key(org_id=u.contact['org_id'],
                                                 entitlement_level=entitlements, user_id=u.getid(),
                                                 channels=[base_channel], release=os_release)

        token = t.get_token()

        params = build_new_system_params_with_token(
            token=token,
            os_release=os_release
        )

        system_id = register_new_system(params)
        rhnSQL.commit()

        s = rhnServer.get(system_id)
        self.assertNotEqual(s, None)

        server_id = s.getid()
        channels = rhnChannel.channels_for_server(server_id)
        self.assertEqual(len(channels), 1)
        self.assertEqual(channels[0]['label'], base_channel)
Пример #3
0
    def listChannels(self, system_id):
        """ Clients v2+ """
        log_debug(5, system_id)
        # Authenticate the system certificate
        self.auth_system('listChannels', system_id)
        # log the entry
        log_debug(1, self.server_id)
        channelList = rhnChannel.channels_for_server(self.server_id)

        loginDict = {
            'X-RHN-Server-Id':
            self.server_id,
            'X-RHN-Auth-Channels':
            rhnChannel.getSubscribedChannels(self.server_id),
        }

        # Duplicate these values in the headers so that the proxy can
        # intercept and cache them without parseing the xmlrpc.
        transport = rhnFlags.get('outputTransportOptions')
        for k, v in list(loginDict.items()):
            # Special case for channels
            if k.lower() == 'x-rhn-auth-channels'.lower():
                # Concatenate the channel information column-separated
                transport[k] = [':'.join(x) for x in v]
            else:
                transport[k] = v
        return channelList
    def test_new_server_1(self):
        "Test normal server registration, with username/password"
        u, password = self._create_new_user()
        username = u.contact['login']
        org_id = u.contact['org_id']
        entitlements = self._entitlements
        os_release = "2.1as"

        t = misc_functions.create_activation_key(
            org_id=u.contact['org_id'],
            entitlement_level=entitlements,
            user_id=u.getid(),
            release=os_release
        )

        params = build_new_system_params_with_username(username=username,
                                                       password=password, os_release=os_release)

        system_id = register_new_system(params)
        rhnSQL.commit()

        s = rhnServer.get(system_id)
        self.assertNotEqual(s, None)

        server_id = s.getid()
        channels = rhnChannel.channels_for_server(server_id)
        self.assertEqual(len(channels), 1)
        self.assertEqual(channels[0]['label'], self._channel)
    def test_new_server_token_2(self):
        "Test registration with token that specifies a base channel"
        u = self._create_new_user()
        org_id = u.contact['org_id']
        base_channel = 'rhel-i386-as-3'
        entitlements = self._entitlements
        t = misc_functions.create_activation_key(org_id=u.contact['org_id'],
            entitlement_level=entitlements, user_id=u.getid(),
            channels=[base_channel])

        token = t.get_token()
        
        params = build_new_system_params_with_token(token=token,
            os_release="2.1AS")

        system_id = register_new_system(params)
        rhnSQL.commit()

        s = rhnServer.get(system_id)
        self.assertNotEqual(s, None)

        server_id = s.getid()
        channels = rhnChannel.channels_for_server(server_id)
        self.assertEqual(len(channels), 1)
        self.assertEqual(channels[0]['label'], base_channel)
Пример #6
0
    def test_new_server_1(self):
        "Test normal server registration, with username/password"
        u, password = self._create_new_user()
        username = u.contact['login']
        org_id = u.contact['org_id']
        entitlements = self._entitlements
        os_release = "2.1as"

        t = misc_functions.create_activation_key(
            org_id=u.contact['org_id'],
            entitlement_level=entitlements,
            user_id=u.getid(),
            release=os_release)

        params = build_new_system_params_with_username(username=username,
                                                       password=password,
                                                       os_release=os_release)

        system_id = register_new_system(params)
        rhnSQL.commit()

        s = rhnServer.get(system_id)
        self.assertNotEqual(s, None)

        server_id = s.getid()
        channels = rhnChannel.channels_for_server(server_id)
        self.assertEqual(len(channels), 1)
        self.assertEqual(channels[0]['label'], self._channel)
Пример #7
0
 def listChannels(self, system_id):
     """ Clients v2+ """
     log_debug(5, system_id)
     # Authenticate the system certificate
     self.auth_system('listChannels', system_id)
     # log the entry
     log_debug(1, self.server_id)
     channelList = rhnChannel.channels_for_server(self.server_id)
     return channelList
Пример #8
0
 def listChannels(self, system_id):
     """ Clients v2+ """
     log_debug(5, system_id)
     # Authenticate the system certificate
     self.auth_system('listChannels', system_id)
     # log the entry
     log_debug(1, self.server_id)
     channelList = rhnChannel.channels_for_server(self.server_id)
     return channelList
Пример #9
0
 def __check_channel(self, version):
     """ check if the current channel version matches that of the client """
     channel_list = rhnChannel.channels_for_server(self.server_id)
     # Check the subscription to this channel
     for channel in channel_list:
         if channel['label'] == self.channelName:
             # Okay, we verified the subscription
             # Check the version too
             if channel['last_modified'] == version:
                 # Great
                 break
             # Old version; should re-login to get the new version
             raise rhnFault(41, "Invalid channel version")
     else:
         # Not subscribed
         raise rhnFault(39, "No subscription to the specified channel")
     return 1
Пример #10
0
 def __check_channel(self, version):
     """ check if the current channel version matches that of the client """
     channel_list = rhnChannel.channels_for_server(self.server_id)
     # Check the subscription to this channel
     for channel in channel_list:
         if channel['label'] == self.channelName:
             # Okay, we verified the subscription
             # Check the version too
             if channel['last_modified'] == version:
                 # Great
                 break
             # Old version; should re-login to get the new version
             raise rhnFault(41, "Invalid channel version")
     else:
         # Not subscribed
         raise rhnFault(39, "No subscription to the specified channel")
     return 1
Пример #11
0
    def _get_channel_info(self):
        """
            Looks up the correct channel based on channel_lookup_string.
            Populates the id, label, and a boolean that tells whether the
            channel is found.
        """
        subscribed_channels = channels_for_server(self.server_id)

        #Our tools channels all start with "rhn-tools", which seems
        #to be the only way to reliably tell one channel from the other
        #automagically.
        self.found_tools_channel = False
        for channel_info in subscribed_channels:
            label_position = channel_info['label'].find(self.channel_lookup_string)
            if label_position > -1 and label_position == 0:
                self.found_channel = True
                self.channel_id = channel_info['id']
                self.channel_label = channel_info['label']
    def test_new_server_1(self):
        "Test normal server registration, with username/password"
        u = self._create_new_user()
        username = u.contact['login']
        password = u.contact['password']
        params = build_new_system_params_with_username(username=username,
            password=password, os_release="2.1AS")
        
        system_id = register_new_system(params)
        rhnSQL.commit()

        s = rhnServer.get(system_id)
        self.assertNotEqual(s, None)

        server_id = s.getid()
        channels = rhnChannel.channels_for_server(server_id)
        self.assertEqual(len(channels), 1)
        self.assertEqual(channels[0]['label'], self._channel)
Пример #13
0
    def _get_channel_info(self):
        """
            Looks up the correct channel based on channel_lookup_string.
            Populates the id, label, and a boolean that tells whether the
            channel is found.
        """
        subscribed_channels = channels_for_server(self.server_id)

        # Our tools channels all start with "rhn-tools", which seems
        # to be the only way to reliably tell one channel from the other
        # automagically.
        self.found_tools_channel = False
        for channel_info in subscribed_channels:
            label_position = channel_info['label'].find(self.channel_lookup_string)
            if label_position > -1 and label_position == 0:
                self.found_channel = True
                self.channel_id = channel_info['id']
                self.channel_label = channel_info['label']
Пример #14
0
 def listChannels(self):
     """ Clients v2+
     returns a list of the channels the server is subscribed to, or
     could subscribe to.
     """
     return rhnChannel.channels_for_server(self.server_id)
Пример #15
0
    def login(self, system_id, extra_data={}):
        """ Clients v2+
            Log in routine.
            Return a dictionary of session token/channel information.
            Also sets this information in the headers.
        """
        log_debug(5, system_id)
        # Authenticate the system certificate. We need the user record
        # to generate the tokens
        self.load_user = 1
        server = self.auth_system('login', system_id)
        # log the entry
        log_debug(1, self.server_id)
        # Update the capabilities list
        rhnCapability.update_client_capabilities(self.server_id)
        # Fetch the channels this client is subscribed to
        channelList = rhnChannel.channels_for_server(self.server_id)
        channels = []
        for each in channelList:
            if not each.has_key('last_modified'):
                # No last_modified attribute
                # Probably an empty channel, so ignore
                continue
            channel = [each['label'], each['last_modified']]
            # isBaseChannel
            if each['parent_channel']:
                flag = "0"
            else:
                flag = "1"
            channel.append(flag)

            # isLocalChannel
            if each['local_channel']:
                flag = "1"
            else:
                flag = "0"
            channel.append(flag)

            channels.append(channel)

        rhnServerTime = str(time.time())
        expireOffset = str(CFG.CLIENT_AUTH_TIMEOUT)
        signature = computeSignature(CFG.SECRET_KEY, self.server_id, self.user,
                                     rhnServerTime, expireOffset)

        loginDict = {
            'X-RHN-Server-Id': self.server_id,
            'X-RHN-Auth-User-Id': self.user,
            'X-RHN-Auth': signature,
            'X-RHN-Auth-Server-Time': rhnServerTime,
            'X-RHN-Auth-Expire-Offset': expireOffset,
            # List of lists [[label,last_mod],...]:
            'X-RHN-Auth-Channels': channels
        }

        # Duplicate these values in the headers so that the proxy can
        # intercept and cache them without parseing the xmlrpc.
        transport = rhnFlags.get('outputTransportOptions')
        for k, v in loginDict.items():
            # Special case for channels
            if string.lower(k) == string.lower('X-RHN-Auth-Channels'):
                # Concatenate the channel information column-separated
                transport[k] = map(lambda x: string.join(x, ':'), v)
            else:
                transport[k] = v
        log_debug(5, "loginDict", loginDict, transport)

        # store route in DB (schema for RHN 3.1+ only!)
        server_route.store_client_route(self.server_id)

        return loginDict
Пример #16
0
    def change_base_channel(self, new_rel):
        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 Red Hat Satellite Update Agent has detected a
            change in the base version of the operating system running
            on your system, additionaly 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
        # 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 = filter(lambda x: not x['parent_channel'],
                                 target_channels)[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 Red Hat Satellite 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
Пример #17
0
    def new_system_user_pass(self, profile_name, os_release_name,
                             version, arch, username,
                             password, other):
        """ Registers a new system to an org specified by a username, password, and
            optionally an org id.

            New for RHEL 5.

            All args are strings except other.
            other is a dict with:
            * org_id - optional. Must be a string that contains the number. If it's
            not given, the default org is used.
            * reg_num - optional. It should be an EN. It will not be activated. It's
            used for automatic subscription to child channels and for deciding which
            service level to entitle the machine to (managment, provisioning, etc).
            If not given, the machine will only be registered to a base channel and
            entitled to the highest level possible.

            If a profile is created it will return a dict with:
            * system_id - the same xml as was previously returned
            * channels - a list of the channels (as strings) the system was
              subscribed to
            * failed_channels - a list of channels (as strings) that
              the system should have been subscribed to but couldn't be because they
              don't have the necessary entitlements available. Can contain all the
              channels including the base channel.
            * system_slots - a list of the system slots used (as strings).
            * failed_system_slots - a list of system slots (as strings) that they
              should have used but couldn't because there weren't available
              entitlements
            * universal_activation_key - a list of universal default activation keys
              (as strings) that were used while registering.
            Allowable slots are 'enterprise_entitled' (management), 'sw_mgr_entitled'
            (updates), 'monitoring_entitled' (monitoring add on to management), and
            provisioning_entitled (provisioning add on to management).
            The call will try to use the highest system slot available. An entry will
            be added to failed_system_slots for each one that is tried and fails and
            system_slots will contain the one that succeeded if any.
            Eg: Calling this on hosted with no reg num and only update entitlements
            will result in system_slots containing 'sw_mgr_entitled' and
            failed_system_slots containing 'enterprise_entitled'.

            If an error occurs which prevents the creation of a profile, a fault will
            be raised:
            TODO
        """

        add_to_seclist(password)

        log_debug(4,'in new_system_user_pass')

        # release_name wasn't required in the old call, so I'm just going to
        # add it to other
        other['release_name'] = os_release_name

        # Authorize the username and password. Save the returned user object.
        user = self.validate_system_user(username, password)

        # This creates the rhnServer record and commits it to the db.
        # It also assigns the system a base channel.
        server_data = self.create_system(user, profile_name,
                                         version,
                                         arch,
                                         other)
        # Save the returned Server object
        newserv = server_data['server']

        # Get the server db id.
        server_id = newserv.getid()

        # Get the server certificate file
        system_certificate = newserv.system_id()

        log_debug(4, 'Server id created as %s' % server_id)

        failures = []
        unknowns = []

        # Build our return values.
        attempted_channels = []
        successful_channels = []
        failed_channels = []

        actual_channels = rhnChannel.channels_for_server(server_id)
        for channel in actual_channels:
            successful_channels.append(channel['label'])

        # If we don't have any successful channels, we know the base channel
        # failed.
        if len(successful_channels) == 0:
            log_debug(4, 'System %s not subscribed to any channels' % server_id)

            # Look up the base channel, and store it as a failure.
            try:
                base = rhnChannel.get_channel_for_release_arch(
                                                        version,
                                                        arch, newserv['org_id'])
                failed_channels.append(base['label'])
            # We want to swallow exceptions here as we are just generating data
            # for the review screen in rhn_register.
            except:
                pass

        # Store any of our child channel failures
        failed_channels = failed_channels + failures

        attempted_system_slots = ['enterprise_entitled', 'sw_mgr_entitled']
        successful_system_slots = server_lib.check_entitlement(server_id)
        successful_system_slots = successful_system_slots.keys()
        failed_system_slots = []

        # Check which entitlement level we got, starting with the highest.
        i = 0
        for slot in attempted_system_slots:
            if slot in successful_system_slots:
                break
            i = i + 1

        # Any entitlements we didn't have, we'll store as a failure.
        failed_system_slots = attempted_system_slots[0:i]

        universal_activation_key = []
        if rhnFlags.test("universal_registration_token"):
            token = rhnFlags.get("universal_registration_token")
            universal_activation_key = token.get_tokens()

        return { 'system_id' : system_certificate,
                 'channels' : successful_channels,
                 'failed_channels' : failed_channels,
                 'failed_options' : unknowns,
                 'system_slots' : successful_system_slots,
                 'failed_system_slots' : failed_system_slots,
                 'universal_activation_key' : universal_activation_key
                 }
Пример #18
0
    print rhnChannel.channels_for_release_arch('2.1AS', 'athlon-redhat-linux', user_id=575937)
    print rhnChannel.channels_for_release_arch('2.1AS', 'XXXX-redhat-linux', user_id=575937)
    # mibanescu-2
#    print rhnChannel.channels_for_release_arch('9', 'i386-redhat-linux', user_id=2012148)
    # mibanescu-plain
    print rhnChannel.channels_for_release_arch('2.1AS', 'athlon-redhat-linux', user_id=2825619)
    sys.exit(1)

    channel = "redhat-linux-i386-7.1"

    start = time.time()
    ret = rhnChannel.list_packages(channel)
    print "Took %.2f seconds to list %d packages in %s" % (
        time.time() - start, len(ret), channel)
    # pprint.pprint(ret)

    start = time.time()
    ret = rhnChannel.list_obsoletes(channel)
    print "Took %.2f seconds to list %d obsoletes in %s" % (
        time.time() - start, len(ret), channel)
    # pprint.pprint(ret)

    server_id = 1002156837
    channels = rhnChannel.channels_for_server(server_id)

    s = rhnServer.search(server_id)
    s.change_base_channel("2.1AS-foobar")
    print map(lambda x: x['label'], channels)
    print map(lambda x: x['label'], rhnChannel.channels_for_server(server_id))
    rhnSQL.commit()
Пример #19
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
Пример #20
0
    def login(self, system_id, extra_data={}):
        """ Clients v2+
            Log in routine.
            Return a dictionary of session token/channel information.
            Also sets this information in the headers.
        """
        log_debug(5, system_id)
        # Authenticate the system certificate. We need the user record
        # to generate the tokens
        self.load_user = 1
        server = self.auth_system('login', system_id)
        # log the entry
        log_debug(1, self.server_id)
        # Update the capabilities list
        rhnCapability.update_client_capabilities(self.server_id)
        # Fetch the channels this client is subscribed to
        channelList = rhnChannel.channels_for_server(self.server_id)
        channels = []
        for each in channelList:
            if not each.has_key('last_modified'):
                # No last_modified attribute
                # Probably an empty channel, so ignore
                continue
            channel = [each['label'], each['last_modified']]
            # isBaseChannel
            if each['parent_channel']:
                flag = "0"
            else:
                flag = "1"
            channel.append(flag)

            # isLocalChannel
            if each['local_channel']:
                flag = "1"
            else:
                flag = "0"
            channel.append(flag)

            channels.append(channel)

        rhnServerTime = str(time.time())
        expireOffset = str(CFG.CLIENT_AUTH_TIMEOUT)
        signature = computeSignature(CFG.SECRET_KEY,
                                     self.server_id,
                                     self.user,
                                     rhnServerTime,
                                     expireOffset)

        loginDict = {
                'X-RHN-Server-Id'           : self.server_id,
                'X-RHN-Auth-User-Id'        : self.user,
                'X-RHN-Auth'                : signature,
                'X-RHN-Auth-Server-Time'    : rhnServerTime,
                'X-RHN-Auth-Expire-Offset'  : expireOffset,
                # List of lists [[label,last_mod],...]:
                'X-RHN-Auth-Channels'       : channels
                }

        # Duplicate these values in the headers so that the proxy can
        # intercept and cache them without parseing the xmlrpc.
        transport = rhnFlags.get('outputTransportOptions')
        for k, v in loginDict.items():
            # Special case for channels
            if string.lower(k) == string.lower('X-RHN-Auth-Channels'):
                # Concatenate the channel information column-separated
                transport[k] = map(lambda x: string.join(x, ':'), v)
            else:
                transport[k] = v
        log_debug(5, "loginDict", loginDict, transport)

        # store route in DB (schema for RHN 3.1+ only!)
        server_route.store_client_route(self.server_id)

        return loginDict
Пример #21
0
 def listChannels(self):
     """ Clients v2+
     returns a list of the channels the server is subscribed to, or
     could subscribe to.
     """
     return rhnChannel.channels_for_server(self.server_id)
Пример #22
0
    print(rhnChannel.channels_for_release_arch('2.1AS', 'athlon-redhat-linux', user_id=575937))
    print(rhnChannel.channels_for_release_arch('2.1AS', 'XXXX-redhat-linux', user_id=575937))
    # mibanescu-2
#    print rhnChannel.channels_for_release_arch('9', 'i386-redhat-linux', user_id=2012148)
    # mibanescu-plain
    print(rhnChannel.channels_for_release_arch('2.1AS', 'athlon-redhat-linux', user_id=2825619))
    sys.exit(1)

    channel = "redhat-linux-i386-7.1"

    start = time.time()
    ret = rhnChannel.list_packages(channel)
    print("Took %.2f seconds to list %d packages in %s" % (
        time.time() - start, len(ret), channel))
    # pprint.pprint(ret)

    start = time.time()
    ret = rhnChannel.list_obsoletes(channel)
    print("Took %.2f seconds to list %d obsoletes in %s" % (
        time.time() - start, len(ret), channel))
    # pprint.pprint(ret)

    server_id = 1002156837
    channels = rhnChannel.channels_for_server(server_id)

    s = rhnServer.search(server_id)
    s.change_base_channel("2.1AS-foobar")
    print([x['label'] for x in channels])
    print([x['label'] for x in rhnChannel.channels_for_server(server_id)])
    rhnSQL.commit()
Пример #23
0
    #    print rhnChannel.channels_for_release_arch('9', 'i386-redhat-linux', user_id=2012148)
    # mibanescu-plain
    print(
        rhnChannel.channels_for_release_arch('2.1AS',
                                             'athlon-redhat-linux',
                                             user_id=2825619))
    sys.exit(1)

    channel = "redhat-linux-i386-7.1"

    start = time.time()
    ret = rhnChannel.list_packages(channel)
    print("Took %.2f seconds to list %d packages in %s" %
          (time.time() - start, len(ret), channel))
    # pprint.pprint(ret)

    start = time.time()
    ret = rhnChannel.list_obsoletes(channel)
    print("Took %.2f seconds to list %d obsoletes in %s" %
          (time.time() - start, len(ret), channel))
    # pprint.pprint(ret)

    server_id = 1002156837
    channels = rhnChannel.channels_for_server(server_id)

    s = rhnServer.search(server_id)
    s.change_base_channel("2.1AS-foobar")
    print([x['label'] for x in channels])
    print([x['label'] for x in rhnChannel.channels_for_server(server_id)])
    rhnSQL.commit()
Пример #24
0
    def new_system_user_pass(self, profile_name, os_release_name,
                             version, arch, username,
                             password, other):
        """ Registers a new system to an org specified by a username, password, and
            optionally an org id.

            New for RHEL 5.

            All args are strings except other.
            other is a dict with:
            * org_id - optional. Must be a string that contains the number. If it's
            not given, the default org is used.
            * reg_num - optional. It should be an EN. It will not be activated. It's
            used for automatic subscription to child channels and for deciding which
            service level to entitle the machine to (managment, provisioning, etc).
            If not given, the machine will only be registered to a base channel and
            entitled to the highest level possible.

            If a profile is created it will return a dict with:
            * system_id - the same xml as was previously returned
            * channels - a list of the channels (as strings) the system was
              subscribed to
            * failed_channels - a list of channels (as strings) that
              the system should have been subscribed to but couldn't be because they
              don't have the necessary entitlements available. Can contain all the
              channels including the base channel.
            * system_slots - a list of the system slots used (as strings).
            * failed_system_slots - a list of system slots (as strings) that they
              should have used but couldn't because there weren't available
              entitlements
            * universal_activation_key - a list of universal default activation keys
              (as strings) that were used while registering.
            Allowable slots are 'enterprise_entitled' (management), 'sw_mgr_entitled'
            (updates), 'monitoring_entitled' (monitoring add on to management), and
            provisioning_entitled (provisioning add on to management).
            The call will try to use the highest system slot available. An entry will
            be added to failed_system_slots for each one that is tried and fails and
            system_slots will contain the one that succeeded if any.
            Eg: Calling this on hosted with no reg num and only update entitlements
            will result in system_slots containing 'sw_mgr_entitled' and
            failed_system_slots containing 'enterprise_entitled'.

            If an error occurs which prevents the creation of a profile, a fault will
            be raised:
            TODO
        """

        add_to_seclist(password)

        log_debug(4,'in new_system_user_pass')

        # release_name wasn't required in the old call, so I'm just going to
        # add it to other
        other['release_name'] = os_release_name

        # Authorize the username and password. Save the returned user object.
        user = self.validate_system_user(username, password)

        # This creates the rhnServer record and commits it to the db.
        # It also assigns the system a base channel.
        server_data = self.create_system(user, profile_name,
                                         version,
                                         arch,
                                         other)
        # Save the returned Server object
        newserv = server_data['server']

        # Get the server db id.
        server_id = newserv.getid()

        # Get the server certificate file
        system_certificate = newserv.system_id()

        log_debug(4, 'Server id created as %s' % server_id)

        failures = []
        unknowns = []

        # Build our return values.
        attempted_channels = []
        successful_channels = []
        failed_channels = []

        actual_channels = rhnChannel.channels_for_server(server_id)
        for channel in actual_channels:
            successful_channels.append(channel['label'])

        # If we don't have any successful channels, we know the base channel
        # failed.
        if len(successful_channels) == 0:
            log_debug(4, 'System %s not subscribed to any channels' % server_id)

            # Look up the base channel, and store it as a failure.
            try:
                base = rhnChannel.get_channel_for_release_arch(
                                                        version,
                                                        arch, newserv['org_id'])
                failed_channels.append(base['label'])
            # We want to swallow exceptions here as we are just generating data
            # for the review screen in rhn_register.
            except:
                pass

        # Store any of our child channel failures
        failed_channels = failed_channels + failures

        attempted_system_slots = ['enterprise_entitled', 'sw_mgr_entitled']
        successful_system_slots = server_lib.check_entitlement(server_id)
        successful_system_slots = successful_system_slots.keys()
        failed_system_slots = []

        # Check which entitlement level we got, starting with the highest.
        i = 0
        for slot in attempted_system_slots:
            if slot in successful_system_slots:
                break
            i = i + 1

        # Any entitlements we didn't have, we'll store as a failure.
        failed_system_slots = attempted_system_slots[0:i]

        universal_activation_key = []
        if rhnFlags.test("universal_registration_token"):
            token = rhnFlags.get("universal_registration_token")
            universal_activation_key = token.get_tokens()

        return { 'system_id' : system_certificate,
                 'channels' : successful_channels,
                 'failed_channels' : failed_channels,
                 'failed_options' : unknowns,
                 'system_slots' : successful_system_slots,
                 'failed_system_slots' : failed_system_slots,
                 'universal_activation_key' : universal_activation_key
                 }