Example #1
0
    def test_update_notes(self):
        """
        Tests updating notes of a consumer
        """

        # Setup
        consumer_id = 'consumer_1'
        name = 'Consumer 1'
        description = 'Test Consumer 1'
        notes = {'note1': 'value1', 'note2': 'value2'}
        self.manager.register(consumer_id, name, description, notes)

        consumers = list(Consumer.get_collection().find())
        self.assertEqual(1, len(consumers))
        consumer = consumers[0]
        self.assertEqual(consumer['notes'], notes)

        # Test
        updated_notes = {'note1': 'new-value1', 'note2': 'new-value2'}
        self.manager.update(consumer_id, delta={'notes': updated_notes})

        # Verify
        consumers = list(Consumer.get_collection().find())
        consumer = consumers[0]
        self.assertEqual(consumer['notes'], updated_notes)
Example #2
0
File: cud.py Project: stpierre/pulp
    def unregister(self, id):
        """
        Unregisters given consumer.

        @param id: identifies the consumer being unregistered
        @type  id: str

        @raises MissingResource: if the given consumer does not exist
        @raises OperationFailed: if any part of the unregister process fails;
                the exception will contain information on which sections failed
        @raises PulpExecutionException: if error during updating database collection
        """

        self.get_consumer(id)
        
        # Remove associate bind
        manager = factory.consumer_bind_manager()
        manager.consumer_deleted(id)
        
        # Remove associated profiles
        manager = factory.consumer_profile_manager()
        manager.consumer_deleted(id)

        # Notify agent
        agent_consumer = factory.consumer_agent_manager()
        agent_consumer.unregistered(id)

        # Database Updates
        try:
            Consumer.get_collection().remove({'id' : id}, safe=True)
        except Exception:
            _LOG.exception('Error updating database collection while removing consumer [%s]' % id)
            raise PulpExecutionException("database-error"), None, sys.exc_info()[2]

        factory.consumer_history_manager().record_event(id, 'consumer_unregistered')
Example #3
0
 def tearDown(self):
     PulpItineraryTests.tearDown(self)
     Consumer.get_collection().remove()
     Repo.get_collection().remove()
     RepoDistributor.get_collection().remove()
     Bind.get_collection().remove()
     mock_plugins.reset()
Example #4
0
 def tearDown(self):
     super(ConsumerTest, self).tearDown()
     Consumer.get_collection().remove(safe=True)
     Repo.get_collection().remove(safe=True)
     RepoDistributor.get_collection().remove(safe=True)
     Bind.get_collection().remove(safe=True)
     mock_plugins.reset()
Example #5
0
 def tearDown(self):
     PulpItineraryTests.tearDown(self)
     Consumer.get_collection().remove()
     Repo.get_collection().remove()
     RepoDistributor.get_collection().remove()
     Bind.get_collection().remove()
     mock_plugins.reset()
Example #6
0
    def test_add_notes(self):
        """
        Tests adding notes to a consumer.
        """

        # Setup
        consumer_id = 'consumer_1'
        name = 'Consumer 1'
        description = 'Test Consumer 1'
        self.manager.register(consumer_id, name, description)

        consumers = list(Consumer.get_collection().find())
        self.assertEqual(1, len(consumers))

        # Test
        consumer = consumers[0]
        self.assertEqual(consumer['notes'], {})

        notes = {'note1': 'value1', 'note2': 'value2'}
        self.manager.update(consumer_id, delta={'notes': notes})

        # Verify
        consumers = list(Consumer.get_collection().find())
        consumer = consumers[0]
        self.assertEqual(consumer['notes'], notes)
Example #7
0
 def tearDown(self):
     super(BindManagerTests, self).tearDown()
     Consumer.get_collection().remove()
     Repo.get_collection().remove()
     RepoDistributor.get_collection().remove()
     Bind.get_collection().remove()
     mock_plugins.reset()
Example #8
0
 def tearDown(self):
     base.PulpServerTests.tearDown(self)
     Consumer.get_collection().remove()
     Repo.get_collection().remove()
     RepoDistributor.get_collection().remove()
     Bind.get_collection().remove()
     mock_plugins.reset()
Example #9
0
 def tearDown(self):
     super(BindManagerTests, self).tearDown()
     Consumer.get_collection().remove()
     Repo.get_collection().remove()
     RepoDistributor.get_collection().remove()
     Bind.get_collection().remove()
     mock_plugins.reset()
Example #10
0
 def tearDown(self):
     base.PulpWebserviceTests.tearDown(self)
     Consumer.get_collection().remove()
     Repo.get_collection().remove()
     RepoDistributor.get_collection().remove()
     Bind.get_collection().remove()
     mock_plugins.reset()
Example #11
0
    def test_update_notes(self):
        """
        Tests updating notes of a consumer
        """

        # Setup
        consumer_id = 'consumer_1'
        name = 'Consumer 1'
        description = 'Test Consumer 1'
        notes = {'note1' : 'value1', 'note2' : 'value2'}
        self.manager.register(consumer_id, name, description, notes)

        consumers = list(Consumer.get_collection().find())
        self.assertEqual(1, len(consumers))
        consumer = consumers[0]
        self.assertEqual(consumer['notes'], notes)

        # Test
        updated_notes = {'note1' : 'new-value1', 'note2' : 'new-value2'}
        self.manager.update(consumer_id, delta={'notes':updated_notes})

        # Verify
        consumers = list(Consumer.get_collection().find())
        consumer = consumers[0]
        self.assertEqual(consumer['notes'], updated_notes)
Example #12
0
    def test_add_notes(self):
        """
        Tests adding notes to a consumer.
        """

        # Setup
        consumer_id = 'consumer_1'
        name = 'Consumer 1'
        description = 'Test Consumer 1'
        self.manager.register(consumer_id, name, description)

        consumers = list(Consumer.get_collection().find())
        self.assertEqual(1, len(consumers))

        # Test
        consumer = consumers[0]
        self.assertEqual(consumer['notes'], {})

        notes = {'note1' : 'value1', 'note2' : 'value2'}
        self.manager.update(consumer_id, delta={'notes':notes})

        # Verify
        consumers = list(Consumer.get_collection().find())
        consumer = consumers[0]
        self.assertEqual(consumer['notes'], notes)
    def test_update_notes(self):
        """
        Tests updating notes of a consumer
        """

        # Setup
        consumer_id = "consumer_1"
        name = "Consumer 1"
        description = "Test Consumer 1"
        notes = {"note1": "value1", "note2": "value2"}
        self.manager.register(consumer_id, name, description, notes)

        consumers = list(Consumer.get_collection().find())
        self.assertEqual(1, len(consumers))
        consumer = consumers[0]
        self.assertEqual(consumer["notes"], notes)

        # Test
        updated_notes = {"note1": "new-value1", "note2": "new-value2"}
        self.manager.update(consumer_id, delta={"notes": updated_notes})

        # Verify
        consumers = list(Consumer.get_collection().find())
        consumer = consumers[0]
        self.assertEqual(consumer["notes"], updated_notes)
    def test_add_notes(self):
        """
        Tests adding notes to a consumer.
        """

        # Setup
        consumer_id = "consumer_1"
        name = "Consumer 1"
        description = "Test Consumer 1"
        self.manager.register(consumer_id, name, description)

        consumers = list(Consumer.get_collection().find())
        self.assertEqual(1, len(consumers))

        # Test
        consumer = consumers[0]
        self.assertEqual(consumer["notes"], {})

        notes = {"note1": "value1", "note2": "value2"}
        self.manager.update(consumer_id, delta={"notes": notes})

        # Verify
        consumers = list(Consumer.get_collection().find())
        consumer = consumers[0]
        self.assertEqual(consumer["notes"], notes)
Example #15
0
 def setUp(self):
     ServerTests.setUp(self)
     self.parentfs = self.tmpdir('parent-')
     self.childfs = self.tmpdir('child-')
     self.alias = (self.parentfs, self.parentfs)
     self.temp_dir = tempfile.mkdtemp()
     Consumer.get_collection().remove()
     Bind.get_collection().remove()
     model.Repository.objects.delete()
     model.Distributor.objects.delete()
     model.Importer.objects.delete()
     RepoContentUnit.get_collection().remove()
     unit_db.clean()
     self.define_plugins()
     plugin_api._create_manager()
     imp_conf = dict(strategy=constants.MIRROR_STRATEGY)
     plugin_api._MANAGER.importers.add_plugin(constants.HTTP_IMPORTER,
                                              NodesHttpImporter, imp_conf)
     plugin_api._MANAGER.distributors.add_plugin(constants.HTTP_DISTRIBUTOR,
                                                 NodesHttpDistributor, {})
     plugin_api._MANAGER.distributors.add_plugin(FAKE_DISTRIBUTOR,
                                                 FakeDistributor,
                                                 FAKE_DISTRIBUTOR_CONFIG)
     plugin_api._MANAGER.profilers.add_plugin(constants.PROFILER_ID,
                                              NodeProfiler, {})
Example #16
0
 def tearDown(self):
     super(ConsumerTest, self).tearDown()
     Consumer.get_collection().remove(safe=True)
     Repo.get_collection().remove(safe=True)
     RepoDistributor.get_collection().remove(safe=True)
     Bind.get_collection().remove(safe=True)
     mock_plugins.reset()
 def tearDown(self):
     super(self.__class__, self).tearDown()
     Consumer.get_collection().remove()
     ConsumerGroup.get_collection().remove()
     Repo.get_collection().remove()
     RepoDistributor.get_collection().remove()
     Bind.get_collection().remove()
     mock_plugins.reset()
Example #18
0
 def setUp(self):
     super(BindManagerTests, self).setUp()
     Consumer.get_collection().remove()
     Repo.get_collection().remove()
     RepoDistributor.get_collection().remove()
     Bind.get_collection().remove()
     plugin_api._create_manager()
     mock_plugins.install()
 def tearDown(self):
     super(self.__class__, self).tearDown()
     Consumer.get_collection().remove()
     ConsumerGroup.get_collection().remove()
     Repo.get_collection().remove()
     RepoDistributor.get_collection().remove()
     Bind.get_collection().remove()
     mock_plugins.reset()
Example #20
0
 def setUp(self):
     base.PulpWebserviceTests.setUp(self)
     Consumer.get_collection().remove()
     Repo.get_collection().remove()
     RepoDistributor.get_collection().remove()
     Bind.get_collection().remove()
     plugin_api._create_manager()
     mock_plugins.install()
Example #21
0
 def tearDown(self):
     super(BindManagerTests, self).tearDown()
     Consumer.get_collection().remove()
     model.Repository.objects.delete()
     model.Distributor.objects.delete()
     Bind.get_collection().remove()
     ConsumerHistoryEvent.get_collection().remove()
     mock_plugins.reset()
Example #22
0
 def setUp(self):
     super(BindManagerTests, self).setUp()
     Consumer.get_collection().remove()
     model.Distributor.objects.delete()
     Bind.get_collection().remove()
     ConsumerHistoryEvent.get_collection().remove()
     plugin_api._create_manager()
     mock_plugins.install()
Example #23
0
 def setUp(self):
     base.PulpWebserviceTests.setUp(self)
     Consumer.get_collection().remove()
     Repo.get_collection().remove()
     RepoDistributor.get_collection().remove()
     Bind.get_collection().remove()
     plugin_api._create_manager()
     mock_plugins.install()
Example #24
0
 def setUp(self):
     super(ConsumerTest, self).setUp()
     Consumer.get_collection().remove(safe=True)
     Repo.get_collection().remove(safe=True)
     RepoDistributor.get_collection().remove(safe=True)
     Bind.get_collection().remove(safe=True)
     plugin_api._create_manager()
     mock_plugins.install()
Example #25
0
 def tearDown(self):
     PulpRPMTests.tearDown(self)
     Consumer.get_collection().remove()
     Repo.get_collection().remove()
     RepoContentUnit.get_collection().remove()
     RepoDistributor.get_collection().remove()
     database.clean()
     plugins.finalize()
 def setUp(self):
     super(self.__class__, self).setUp()
     Consumer.get_collection().remove()
     ConsumerGroup.get_collection().remove()
     Repo.get_collection().remove()
     RepoDistributor.get_collection().remove()
     Bind.get_collection().remove()
     plugin_api._create_manager()
     mock_plugins.install()
Example #27
0
 def setUp(self):
     PulpItineraryTests.setUp(self)
     Consumer.get_collection().remove()
     Repo.get_collection().remove()
     RepoDistributor.get_collection().remove()
     Bind.get_collection().remove()
     plugin_api._create_manager()
     mock_plugins.install()
     mock_agent.install()
 def setUp(self):
     super(self.__class__, self).setUp()
     Consumer.get_collection().remove()
     ConsumerGroup.get_collection().remove()
     Repo.get_collection().remove()
     RepoDistributor.get_collection().remove()
     Bind.get_collection().remove()
     plugin_api._create_manager()
     mock_plugins.install()
Example #29
0
 def setUp(self):
     PulpItineraryTests.setUp(self)
     Consumer.get_collection().remove()
     Repo.get_collection().remove()
     RepoDistributor.get_collection().remove()
     Bind.get_collection().remove()
     plugin_api._create_manager()
     mock_plugins.install()
     mock_agent.install()
Example #30
0
File: cud.py Project: zjhuntin/pulp
    def register(consumer_id,
                 display_name=None,
                 description=None,
                 notes=None,
                 capabilities=None,
                 rsa_pub=None):
        """
        Registers a new Consumer

        :param consumer_id: unique identifier for the consumer
        :type  consumer_id: str
        :param rsa_pub: The consumer public key used for message authentication.
        :type rsa_pub: str
        :param display_name: user-friendly name for the consumer
        :type  display_name: str
        :param description:  user-friendly text describing the consumer
        :type  description: str
        :param notes: key-value pairs to pragmatically tag the consumer
        :type  notes: dict
        :param capabilities: operations supported on the consumer
        :type  capabilities: dict
        :raises DuplicateResource: if there is already a consumer or a used with the requested ID
        :raises InvalidValue: if any of the fields is unacceptable
        :return: A tuple of: (consumer, certificate)
        :rtype: tuple
        """
        if not is_consumer_id_valid(consumer_id):
            raise InvalidValue(['id'])

        collection = Consumer.get_collection()

        consumer = collection.find_one({'id': consumer_id})
        if consumer is not None:
            raise DuplicateResource(consumer_id)

        if notes is not None and not isinstance(notes, dict):
            raise InvalidValue(['notes'])

        if capabilities is not None and not isinstance(capabilities, dict):
            raise InvalidValue(['capabilities'])

        # Use the ID for the display name if one was not specified
        display_name = display_name or consumer_id

        # Creation
        consumer = Consumer(consumer_id, display_name, description, notes, capabilities, rsa_pub)
        _id = collection.save(consumer, safe=True)

        # Generate certificate
        cert_gen_manager = factory.cert_generation_manager()
        expiration_date = config.config.getint('security', 'consumer_cert_expiration')
        key, certificate = cert_gen_manager.make_cert(consumer_id, expiration_date, uid=str(_id))

        factory.consumer_history_manager().record_event(consumer_id, 'consumer_registered')

        return consumer, Bundle.join(key, certificate)
 def setUp(self):
     base.PulpServerTests.setUp(self)
     Consumer.get_collection().remove()
     UnitProfile.get_collection().remove()
     plugins._create_manager()
     mock_plugins.install()
     profiler, cfg = plugins.get_profiler_by_type('rpm')
     profiler.units_applicable = \
         Mock(side_effect=lambda i,r,t,u,c,x:
              [ApplicabilityReport('mysummary', 'mydetails')])
Example #32
0
 def tearDown(self):
     super(BaseProfilerConduitTests, self).tearDown()
     Consumer.get_collection().remove()
     Repo.get_collection().remove()
     RepoDistributor.get_collection().remove()
     Bind.get_collection().remove()
     RepoContentUnit.get_collection().remove()
     UnitProfile.get_collection().remove()
     typedb.clean()
     factory.reset()
Example #33
0
 def setUp(self):
     super(BaseProfilerConduitTests, self).setUp()
     Consumer.get_collection().remove()
     RepoDistributor.get_collection().remove()
     Bind.get_collection().remove()
     RepoContentUnit.get_collection().remove()
     UnitProfile.get_collection().remove()
     plugin_api._create_manager()
     typedb.update_database([self.TYPE_1_DEF, self.TYPE_2_DEF])
     mock_plugins.install()
Example #34
0
 def setUp(self):
     base.PulpServerTests.setUp(self)
     Consumer.get_collection().remove()
     UnitProfile.get_collection().remove()
     plugins._create_manager()
     mock_plugins.install()
     profiler, cfg = plugins.get_profiler_by_type('rpm')
     profiler.find_applicable_units = \
         Mock(side_effect=lambda i,r,t,u,c,x:
              [ApplicabilityReport('mysummary', 'mydetails')])
Example #35
0
 def setUp(self):
     super(BaseProfilerConduitTests, self).setUp()
     Consumer.get_collection().remove()
     RepoDistributor.get_collection().remove()
     Bind.get_collection().remove()
     RepoContentUnit.get_collection().remove()
     UnitProfile.get_collection().remove()
     plugin_api._create_manager()
     typedb.update_database([self.TYPE_1_DEF, self.TYPE_2_DEF])
     mock_plugins.install()
Example #36
0
 def setUp(self):
     base.PulpWebserviceTests.setUp(self)
     Consumer.get_collection().remove()
     UnitProfile.get_collection().remove()
     plugin_api._create_manager()
     mock_plugins.install()
     profiler = plugin_api.get_profiler_by_type('errata')[0]
     profiler.unit_applicable = \
         mock.Mock(side_effect=lambda i,u,c,x:
             ApplicabilityReport(u, True, self.SUMMARY, self.DETAILS))
Example #37
0
 def tearDown(self):
     super(BaseProfilerConduitTests, self).tearDown()
     Consumer.get_collection().remove()
     Repo.get_collection().remove()
     RepoDistributor.get_collection().remove()
     Bind.get_collection().remove()
     RepoContentUnit.get_collection().remove()
     UnitProfile.get_collection().remove()
     typedb.clean()
     factory.reset()
Example #38
0
 def add_schedule(cls, operation, consumer_id, schedule_id):
     """
     Adds a install schedule for a repo to the importer.
     @param repo_id:
     @param schedule_id:
     @return:
     """
     cls._validate_scheduled_operation(operation)
     Consumer.get_collection().update(
         {'_id': consumer_id},
         {'$addToSet': {'schedules.%s' % operation: schedule_id}})
Example #39
0
 def remove_schedule(cls, operation, consumer_id, schedule_id):
     """
     Removes a install schedule for a repo from the importer.
     @param repo_id:
     @param schedule_id:
     @return:
     """
     cls._validate_scheduled_operation(operation)
     Consumer.get_collection().update(
         {'_id': consumer_id},
         {'$pull': {'schedules.%s' % operation: schedule_id}})
Example #40
0
 def remove_schedule(cls, operation, consumer_id, schedule_id):
     """
     Removes a install schedule for a repo from the importer.
     @param repo_id:
     @param schedule_id:
     @return:
     """
     cls._validate_scheduled_operation(operation)
     Consumer.get_collection().update(
         {'_id': consumer_id},
         {'$pull': {'schedules.%s' % operation: schedule_id}})
Example #41
0
 def tearDown(self):
     super(BaseProfilerConduitTests, self).tearDown()
     Consumer.get_collection().remove()
     model.Repository.objects.delete()
     model.Distributor.objects.delete()
     Bind.get_collection().remove()
     RepoContentUnit.get_collection().remove()
     UnitProfile.get_collection().remove()
     typedb.clean()
     factory.reset()
     mock_plugins.reset()
Example #42
0
 def tearDown(self):
     ServerTests.tearDown(self)
     shutil.rmtree(self.parentfs)
     shutil.rmtree(self.childfs)
     Consumer.get_collection().remove()
     Bind.get_collection().remove()
     model.Repository.objects.delete()
     model.Distributor.objects.delete()
     model.Importer.objects.delete()
     RepoContentUnit.get_collection().remove()
     unit_db.clean()
Example #43
0
 def tearDown(self):
     WebTest.tearDown(self)
     shutil.rmtree(self.parentfs)
     shutil.rmtree(self.childfs)
     Consumer.get_collection().remove()
     Bind.get_collection().remove()
     Repo.get_collection().remove()
     RepoDistributor.get_collection().remove()
     RepoImporter.get_collection().remove()
     RepoContentUnit.get_collection().remove()
     unit_db.clean()
Example #44
0
 def tearDown(self):
     WebTest.tearDown(self)
     shutil.rmtree(self.parentfs)
     shutil.rmtree(self.childfs)
     Consumer.get_collection().remove()
     Bind.get_collection().remove()
     Repo.get_collection().remove()
     RepoDistributor.get_collection().remove()
     RepoImporter.get_collection().remove()
     RepoContentUnit.get_collection().remove()
     unit_db.clean()
Example #45
0
 def add_schedule(cls, operation, consumer_id, schedule_id):
     """
     Adds a install schedule for a repo to the importer.
     @param repo_id:
     @param schedule_id:
     @return:
     """
     cls._validate_scheduled_operation(operation)
     Consumer.get_collection().update(
         {'_id': consumer_id},
         {'$addToSet': {'schedules.%s' % operation: schedule_id}})
Example #46
0
 def tearDown(self):
     ServerTests.tearDown(self)
     shutil.rmtree(self.parentfs)
     shutil.rmtree(self.childfs)
     Consumer.get_collection().remove()
     Bind.get_collection().remove()
     model.Repository.objects.delete()
     model.Distributor.objects.delete()
     model.Importer.objects.delete()
     RepoContentUnit.get_collection().remove()
     unit_db.clean()
Example #47
0
 def tearDown(self):
     super(BaseProfilerConduitTests, self).tearDown()
     Consumer.get_collection().remove()
     model.Repository.objects.delete()
     model.Distributor.objects.delete()
     Bind.get_collection().remove()
     RepoContentUnit.get_collection().remove()
     UnitProfile.get_collection().remove()
     typedb.clean()
     factory.reset()
     mock_plugins.reset()
Example #48
0
    def unregister(consumer_id):
        """
        Unregisters given consumer.

        :param  consumer_id:            identifies the consumer being unregistered
        :type   consumer_id:            str
        :raises MissingResource:        if the given consumer does not exist
        :raises OperationFailed:        if any part of the unregister process fails; the exception
                                        will contain information on which sections failed
        :raises PulpExecutionException: if error during updating database collection
        """

        ConsumerManager.get_consumer(consumer_id)

        # Remove associate bind
        manager = factory.consumer_bind_manager()
        manager.consumer_deleted(consumer_id)

        # Remove associated profiles
        manager = factory.consumer_profile_manager()
        manager.consumer_deleted(consumer_id)

        # Notify agent
        agent_consumer = factory.consumer_agent_manager()
        agent_consumer.unregistered(consumer_id)

        # remove from consumer groups
        group_manager = factory.consumer_group_manager()
        group_manager.remove_consumer_from_groups(consumer_id)

        # delete any scheduled unit installs
        schedule_manager = factory.consumer_schedule_manager()
        for schedule in schedule_manager.get(consumer_id):
            # using "delete" on utils skips validation that the consumer exists.
            schedule_utils.delete(schedule.id)

        # Database Updates
        try:
            Consumer.get_collection().remove({'id': consumer_id}, safe=True)
        except Exception:
            _logger.exception(
                'Error updating database collection while removing consumer [%s]'
                % consumer_id)
            raise PulpExecutionException(
                "database-error"), None, sys.exc_info()[2]

        # remove the consumer from any groups it was a member of
        group_manager = factory.consumer_group_manager()
        group_manager.remove_consumer_from_groups(consumer_id)

        factory.consumer_history_manager().record_event(
            consumer_id, 'consumer_unregistered')
Example #49
0
File: cud.py Project: bartwo/pulp
    def unregister(self, consumer_id):
        """
        Unregisters given consumer.

        @param consumer_id: identifies the consumer being unregistered
        @type  consumer_id: str

        @raises MissingResource: if the given consumer does not exist
        @raises OperationFailed: if any part of the unregister process fails;
                the exception will contain information on which sections failed
        @raises PulpExecutionException: if error during updating database collection
        """

        self.get_consumer(consumer_id)

        # Remove associate bind
        manager = factory.consumer_bind_manager()
        manager.consumer_deleted(consumer_id)

        # Remove associated profiles
        manager = factory.consumer_profile_manager()
        manager.consumer_deleted(consumer_id)

        # Notify agent
        agent_consumer = factory.consumer_agent_manager()
        agent_consumer.unregistered(consumer_id)

        # remove from consumer groups
        group_manager = factory.consumer_group_manager()
        group_manager.remove_consumer_from_groups(consumer_id)

        # delete any scheduled unit installs
        schedule_manager = factory.schedule_manager()
        schedule_manager.delete_all_unit_install_schedules(consumer_id)
        schedule_manager.delete_all_unit_update_schedules(consumer_id)
        schedule_manager.delete_all_unit_uninstall_schedules(consumer_id)

        # Database Updates
        try:
            Consumer.get_collection().remove({'id' : consumer_id}, safe=True)
        except Exception:
            _LOG.exception('Error updating database collection while removing '
                'consumer [%s]' % consumer_id)
            raise PulpExecutionException("database-error"), None, sys.exc_info()[2]

        # remove the consumer from any groups it was a member of
        group_manager = factory.consumer_group_manager()
        group_manager.remove_consumer_from_groups(consumer_id)

        factory.consumer_history_manager().record_event(consumer_id, 'consumer_unregistered')
Example #50
0
    def register(self, id, display_name=None, description=None, notes=None, capabilities=None):
        """
        Registers a new Consumer

        @param id: unique identifier for the consumer
        @type  id: str

        @param display_name: user-friendly name for the consumer
        @type  display_name: str

        @param description: user-friendly text describing the consumer
        @type  description: str

        @param notes: key-value pairs to programmatically tag the consumer
        @type  notes: dict

        @param capabilities: operations permitted on the consumer
        @type capabilities: dict

        @raises DuplicateResource: if there is already a consumer or a used with the requested ID
        @raises InvalidValue: if any of the fields is unacceptable
        """
        if not is_consumer_id_valid(id):
            raise InvalidValue(['id'])
        
        existing_consumer = Consumer.get_collection().find_one({'id' : id})
        if existing_consumer is not None:
            raise DuplicateResource(id)
            
        if notes is not None and not isinstance(notes, dict):
            raise InvalidValue(['notes'])

        if capabilities is not None and not isinstance(capabilities, dict):
            raise InvalidValue(['capabilities'])

        # Use the ID for the display name if one was not specified
        display_name = display_name or id

        # Generate certificate
        cert_gen_manager = factory.cert_generation_manager()
        expiration_date = config.config.getint('security', 'consumer_cert_expiration')
        key, crt = cert_gen_manager.make_cert(id, expiration_date)

        # Creation
        create_me = Consumer(id, display_name, description, notes, capabilities, certificate=crt.strip())
        Consumer.get_collection().save(create_me, safe=True)

        factory.consumer_history_manager().record_event(id, 'consumer_registered')
        create_me.certificate = Bundle.join(key, crt)
        return create_me
Example #51
0
    def unregister(consumer_id):
        """
        Unregisters given consumer.

        :param  consumer_id:            identifies the consumer being unregistered
        :type   consumer_id:            str
        :raises MissingResource:        if the given consumer does not exist
        :raises OperationFailed:        if any part of the unregister process fails; the exception
                                        will contain information on which sections failed
        :raises PulpExecutionException: if error during updating database collection
        """

        ConsumerManager.get_consumer(consumer_id)

        # Remove associate bind
        manager = factory.consumer_bind_manager()
        manager.consumer_deleted(consumer_id)

        # Remove associated profiles
        manager = factory.consumer_profile_manager()
        manager.consumer_deleted(consumer_id)

        # Notify agent
        agent_consumer = factory.consumer_agent_manager()
        agent_consumer.unregister(consumer_id)

        # remove from consumer groups
        group_manager = factory.consumer_group_manager()
        group_manager.remove_consumer_from_groups(consumer_id)

        # delete any scheduled unit installs
        schedule_manager = factory.consumer_schedule_manager()
        for schedule in schedule_manager.get(consumer_id):
            # using "delete" on utils skips validation that the consumer exists.
            schedule_utils.delete(schedule.id)

        # Database Updates
        try:
            Consumer.get_collection().remove({'id': consumer_id})
        except Exception:
            _logger.exception(
                'Error updating database collection while removing consumer [%s]' % consumer_id)
            raise PulpExecutionException("database-error"), None, sys.exc_info()[2]

        # remove the consumer from any groups it was a member of
        group_manager = factory.consumer_group_manager()
        group_manager.remove_consumer_from_groups(consumer_id)

        factory.consumer_history_manager().record_event(consumer_id, 'consumer_unregistered')
Example #52
0
    def test_create(self):
        """
        Tests creating a consumer with valid data is successful.
        """

        # Setup
        consumer_id = 'consumer_1'
        name = 'Consumer 1'
        description = 'Test Consumer 1'
        notes = {'note1': 'value1'}

        # Test
        created = self.manager.register(consumer_id, name, description, notes)
        print created

        # Verify
        consumers = list(Consumer.get_collection().find())
        self.assertEqual(1, len(consumers))

        consumer = consumers[0]
        self.assertEqual(consumer_id, consumer['id'])
        self.assertEqual(name, consumer['display_name'])
        self.assertEqual(description, consumer['description'])
        self.assertEqual(notes, consumer['notes'])

        self.assertEqual(consumer_id, created['id'])
        self.assertEqual(name, created['display_name'])
        self.assertEqual(description, created['description'])
        self.assertEqual(notes, created['notes'])
Example #53
0
    def create_schedule(cls,
                        action,
                        consumer_id,
                        units,
                        options,
                        schedule,
                        failure_threshold=None,
                        enabled=True):
        """
        Creates a new schedule for a consumer action

        :param action:          a unique identified for an action, one of
                                UNIT_INSTALL_ACTION, UNIT_UPDATE_ACTION,
                                UNIT_UNINSTALL_ACTION
        :type  action:          basestring
        :param consumer_id:     a unique ID for a consumer
        :type  consumer_id:     basestring
        :param units:           A list of content units to be installed, each as
                                a dict in the form:
                                    { type_id:<str>, unit_key:<dict> }
        :type  units:           list
        :param options:         a dictionary that will be passed to the
                                action-appropriate task as the "options"
                                argument
        :type  options:         dict
        :param schedule:        ISO8601 string representation of the schedule
        :type  schedule:        basestring
        :param failure_threshold:   optional positive integer indicating how
                                many times this schedule's execution can fail
                                before being automatically disabled.
        :type  failure_threshold:   int or NoneType
        :param enabled:         boolean indicating if this schedule should
                                be actively loaded and executed by the
                                scheduler. Defaults to True.
        :type  enabled:         bool
        :return:    instance of the new ScheduledCal
        :rtype:     pulp.server.db.models.dispatch.ScheduledCall

        :raise:     pulp.server.exceptions.MissingValue
        """
        cls._validate_consumer(consumer_id)
        utils.validate_initial_schedule_options(schedule, failure_threshold,
                                                enabled)
        if not units:
            raise MissingValue(['units'])

        task = ACTIONS_TO_TASKS[action]
        args = [consumer_id]
        kwargs = {'units': units, 'options': options}
        resource = Consumer.build_resource_tag(consumer_id)

        schedule = ScheduledCall(schedule,
                                 task,
                                 args=args,
                                 kwargs=kwargs,
                                 resource=resource,
                                 failure_threshold=failure_threshold,
                                 enabled=enabled)
        schedule.save()
        return schedule
Example #54
0
    def record_event(self, consumer_id, event_type, event_details=None):
        """
        @ivar consumer_id: identifies the consumer
        @type id: str

        @param type: event type
        @type type: str

        @param details: event details
        @type details: dict

        @raises MissingResource: if the given consumer does not exist
        @raises InvalidValue: if any of the fields is unacceptable
        """
        # Check that consumer exists for all except registration event
        existing_consumer = Consumer.get_collection().find_one(
            {'id': consumer_id})
        if not existing_consumer and event_type != TYPE_CONSUMER_UNREGISTERED:
            raise MissingResource(consumer=consumer_id)

        invalid_values = []
        if event_type not in TYPES:
            invalid_values.append('event_type')

        if event_details is not None and not isinstance(event_details, dict):
            invalid_values.append('event_details')

        if invalid_values:
            raise InvalidValue(invalid_values)

        event = ConsumerHistoryEvent(consumer_id, self._originator(),
                                     event_type, event_details)
        ConsumerHistoryEvent.get_collection().save(event)
Example #55
0
 def associate(group_id, criteria):
     """
     Associate a set of consumers, that match the passed in criteria, to a consumer group.
     @param group_id: unique id of the group to associate consumers to
     @type  group_id: str
     @param criteria: Criteria instance representing the set of consumers to associate
     @type  criteria: L{pulp.server.db.model.criteria.Criteria}
     """
     group_collection = validate_existing_consumer_group(group_id)
     consumer_collection = Consumer.get_collection()
     cursor = consumer_collection.query(criteria)
     consumer_ids = [r['id'] for r in cursor]
     if consumer_ids:
         group_collection.update(
             {'id': group_id},
             {'$addToSet': {
                 'consumer_ids': {
                     '$each': consumer_ids
                 }
             }},
             safe=True)
     details = {'group_id': group_id}
     for consumer_id in consumer_ids:
         manager_factory.consumer_history_manager().record_event(
             consumer_id, 'added_to_group', details)
Example #56
0
    def test_update_consumer(self):
        """
        Tests the case of successfully updating a consumer.
        """

        # Setup
        self.manager.register('update-me',
                              display_name='display_name_1',
                              description='description_1',
                              notes={'a': 'a'})

        delta = {
            'display_name': 'display_name_2',
            'description': 'description_2',
            'disregard': 'ignored',
        }

        # Test
        updated = self.manager.update('update-me', delta)

        # Verify
        consumer = Consumer.get_collection().find_one({'id': 'update-me'})
        self.assertEqual(consumer['display_name'], delta['display_name'])
        self.assertEqual(consumer['description'], delta['description'])

        self.assertEqual(updated['display_name'], delta['display_name'])
        self.assertEqual(updated['description'], delta['description'])
Example #57
0
    def record_event(self, consumer_id, event_type, event_details=None):
        """
        @ivar consumer_id: identifies the consumer
        @type id: str

        @param type: event type
        @type type: str

        @param details: event details
        @type details: dict

        @raises MissingResource: if the given consumer does not exist
        @raises InvalidValue: if any of the fields is unacceptable
        """
        # Check that consumer exists for all except registration event
        existing_consumer = Consumer.get_collection().find_one({'id': consumer_id})
        if not existing_consumer and event_type != TYPE_CONSUMER_UNREGISTERED:
            raise MissingResource(consumer=consumer_id)

        invalid_values = []
        if event_type not in TYPES:
            invalid_values.append('event_type')

        if event_details is not None and not isinstance(event_details, dict):
            invalid_values.append('event_details')

        if invalid_values:
            raise InvalidValue(invalid_values)

        event = ConsumerHistoryEvent(consumer_id, self._originator(), event_type, event_details)
        ConsumerHistoryEvent.get_collection().save(event)
Example #58
0
    def test_with_action(self, mock_get_by_resource):
        mock_get_by_resource.return_value = self.calls

        result = self.manager.get('consumer1', UNIT_INSTALL_ACTION)

        mock_get_by_resource.assert_called_once_with(
            Consumer.build_resource_tag('consumer1'))
        self.assertEqual(list(result), self.calls[:1])