def list_nodes(self, ex_node_ids=None):
        """
        List all nodes

        Ex_node_ids parameter is used to filter the list of
        nodes that should be returned. Only the nodes
        with the corresponding node ids will be returned.

        @param      ex_node_ids: List of C{node.id}
        @type       ex_node_ids: C{list} of C{str}

        @rtype: C{list} of L{Node}
        """
        params = {'Action': 'DescribeInstances'}
        if ex_node_ids:
            params.update(self._pathlist('InstanceId', ex_node_ids))
        elem = self.connection.request(self.path, params=params).object
        nodes = []
        for rs in findall(element=elem, xpath='reservationSet/item',
                          namespace=NAMESPACE):
            groups = [g.findtext('')
                      for g in findall(element=rs,
                                       xpath='groupSet/item/groupId',
                                       namespace=NAMESPACE)]
            nodes += self._to_nodes(rs, 'instancesSet/item', groups)

        nodes_elastic_ips_mappings = self.ex_describe_addresses(nodes)
        for node in nodes:
            ips = nodes_elastic_ips_mappings[node.id]
            node.public_ips.extend(ips)
        return nodes
Example #2
0
    def _to_node(self, el):
        def get_ips(el):
            return [ip.get('addr') for ip in el]

        def get_meta_dict(el):
            d = {}
            for meta in el:
                d[meta.get('key')] = meta.text
            return d

        public_ip = get_ips(findall(el, 'addresses/public/ip',
                                          self.XML_NAMESPACE))
        private_ip = get_ips(findall(el, 'addresses/private/ip',
                                          self.XML_NAMESPACE))
        metadata = get_meta_dict(findall(el, 'metadata/meta',
                                          self.XML_NAMESPACE))

        n = Node(id=el.get('id'),
                 name=el.get('name'),
                 state=self.NODE_STATE_MAP.get(
                     el.get('status'), NodeState.UNKNOWN),
                 public_ips=public_ip,
                 private_ips=private_ip,
                 driver=self.connection.driver,
                 extra={
                    'password': el.get('adminPass'),
                    'hostId': el.get('hostId'),
                    'imageId': el.get('imageId'),
                    'flavorId': el.get('flavorId'),
                    'uri': "https://%s%s/servers/%s" % (
                         self.connection.host,
                         self.connection.request_path, el.get('id')),
                    'metadata': metadata,
                 })
        return n
Example #3
0
    def _to_rule(self, el):
        def __to_bool__(val):
            return val.lower() in ("yes", "true", "t", "1")

        conditions = {}
        cond_members = findall(element=el,
                               xpath='Conditions/member',
                               namespace=NS)
        for cond_member in cond_members:
            field = findtext(element=cond_member, xpath='Field', namespace=NS)
            conditions[field] = []
            value_members = findall(element=cond_member,
                                    xpath='Values/member',
                                    namespace=NS)
            for value_member in value_members:
                conditions[field].append(value_member.text)

        rule = ALBRule(
            rule_id=findtext(element=el, xpath='RuleArn', namespace=NS),
            is_default=__to_bool__(
                findtext(element=el, xpath='IsDefault', namespace=NS)),
            # CreateRule API method accepts only int for priority, however
            # DescribeRules method returns 'default' string for default
            # listener rule. So leaving it as string.
            priority=findtext(element=el, xpath='Priority', namespace=NS),
            target_group=None,
            driver=self.connection.driver,
            conditions=conditions)

        rule._target_group_arn = findtext(
            element=el, xpath='Actions/member/TargetGroupArn', namespace=NS)

        return rule
    def _to_volumes(self, element):
        # ステータスチェック(保留)
        # try:
        #    state = self.NODE_STATE_MAP[
        #            findattr(element=element, xpath="instanceState/name",
        #                     namespace=NAMESPACE)
        #    ]
        # except KeyError:
        #    state = NodeState.UNKNOWN

        tags = dict(
            (
                findtext(element=item, xpath="key", namespace=NAMESPACE),
                findtext(element=item, xpath="value", namespace=NAMESPACE),
            )
            for item in findall(element=element, xpath="tagSet/item", namespace=NAMESPACE)
        )

        attachment = []
        for rs in findall(element=element, xpath="attachmentSet/item", namespace=NAMESPACE):
            attachmentset = self._to_attachmentSet(rs)
            attachmentset.setDeleteOnTermination(
                findattr(element=element, xpath="deleteOnTermination", namespace=NAMESPACE)
            )
            attachment.append(attachmentset)

        v = self._to_volume(element, attachment, tags)
        return v
Example #5
0
    def list_nodes(self, ex_node_ids=None):
        """
        @type node.id: C{list}
        @param ex_node_ids: List of C{node.id}
        This parameter is used to filter the list of
        nodes that should be returned. Only the nodes
        with the corresponding node ids will be returned.
        """
        params = {'Action': 'DescribeInstances'}
        if ex_node_ids:
            params.update(self._pathlist('InstanceId', ex_node_ids))
        elem = self.connection.request(self.path, params=params).object
        nodes = []
        for rs in findall(element=elem, xpath='reservationSet/item',
                          namespace=NAMESPACE):
            groups = [g.findtext('')
                      for g in findall(element=rs,
                                       xpath='groupSet/item/groupId',
                                       namespace=NAMESPACE)]
            nodes += self._to_nodes(rs, 'instancesSet/item', groups)

        nodes_elastic_ips_mappings = self.ex_describe_addresses(nodes)
        for node in nodes:
            ips = nodes_elastic_ips_mappings[node.id]
            node.public_ips.extend(ips)
        return nodes
    def _to_volumes(self, element):
        #ステータスチェック(保留)
        #try:
        #    state = self.NODE_STATE_MAP[
        #            findattr(element=element, xpath="instanceState/name",
        #                     namespace=NAMESPACE)
        #    ]
        #except KeyError:
        #    state = NodeState.UNKNOWN

        tags = dict(
            (findtext(element=item, xpath='key', namespace=NAMESPACE),
             findtext(element=item, xpath='value', namespace=NAMESPACE))
            for item in findall(
                element=element, xpath='tagSet/item', namespace=NAMESPACE))

        attachment = []
        for rs in findall(element=element,
                          xpath='attachmentSet/item',
                          namespace=NAMESPACE):
            attachmentset = self._to_attachmentSet(rs)
            attachmentset.setDeleteOnTermination(
                findattr(element=element,
                         xpath="deleteOnTermination",
                         namespace=NAMESPACE))
            attachment.append(attachmentset)

        v = self._to_volume(element, attachment, tags)
        return v
Example #7
0
    def _to_rule(self, el):
        def __to_bool__(val):
            return val.lower() in ("yes", "true", "t", "1")

        id = findtext(element=el, xpath='RuleArn', namespace=NS)
        is_default = findtext(element=el, xpath='IsDefault', namespace=NS)
        priority = findtext(element=el, xpath='Priority', namespace=NS)
        target_group = findtext(element=el,
                                xpath='Actions/member/TargetGroupArn',
                                namespace=NS)
        conditions = {}
        cond_members = findall(element=el,
                               xpath='Conditions/member',
                               namespace=NS)
        for cond_member in cond_members:
            field = findtext(element=cond_member, xpath='Field', namespace=NS)
            conditions[field] = []
            value_members = findall(element=cond_member,
                                    xpath='Values/member',
                                    namespace=NS)
            for value_member in value_members:
                conditions[field].append(value_member.text)

        rule = {
            'id': id,
            'is_default': __to_bool__(is_default),
            'priority': priority,
            'target_group': target_group,
            'conditions': conditions
        }

        return rule
Example #8
0
    def ex_limits(self):
        """
        Extra call to get account's limits, such as
        rates (for example amount of POST requests per day)
        and absolute limits like total amount of available
        RAM to be used by servers.

        @return: C{dict} with keys 'rate' and 'absolute'
        """
        def _to_rate(el):
            rate = {}
            for item in list(el.items()):
                rate[item[0]] = item[1]

            return rate

        def _to_absolute(el):
            return {el.get('name'): el.get('value')}

        limits = self.connection.request("/limits").object
        rate = [
            _to_rate(el)
            for el in findall(limits, 'rate/limit', self.XML_NAMESPACE)
        ]
        absolute = {}
        for item in findall(limits, 'absolute/limit', self.XML_NAMESPACE):
            absolute.update(_to_absolute(item))

        return {"rate": rate, "absolute": absolute}
    def describeInstances(self, instanceid=None):
        params = {'Action': 'DescribeInstances'}

        #任意パラメータ
        if instanceid != None:
            params.update({'InstanceId.0': instanceid})

        elem = self.connection.request(self.path, params=params).object

        nodes = []
        for rs in findall(element=elem,
                          xpath='reservationSet/item',
                          namespace=NAMESPACE):
            groups = []
            for g in findall(
                    element=rs,
                    xpath=
                    'instancesSet/item/networkInterfaceSet/item/groupSet/item',
                    namespace=NAMESPACE):
                groups.append(
                    findattr(element=g, xpath='groupId', namespace=NAMESPACE))

            nodes += self._to_nodes(rs, 'instancesSet/item', groups)
        nodes_elastic_ips_mappings = self.ex_describe_addresses(nodes)
        for node in nodes:
            node.public_ip.extend(nodes_elastic_ips_mappings[node.id])
        return nodes
Example #10
0
 def _to_balancer_attribute(self, element):
     balancer = self._to_balancer(element)
     port_proto_elements = findall(
         element,
         'ListenerPortsAndProtocol/ListenerPortAndProtocol',
         namespace=self.namespace)
     if len(port_proto_elements) > 0:
         listeners = [
             self._to_port_and_protocol(el) for el in port_proto_elements
         ]
     else:
         port_elements = findall(element,
                                 'ListenerPorts/ListenerPort',
                                 namespace=self.namespace)
         listeners = [{
             'ListenerPort': el.text,
             'ListenerProtocol': 'http'
         } for el in port_elements]
     server_elements = findall(element,
                               'BackendServers/BackendServer',
                               namespace=self.namespace)
     backend_servers = [
         self._to_server_and_weight(el) for el in server_elements
     ]
     return SLBLoadBalancerAttribute(balancer, listeners, backend_servers)
Example #11
0
    def ex_limits(self):
        """
        Extra call to get account's limits, such as
        rates (for example amount of POST requests per day)
        and absolute limits like total amount of available
        RAM to be used by servers.

        @return: C{dict} with keys 'rate' and 'absolute'
        """

        def _to_rate(el):
            rate = {}
            for item in list(el.items()):
                rate[item[0]] = item[1]

            return rate

        def _to_absolute(el):
            return {el.get('name'): el.get('value')}

        limits = self.connection.request("/limits").object
        rate = [_to_rate(el) for el in findall(limits, 'rate/limit',
            self.XML_NAMESPACE)]
        absolute = {}
        for item in findall(limits, 'absolute/limit',
          self.XML_NAMESPACE):
            absolute.update(_to_absolute(item))

        return {"rate": rate, "absolute": absolute}
Example #12
0
    def _to_rule(self, el):
        def __to_bool__(val):
            return val.lower() in ("yes", "true", "t", "1")

        id = findtext(element=el, xpath='RuleArn', namespace=NS)
        is_default = findtext(element=el, xpath='IsDefault', namespace=NS)
        priority = findtext(element=el, xpath='Priority', namespace=NS)
        target_group = findtext(
            element=el,
            xpath='Actions/member/TargetGroupArn',
            namespace=NS
        )
        conditions = {}
        cond_members = findall(
            element=el, xpath='Conditions/member', namespace=NS
        )
        for cond_member in cond_members:
            field = findtext(element=cond_member, xpath='Field', namespace=NS)
            conditions[field] = []
            value_members = findall(
                element=cond_member, xpath='Values/member', namespace=NS
            )
            for value_member in value_members:
                conditions[field].append(value_member.text)

        rule = {
            'id': id,
            'is_default': __to_bool__(is_default),
            'priority': priority,
            'target_group': target_group,
            'conditions': conditions
        }

        return rule
Example #13
0
 def _to_ip_addresses(self, el):
     return OpenStack_1_0_NodeIpAddresses(
         [ip.get('addr') for ip in
          findall(findall(el, 'public', self.XML_NAMESPACE)[0],
          'ip', self.XML_NAMESPACE)],
         [ip.get('addr') for ip in
          findall(findall(el, 'private', self.XML_NAMESPACE)[0],
          'ip', self.XML_NAMESPACE)])
Example #14
0
 def _to_shared_ip_group(self, el):
     servers_el = findall(el, 'servers', self.XML_NAMESPACE)
     if servers_el:
         servers = [s.get('id')
                    for s in findall(servers_el[0], 'server',
                    self.XML_NAMESPACE)]
     else:
         servers = None
     return OpenStack_1_0_SharedIpGroup(id=el.get('id'),
                                   name=el.get('name'),
                                   servers=servers)
Example #15
0
 def _to_policy_types(self, data):
     xpath = "DescribeLoadBalancerPolicyTypesResult/"
     xpath += "PolicyTypeDescriptions/member"
     return [
         findtext(element=el, xpath="PolicyTypeName", namespace=NS)
         for el in findall(element=data, xpath=xpath, namespace=NS)
     ]
Example #16
0
 def get_zone(self, zone_id):
     self.connection.set_context({'zone_id': zone_id})
     uri = API_ROOT + 'hostedzone/' + zone_id
     data = self.connection.request(uri).object
     elem = findall(element=data, xpath='HostedZone',
                    namespace=NAMESPACE)[0]
     return self._to_zone(elem)
Example #17
0
    def ex_create_network_domain(self, location, name, service_plan,
                                 description=None):
        """
        Deploy a new network domain to a data center
        """
        create_node = ET.Element('deployNetworkDomain', {'xmlns': TYPES_URN})
        ET.SubElement(create_node, "datacenterId").text = location.id
        ET.SubElement(create_node, "name").text = name
        if description is not None:
            ET.SubElement(create_node, "description").text = description
        ET.SubElement(create_node, "type").text = service_plan

        response = self.connection.request_with_orgId_api_2(
            'network/deployNetworkDomain',
            method='POST',
            data=ET.tostring(create_node)).object

        network_domain_id = None

        for info in findall(response, 'info', TYPES_URN):
            if info.get('name') == 'networkDomainId':
                network_domain_id = info.get('value')

        return DimensionDataNetworkDomain(
            id=network_domain_id,
            name=name,
            description=description,
            location=location,
            status=NodeState.RUNNING,
            plan=service_plan
        )
Example #18
0
 def _to_volumes(self, element):
     element_volumes = findall(element=element,
                               xpath='volumeSet/item', namespace=NAMESPACE)
     volumes = []
     for vol in element_volumes:
         volumes.append(self._to_volume(vol))
     return volumes
Example #19
0
    def _to_ip_blocks(self, object):
        blocks = []
        locations = self.list_locations()
        for element in findall(object, 'publicIpBlock', TYPES_URN):
            blocks.append(self._to_ip_block(element, locations))

        return blocks
    def describeVpcAddress(self, publicIp=None):
        params = {'Action': 'DescribeAddresses'}
        #任意パラメータ
        if publicIp != None:
            params.update({'PublicIp.0': publicIp})

        elem = self.connection.request(self.path, params=params).object

        address = []
        for rs in findall(element=elem,
                          xpath='addressesSet/item',
                          namespace=NAMESPACE):
            address.append(self._to_vpcaddress(rs))

        if not address or len(address) == 0:
            #アドレスが存在しない場合
            raise IaasException("EPROCESS-000117", [
                publicIp,
            ])

        if len(address) > 1:
            #アドレスを複数参照できた場合
            raise IaasException("EPROCESS-000118", [
                publicIp,
            ])

        return address[0]
Example #21
0
    def parse_error(self):
        status = int(self.status)

        if status == 401:
            if not self.body:
                raise InvalidCredsError(str(self.status) + ': ' + self.error)
            else:
                raise InvalidCredsError(self.body)
        elif status == 404:
            context = self.connection.context
            if context['resource'] == 'zone':
                raise ZoneDoesNotExistError(value='', driver=self,
                                            zone_id=context['id'])
            elif context['resource'] == 'record':
                raise RecordDoesNotExistError(value='', driver=self,
                                              record_id=context['id'])
        elif status != 503:
            try:
                body = ET.XML(self.body)
            except:
                raise MalformedResponseError('Failed to parse XML',
                                             body=self.body)

            errors = []
            for error in findall(element=body, xpath='error'):
                errors.append(error.text)

            raise ZerigoError(code=status, errors=errors)

        return self.body
Example #22
0
    def _to_networks(self, object):
        networks = []
        locations = self.list_locations()
        for element in findall(object, 'network', NETWORK_NS):
            networks.append(self._to_network(element, locations))

        return networks
Example #23
0
    def ex_list_certificates(self, certificate_ids=[]):
        """
        List all server certificates

        :param certificate_ids: certificate ids to filter results
        :type certificate_ids: ``str``

        :return: certificates
        :rtype: ``SLBServerCertificate``
        """

        params = {
            'Action': 'DescribeServerCertificates',
            'RegionId': self.region
        }
        if certificate_ids and isinstance(certificate_ids, list):
            params['ServerCertificateId'] = ','.join(certificate_ids)

        resp_body = self.connection.request(self.path, params).object
        cert_elements = findall(resp_body,
                                'ServerCertificates/ServerCertificate',
                                namespace=self.namespace)
        certificates = [
            self._to_server_certificate(el) for el in cert_elements
        ]
        return certificates
    def ex_describe_all_addresses(self, only_allocated=False):
        """
        Return all the Elastic IP addresses for this account
        optionally, return only the allocated addresses

        @param    only_allocated: If true, return only those addresses
                                  that are associated with an instance
        @type     only_allocated: C{str}

        @return:   list list of elastic ips for this particular account.
        @rtype: C{list} of C{str}
        """
        params = {'Action': 'DescribeAddresses'}

        result = self.connection.request(self.path,
                                         params=params.copy()).object

        # the list which we return
        elastic_ip_addresses = []
        for element in findall(element=result, xpath='addressesSet/item',
                               namespace=NAMESPACE):
            instance_id = findtext(element=element, xpath='instanceId',
                                   namespace=NAMESPACE)

            # if only allocated addresses are requested
            if only_allocated and not instance_id:
                continue

            ip_address = findtext(element=element, xpath='publicIp',
                                  namespace=NAMESPACE)

            elastic_ip_addresses.append(ip_address)

        return elastic_ip_addresses
Example #25
0
    def _get_resource_tags(self, element):
        """
        Parse tags from the provided element and return a dictionary with
        key/value pairs.

        :rtype: ``dict``
        """
        tags = {}

        # Get our tag set by parsing the element
        tag_set = findall(element=element,
                          xpath='tagSet/item',
                          namespace=NS)

        for tag in tag_set:
            key = findtext(element=tag,
                           xpath='key',
                           namespace=NS)

            value = findtext(element=tag,
                             xpath='value',
                             namespace=NS)

            tags[key] = value

        return tags
Example #26
0
    def parse_error(self):
        status = int(self.status)

        if status == 401:
            if not self.body:
                raise InvalidCredsError(str(self.status) + ": " + self.error)
            else:
                raise InvalidCredsError(self.body)
        elif status == 404:
            context = self.connection.context
            if context["resource"] == "zone":
                raise ZoneDoesNotExistError(value="",
                                            driver=self,
                                            zone_id=context["id"])
            elif context["resource"] == "record":
                raise RecordDoesNotExistError(value="",
                                              driver=self,
                                              record_id=context["id"])
        elif status != 503:
            try:
                body = ET.XML(self.body)
            except Exception:
                raise MalformedResponseError("Failed to parse XML",
                                             body=self.body)

            errors = []
            for error in findall(element=body, xpath="error"):
                errors.append(error.text)

            raise ZerigoError(code=status, errors=errors)

        return self.body
Example #27
0
 def _to_sizes(self, element):
     """
     Create a NodeSize object given a libcloud XML element.
     Extra information is available in nodesize.extra dictionary.
     """
     # elem_sizes = element/availabilityZoneInfo/item.
     # elem_sizes[0]  == zone and ip
     # elem_sizes[1]  == column descriptors
     # elem_sizes[2]+ == occupancy and type information.
     elem_sizes = findall(element=element,
                          xpath='availabilityZoneInfo/item',
                          namespace=NAMESPACE)[2:]
     sizes = []
     for s in elem_sizes:
         pieces = re.findall(r'\w+|!/', s[1].text)
         # expected format of pieces is
         # ['0058', '0215', '2', '4096', '10']
         # ['remaining', 'total', 'cpu', 'ram', 'disk']
         id = s[0].text.split()[1]
         size_info = {'id': id,
                      'name': id,
                      'ram': int(pieces[3]),
                      'disk': int(pieces[4]),
                      'bandwidth': 0,
                      'price': 0}
         node_size = NodeSize(driver=self, **size_info)
         node_size.extra = {'cpu': int(pieces[2]),
                            'occupancy': {'remaining': int(pieces[0]),
                                          'total': int(pieces[1])}}
         sizes.append(node_size)
     return sizes
Example #28
0
    def _to_vlans(self, object):
        vlans = []
        locations = self.list_locations()
        for element in findall(object, 'vlan', TYPES_URN):
            vlans.append(self._to_vlan(element, locations=locations))

        return vlans
Example #29
0
    def ex_create_network_domain(self,
                                 location,
                                 name,
                                 service_plan,
                                 description=None):
        """
        Deploy a new network domain to a data center
        """
        create_node = ET.Element('deployNetworkDomain', {'xmlns': TYPES_URN})
        ET.SubElement(create_node, "datacenterId").text = location.id
        ET.SubElement(create_node, "name").text = name
        if description is not None:
            ET.SubElement(create_node, "description").text = description
        ET.SubElement(create_node, "type").text = service_plan

        response = self.connection.request_with_orgId_api_2(
            'network/deployNetworkDomain',
            method='POST',
            data=ET.tostring(create_node)).object

        network_domain_id = None

        for info in findall(response, 'info', TYPES_URN):
            if info.get('name') == 'networkDomainId':
                network_domain_id = info.get('value')

        return DimensionDataNetworkDomain(id=network_domain_id,
                                          name=name,
                                          description=description,
                                          location=location,
                                          status=NodeState.RUNNING,
                                          plan=service_plan)
Example #30
0
    def _to_network_domains(self, object):
        network_domains = []
        locations = self.list_locations()
        for element in findall(object, 'networkDomain', TYPES_URN):
            network_domains.append(self._to_network_domain(element, locations))

        return network_domains
Example #31
0
    def _to_ip_blocks(self, object):
        blocks = []
        locations = self.list_locations()
        for element in findall(object, 'publicIpBlock', TYPES_URN):
            blocks.append(self._to_ip_block(element, locations))

        return blocks
    def _to_securityGroup(self, element):

        ipPermissions = []
        for rs in findall(element=element,
                          xpath='ipPermissions/item',
                          namespace=NAMESPACE):
            ipPermissions.append(self._to_ipPermissions(rs))

        n = SecurityGroup(
            ownerId=findattr(element=element,
                             xpath="ownerId",
                             namespace=NAMESPACE),
            groupId=findattr(element=element,
                             xpath="groupId",
                             namespace=NAMESPACE),
            groupName=findattr(element=element,
                               xpath="groupName",
                               namespace=NAMESPACE),
            groupDescription=findattr(element=element,
                                      xpath="groupDescription",
                                      namespace=NAMESPACE),
            vpcId=findattr(element=element, xpath="vpcId",
                           namespace=NAMESPACE),
            ipPermissions=ipPermissions,
            ipPermissionsEgress=findattr(element=element,
                                         xpath="ipPermissionsEgress",
                                         namespace=NAMESPACE),
            tagSet=findattr(element=element,
                            xpath="tagSet",
                            namespace=NAMESPACE),
        )
        return n
Example #33
0
    def _to_networks(self, object):
        networks = []
        locations = self.list_locations()
        for element in findall(object, 'network', NETWORK_NS):
            networks.append(self._to_network(element, locations))

        return networks
Example #34
0
    def _to_nat_rules(self, object, network_domain):
        rules = []
        for element in findall(object, 'natRule', TYPES_URN):
            rules.append(
                self._to_nat_rule(element, network_domain))

        return rules
Example #35
0
    def _to_network_domains(self, object):
        network_domains = []
        locations = self.list_locations()
        for element in findall(object, 'networkDomain', TYPES_URN):
            network_domains.append(self._to_network_domain(element, locations))

        return network_domains
    def terminateInstance(self, instanceid):
        params = {'Action': 'TerminateInstances', 'InstanceId': instanceid}
        try:
            elem = self.connection.request(self.path, params=params).object
            previousStates = []
            for rs in findall(element=elem,
                              xpath='instancesSet/item',
                              namespace=NAMESPACE):
                code = findtext(element=rs,
                                xpath='previousState/code',
                                namespace=NAMESPACE)
                name = findtext(element=rs,
                                xpath='previousState/name',
                                namespace=NAMESPACE)
                previousStates.append({"code": code, "name": name})

            if len(previousStates) > 1:
                #複数のインスタンスが削除された場合
                raise IaasException("EPROCESS-000108", [
                    instanceid,
                ])

            #実行ログ
            self.logger.info(None, "IPROCESS-100117", [
                instanceid,
            ])

            return previousStates[0]
        except Exception:
            # インスタンス削除失敗時
            raise IaasException("EPROCESS-000107", [
                instanceid,
            ])
        return None
    def ex_describe_tags(self, resource):
        """
        Return a dictionary of tags for a resource (Node or StorageVolume).

        @param  resource: resource which should be used
        @type   resource: L{Node} or L{StorageVolume}

        @return: dict Node tags
        @rtype: C{dict}
        """
        params = {'Action': 'DescribeTags',
                  'Filter.0.Name': 'resource-id',
                  'Filter.0.Value.0': resource.id,
                  'Filter.1.Name': 'resource-type',
                  'Filter.1.Value.0': 'instance',
                  }

        result = self.connection.request(self.path,
                                         params=params.copy()).object

        tags = {}
        for element in findall(element=result, xpath='tagSet/item',
                               namespace=NAMESPACE):
            key = findtext(element=element, xpath='key', namespace=NAMESPACE)
            value = findtext(element=element,
                             xpath='value', namespace=NAMESPACE)

            tags[key] = value
        return tags
Example #38
0
 def _to_policy_types(self, data):
     xpath = 'DescribeLoadBalancerPolicyTypesResult/'
     xpath += 'PolicyTypeDescriptions/member'
     return [
         findtext(element=el, xpath='PolicyTypeName', namespace=NS)
         for el in findall(element=data, xpath=xpath, namespace=NS)
     ]
Example #39
0
    def _to_volume(self, element, name=None):
        element_as = findall(element=element,
                             xpath='attachmentSet/item', namespace=NAMESPACE)
        volume = {}
        for key in ['volumeId', 'size', 'createTime',
                    'status', 'attachmentSet']:
            volume[key] = findtext(element=element,
                                   xpath=key, namespace=NAMESPACE)
        if name is None:
            name = volume['volumeId']
        svolume = StorageVolume(id=volume['volumeId'],
                                name=name,
                                size=int(volume['size']),
                                driver=self)
        try:
            created_time = datetime.strptime(volume['createTime'],
                                             '%Y-%m-%dT%H:%M:%S.%fZ')
        except ValueError:  # Wrong Format, try again..
            created_time = datetime.strptime(volume['createTime'],
                                             '%Y-%m-%dT%H:%M:%SZ')

        svolume.extra = {
            'createTime': created_time,
            'status': volume['status'],
            'attachmentSet': [self._get_attachment_set(element_as)]}
        return svolume
Example #40
0
 def get_zone(self, zone_id):
     self.connection.set_context({'zone_id': zone_id})
     uri = API_ROOT + 'hostedzone/' + zone_id
     data = self.connection.request(uri).object
     elem = findall(element=data, xpath='HostedZone',
                    namespace=NAMESPACE)[0]
     return self._to_zone(elem)
Example #41
0
    def parse_error(self):
        status = int(self.status)

        if status == 401:
            if not self.body:
                raise InvalidCredsError(str(self.status) + ': ' + self.error)
            else:
                raise InvalidCredsError(self.body)
        elif status == 404:
            context = self.connection.context
            if context['resource'] == 'zone':
                raise ZoneDoesNotExistError(value='',
                                            driver=self,
                                            zone_id=context['id'])
            elif context['resource'] == 'record':
                raise RecordDoesNotExistError(value='',
                                              driver=self,
                                              record_id=context['id'])
        elif status != 503:
            try:
                body = ET.XML(self.body)
            except:
                raise MalformedResponseError('Failed to parse XML',
                                             body=self.body)

            errors = []
            for error in findall(element=body, xpath='error'):
                errors.append(error.text)

            raise ZerigoError(code=status, errors=errors)

        return self.body
Example #42
0
    def _to_vlans(self, object):
        vlans = []
        locations = self.list_locations()
        for element in findall(object, 'vlan', TYPES_URN):
            vlans.append(self._to_vlan(element, locations=locations))

        return vlans
Example #43
0
 def ex_list_ip_groups(self, details=False):
     uri = '/shared_ip_groups/detail' if details else '/shared_ip_groups'
     resp = self.connection.request(uri,
                                    method='GET')
     groups = findall(resp.object, 'sharedIpGroup',
                            self.XML_NAMESPACE)
     return [self._to_shared_ip_group(el) for el in groups]
Example #44
0
    def ex_describe_all_addresses(self, only_allocated=False):
        """
        Return all the Elastic IP addresses for this account
        optionally, return only the allocated addresses

        @keyword  only_allocated: If true, return only those addresses
                                  that are associated with an instance
        @type     only_allocated: C{string}

        @return   list list of elastic ips for this particular account.
        """
        params = {'Action': 'DescribeAddresses'}

        result = self.connection.request(self.path,
                                         params=params.copy()).object

        # the list which we return
        elastic_ip_addresses = []
        for element in findall(element=result, xpath='addressesSet/item',
                               namespace=NAMESPACE):
            instance_id = findtext(element=element, xpath='instanceId',
                                   namespace=NAMESPACE)

            # if only allocated addresses are requested
            if only_allocated and not instance_id:
                continue

            ip_address = findtext(element=element, xpath='publicIp',
                                  namespace=NAMESPACE)

            elastic_ip_addresses.append(ip_address)

        return elastic_ip_addresses
Example #45
0
    def ex_describe_tags(self, resource):
        """
        Return a dictionary of tags for a resource (Node or StorageVolume).

        @type node: C{Node}
        @param node: Node instance

        @return dict Node tags
        """
        params = {'Action': 'DescribeTags',
                  'Filter.0.Name': 'resource-id',
                  'Filter.0.Value.0': resource.id,
                  'Filter.1.Name': 'resource-type',
                  'Filter.1.Value.0': 'instance',
                  }

        result = self.connection.request(self.path,
                                         params=params.copy()).object

        tags = {}
        for element in findall(element=result, xpath='tagSet/item',
                               namespace=NAMESPACE):
            key = findtext(element=element, xpath='key', namespace=NAMESPACE)
            value = findtext(element=element,
                             xpath='value', namespace=NAMESPACE)

            tags[key] = value
        return tags
Example #46
0
    def ex_create_listener_rule(
        self,
        listener,
        priority,
        target_group,
        action="forward",
        condition_field=None,
        condition_value=None,
    ):
        """
        Create a rule for listener.

        :param listener: Listener object where to create rule
        :type listener: :class:`ALBListener`

        :param priority: The priority for the rule. A listener can't have
                        multiple rules with the same priority.
        :type priority: ``str``

        :param target_group: Target group object to associate with rule
        :type target_group: :class:`ALBTargetGroup`

        :param action: Action for the rule, valid value is 'forward'
        :type action: ``str``

        :param condition_field: Rule condition field name. The possible values
                                are 'host-header' and 'path-pattern'.
        :type condition_field: ``str``

        :param condition_value: Value to match. Wildcards are supported, for
                                example: '/img/*'

        :return: Rule object
        :rtype: :class:`ALBRule`
        """

        condition_field = condition_field or ""
        condition_value = condition_value or ""

        # mandatory params
        params = {
            "Action": "CreateRule",
            "ListenerArn": listener.id,
            "Priority": priority,  # Valid Range: Min value of 1. Max: 99999.
            "Actions.member.1.Type": action,
            "Actions.member.1.TargetGroupArn": target_group.id,
            # Valid values are host-header and path-pattern.
            "Conditions.member.1.Field": condition_field,
            "Conditions.member.1.Values.member.1": condition_value,
        }

        data = self.connection.request(ROOT, params=params).object

        xpath = "CreateRuleResult/Rules/member"
        for el in findall(element=data, xpath=xpath, namespace=NS):
            rule = self._to_rule(el)
            rule.listener = listener

        return rule
Example #47
0
    def _to_firewall_rules(self, object, network_domain):
        rules = []
        locations = self.list_locations()
        for element in findall(object, 'firewallRule', TYPES_URN):
            rules.append(
                self._to_firewall_rule(element, locations, network_domain))

        return rules
Example #48
0
    def _to_zones(self, elem):
        zones = []

        for item in findall(element=elem, xpath='zone'):
            zone = self._to_zone(elem=item)
            zones.append(zone)

        return zones
Example #49
0
    def _to_records(self, elem, zone):
        records = []

        for item in findall(element=elem, xpath='host'):
            record = self._to_record(elem=item, zone=zone)
            records.append(record)

        return records
Example #50
0
    def _to_images(self, object, ex_only_active):
        images = []
        for image in findall(object, 'image', self.XML_NAMESPACE):
            if ex_only_active and image.get('status') != 'ACTIVE':
                continue
            images.append(self._to_image(image))

        return images
    def _get_state_boolean(self, element):
        """
        Checks for the instances's state
        """
        state = findall(element=element,
                        xpath='instancesSet/item/currentState/name',
                        namespace=NAMESPACE)[0].text

        return state in ('stopping', 'pending', 'starting')
    def describeKeyPairs(self):
        params = {"Action": "DescribeKeyPairs"}

        elem = self.connection.request(self.path, params=params).object

        keypairs = []
        for rs in findall(element=elem, xpath="keySet/item", namespace=NAMESPACE):
            keypairs.append(self._to_keypair(rs))

        return keypairs
    def registerInstancesWithLoadBalancer(self, instances, loadBalancerName):
        params = {'Action': 'RegisterInstancesWithLoadBalancer', 'LoadBalancerName':loadBalancerName}

        for i, instance in enumerate(instances,1):
            params['Instances.member.%d.InstanceId' % i] = instance

        elem = self.connection.request(self.path, params=params).object

        instanceids = []
        for rs in findall(element=elem, xpath='RegisterInstancesWithLoadBalancerResult/Instances/member', namespace=NAMESPACE):
            instanceids.append(findattr(element=rs, xpath="InstanceId", namespace=NAMESPACE))

        return instanceids