Exemplo n.º 1
0
    def attach_volume(self, **kwargs):
        """Attach volume to a Power Virtual Instance

        :param instance: Instance name or ID
        :type instance: str
        :param pvm: Power Virtual Instance name or ID
        :type pvm: str
        :param volume: Volume name or ID
        :type volume: str
        :return: Attachment status
        :rtype: dict
        """
        args = ["instance", "pvm", "volume"]
        check_args(args, **kwargs)

        # Build dict of argument and assign default value when needed
        args = {
            'instance': kwargs.get('instance'),
            'pvm': kwargs.get('pvm'),
            'volume': kwargs.get('volume'),
        }

        try:
            # Check if cloud instance exists and retrieve information
            ci_info = self.instance.get_instance(args['instance'])
            if "errors" in ci_info:
                return ci_info

            # Check if pvm exists and retrieve information
            pvm_info = self.pvm.get_pvm(args['instance'], args['pvm'])
            if "errors" in pvm_info:
                return pvm_info

            # Check if volume exists and retrieve information
            vol_info = self.get_volume(ci_info["name"], args["volume"])
            if "errors" in vol_info:
                return vol_info

            # Connect to api endpoint for cloud-instances
            path = ("/pcloud/v1/cloud-instances/{}/pvm-instances/{}"
                    "/volumes/{}".format(ci_info["name"],
                                         pvm_info["pvmInstanceID"],
                                         vol_info["volumeID"]))

            data = qw("power", "POST", path, headers())

            # Return data
            if data["response"].status != 200:
                return data["data"]

            # Return status
            payload = {"status": "attached"}
            return resource_created(payload)

        except Exception as error:
            print("Error attaching volume {} to Power Virtual Instance {}"
                  " from cloud instance {}. {}".format(args["volume"],
                                                       args['pvm'],
                                                       args['instance'],
                                                       error))
Exemplo n.º 2
0
    def delete_record(self, **kwargs):
        """Delete a record

        :param record: Record name
        :type record: str
        :param zone: Zone name
        :type zone: str
        """
        args = set(["record", "zone"])
        check_args(args, **kwargs)

        args = {
            'record': kwargs.get('record'),
            'zone': kwargs.get('zone'),
        }
        record = self.get_record(record=args["record"], zone=args["zone"])
        if "errors" in record:
            for key_name in record["errors"]:
                if key_name["code"] == "not_found":
                    return resource_not_found()
        try:
            self.dns.delete_record(record["id"])
        except Exception as error:
            print("Error while deleting record. {}".format(error))
            raise
Exemplo n.º 3
0
    def create_snapshot(self, **kwargs):
        """Creates a snapshot on the given file volume

        :param volume_id: The volume ID
        :type volume_id: int
        :param notes: The notes or "name" to assign the snapshot
        :type notes: str
        :return: Returns the id of the new snapshot
        :rtype: str
        """
        args = ["volume_id", "notes"]
        check_args(args, **kwargs)

        # Build dict of argument and assign default value when needed
        args = {
            'volume_id': kwargs.get('volume_id'),
            'notes': kwargs.get('notes'),
        }

        try:
            return self.file.create_snapshot(
                args['volume_id'],
                notes=args['notes'])
        except sl.SoftLayer.SoftLayerAPIError as error:
            return resource_error(error.faultCode, error.faultString)
Exemplo n.º 4
0
    def download_file(self, **kwargs):
        """Download file from a S3 object

        :param bucket: Bucket name
        :type bucket: str
        :param path: The path to the file to download to
        :type path: str
        :param key: The name of the key to download from
        :type key: str
        :return: Download status
        :rtype: dict
        """
        args = ["bucket", "path", "key"]
        check_args(args, **kwargs)

        # Build dict of argument and assign default value when needed
        args = {
            'bucket': kwargs.get('bucket'),
            'key': kwargs.get('key'),
            'path': kwargs.get('path'),
        }

        try:
            result = self.client.download_file(
                args["bucket"], args["key"], args["path"])
            if result is not None:
                return result

            msg = {"object": args["key"], "path": args['path'],
                   "status": "downloaded"}
            return resource_created(msg)

        except Exception as error:
            return resource_error("unable_to_download_object", error)
Exemplo n.º 5
0
    def order_modified_volume(self, **kwargs):
        """Places an order for modifying an existing file volume

        :param volume_id: The ID of the volume to be modified
        :type volume_id: int
        :param new_size: The new size/capacity for the volume
        :type new_size: int
        :param new_iops: The new IOPS for the volume
        :type new_iops: int
        :param new_tier_level: The new tier level for the volume
        :type new_tier_level: str
        :return: Returns a SoftLayer_Container_Product_Order_Receipt
        :rtype: dict
        """

        args = ["volume_id", "new_size", "new_iops", "new_tier_level"]
        check_args(args, **kwargs)

        # Build dict of argument and assign default value when needed
        args = {
            'volume_id': kwargs.get('storage_type'),
            'new_size': kwargs.get('new_size'),
            'new_iops': kwargs.get('new_iops'),
            'new_tier_level': kwargs.get('new_tier_level')
        }

        try:
            return self.file.order_modified_volume(
                args['volume_id'],
                args['new_size'],
                args['new_iops'],
                args['new_tier_level'])
        except sl.SoftLayer.SoftLayerAPIError as error:
            return resource_error(error.faultCode, error.faultString)
Exemplo n.º 6
0
    def order_snapshot_space(self, **kwargs):
        """Orders snapshot space for the given file volume

        :param volume_id: The ID of the volume
        :type volume_id: int
        :param capacity: The capacity to order, in GB
        :type capacity: int
        :param tier: The tier level of the file volume, in IOPS per GB
        :type tier: int
        :param upgrade: Flag to indicate if this order is an upgrade
        :type upgrade: bool
        :return: Returns a SoftLayer_Container_Product_Order_Receipt
        :rtype: dict
        """

        args = ["volume_id", "capacity", "tier", "upgrade"]
        check_args(args, **kwargs)

        # Build dict of argument and assign default value when needed
        args = {
            'volume_id': kwargs.get('storage_type'),
            'capacity': kwargs.get('capacity'),
            'tier': kwargs.get('tier'),
            'upgrade': kwargs.get('upgrade')
        }

        try:
            return self.file.order_snapshot_space(args['volume_id'],
                                                  args['capacity'],
                                                  args['tier'],
                                                  args['upgrade'])
        except sl.SoftLayer.SoftLayerAPIError as error:
            return resource_error(error.faultCode, error.faultString)
Exemplo n.º 7
0
    def export_instance_image(self, **kwargs):
        """Export an image for a cloud instance

        :param instance: Cloud instance ID
        :type instance: str
        :param image: Image ID of existing source image
        :type image: str
        :param region: Cloud Storage Region
        :type region: str, optional
        :param bucket: Cloud Storage bucket name
        :type bucket: str, optional
        :param access_key: Cloud Storage access key
        :type access_key: str, optional
        :param secret_key: Cloud Storage secret key
        :type secret_key: str, optional
        :return: Export image information
        :rtype: dict
        """
        args = ["instance", "image"]
        check_args(args, **kwargs)

        # Build dict of argument and assign default value when needed
        args = {
            'instance': kwargs.get('source'),
            'image': kwargs.get('image'),
            'region': kwargs.get('region'),
            'bucketName': kwargs.get('bucket'),
            'accessKey': kwargs.get('access_key'),
            'secretKey': kwargs.get('secret_key'),
        }

        # Construct payload
        payload = {}
        for key, value in args.items():
            if key != "instance" and key != "image" and value is not None:
                payload[key] = value

        try:
            # Check if cloud instance exists and retrieve information
            ci_info = self.instance.get_instance(args['instance'])
            if "errors" in ci_info:
                return ci_info

            # Check if image exists and retrieve information
            image_info = self.get_instance_image(ci_info["name"],
                                                 args["image"])
            if "errors" in image_info:
                return image_info

            # Connect to api endpoint for cloud-instances
            path = ("/pcloud/v1/cloud-instances/{}/images/{}/export".format(
                ci_info["name"], image_info["imageID"]))

            # Return data
            return qw("power", "POST", path, headers(),
                      json.dumps(payload))["data"]

        except Exception as error:
            print("Error exporting image {} for cloud instance {}. {}".format(
                args['image'], args['instance'], error))
Exemplo n.º 8
0
    def cancel_file_volume(self, **kwargs):
        """Cancels the given file storage volume

        :param volume_id: The volume ID
        :type volume_id: int
        :param reason: The reason for cancellation
        :type reason: str
        :param immediate: Cancel immediately or on anniversary date
        :type immediate: bool
        """
        args = ["volume_id", "reason", "immediate"]
        check_args(args, **kwargs)

        # Build dict of argument and assign default value when needed
        args = {
            'volume_id': kwargs.get('volume_id'),
            'reason': kwargs.get('reason'),
            'immediate': kwargs.get('immediate')
        }

        try:
            return self.file.cancel_file_volume(args['volume_id'],
                                                reason=args['reason'],
                                                immediate=args['immediate'])
        except sl.SoftLayer.exceptions.SoftLayerError:
            return({"msg": "Storage Volume was already cancelled"})
        except sl.SoftLayer.SoftLayerAPIError as error:
            return resource_error(error.faultCode, error.faultString)
Exemplo n.º 9
0
    def authorize_host_to_volume(self, **kwargs):
        """Authorizes hosts to File Storage Volumes

        :param volume_id: The File volume to authorize hosts to
        :type volume_id: str
        :param hardware_ids: A List of SoftLayer_Hardware IDs
        :type hardware_ids: list
        :param virtual_guest_ids: A List of SoftLayer_Virtual_Guest IDs
        :type virtual_guest_ids: list
        :param ip_address_ids: A List of SoftLayer_Network_Subnet_IpAddress IDs
        :type ip_address_ids: list
        :param subnet_ids: A List of SoftLayer_Network_Subnet ids
        """
        args = ["volume_id", "hardware_ids", "virtual_guest_ids",
                "ip_address_ids", "subnet_ids"]
        check_args(args, **kwargs)

        # Build dict of argument and assign default value when needed
        args = {
            'volume_id': kwargs.get('volume_id'),
            'hardware_ids': kwargs.get('hardware_ids') or None,
            'virtual_guest_ids': kwargs.get('virtual_guest_ids') or None,
            'ip_address_ids': kwargs.get('ip_address_ids') or None,
            'subnet_ids': kwargs.get('subnet_ids') or None
        }
        try:
            self.file.authorize_host_to_volume(args['volume_id'],
                                               args['hardware_ids'],
                                               args['virtual_guest_ids'],
                                               args['ip_address_ids'],
                                               args['subnet_ids'])
        except sl.SoftLayer.SoftLayerAPIError as error:
            return resource_error(error.faultCode, error.faultString)
Exemplo n.º 10
0
    def failover_to_replicant(self, **kwargs):
        """Failover to a volume replicant

        :param volume_id: The ID of the volume
        :type volume_id: int
        :param replicant_id: ID of replicant to failback from
        :type replicant_id: int
        :param immediate: Flag indicating if failover is immediate
        :type immediate: bool
        :return: Returns whether failover was successful or not
        """

        args = ["volume_id", "replicant_id"]
        check_args(args, **kwargs)

        # Build dict of argument and assign default value when needed
        args = {
            'volume_id': kwargs.get('volume_id'),
            'replicant_id': kwargs.get('replicant_id'),
            'immediate': kwargs.get('immediate')
        }

        try:
            return self.file.failover_to_replicant(
                args['volume_id'],
                args['replicant_id'],
                immediate=args['immediate'])
        except sl.SoftLayer.SoftLayerAPIError as error:
            return resource_error(error.faultCode, error.faultString)
Exemplo n.º 11
0
    def create_group(self, **kwargs):
        """Create resource group

        :param name: Name of the resource group
        :type name: str
        :param account_id: The account ID of the resource group
        :type account_id: str
        """
        args = ["name", "account_id"]
        check_args(args, **kwargs)

        # Build dict of argument and assign default value when needed
        args = {
            'name': kwargs.get('name'),
            'account_id': kwargs.get('account_id'),
        }

        # Construct payload
        payload = {}
        for key, value in args.items():
            if value is not None:
                payload[key] = value

        try:
            # Connect to api endpoint for resource_groups
            path = ("/v2/resource_groups")

            # Return data
            return qw("rg", "POST", path, headers(),
                      json.dumps(payload))["data"]

        except Exception as error:
            print("Error create resource group. {}".format(error))
            raise
Exemplo n.º 12
0
    def get_record_by_value(self, **kwargs):
        """Get record by value
        
        :param record: Record value
        :type record: str
        :param zone: Zone name
        :type zone: str
        """
        args = set(["record", "zone"])
        check_args(args, **kwargs)

        args = {
            'record': kwargs.get('record'),
            'zone': kwargs.get('zone'),
        }

        records = self.get_records(zone=args["zone"])
        if "errors" in records:
            for key_name in records["errors"]:
                if key_name["code"] == "not_found":
                    return resource_not_found()

        for record in records:
            if record["data"] == args["record"]:
                return record
        return resource_not_found()
Exemplo n.º 13
0
    def get_dns_zone(self, **kwargs):
        """Get a specific DNS zone hosted by a resource instance

        :param dns_zone: DNS zone name or ID to query
        :type dns_zone: str
        :param resource_instance: Name or GUID of the resource instance
        :type resource_instance: str
        :return: DNS zone information
        :rtype: dict
        """
        # Required parameters
        args = ['dns_zone', 'resource_instance']
        check_args(args, **kwargs)

        # Set default value if required paramaters are not defined
        args = {
            'dns_zone': kwargs.get('dns_zone'),
            'resource_instance': kwargs.get('resource_instance'),
        }
        by_name = self.get_dns_zone_by_name(
            dns_zone=args['dns_zone'],
            resource_instance=args['resource_instance'])
        if "errors" in by_name:
            for key_name in by_name["errors"]:
                if key_name["code"] == "not_found":
                    by_guid = self.get_dns_zone_by_id(
                        dns_zone=args['dns_zone'],
                        resource_instance=args['resource_instance'])
                    if "errors" in by_guid:
                        return by_guid
                    return by_guid
                return by_name
        else:
            return by_name
Exemplo n.º 14
0
    def get_dns_zones(self, **kwargs):
        """Get all DNS zones hosted by a resource instance

        :param resource_instance: Name or GUID of the resource instance
        :type resource_instance: str
        :return: DNS zones
        :rtype: list
        """
        args = ['resource_instance']
        check_args(args, **kwargs)

        # Set default value if required paramaters are not defined
        args = {
            'resource_instance': kwargs.get('resource_instance'),
        }

        # Get resource instance guid
        temp_ri = self.resource_instance.get_resource_instance(
            args['resource_instance'])
        if "errors" in temp_ri:
            return temp_ri
        resource_instance_guid = temp_ri["guid"]

        try:
            # Connect to api endpoint for dns zones
            path = ("/v1/instances/{}/dnszones").format(resource_instance_guid)

            return qw("dns", "GET", path, headers())["data"]
        except Exception as error:
            print("Error creating dns zone. {}".format(error))
            raise
Exemplo n.º 15
0
    def get_record_by_name(self, **kwargs):
        """Get record by name

        :param record: Record name
        :type record: str
        :param zone: Zone name
        :type zone: str
        """
        required_args = set(["record", "zone"])
        check_args(required_args, **kwargs)

        args = {
            'record': kwargs.get('record'),
            'zone': kwargs.get('zone'),
        }
        zone_id = self.get_zone_id(args['zone'])
        if not isinstance(zone_id, int):
            if "errors" in zone_id:
                for key_name in zone_id["errors"]:
                    if key_name["code"] == "not_found":
                        return resource_not_found()

        records = self.get_records(zone=args["zone"])
        for record in records:
            if record["host"] == args["record"]:
                return record
        return resource_not_found()
Exemplo n.º 16
0
    def clone_volume(self, **kwargs):
        """Create a clone from a volume

        :param instance: Instance name or ID
        :type instance: str
        :param volumes: List of volumes to be cloned
        :type volumes: list
        :param name: Display name for the new cloned volumes. Cloned Volume
            names will be prefixed with 'clone-'. If multiple volumes cloned
            they will be suffix with a '-' and an incremental number starting
            with 1.
        :type name: str
        :param prefix_name: Prefix to use when naming the new cloned volumes
        :type prefix_name: str, optional
        :return: Volume clone information
        :rtype: dict
        """
        args = ["instance", "volumes", "name"]
        check_args(args, **kwargs)

        # Build dict of argument and assign default value when needed
        args = {
            'instance': kwargs.get('instance'),
            'volumeIDs': kwargs.get('volumes'),
            'displayName': kwargs.get('name'),
            'namingPrefix': kwargs.get('prefix_name'),
        }

        # Check if cloud instance exists and retrieve information
        ci_info = self.instance.get_instance(args['instance'])
        if "errors" in ci_info:
            return ci_info

        # Construct payload
        payload = {}
        for key, value in args.items():
            if key != "instance" and value is not None:
                if key == "volumeIDs":
                    vl = []
                    for volume in args["volumeIDs"]:
                        vol_info = self.get_volume(ci_info["name"], volume)
                        if "errors" in vol_info:
                            return vol_info
                        vl.append(vol_info["volumeID"])
                    payload["volumeIDs"] = vl
                payload[key] = value

        try:
            # Connect to api endpoint for cloud-instances
            path = ("/pcloud/v1/cloud-instances/{}/volumes/clone".format(
                ci_info["name"]))

            # Return data
            return qw("power", "POST", path, headers(),
                      json.dumps(payload))["data"]

        except Exception as error:
            print("Error creating clone from volume(s) {} for cloud instance"
                  " {}. {}".format(args["volumeIDs"], args['instance'], error))
Exemplo n.º 17
0
    def add_permitted_network(self, **kwargs):
        """Add permitted network to DNS zone

        :param dns_zone: DNS zone name
        :type dns_zone: str
        :param resource_instance: Name or GUID of the resource instance
        :type resource_instance: str
        :param vpc: The allowed VPC name or ID
        :type vpc: str
        """
        # Required parameters
        args = ['dns_zone', 'resource_instance', 'vpc']
        check_args(args, **kwargs)

        # Set default value if required paramaters are not defined
        args = {
            'dns_zone': kwargs.get('dns_zone'),
            'vpc': kwargs.get('vpc'),
            'resource_instance': kwargs.get('resource_instance'),
        }

        # get resource instance guid
        temp_ri = self.resource_instance.get_resource_instance(
            args['resource_instance'])
        if "errors" in temp_ri:
            return temp_ri
        resource_instance_guid = temp_ri["guid"]

        # get vpc crn
        temp_vpc = self.vpc.get_vpc(args["vpc"])
        if "errors" in temp_vpc:
            return temp_vpc
        vpc_crn = temp_vpc["crn"]

        # Get zone ID
        zone_id = self.get_dns_zone_id(
            dns_zone=args['dns_zone'],
            resource_instance=resource_instance_guid)
        if "errors" in zone_id:
            return zone_id

        payload = {}

        # Construct payload
        payload["type"] = "vpc"
        payload["permitted_network"] = {}
        payload["permitted_network"]["vpc_crn"] = vpc_crn

        try:
            # Connect to api endpoint for permitted network
            path = ("/v1/instances/{}/dnszones/{}/permitted_networks").format(
                resource_instance_guid, zone_id)

            return qw("dns", "POST", path, headers(),
                      json.dumps(payload))["data"]

        except Exception as error:
            print("Error adding permitted network. {}".format(error))
            raise
Exemplo n.º 18
0
    def create_security_group(self, **kwargs):
        """Create security group

        :param name: The user-defined name for this security group
        :type name: str, optional
        :param resource_group: The resource group to use
        :type security_group: str, optional
        :param vpc: The VPC this security group is to be a part of
        :type vpc: str
        :param rules: Array of rule prototype objects for rules to be created
            for this security group
        :type rules: list, optional
        """
        args = ["vpc"]
        check_args(args, **kwargs)

        # Build dict of argument and assign default value when needed
        args = {
            'name': kwargs.get('name'),
            'resource_group': kwargs.get('resource_group'),
            'vpc': kwargs.get('vpc'),
            'rules': kwargs.get('rules'),
        }

        # Construct payload
        payload = {}
        for key, value in args.items():
            if value is not None:
                if key == "vpc":
                    vpc_info = self.vpc.get_vpc(args["vpc"])
                    if "errors" in vpc_info:
                        return vpc_info
                    payload["vpc"] = {"id": vpc_info["id"]}
                elif key == "resource_group":
                    rg_info = self.rg.get_resource_group(
                        args["resource_group"])
                    if "errors" in rg_info:
                        return rg_info
                    payload["resource_group"] = {"id": rg_info["id"]}
                elif key == "rules":
                    rs = []
                    for sg_rules in args["rules"]:
                        rs.append(sg_rules)
                    payload["rules"] = rs
                else:
                    payload[key] = value

        try:
            # Connect to api endpoint for security_groups
            path = ("/v1/security_groups?version={}&generation={}".format(
                self.cfg["version"], self.cfg["generation"]))

            # Return data
            return qw("iaas", "POST", path, headers(),
                      json.dumps(payload))["data"]

        except Exception as error:
            print("Error creating security group. {}".format(error))
            raise
Exemplo n.º 19
0
    def create_address_prefix(self, **kwargs):
        """Create address prefix

        :param vpc: VPC name or ID
        :type vpc: str
        :param name: The user-defined name for this address prefix
        :type name: str, optional
        :param cidr: The CIDR block for this address prefix
        :type cidr: str
        :param is_default: Indicates whether this is the default prefix for
            this zone in this VPC
        :type is_default: bool, optional
        :param zone: The zone this address prefix is to belong to
        :type zone: str
        :return: Address prefix information
        :rtype: dict
        """
        args = ["vpc", "cidr", "zone"]
        check_args(args, **kwargs)

        # Build dict of argument and assign default value when needed
        args = {
            'vpc': kwargs.get('vpc'),
            'name': kwargs.get('name'),
            'cidr': kwargs.get('cidr'),
            'is_default': kwargs.get('is_default', False),
            'zone': kwargs.get('zone'),
        }

        # Construct payload
        payload = {}
        for key, value in args.items():
            if key != "vpc" and value is not None:
                if key == "zone":
                    payload["zone"] = {"name": args["zone"]}
                else:
                    payload[key] = value

        # Check if VPC exists and get information
        vpc_info = self.get_vpc(args['vpc'])
        if "errors" in vpc_info:
            return vpc_info

        try:
            # Connect to api endpoint for vpcs
            path = ("/v1/vpcs/{}/address_prefixes?version={}"
                    "&generation={}".format(vpc_info["id"],
                                            self.cfg["version"],
                                            self.cfg["generation"]))

            # Return data
            return qw("iaas", "POST", path, headers(),
                      json.dumps(payload))["data"]

        except Exception as error:
            print("Error creating address prefix in VPC {}. {}".format(
                args['vpc'], error))
            raise
Exemplo n.º 20
0
    def create_ike_policy(self, **kwargs):
        """Create IKE policy

        :param name: The user-defined name for this IKE policy
        :type name: str, optional
        :param resource_group: The resource group to use
        :type resource_group: str, optional
        :param authentication_algorithm: The authentication algorithm
        :type authentication_algorithm: str
        :param dh_group: The Diffie-Hellman group
        :type dh_group: str
        :param encryption_algorithm: The encryption algorithm
        :type encryption_algorithm: str
        :param ike_version: The IKE protocol version
        :type ike_version: int
        :param key_lifetime: The key lifetime in seconds
        :type key_lifetime: int, optional
        """
        args = ["authentication_algorithm", "dh_group",
                "encryption_algorithm", "ike_version"]
        check_args(args, **kwargs)

        # Build dict of argument and assign default value when needed
        args = {
            'name': kwargs.get('name'),
            'resource_group': kwargs.get('resource_group'),
            'authentication_algorithm': kwargs.get('authentication_algorithm'),
            'dh_group': kwargs.get('dh_group'),
            'encryption_algorithm': kwargs.get('encryption_algorithm'),
            'ike_version': kwargs.get('ike_version'),
            'key_lifetime': kwargs.get('key_lifetime'),
        }

        # Construct payload
        payload = {}
        for key, value in args.items():
            if value is not None:
                if key == "resource_group":
                    rg_info = self.rg.get_resource_group(
                        args["resource_group"])
                    if "errors" in rg_info:
                        return rg_info
                    payload["resource_group"] = {"id": rg_info["id"]}
                else:
                    payload[key] = value

        try:
            # Connect to api endpoint for ike_policies
            path = ("/v1/ike_policies?version={}&generation={}".format(
                self.cfg["version"], self.cfg["generation"]))

            # Return data
            return qw("iaas", "POST", path, headers(),
                      json.dumps(payload))["data"]

        except Exception as error:
            print("Error creating IKE policy. {}".format(error))
            raise
Exemplo n.º 21
0
    def get_dns_zone_by_name(self, **kwargs):
        """Get DNS zone by name

        :param dns_zone: DNS zone name to query
        :type dns_zone: str
        :param resource_instance: Name or GUID of the resource instance
        :type resource_instance: str
        :return: DNS zone information
        :rtype: dict
        """
        # Required parameters
        args = ['dns_zone', 'resource_instance']
        check_args(args, **kwargs)

        # Set default value if required paramaters are not defined
        args = {
            'dns_zone': kwargs.get('dns_zone'),
            'resource_instance': kwargs.get('resource_instance'),
        }

        # get resource instance guid
        temp_ri = self.resource_instance.get_resource_instance(
            args['resource_instance'])
        if "errors" in temp_ri:
            return temp_ri
        resource_instance_guid = temp_ri["guid"]

        try:
            # Connect to api endpoint for dns zones
            path = ("/v1/instances/{}/dnszones").format(resource_instance_guid)

            dns_zones = qw("dns", "GET", path, headers())["data"]

            if "errors" in dns_zones or not dns_zones:
                return ({
                    "errors": [{
                        "code": "not_found",
                        "message": "No dns zones found."
                    }]
                })

            # Find the existing domain matching the query
            for dns_zone in dns_zones['dnszones']:
                if dns_zone["name"] == args['dns_zone']:
                    return dns_zone

            # Return error message if no existing domain matches the query
            return ({
                "errors": [{
                    "code": "not_found",
                    "message": "No dns zone found."
                }]
            })

        except Exception as error:
            print("Error creating dns zone. {}".format(error))
            raise
Exemplo n.º 22
0
    def create_instance_interface(self, **kwargs):
        """Create instance interface

        :param instance: The instance name or ID
        :type instance: str
        :param subnet: The associated subnet name or ID
        :type subnet: str
        :param primary_ipv4_address: The primary IPv4 address
        :type primary_ipv4_address: str, optional
        :param security_groups: Collection of security groups
        :type security_groups: str, optional
        """
        args = ["instance", "subnet"]
        check_args(args, **kwargs)

        args = {
            'instance': kwargs.get('instance'),
            'subnet': kwargs.get('forsubnetce'),
            'primary_ipv4_address': kwargs.get('primary_ipv4_address'),
            'security_groups': kwargs.get('security_groups'),
        }

        instance_info = self.get_instance(args["instance"])
        if "errors" in instance_info:
            return instance_info

        subnet_info = self.subnet.get_subnet(args["subnet"])
        if "errors" in subnet_info:
            return subnet_info

        payload = {}
        for key, value in args.items():
            if key != "instance" and value is not None:
                if key == "security_groups":
                    sg = []
                    for key_sg in args["security_groups"]:
                        tmp_sg = {}
                        tmp_sg["id"] = key_sg
                        sg.append(tmp_sg)
                    payload["security_groups"] = sg
                elif key == "subnet":
                    payload["subnet"] = {"id": subnet_info["id"]}
                else:
                    payload[key] = value

        try:
            path = ("/v1/instances/{}/network_interfaces?version={}"
                    "&generation={}".format(instance_info["id"],
                                            self.cfg["version"],
                                            self.cfg["generation"]))

            return qw("iaas", "POST", path, headers(),
                      json.dumps(payload))["data"]

        except Exception as error:
            print("Error creating instance interface. {}".format(error))
            raise
Exemplo n.º 23
0
    def order_file_volume(self, **kwargs):
        """Places an order for a file volume

        :param storage_type: Type of volume "Endurance|Performance"
        :type storage_type: str
        :param location: Name of the datacenter in which to order the volume
        :type location: str
        :param size: Size of the desired volume, in GB
        :type size: int
        :param iops: Number of IOPS for a "Performance" order
        :type iops: int
        :param tier_level: Tier level to use for an "Endurance" order
            (0.25|2|4|10)
        :type tier_level: int
        :param snapshot_size: The size of optional snapshot space, if snapshot
            space should also be ordered (None if not ordered)
        :type snapshot_size: int
        :param service_offering: Requested offering package to use in the order
            ("storage_as_a_service", "enterprise", or "performance")
        :type service_offering: str
        :param hourly_billing_flag: Billing type, monthly (False) or
            hourly (True), default to monthly
        :type hourly_billing_flag: bool
        :return: Created volume description
        :rtype: dict
        """

        args = ["storage_type", "location", "size"]
        check_args(args, **kwargs)

        # Build dict of argument and assign default value when needed
        args = {
            'storage_type': kwargs.get('storage_type'),
            'location': kwargs.get('location'),
            'size': kwargs.get('size'),
            'iops': kwargs.get('iops') or None,
            'tier_level': kwargs.get('tier_level') or None,
            'snapshot_size': kwargs.get('snapshot_size') or None,
            'service_offering': kwargs.get('service_offering',
                                           'storage_as_a_service'),
            'hourly_billing_flag': kwargs.get('hourly_billing_flag') or False
        }

        try:
            order = self.file.order_file_volume(
                args['storage_type'],
                args['location'],
                args['size'],
                iops=args['iops'],
                tier_level=args['tier_level'],
                snapshot_size=args['snapshot_size'],
                service_offering=args['service_offering'],
                hourly_billing_flag=args['hourly_billing_flag'])
            return order
        except sl.SoftLayer.SoftLayerAPIError as error:
            return resource_error(error.faultCode, error.faultString)
Exemplo n.º 24
0
    def create_port(self, **kwargs):
        """Create network

        :param instance: Instance name or ID
        :type instance: str
        :param network: Network name or ID
        :type network: str
        :param description: Description of the port
        :type description: str, optional
        :param ip_address: The requested ip address of this port
        :type ip_address: str, optional
        :return: Port information
        :rtype: dict
        """
        args = ["instance", "network"]
        check_args(args, **kwargs)

        # Build dict of argument and assign default value when needed
        args = {
            'instance': kwargs.get('instance'),
            'network': kwargs.get('network'),
            'description': kwargs.get('description'),
            'ip_address': kwargs.get('ip_address'),
        }

        # Construct payload
        payload = {}
        for key, value in args.items():
            if key != "instance" and key != "network" and value is not None:
                if key == "ip_address":
                    payload["ipAddress"] = args['ip_address']
                else:
                    payload[key] = value

        try:
            # Check if cloud instance exists and retrieve information
            ci_info = self.instance.get_instance(instance)
            if "errors" in ci_info:
                return ci_info

            # Check if network exists and retrieve information
            net_info = self.get_network(ci_info["name"], args['network'])
            if "errors" in net_info:
                return net_info

            # Connect to api endpoint for cloud-instances
            path = ("/pcloud/v1/cloud-instances/{}/networks/{}/ports".format(
                ci_info["name"], net_info["networkID"]))

            # Return data
            return qw("power", "POST", path, headers(),
                      json.dumps(payload))["data"]

        except Exception as error:
            print("Error creating port in network {} for cloud instance {}."
                  " {}".format(args['network'], args['instance'], error))
Exemplo n.º 25
0
    def attach_volume(self, **kwargs):
        """Attach a volume to an instance

        :param instance: The instance name or ID
        :type instance: str
        :param volume: The identity of the volume to attach to the instance
        :type volume: str
        :param delete_volume_on_instance_delete: If set to true, when deleting
            the instance the volume will also be deleted
        :type delete_volume_on_instance_delete: bool, optional
        :param name: The user-defined name for this volume attachment
        :type name: str
        """
        args = ["instance", "volume"]
        check_args(args, **kwargs)

        args = {
            'instance':
            kwargs.get('instance'),
            'volume':
            kwargs.get('volume'),
            'delete_volume_on_instance_delete':
            kwargs.get('delete_volume_on_instance_delete'),
            'name':
            kwargs.get('name'),
        }

        instance_info = self.get_instance(args["instance"])
        if "errors" in instance_info:
            return instance_info

        volume_info = self.volume.get_volume(args["volume"])
        if "errors" in volume_info:
            return volume_info

        payload = {}
        for key, value in args.items():
            if key != "instance" and value is not None:
                if key == "volume":
                    payload["volume"] = {"id": volume_info["id"]}
                else:
                    payload[key] = value

        try:
            path = ("/v1/instances/{}/volume_attachments?version={}"
                    "&generation={}".format(instance_info["id"],
                                            self.cfg["version"],
                                            self.cfg["generation"]))

            return qw("iaas", "POST", path, headers(),
                      json.dumps(payload))["data"]

        except Exception as error:
            print("Error creating volume attachment. {}".format(error))
            raise
Exemplo n.º 26
0
    def create_zone(self, **kwargs):
        """Create a zone in a specified resource instance

        :param dns_zone: The user-defined name to create
        :type dns_zone: str
        :param description: A description for the domain
        :type description: str, optional
        :param label: A label for the domain
        :type label: str, optional
        :param resource_instance: Name or GUID of the resource instance
        :type resource_instance: str
        """
        # Required parameters
        args = ['dns_zone', 'resource_instance']
        check_args(args, **kwargs)

        # Set default value if required paramaters are not defined
        args = {
            'name': kwargs.get('dns_zone'),
            'description': kwargs.get('description') or "",
            'label': kwargs.get('label') or "",
        }

        # get resource instance guid
        temp_ri = self.resource_instance.get_resource_instance(
            kwargs.get('resource_instance'))
        if "errors" in temp_ri:
            return temp_ri
        resource_instance_guid = temp_ri["guid"]

        zone = self.get_dns_zone(dns_zone=args['name'],
                                 resource_instance=resource_instance_guid)

        if "errors" in zone:
            for key_zone in zone["errors"]:
                if key_zone["code"] == "not_found":
                    payload = {}

                    # Construct payload
                    for key, value in args.items():
                        payload[key] = value

                    try:
                        # Connect to api endpoint for dns zone
                        path = ("/v1/instances/{}/dnszones"
                                ).format(resource_instance_guid)
                        # Return data
                        return qw("dns", "POST", path, headers(),
                                  json.dumps(payload))["data"]

                    except Exception as error:
                        print("Error creating dns zone. {}".format(error))
                        raise
        return zone
Exemplo n.º 27
0
    def perform_action(self, **kwargs):
        """Perform an action on Power Virtual Machine

        :param instance: Cloud instance ID
        :type instance: str
        :param pvm: Power Virtual Instance name or ID
        :type pvm: str
        :param action: Name of the action to take
        :type action: str
        :return: Action information
        :rtype: dict
        """
        args = ["instance", "pvm", "action"]
        check_args(args, **kwargs)

        # Build dict of argument and assign default value when needed
        args = {
            'instance': kwargs.get('instance'),
            'pvm': kwargs.get('pvm'),
            'action': kwargs.get('action'),
        }

        # Construct payload
        payload = {}
        for key, value in args.items():
            if key != "instance" and key != "pvm" and value is not None:
                payload[key] = value

        try:
            # Check if cloud instance exists and retrieve information
            ci_info = self.instance.get_instance(args['instance'])
            if "errors" in ci_info:
                return ci_info

            # Check if pvm exists and retrieve information
            pvm_info = self.get_pvm(ci_info["name"], args['pvm'])
            if "errors" in pvm_info:
                return pvm_info

            # Connect to api endpoint for cloud-instances
            path = ("/pcloud/v1/cloud-instances/{}/pvm-instances/{}"
                    "/action".format(ci_info["name"],
                                     pvm_info["pvmInstanceID"]))

            # Return data
            return qw("power", "POST", path, headers(),
                      json.dumps(payload))["data"]

        except Exception as error:
            print("Error performing action {} on Power Virtual Machine {} for"
                  " cloud instance {}. {}".format(args['action'],
                                                  args['network'],
                                                  args['instance'], error))
Exemplo n.º 28
0
    def create_gateway(self, **kwargs):
        """Create gateway

        :param name: The user-defined name for this gateway
        :type name: str, optional
        :param resource_group: The resource group to use
        :type resource_group: str, optional
        :param subnet: Identifies a subnet by a unique property
        :type subnet: str
        """
        args = ["subnet"]
        check_args(args, **kwargs)

        # Build dict of argument and assign default value when needed
        args = {
            'name': kwargs.get('name'),
            'resource_group': kwargs.get('resource_group'),
            'subnet': kwargs.get('subnet'),
        }

        # Retrieve subnet information to get the ID
        subnet_info = self.subnet.get_subnet(args["subnet"])
        if "errors" in subnet_info:
            return subnet_info

        # Construct payload
        payload = {}
        for key, value in args.items():
            if value is not None:
                if key == "resource_group":
                    rg_info = self.rg.get_resource_group(
                        args["resource_group"])
                    if "errors" in rg_info:
                        return rg_info
                    payload["resource_group"] = {"id": rg_info["id"]}
                elif key == "subnet":
                    payload["subnet"] = {"id": subnet_info["id"]}
                else:
                    payload[key] = value

        try:
            # Connect to api endpoint for vpn_gateways
            path = ("/v1/vpn_gateways?version={}&generation={}".format(
                self.cfg["version"], self.cfg["generation"]))

            # Return data
            return qw("iaas", "POST", path, headers(),
                      json.dumps(payload))["data"]

        except Exception as error:
            print("Error creating gateway. {}".format(error))
            raise
Exemplo n.º 29
0
    def delete_zone(self, **kwargs):
        """Delete a zone in from a specified resource instance

        :param dns_zone: DNS zone name to delete
        :type dns_zone: str
        :param resource_instance: Name or GUID of the resource instance
        :type resource_instance: str
        """
        # Required parameters
        args = ['dns_zone', 'resource_instance']
        check_args(args, **kwargs)

        # Set default value if required paramaters are not defined
        args = {
            'name': kwargs.get('dns_zone'),
            'resource_instance': kwargs.get('resource_instance'),
        }

        # get resource instance guid
        temp_ri = self.resource_instance.get_resource_instance(
            args['resource_instance'])
        if "errors" in temp_ri:
            return temp_ri
        resource_instance_guid = temp_ri["guid"]

        dns_zone = self.get_dns_zone(
            dns_zone=args['name'], resource_instance=args['resource_instance'])

        if "errors" in dns_zone:
            return dns_zone
        dns_zone_id = dns_zone['id']

        try:
            # Connect to api endpoint for dns zone
            path = ("/v1/instances/{}/dnszones/{}").format(
                resource_instance_guid, dns_zone_id)

            # Return data
            result = qw("dns", "DELETE", path, headers())

            if result["data"] is None:
                if result["response"].getcode() == 204:
                    return ({
                        "message":
                        "deletion request successfully initiated"
                    })
            return result

        except Exception as error:
            print("Error creating dns zone. {}".format(error))
            raise
Exemplo n.º 30
0
    def add_interface_security_group(self, **kwargs):
        """Add network interface to a security group

        :param interface: The network interface ID
        :type interface: str
        :param security_group: The security group name or ID
        :type security_group: str
        :param instance: Instance name or ID
        :type instance: str, optional
        """
        args = ["interface", "security_group"]
        check_args(args, **kwargs)

        # Build dict of argument and assign default value when needed
        args = {
            'interface': kwargs.get('interface'),
            'security_group': kwargs.get('security_group'),
            'instance': kwargs.get('instance'),
        }

        target = args["interface"]

        # Retrieve security group information to get the ID
        # (mostly useful if a name is provided)
        sg_info = self.get_security_group(args["security_group"])
        if "errors" in sg_info:
            return sg_info

        if args["instance"]:
            # Retrieve network interface information to get the ID
            # (mostly useful if a name is provided)
            nic_info = self.instance.get_instance_interface(
                args["instance"], args["interface"])
            if "errors" in nic_info:
                return nic_info
            target = nic_info["id"]

        try:
            # Connect to api endpoint for security_groups
            path = ("/v1/security_groups/{}/network_interfaces/{}?version={}"
                    "&generation={}".format(sg_info["id"], target,
                                            self.cfg["version"],
                                            self.cfg["generation"]))

            # Return data
            return qw("iaas", "PUT", path, headers(), None)["data"]

        except Exception as error:
            print("Error adding network interface {} to security group"
                  " {}. {}".format(target, args["security_group"], error))
            raise