def setUp(self): self.registry.set_hostname('http://127.0.0.1') self.app = Application([(r"(.*)/", CollectionWrapper)]) self.registry.set_renderer('text/plain', TextPlainRendering(self.registry)) self.registry.set_renderer('text/occi', TextOcciRendering(self.registry)) self.registry.set_renderer('text/uri-list', TextUriListRendering(self.registry)) self.mixin = Mixin('foo', 'mystuff') self.compute = Resource('/compute/1', COMPUTE, []) self.compute.attributes = {'foo2': 'bar2'} self.network = Resource('/network/1', NETWORK, [IPNETWORK]) self.network_interface = Link('/network/interface/1', NETWORKINTERFACE, [IPNETWORKINTERFACE], self.compute, self.network) self.registry.set_backend(COMPUTE, SimpleComputeBackend()) self.registry.set_backend(NETWORK, KindBackend()) self.registry.set_backend(self.mixin, MixinBackend()) self.registry.set_backend(START, SimpleComputeBackend()) self.registry.add_resource(self.compute.identifier, self.compute) self.registry.add_resource(self.network.identifier, self.network) self.registry.add_resource(self.network_interface.identifier, self.network_interface)
def test_deploy_so_sanity(self): # initialization kind = Kind('http://schemas.mobile-cloud-networking.eu/occi/sm#', 'myservice', title='Test Service', attributes={'mcn.test.attribute1': 'immutable'}, related=[Resource.kind], actions=[]) entity = Resource('my-id', kind, None) entity.extras = {} host = 'test.mcn.org:8888/myservice' entity.extras['host'] = host extras = {} extras['token'] = 'test_token' extras['tenant_name'] = 'test_tenantname' body_content = '123456789' httpretty.register_uri(httpretty.POST, 'http://' + host + '/action=deploy', status=200, body=body_content, content_type='text/occi') # Test method self.som._SOManager__deploy_so(entity, extras) # Asserts self.assertEqual(entity.extras['stack_id'], body_content)
def test_init_so(self): # initialization kind = Kind('http://schemas.mobile-cloud-networking.eu/occi/sm#', 'myservice', title='Test Service', attributes={'mcn.test.attribute1': 'immutable'}, related=[Resource.kind], actions=[]) entity = Resource('my-id', kind, None) entity.extras = {} host = 'localhost:8888/myservice' entity.extras['host'] = host extras = {} extras['token'] = 'test_token' extras['tenant_name'] = 'test_tenantname' httpretty.register_uri(httpretty.POST, 'http://' + host + '/action=init', status=200, content_type='text/occi') # Test method self.som._SOManager__init_so(entity, extras) # Asserts sent_headers = httpretty.last_request().headers self.assertEqual(sent_headers['X-Auth-Token'], 'test_token') self.assertEqual(sent_headers['X-Tenant-Name'], 'test_tenantname')
def test_deploy_so_failure(self): # Initialization kind = Kind('http://schemas.mobile-cloud-networking.eu/occi/sm#', 'myservice', title='Test Service', attributes={'mcn.test.attribute1': 'immutable'}, related=[Resource.kind], actions=[]) entity = Resource('my-id', kind, None) entity.extras = {} host = 'test.mcn.org:8888/myservice' entity.extras['host'] = host extras = {} extras['token'] = 'test_token' extras['tenant_name'] = 'test_tenantname' body_content = 'Please initialize SO with token and tenant first.' httpretty.register_uri(httpretty.POST, 'http://' + host + '/action=deploy', status=200, body=body_content, content_type='text/occi') # Test method and Assert exception self.assertRaises(Exception, self.som._SOManager__deploy_so, (entity, extras))
def __get_occi_links(self, svcs_deps): links = [] for svcs_dep in svcs_deps: source = Resource(svcs_dep['location'], Resource.kind, []) for _, v in svcs_dep['deps'].iteritems(): target = Resource(v[0], Resource.kind, []) links.append(Link(str(uuid.uuid4()), Link.kind, [], source, target)) return links
def test_replace_collection_for_sanity(self): ''' Check if the replace functionalities are implemented correctly. ''' res1 = Resource('/foo/target', self.kind, [self.mixin], []) res2 = Resource('/foo/target', self.kind, [], []) workflow.replace_collection(self.mixin, [res1], [res2], self.registry) self.assertTrue(self.mixin not in res1.mixins) self.assertTrue(self.mixin in res2.mixins)
def test_resource_for_failure(self): """ Check if the correct exceptions are thrown. """ # no kind available... res = Resource("/foo/1", self.mixin, [], links=[]) headers, body = self.rendering.from_entity(res) self.assertRaises(AttributeError, self.rendering.to_entity, headers, body, None) # kind does not relate to link or resource... res.kind = self.invalid_kind headers, body = self.rendering.from_entity(res) self.assertRaises(AttributeError, self.rendering.to_entity, headers, body, None)
def test_delete_from_collection_for_sanity(self): ''' Check if the delete functionalities are implemented correctly. ''' res1 = Resource('/foo/1', self.kind, [self.mixin], []) res2 = Resource('/foo/2', self.kind, [self.mixin], []) self.registry.add_resource('/foo/1', res1) self.registry.add_resource('/foo/2', res2) workflow.delete_from_collection(self.mixin, [res2], self.registry) self.assertTrue(self.mixin not in res2.mixins) self.assertTrue(self.mixin in res1.mixins)
def setUp(self): action = Action('http://example.com/foo#', 'action') self.kind = Kind('http://example.com/foo#', 'bar', 'http://schemeas.ogf.org/occi/core#', [action], 'Some bla bla', {'foo': 'required', 'foo2': 'immutable', 'bar': ''}, '/foo/') mixin = Mixin('http://example.com/foo#', 'mixin') action = Action('http://example.com/foo#', 'action') self.target = Resource('/foo/target', self.kind, [], []) self.source = Resource('/foo/src', self.kind, [mixin], []) self.link = Link('/link/foo', self.kind, [], self.source, self.target) self.source.links = [self.link] self.source.actions = [action]
def setUp(self): self.test_kind = Kind('http://example.com#', 'test') self.link_kind = Kind('http://example.com#link', 'link') mixins = [] self.action = Action('http://example.com#', 'action') self.src_entity = Resource(None, self.test_kind, mixins, []) self.trg_entity = Resource('/foo/trg', self.test_kind, mixins, []) self.link1 = Link('/link/1', self.link_kind, [], self.src_entity, self.trg_entity) self.src_entity.links = [self.link1] self.registry.add_resource(self.trg_entity.identifier, self.trg_entity) self.registry.set_backend(self.test_kind, KindBackend()) self.registry.set_backend(self.link_kind, KindBackend()) self.registry.set_backend(self.action, ActionBackend())
def test_resource_for_failure(self): ''' Check if the correct exceptions are thrown. ''' # no kind available... res = Resource('/foo/1', self.mixin, [], links=[]) headers, body = self.rendering.from_entity(res) self.assertRaises(AttributeError, self.rendering.to_entity, headers, body, None) # kind does not relate to link or resource... res.kind = self.invalid_kind headers, body = self.rendering.from_entity(res) self.assertRaises(AttributeError, self.rendering.to_entity, headers, body, None)
def test_create_app(self): # Initialization # Tentative Kind/Resource Creation kind = Kind('http://schemas.mobile-cloud-networking.eu/occi/sm#', 'myservice', title='Test Service', attributes={'mcn.test.attribute1': 'immutable'}, related=[Resource.kind], actions=[]) entity = Resource('my-id', kind, None) httpretty.register_uri( httpretty.POST, 'http://*****:*****@git.mcn.eu:myserv.git"' }) # Test method repo_uri = self.som._SOManager__create_app(entity, None) # Asserts self.assertEqual(repo_uri, '[email protected]:myserv.git')
def setUp(self): self.app = Application([(r"(.*)", ResourceWrapper)]) self.registry.set_renderer('text/plain', TextPlainRendering(self.registry)) self.registry.set_renderer('text/occi', TextOcciRendering(self.registry)) self.registry.set_backend(COMPUTE, SimpleComputeBackend()) self.registry.set_backend(NETWORK, KindBackend()) self.registry.set_backend(NETWORKINTERFACE, KindBackend()) self.registry.set_backend(START, SimpleComputeBackend()) self.compute = Resource('/compute/1', COMPUTE, []) self.network = Resource('/network/1', NETWORK, [IPNETWORK]) self.registry.add_resource('/compute/1', self.compute) self.registry.add_resource('/network/1', self.network)
def test_from_entities_for_sanity(self): ''' Test uri listings... ''' res = Resource('/foo/123', None, []) entities = [res] heads, body = self.rendering.from_entities(entities, 'foo') self.assertTrue(heads == {}) self.assertTrue(res.identifier in body)
def run(self): # example request to the SO # curl -v -X GET http://localhost:8051/orchestrator/default \ # -H 'X-Auth-Token: '$KID \ # -H 'X-Tenant-Name: '$TENANT if self.entity.attributes['mcn.service.state'] in ['activate', 'deploy', 'provision', 'update']: heads = { 'Content-Type': 'text/occi', 'Accept': 'text/occi', 'X-Auth-Token': self.extras['token'], 'X-Tenant-Name': self.extras['tenant_name']} LOG.info('Getting state of service orchestrator with: ' + self.host + '/orchestrator/default') LOG.info('Sending headers: ' + heads.__repr__()) r = http_retriable_request('GET', HTTP + self.host + '/orchestrator/default', headers=heads) attrs = r.headers['x-occi-attribute'].split(', ') for attr in attrs: kv = attr.split('=') if kv[0] != 'occi.core.id': if kv[1].startswith('"') and kv[1].endswith('"'): kv[1] = kv[1][1:-1] # scrub off quotes self.entity.attributes[kv[0]] = kv[1] LOG.debug('OCCI Attribute: ' + kv[0] + ' --> ' + kv[1]) # Assemble the SIG svcinsts = '' try: svcinsts = self.entity.attributes['mcn.so.svcinsts'] del self.entity.attributes['mcn.so.svcinsts'] # remove this, not be be used anywhere else except KeyError: LOG.warn('There was no service instance endpoints - ignore if not a composition.') pass if self.registry is None: LOG.error('No registry!') if len(svcinsts) > 0: svcinsts = svcinsts.split() # all instance EPs for svc_loc in svcinsts: # TODO get the service instance resource representation # source resource is self.entity compos = svc_loc.split('/') key = '/' + compos[3] + '/' + compos[4] target = Resource(key, Resource.kind, []) # target resource target.attributes['mcn.sm.endpoint'] = svc_loc self.registry.add_resource(key, target, None) key = '/link/'+str(uuid.uuid4()) link = Link(key, Link.kind, [], self.entity, target) self.registry.add_resource(key, link, None) self.entity.links.append(link) else: LOG.debug('Cannot GET entity as it is not in the activated, deployed or provisioned, updated state') return self.entity, self.extras
def test_link_for_failure(self): ''' Test link... ''' # call creation of entity with non existing trg resource. trg = Resource('/bar/1', self.kind, [], []) link = Link('/bar/1', self.link, [], self.entity, trg) headers, body = self.rendering.from_entity(link) self.assertRaises(AttributeError, self.rendering.to_entity, headers, body, None)
def setUp(self): self.kind = Kind('http://example.com/foo#', 'bar') self.link_kind = Kind('http://example.com/foo#', 'link') self.mixin = Mixin('http://example.com/foo#', 'mixin') target = Resource('/foo/target', self.kind, [], []) source = Resource('/foo/src', self.kind, [self.mixin], []) source.attributes = {'foo': 'bar'} link = Link('/link/foo', self.link_kind, [], source, target) link.attributes = {'foo': 'bar'} source.links = [link] self.resources = [source, target, link] for item in self.resources: self.registry.add_resource(item.identifier, item) self.registry.set_backend(self.kind, KindBackend()) self.registry.set_backend(self.mixin, MixinBackend())
def test_remove_mixins_for_sanity(self): ''' Test if mixin get removed. ''' workflow.append_mixins([self.mixin], self.registry) res = Resource('/foo/1', self.kind1, [self.mixin]) self.registry.add_resource('/foo/1', res) workflow.remove_mixins([self.mixin], self.registry) self.assertFalse(self.mixin in self.registry.get_categories()) self.assertFalse(self.mixin in res.mixins)
def setUp(self): self.kind1 = Kind('http://example.com#', '1') self.kind2 = Kind('http://example.com#', '2') self.action = Action('http://example.com#', 'action') self.mixin = Mixin('http://example.com#', 'mixin') self.registry.set_backend(self.kind1, KindBackend()) self.registry.set_backend(self.kind2, DummyBackend()) self.registry.set_backend(self.action, ActionBackend()) self.registry.set_backend(self.mixin, MixinBackend()) self.entity = Resource('foo', self.kind1, [self.kind2])
def setUp(self): kind = Kind('http://schemas.mobile-cloud-networking.eu/occi/sm#', 'myservice', title='Test Service', attributes={'mcn.test.attribute1': 'immutable'}, related=[Resource.kind], actions=[]) self.test_entity = Resource('my-id', kind, None) self.patcher_system = patch('os.system', return_value=0) self.patcher_system.start() self.patcher_config = patch('mcn.sm.so_manager.CONFIG') self.patcher_config.start() self.patcher_log = patch('mcn.sm.so_manager.LOG') self.patcher_log.start()
def setUp(self): self.back = KindBackend() self.action = Action('foo', 'action') self.kind = Kind('foo', 'bar', actions=[self.action], attributes={ 'foo': 'mutable', 'bar': 'required' }) self.link_kind = Kind('foo', 'bar', related=self.kind) self.resource = Resource('/foo/1', self.kind, []) self.resource.actions = [self.action] self.link = Link('/link/1', self.link_kind, [], None, self.resource)
def setUp(self): self.rendering = TextOcciRendering(self.registry) # type system... self.kind = Kind('http://example.com#', 'foo', related=[Resource.kind]) self.invalid_kind = Kind('http://example.com#', 'invalid') self.link = Kind('http://example.com#', 'link', related=[Link.kind]) self.mixin = Mixin('http://example.com#', 'mixin') self.action = Action('http://example.com#', 'action') self.registry.set_backend(self.kind, KindBackend()) self.registry.set_backend(self.invalid_kind, KindBackend()) self.registry.set_backend(self.link, KindBackend()) self.registry.set_backend(self.mixin, MixinBackend()) self.registry.set_backend(self.action, ActionBackend()) # 2 linked entities self.entity = Resource('/foo/1', self.kind, [self.mixin]) trg = Resource('/foo/2', self.kind, [], []) self.link1 = Link('/link/1', self.link, [], self.entity, trg) self.entity.links = [self.link1] self.registry.add_resource('/foo/2', trg) self.registry.add_resource('/link/1', self.link1) self.registry.add_resource('/foo/1', self.entity)
def test_deploy(self, mock_deploy_so, mock_init_so, mock_deploy_app, mock_create_app, mock_ensure_ssh, mcn_log): # Initialization kind = Kind('http://schemas.mobile-cloud-networking.eu/occi/sm#', 'myservice', title='Test Service', attributes={'mcn.test.attribute1': 'immutable'}, related=[Resource.kind], actions=[]) entity = Resource('my-id', kind, None) # repo uri is weird repo = 'http://[email protected]:myserv.git' mock_create_app.return_value = repo # Test method self.som.deploy(entity, extras={}) # Asserts mock_deploy_app.assert_called_with(repo) self.assertEqual(entity.extras['host'], 'git.mcn.eu:myserv.git')
def test_entities_for_sanity(self): ''' Tests for Entity, Resource and Link. ''' Resource(None, None, None) Link(None, None, None, 'foo', 'bar')
def setUp(self): self.res1 = Resource('foo', None, None) self.res2 = Resource('bar', None, None)
class TestParser(unittest.TestCase): ''' Test for the parser. ''' start_action = Action('http://schemas.ogf.org/occi/infrastructure#', 'start') compute = Kind('http://schemas.ogf.org/occi/infrastructure#', 'compute', title='A OCCI compute...', attributes={ 'occi.compute.cores': '', 'occi.compute.state': 'immutable', 'occi.compute.memory': 'required' }, related=[Resource.kind], actions=[start_action]) network_link = Kind('http://schemas.ogf.org/occi/infrastructure#', 'networkinterface', related=[Link.kind]) source = Resource('/1', compute, []) target = Resource('/2', compute, []) link1 = Link('/link/1', network_link, [], source, target) link2 = Link(None, network_link, [], source, target) registry = NonePersistentRegistry() def setUp(self): self.registry.add_resource(self.source.identifier, self.source) self.registry.add_resource(self.target.identifier, self.target) self.registry.set_backend(self.start_action, None) self.registry.set_backend(self.compute, None) self.registry.set_backend(self.network_link, None) self.link1.attributes = {'foo': 'bar'} def tearDown(self): for item in self.registry.get_categories(): self.registry.delete_mixin(item) #========================================================================== # Success #========================================================================== def test_get_category_for_success(self): ''' Tests if a mixin can be created. ''' # disabling 'Method could be func' pylint check (pyunit fault :-)) # pylint: disable=R0201 # mixin check... tmp = 'foo; scheme="http://example.com#"; location="/foo_bar/"' parser.get_category(tmp, self.registry.get_categories(), is_mixin=True) #========================================================================== # Failure #========================================================================== def test_get_category_for_failure(self): ''' Test with faulty category. ''' self.assertRaises(AttributeError, parser.get_category, 'some crap', self.registry.get_categories()) self.assertRaises(AttributeError, parser.get_category, 'foo; scheme="bar"', self.registry.get_categories()) # mixin with msg location check... tmp = 'foo; scheme="http://example.com#"' self.assertRaises(AttributeError, parser.get_category, tmp, self.registry.get_categories(), True) # mixin with faulty location check... tmp = 'foo; scheme="http://example.com#"; location="sdf"' self.assertRaises(AttributeError, parser.get_category, tmp, self.registry.get_categories(), True) def test_get_link_for_failure(self): ''' Test with msg category. ''' # no valid string... self.assertRaises(AttributeError, parser.get_link, 'some crap', None, self.registry.get_categories()) # no target... link_string = parser.get_link_str(self.link1) self.registry.delete_resource(self.target.identifier) self.assertRaises(AttributeError, parser.get_link, link_string, None, self.registry) def test_get_attributes_for_failure(self): ''' Verifies the parsing of attributes. ''' self.assertRaises(AttributeError, parser.get_attributes, 'bla blub') #========================================================================== # Sanity #========================================================================== def test_get_category_for_sanity(self): ''' Simple sanity check... ''' res = parser.get_category(parser.get_category_str(self.compute), self.registry.get_categories()) self.assertEqual(res, self.compute) def test_get_link_for_sanity(self): ''' Verifies that source and target are set... ''' link_string = parser.get_link_str(self.link1) link = parser.get_link(link_string, self.source, self.registry) self.assertEquals(link.kind, self.network_link) self.assertEquals(link.source, self.source) self.assertEquals(link.target, self.target) # 4 = 1 attr + core.id + core.src + core.target self.assertTrue(len(link.attributes) == 4) # identifier checks... link_string = parser.get_link_str(self.link1) link = parser.get_link(link_string, self.source, self.registry) self.assertEquals(link.identifier, '/link/1') tmp = link_string.split('; ') tmp.pop(2) link_string = '; '.join(tmp) link = parser.get_link(link_string, self.source, self.registry) self.assertEquals(link.identifier, None) def test_strip_all_for_sanity(self): ''' Tests if information get's stripped correctly. ''' self.assertEqual('bla', parser._strip_all('bla')) self.assertEqual('bla', parser._strip_all('"bla"')) self.assertEqual('bla', parser._strip_all(' bla ')) self.assertEqual('bla', parser._strip_all('"bla')) self.assertEqual('bla', parser._strip_all('bla" ')) self.assertEqual(' bla', parser._strip_all('" bla" ')) self.assertEqual('some text', parser._strip_all('"some text" ')) def test_get_attributes_for_sanity(self): ''' Verifies the parsing of attributes. ''' self.assertEquals(parser.get_attributes('foo=bar'), ('foo', 'bar')) self.assertEquals(parser.get_attributes('foo=bar '), ('foo', 'bar')) self.assertEquals(parser.get_attributes('foo= "some stuff"'), ('foo', 'some stuff')) self.assertEquals(parser.get_attributes('foo = "bar"'), ('foo', 'bar'))
def refresh_compute_instances(self, snf, client): '''Syncing registry with cyclades resources''' servers = snf.list_servers() snf_keys = [] for server in servers: snf_keys.append(str(server['id'])) resources = self.registry.resources occi_keys = resources.keys() print occi_keys for serverID in occi_keys: if '/compute/' in serverID and resources[serverID].attributes['occi.compute.hostname'] == "": self.registry.delete_resource(serverID, None) occi_keys = resources.keys() #Compute instances in synnefo not available in registry diff = [x for x in snf_keys if '/compute/'+x not in occi_keys] for key in diff: details = snf.get_server_details(int(key)) flavor = snf.get_flavor_details(details['flavor']['id']) try: print "line 65:Finished getting image details for VM "+key+" with ID" + str(details['flavor']['id']) image = snf.get_image_details(details['image']['id']) for i in self.registry.backends: if i.term == occify_terms(str(image['name'])): rel_image = i if i.term == occify_terms(str(flavor['name'])): rel_flavor = i resource = Resource(key, COMPUTE, [rel_flavor, rel_image]) resource.actions = [START] resource.attributes['occi.core.id'] = key resource.attributes['occi.compute.state'] = 'inactive' resource.attributes['occi.compute.architecture'] = SERVER_CONFIG['compute_arch'] resource.attributes['occi.compute.cores'] = str(flavor['vcpus']) resource.attributes['occi.compute.memory'] = str(flavor['ram']) resource.attributes['occi.core.title'] = str(details['name']) networkIDs = details['addresses'].keys() if len(networkIDs)>0: resource.attributes['occi.compute.hostname'] = str(details['addresses'][networkIDs[0]][0]['addr']) else: resource.attributes['occi.compute.hostname'] = "" self.registry.add_resource(key, resource, None) for netKey in networkIDs: link_id = str(uuid.uuid4()) NET_LINK = core_model.Link("http://schemas.ogf.org/occi/infrastructure#networkinterface" + link_id, NETWORKINTERFACE, [IPNETWORKINTERFACE], resource, self.registry.resources['/network/'+str(netKey)]) for version in details['addresses'][netKey]: ip4address = '' ip6address = '' if version['version']==4: ip4address = str(version['addr']) allocheme = str(version['OS-EXT-IPS:type']) elif version['version']==6: ip6address = str(version['addr']) allocheme = str(version['OS-EXT-IPS:type']) if 'attachments' in details.keys(): for item in details['attachments']: NET_LINK.attributes ={'occi.core.id':link_id, 'occi.networkinterface.allocation' : allocheme, 'occi.networking.interface': str(item['id']), 'occi.networkinterface.mac' : str(item['mac_address']), 'occi.networkinterface.address' : ip4address, 'occi.networkinterface.ip6' : ip6address } elif len(details['addresses'][netKey])>0: NET_LINK.attributes ={'occi.core.id':link_id, 'occi.networkinterface.allocation' : allocheme, 'occi.networking.interface': '', 'occi.networkinterface.mac' : '', 'occi.networkinterface.address' : ip4address, 'occi.networkinterface.ip6' : ip6address } else: NET_LINK.attributes ={'occi.core.id':link_id, 'occi.networkinterface.allocation' : '', 'occi.networking.interface': '', 'occi.networkinterface.mac' : '', 'occi.networkinterface.address' :'', 'occi.networkinterface.ip6' : '' } resource.links.append(NET_LINK) self.registry.add_resource(link_id, NET_LINK, None) except ClientError as ce: if ce.status == 404: print('Image not found (probably older version') continue else: raise ce #Compute instances in registry not available in synnefo diff = [x for x in occi_keys if x[9:] not in snf_keys] for key in diff: if '/network/' not in key: self.registry.delete_resource(key, None)
def _to_entity(data, def_kind, registry): ''' Extract an entity from the HTTP data object. kind -- The kind definition. registry -- The registry. ''' # disable 'Too many local vars' pylint check (It's a bit ugly but will do) # disable 'Too many branches' pylint check (Needs to be improved) # pylint: disable=R0914,R0912 kind = None mixins = [] # first kind & mixins kind_found = False for category_string in data.categories: category = parser.get_category(category_string.strip(), registry.get_categories()) if repr(category) == 'kind' and not kind_found: kind = category kind_found = True else: mixins.append(category) # the attributes attributes = {} for attr_string in data.attributes: key, value = parser.get_attributes(attr_string) attributes[key] = value # now create the entity if kind_found is False and def_kind is None: raise AttributeError('Could not find a valid kind.') elif def_kind is not None: kind = def_kind if Resource.kind in kind.related: # links entity = Resource(None, kind, mixins, []) for link_string in data.links: entity.links.append( parser.get_link(link_string.strip(), entity, registry)) elif Link.kind in kind.related: try: source_attr = attributes['occi.core.source'] target_attr = attributes['occi.core.target'] if source_attr.find(registry.get_hostname()) == 0: source_attr = source_attr.replace(registry.get_hostname(), '') if target_attr.find(registry.get_hostname()) == 0: target_attr = target_attr.replace(registry.get_hostname(), '') source = registry.get_resource(source_attr) target = registry.get_resource(target_attr) except KeyError: raise AttributeError('Both occi.core.[source, target]' + ' attributes need to be resources.') entity = Link(None, kind, mixins, source, target) else: raise AttributeError('This kind seems not to be related to either' + ' resource or link.') entity.attributes = attributes return entity
def _to_entity(data, def_kind, registry): """ Extract an entity from the HTTP data object. kind -- The kind definition. registry -- The registry. """ # disable 'Too many local vars' pylint check (It's a bit ugly but will do) # disable 'Too many branches' pylint check (Needs to be improved) # pylint: disable=R0914,R0912 kind = None mixins = [] # first kind & mixins kind_found = False for category_string in data.categories: category = parser.get_category(category_string.strip(), registry.get_categories()) if repr(category) == "kind" and not kind_found: kind = category kind_found = True else: mixins.append(category) # the attributes attributes = {} for attr_string in data.attributes: key, value = parser.get_attributes(attr_string) attributes[key] = value # now create the entity if kind_found is False and def_kind is None: raise AttributeError("Could not find a valid kind.") elif def_kind is not None: kind = def_kind if Resource.kind in kind.related: # links entity = Resource(None, kind, mixins, []) for link_string in data.links: entity.links.append(parser.get_link(link_string.strip(), entity, registry)) elif Link.kind in kind.related: try: source_attr = attributes["occi.core.source"] target_attr = attributes["occi.core.target"] if source_attr.find(registry.get_hostname()) == 0: source_attr = source_attr.replace(registry.get_hostname(), "") if target_attr.find(registry.get_hostname()) == 0: target_attr = target_attr.replace(registry.get_hostname(), "") source = registry.get_resource(source_attr) target = registry.get_resource(target_attr) except KeyError: raise AttributeError("Both occi.core.[source, target]" + " attributes need to be resources.") entity = Link(None, kind, mixins, source, target) else: raise AttributeError("This kind seems not to be related to either" + " resource or link.") entity.attributes = attributes return entity