コード例 #1
0
def read_syspurpose(raise_on_error=False):
    """
    Reads the system purpose from the correct location on the file system.
    Makes an attempt to use a SyspurposeStore if available falls back to reading the json directly.
    :return: A dictionary containing the total syspurpose.
    """
    if SyncedStore is not None:
        try:
            syspurpose = SyncedStore(None).get_local_contents()
        except (OSError, IOError):
            syspurpose = {}
    else:
        try:
            syspurpose = json.load(open(USER_SYSPURPOSE))
        except (os.error, ValueError, IOError):
            # In the event this file could not be read treat it as empty
            if raise_on_error:
                raise
            syspurpose = {}
    return syspurpose
コード例 #2
0
def write_syspurpose(values):
    """
    Write the syspurpose to the file system.
    :param values:
    :return:
    """
    if SyncedStore is not None:
        sp = SyncedStore(None)
        sp.update_local(values)
    else:
        # Simple backup in case the syspurpose tooling is not installed.
        try:
            json.dump(values,
                      open(USER_SYSPURPOSE),
                      ensure_ascii=True,
                      indent=2)
        except OSError:
            log.warning('Could not write syspurpose to %s' % USER_SYSPURPOSE)
            return False
    return True
コード例 #3
0
    def test_list_items_are_order_agnostic(self):
        addons = [1, 2]
        self.uep.getConsumer.return_value = {'addOns': addons}

        # Write an out of order list to both the local and cache
        write_to_file_utf8(io.open(self.local_syspurpose_file, 'w'), {'addons': addons[::-1]})
        write_to_file_utf8(io.open(self.cache_syspurpose_file, 'w'), {'addons': addons[::-1]})

        synced_store = SyncedStore(self.uep, consumer_uuid="something")
        result = self.assertRaisesNothing(synced_store.sync)

        self.assertTrue(isinstance(result, SyncResult))

        local_result = json.load(io.open(self.local_syspurpose_file, 'r'))
        cache_result = json.load(io.open(self.cache_syspurpose_file, 'r'))

        self.assertSetEqual(set(result.result['addons']), set(local_result['addons']),
                            'Expected local file to have the same set of addons as the result')
        self.assertSetEqual(set(result.result['addons']),  set(cache_result['addons']),
                            'Expected cache file to have the same set of addons as the result')
コード例 #4
0
    def _assert_falsey_values_removed_from_local(self, remote_contents,
                                                 local_contents,
                                                 cache_contents):
        self.uep.getConsumer.return_value = remote_contents

        write_to_file_utf8(io.open(self.local_syspurpose_file, 'w'),
                           local_contents)
        write_to_file_utf8(io.open(self.cache_syspurpose_file, 'w'),
                           cache_contents)

        synced_store = SyncedStore(self.uep, consumer_uuid="something")
        result = self.assertRaisesNothing(synced_store.sync)

        self.assertTrue(isinstance(result, SyncResult))
        local_result = json.load(io.open(self.local_syspurpose_file, 'r'))
        # All the values from the local file should be truthy.
        self.assertTrue(all(local_result[key] for key in local_result))

        cache_result = json.load(io.open(self.cache_syspurpose_file, 'r'))
        # The cache should contain the entire set of values from the SyncResult
        self.assertDictEqual(cache_result, result.result)
コード例 #5
0
def save_sla_to_syspurpose_metadata(service_level):
    """
    Saves the provided service-level value to the local Syspurpose Metadata (syspurpose.json) file.
    If the service level provided is null or empty, the sla value to the local syspurpose file is set to null.

    :param service_level: The service-level value to be saved in the syspurpose file.
    :type service_level: str
    """

    if 'SyncedStore' in globals() and SyncedStore is not None:
        store = SyncedStore(None)

        # if empty, set it to null
        if service_level is None or service_level == "":
            service_level = None

        store.set("service_level_agreement", service_level)
        store.finish()
        log.info("Syspurpose SLA value successfully saved locally.")
    else:
        log.error("SyspurposeStore could not be imported. Syspurpose SLA value not saved locally.")
コード例 #6
0
    def test_server_side_falsey_removes_value_locally(self):
        initial_syspurpose = {'role': 'something'}
        remote_contents = {'role': ''}
        self.uep.getConsumer.return_value = remote_contents

        # Write an out of order list to both the local and cache
        write_to_file_utf8(io.open(self.local_syspurpose_file, 'w'), initial_syspurpose)
        write_to_file_utf8(io.open(self.cache_syspurpose_file, 'w'), initial_syspurpose)

        synced_store = SyncedStore(self.uep, consumer_uuid="something")
        result = self.assertRaisesNothing(synced_store.sync)

        self.assertTrue(isinstance(result, SyncResult))

        local_result = json.load(io.open(self.local_syspurpose_file, 'r'))
        cache_result = json.load(io.open(self.cache_syspurpose_file, 'r'))

        self.assertTrue('role' not in local_result,
                        'The role was falsey and should not have been in the local file')
        self.assertTrue('role' in cache_result and cache_result['role'] == remote_contents['role'],
                        'Expected the cache file to contain the same value for role as the remote')
コード例 #7
0
    def test_server_does_not_support_syspurpose(self):
        # This is how we detect if we have syspurpose support
        self.uep.has_capability = mock.Mock(side_effect=lambda x: x in [])

        write_to_file_utf8(io.open(self.local_syspurpose_file, 'w'), {u'role': u'initial'})
        write_to_file_utf8(io.open(self.cache_syspurpose_file, 'w'), {})

        synced_store = SyncedStore(self.uep, consumer_uuid="something")

        self.assertRaisesNothing(synced_store.set, u'role', u'new_role')
        result = self.assertRaisesNothing(synced_store.sync)

        self.assertTrue(isinstance(result, SyncResult))

        local_result = json.load(io.open(self.local_syspurpose_file, 'r'))
        cache_result = json.load(io.open(self.cache_syspurpose_file, 'r'))

        # The cache should not be updated at all
        self.assert_equal_dict({}, cache_result)
        self.assert_equal_dict({u'role': u'new_role'}, local_result)

        self.uep.updateConsumer.assert_not_called()
コード例 #8
0
    def perform(self, include_result=False):
        """
        Perform the action that this Command represents.
        :return:
        """
        result = {}
        consumer_uuid = inj.require(inj.IDENTITY).uuid

        try:
            store = SyncedStore(uep=self.uep,
                                consumer_uuid=consumer_uuid,
                                on_changed=self.report.record_change)
            result = store.sync()
        except ConnectionException as e:
            self.report._exceptions.append(
                'Unable to sync syspurpose with server: %s' % str(e))
            self.report._status = 'Failed to sync system purpose'
        self.report._updates = "\n\t\t ".join(self.report._updates)
        log.debug("Syspurpose updated: %s" % self.report)
        if not include_result:
            return self.report
        else:
            return self.report, result
コード例 #9
0
def main():
    """
    Run the cli (Do the syspurpose tool thing!!)
    :return: 0
    """
    log.debug("Running the syspurpose utility...")

    parser = setup_arg_parser()
    args = parser.parse_args()

    # Syspurpose is not intended to be used in containers for the time being (could change later).
    if in_container():
        print(
            _("WARNING: Setting syspurpose in containers has no effect."
              "Please run syspurpose on the host.\n"))

    try:
        from subscription_manager.identity import Identity
        from subscription_manager.cp_provider import CPProvider
        identity = Identity()
        uuid = identity.uuid
        uep = CPProvider().get_consumer_auth_cp()
    except ImportError:
        uuid = None
        uep = None
        print(
            _("Warning: Unable to sync system purpose with subscription management server:"
              " subscription_manager module is not available."))

    syspurposestore = SyncedStore(uep=uep, consumer_uuid=uuid)
    if getattr(args, 'func', None) is not None:
        args.func(args, syspurposestore)
    else:
        parser.print_help()
        return 0

    return 0
コード例 #10
0
    def test_user_deletes_syspurpose_file(self):
        cache_contents = {
            u'role': u'initial_role',
            u'usage': u'initial_usage',
            u'service_level_agreement': u'',
            u'addons': []
        }
        remote_contents = {
            u'role': u'initial_role',
            u'usage': u'initial_usage',
            u'serviceLevel': u'',
            u'addOns': []
        }
        consumer_uuid = "something"
        self.uep.getConsumer.return_value = remote_contents
        write_to_file_utf8(io.open(self.cache_syspurpose_file, 'w'),
                           cache_contents)
        # We don't write anything to the self.local_syspurpose_file anywhere else, so not making
        # one is equivalent to removing an existing one.

        synced_store = SyncedStore(self.uep, consumer_uuid=consumer_uuid)
        result = self.assertRaisesNothing(synced_store.sync)

        expected_cache = {u'service_level_agreement': u'', u'addons': []}
        expected_local = {}

        local_result = json.load(io.open(self.local_syspurpose_file, 'r'))
        cache_result = json.load(io.open(self.cache_syspurpose_file, 'r'))

        self.assert_equal_dict(expected_local, local_result)
        self.assert_equal_dict(expected_cache, cache_result)
        self.uep.updateConsumer.assert_called_once_with(consumer_uuid,
                                                        role="",
                                                        usage="",
                                                        service_level=u"",
                                                        addons=[])
コード例 #11
0
def save_sla_to_syspurpose_metadata(uep, consumer_uuid, service_level):
    """
    Saves the provided service-level value to the local Syspurpose Metadata (syspurpose.json) file.
    If the service level provided is null or empty, the sla value to the local syspurpose file is set to null.
    when uep and consumer_uuid is not None, then service_level is also synced with candlepin server

    :param uep: The object with uep connection (connection to candlepin server)
    :param consumer_uuid: Consumer UUID
    :param service_level: The service-level value to be saved in the syspurpose file.
    :type service_level: str
    """

    if 'SyncedStore' in globals() and SyncedStore is not None:
        synced_store = SyncedStore(uep=uep, consumer_uuid=consumer_uuid)

        # if empty, set it to null
        if service_level is None or service_level == "":
            service_level = None

        synced_store.set("service_level_agreement", service_level)
        synced_store.finish()
        log.debug("Syspurpose SLA value successfully saved locally.")
    else:
        log.error("SyspurposeStore could not be imported. Syspurpose SLA value not saved locally.")
コード例 #12
0
def main():
    """
    Run the cli (Do the syspurpose tool thing!!)
    :return: 0
    """

    parser = setup_arg_parser()
    args = parser.parse_args()

    # Syspurpose is not intended to be used in containers for the time being (could change later).
    if in_container():
        print(_("WARNING: Setting syspurpose in containers has no effect."
              "Please run syspurpose on the host.\n"))

    print(_("The 'syspurpose' command is deprecated and will be removed in a future major release."
        " Please use the 'subscription-manager syspurpose' command going forward."), file=sys.stderr)
    try:
        from subscription_manager.identity import Identity
        from subscription_manager.cp_provider import CPProvider
        identity = Identity()
        uuid = identity.uuid
        uep = CPProvider().get_consumer_auth_cp()
    except ImportError:
        uuid = None
        uep = None
        print(_("Warning: Unable to sync system purpose with subscription management server:"
                " subscription_manager module is not available."))

    syspurposestore = SyncedStore(uep=uep, consumer_uuid=uuid, use_valid_fields=True)
    if getattr(args, 'func', None) is not None:
        args.func(args, syspurposestore)
    else:
        parser.print_help()
        return 0

    return 0