def _authenticate_security_group_response(response, rule_type): """ Generate a response for authenticate security group request. @param response: Cloudstack response. @param rule_type: The type of rule to add. @raise Ec2stackError: If authorize security group fails. @return: Response """ if 'errortext' in response: if 'Failed to authorize security group' in response['errortext']: cidrlist = str(helpers.get('CidrIp')) protocol = str(helpers.get('IpProtocol')) from_port = str(helpers.get('FromPort')) to_port = str(helpers.get('toPort')) raise Ec2stackError( '400', 'InvalidPermission.Duplicate', 'the specified rule "peer: ' + cidrlist + ', ' + protocol + ', from port: ' + from_port + ', to port: ' + to_port + ', ALLOW" already exists') elif 'Unable to find security group' in response['errortext']: errors.invalid_security_group() else: errors.invalid_request(response['errortext']) else: if rule_type == 'ingress': rule_type = 'AuthorizeSecurityGroupIngressResponse' elif rule_type == 'egress': rule_type = 'AuthorizeSecurityGroupEgressResponse' return { 'template_name_or_list': 'status.xml', 'response_type': rule_type, 'return': 'true' }
def _create_volume_request(): """ Request to create a volume. @return: Response. """ args = {} if helpers.contains_parameter('SnapshotId'): args['snapshotid'] = helpers.get('SnapshotId') else: helpers.require_parameters(['Size']) args['size'] = helpers.get('Size') args['diskofferingid'] = disk_offerings.get_disk_offering( current_app.config['CLOUDSTACK_CUSTOM_DISK_OFFERING'] )['id'] zone_name = helpers.get('AvailabilityZone') zone_id = zones.get_zone(zone_name)['id'] args['zoneid'] = zone_id args['command'] = 'createVolume' args['name'] = uuid.uuid4() response = requester.make_request_async(args) return response
def _create_volume_request(): """ Request to create a volume. @return: Response. """ args = {} if helpers.contains_parameter('SnapshotId'): args['snapshotid'] = helpers.get('SnapshotId') else: helpers.require_parameters(['Size']) args['size'] = helpers.get('Size') args['diskofferingid'] = disk_offerings.get_disk_offering( current_app.config['CLOUDSTACK_CUSTOM_DISK_OFFERING'] )['id'] zone_name = helpers.get('AvailabilityZone') zone_id = zones.get_zone(zone_name)['id'] args['zoneid'] = zone_id args['command'] = 'createVolume' args['name'] = uuid.uuid1() response = requester.make_request_async(args) return response
def register_secret_key(): """ Register a user's API key and secret key. @return: Response. @raise Ec2stackError: API key already registered. """ require_parameters({'AWSAccessKeyId', 'AWSSecretKey'}) found_user = USERS.get(get('AWSAccessKeyId')) if found_user is None: USERS.create( apikey=get('AWSAccessKeyId'), secretkey=get('AWSSecretKey') ) return { 'template_name_or_list': 'secretkey.xml', 'response_type': 'RegisterSecretKeyResponse', 'AWSAccessKeyId': get('AWSAccessKeyId'), 'AWSSecretKey': get('AWSSecretKey'), 'Message': 'Successfully Registered!' } else: raise Ec2stackError( '400', 'DuplicateUser', 'The given AWSAccessKeyId is already registered' )
def _delete_tag_request(): """ Request to delete a tag. @return: Response. """ key = helpers.get('Tag.1.Key') resource_id = helpers.get('ResourceId.1') if resource_id in current_app.config['RESOURCE_TYPE_MAP']: resource_type = current_app.config['RESOURCE_TYPE_MAP'][resource_id] else: errors.invalid_request( str(resource_id) + " not found in configuration") args = { 'command': 'deleteTags', 'resourceids': resource_id, 'resourcetype': resource_type, 'tags[0].key': key } response = requester.make_request_async(args) return response
def remove_secret_key(): """ Remove a user's API key and secret key @return: Response. @raise Ec2stackError: API key doesn't exist. """ require_parameters({'AWSAccessKeyId', 'AWSSecretKey'}) accesskey = get('AWSAccessKeyId') secretkey = get('AWSSecretKey') found_user = USERS.get(accesskey) if found_user is not None and found_user.secretkey == secretkey: USERS.delete(found_user) return { 'template_name_or_list': 'secretkey.xml', 'response_type': 'RemoveSecretKeyResponse', 'AWSAccessKeyId': get('AWSAccessKeyId'), 'AWSSecretKey': get('AWSSecretKey'), 'Message': 'Successfully removed!' } else: raise Ec2stackError( '400', 'NoSuchUser', 'The no matching AWSAccessKeyId and AWSSecretKey was not found')
def remove_secret_key(): """ Remove a user's API key and secret key @return: Response. @raise Ec2stackError: API key doesn't exist. """ require_parameters({'AWSAccessKeyId', 'AWSSecretKey'}) accesskey = get('AWSAccessKeyId') secretkey = get('AWSSecretKey') found_user = USERS.get(accesskey) if found_user is not None and found_user.secretkey == secretkey: USERS.delete(found_user) return { 'template_name_or_list': 'secretkey.xml', 'response_type': 'RemoveSecretKeyResponse', 'AWSAccessKeyId': get('AWSAccessKeyId'), 'AWSSecretKey': get('AWSSecretKey'), 'Message': 'Successfully removed!' } else: raise Ec2stackError( '400', 'NoSuchUser', 'The no matching AWSAccessKeyId and AWSSecretKey was not found' )
def _authenticate_security_group_response(response, rule_type): if "errortext" in response: if "Failed to authorize security group" in response["errortext"]: cidrlist = str(helpers.get("CidrIp")) protocol = str(helpers.get("IpProtocol")) from_port = str(helpers.get("FromPort")) to_port = str(helpers.get("toPort")) raise Ec2stackError( "400", "InvalidPermission.Duplicate", 'the specified rule "peer: ' + cidrlist + ", " + protocol + ", from port: " + from_port + ", to port: " + to_port + ', ALLOW" already exists', ) elif "Unable to find security group" in response["errortext"]: errors.invalid_security_group() errors.invalid_paramater_value(response["errortext"]) else: if rule_type == "ingress": rule_type = "AuthorizeSecurityGroupIngressResponse" elif rule_type == "egress": rule_type = "AuthorizeSecurityGroupEgressResponse" return {"template_name_or_list": "status.xml", "response_type": rule_type, "return": "true"}
def _import_keypair_request(): args = {'command': 'registerSSHKeyPair', 'name': helpers.get('KeyName'), 'publickey': b64decode(helpers.get('PublicKeyMaterial'))} response = requester.make_request(args) response = response['registersshkeypairresponse'] return response
def _import_keypair_request(): args = { 'command': 'registerSSHKeyPair', 'name': helpers.get('KeyName'), 'publickey': b64decode(helpers.get('PublicKeyMaterial')) } response = requester.make_request(args) response = response['registersshkeypairresponse'] return response
def _create_security_group_request(): args = { "command": "createSecurityGroup", "name": helpers.get("GroupName"), "description": helpers.get("GroupDescription"), } response = requester.make_request(args) response = response["createsecuritygroupresponse"] return response
def _create_security_group_request(): args = { 'command': 'createSecurityGroup', 'name': helpers.get('GroupName'), 'description': helpers.get('GroupDescription') } response = requester.make_request(args) response = response['createsecuritygroupresponse'] return response
def _create_security_group_request(): """ Request to create a security group. @return: response. """ args = {'command': 'createSecurityGroup', 'name': helpers.get('GroupName'), 'description': helpers.get('GroupDescription')} response = requester.make_request(args) response = response['createsecuritygroupresponse'] return response
def _attach_volume_request(): args = {} volume_id = helpers.get("VolumeId") instance_id = helpers.get("InstanceId") device = helpers.get("Device") args["id"] = volume_id args["command"] = "attachVolume" args["virtualmachineid"] = instance_id args["device"] = device response = requester.make_request_async(args) return response
def _attach_volume_request(): args = {} volume_id = helpers.get('VolumeId') instance_id = helpers.get('InstanceId') device = helpers.get('Device') args['id'] = volume_id args['command'] = 'attachVolume' args['virtualmachineid'] = instance_id args['device'] = device response = requester.make_request_async(args) return response
def _delete_volume_request(): args = {'id': helpers.get('VolumeId'), 'command': 'deleteVolume'} response = requester.make_request(args) response = response['deletevolumeresponse'] return response
def _create_vpc_request(): """ Request to create a vpc. @return: Response. """ args = {'command': 'createVPC'} name = uuid.uuid1() args['name'] = name args['displaytext'] = name args['zoneid'] = zones.get_zone( current_app.config['CLOUDSTACK_DEFAULT_ZONE'])['id'] if 'VPC_OFFERING_ID' in current_app.config: args['vpcofferingid'] = current_app.config['VPC_OFFERING_ID'] else: errors.invalid_request( str('VPC_OFFERING_ID') + " not found in configuration, " + "please run ec2stack-configure -a True") args['cidr'] = helpers.get('CidrBlock') response = requester.make_request_async(args) return response
def _detach_volume_request(): args = {} volume_id = helpers.get('VolumeId') if helpers.contains_parameter('InstanceId'): args['virtualmachineid'] = helpers.get('InstanceId') if helpers.contains_parameter('Device'): args['deviceid'] = helpers.get('Device') args['id'] = volume_id args['command'] = 'detachVolume' response = requester.make_request_async(args) return response
def _delete_security_group_request(): args = {} helpers.require_atleast_one_parameter(['GroupName', 'GroupId']) if helpers.contains_parameter('GroupName'): args['name'] = helpers.get('GroupName') elif helpers.contains_parameter('GroupId'): args['id'] = helpers.get('GroupId') args['command'] = 'deleteSecurityGroup' response = requester.make_request(args) return response
def _describe_specific_item(args, keyname, not_found, prefix): """ Describe a specific item based on args['id'] or args['name']. @param args: Arguments involved in the request. @param keyname: Keyname of the Cloudstack response. @param not_found: Function to call if the item is not found. @param prefix: Parameter prefix. @return: Response. """ keys = helpers.get_request_parameter_keys(prefix) response = {keyname: []} for key in keys: name = helpers.get(key) if 'Id' in key: args['id'] = name elif 'Name' in key: args['name'] = name request = describe_item_request(args, keyname, not_found) response[keyname].append(request) return response
def register_secret_key(): require_parameters({'AWSAccessKeyId', 'AWSSecretKey'}) found_user = USERS.get(get('AWSAccessKeyId')) if found_user is None: USERS.create(apikey=get('AWSAccessKeyId'), secretkey=get('AWSSecretKey')) return { 'template_name_or_list': 'secretkey.xml', 'response_type': 'RegisterSecretKeyResponse', 'AWSAccessKeyId': get('AWSAccessKeyId'), 'AWSSecretKey': get('AWSSecretKey'), 'Message': 'Successfully Registered!' } else: raise Ec2stackError('400', 'DuplicateUser', 'The given AWSAccessKeyId is already registered')
def _delete_security_group_request(): args = {} helpers.require_atleast_one_parameter(["GroupName", "GroupId"]) if helpers.contains_parameter("GroupName"): args["name"] = helpers.get("GroupName") elif helpers.contains_parameter("GroupId"): args["id"] = helpers.get("GroupId") args["command"] = "deleteSecurityGroup" response = requester.make_request(args) return response
def _import_keypair_request(): """ Request to import a keypair. @return: Response. """ args = { "command": "registerSSHKeyPair", "name": helpers.get("KeyName"), "publickey": b64decode(helpers.get("PublicKeyMaterial")), } response = requester.make_request(args) response = response["registersshkeypairresponse"] return response
def _delete_volume_request(): args = {"id": helpers.get("VolumeId"), "command": "deleteVolume"} response = requester.make_request(args) response = response["deletevolumeresponse"] return response
def make_request(args): args['apikey'] = helpers.get('AWSAccessKeyId') args['response'] = 'json' secretkey = helpers.get_secretkey() request_url = _generate_request_url(args, secretkey) response = requests.get(request_url) if response.status_code in [401, 432]: abort(400) else: response_data = json.loads( response.text, object_hook=helpers.normalize_dict_keys ) current_app.logger.debug( 'request url:' + str(request_url) + 'status code: ' + str(response.status_code) + json.dumps(response_data, indent=4, separators=(',', ': ')) ) return response_data
def make_request(args): """ Makes a request to Cloudstack. @param args: Request Payload. @return: Response. """ args['apikey'] = helpers.get('AWSAccessKeyId') args['response'] = 'json' secretkey = helpers.get_secretkey() request_url = _generate_request_url(args, secretkey) response = requests.get(request_url) response_data = json.loads(response.text, object_hook=helpers.normalize_dict_keys) current_app.logger.debug( 'request url:' + str(request_url) + 'status code: ' + str(response.status_code) + json.dumps(response_data, indent=4, separators=(',', ': '))) if response.status_code in [401, 432]: abort(400) else: return response_data
def _detach_volume_request(): args = {} volume_id = helpers.get("VolumeId") if helpers.contains_parameter("InstanceId"): args["virtualmachineid"] = helpers.get("InstanceId") if helpers.contains_parameter("Device"): args["deviceid"] = helpers.get("Device") args["id"] = volume_id args["command"] = "detachVolume" response = requester.make_request_async(args) return response
def _create_keypair_request(): args = {'command': 'createSSHKeyPair', 'name': helpers.get('KeyName')} response = requester.make_request(args) response = response['createsshkeypairresponse'] return response
def _run_instance_request(): args = {} if helpers.get('InstanceType') is None: instance_type = 'm1.small' else: instance_type = helpers.get('InstanceType') if instance_type in current_app.config['INSTANCE_TYPE_MAP']: instance_type = current_app.config[ 'INSTANCE_TYPE_MAP'][instance_type] else: instance_type = instance_type args['serviceofferingid'] = \ service_offerings.get_service_offering(instance_type)['id'] args['templateid'] = helpers.get('ImageId') if helpers.contains_parameter('Placement.AvailabilityZone'): args['zoneid'] = zones.get_zone( helpers.get('Placement.AvailabilityZone') ) else: args['zoneid'] = zones.get_zone( current_app.config['CLOUDSTACK_DEFAULT_ZONE'] )['id'] if helpers.contains_parameter('KeyName'): args['keypair'] = helpers.get('KeyName') if helpers.contains_parameter('UserData'): args['userdata'] = helpers.get('UserData') if helpers.contains_parameter_with_keyword('SecurityGroupId.'): keys = helpers.get_request_parameter_keys('SecurityGroupId.') securitygroupids = [] for key in keys: securitygroupids.append(helpers.get(key)) args['securitygroupids'] = ",".join(securitygroupids) if helpers.contains_parameter_with_keyword('SecurityGroup.'): keys = helpers.get_request_parameter_keys('SecurityGroup.') securitygroupnames = [] for key in keys: securitygroupnames.append(helpers.get(key)) args['securitygroupnames'] = ",".join(securitygroupnames) args['command'] = 'deployVirtualMachine' response = requester.make_request_async(args) return response
def describe_image_attribute(): image_id = helpers.get('ImageId') attribute = helpers.get('Attribute') supported_attribute_map = { 'description': 'displaytext' } if attribute not in supported_attribute_map.iterkeys(): errors.invalid_paramater_value( 'The specified attribute is not valid, please specify a valid ' + 'image attribute.' ) response = describe_image_by_id(image_id) return _describe_image_attribute_response( response, attribute, supported_attribute_map)
def _get_password_data_request(): args = {'command': 'getVMPassword', 'id': helpers.get('InstanceId')} response = requester.make_request(args) response = response['getvmpasswordresponse'] return response
def stop_instance(): helpers.require_parameters(['InstanceId.1']) instance_id = helpers.get('InstanceId.1') previous_instance_state_description = describe_instance_by_id(instance_id) new_instance_state_description = _stop_instance_request(instance_id) return _stop_instance_response( previous_instance_state_description, new_instance_state_description )
def describe_instance_attribute(): instance_id = helpers.get('InstanceId') attribute = helpers.get('Attribute') supported_attribute_map = { 'instanceType': 'serviceofferingname', 'groupSet': 'securitygroup' } if attribute not in supported_attribute_map.iterkeys(): errors.invalid_paramater_value( 'The specified attribute is not valid, please specify a valid ' + 'instance attribute.' ) response = describe_instance_by_id(instance_id) return _describe_instance_attribute_response( response, attribute, supported_attribute_map)
def reboot_instance(): """ Reboot an instance. @return: Response. """ helpers.require_parameters(['InstanceId.1']) instance_id = helpers.get('InstanceId.1') _reboot_instance_request(instance_id) return _reboot_instance_response()
def _create_snapshot_request(): """ Request to create a snapshot. @return: Response. """ args = {'command': 'createSnapshot', 'volumeid': helpers.get('VolumeId')} response = requester.make_request_async(args) return response
def _delete_snapshot_request(): """ Request to delete a snapshot. @return: Response. """ args = {'command': 'deleteSnapshot', 'id': helpers.get('SnapshotId')} response = requester.make_request_async(args) return response
def _delete_keypair_request(): """ Request to delete a keypair. @return: Response. """ args = {"command": "deleteSSHKeyPair", "name": helpers.get("KeyName")} response = requester.make_request(args) return response
def _attach_volume_request(): """ Request to attach a volume. @return: Response. """ args = {} volume_id = helpers.get('VolumeId') instance_id = helpers.get('InstanceId') device = helpers.get('Device') args['id'] = volume_id args['command'] = 'attachVolume' args['virtualmachineid'] = instance_id args['device'] = device response = requester.make_request_async(args) return response
def _delete_keypair_request(): """ Request to delete a keypair. @return: Response. """ args = {'command': 'deleteSSHKeyPair', 'name': helpers.get('KeyName')} response = requester.make_request(args) return response
def register_secret_key(): """ Register a user's API key and secret key. @return: Response. @raise Ec2stackError: API key already registered. """ require_parameters({"AWSAccessKeyId", "AWSSecretKey"}) found_user = USERS.get(get("AWSAccessKeyId")) if found_user is None: USERS.create(apikey=get("AWSAccessKeyId"), secretkey=get("AWSSecretKey")) return { "template_name_or_list": "secretkey.xml", "response_type": "RegisterSecretKeyResponse", "AWSAccessKeyId": get("AWSAccessKeyId"), "AWSSecretKey": get("AWSSecretKey"), "Message": "Successfully Registered!", } else: raise Ec2stackError("400", "DuplicateUser", "The given AWSAccessKeyId is already registered")
def _delete_vpc_request(): """ Request to delete a vpc. @return: Response. """ args = {'command': 'deleteVPC', 'id': helpers.get('VpcId')} response = requester.make_request_async(args) return response
def index(): """ URL entry point. Parses the Action parameter and executes the associated functions to generate a response. @return: Response. """ try: response_data = _get_action(get('Action'))() return successful_response(**response_data) except Ec2stackError as err: return error_response(err.code, err.error, err.message)
def terminate_instance(): """ Terminate an instance. @return: Response. """ helpers.require_parameters(['InstanceId.1']) instance_id = helpers.get('InstanceId.1') previous_state = describe_instance_by_id(instance_id) new_state = _terminate_instance_request(instance_id) return _modify_instance_state_response('TerminateInstancesResponse', previous_state, new_state)
def _get_password_data_format_response(response): instanceid = helpers.get('InstanceId') if 'errortext' in response: raise Ec2stackError( '400', 'InvalidInstanceID.NotFound', 'The instance ID \'%s\' does not exist.' % instanceid ) else: response = response['password'] return { 'template_name_or_list': 'password.xml', 'response_type': 'GetPasswordDataResponse', 'response': response }
def _describe_specific_item(args, keyname, not_found, prefix): keys = helpers.get_request_parameter_keys(prefix) response = {keyname: []} for key in keys: name = helpers.get(key) if 'Id' in key: args['id'] = name elif 'Name' in key: args['name'] = name request = describe_item_request(args, keyname, not_found) response[keyname].append(request) return response
def _run_instance_request(): """ Request to bring up an instance. @return: Response. """ args = {} if helpers.contains_parameter('Placement.AvailabilityZone'): args['zoneid'] = zones.get_zone( helpers.get('Placement.AvailabilityZone')) else: args['zoneid'] = zones.get_zone( current_app.config['CLOUDSTACK_DEFAULT_ZONE'])['id'] if helpers.get('BlockDeviceMapping.1.Ebs.VolumeType') is not None: disk_type = helpers.get('BlockDeviceMapping.1.Ebs.VolumeType') if disk_type == 'gp2': args['diskofferingid'] = disk_offerings.get_disk_offering( current_app.config['CLOUDSTACK_CUSTOM_DISK_OFFERING'])['id'] if helpers.get('BlockDeviceMapping.1.Ebs.VolumeSize') is None: errors.invalid_request( "VolumeSize not found in BlockDeviceMapping") else: args['size'] = helpers.get('BlockDeviceMapping.1.Ebs.VolumeSize') if helpers.get('InstanceType') is None: instance_type = 'm1.small' else: instance_type = helpers.get('InstanceType') if instance_type in current_app.config['INSTANCE_TYPE_MAP']: instance_type = current_app.config['INSTANCE_TYPE_MAP'][instance_type] else: instance_type = instance_type args['serviceofferingid'] = \ service_offerings.get_service_offering(instance_type)['id'] args['templateid'] = helpers.get('ImageId') if helpers.contains_parameter('KeyName'): args['keypair'] = helpers.get('KeyName') if helpers.contains_parameter('UserData'): args['userdata'] = helpers.get('UserData') if helpers.contains_parameter_with_keyword('SecurityGroupId.'): keys = helpers.get_request_parameter_keys('SecurityGroupId.') securitygroupids = [] for key in keys: securitygroupids.append(helpers.get(key)) args['securitygroupids'] = ",".join(securitygroupids) if helpers.contains_parameter_with_keyword('SecurityGroup.'): keys = helpers.get_request_parameter_keys('SecurityGroup.') securitygroupnames = [] for key in keys: securitygroupnames.append(helpers.get(key)) args['securitygroupnames'] = ",".join(securitygroupnames) if helpers.get('SubnetId') is not None: args['networkids'] = helpers.get('SubnetId') args['command'] = 'deployVirtualMachine' response = requester.make_request_async(args) return response