示例#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))
示例#2
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)
示例#3
0
    def put_object(self, **kwargs):
        """Adds an object to a bucket

        :param acl: The canned ACL to apply to the object
        :type acl: str
        :param bucket: Bucket name
        :type bucket: str
        :param body: Object data
        :type body: str
        :param key: Object key for which the PUT operation was initiated
        :type key: str
        :return: Upload status
        :rtype: dict
        """
        args = ["bucket", "body", "key"]
        check_args(args, **kwargs)

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

        try:
            result = self.client.put_object(
                Bucket=args["bucket"],
                ACL=args['acl'],
                Body=args["body"],
                Key=args["key"]
            )
            if result["ResponseMetadata"]["HTTPStatusCode"] != 200:
                return result

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

        except Exception as error:
            return resource_error("unable_to_put_object", error)
示例#4
0
    def add_peer_cidr_connection(self, **kwargs):
        """Add peer CIDR to a connection

        :param gateway: The VPN gateway name or ID
        :type gateway: str
        :param connection: The connection name or ID
        :type connection: str
        :param prefix_address: The prefix address part of the CIDR
        :type prefix_address: str
        :param prefix_length: The prefix length part of the CIDR
        :type prefix_length: int
        """
        args = ["gateway", "connection", "prefix_address", "prefix_length"]
        check_args(args, **kwargs)

        # Build dict of argument and assign default value when needed
        args = {
            'gateway': kwargs.get('gateway'),
            'connection': kwargs.get('connection'),
            'prefix_address': kwargs.get('prefix_address'),
            'prefix_length': kwargs.get('prefix_length'),
        }

        # Retrieve gateway information to get the ID
        gateway_info = self.get_vpn_gateway(args["gateway"])
        if "errors" in gateway_info:
            return gateway_info

        # Retrieve connection information to get the ID
        connection_info = self.get_vpn_gateway_connection(gateway_info["id"],
                                                          args["connection"])
        if "errors" in connection_info:
            return connection_info

        try:
            # Connect to api endpoint for vpn_gateways
            path = ("/v1/vpn_gateways/{}/connections/{}/peer_cidrs/{}/{}"
                    "?version={}&generation={}".format(gateway_info["id"],
                                                       connection_info["id"],
                                                       args["prefix_address"],
                                                       args["prefix_length"],
                                                       self.cfg["version"],
                                                       self.cfg["generation"]))

            data = qw("iaas", "PUT", path, headers())

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

            # Return custom JSON
            payload = {"peer_cidr": ("{}/{}".format(args["prefix_address"],
                                                    args["prefix_length"]))}
            return resource_created(payload)

        except Exception as error:
            print("Error adding peer CIDR {}/{} to connection {} on VPN"
                  " gateway {}. {}".format(args["prefix_address"],
                                           args["prefix_length"],
                                           args["connection"],
                                           args["gateway"], error))
            raise
示例#5
0
    def create_bucket(self, **kwargs):
        """Create bucket

        :param bucket: Bucket name
        :type bucket: str
        :param acl: The canned ACL to apply to the bucket
        :type acl: str
        :param grant_full_control: Allows grantee the read, write, read ACP,
            and write ACP permissions on the bucket
        :type grant_full_control: str
        :param grant_read: Allows grantee to list the objects in the bucket
        :type grant_read: str
        :param grant_read_acp: Allows grantee to read the bucket ACL
        :type grant_read_acp: str
        :param grant_write: Allows grantee to create, overwrite, and delete
            any object in the bucket
        :type grant_write: str
        :param grant_write_acp: Allows grantee to write the ACL for the
            applicable bucket
        :type grant_write_acp: str
        :param ibm_sse_kp_encryptions_algorithm: The encryption algorithm that
            will be used for objects stored in the newly created bucket
        :type ibm_sse_kp_encryptions_algorithm: str
        :param ibm_sse_kp_customer_root_key_crn: Container for describing the
            KMS-KP Key CRN
        :type ibm_sse_kp_customer_root_key_crn: str
        :return: Bucket creation status
        :rtype: dict
        """
        args = ["bucket"]
        check_args(args, **kwargs)

        # Build dict of argument and assign default value when needed
        args = {
            'Bucket':
            kwargs.get('bucket'),
            'ACL':
            kwargs.get('acl', 'private'),
            'GrantFullControl':
            kwargs.get('grant_full_control'),
            'GrantRead':
            kwargs.get('grant_read'),
            'GrantReadACP':
            kwargs.get('grant_read_acp'),
            'GrantWrite':
            kwargs.get('grant_write'),
            'GrantWriteACP':
            kwargs.get('grant_write_acp'),
            'IBMSSEKPEncryptionAlgorithm':
            kwargs.get('ibm_sse_kp_encryptions_algorithm'),
            'IBMSSEKPCustomerRootKeyCrn':
            kwargs.get('ibm_sse_kp_customer_root_key_crn')
        }

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

        try:
            result = self.client.create_bucket(**payload)
            if result["ResponseMetadata"]["HTTPStatusCode"] != 200:
                return result

            msg = {"bucket": args['Bucket'], "status": "created"}
            return resource_created(msg)

        except Exception as error:
            return resource_error("unable_to_create", error)