def test_deploy_instance_returns_deploy_app_result(self): """ Tests deploy_instance method with deploy_result assertions. :return: """ mock_logger = Mock() dep_atts_json = '[{"attributeName":"Auto Delete","attributeValue":"True","type":"attributes"},{"attributeName":"Autoload","attributeValue":"True","type":"attributes"},{"attributeName":"IP Regex","attributeValue":"","type":"attributes"},{"attributeName":"Refresh IP Timeout","attributeValue":"600","type":"attributes"},{"attributeName":"vCenter VM","attributeValue":"Tor/Temps/ImageMonoNew","type":"attributes"},{"attributeName":"vCenter VM Snapshot","attributeValue":"1","type":"attributes"},{"attributeName":"VM Cluster","attributeValue":"","type":"attributes"},{"attributeName":"VM Storage","attributeValue":"","type":"attributes"},{"attributeName":"VM Resource Pool","attributeValue":"","type":"attributes"},{"attributeName":"VM Location","attributeValue":"","type":"attributes"},{"attributeName":"Auto Power On","attributeValue":"True","type":"attributes"},{"attributeName":"Auto Power Off","attributeValue":"True","type":"attributes"},{"attributeName":"Wait for IP","attributeValue":"True","type":"attributes"},{"attributeName":"Password","attributeValue":"3M3u7nkDzxWb0aJ/IZYeWw==","type":"attributes"},{"attributeName":"Public IP","attributeValue":"","type":"attributes"},{"attributeName":"User","attributeValue":"","type":"attributes"},{"attributeName":"Cloud Provider","attributeValue":"test_cloud_provider","type":"attributes"},{"attributeName":"Availability Zone","attributeValue":"test_availability_zone","type":"attributes"},{"attributeName":"Image ID","attributeValue":"test_image_uuid","type":"attributes"},{"attributeName":"Instance Flavor","attributeValue":"test_instance_flavor","type":"attributes"},{"attributeName":"Add Floating IP","attributeValue":"True","type":"attributes"},{"attributeName":"Autoload","attributeValue":"1","type":"attributes"},{"attributeName":"Floating IP Subnet ID","attributeValue":"floating_ip_subnet_id","type":"attributes"},{"attributeName":"Affinity Group ID","attributeValue":"affinity_group_id","type":"attributes"},{"attributeName":"Auto udev","attributeValue":"True","type":"attributes"}]' resource_atts_json = '[{"attributeName":"Password","attributeValue":"3M3u7nkDzxWb0aJ/IZYeWw==","type":"attributes"},{"attributeName":"Public IP","attributeValue":"","type":"attributes"},{"attributeName":"User","attributeValue":"","type":"attributes"}]' deploy_req_json = '{"driverRequest":{"actions":[{"actionParams":{"appName":"test_deploy_appname","deployment":{"deploymentPath":"OpenStack Deploy From Glance Image","attributes": ' + dep_atts_json +' ,"type":"deployAppDeploymentInfo"},"appResource":{"attributes":'+ resource_atts_json +',"type":"appResourceInfo"},"type":"deployAppParams"},"actionId":"7808cf76-b8c5-4392-b571-5da99836b84b","type":"deployApp"}]}}' with patch('cloudshell.cp.openstack.openstack_shell.LoggingSessionContext', autospec=True) as mock_logger: mock_log_obj = Mock() mock_logger.return_value.__enter__ = Mock(return_value=mock_log_obj) with patch('cloudshell.cp.openstack.openstack_shell.ErrorHandlingContext'): with patch('cloudshell.cp.openstack.openstack_shell.CloudShellSessionContext'): parser = DriverRequestParser() parser.add_deployment_model(DeployOSNovaImageInstanceDeploymentModel) deploy_app_req = single(parser.convert_driver_request_to_actions(jsonpickle.decode(deploy_req_json)), lambda x: isinstance(x, DeployApp)) # deploy_result = DeployResultModel(vm_name=deploy_app_req.actionParams.appName, # vm_uuid='1234-56', # deployed_app_ip="10.1.1.1", # deployed_app_attributes={'Public IP':'test_public_ip'}, # floating_ip="4.3.2.1", # vm_details_data='') deploy_result = DeployAppResult(vmUuid='1234-56', deployedAppAddress="10.1.1.1",vmName=deploy_app_req.actionParams.appName, deployedAppAttributes=[Attribute('Public IP','test_public_ip')]) self.os_shell_api.deploy_operation.deploy = Mock(return_value=deploy_result) cancellation_context = Mock() res = self.os_shell_api.deploy_instance_from_image(command_context=self.command_context, deploy_app_action=deploy_app_req, cancellation_context=cancellation_context) if isinstance(deploy_app_req ,DeployApp): pass self.assertEqual(res.vmName, deploy_app_req.actionParams.appName) self.assertEqual(res.vmUuid, '1234-56') self.assertEqual(res.deployedAppAddress,"10.1.1.1")
class TestModelParser(TestCase): def setUp(self): pass def test_parse_public_ip_options_attribute_elastic(self): # arrange public_ip_options_val = "Elastic IPs" # act (public, elastic) = AWSModelsParser.parse_public_ip_options_attribute( public_ip_options_val) # assert self.assertFalse(public) self.assertTrue(elastic) def test_parse_public_ip_options_attribute_public(self): # arrange public_ip_options_val = "Public IP" # act (public, elastic) = AWSModelsParser.parse_public_ip_options_attribute( public_ip_options_val) # assert self.assertTrue(public) self.assertFalse(elastic) def test_parse_public_ip_options_attribute_no_public_ip(self): # arrange public_ip_options_val = "No Public IP" # act (public, elastic) = AWSModelsParser.parse_public_ip_options_attribute( public_ip_options_val) # assert self.assertFalse(public) self.assertFalse(elastic) def test_convert_to_deployment_resource_model(self): # Arrange json = '{'\ '"driverRequest": {'\ '"actions": ['\ '{'\ '"actionParams": {'\ '"appName": "AWS",'\ '"deployment": {'\ '"deploymentPath": "AWS EC2 Instance",'\ '"attributes": ['\ '{'\ '"attributeName": "AWS AMI Id",'\ '"attributeValue": "ami_id",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Allow all Sandbox Traffic",'\ '"attributeValue": "True",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Instance Type",'\ '"attributeValue": "t.nano",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Storage Size",'\ '"attributeValue": "0",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Storage IOPS",'\ '"attributeValue": "0",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Storage Type",'\ '"attributeValue": "storage_type",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Inbound Ports",'\ '"attributeValue": "80",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Wait for IP",'\ '"attributeValue": "False",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Wait for Status Check",'\ '"attributeValue": "True",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Autoload",'\ '"attributeValue": "False",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Wait for Credentials",'\ '"attributeValue": "False",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Public IP Options",'\ '"attributeValue": "Elastic IP",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Root Volume Name",'\ '"attributeValue": "root_vol_name",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "IAM Role Name",'\ '"attributeValue": "top secret",'\ '"type": "attribute"'\ '}'\ '],'\ '"type": "deployAppDeploymentInfo"'\ '},'\ '"appResource": {'\ '"attributes": ['\ '{'\ '"attributeName": "Password",'\ '"attributeValue": "3M3u7nkDzxWb0aJ/IZYeWw==",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Public IP",'\ '"attributeValue": "",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "User",'\ '"attributeValue": "",'\ '"type": "attribute"'\ '}'\ '],'\ '"type": "appResourceInfo"'\ '},'\ '"type": "deployAppParams"'\ '},'\ '"actionId": "f09b5640-1349-440d-b66f-f16a3009369f",'\ '"type": "deployApp"'\ '}'\ ']'\ '}'\ '}' # Act self.request_parser = DriverRequestParser() self.request_parser.add_deployment_model( deployment_model_cls=DeployAWSEc2AMIInstanceResourceModel) model = self.request_parser.convert_driver_request_to_actions(json)[0] # Assert self.assertEquals(model.actionParams.deployment.customModel.aws_ami_id, "ami_id") self.assertEquals( model.actionParams.deployment.customModel.storage_size, "0") self.assertEquals( model.actionParams.deployment.customModel.storage_iops, "0") self.assertEquals( model.actionParams.deployment.customModel.storage_type, "storage_type") self.assertEquals( model.actionParams.deployment.customModel.instance_type, "t.nano") self.assertEquals(model.actionParams.deployment.customModel.iam_role, "top secret") self.assertEquals( model.actionParams.deployment.customModel.root_volume_name, "root_vol_name") self.assertFalse(model.actionParams.deployment.customModel.wait_for_ip) self.assertTrue( model.actionParams.deployment.customModel.wait_for_status_check) self.assertFalse(model.actionParams.deployment.customModel.autoload) self.assertEquals( model.actionParams.deployment.customModel.inbound_ports, "80") self.assertFalse( model.actionParams.deployment.customModel.wait_for_credentials) self.assertFalse( model.actionParams.deployment.customModel.add_public_ip) self.assertTrue( model.actionParams.deployment.customModel.allocate_elastic_ip) def test_convert_to_deployment_resource_model_with_network(self): json = '{'\ '"driverRequest": {'\ '"actions": ['\ '{'\ '"actionParams": {'\ '"cidr": "10.0.5.0/28",'\ '"subnetId": "some_id",'\ '"isPublic": true,'\ '"subnetServiceAttributes": ['\ '{'\ '"attributeName": "QnQ",'\ '"attributeValue": "False",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "CTag",'\ '"attributeValue": "",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Subnet Size",'\ '"attributeValue": "16",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Public",'\ '"attributeValue": "True",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Allocated CIDR",'\ '"attributeValue": "10.0.1.0/28",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Subnet Id",'\ '"attributeValue": "some_id",'\ '"type": "attribute"'\ '}'\ '],'\ '"type": "connectToSubnetParams"'\ '},'\ '"actionId": "some_id",'\ '"type": "connectSubnet"'\ '},'\ '{'\ '"actionParams": {'\ '"appName": "AWS",'\ '"deployment": {'\ '"deploymentPath": "AWS EC2 Instance",'\ '"attributes": ['\ '{'\ '"attributeName": "AWS AMI Id",'\ '"attributeValue": "ami-b7b4fedd",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Allow all Sandbox Traffic",'\ '"attributeValue": "True",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Wait for IP",'\ '"attributeValue": "False",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Wait for Status Check",'\ '"attributeValue": "False",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Autoload",'\ '"attributeValue": "True",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Wait for Credentials",'\ '"attributeValue": "True",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Public IP Options",'\ '"attributeValue": "No Public IP",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Root Volume Name",'\ '"attributeValue": "",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "IAM Role Name",'\ '"attributeValue": "",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Instance Type",'\ '"attributeValue": "",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Storage Size",'\ '"attributeValue": "0",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Storage IOPS",'\ '"attributeValue": "0",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Storage Type",'\ '"attributeValue": "auto",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Inbound Ports",'\ '"attributeValue": "",'\ '"type": "attribute"'\ '}'\ '],'\ '"type": "deployAppDeploymentInfo"'\ '},'\ '"appResource": {'\ '"attributes": ['\ '{'\ '"attributeName": "Password",'\ '"attributeValue": "3M3u7nkDzxWb0aJ/IZYeWw==",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Public IP",'\ '"attributeValue": "",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "User",'\ '"attributeValue": "",'\ '"type": "attribute"'\ '}'\ '],'\ '"type": "appResourceInfo"'\ '},'\ '"type": "deployAppParams"'\ '},'\ '"actionId": "bbf48f30-1e75-45b0-b49a-23c5d0213727",'\ '"type": "deployApp"'\ '}'\ ']'\ '}'\ '}' resource = Mock() resource.name = "cloud_provider_name" # Act self.request_parser = DriverRequestParser() self.request_parser.add_deployment_model( deployment_model_cls=DeployAWSEc2AMIInstanceResourceModel) model = self.request_parser.convert_driver_request_to_actions(json)[0] # Assert self.assertEquals(model.actionId, "some_id") self.assertEquals(len(model.actionParams.subnetServiceAttributes), 6) self.assertEquals(model.actionParams.subnetServiceAttributes["Public"], 'True') self.assertTrue(isinstance(model.actionParams, ConnectToSubnetParams)) def test_subnet_connection_params_check_is_public_subnet_true(self): # arrange test_obj = PrepareSubnetParams() attr1 = PrepareCloudInfra() attr1.name = "Some Attribute" attr1.value = "Some Value" attr2 = PrepareCloudInfra() attr2.name = "Public" attr2.value = "True" test_obj.subnetServiceAttributes = [attr1, attr2] # act is_public = test_obj.isPublic # assert self.assertTrue(is_public) def test_subnet_connection_params_check_is_public_subnet_true_when_no_attribute( self): # arrange test_obj = PrepareSubnetParams() attr1 = PrepareCloudInfra() attr1.name = "Some Attribute" attr1.value = "Some Value" test_obj.subnetServiceAttributes = [attr1] # act is_public = test_obj.isPublic # assert self.assertTrue(is_public) def test_parse_bool_value_as_string_and_as_boolean(self): self.assertTrue(convert_to_bool("True")) self.assertTrue(convert_to_bool(True)) self.assertFalse(convert_to_bool("False")) self.assertFalse(convert_to_bool(False))
class TestModelParser(TestCase): def setUp(self): pass def test_parse_public_ip_options_attribute_elastic(self): # arrange public_ip_options_val = "Elastic IPs" # act (public, elastic) = AWSModelsParser.parse_public_ip_options_attribute(public_ip_options_val) # assert self.assertFalse(public) self.assertTrue(elastic) def test_parse_public_ip_options_attribute_public(self): # arrange public_ip_options_val = "Public IP" # act (public, elastic) = AWSModelsParser.parse_public_ip_options_attribute(public_ip_options_val) # assert self.assertTrue(public) self.assertFalse(elastic) def test_parse_public_ip_options_attribute_no_public_ip(self): # arrange public_ip_options_val = "No Public IP" # act (public, elastic) = AWSModelsParser.parse_public_ip_options_attribute(public_ip_options_val) # assert self.assertFalse(public) self.assertFalse(elastic) def test_convert_to_deployment_resource_model(self): # Arrange json = '{'\ '"driverRequest": {'\ '"actions": ['\ '{'\ '"actionParams": {'\ '"appName": "AWS",'\ '"deployment": {'\ '"deploymentPath": "AWS EC2 Instance",'\ '"attributes": ['\ '{'\ '"attributeName": "AWS AMI Id",'\ '"attributeValue": "ami_id",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Allow all Sandbox Traffic",'\ '"attributeValue": "True",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Instance Type",'\ '"attributeValue": "t.nano",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Storage Size",'\ '"attributeValue": "0",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Storage IOPS",'\ '"attributeValue": "0",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Storage Type",'\ '"attributeValue": "storage_type",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Inbound Ports",'\ '"attributeValue": "80",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Wait for IP",'\ '"attributeValue": "False",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Wait for Status Check",'\ '"attributeValue": "True",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Autoload",'\ '"attributeValue": "False",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Wait for Credentials",'\ '"attributeValue": "False",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Public IP Options",'\ '"attributeValue": "Elastic IP",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Root Volume Name",'\ '"attributeValue": "root_vol_name",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "IAM Role Name",'\ '"attributeValue": "top secret",'\ '"type": "attribute"'\ '}'\ '],'\ '"type": "deployAppDeploymentInfo"'\ '},'\ '"appResource": {'\ '"attributes": ['\ '{'\ '"attributeName": "Password",'\ '"attributeValue": "3M3u7nkDzxWb0aJ/IZYeWw==",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Public IP",'\ '"attributeValue": "",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "User",'\ '"attributeValue": "",'\ '"type": "attribute"'\ '}'\ '],'\ '"type": "appResourceInfo"'\ '},'\ '"type": "deployAppParams"'\ '},'\ '"actionId": "f09b5640-1349-440d-b66f-f16a3009369f",'\ '"type": "deployApp"'\ '}'\ ']'\ '}'\ '}' # Act self.request_parser = DriverRequestParser() self.request_parser.add_deployment_model(deployment_model_cls=DeployAWSEc2AMIInstanceResourceModel) model = self.request_parser.convert_driver_request_to_actions(json)[0] # Assert self.assertEquals(model.actionParams.deployment.customModel.aws_ami_id, "ami_id") self.assertEquals(model.actionParams.deployment.customModel.storage_size, "0") self.assertEquals(model.actionParams.deployment.customModel.storage_iops, "0") self.assertEquals(model.actionParams.deployment.customModel.storage_type, "storage_type") self.assertEquals(model.actionParams.deployment.customModel.instance_type, "t.nano") self.assertEquals(model.actionParams.deployment.customModel.iam_role, "top secret") self.assertEquals(model.actionParams.deployment.customModel.root_volume_name, "root_vol_name") self.assertFalse(model.actionParams.deployment.customModel.wait_for_ip) self.assertTrue(model.actionParams.deployment.customModel.wait_for_status_check) self.assertFalse(model.actionParams.deployment.customModel.autoload) self.assertEquals(model.actionParams.deployment.customModel.inbound_ports, "80") self.assertFalse(model.actionParams.deployment.customModel.wait_for_credentials) self.assertFalse(model.actionParams.deployment.customModel.add_public_ip) self.assertTrue(model.actionParams.deployment.customModel.allocate_elastic_ip) def test_convert_to_deployment_resource_model_with_network(self): json = '{'\ '"driverRequest": {'\ '"actions": ['\ '{'\ '"actionParams": {'\ '"cidr": "10.0.5.0/28",'\ '"subnetId": "some_id",'\ '"isPublic": true,'\ '"subnetServiceAttributes": ['\ '{'\ '"attributeName": "QnQ",'\ '"attributeValue": "False",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "CTag",'\ '"attributeValue": "",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Subnet Size",'\ '"attributeValue": "16",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Public",'\ '"attributeValue": "True",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Allocated CIDR",'\ '"attributeValue": "10.0.1.0/28",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Subnet Id",'\ '"attributeValue": "some_id",'\ '"type": "attribute"'\ '}'\ '],'\ '"type": "connectToSubnetParams"'\ '},'\ '"actionId": "some_id",'\ '"type": "connectSubnet"'\ '},'\ '{'\ '"actionParams": {'\ '"appName": "AWS",'\ '"deployment": {'\ '"deploymentPath": "AWS EC2 Instance",'\ '"attributes": ['\ '{'\ '"attributeName": "AWS AMI Id",'\ '"attributeValue": "ami-b7b4fedd",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Allow all Sandbox Traffic",'\ '"attributeValue": "True",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Wait for IP",'\ '"attributeValue": "False",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Wait for Status Check",'\ '"attributeValue": "False",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Autoload",'\ '"attributeValue": "True",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Wait for Credentials",'\ '"attributeValue": "True",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Public IP Options",'\ '"attributeValue": "No Public IP",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Root Volume Name",'\ '"attributeValue": "",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "IAM Role Name",'\ '"attributeValue": "",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Instance Type",'\ '"attributeValue": "",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Storage Size",'\ '"attributeValue": "0",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Storage IOPS",'\ '"attributeValue": "0",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Storage Type",'\ '"attributeValue": "auto",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Inbound Ports",'\ '"attributeValue": "",'\ '"type": "attribute"'\ '}'\ '],'\ '"type": "deployAppDeploymentInfo"'\ '},'\ '"appResource": {'\ '"attributes": ['\ '{'\ '"attributeName": "Password",'\ '"attributeValue": "3M3u7nkDzxWb0aJ/IZYeWw==",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "Public IP",'\ '"attributeValue": "",'\ '"type": "attribute"'\ '},'\ '{'\ '"attributeName": "User",'\ '"attributeValue": "",'\ '"type": "attribute"'\ '}'\ '],'\ '"type": "appResourceInfo"'\ '},'\ '"type": "deployAppParams"'\ '},'\ '"actionId": "bbf48f30-1e75-45b0-b49a-23c5d0213727",'\ '"type": "deployApp"'\ '}'\ ']'\ '}'\ '}' resource = Mock() resource.name = "cloud_provider_name" # Act self.request_parser = DriverRequestParser() self.request_parser.add_deployment_model(deployment_model_cls=DeployAWSEc2AMIInstanceResourceModel) model = self.request_parser.convert_driver_request_to_actions(json)[0] # Assert self.assertEquals(model.actionId, "some_id") self.assertEquals(len(model.actionParams.subnetServiceAttributes), 6) self.assertEquals(model.actionParams.subnetServiceAttributes["Public"], 'True') self.assertTrue(isinstance(model.actionParams, ConnectToSubnetParams)) def test_subnet_connection_params_check_is_public_subnet_true(self): # arrange test_obj = PrepareSubnetParams() attr1 = PrepareCloudInfra() attr1.name = "Some Attribute" attr1.value = "Some Value" attr2 = PrepareCloudInfra() attr2.name = "Public" attr2.value = "True" test_obj.subnetServiceAttributes = [attr1, attr2] # act is_public = test_obj.isPublic # assert self.assertTrue(is_public) def test_subnet_connection_params_check_is_public_subnet_true_when_no_attribute(self): # arrange test_obj = PrepareSubnetParams() attr1 = PrepareCloudInfra() attr1.name = "Some Attribute" attr1.value = "Some Value" test_obj.subnetServiceAttributes = [attr1] # act is_public = test_obj.isPublic # assert self.assertTrue(is_public) def test_parse_bool_value_as_string_and_as_boolean(self): self.assertTrue(convert_to_bool("True")) self.assertTrue(convert_to_bool(True)) self.assertFalse(convert_to_bool("False")) self.assertFalse(convert_to_bool(False))
class L3HeavenlyCloudShellDriver(ResourceDriverInterface): def __init__(self): """ ctor must be without arguments, it is created with reflection at run time """ self.request_parser = DriverRequestParser() def initialize(self, context): """ Initialize the driver session, this function is called everytime a new instance of the driver is created This is a good place to load and cache the driver configuration, initiate sessions etc. :param InitCommandContext context: the context the command runs on """ self.request_parser = DriverRequestParser() self.request_parser.add_deployment_model( HeavenlyCloudAngelDeploymentModel) self.request_parser.add_deployment_model( HeavenlyCloudManDeploymentModel) # <editor-fold desc="Discovery"> def get_inventory(self, context): ## uncomment - if there is nothing to validate # return AutoLoadDetails([], []) # read from context cloud_provider_resource = L3HeavenlyCloudShell.create_from_context( context) with LoggingSessionContext(context) as logger, ErrorHandlingContext( logger): self._log(logger, 'get_inventory_context_json', context) # validating if cloud_provider_resource.name == 'evil': raise ValueError('evil cannot use heaven ') if cloud_provider_resource.region == 'sun': raise ValueError( 'invalid region, sorry cannot deploy instances on the sun') # using your cloud provider sdk if not HeavenlyCloudService.can_connect( cloud_provider_resource.user, cloud_provider_resource.password, context.resource.address ): # TODO add address to resource (gal shellfoundry team) raise ValueError('could not connect using given credentials') # discovering - using your prefered custom cloud service you can discover and then update values if not cloud_provider_resource.heaven_cloud_color: cloud_provider_resource.heaven_cloud_color = HeavenlyCloudService.get_prefered_cloud_color( ) return cloud_provider_resource.create_autoload_details() # </editor-fold> # <editor-fold desc="Mandatory Commands"> def Deploy(self, context, request, cancellation_context=None): """ Deploy :param ResourceCommandContext context: :param str request: A JSON string with the list of requested deployment actions :param CancellationContext cancellation_context: :return: :rtype: str """ with LoggingSessionContext(context) as logger, ErrorHandlingContext( logger): with CloudShellSessionContext(context) as cloudshell_session: self._log(logger, 'deploy_request', request) self._log(logger, 'deploy_context', context) # parse the json strings into action objects cloud_provider_resource = L3HeavenlyCloudShell.create_from_context( context) actions = self.request_parser.convert_driver_request_to_actions( request) # extract DeployApp action deploy_action = single(actions, lambda x: isinstance(x, DeployApp)) # extract ConnectToSubnetActions connect_subnet_actions = list( filter(lambda x: isinstance(x, ConnectSubnet), actions)) # if we have multiple supported deployment options use the 'deploymentPath' property # to decide which deployment option to use. deployment_name = deploy_action.actionParams.deployment.deploymentPath if deployment_name == 'L3HeavenlyCloudShell.HeavenlyCloudAngelDeployment': logger.info('calling deploy_angel') deploy_results = HeavenlyCloudServiceWrapper.deploy_angel( context, cloudshell_session, cloud_provider_resource, deploy_action, connect_subnet_actions, cancellation_context) elif deployment_name == 'L3HeavenlyCloudShell.HeavenlyCloudManDeployment': deploy_results = HeavenlyCloudServiceWrapper.deploy_man( context, cloudshell_session, cloud_provider_resource, deploy_action, connect_subnet_actions, cancellation_context) else: raise ValueError(deployment_name + ' deployment option is not supported.') self._log(logger, 'deployment_name', deployment_name) self._log(logger, 'deploy_results', deploy_results) return DriverResponse(deploy_results).to_driver_response_json() def PowerOn(self, context, ports): """ Will power on the compute resource :param ResourceRemoteCommandContext context: :param ports: """ with LoggingSessionContext(context) as logger, ErrorHandlingContext( logger): self._log(logger, 'power_on_context', context) self._log(logger, 'power_on_ports', ports) cloud_provider_resource = L3HeavenlyCloudShell.create_from_context( context) resource_ep = context.remote_endpoints[0] deployed_app_dict = json.loads( resource_ep.app_context.deployed_app_json) HeavenlyCloudServiceWrapper.power_on( cloud_provider_resource, deployed_app_dict['vmdetails']['uid']) def PowerOff(self, context, ports): """ Will power off the compute resource :param ResourceRemoteCommandContext context: :param ports: """ with LoggingSessionContext(context) as logger, ErrorHandlingContext( logger): self._log(logger, 'power_off_context', context) self._log(logger, 'power_off_ports', ports) cloud_provider_resource = L3HeavenlyCloudShell.create_from_context( context) resource_ep = context.remote_endpoints[0] deployed_app_dict = json.loads( resource_ep.app_context.deployed_app_json) HeavenlyCloudServiceWrapper.power_off( cloud_provider_resource, deployed_app_dict['vmdetails']['uid']) def PowerCycle(self, context, ports, delay): pass def DeleteInstance(self, context, ports): """ Will delete the compute resource :param ResourceRemoteCommandContext context: :param ports: """ with LoggingSessionContext(context) as logger, ErrorHandlingContext( logger): self._log(logger, 'DeleteInstance_context', context) self._log(logger, 'DeleteInstance_ports', ports) cloud_provider_resource = L3HeavenlyCloudShell.create_from_context( context) resource_ep = context.remote_endpoints[0] deployed_app_dict = json.loads( resource_ep.app_context.deployed_app_json) HeavenlyCloudServiceWrapper.delete_instance( cloud_provider_resource, deployed_app_dict['vmdetails']['uid']) def GetVmDetails(self, context, requests, cancellation_context): """ :param ResourceCommandContext context: :param str requests: :param CancellationContext cancellation_context: :return: """ with LoggingSessionContext(context) as logger, ErrorHandlingContext( logger): self._log(logger, 'GetVmDetails_context', context) self._log(logger, 'GetVmDetails_requests', requests) cloud_provider_resource = L3HeavenlyCloudShell.create_from_context( context) result = HeavenlyCloudServiceWrapper.get_vm_details( cloud_provider_resource, cancellation_context, requests) result_json = json.dumps(result, default=lambda o: o.__dict__, sort_keys=True, separators=(',', ':')) self._log(logger, 'GetVmDetails_result', result_json) return result_json def remote_refresh_ip(self, context, ports, cancellation_context): """ Will update the address of the computer resource on the Deployed App resource in cloudshell :param ResourceRemoteCommandContext context: :param ports: :param CancellationContext cancellation_context: :return: """ with LoggingSessionContext(context) as logger, ErrorHandlingContext( logger): with CloudShellSessionContext(context) as cloudshell_session: self._log(logger, 'remote_refresh_ip_context', context) self._log(logger, 'remote_refresh_ip_ports', ports) self._log(logger, 'remote_refresh_ip_cancellation_context', cancellation_context) cloud_provider_resource = L3HeavenlyCloudShell.create_from_context( context) deployed_app_dict = json.loads( context.remote_endpoints[0].app_context.deployed_app_json) remote_ep = context.remote_endpoints[0] deployed_app_private_ip = remote_ep.address deployed_app_public_ip = None public_ip_att = first_or_default( deployed_app_dict['attributes'], lambda x: x['name'] == 'Public IP') if public_ip_att: deployed_app_public_ip = public_ip_att['value'] deployed_app_fullname = remote_ep.fullname vm_instance_id = deployed_app_dict['vmdetails']['uid'] HeavenlyCloudServiceWrapper.remote_refresh_ip( cloud_provider_resource, cancellation_context, cloudshell_session, deployed_app_fullname, vm_instance_id, deployed_app_private_ip, deployed_app_public_ip) # </editor-fold> ### NOTE: According to the Connectivity Type of your shell, remove the commands that are not ### relevant from this file and from drivermetadata.xml. # <editor-fold desc="Mandatory Commands For L3 Connectivity Type"> def PrepareSandboxInfra(self, context, request, cancellation_context): """ :param ResourceCommandContext context: :param str request: :param CancellationContext cancellation_context: :return: :rtype: DriverResponse """ with LoggingSessionContext(context) as logger, ErrorHandlingContext( logger): with CloudShellSessionContext(context) as cloudshell_session: self._log(logger, 'PrepareSandboxInfra_request', request) self._log(logger, 'PrepareSandboxInfra_context', context) cloud_provider_resource = L3HeavenlyCloudShell.create_from_context( context) # parse the json strings into action objects actions = self.request_parser.convert_driver_request_to_actions( request) # extract PrepareCloudInfra action prepare_infa_action = single( actions, lambda x: isinstance(x, PrepareCloudInfra)) # extract CreateKeys action create_keys_action = single( actions, lambda x: isinstance(x, CreateKeys)) # extract PrepareSubnet actions prepare_subnet_actions = list( filter(lambda x: isinstance(x, PrepareSubnet), actions)) action_results = HeavenlyCloudServiceWrapper.prepare_sandbox_infra( logger, cloud_provider_resource, prepare_infa_action, create_keys_action, prepare_subnet_actions, cancellation_context) self._log(logger, 'PrepareSandboxInfra_action_results', action_results) return DriverResponse(action_results).to_driver_response_json() def CleanupSandboxInfra(self, context, request): """ :param ResourceCommandContext context: :param str request: :return: :rtype: str """ with LoggingSessionContext(context) as logger, ErrorHandlingContext( logger): with CloudShellSessionContext(context) as cloudshell_session: self._log(logger, 'CleanupSandboxInfra_request', request) self._log(logger, 'CleanupSandboxInfra_context', context) cloud_provider_resource = L3HeavenlyCloudShell.create_from_context( context) # parse the json strings into action objects actions = self.request_parser.convert_driver_request_to_actions( request) # extract CleanupNetwork action cleanup_action = single( actions, lambda x: isinstance(x, CleanupNetwork)) action_result = HeavenlyCloudServiceWrapper.cleanup_sandbox_infra( cloud_provider_resource, cleanup_action) self._log(logger, 'CleanupSandboxInfra_action_result', action_result) return DriverResponse([action_result ]).to_driver_response_json() # </editor-fold> # <editor-fold desc="Optional Commands For L3 Connectivity Type"> def SetAppSecurityGroups(self, context, request): """ :param ResourceCommandContext context: :param str request: :return: :rtype: str """ pass # </editor-fold> def cleanup(self): """ Destroy the driver session, this function is called everytime a driver instance is destroyed This is a good place to close any open sessions, finish writing to log files, etc. """ pass def _log(self, logger, name, obj): if not obj: logger.info(name + 'Value is None') if not self._is_primitive(obj): name = name + '__json_serialized' obj = json.dumps(obj, default=lambda o: o.__dict__, sort_keys=True, separators=(',', ':')) logger.info(name) logger.info(obj) def _is_primitive(self, thing): primitive = (int, str, bool, float, unicode) return isinstance(thing, primitive)
class OpenStackShellDriver(ResourceDriverInterface): def __init__(self): """ ctor must be without arguments, it is created with reflection at run time """ self.deployments = dict() self.parser = DriverRequestParser() self.parser.add_deployment_model(DeployOSNovaImageInstanceDeploymentModel) self.deployments[DeployOSNovaImageInstanceDeploymentModel.__deploymentModel__] = self.deploy_from_image self.os_shell = OpenStackShell() def Deploy(self, context, request=None, cancellation_context=None): """ :param cloudshell.shell.core.context.ResourceCommandContext context: :param DeployDataHolder request: :param cloudshell.shell.core.context.CancellationContext cancellation_context: :return: """ actions = self.parser.convert_driver_request_to_actions(request) deploy_action = single(actions,lambda x: isinstance(x,DeployApp)) deployment_path = deploy_action.actionParams.deployment.deploymentPath if not deployment_path in self.deployments.keys(): raise Exception('Could not find deployment') deploy_action_result = self.deployments[deployment_path](context, deploy_action, cancellation_context) driver_response = DriverResponse([deploy_action_result]) return driver_response.to_driver_response_json() def initialize(self, context): pass def cleanup(self): pass def deploy_from_image(self, context, request, cancellation_context): """ :param cloudshell.shell.core.context.CancellationContext cancellation_context: :param cloudshell.shell.core.context.ResourceCommandContext context: :param DeployDataHolder request: :rtype : str """ deploy_action_result = self.os_shell.deploy_instance_from_image(command_context=context,deploy_app_action =request, cancellation_context=cancellation_context) return deploy_action_result def ApplyConnectivityChanges(self, context, request): apply_connectivity_results = self.os_shell.apply_connectivity(context, request) driver_response = DriverResponse(apply_connectivity_results) return driver_response.to_driver_response_json() def PowerOn(self, context, ports): return self.os_shell.power_on(context) def PowerOff(self, context, ports): return self.os_shell.power_off(context) def PowerCycle(self, context, ports, delay): pass def DeleteInstance(self, context, ports): return self.os_shell.delete_instance(context) def remote_refresh_ip(self, context, ports, cancellation_context): return self.os_shell.refresh_ip(context) def get_inventory(self, context): return self.os_shell.get_inventory(command_context=context) def GetVmDetails(self, context, cancellation_context, requests): return self.os_shell.get_vm_details(context, cancellation_context, requests)
class HeavenlyCloudsShellDriver(ResourceDriverInterface): def __init__(self): """ ctor must be without arguments, it is created with reflection at run time """ self.request_parser = DriverRequestParser() def initialize(self, context): """ Initialize the driver session, this function is called everytime a new instance of the driver is created This is a good place to load and cache the driver configuration, initiate sessions etc. :param InitCommandContext context: the context the command runs on """ self.request_parser = DriverRequestParser() self.deployments = dict() self.request_parser.add_deployment_model(DeployAngelModel) self.request_parser.add_deployment_model(DeployManModel) # TODO # add custom deployment models to shellfoundry generate # fix or discuss on the fact that deployapp deployment path format is HeavenlyCloudsShell.HeavenlyCloudsAngelDeployment (why namespace?) self.deployments[ DeployAngelModel. __deploymentModel__] = HeavenlyCloudsServiceWrapper.deploy_angel self.deployments[ DeployManModel. __deploymentModel__] = HeavenlyCloudsServiceWrapper.deploy_man # <editor-fold desc="Discovery"> def get_inventory(self, context): # uncomment - if there is nothing to validate # return AutoLoadDetails([], []) # read from context resource = HeavenlyCloudsShell.create_from_context(context) with LoggingSessionContext(context) as logger: with ErrorHandlingContext(logger): self._log_value(logger, 'get_inventory_context_json', context) # validating if resource.name == 'evil': raise ValueError('evil cannot use heaven ') if resource.region == 'sun': raise ValueError( 'invalid region, sorry ca\'nt deploy instances on the sun' ) # using your cloud provider sdk if not HeavenlyCloudsService.can_connect( resource.user, resource.password, context.resource.address ): # TODO add address to resource (gal shellfoundry team) raise ValueError( 'could not connect using given credentials') # discovering - using your prefered custom cloud service you can discover and then update values if not resource.heaven_cloud_color: resource.heaven_cloud_color = HeavenlyCloudsService.get_prefered_cloud_color( ) return resource.create_autoload_details() # </editor-fold> # <editor-fold desc="Mandatory Commands"> def Deploy(self, context, request=None, cancellation_context=None): """ Deploy :param ResourceCommandContext context: :param str request: A JSON string with the list of requested deployment actions :param CancellationContext cancellation_context: :return: :rtype: str """ with LoggingSessionContext(context) as logger: with ErrorHandlingContext(logger): self._log_value(logger, 'deploy_request', request) self._log_value(logger, 'deploy_context', context) # parse the json strings into action objects cloud_provider_resource = HeavenlyCloudsShell.create_from_context( context) actions = self.request_parser.convert_driver_request_to_actions( request) # extract DeployApp action deploy_action = single(actions, lambda x: isinstance(x, DeployApp)) # if we have multiple supported deployment options use the 'deploymentPath' property # to decide which deployment option to use. deployment_name = deploy_action.actionParams.deployment.deploymentPath self._log_value(logger, 'deployment_name', deployment_name) _my_deploy_method = self.deployments[deployment_name] deploy_result = _my_deploy_method(cloud_provider_resource, deploy_action, cancellation_context, logger) self._log_value(logger, 'deploy_result', deploy_result) return DriverResponse([deploy_result ]).to_driver_response_json() def PowerOn(self, context, ports): """ Will power on the compute resource :param ResourceRemoteCommandContext context: :param ports: """ with LoggingSessionContext(context) as logger: with ErrorHandlingContext(logger): self._log_value(logger, 'power_on_context', context) self._log_value(logger, 'power_on_ports', ports) deployed_app_dict = json.loads( context.remote_endpoints[0].app_context.deployed_app_json) cloud_provider_resource = HeavenlyCloudsShell.create_from_context( context) HeavenlyCloudsServiceWrapper.power_on( cloud_provider_resource, deployed_app_dict['vmdetails']['uid']) def PowerOff(self, context, ports): """+ Will power off the compute resource :param ResourceRemoteCommandContext context: :param ports: """ pass def PowerCycle(self, context, ports, delay): pass def DeleteInstance(self, context, ports): """ Will delete the compute resource :param ResourceRemoteCommandContext context: :param ports: """ pass def GetVmDetails(self, context, requests, cancellation_context): """ :param ResourceCommandContext context: :param str requests: :param CancellationContext cancellation_context: :return: """ with LoggingSessionContext(context) as logger: with ErrorHandlingContext(logger): self._log_value(logger, 'GetVmDetails_context', context) self._log_value(logger, 'GetVmDetails_requests', requests) cloud_provider_resource = HeavenlyCloudsShell.create_from_context( context) result = HeavenlyCloudsServiceWrapper.get_vm_details( cloud_provider_resource, cancellation_context, requests) result_json = json.dumps(result, default=lambda o: o.__dict__, sort_keys=True, separators=(',', ':')) self._log_value(logger, 'GetVmDetails_result', result_json) return result_json def remote_refresh_ip(self, context, ports, cancellation_context): """ Will update the address of the computer resource on the Deployed App resource in cloudshell :param ResourceRemoteCommandContext context: :param ports: :param CancellationContext cancellation_context: :return: """ pass # </editor-fold> ### NOTE: According to the Connectivity Type of your shell, remove the commands that are not ### relevant from this file and from drivermetadata.xml. # <editor-fold desc="Mandatory Commands For L2 Connectivity Type"> def ApplyConnectivityChanges(self, context, request): """ Configures VLANs on multiple ports or port-channels :param ResourceCommandContext context: The context object for the command with resource and reservation info :param str request: A JSON string with the list of requested connectivity changes :return: a json object with the list of connectivity changes which were carried out by the driver :rtype: str """ pass # </editor-fold> # <editor-fold desc="Mandatory Commands For L3 Connectivity Type"> def PrepareSandboxInfra(self, context, request, cancellation_context): """ :param ResourceCommandContext context: :param str request: :param CancellationContext cancellation_context: :return: :rtype: str """ ''' # parse the json strings into action objects actions = self.request_parser.convert_driver_request_to_actions(request) action_results = _my_prepare_connectivity(context, actions, cancellation_context) return DriverResponse(action_results).to_driver_response_json() ''' pass def CleanupSandboxInfra(self, context, request): """ :param ResourceCommandContext context: :param str request: :return: :rtype: str """ ''' # parse the json strings into action objects actions = self.request_parser.convert_driver_request_to_actions(request) action_results = _my_cleanup_connectivity(context, actions) return DriverResponse(action_results).to_driver_response_json() ''' pass # </editor-fold> # <editor-fold desc="Optional Commands For L3 Connectivity Type"> def SetAppSecurityGroups(self, context, request): """ :param ResourceCommandContext context: :param str request: :return: :rtype: str """ pass # </editor-fold> def cleanup(self): """ Destroy the driver session, this function is called everytime a driver instance is destroyed This is a good place to close any open sessions, finish writing to log files, etc. """ pass # region helpers def _log_value(self, logger, name, obj): if not obj: logger.info(name + 'Value is None') if not self._is_primitive(obj): name = name + '__json_serialized' obj = json.dumps(obj, default=lambda o: o.__dict__, sort_keys=True, separators=(',', ':')) logger.info(name) logger.info(obj) def _is_primitive(self, thing): primitive = (int, str, bool, float, unicode) return isinstance(thing, primitive)
class AmazonAwsCloudProviderShell2GDriver(ResourceDriverInterface): def cleanup(self): pass def __init__(self): self.aws_shell = AWSShell() self.request_parser = DriverRequestParser() self.request_parser.add_deployment_model( deployment_model_cls=DeployAWSEc2AMIInstanceResourceModel) deploy_name = "Amazon AWS Cloud Provider Shell 2G.Amazon AWS EC2 Instance 2G" self.deployments = {deploy_name: self.deploy_ami} def initialize(self, context): pass def Deploy(self, context, request=None, cancellation_context=None): actions = self.request_parser.convert_driver_request_to_actions( request) deploy_action = single(actions, lambda x: isinstance(x, DeployApp)) deployment_name = deploy_action.actionParams.deployment.deploymentPath self.parse_vnicename(actions) if deployment_name in self.deployments.keys(): deploy_method = self.deployments[deployment_name] deploy_result = deploy_method(context, actions, cancellation_context) return DriverResponse(deploy_result).to_driver_response_json() else: raise Exception("Could not find the deployment") def parse_vnicename(self, actions): network_actions = [a for a in actions if isinstance(a, ConnectSubnet)] for network_action in network_actions: try: network_action.actionParams.vnicName = int( network_action.actionParams.vnicName) except Exception: network_action.actionParams.vnicName = None def deploy_ami(self, context, actions, cancellation_context): return self.aws_shell.deploy_ami(context, actions, cancellation_context) def PowerOn(self, context, ports): return self.aws_shell.power_on_ami(context) def PowerOff(self, context, ports): return self.aws_shell.power_off_ami(context) def orchestration_power_on(self, context, ports): return self.aws_shell.power_on_ami(context) def orchestration_power_off(self, context, ports): return self.aws_shell.power_off_ami(context) def PowerCycle(self, context, ports, delay): pass def remote_refresh_ip(self, context, ports, cancellation_context): return self.aws_shell.refresh_ip(context) def DeleteInstance(self, context, ports): return self.aws_shell.delete_instance(context) def PrepareSandboxInfra(self, context, request, cancellation_context): actions = self.request_parser.convert_driver_request_to_actions( request) action_results = self.aws_shell.prepare_connectivity( context, actions, cancellation_context) return DriverResponse(action_results).to_driver_response_json() def CleanupSandboxInfra(self, context, request): actions = self.request_parser.convert_driver_request_to_actions( request) return self.aws_shell.cleanup_connectivity(context, actions) def GetApplicationPorts(self, context, ports): return self.aws_shell.get_application_ports(context) def get_inventory(self, context): return self.aws_shell.get_inventory(command_context=context) def GetAccessKey(self, context, ports): return self.aws_shell.get_access_key(context) def SetAppSecurityGroups(self, context, request): return self.aws_shell.set_app_security_groups(context, request) def GetVmDetails(self, context, cancellation_context, requests): return self.aws_shell.get_vm_details(context, cancellation_context, requests) def CreateTrafficMirroring(self, context, request, cancellation_context=None): action_results = self.aws_shell.create_traffic_mirroring( context, cancellation_context, request) return DriverResponse(action_results).to_driver_response_json() def RemoveTrafficMirroring(self, context, request): action_results = self.aws_shell.remove_traffic_mirroring( context, request) return DriverResponse(action_results).to_driver_response_json() def AddCustomTags(self, context, request, ports): return self.aws_shell.add_custom_tags(context, request) def save_app(self, context, cancellation_context, ports): return self.aws_shell.save_app(context, cancellation_context) def remote_save_snapshot( self, context: ResourceCommandContext, ports: List[str], snapshot_name: str, save_memory: str, ): """Saves virtual machine to a snapshot. :param context: resource context of the vCenterShell :param ports:list[string] ports: the ports of the connection between the remote resource and the local resource :param snapshot_name: snapshot name to save to :param save_memory: Snapshot the virtual machine's memory. Lookup, Yes / No """ self.aws_shell.remote_save_snapshot(context, snapshot_name) def remote_restore_snapshot(self, context: ResourceCommandContext, ports: List[str], snapshot_name: str): """Restores virtual machine from a snapshot. :param context: resource context of the vCenterShell :param ports:list[string] ports: the ports of the connection between the remote resource and the local resource :param snapshot_name: Snapshot name to restore from """ self.aws_shell.remote_restore_snapshot(context, snapshot_name) def remote_get_snapshots(self, context: ResourceCommandContext, ports: List[str]) -> list: """Returns list of snapshots. :param context: resource context of the vCenterShell :param ports:list[string] ports: the ports of the connection between the remote resource and the local resource """ return self.aws_shell.remote_get_snapshots(context) def assign_additional_private_ipv4s(self, context, ports, vnic_id, new_ips): return self.aws_shell.assign_additional_private_ipv4s( context, vnic_id, new_ips)
class AWSShellDriver(ResourceDriverInterface): def cleanup(self): pass def __init__(self): """ ctor must be without arguments, it is created with reflection at run time """ self.aws_shell = AWSShell() self.request_parser = DriverRequestParser() self.request_parser.add_deployment_model(deployment_model_cls=DeployAWSEc2AMIInstanceResourceModel) self.deployments = dict() self.deployments['AWS EC2 Instance'] = self.deploy_ami def initialize(self, context): pass def Deploy(self, context, request=None, cancellation_context=None): actions = self.request_parser.convert_driver_request_to_actions(request) deploy_action = single(actions, lambda x: isinstance(x, DeployApp)) deployment_name = deploy_action.actionParams.deployment.deploymentPath self.parse_vnicename(actions) if deployment_name in self.deployments.keys(): deploy_method = self.deployments[deployment_name] deploy_result = deploy_method(context, actions, cancellation_context) return DriverResponse(deploy_result).to_driver_response_json() else: raise Exception('Could not find the deployment') def parse_vnicename(self, actions): network_actions = [a for a in actions if isinstance(a, ConnectSubnet)] for network_action in network_actions: try: network_action.actionParams.vnicName = int(network_action.actionParams.vnicName) except: network_action.actionParams.vnicName = None def deploy_ami(self, context, actions, cancellation_context): return self.aws_shell.deploy_ami(context, actions, cancellation_context) def PowerOn(self, context, ports): return self.aws_shell.power_on_ami(context) def PowerOff(self, context, ports): return self.aws_shell.power_off_ami(context) def PowerCycle(self, context, ports, delay): pass def remote_refresh_ip(self, context, ports, cancellation_context): return self.aws_shell.refresh_ip(context) def DeleteInstance(self, context, ports): return self.aws_shell.delete_instance(context) def PrepareSandboxInfra(self, context, request, cancellation_context): actions = self.request_parser.convert_driver_request_to_actions(request) action_results = self.aws_shell.prepare_connectivity(context, actions, cancellation_context) return DriverResponse(action_results).to_driver_response_json() def CleanupSandboxInfra(self, context, request): actions = self.request_parser.convert_driver_request_to_actions(request) return self.aws_shell.cleanup_connectivity(context, actions) def GetApplicationPorts(self, context, ports): return self.aws_shell.get_application_ports(context) def get_inventory(self, context): return AutoLoadDetails([], []) def GetAccessKey(self, context, ports): return self.aws_shell.get_access_key(context) def SetAppSecurityGroups(self, context, request): return self.aws_shell.set_app_security_groups(context, request) def GetVmDetails(self, context, cancellation_context, requests): return self.aws_shell.get_vm_details(context, cancellation_context, requests)