Пример #1
0
    def show(self, request, image):
        """Return a dictionary with image details."""
        image_dict = {
            "id": image.get("id"),
            "name": image.get("name"),
            "minRam": int(image.get("min_ram") or 0),
            "minDisk": int(image.get("min_disk") or 0),
            "metadata": image.get("properties", {}),
            "created": self._format_date(image.get("created_at")),
            "updated": self._format_date(image.get("updated_at")),
            "status": self._get_status(image),
            "progress": self._get_progress(image),
            "links": self._get_links(request, image["id"]),
        }

        server_ref = image.get("properties", {}).get("instance_ref")

        if server_ref is not None:
            image_dict["server"] = {
                "id":
                common.get_id_from_href(server_ref),
                "links": [{
                    "rel": "self",
                    "href": server_ref,
                }, {
                    "rel": "bookmark",
                    "href": common.remove_version_from_href(server_ref),
                }],
            }

        return dict(image=image_dict)
Пример #2
0
    def show(self, request, image):
        """Return a dictionary with image details."""
        image_dict = {
            "id": image.get("id"),
            "name": image.get("name"),
            "minRam": int(image.get("min_ram") or 0),
            "minDisk": int(image.get("min_disk") or 0),
            "metadata": image.get("properties", {}),
            "created": self._format_date(image.get("created_at")),
            "updated": self._format_date(image.get("updated_at")),
            "status": self._get_status(image),
            "progress": self._get_progress(image),
            "links": self._get_links(request, image["id"]),
        }

        instance_uuid = image.get("properties", {}).get("instance_uuid")

        if instance_uuid is not None:
            server_ref = os.path.join(request.application_url, 'servers',
                                      instance_uuid)
            image_dict["server"] = {
                "id": instance_uuid,
                "links": [{
                    "rel": "self",
                    "href": server_ref,
                },
                {
                    "rel": "bookmark",
                    "href": common.remove_version_from_href(server_ref),
                }],
            }

        return dict(image=image_dict)
Пример #3
0
 def _build_server(self, image, image_obj):
     try:
         serverRef = image_obj["properties"]["instance_ref"]
         image["server"] = {
             "id": common.get_id_from_href(serverRef),
             "links": [
                 {"rel": "self", "href": serverRef},
                 {"rel": "bookmark", "href": common.remove_version_from_href(serverRef)},
             ],
         }
     except KeyError:
         return
Пример #4
0
 def _build_server(self, image, image_obj):
     try:
         serverRef = image_obj['properties']['instance_ref']
         image['server'] = {
             "id": common.get_id_from_href(serverRef),
             "links": [
                 {
                     "rel": "self",
                     "href": serverRef,
                 },
                 {
                     "rel": "bookmark",
                     "href": common.remove_version_from_href(serverRef),
                 },
             ]
         }
     except KeyError:
         return
Пример #5
0
 def _build_server(self, image, image_obj):
     try:
         serverRef = image_obj['properties']['instance_ref']
         image['server'] = {
             "id":
             common.get_id_from_href(serverRef),
             "links": [
                 {
                     "rel": "self",
                     "href": serverRef,
                 },
                 {
                     "rel": "bookmark",
                     "href": common.remove_version_from_href(serverRef),
                 },
             ]
         }
     except KeyError:
         return
Пример #6
0
 def generate_bookmark(self, image_id):
     """Create a URL that refers to a specific flavor id."""
     return os.path.join(common.remove_version_from_href(self.base_url),
         self.project_id, "images", str(image_id))
Пример #7
0
 def generate_bookmark(self, server_id):
     """Create an url that refers to a specific flavor id."""
     return os.path.join(common.remove_version_from_href(self.base_url),
         "servers", str(server_id))
Пример #8
0
 def test_remove_version_from_href_3(self):
     fixture = "http://www.testsite.com/v10.10"
     expected = "http://www.testsite.com"
     actual = common.remove_version_from_href(fixture)
     self.assertEqual(actual, expected)
Пример #9
0
 def generate_bookmark(self, image_id):
     """Create an url that refers to a specific flavor id."""
     return os.path.join(common.remove_version_from_href(self.base_url),
                         self.project_id, "images", str(image_id))
Пример #10
0
 def generate_bookmark(self, server_id):
     """Create an url that refers to a specific flavor id."""
     return os.path.join(common.remove_version_from_href(self.base_url),
                         "servers", str(server_id))
Пример #11
0
 def test_remove_major_version_from_href(self):
     fixture = "http://www.testsite.com/v1/images"
     expected = "http://www.testsite.com/images"
     actual = common.remove_version_from_href(fixture)
     self.assertEqual(actual, expected)
Пример #12
0
def replace_with_links(xml_str, tag_dict_list, replace_dict_out):
    """ Replace entity nodes in input xml with entity references.
        tag_dict_list should contain tag dictionaries; each dict should
        contain the following keys:
        tag: element tag name
        tag_replacement : replacement tag in output xml, same as input tag
                          if None.
        tag_key: Key element tag, if entity does not contain any child
                 elements, this would be added as attribute with value as
                 element text.
        tag_attrib: list of child element tags that are used as attributes
                    in the replaced entity reference.
        tag_collection_url: collection url to be used for creation
                    of the link.
        If the child is an element containing only a single text node
        and tag_key is null, it's data is taken as the tag_key.
        :param xml_str: input xml with no default namespace prefixes
        :param tag_dict_list: list of tag dictionaries
        :param replace_dict_out: the xpath of elements replaced are put in the
                out parameter dict
        :returns: output xml containing entity references
        :raises TagDictionaryError: if resource references cannot be
        constructed using the given tag dictionary.
    """

    def _validate_tag_dict(tag_dict):
        if not tag_dict:
            return False
        try:
            tag_dict['tag']
            tag_dict['tag_key']
            tag_dict['tag_replacement']
            tag_dict['tag_attrib']
            tag_dict['tag_collection_url']
        except KeyError:
            return False
        return True

    def _get_tag_dict_values(tag_dict):
        return (tag_dict['tag'], tag_dict['tag_key'],
                tag_dict['tag_replacement'], tag_dict['tag_attrib'],
                tag_dict['tag_collection_url'])

    if not tag_dict_list:
        return xml_str

#    if (not replace_dict_out):
#        replace_dict_out = {}

    tree = etree.parse(StringIO.StringIO(xml_str),
                       etree.XMLParser(remove_blank_text=True))
    root = tree.getroot()
    rootNS = ''
    if not root.prefix and root.nsmap:
        rootNS = root.nsmap[None]
    elif root.nsmap and root.prefix is not None:
        rootNS = root.nsmap[root.prefix]
    ROOTNS = '{%s}' % rootNS
    for tag_dict in tag_dict_list:
        if _validate_tag_dict(tag_dict):
            try:
                (tag, tag_key, tag_replacement, tag_attrib_list,
                 tag_collection_url) = _get_tag_dict_values(tag_dict)
                elements_to_be_replaced = []
                for element in root.iter(ROOTNS + str(tag)):
                    nsmap = {'atom': constants.XMLNS_ATOM}
                    out_dict = {}
                    if not tag_replacement:
                        tag_replacement = tag
                    replace_element = Element(ROOTNS + tag_replacement,
                                              nsmap=nsmap)
                    if tag_attrib_list is not None:
                        for tag in tag_attrib_list:
                            if element.find(tag) is not None:
                                replace_element.attrib[ROOTNS + tag] = \
                                    element.find(tag).text
                                out_dict[tag] = element.find(tag).text
                    resource_key = None
                    if not tag_key or len(element) == 0:
                        resource_key = element.text
                    elif tag_key is not None and element.find(
                            ROOTNS + tag_key) is not None and \
                            element.find(ROOTNS + tag_key).text is not None:

                        resource_key = element.find(ROOTNS
                                                    + tag_key).text
                    if not resource_key:
                        raise TagDictionaryError(
                            'No resource key found from tag dictionary:',
                            tag_dict)
                    if tag_key is not None:
                        replace_element.attrib[ROOTNS + tag_key] = \
                            resource_key
                        out_dict[tag_key] = resource_key

                    href = os.path.join(tag_collection_url,
                                        str(resource_key))
                    bookmark = \
                        os.path.join(
                            common.remove_version_from_href(
                                tag_collection_url),
                            str(resource_key))
                    links = [{'rel': 'self', 'href': href},
                             {'rel': 'bookmark', 'href': bookmark}]

                    for link_dict in links:
                        SubElement(replace_element, constants.ATOM
                                   + 'link', attrib=link_dict)
                    out_dict['links'] = links
                    elements_to_be_replaced.append((element,
                                                    replace_element, out_dict))

                for (element, replace_element, out_dict) in \
                        elements_to_be_replaced:
                    if element.getparent() is None:
                        tree._setroot(replace_element)
                    else:
                        element.getparent().replace(element,
                                                    replace_element)

                for (element, replace_element, out_dict) in \
                        elements_to_be_replaced:
                    LOG.debug(_('Replaced element path: %s'
                                % replace_element.getroottree().getpath(
                                    replace_element)))
                    replace_dict_out.update(
                        {tree.getpath(replace_element): out_dict})
            except (KeyError, IndexError, ValueError), err:
                LOG.error(_('Lookup Error while finding tag \
                healthnmon api... %s ' % str(err)), exc_info=1)
Пример #13
0
 def generate_bookmark(self, flavor_id):
     """Create an url that refers to a specific flavor id."""
     return "%s/flavors/%s" % (
         common.remove_version_from_href(self.base_url),
         flavor_id,
     )
Пример #14
0
 def test_remove_version_from_href_4(self):
     fixture = 'http://www.testsite.com/v1.1/images/v10.5'
     expected = 'http://www.testsite.com/images/v10.5'
     actual = common.remove_version_from_href(fixture)
     self.assertEqual(actual, expected)
Пример #15
0
 def generate_bookmark(self, flavor_id):
     """Create an url that refers to a specific flavor id."""
     return "%s/flavors/%s" % (
         common.remove_version_from_href(self.base_url),
         flavor_id,
     )
Пример #16
0
 def test_remove_version_from_href_4(self):
     fixture = 'http://www.testsite.com/v1.1/images/v10.5'
     expected = 'http://www.testsite.com/images/v10.5'
     actual = common.remove_version_from_href(fixture)
     self.assertEqual(actual, expected)
Пример #17
0
def replace_with_links(xml_str, tag_dict_list, replace_dict_out):
    """ Replace entity nodes in input xml with entity references.
        tag_dict_list should contain tag dictionaries; each dict should
        contain the following keys:
        tag: element tag name
        tag_replacement : replacement tag in output xml, same as input tag
                          if None.
        tag_key: Key element tag, if entity does not contain any child
                 elements, this would be added as attribute with value as
                 element text.
        tag_attrib: list of child element tags that are used as attributes
                    in the replaced entity reference.
        tag_collection_url: collection url to be used for creation
                    of the link.
        If the child is an element containing only a single text node
        and tag_key is null, it's data is taken as the tag_key.
        :param xml_str: input xml with no default namespace prefixes
        :param tag_dict_list: list of tag dictionaries
        :param replace_dict_out: the xpath of elements replaced are put in the
                out parameter dict
        :returns: output xml containing entity references
        :raises TagDictionaryError: if resource references cannot be
        constructed using the given tag dictionary.
    """
    def _validate_tag_dict(tag_dict):
        if not tag_dict:
            return False
        try:
            tag_dict['tag']
            tag_dict['tag_key']
            tag_dict['tag_replacement']
            tag_dict['tag_attrib']
            tag_dict['tag_collection_url']
        except KeyError:
            return False
        return True

    def _get_tag_dict_values(tag_dict):
        return (tag_dict['tag'], tag_dict['tag_key'],
                tag_dict['tag_replacement'], tag_dict['tag_attrib'],
                tag_dict['tag_collection_url'])

    if not tag_dict_list:
        return xml_str


#    if (not replace_dict_out):
#        replace_dict_out = {}

    tree = etree.parse(StringIO.StringIO(xml_str),
                       etree.XMLParser(remove_blank_text=True))
    root = tree.getroot()
    rootNS = ''
    if not root.prefix and root.nsmap:
        rootNS = root.nsmap[None]
    elif root.nsmap and root.prefix is not None:
        rootNS = root.nsmap[root.prefix]
    ROOTNS = '{%s}' % rootNS
    for tag_dict in tag_dict_list:
        if _validate_tag_dict(tag_dict):
            try:
                (tag, tag_key, tag_replacement, tag_attrib_list,
                 tag_collection_url) = _get_tag_dict_values(tag_dict)
                elements_to_be_replaced = []
                for element in root.iter(ROOTNS + str(tag)):
                    nsmap = {'atom': constants.XMLNS_ATOM}
                    out_dict = {}
                    if not tag_replacement:
                        tag_replacement = tag
                    replace_element = Element(ROOTNS + tag_replacement,
                                              nsmap=nsmap)
                    if tag_attrib_list is not None:
                        for tag in tag_attrib_list:
                            if element.find(tag) is not None:
                                replace_element.attrib[ROOTNS + tag] = \
                                    element.find(tag).text
                                out_dict[tag] = element.find(tag).text
                    resource_key = None
                    if not tag_key or len(element) == 0:
                        resource_key = element.text
                    elif tag_key is not None and element.find(
                            ROOTNS + tag_key) is not None and element.find(
                                ROOTNS + tag_key).text is not None:

                        resource_key = element.find(ROOTNS + tag_key).text
                    if not resource_key:
                        raise TagDictionaryError(
                            'No resource key found from tag dictionary:',
                            tag_dict)
                    if tag_key is not None:
                        replace_element.attrib[ROOTNS + tag_key] = \
                            resource_key
                        out_dict[tag_key] = resource_key

                    href = os.path.join(tag_collection_url, str(resource_key))
                    bookmark = \
                        os.path.join(
                            common.remove_version_from_href(
                                tag_collection_url),
                            str(resource_key))
                    links = [{
                        'rel': 'self',
                        'href': href
                    }, {
                        'rel': 'bookmark',
                        'href': bookmark
                    }]

                    for link_dict in links:
                        SubElement(replace_element,
                                   constants.ATOM + 'link',
                                   attrib=link_dict)
                    out_dict['links'] = links
                    elements_to_be_replaced.append(
                        (element, replace_element, out_dict))

                for (element, replace_element, out_dict) in \
                        elements_to_be_replaced:
                    if element.getparent() is None:
                        tree._setroot(replace_element)
                    else:
                        element.getparent().replace(element, replace_element)

                for (element, replace_element, out_dict) in \
                        elements_to_be_replaced:
                    LOG.debug(
                        _('Replaced element path: %s' %
                          replace_element.getroottree().getpath(
                              replace_element)))
                    replace_dict_out.update(
                        {tree.getpath(replace_element): out_dict})
            except (KeyError, IndexError, ValueError), err:
                LOG.error(
                    _('Lookup Error while finding tag healthnmon api... %s ' %
                      str(err)),
                    exc_info=1)