Esempio n. 1
0
    def wait(self, vpc_peering_connection, state, throw_on_error=True, load=False):
        """
        Will sync wait for the change of state of the instance
        :param vpc_peering_connection: vpc_peering_connection object
        :param str state:
        :param boolean throw_on_error: indicates if waiter should throw if in error state
        :param load:
        :return:
        """
        if not vpc_peering_connection:
            raise ValueError('Instance cannot be null')
        if state not in self.STATES:
            raise ValueError('Unsupported vpc peering connection state')

        start_time = time.time()
        while vpc_peering_connection.status['Code'] != state:
            retry_helper.do_with_retry(lambda: vpc_peering_connection.reload())

            if vpc_peering_connection.status['Code'] == state:
                break
            if throw_on_error and vpc_peering_connection.status['Code'] in [VpcPeeringConnectionWaiter.REJECTED,
                                                                            VpcPeeringConnectionWaiter.FAILED]:
                raise Exception('Error: vpc peering connection state is {0}. Expected state: {1}'
                                .format(vpc_peering_connection.status['Code'], state))

            if time.time() - start_time >= self.timeout:
                raise Exception('Timeout waiting for vpc peering connection to be {0}. Current state is {1}'
                                .format(state, vpc_peering_connection.status['Code']))
            time.sleep(self.delay)

        if load:
            retry_helper.do_with_retry(lambda: vpc_peering_connection.reload())
        return vpc_peering_connection
Esempio n. 2
0
    def wait(self, subnet, state, load=False):
        """# noqa
        Will sync wait for the change of state of the subnet
        :param subnet:
        :param state:
        :param load:
        :return:
        """
        if not subnet:
            raise ValueError("Instance cannot be null")
        if state not in self.INSTANCE_STATES:
            raise ValueError("Unsupported instance state")

        retry_helper.do_with_retry(lambda: subnet.reload())

        start_time = time.time()
        while subnet.state != state:

            retry_helper.do_with_retry(lambda: subnet.reload())

            if time.time() - start_time >= self.timeout:
                raise Exception(f"Timeout: Waiting for instance to be {state} from")
            time.sleep(self.delay)

        if load:
            subnet.reload()

        return subnet
Esempio n. 3
0
    def wait(self, subnet, state, load=False):
        """
        Will sync wait for the change of state of the subnet
        :param subnet:
        :param state:
        :param load:
        :return:
        """
        if not subnet:
            raise ValueError('Instance cannot be null')
        if state not in self.INSTANCE_STATES:
            raise ValueError('Unsupported instance state')

        retry_helper.do_with_retry(lambda: subnet.reload())

        start_time = time.time()
        while subnet.state != state:

            retry_helper.do_with_retry(lambda: subnet.reload())

            if time.time() - start_time >= self.timeout:
                raise Exception('Timeout: Waiting for instance to be {0} from'.format(state, subnet.state))
            time.sleep(self.delay)

        if load:
            subnet.reload()

        return subnet
Esempio n. 4
0
    def test_retry_action_executed_3_times(self):
        def test_method():
            TestRetryHelper.counter += 1
            if TestRetryHelper.counter != 3:
                raise Exception()

        retry_helper.do_with_retry(test_method)

        assert TestRetryHelper.counter == 3
    def test_retry_action_executed_3_times(self):
        def test_method():
            TestRetryHelper.counter += 1
            if TestRetryHelper.counter != 3:
                raise Exception()

        retry_helper.do_with_retry(test_method)

        assert TestRetryHelper.counter == 3
Esempio n. 6
0
    def peer_vpcs(self, ec2_session, vpc_id1, vpc_id2, reservation_model,
                  logger):
        """# noqa
        Will create a peering request between 2 vpc's and approve it
        :param logger:
        :param ec2_session: EC2 session
        :param vpc_id1: VPC Id
        :type vpc_id1: str
        :param vpc_id2: VPC Id
        :type vpc_id2: str
        :param reservation_model:
        :type reservation_model: cloudshell.cp.aws.models.reservation_model.ReservationModel  # noqa: E501
        :return: vpc peering id
        """

        # create peering connection
        logger.info(f"Creating VPC Peering between {vpc_id1} to {vpc_id1} ")
        vpc_peer_connection = ec2_session.create_vpc_peering_connection(
            VpcId=vpc_id1, PeerVpcId=vpc_id2)
        logger.info("VPC Peering created {} ,State : {} ".format(
            vpc_peer_connection.id, vpc_peer_connection.status["Code"]))

        # wait until pending acceptance
        logger.info(
            "Waiting until VPC peering state will be pending-acceptance ")
        self.vpc_peering_waiter.wait(
            vpc_peer_connection, self.vpc_peering_waiter.PENDING_ACCEPTANCE)
        logger.info("VPC peering state {}".format(
            vpc_peer_connection.status["Code"]))

        # accept peering request (will try 3 times)
        self.accept_vpc_peering(vpc_peer_connection, logger)

        # wait until active
        logger.info(
            f"Waiting until VPC peering state will be {self.vpc_peering_waiter.ACTIVE}"
        )
        self.vpc_peering_waiter.wait(vpc_peer_connection,
                                     self.vpc_peering_waiter.ACTIVE)
        logger.info("VPC peering state {}".format(
            vpc_peer_connection.status["Code"]))

        # set tags on peering connection
        tags = self.tag_service.get_default_tags(
            self._get_peering_connection_name(reservation_model),
            reservation_model)
        retry_helper.do_with_retry(lambda: ec2_session.create_tags(
            Resources=[vpc_peer_connection.id], Tags=tags))

        return vpc_peer_connection.id
Esempio n. 7
0
    def create_instance(
        self,
        ec2_session,
        name,
        reservation,
        ami_deployment_info,
        ec2_client,
        wait_for_status_check,
        cancellation_context,
        logger,
    ):
        """# noqa
        Deploys an AMI
        :param wait_for_status_check: bool
        :param ec2_client: boto3.ec2.client
        :param str name: Will assign the deployed vm with the name
        :param cloudshell.cp.aws.models.reservation_model.ReservationModel reservation: reservation model
        :param boto3.ec2.session ec2_session:
        :param cloudshell.cp.aws.models.ami_deployment_model.AMIDeploymentModel ami_deployment_info: request details of the AMI
        :param CancellationContext cancellation_context:
        :param logging.Logger logger: logger
        :return:
        """
        instance = ec2_session.create_instances(
            ImageId=ami_deployment_info.aws_ami_id,
            MinCount=ami_deployment_info.min_count,
            MaxCount=ami_deployment_info.max_count,
            InstanceType=ami_deployment_info.instance_type,
            KeyName=ami_deployment_info.aws_key,
            BlockDeviceMappings=ami_deployment_info.block_device_mappings,
            NetworkInterfaces=ami_deployment_info.network_interfaces,
            IamInstanceProfile=ami_deployment_info.iam_role,
            UserData=ami_deployment_info.user_data,
        )[0]

        self.wait_for_instance_to_run_in_aws(
            ec2_client=ec2_client,
            instance=instance,
            wait_for_status_check=wait_for_status_check,
            cancellation_context=cancellation_context,
            logger=logger,
        )

        self._set_tags(instance, name, reservation, ami_deployment_info.custom_tags)

        # Reload the instance attributes
        retry_helper.do_with_retry(lambda: instance.load())
        return instance
Esempio n. 8
0
    def wait(self, vpc, state):
        """Will sync wait for the change of state of the vpc."""
        if not vpc:
            raise ValueError("Instance cannot be null")
        if state not in self.INSTANCE_STATES:
            raise ValueError("Unsupported instance state")

        start_time = time.time()
        while vpc.state != state:
            time.sleep(self.delay)
            if time.time() - start_time >= self.timeout:
                raise Exception(
                    f"Timeout: Waiting for instance to be {state} from")

            retry_helper.do_with_retry(lambda: vpc.reload())

        return vpc
Esempio n. 9
0
    def wait(self,
             vpc_peering_connection,
             state,
             throw_on_error=True,
             load=False):
        """# noqa
        Will sync wait for the change of state of the instance
        :param vpc_peering_connection: vpc_peering_connection object
        :param str state:
        :param boolean throw_on_error: indicates if waiter should throw if in error state
        :param load:
        :return:
        """
        if not vpc_peering_connection:
            raise ValueError("Instance cannot be null")
        if state not in self.STATES:
            raise ValueError("Unsupported vpc peering connection state")

        start_time = time.time()
        while vpc_peering_connection.status["Code"] != state:
            retry_helper.do_with_retry(lambda: vpc_peering_connection.reload())

            if vpc_peering_connection.status["Code"] == state:
                break
            if throw_on_error and vpc_peering_connection.status["Code"] in [
                    VpcPeeringConnectionWaiter.REJECTED,
                    VpcPeeringConnectionWaiter.FAILED,
            ]:
                raise Exception(
                    "Error: vpc peering connection state is {}. Expected state: "
                    "{}".format(vpc_peering_connection.status["Code"], state))

            if time.time() - start_time >= self.timeout:
                raise Exception(
                    "Timeout waiting for vpc peering connection to be {}. "
                    "Current state is {}".format(
                        state, vpc_peering_connection.status["Code"]))
            time.sleep(self.delay)

        if load:
            retry_helper.do_with_retry(lambda: vpc_peering_connection.reload())
        return vpc_peering_connection
Esempio n. 10
0
    def wait(self, vpc, state):
        """
        Will sync wait for the change of state of the vpc
        :param vpc:
        :param state:
        :param load:
        :return:
        """
        if not vpc:
            raise ValueError('Instance cannot be null')
        if state not in self.INSTANCE_STATES:
            raise ValueError('Unsupported instance state')

        start_time = time.time()
        while vpc.state != state:
            time.sleep(self.delay)
            if time.time() - start_time >= self.timeout:
                raise Exception('Timeout: Waiting for instance to be {0} from'.format(state, vpc.state))

            retry_helper.do_with_retry(lambda: vpc.reload())

        return vpc
Esempio n. 11
0
    def peer_vpcs(self, ec2_session, vpc_id1, vpc_id2, reservation_model, logger):
        """
        Will create a peering request between 2 vpc's and approve it
        :param logger:
        :param ec2_session: EC2 session
        :param vpc_id1: VPC Id
        :type vpc_id1: str
        :param vpc_id2: VPC Id
        :type vpc_id2: str
        :param reservation_model:
        :type reservation_model: cloudshell.cp.aws.models.reservation_model.ReservationModel
        :return: vpc peering id
        """

        # create peering connection
        logger.info("Creating VPC Peering between {0} to {1} ".format(vpc_id1, vpc_id1))
        vpc_peer_connection = ec2_session.create_vpc_peering_connection(VpcId=vpc_id1, PeerVpcId=vpc_id2)
        logger.info(
            "VPC Peering created {0} ,State : {1} ".format(vpc_peer_connection.id, vpc_peer_connection.status['Code']))

        # wait until pending acceptance
        logger.info("Waiting until VPC peering state will be pending-acceptance ")
        self.vpc_peering_waiter.wait(vpc_peer_connection, self.vpc_peering_waiter.PENDING_ACCEPTANCE)
        logger.info("VPC peering state {0}".format(vpc_peer_connection.status['Code']))

        # accept peering request (will try 3 times)
        self.accept_vpc_peering(vpc_peer_connection, logger)

        # wait until active
        logger.info("Waiting until VPC peering state will be {0}".format(self.vpc_peering_waiter.ACTIVE))
        self.vpc_peering_waiter.wait(vpc_peer_connection, self.vpc_peering_waiter.ACTIVE)
        logger.info("VPC peering state {0}".format(vpc_peer_connection.status['Code']))

        # set tags on peering connection
        tags = self.tag_service.get_default_tags(self._get_peering_connection_name(reservation_model),
                                                 reservation_model)
        retry_helper.do_with_retry(lambda: ec2_session.create_tags(Resources=[vpc_peer_connection.id], Tags=tags))

        return vpc_peer_connection.id
Esempio n. 12
0
    def create_instance(self, ec2_session, name, reservation, ami_deployment_info, ec2_client, wait_for_status_check,
                        cancellation_context, logger):
        """
        Deploys an AMI
        :param wait_for_status_check: bool
        :param ec2_client: boto3.ec2.client
        :param str name: Will assign the deployed vm with the name
        :param cloudshell.cp.aws.models.reservation_model.ReservationModel reservation: reservation model
        :param boto3.ec2.session ec2_session:
        :param cloudshell.cp.aws.models.ami_deployment_model.AMIDeploymentModel ami_deployment_info: request details of the AMI
        :param CancellationContext cancellation_context:
        :param logging.Logger logger: logger
        :return:
        """
        instance = ec2_session.create_instances(
                ImageId=ami_deployment_info.aws_ami_id,
                MinCount=ami_deployment_info.min_count,
                MaxCount=ami_deployment_info.max_count,
                InstanceType=ami_deployment_info.instance_type,
                KeyName=ami_deployment_info.aws_key,
                BlockDeviceMappings=ami_deployment_info.block_device_mappings,
                NetworkInterfaces=ami_deployment_info.network_interfaces,
                IamInstanceProfile=ami_deployment_info.iam_role
                # PrivateIpAddress=ami_deployment_info.private_ip_address
        )[0]

        self.wait_for_instance_to_run_in_aws(ec2_client=ec2_client,
                                             instance=instance,
                                             wait_for_status_check=wait_for_status_check,
                                             cancellation_context=cancellation_context,
                                             logger=logger)

        self._set_tags(instance, name, reservation)

        # Reload the instance attributes
        retry_helper.do_with_retry(lambda: instance.load())
        return instance