def __init__(self):
        self.image_waiter = AMIWaiter()
        self.command_result_parser = CommandResultsParser()
        self.cancellation_service = CommandCancellationService()
        self.client_err_wrapper = ClientErrorWrapper()
        self.tag_service = TagService(
            client_err_wrapper=self.client_err_wrapper)
        self.ec2_instance_waiter = InstanceWaiter(
            cancellation_service=self.cancellation_service)
        self.instance_service = InstanceService(self.tag_service,
                                                self.ec2_instance_waiter)
        self.ec2_storage_service = EC2StorageService()
        self.model_parser = AWSModelsParser()
        self.cloudshell_session_helper = CloudshellDriverHelper()
        self.aws_session_manager = AWSSessionProvider()
        self.password_waiter = PasswordWaiter(self.cancellation_service)
        self.vm_custom_params_extractor = VmCustomParamsExtractor()
        self.ami_credentials_service = InstanceCredentialsService(
            self.password_waiter)
        self.security_group_service = SecurityGroupService(self.tag_service)
        self.subnet_waiter = SubnetWaiter()
        self.subnet_service = SubnetService(self.tag_service,
                                            self.subnet_waiter)
        self.s3_service = S3BucketService()
        self.vpc_peering_waiter = VpcPeeringConnectionWaiter()
        self.key_pair_service = KeyPairService(self.s3_service)
        self.vpc_waiter = VPCWaiter()
        self.route_tables_service = RouteTablesService(self.tag_service)
        self.network_interface_service = NetworkInterfaceService(
            subnet_service=self.subnet_service,
            security_group_service=self.security_group_service,
        )
        self.elastic_ip_service = ElasticIpService()
        self.vm_details_provider = VmDetailsProvider()
        self.session_number_service = SessionNumberService()
        self.traffic_mirror_service = TrafficMirrorService()
        self.request_parser = DriverRequestParser()

        self.vpc_service = VPCService(
            tag_service=self.tag_service,
            subnet_service=self.subnet_service,
            instance_service=self.instance_service,
            vpc_waiter=self.vpc_waiter,
            vpc_peering_waiter=self.vpc_peering_waiter,
            sg_service=self.security_group_service,
            route_table_service=self.route_tables_service,
            traffic_mirror_service=self.traffic_mirror_service,
        )
        self.prepare_connectivity_operation = PrepareSandboxInfraOperation(
            vpc_service=self.vpc_service,
            security_group_service=self.security_group_service,
            key_pair_service=self.key_pair_service,
            tag_service=self.tag_service,
            route_table_service=self.route_tables_service,
            cancellation_service=self.cancellation_service,
            subnet_service=self.subnet_service,
            subnet_waiter=self.subnet_waiter,
        )

        self.deploy_ami_operation = DeployAMIOperation(
            instance_service=self.instance_service,
            ami_credential_service=self.ami_credentials_service,
            security_group_service=self.security_group_service,
            tag_service=self.tag_service,
            vpc_service=self.vpc_service,
            key_pair_service=self.key_pair_service,
            subnet_service=self.subnet_service,
            elastic_ip_service=self.elastic_ip_service,
            network_interface_service=self.network_interface_service,
            cancellation_service=self.cancellation_service,
            device_index_strategy=AllocateMissingValuesDeviceIndexStrategy(),
            vm_details_provider=self.vm_details_provider,
        )

        self.refresh_ip_operation = RefreshIpOperation(
            instance_service=self.instance_service)

        self.power_management_operation = PowerOperation(
            instance_service=self.instance_service,
            instance_waiter=self.ec2_instance_waiter,
        )

        self.delete_ami_operation = DeleteAMIOperation(
            instance_service=self.instance_service,
            ec2_storage_service=self.ec2_storage_service,
            security_group_service=self.security_group_service,
            tag_service=self.tag_service,
            elastic_ip_service=self.elastic_ip_service,
        )

        self.clean_up_operation = CleanupSandboxInfraOperation(
            vpc_service=self.vpc_service,
            key_pair_service=self.key_pair_service,
            route_table_service=self.route_tables_service,
            traffic_mirror_service=self.traffic_mirror_service,
        )

        self.deployed_app_ports_operation = DeployedAppPortsOperation(
            self.vm_custom_params_extractor,
            security_group_service=self.security_group_service,
            instance_service=self.instance_service,
        )

        self.access_key_operation = GetAccessKeyOperation(
            key_pair_service=self.key_pair_service)

        self.set_app_security_groups_operation = SetAppSecurityGroupsOperation(
            instance_service=self.instance_service,
            tag_service=self.tag_service,
            security_group_service=self.security_group_service,
        )

        self.vm_details_operation = VmDetailsOperation(
            instance_service=self.instance_service,
            vm_details_provider=self.vm_details_provider,
        )

        self.autoload_operation = AutoloadOperation()

        self.snapshot_operation = SnapshotOperation(self.instance_service,
                                                    self.image_waiter)

        self.traffic_mirroring_operation = TrafficMirrorOperation(
            tag_service=self.tag_service,
            session_number_service=self.session_number_service,
            traffic_mirror_service=self.traffic_mirror_service,
            cancellation_service=self.cancellation_service,
        )
示例#2
0
class TestInstanceWaiter(TestCase):
    def setUp(self):
        self.cancellation_service = Mock()
        self.instance_waiter = InstanceWaiter(self.cancellation_service, 1, 0.02)
        self.instance = Mock()
        self.logger = Mock()

    @patch('time.sleep', helper.change_to_stopped)
    def test_waiter(self):
        helper.change_to_running(Mock())
        inst = self.instance_waiter.wait(instance, InstanceWaiter.STOPPED)
        self.assertEqual(inst, instance)
        self.assertEqual(inst.reload.call_count, 1)

    def test_waiter_timeout(self):
        helper.change_to_running(Mock())
        self.assertRaises(Exception, self.instance_waiter.wait, instance, InstanceWaiter.STOPPED)

    @patch('time.sleep', helper.change_to_stopped)
    def test_waiter_multi(self):
        helper.change_to_stopped(Mock())

        instance.state['Name'] = InstanceWaiter.RUNNING

        inst = Mock()
        inst.state = dict()
        inst.state['Name'] = InstanceWaiter.STOPPED

        res = self.instance_waiter.multi_wait([instance, inst], InstanceWaiter.STOPPED)
        self.assertEqual(res, [instance, inst])
        self.assertTrue(instance.reload.call_count, 2)

    @patch('time.sleep', helper.change_to_stopped)
    def test_waiter_multi_with_cancellation(self):
        cancellation_context = Mock()
        helper.change_to_stopped(Mock())

        instance.state['Name'] = InstanceWaiter.RUNNING

        inst = Mock()
        inst.state = dict()
        inst.state['Name'] = InstanceWaiter.STOPPED

        instances = [instance, inst]

        res = self.instance_waiter.multi_wait(instances, InstanceWaiter.STOPPED, cancellation_context)

        self.assertEqual(res, [instance, inst])
        self.assertTrue(instance.reload.call_count, 2)
        self.assertTrue(self.cancellation_service.check_if_cancelled.call_count, 2)
        instance_ids = filter(lambda x: str(x.id), instances)
        self.cancellation_service.check_if_cancelled.assert_called_with(cancellation_context,
                                                                        {'instance_ids': instance_ids})

    def test_waiter_multi_errors(self):
        self.assertRaises(ValueError, self.instance_waiter.multi_wait, [], InstanceWaiter.STOPPED)
        self.assertRaises(ValueError, self.instance_waiter.multi_wait, [Mock], 'blalala')

    @patch('cloudshell.cp.aws.domain.services.waiters.instance.time')
    def test_wait_status_ok(self, time):
        # arrange
        def describe_instance_status_handler(*args, **kwargs):
            result = Mock()
            instance_id_mock = kwargs['InstanceIds'][0]
            if hasattr(instance_id_mock, "called_already") and instance_id_mock.called_already is True:
                result.InstanceStatuses = [{'SystemStatus': {'Status': self.instance_waiter.STATUS_OK},
                                            'InstanceStatus': {'Status': self.instance_waiter.STATUS_OK}}]
            else:
                instance_id_mock.called_already = True
                result.InstanceStatuses = [
                    {'SystemStatus': {'Status': 'initializing'}, 'InstanceStatus': {'Status': 'initializing'}}]

            return result

        ec2_client = Mock()
        ec2_client.describe_instance_status = Mock(side_effect=describe_instance_status_handler)
        instance = Mock()

        # act
        instance_state = self.instance_waiter.wait_status_ok(ec2_client=ec2_client,
                                                             instance=instance,
                                                             logger=self.logger)

        # assert
        self.assertEquals(instance_state['SystemStatus']['Status'], self.instance_waiter.STATUS_OK)
        self.assertEquals(instance_state['InstanceStatus']['Status'], self.instance_waiter.STATUS_OK)

    @patch('cloudshell.cp.aws.domain.services.waiters.instance.time')
    def test_wait_status_ok_raises_impaired_status(self, time):
        # arrange
        def describe_instance_status_handler(*args, **kwargs):
            result = Mock()
            instance_id_mock = kwargs['InstanceIds'][0]
            if hasattr(instance_id_mock, "called_already") and instance_id_mock.called_already is True:
                result.InstanceStatuses = [{'SystemStatus': {'Status': self.instance_waiter.STATUS_IMPAIRED},
                                            'InstanceStatus': {'Status': self.instance_waiter.STATUS_IMPAIRED}}]
            else:
                instance_id_mock.called_already = True
                result.InstanceStatuses = [
                    {'SystemStatus': {'Status': 'initializing'}, 'InstanceStatus': {'Status': 'initializing'}}]

            return result

        ec2_client = Mock()
        ec2_client.describe_instance_status = Mock(side_effect=describe_instance_status_handler)
        instance = Mock()

        # act & assert
        with self.assertRaisesRegexp(ValueError, "Instance status check is not OK.*"):
            instance_state = self.instance_waiter.wait_status_ok(ec2_client=ec2_client,
                                                                 instance=instance,
                                                                 logger=self.logger)
示例#3
0
 def setUp(self):
     self.cancellation_service = Mock()
     self.instance_waiter = InstanceWaiter(self.cancellation_service, 1, 0.02)
     self.instance = Mock()
     self.logger = Mock()
示例#4
0
class TestInstanceWaiter(TestCase):
    def setUp(self):
        self.cancellation_service = Mock()
        self.instance_waiter = InstanceWaiter(self.cancellation_service, 1,
                                              0.02)
        self.instance = Mock()
        self.logger = Mock()

    @patch("time.sleep", helper.change_to_stopped)
    def test_waiter(self):
        helper.change_to_running(Mock())
        inst = self.instance_waiter.wait(instance, InstanceWaiter.STOPPED)
        self.assertEqual(inst, instance)
        self.assertEqual(inst.reload.call_count, 1)

    def test_waiter_timeout(self):
        helper.change_to_running(Mock())
        self.assertRaises(Exception, self.instance_waiter.wait, instance,
                          InstanceWaiter.STOPPED)

    @patch("time.sleep", helper.change_to_stopped)
    def test_waiter_multi(self):
        helper.change_to_stopped(Mock())

        instance.state["Name"] = InstanceWaiter.RUNNING

        inst = Mock()
        inst.state = {}
        inst.state["Name"] = InstanceWaiter.STOPPED

        res = self.instance_waiter.multi_wait([instance, inst],
                                              InstanceWaiter.STOPPED)
        self.assertEqual(res, [instance, inst])
        self.assertTrue(instance.reload.call_count, 2)

    @patch("cloudshell.cp.aws.domain.services.waiters.instance.time.sleep",
           Mock())
    def test_waiter_multi_with_cancellation(self):
        cancellation_context = Mock()
        helper.change_to_stopped(Mock())
        inst1 = Mock()
        inst2 = Mock(state={"Name": InstanceWaiter.STOPPED})
        p = PropertyMock(side_effect=[
            {
                "Name": InstanceWaiter.RUNNING
            },
            {
                "Name": InstanceWaiter.STOPPED
            },
        ])
        type(inst1).state = p
        instances = [inst1, inst2]

        res = self.instance_waiter.multi_wait(instances,
                                              InstanceWaiter.STOPPED,
                                              cancellation_context)

        self.assertEqual(res, [inst1, inst2])
        self.assertTrue(inst1.reload.call_count, 2)
        self.assertTrue(
            self.cancellation_service.check_if_cancelled.call_count, 2)
        instance_ids = set(filter(lambda x: str(x.id), instances))
        self.cancellation_service.check_if_cancelled.assert_called_with(
            cancellation_context, {"instance_ids": instance_ids})

    def test_waiter_multi_errors(self):
        self.assertRaises(ValueError, self.instance_waiter.multi_wait, [],
                          InstanceWaiter.STOPPED)
        self.assertRaises(ValueError, self.instance_waiter.multi_wait, [Mock],
                          "blalala")

    @patch(
        "cloudshell.cp.aws.domain.services.waiters.instance.time",
        Mock(time=Mock(return_value=time.time())),
    )
    def test_wait_status_ok(self):
        # arrange
        def describe_instance_status_handler(*args, **kwargs):
            result = Mock()
            instance_id_mock = kwargs["InstanceIds"][0]
            if (hasattr(instance_id_mock, "called_already")
                    and instance_id_mock.called_already is True):
                result.InstanceStatuses = [{
                    "SystemStatus": {
                        "Status": self.instance_waiter.STATUS_OK
                    },
                    "InstanceStatus": {
                        "Status": self.instance_waiter.STATUS_OK
                    },
                }]
            else:
                instance_id_mock.called_already = True
                result.InstanceStatuses = [{
                    "SystemStatus": {
                        "Status": "initializing"
                    },
                    "InstanceStatus": {
                        "Status": "initializing"
                    },
                }]

            return result

        ec2_client = Mock()
        ec2_client.describe_instance_status = Mock(
            side_effect=describe_instance_status_handler)
        instance = Mock()

        # act
        instance_state = self.instance_waiter.wait_status_ok(
            ec2_client=ec2_client, instance=instance, logger=self.logger)

        # assert
        self.assertEquals(instance_state["SystemStatus"]["Status"],
                          self.instance_waiter.STATUS_OK)
        self.assertEquals(instance_state["InstanceStatus"]["Status"],
                          self.instance_waiter.STATUS_OK)

    @patch(
        "cloudshell.cp.aws.domain.services.waiters.instance.time",
        Mock(time=Mock(return_value=time.time())),
    )
    def test_wait_status_ok_raises_impaired_status(self):
        # arrange
        def describe_instance_status_handler(*args, **kwargs):
            result = Mock()
            instance_id_mock = kwargs["InstanceIds"][0]
            if (hasattr(instance_id_mock, "called_already")
                    and instance_id_mock.called_already is True):
                result.InstanceStatuses = [{
                    "SystemStatus": {
                        "Status": self.instance_waiter.STATUS_IMPAIRED
                    },
                    "InstanceStatus": {
                        "Status": self.instance_waiter.STATUS_IMPAIRED
                    },
                }]
            else:
                instance_id_mock.called_already = True
                result.InstanceStatuses = [{
                    "SystemStatus": {
                        "Status": "initializing"
                    },
                    "InstanceStatus": {
                        "Status": "initializing"
                    },
                }]

            return result

        ec2_client = Mock()
        ec2_client.describe_instance_status = Mock(
            side_effect=describe_instance_status_handler)
        instance = Mock()

        # act & assert
        with self.assertRaisesRegexp(ValueError,
                                     "Instance status check is not OK.*"):
            self.instance_waiter.wait_status_ok(ec2_client=ec2_client,
                                                instance=instance,
                                                logger=self.logger)