Exemplo n.º 1
0
 def test_is_related_for_sanity(self):
     '''
     Tests links...
     '''
     self.assertTrue(backend.is_related_valid(self.link))
     link2 = Link('/link/2', self.kind, [], None, self.resource)
     self.assertFalse(backend.is_related_valid(link2))
Exemplo n.º 2
0
    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)
Exemplo n.º 3
0
def get_link(link_string, source, registry):
    '''
    Create a Link from a string rendering.

    Also note that the link_id is set but is not yet registered as resource.

    link_string -- A string rendering of a link.
    source -- The source entity.
    registry -- Registry used for this call.
    '''
    tmp = link_string.find('<') + 1
    target_id = link_string[tmp:link_string.rfind('>', tmp)].strip()

    try:
        link_id = find_in_string(link_string, 'self')
    except AttributeError:
        link_id = None

    try:
        tmp_category = find_in_string(link_string, 'category')
    except AttributeError:
        raise AttributeError('Could not determine the Category of the Link.')
    tempus = tmp_category.split('#')
    link_category = get_category(
        tempus[1].strip() + ';scheme="' + tempus[0].strip() + '#"',
        registry.get_categories())

    attributes = {}
    attr_begin = link_string.find('category="') + 12 + len(tmp_category)
    attributes_str = link_string[attr_begin:]
    for attribute in attributes_str.split(';'):
        tmp = attribute.strip().split('=')
        if len(tmp) == 2:
            attributes[tmp[0].strip()] = tmp[1].rstrip('"').lstrip('"').strip()

    try:
        if target_id.find(registry.get_hostname()) == 0:
            target_id = target_id.replace(registry.get_hostname(), '')
        target = registry.get_resource(target_id)
    except KeyError:
        raise AttributeError('The target for the link cannot be found: ' +
                             target_id)

    link = Link(link_id, link_category, [], source, target)
    link.attributes = attributes
    return link
Exemplo n.º 4
0
def get_link(link_string, source, registry):
    '''
    Create a Link from a string rendering.

    Also note that the link_id is set but is not yet registered as resource.

    link_string -- A string rendering of a link.
    source -- The source entity.
    registry -- Registry used for this call.
    '''
    tmp = link_string.find('<') + 1
    target_id = link_string[tmp:link_string.rfind('>', tmp)].strip()

    try:
        link_id = find_in_string(link_string, 'self')
    except AttributeError:
        link_id = None

    try:
        tmp_category = find_in_string(link_string, 'category')
    except AttributeError:
        raise AttributeError('Could not determine the Category of the Link.')
    tempus = tmp_category.split('#')
    link_category = get_category(tempus[1].strip() + ';scheme="'
                                 + tempus[0].strip() + '#"',
                                 registry.get_categories())

    attributes = {}
    attr_begin = link_string.find('category="') + 12 + len(tmp_category)
    attributes_str = link_string[attr_begin:]
    for attribute in attributes_str.split(';'):
        tmp = attribute.strip().split('=')
        if len(tmp) == 2:
            attributes[tmp[0].strip()] = tmp[1].rstrip('"').lstrip('"').strip()

    try:
        if target_id.find(registry.get_hostname()) == 0:
            target_id = target_id.replace(registry.get_hostname(), '')
        target = registry.get_resource(target_id)
    except KeyError:
        raise AttributeError('The target for the link cannot be found: '
                             + target_id)

    link = Link(link_id, link_category, [], source, target)
    link.attributes = attributes
    return link
Exemplo n.º 5
0
 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
Exemplo n.º 6
0
    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
Exemplo n.º 7
0
 def test_create_resource_for_failure(self):
     '''
     Test if create behaves correct on faulty create calls...
     '''
     # the id of this link already exists...
     link2 = Link('/link/1', self.link_kind, [], self.src_entity,
                  self.trg_entity)
     self.src_entity.links.append(link2)
     self.assertRaises(AttributeError, workflow.create_entity, '/foo/bar',
                       self.src_entity, self.registry)
Exemplo n.º 8
0
 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)
Exemplo n.º 9
0
    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())
Exemplo n.º 10
0
    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 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]
Exemplo n.º 12
0
 def test_create_link_for_sanity(self):
     '''
     Test creation...
     '''
     link2 = Link(None, self.link_kind, [], self.src_entity,
                  self.trg_entity)
     workflow.create_entity('/link/2', link2, self.registry)
     # id needs to be set
     self.assertEqual(link2.identifier, '/link/2')
     # entity needs to be available
     self.assertTrue(link2 in self.registry.get_resources())
     # link needs to be added to the src entity
     self.assertTrue(link2 in self.src_entity.links)
     self.assertTrue(len(self.src_entity.links) == 2)
Exemplo n.º 13
0
 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)
Exemplo n.º 14
0
    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())
Exemplo n.º 15
0
    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)
Exemplo n.º 16
0
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'))
Exemplo n.º 17
0
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
Exemplo n.º 18
0
 def test_entities_for_sanity(self):
     '''
     Tests for Entity, Resource and Link.
     '''
     Resource(None, None, None)
     Link(None, None, None, 'foo', 'bar')