def setUp(self): self.dummy = dummies.DummyOpenShift2Adapter() self.cut = backends.ServiceLink(self.dummy) self.src = core_model.Resource('123', occi_ext.APP, []) self.trg = core_model.Resource('abc', occi_ext.COMPONENT, []) self.extras = {'auth_header': {'Authorization': 'Basic foobar'}} self.entity = core_model.Link('', occi_ext.APP, [], self.src, self.trg)
def test_populate_dictionary_with_basic_link_from_DB(self): # Create resources and Link src_id = "124816" tar_id = "112358" src_res = core_model.Resource(src_id, occi_sla.AGREEMENT, None) tar_res = core_model.Resource(tar_id, occi_sla.AGREEMENT, None) lnk_id = "/agreement/load-link-entity-from-DB" lnk = core_model.Link(lnk_id, None, None, src_res, tar_res) links = EntityDictionary(self.api.registry) links._persist_resource(src_id, src_res) links._persist_resource(tar_id, tar_res) links._persist_link(lnk_id, lnk) links.populate_from_db() self.assertEqual(len(links), 3) self.assertTrue(isinstance(links[lnk_id], core_model.Link)) self.assertEqual(links[lnk_id].identifier, lnk_id) # Removing assistive field templates for comparison temp_src = links[lnk_id].source.__dict__ temp_trgt = links[lnk_id].target.__dict__ temp_src.pop('templates') temp_trgt.pop('templates') self.assertEqual(temp_src, src_res.__dict__) self.assertEqual(temp_trgt, tar_res.__dict__)
def test_update_for_sanity(self): """ Simulate a update call! """ res1 = core_model.Resource('/foo/bar', infrastructure.COMPUTE, [self.os_template]) res1.attributes = {'occi.core.id': 'bar'} # case 1 - rebuild VM with different OS res2 = core_model.Resource('/foo/bar', infrastructure.COMPUTE, [self.os_template2]) self.mox.StubOutWithMock(nova_glue.vm, 'rebuild_vm') nova_glue.vm.rebuild_vm(mox.IsA(object), mox.IsA(object), mox.IsA(object)) self.mox.ReplayAll() self.backend.update(res1, res2, self.sec_obj) self.assertIn(self.os_template2, res1.mixins) self.mox.VerifyAll() # case 2 - resize the VM res2 = core_model.Resource('/foo/bar', infrastructure.COMPUTE, [self.res_template2]) self.mox.StubOutWithMock(nova_glue.vm, 'resize_vm') nova_glue.vm.resize_vm(mox.IsA(object), mox.IsA(object), mox.IsA(object)) self.mox.ReplayAll() self.backend.update(res1, res2, self.sec_obj) self.assertIn(self.res_template2, res1.mixins) self.mox.VerifyAll()
def __init__(self): super(OCCIRegistry, self).__init__() self.cache = {} self.adm_net = core_model.Resource('/network/admin', infrastructure.NETWORK, [infrastructure.IPNETWORK]) self.pub_net = core_model.Resource('/network/public', infrastructure.NETWORK, [infrastructure.IPNETWORK]) self._setup_network()
def test_populate_dictionary_with_resource_containing_links(self): # Test entities - creating a resource with two links res_tar_1_id = "/an-id/res_tar_1" res_src_1_id = "/an-id/res_src_1" lnk_1_id = "/an-id/lnk_1_id" res_tar_2_id = "/an-id/res_tar_2" res_src_2_id = "/an-id/res_src_2" lnk_2_id = "/an-id/lnk_2_id" res_m_id = "/an-id/res_m" res_src_1 = core_model.Resource(res_src_1_id, occi_sla.AGREEMENT, None) res_tar_1 = core_model.Resource(res_tar_1_id, occi_sla.AGREEMENT, None) lnk_1 = core_model.Link(lnk_1_id, occi_sla.AGREEMENT_LINK, None, res_src_1, res_tar_1) res_src_2 = core_model.Resource(res_src_2_id, occi_sla.AGREEMENT, None) res_tar_2 = core_model.Resource(res_tar_2_id, occi_sla.AGREEMENT, None) lnk_2 = core_model.Link(lnk_2_id, occi_sla.AGREEMENT_LINK, None, res_src_2, res_tar_2) res_m = core_model.Resource(res_m_id, occi_sla.AGREEMENT, None, [lnk_1, lnk_2]) # Persist all to DB but not dict in memory entities = EntityDictionary(self.api.registry) entities._persist_link(lnk_1_id, lnk_1) entities._persist_link(lnk_2_id, lnk_2) entities._persist_resource(res_src_1_id, res_src_1) entities._persist_resource(res_tar_1_id, res_tar_1) entities._persist_resource(res_src_2_id, res_src_2) entities._persist_resource(res_tar_2_id, res_tar_2) entities._persist_resource(res_m_id, res_m) entities.populate_from_db() self.assertEqual(len(entities), 7) self.assertEqual(len(entities[res_m_id].links), 2) for link in entities[res_m_id].links: if link.identifier == lnk_1_id: # Removing assistive field templates for comparison temp_src = link.source.__dict__ temp_trgt = link.target.__dict__ temp_src.pop('templates') temp_trgt.pop('templates') self.assertEqual(temp_src, res_src_1.__dict__) self.assertEqual(temp_trgt, res_tar_1.__dict__) else: # Removing assistive field templates for comparison temp_src = link.source.__dict__ temp_trgt = link.target.__dict__ temp_src.pop('templates') temp_trgt.pop('templates') self.assertEqual(temp_src, res_src_2.__dict__) self.assertEqual(temp_trgt, res_tar_2.__dict__)
def test_retrieve_dictionary_keys(self): res_id_1 = "/agreement/delete-resource-dict-using-clear_1" res_1 = core_model.Resource(res_id_1, None, None) res_id_2 = "/agreement/delete-resource-dict-using-clear_2" res_2 = core_model.Resource(res_id_2, None, None) resources = EntityDictionary(None) resources[res_id_1] = res_1 resources[res_id_2] = res_2 s1 = set(resources.keys()) s2 = {res_id_1, res_id_2} self.assertEqual(s1, s2)
def test_past_agreement_non_detection(self): """ Check that the temp agreement with pending state is not detected as active agreement. """ gold = core_model.Mixin('', 'gold', [occi_sla.AGREEMENT_TEMPLATE]) compute = core_model.Mixin('', 'compute', [occi_sla.AGREEMENT_TEMPLATE]) availability = core_model.Mixin('', 'availability', [occi_sla.AGREEMENT_TEMPLATE]) mixins = [gold, compute, availability] res = core_model.Resource(self.id, occi_sla.AGREEMENT, mixins) res.attributes = { 'occi.agreement.state': 'accepted', 'occi.agreement.effectiveFrom': '2014-10-02T02:20:26+00:00', 'occi.agreement.effectiveUntil': '2014-11-02T02:20:27+00:00' } northbound_api = api.build() resources = EntityDictionary(northbound_api.registry) resources[self.id] = res resources.registry.populate_resources() active_agreements = resources.registry.get_active_agreement_resources() self.assertEqual(active_agreements.__len__(), 0)
def test_active_agreement_detection(self): """ Check that the temp agreement is detected as active agreement. """ gold = core_model.Mixin('', 'gold', [occi_sla.AGREEMENT_TEMPLATE]) compute = core_model.Mixin('', 'compute', [occi_sla.AGREEMENT_TEMPLATE]) availability = core_model.Mixin('', 'availability', [occi_sla.AGREEMENT_TEMPLATE]) mixins = [gold, compute, availability] res = core_model.Resource(self.id, occi_sla.AGREEMENT, mixins) res.attributes = { 'occi.agreement.state': 'accepted', 'occi.agreement.effectiveFrom': '2014-11-02T02:20:26+00:00', 'occi.agreement.effectiveUntil': '2015-11-02T02:20:27+00:00' } northbound_api = api.build() resources = EntityDictionary(northbound_api.registry) resources[self.id] = res resources.registry.populate_resources() active_agreements = resources.registry.get_active_agreement_resources() if active_agreements.__len__() == 1: self.assertEqual(active_agreements[0].identifier, self.id) else: for agr in active_agreements: self.assertTrue(agr.identifier == self.id)
def test_no_policy_creation(self): """ Check that if no link (aka device id) exist, no policy is created """ gold = core_model.Mixin('', 'gold', [occi_sla.AGREEMENT_TEMPLATE]) compute = core_model.Mixin('', 'compute', [occi_sla.AGREEMENT_TEMPLATE]) availability = core_model.Mixin('', 'availability', [occi_sla.AGREEMENT_TEMPLATE]) mixins = [gold, compute, availability] res = core_model.Resource(self.id, occi_sla.AGREEMENT, mixins) res.attributes = { 'occi.agreement.state': 'accepted', 'occi.agreement.effectiveFrom': '2014-11-02T02:20:26+00:00', 'occi.agreement.effectiveUntil': '2015-11-02T02:20:27+00:00' } northbound_api = api.build() resources = EntityDictionary(northbound_api.registry) resources[self.id] = res resources.registry.populate_resources() myrulesengine = rulesengine.RulesEngine(resources.registry) myrulesengine.active_policies = {} myrulesengine.active_agreements = {} # myrulesengine.registry=registry myrulesengine.start_engine(0) temp_policy_record = DB.policies.find({'agreement_id': self.id}, {'_id': 0}) self.assertEqual(temp_policy_record.count(), 0)
def __create_violation_resource(self, term, metric_name, metric_value, device_id, violation_metrics, remedy, extras): """ Create an OCCI violation instance with the proper attribute values """ LOG.debug( 'Violation instance created for metric {} on device {}'.format( metric_name, device_id)) now_iso = arrow.utcnow().isoformat() id = '/violation/' + str(uuid.uuid4()) res = core_model.Resource(id, occi_violation.VIOLATION, []) res.attributes = { 'occi.violation.timestamp.start': now_iso, 'occi.violation.term': term, 'occi.violation.metrics': json.dumps(violation_metrics), 'occi.violation.device': device_id, 'occi.violation.remedy': remedy } res.provider = extras["security"].items()[0][0] res.customer = extras["customer"] LOG.debug('Inserting resource with ID: {}'.format(id)) myrulesengine = rulesengine.RulesEngine() myrulesengine._registry.resources.__setitem__(id, res) return res
def test_action_for_failure(self): """ Test if correct errors are thrown. """ # wrong action res1 = core_model.Resource('/foo/bar', infrastructure.COMPUTE, []) res1.attributes = {'occi.core.id': 'bar'} self.mox.StubOutWithMock(nova_glue.vm, 'get_vm') nova_glue.vm.get_vm(mox.IsA(object), mox.IsA(object)).AndReturn( { 'vm_state': vm_states.STOPPED }) self.mox.ReplayAll() self.assertRaises(AttributeError, self.backend.action, res1, infrastructure.STOP, {}, self.sec_obj) self.mox.VerifyAll() # missing method! self.mox.UnsetStubs() self.mox.StubOutWithMock(nova_glue.vm, 'get_vm') nova_glue.vm.get_vm(mox.IsA(object), mox.IsA(object)).AndReturn( { 'vm_state': vm_states.ACTIVE }) self.mox.ReplayAll() self.assertRaises(AttributeError, self.backend.action, res1, infrastructure.RESTART, {}, self.sec_obj) self.mox.VerifyAll()
def test_update_contract_duration(self): """ Test that "occi.agreement.effectiveFrom" and "occi.agreement.effectiveUntil" are updated """ # entity comes pre-loaded with from and until times diff to below self.entity.__dict__["provider"] = "DSS" self.entity.attributes["occi.agreement.state"] = "pending" attrs = { "occi.agreement.effectiveFrom": "2014-11-05T14:00:00Z", "occi.agreement.effectiveUntil": "2014-11-12T14:00:00Z", "occi.agreement.state": "pending" } new = core_model.Resource('', occi_sla.AGREEMENT, [occi_sla.AGREEMENT_TEMPLATE]) new.attributes = attrs self.agree_back.update(self.entity, new, self.extras) from_expected = arrow.get(attrs["occi.agreement.effectiveFrom"]) from_actual = arrow.get( self.entity.attributes["occi.agreement.effectiveFrom"]) until_expected = arrow.get(attrs["occi.agreement.effectiveUntil"]) until_actual = arrow.get( self.entity.attributes["occi.agreement.effectiveUntil"]) self.assertEqual(from_expected, from_actual) self.assertEqual(until_expected, until_actual)
def _add_resource(self, entity_record, add_link=True): """ Takes a dictionary representation of a resource and generates a resource object and adds to the dictionary data structure. """ key = entity_record["_id"] del entity_record["_id"] entity = core_model.Resource("", None, None) entity.__dict__ = entity_record entity.kind = self.registry.get_category(entity.kind, None) entity.mixins = self._get_mixins(entity) links = [] if entity.links is not None and add_link: for link_id in entity.links: link_record = self.entities.find_one(link_id) self._add_link(link_record) links.append(self[link_id]) # if links is not []: if len(links) > 0: entity.links = links entity.attributes = self._decode_attributes(entity.attributes) super(EntityDictionary, self).__setitem__(key, entity)
def test_action_for_sanity(self): """ Test actions """ res1 = core_model.Resource('/foo/bar', infrastructure.COMPUTE, []) res1.attributes = {'occi.core.id': 'bar'} # start self.mox.StubOutWithMock(nova_glue.vm, 'start_vm') nova_glue.vm.start_vm(mox.IsA(object), mox.IsA(object)) self.mox.StubOutWithMock(nova_glue.vm, 'get_vm') nova_glue.vm.get_vm(mox.IsA(object), mox.IsA(object)).AndReturn( { 'vm_state': vm_states.STOPPED }) self.mox.ReplayAll() self.backend.action(res1, infrastructure.START, {}, self.sec_obj) self.mox.VerifyAll() # stop self.mox.UnsetStubs() self.mox.StubOutWithMock(nova_glue.vm, 'stop_vm') nova_glue.vm.stop_vm(mox.IsA(object), mox.IsA(object)) self.mox.StubOutWithMock(nova_glue.vm, 'get_vm') nova_glue.vm.get_vm(mox.IsA(object), mox.IsA(object)).AndReturn( { 'vm_state': vm_states.ACTIVE }) self.mox.ReplayAll() self.backend.action(res1, infrastructure.STOP, {}, self.sec_obj) self.mox.VerifyAll() # reboot self.mox.UnsetStubs() self.mox.StubOutWithMock(nova_glue.vm, 'restart_vm') nova_glue.vm.restart_vm(mox.IsA(object), mox.IsA(str), mox.IsA(object)) self.mox.StubOutWithMock(nova_glue.vm, 'get_vm') nova_glue.vm.get_vm(mox.IsA(object), mox.IsA(object)).AndReturn( { 'vm_state': vm_states.ACTIVE }) self.mox.ReplayAll() self.backend.action(res1, infrastructure.RESTART, {'method': 'graceful'}, self.sec_obj) self.mox.VerifyAll() # suspend self.mox.UnsetStubs() self.mox.StubOutWithMock(nova_glue.vm, 'suspend_vm') nova_glue.vm.suspend_vm(mox.IsA(object), mox.IsA(object)) self.mox.StubOutWithMock(nova_glue.vm, 'get_vm') nova_glue.vm.get_vm(mox.IsA(object), mox.IsA(object)).AndReturn( { 'vm_state': vm_states.ACTIVE }) self.mox.ReplayAll() self.backend.action(res1, infrastructure.SUSPEND, {}, self.sec_obj) self.mox.VerifyAll()
def test_add_resource_which_is_already_in_dictionary(self): """ Add a resource with the same ID of a value already in the database """ id = {"_id": "/agreement/4545-4545454-sdasdas-blah"} res_0 = core_model.Resource("11235", None, None) res_1 = core_model.Resource("18512", None, None) resources = EntityDictionary(None) resources[id["_id"]] = res_0 resources[id["_id"]] = res_1 self.assertEqual(self.db.entities.find().count(), 1) self.assertEqual( self.db.entities.find_one(id)["identifier"], res_1.identifier) LOG.info("Overwriting existing entry in dict reflected in DB")
def test_create_for_failure(self): """ Test for proper error handling. """ # msg OS template res = core_model.Resource('/foo/bar', infrastructure.COMPUTE, []) self.assertRaises(AttributeError, self.backend.create, res, self.sec_obj) # provide immutable attr res = core_model.Resource('/foo/bar', infrastructure.COMPUTE, [self.os_template]) res.attributes = {'occi.compute.cores': 2} self.assertRaises(AttributeError, self.backend.create, res, self.sec_obj)
def test_entire_dictionary_using_clear(self): res_id_1 = "/agreement/delete-resource-dict-using-clear_1" res_1 = core_model.Resource(res_id_1, None, None) res_id_2 = "/agreement/delete-resource-dict-using-clear_2" res_2 = core_model.Resource(res_id_2, None, None) resources = EntityDictionary(None) resources[res_id_1] = res_1 resources[res_id_2] = res_2 resources.clear() db_results = self.db.entities.find({}) self.assertEqual(len(resources), 0) self.assertEqual(db_results.count(), 0)
def test_add_resource_with_kind(self): res_id = "/agreement/adding-resource-kind" res = core_model.Resource(res_id, occi_sla.AGREEMENT, None) resources = EntityDictionary(None) resources[res_id] = res result_dict = self.db.entities.find_one(res_id) self.assertEqual(result_dict["kind"], occi_sla.AGREEMENT.location)
def test_update_for_failure(self): """ Test if correct errors are thrown. """ # msg mixin res1 = core_model.Resource('/foo/bar', infrastructure.COMPUTE, []) res1.attributes = {'occi.core.id': 'bar'} res2 = core_model.Resource('/foo/bar', infrastructure.COMPUTE, []) self.assertRaises(AttributeError, self.backend.update, res1, res2, self.sec_obj) res2 = core_model.Resource( '/foo/bar', infrastructure.COMPUTE, [core_model.Category('http://foo.com', 'bar', '', '', '')]) self.assertRaises(AttributeError, self.backend.update, res1, res2, self.sec_obj)
def test_policy_creation(self): """ Check that an active agreement has been detected and a record inserted into the database """ availability = core_model.Mixin('', 'availability', [occi_sla.AGREEMENT_TEMPLATE]) mixins = [availability] res = core_model.Resource(self.id, occi_sla.AGREEMENT, mixins) res.attributes = { 'occi.agreement.state': 'accepted', 'occi.agreement.effectiveFrom': '2014-11-02T02:20:26+00:00', 'occi.agreement.effectiveUntil': '2015-11-02T02:20:27+00:00' } comp_res = core_model.Resource(self.compute_id, infrastructure.COMPUTE, []) comp_res.attributes = {} link_res = core_model.Link(self.link_id, occi_sla.AGREEMENT_LINK, [], res, comp_res) link_res.attributes = {} res.links = [link_res] northbound_api = api.build() resources = EntityDictionary(northbound_api.registry) resources[self.id] = res resources[self.compute_id] = comp_res resources[self.link_id] = link_res resources.registry.populate_resources() myrulesengine = rulesengine.RulesEngine(resources.registry) myrulesengine.active_policies = {} myrulesengine.active_agreements = {} myrulesengine.start_engine(0) temp_policy_record = DB.policies.find({'agreement_id': self.id}, {'_id': 0}) self.assertEqual(temp_policy_record.count(), 1)
def test_add_resource_to_dictionary(self): """ Test that a resource is being added to the DB """ resources = EntityDictionary(None) id = {"_id": "/agreement/4545-4545454-sdasdas"} res = core_model.Resource("4777", None, []) resources[id["_id"]] = res self.assertGreater(self.db.entities.find(id).count(), 0) LOG.info("Added dictionary item to db")
def get_occi_resource(kind, uuid): """ Get the occi instance of a resource :param kind: kind of the resource :param uuid: UUID of the resource :return Resource: OCCI resource """ kind = kind.lower() iden = KIND_TYPE_MAPPING[kind].location + uuid entity = core_model.Resource(iden, KIND_TYPE_MAPPING[kind], []) return entity
def setUp(self): self.agree_back = backends.Agreement() self.extras = {"security": {"DSS": "dss_pass"}, "customer": "larry"} self.entity = core_model.Resource('', occi_sla.AGREEMENT, [occi_sla.AGREEMENT_TEMPLATE]) self.entity.attributes = \ {"occi.agreement.effectiveFrom": "2114-11-02T02:17:26Z", "occi.agreement.effectiveUntil": "2114-11-02T02:17:29Z"} self.template_list = json.load( file("tests/sample_data/template_definition_v2.json")) provider_details.load_providers()
def test_delete_entire_dictionary(self): """ Delete the entire dictionary using "del dict_instance" """ res_0 = core_model.Resource("res_0", None, None) res_1 = core_model.Resource("res_1", None, None) res_2 = core_model.Resource("res_2", None, None) res_3 = core_model.Resource("res_3", None, None) entities = EntityDictionary(None) entities[res_0.identifier] = res_0 entities[res_1.identifier] = res_1 entities[res_2.identifier] = res_2 entities[res_3.identifier] = res_3 del entities self.assertIsNone(self.db.entities.find_one("res_0")) self.assertIsNone(self.db.entities.find_one("res_1")) self.assertIsNone(self.db.entities.find_one("res_2")) self.assertIsNone(self.db.entities.find_one("res_3"))
def test_resource_added_to_DB_reflects_resource_sent(self): """ Test to ensure that the correct data is being sent to the DB """ resources = EntityDictionary(None) id = {"_id": "/agreement/4545-4545454-sdasdas-blah"} res = core_model.Resource("1245", None, []) resources[id["_id"]] = res self.assertEqual(id["_id"], self.db.entities.find_one({}, {"_id": 1})["_id"]) LOG.info("Correct entity added to the db")
def test_correct_resource_links_collection_are_being_added_to_db(self): """ Test if the correct links are being added to the resource record in the DB. note: these are links within resources. Not links as resources """ # Create resources and Link src_res_id = "124816" tar_res_id = "112358" src_res = core_model.Resource(src_res_id, None, None) tar_res = core_model.Resource(tar_res_id, None, None) lnk_id = {"_id": "/agreement/add-link-entity"} lnk = core_model.Link(lnk_id["_id"], None, None, src_res, tar_res) # Load Link resources = EntityDictionary(None) resources[lnk_id["_id"]] = lnk result_dict = self.db.entities.find_one(lnk_id["_id"]) self.assertEqual(result_dict["source"], src_res_id) self.assertEqual(result_dict["target"], tar_res_id) LOG.info("Correct resource links added to the DB")
def test_delete_for_sanity(self): """ Simulate a delete call. """ res = core_model.Resource('/foo/bar', infrastructure.COMPUTE, [self.os_template]) res.attributes = {'occi.core.id': 'bar'} self.mox.StubOutWithMock(nova_glue.vm, 'delete_vm') nova_glue.vm.delete_vm(mox.IsA(object), mox.IsA(object)) self.mox.ReplayAll() self.backend.delete(res, self.sec_obj) self.mox.VerifyAll()
def test_mixins_are_being_added_to_db(self): """ Test that mixins are being added to the DB """ resources = EntityDictionary(None) id = {"_id": "/agreement/45454-ghghg53-454545"} res = core_model.Resource(id["_id"], None, [test_data.epc_mixin, test_data.ran_mixin]) resources[id["_id"]] = res cursor = self.db.entities.find_one(id, {"_id": 0, "mixins": 1}) mixins = cursor["mixins"] self.assertEqual(len(mixins), 2) LOG.info("Correct number of mixins added to DB with resource")
def _register_services(app, auth_head): """ Register available services. """ # No sense in OpS3 # TODO move check one-level up if GLUE.PLATFORM == 'OpenShift2': tmp = GLUE.list_features(auth_head)['data'] for item in tmp: if item['type'] == 'embedded' and 'embedded' in item['tags']: key = '/component/' + item['name'] res = core_model.Resource(key, occi_ext.COMPONENT, [], title=item['description']) app.registry.add_resource(key, res, None)
def _register_keys(app, auth_head): """ Register SSH keys. """ # No sense in OpS3 # TODO move check one-level up if GLUE.PLATFORM == 'OpenShift2': tmp = GLUE.list_keys(auth_head)['data'] for item in tmp: key = '/public_key/' + item['name'] res = core_model.Resource(key, occi_ext.KEY_KIND, []) res.attributes['occi.key.name'] = item['name'] res.attributes['occi.key.content'] = item['content'] res.attributes['occi.core.id'] = item['name'] app.registry.add_resource(key, res, None)