def test_callback_func(virtual_network, config):
    name = "pythonsdk_waiter_" + tests.util.random_number_string()

    counters = {'create': 0, 'delete': 0}

    def create_vcn_callback(times_called, response):
        counters['create'] = times_called

    def delete_vcn_callback(times_called, response):
        counters['delete'] = times_called

    request = oci.core.models.CreateVcnDetails()
    request.cidr_block = '10.0.0.0/16'
    request.display_name = name
    request.compartment_id = config["tenancy"]

    response = virtual_network.create_vcn(request)
    vcn = response.data
    get_vcn_response = virtual_network.get_vcn(vcn.id)
    get_vcn_response.data.lifecycle_state = 'DUMMY'  # This will force at least one service call
    response = oci.wait_until(virtual_network, get_vcn_response, 'lifecycle_state', 'AVAILABLE', wait_callback=create_vcn_callback)
    assert 'AVAILABLE' == response.data.lifecycle_state
    assert counters['create'] > 0

    print('Deleting vcn')
    response = virtual_network.delete_vcn(vcn.id)
    result = oci.wait_until(virtual_network, get_vcn_response, 'lifecycle_state', 'TERMINATED', max_wait_seconds=180, succeed_on_not_found=True, wait_callback=delete_vcn_callback)
    assert result == oci.waiter.WAIT_RESOURCE_NOT_FOUND
    assert counters['delete'] >= 0
def delete_vcn_and_subnet(virtual_network, vcn_and_subnet):
    vcn = vcn_and_subnet['vcn']
    subnet = vcn_and_subnet['subnet']

    # Sometimes we can't delete the subnet straight after a mount target has been deleted as network resources
    # still need to clear. If we get a conflict, try a few times before bailing out
    attempts = 0
    while attempts < 5:
        try:
            virtual_network.delete_subnet(subnet.id)
            oci.wait_until(
                virtual_network,
                virtual_network.get_subnet(subnet.id),
                'lifecycle_state',
                'TERMINATED',
                max_wait_seconds=600,
                succeed_on_not_found=True
            )
            break
        except oci.exceptions.ServiceError as e:
            attempts += 1
            if e.status == 409 and attempts < 5:
                time.sleep(5)
            else:
                raise

    virtual_network.delete_vcn(vcn.id)
    oci.wait_until(
        virtual_network,
        virtual_network.get_vcn(vcn.id),
        'lifecycle_state',
        'TERMINATED',
        max_wait_seconds=600,
        succeed_on_not_found=True
    )
def delete_vcn_and_subnet(virtual_network, vcn_and_subnet):
    vcn = vcn_and_subnet['vcn']
    subnet = vcn_and_subnet['subnet']

    virtual_network.delete_subnet(subnet.id)
    oci.wait_until(
        virtual_network,
        virtual_network.get_subnet(subnet.id),
        'lifecycle_state',
        'TERMINATED',
        max_wait_seconds=300,
        # For a deletion, the record may no longer be available and the waiter may encounter a 404 when trying to retrieve it.
        # This flag tells the waiter to consider 404s as successful (which is only really valid for delete/terminate since
        # the record not being there anymore can signify a successful delete/terminate)
        succeed_on_not_found=True
    )

    virtual_network.delete_vcn(vcn.id)
    oci.wait_until(
        virtual_network,
        virtual_network.get_vcn(vcn.id),
        'lifecycle_state',
        'TERMINATED',
        max_wait_seconds=300,
        succeed_on_not_found=True
    )
def create_vcn_drg_and_drg_attachment(virtual_network_client, compartment_id, cidr_block, vcn_dns_label):
    vcn_name = 'py_sdk_example_vcn'

    result = virtual_network_client.create_vcn(
        oci.core.models.CreateVcnDetails(
            cidr_block=cidr_block,
            display_name=vcn_name,
            compartment_id=compartment_id,
            dns_label=vcn_dns_label
        )
    )
    vcn = oci.wait_until(
        virtual_network_client,
        virtual_network_client.get_vcn(result.data.id),
        'lifecycle_state',
        'AVAILABLE',
        max_wait_seconds=300
    ).data
    print('Created VCN')
    print('===============')
    print(vcn)
    print('\n\n')

    result = virtual_network_client.create_drg(
        oci.core.models.CreateDrgDetails(
            compartment_id=compartment_id,
            display_name='Python SDK Example DRG'
        )
    )
    drg = oci.wait_until(
        virtual_network_client,
        virtual_network_client.get_drg(result.data.id),
        'lifecycle_state',
        'AVAILABLE'
    ).data
    print('Created DRG')
    print('===============')
    print(drg)
    print('\n\n')

    result = virtual_network_client.create_drg_attachment(
        oci.core.models.CreateDrgAttachmentDetails(
            display_name='Python SDK Example DRG Attachment',
            vcn_id=vcn.id,
            drg_id=drg.id
        )
    )
    drg_attachment = oci.wait_until(
        virtual_network_client,
        virtual_network_client.get_drg_attachment(result.data.id),
        'lifecycle_state',
        'ATTACHED'
    ).data
    print('Created DRG Attachment')
    print('=========================')
    print(drg_attachment)
    print('\n\n')

    return {'vcn': vcn, 'drg': drg, 'drg_attachment': drg_attachment}
def delete_volume(block_storage, volume):
    block_storage.delete_volume(volume.id)
    oci.wait_until(
        block_storage,
        block_storage.get_volume(volume.id),
        'lifecycle_state',
        'TERMINATED'
    )
def detach_volume(compute, volume_attachment):
    compute.detach_volume(volume_attachment.id)
    oci.wait_until(
        compute,
        compute.get_volume_attachment(volume_attachment.id),
        'lifecycle_state',
        'DETACHED'
    )
def terminate_instance(compute, instance):
    compute.terminate_instance(instance.id)
    oci.wait_until(
        compute,
        compute.get_instance(instance.id),
        'lifecycle_state',
        'TERMINATED',
        max_wait_seconds=300,
        succeed_on_not_found=True
    )
def delete_subnet(virtual_network, subnet):
    virtual_network.delete_subnet(subnet.id)
    oci.wait_until(
        virtual_network,
        virtual_network.get_subnet(subnet.id),
        'lifecycle_state',
        'TERMINATED',
        succeed_on_not_found=True
    )
    print('Deleted Subnet: {}'.format(subnet.id))
def delete_internet_gateway(virtual_network, internet_gateway):
    virtual_network.delete_internet_gateway(internet_gateway.id)
    oci.wait_until(
        virtual_network,
        virtual_network.get_internet_gateway(internet_gateway.id),
        'lifecycle_state',
        'TERMINATED',
        succeed_on_not_found=True
    )
    print('Deleted Internet Gateway: {}'.format(internet_gateway.id))
def clear_route_rules_from_default_route_table(virtual_network, vcn):
    virtual_network.update_route_table(
        vcn.default_route_table_id,
        oci.core.models.UpdateRouteTableDetails(route_rules=[])
    )
    oci.wait_until(
        virtual_network,
        virtual_network.get_route_table(vcn.default_route_table_id),
        'lifecycle_state',
        'AVAILABLE'
    )
    print('Cleared route rules from route table: {}'.format(vcn.default_route_table_id))
def delete_vcn(virtual_network, vcn):
    virtual_network.delete_vcn(vcn.id)
    oci.wait_until(
        virtual_network,
        virtual_network.get_vcn(vcn.id),
        'lifecycle_state',
        'TERMINATED',
        # For a deletion, the record may no longer be available and the waiter may encounter a 404 when trying to retrieve it.
        # This flag tells the waiter to consider 404s as successful (which is only really valid for delete/terminate since
        # the record not being there anymore can signify a successful delete/terminate)
        succeed_on_not_found=True
    )
    print('Deleted VCN: {}'.format(vcn.id))
def launch_instance(compute, compartment_id, subnet, image_id):
    create_instance_details = oci.core.models.LaunchInstanceDetails()
    create_instance_details.compartment_id = compartment_id
    create_instance_details.availability_domain = subnet.availability_domain
    create_instance_details.display_name = 'pub_ip_test_instance'
    create_instance_details.create_vnic_details = oci.core.models.CreateVnicDetails(
        subnet_id=subnet.id,
        # We don't assign a public IP here so that we can demonstrate public IP functionality later on
        # in the script
        assign_public_ip=False
    )
    create_instance_details.image_id = image_id
    create_instance_details.shape = 'VM.Standard1.1'

    result = compute.launch_instance(create_instance_details)
    instance_ocid = result.data.id

    get_instance_response = oci.wait_until(
        compute,
        compute.get_instance(instance_ocid),
        'lifecycle_state',
        'RUNNING',
        max_wait_seconds=600
    )
    print('Launched instance')

    return get_instance_response.data
def add_route_rule_to_default_route_table_for_internet_gateway(virtual_network, vcn, internet_gateway):
    get_route_table_response = virtual_network.get_route_table(vcn.default_route_table_id)
    route_rules = get_route_table_response.data.route_rules

    print('\nCurrent Route Rules For VCN')
    print('===========================')
    print('{}\n\n'.format(route_rules))

    # Updating route rules will totally replace any current route rules with what we send through.
    # If we wish to preserve any existing route rules, we need to read them out first and then send
    # them back to the service as part of any update
    route_rules.append(
        oci.core.models.RouteRule(
            cidr_block='0.0.0.0/0',
            network_entity_id=internet_gateway.id
        )
    )

    virtual_network.update_route_table(
        vcn.default_route_table_id,
        oci.core.models.UpdateRouteTableDetails(route_rules=route_rules)
    )

    get_route_table_response = oci.wait_until(
        virtual_network,
        virtual_network.get_route_table(vcn.default_route_table_id),
        'lifecycle_state',
        'AVAILABLE'
    )

    print('\nUpdated Route Rules For VCN')
    print('===========================')
    print('{}\n\n'.format(get_route_table_response.data.route_rules))

    return get_route_table_response.data
def create_internet_gateway(virtual_network, vcn):
    internet_gateway_name = 'py_sdk_example_ig'
    result = virtual_network.create_internet_gateway(
        oci.core.models.CreateInternetGatewayDetails(
            display_name=internet_gateway_name,
            compartment_id=vcn.compartment_id,
            is_enabled=True,
            vcn_id=vcn.id
        )
    )
    get_internet_gateway_response = oci.wait_until(
        virtual_network,
        virtual_network.get_internet_gateway(result.data.id),
        'lifecycle_state',
        'AVAILABLE'
    )
    print('Created internet gateway: {}'.format(get_internet_gateway_response.data.id))

    add_route_rule_to_default_route_table_for_internet_gateway(
        virtual_network,
        vcn,
        get_internet_gateway_response.data
    )

    return get_internet_gateway_response.data
Beispiel #15
0
def test_basic_wait(virtual_network, config):
    """Creates and deletes a VCN, waiting after each operation."""

    name = "pythonsdk_waiter_" + tests.util.random_number_string()
    print('Creating cloud network ' + name)

    start_time = time.time()

    request = oci.core.models.CreateVcnDetails()
    request.cidr_block = '10.0.0.0/16'
    request.display_name = name
    request.compartment_id = config["tenancy"]

    response = virtual_network.create_vcn(request)
    vcn = response.data

    response = virtual_network.get_vcn(vcn.id)
    response = oci.wait_until(virtual_network, response, 'lifecycle_state', 'AVAILABLE')

    assert 'AVAILABLE' == response.data.lifecycle_state

    print('Deleting vcn')
    response = virtual_network.delete_vcn(vcn.id)

    assert response.status == 204

    with pytest.raises(oci.exceptions.ServiceError) as excinfo:
        response = virtual_network.get_vcn(vcn.id)
        assert 'TERMINATING' == response.data.lifecycle_state
        oci.wait_until(
            virtual_network,
            response,
            'lifecycle_state',
            'TERMINATED',
            max_wait_seconds=180
        )

    assert excinfo.value.status == 404

    result = oci.wait_until(virtual_network, response, 'lifecycle_state', 'TERMINATED', max_wait_seconds=180, succeed_on_not_found=True)
    assert result == oci.waiter.WAIT_RESOURCE_NOT_FOUND

    total_time = time.time() - start_time

    # This should always be between 1 second and 5 minutes.
    assert total_time < 60 * 5
    assert total_time > 1
Beispiel #16
0
def do_vcn_interactions_with_retries(virtual_network_client, compartment_id, retry_strategy):
    vcn_name = 'python_sdk_example_vcn'
    cidr_block = '10.0.0.0/16'
    result = virtual_network_client.create_vcn(
        oci.core.models.CreateVcnDetails(
            cidr_block=cidr_block,
            display_name=vcn_name,
            compartment_id=compartment_id
        ),
        retry_strategy=retry_strategy
    )

    vcn = oci.wait_until(
        virtual_network_client,
        virtual_network_client.get_vcn(result.data.id),
        'lifecycle_state',
        'AVAILABLE',
        max_wait_seconds=300
    ).data
    print('Created VCN')
    print('================')
    print(vcn)
    print('\n\n')

    result = virtual_network_client.update_vcn(
        vcn.id,
        oci.core.models.UpdateVcnDetails(display_name='python_sdk_example_vcn_updated'),
        retry_strategy=retry_strategy
    )
    print('Updated VCN')
    print('================')
    print(result.data)
    print('\n\n')

    virtual_network_client.delete_vcn(vcn.id, retry_strategy=retry_strategy)
    oci.wait_until(
        virtual_network_client,
        virtual_network_client.get_vcn(vcn.id),
        'lifecycle_state',
        'TERMINATED',
        max_wait_seconds=300,
        succeed_on_not_found=True
    )
    print('Deleted VCN')
    print('\n\n')
Beispiel #17
0
def test_already_in_state(identity, config):
    description = 'test user'
    request = oci.identity.models.CreateUserDetails()
    request.compartment_id = config["tenancy"]
    request.name = tests.util.unique_name('python_wait_test_user')
    request.description = description
    response = identity.create_user(request)
    user_id = response.data.id

    response = identity.get_user(user_id)
    assert description == response.data.description

    start_time = time.time()
    oci.wait_until(identity, response, 'description', description)
    assert start_time - time.time() < 1

    # clean up
    identity.delete_user(user_id)
def create_vcn_and_subnet(virtual_network, compartment_id, availability_domain):
    # Create a VCN
    vcn_name = 'python_sdk_test_vcn'
    cidr_block = "10.0.0.0/16"
    result = virtual_network.create_vcn(
        oci.core.models.CreateVcnDetails(
            cidr_block=cidr_block,
            display_name=vcn_name,
            compartment_id=compartment_id
        )
    )

    vcn = oci.wait_until(
        virtual_network,
        virtual_network.get_vcn(result.data.id),
        'lifecycle_state',
        'AVAILABLE',
        max_wait_seconds=300
    ).data
    print('Created VCN')

    # Create a subnet
    subnet_name = 'python_sdk_test_subnet1'
    subnet_cidr_block1 = "10.0.0.0/24"
    result = virtual_network.create_subnet(
        oci.core.models.CreateSubnetDetails(
            compartment_id=compartment_id,
            availability_domain=availability_domain,
            display_name=subnet_name,
            vcn_id=vcn.id,
            cidr_block=subnet_cidr_block1
        )
    )
    subnet = oci.wait_until(
        virtual_network,
        virtual_network.get_subnet(result.data.id),
        'lifecycle_state',
        'AVAILABLE',
        max_wait_seconds=300
    ).data
    print('Created subnet')

    return {'vcn': vcn, 'subnet': subnet}
def create_vcn_and_subnet(virtual_network, compartment_id, availability_domain):
    vcn_name = 'py_sdk_fs_example_vcn'
    cidr_block = "10.0.0.0/16"
    vcn_dns_label = 'pysdkfs'

    result = virtual_network.create_vcn(
        oci.core.models.CreateVcnDetails(
            cidr_block=cidr_block,
            display_name=vcn_name,
            compartment_id=compartment_id,
            dns_label=vcn_dns_label
        )
    )
    vcn = oci.wait_until(
        virtual_network,
        virtual_network.get_vcn(result.data.id),
        'lifecycle_state',
        'AVAILABLE',
        max_wait_seconds=300
    ).data

    subnet_name = 'py_sdk_fs_example_subnet'
    subnet_dns_label = 'pyfssub'
    result = virtual_network.create_subnet(
        oci.core.models.CreateSubnetDetails(
            compartment_id=compartment_id,
            availability_domain=availability_domain,
            display_name=subnet_name,
            vcn_id=vcn.id,
            cidr_block=cidr_block,
            dns_label=subnet_dns_label
        )
    )
    subnet = oci.wait_until(
        virtual_network,
        virtual_network.get_subnet(result.data.id),
        'lifecycle_state',
        'AVAILABLE',
        max_wait_seconds=300
    ).data

    return {'vcn': vcn, 'subnet': subnet}
Beispiel #20
0
def test_eval_function_func_ref(identity, config):
    user_id = None
    try:
        description = 'test user'
        request = oci.identity.models.CreateUserDetails()
        request.compartment_id = config["tenancy"]
        request.name = tests.util.unique_name('python_wait_test_user')
        request.description = description
        response = identity.create_user(request)
        user_id = response.data.id

        response = identity.get_user(user_id)
        assert description == response.data.description

        def test_user_response(user_response):
            print('Invoked function reference in test_user_response')
            user = user_response.data
            return user.description == description and user.name == request.name and user.lifecycle_state == 'ACTIVE'

        response = oci.wait_until(identity, response, evaluate_response=test_user_response)
        assert response.data.id == user_id
        assert response.data.description == description
        assert response.data.name == request.name
        assert response.data.lifecycle_state == 'ACTIVE'

        times_called = {'counter': 0}

        def test_user_response_for_timeout(user_response):
            print('Invoked function reference in test_user_response_for_timeout')
            user = user_response.data
            times_called['counter'] += 1
            return user.description == description and user.name == request.name and user.lifecycle_state == 'superman'

        with pytest.raises(oci.exceptions.MaximumWaitTimeExceeded):
            response = oci.wait_until(identity, response, evaluate_response=test_user_response_for_timeout, max_wait_seconds=45, max_interval_seconds=10)

        assert times_called['counter'] >= 2
    finally:
        if user_id:
            identity.delete_user(user_id)
def delete_vcn_drg_and_drg_attachment(virtual_network_client, vcn_drg_and_drg_attachment):
    vcn = vcn_drg_and_drg_attachment['vcn']
    drg = vcn_drg_and_drg_attachment['drg']
    drg_attachment = vcn_drg_and_drg_attachment['drg_attachment']

    print('Deleting DRG Attachment')
    virtual_network_client.delete_drg_attachment(drg_attachment.id)
    oci.wait_until(
        virtual_network_client,
        virtual_network_client.get_drg_attachment(drg_attachment.id),
        'lifecycle_state',
        'DETACHED',
        succeed_on_not_found=True
    )

    print('Deleting DRG')
    virtual_network_client.delete_drg(drg.id)
    oci.wait_until(
        virtual_network_client,
        virtual_network_client.get_drg(drg.id),
        'lifecycle_state',
        'TERMINATED',
        succeed_on_not_found=True
    )

    print('Deleting VCN')
    virtual_network_client.delete_vcn(vcn.id)
    oci.wait_until(
        virtual_network_client,
        virtual_network_client.get_vcn(vcn.id),
        'lifecycle_state',
        'TERMINATED',
        succeed_on_not_found=True
    )
Beispiel #22
0
def test_wait_time_exceeded(identity, config):
    description = 'test user'
    request = oci.identity.models.CreateUserDetails()
    request.compartment_id = config["tenancy"]
    request.name = tests.util.unique_name('python_wait_test_user')
    request.description = description
    response = identity.create_user(request)
    user_id = response.data.id

    response = identity.get_user(user_id)
    assert description == response.data.description

    start_time = time.time()
    with pytest.raises(oci.exceptions.MaximumWaitTimeExceeded):
        # Wait on a property that will not change until we time out.
        oci.wait_until(identity, response, 'name', 'test', max_wait_seconds=2)

    total_time = time.time() - start_time
    assert 1 < total_time < 4

    # clean up
    identity.delete_user(user_id)
def create_volume(block_storage, compartment_id, availability_domain, display_name):
    result = block_storage.create_volume(
        oci.core.models.CreateVolumeDetails(
            compartment_id=compartment_id,
            availability_domain=availability_domain,
            display_name=display_name
        )
    )
    volume = oci.wait_until(
        block_storage,
        block_storage.get_volume(result.data.id),
        'lifecycle_state',
        'AVAILABLE'
    ).data
    print('Created Volume: {}'.format(display_name))

    return volume
def create_vcn(virtual_network, compartment_id, cidr_block):
    vcn_name = 'py_sdk_example_vcn'
    result = virtual_network.create_vcn(
        oci.core.models.CreateVcnDetails(
            cidr_block=cidr_block,
            display_name=vcn_name,
            compartment_id=compartment_id
        )
    )
    get_vcn_response = oci.wait_until(
        virtual_network,
        virtual_network.get_vcn(result.data.id),
        'lifecycle_state',
        'AVAILABLE'
    )
    print('Created VCN: {}'.format(get_vcn_response.data.id))

    return get_vcn_response.data
    def db_node_action_and_wait_for_state(self, db_node_id, action, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
        """
        Calls :py:func:`~oci.database.DatabaseClient.db_node_action` and waits for the :py:class:`~oci.database.models.DbNode` acted upon
        to enter the given state(s).

        :param str db_node_id: (required)
            The database node `OCID`__.

            __ https://docs.us-phoenix-1.oraclecloud.com/Content/General/Concepts/identifiers.htm

        :param str action: (required)
            The action to perform on the DB Node.

            Allowed values are: "STOP", "START", "SOFTRESET", "RESET"

        :param list[str] wait_for_states:
            An array of states to wait on. These should be valid values for :py:attr:`~oci.database.models.DbNode.lifecycle_state`

        :param dict operation_kwargs:
            A dictionary of keyword arguments to pass to :py:func:`~oci.database.DatabaseClient.db_node_action`

        :param dict waiter_kwargs:
            A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
            as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
        """
        operation_result = self.client.db_node_action(db_node_id, action, **operation_kwargs)
        if not wait_for_states:
            return operation_result

        lowered_wait_for_states = [w.lower() for w in wait_for_states]
        wait_for_resource_id = operation_result.data.id

        try:
            waiter_result = oci.wait_until(
                self.client,
                self.client.get_db_node(wait_for_resource_id),
                evaluate_response=lambda r: getattr(r.data, 'lifecycle_state') and getattr(r.data, 'lifecycle_state').lower() in lowered_wait_for_states,
                **waiter_kwargs
            )
            result_to_return = waiter_result

            return result_to_return
        except Exception as e:
            raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
    def update_idp_group_mapping_and_wait_for_state(self, identity_provider_id, mapping_id, update_idp_group_mapping_details, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
        """
        Calls :py:func:`~oci.identity.IdentityClient.update_idp_group_mapping` and waits for the :py:class:`~oci.identity.models.IdpGroupMapping` acted upon
        to enter the given state(s).

        :param str identity_provider_id: (required)
            The OCID of the identity provider.

        :param str mapping_id: (required)
            The OCID of the group mapping.

        :param UpdateIdpGroupMappingDetails update_idp_group_mapping_details: (required)
            Request object for updating an identity provider group mapping

        :param list[str] wait_for_states:
            An array of states to wait on. These should be valid values for :py:attr:`~oci.identity.models.IdpGroupMapping.lifecycle_state`

        :param dict operation_kwargs:
            A dictionary of keyword arguments to pass to :py:func:`~oci.identity.IdentityClient.update_idp_group_mapping`

        :param dict waiter_kwargs:
            A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
            as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
        """
        operation_result = self.client.update_idp_group_mapping(identity_provider_id, mapping_id, update_idp_group_mapping_details, **operation_kwargs)
        if not wait_for_states:
            return operation_result

        lowered_wait_for_states = [w.lower() for w in wait_for_states]
        wait_for_resource_id = operation_result.data.id

        try:
            waiter_result = oci.wait_until(
                self.client,
                self.client.get_idp_group_mapping(wait_for_resource_id),
                evaluate_response=lambda r: getattr(r.data, 'lifecycle_state') and getattr(r.data, 'lifecycle_state').lower() in lowered_wait_for_states,
                **waiter_kwargs
            )
            result_to_return = waiter_result

            return result_to_return
        except Exception as e:
            raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
def create_subnet(virtual_network, vcn, availability_domain):
    subnet_name = 'py_sdk_example_subnet1'
    result = virtual_network.create_subnet(
        oci.core.models.CreateSubnetDetails(
            compartment_id=vcn.compartment_id,
            availability_domain=availability_domain,
            display_name=subnet_name,
            vcn_id=vcn.id,
            cidr_block=vcn.cidr_block
        )
    )
    get_subnet_response = oci.wait_until(
        virtual_network,
        virtual_network.get_subnet(result.data.id),
        'lifecycle_state',
        'AVAILABLE'
    )
    print('Created Subnet: {}'.format(get_subnet_response.data.id))

    return get_subnet_response.data
def launch_instance(compute, vcn_and_subnet):
    result = compute.launch_instance(
        oci.core.models.LaunchInstanceDetails(
            availability_domain=vcn_and_subnet['subnet'].availability_domain,
            compartment_id=vcn_and_subnet['subnet'].compartment_id,
            display_name='VolAttachTypesExampleInstance',
            shape='VM.Standard1.1',
            subnet_id=vcn_and_subnet['subnet'].id,
            image_id=get_image(compute, vcn_and_subnet['subnet'].compartment_id, 'Oracle Linux', '7.4', 'VM.Standard1.1').id
        )
    )
    get_instance_response = oci.wait_until(
        compute,
        compute.get_instance(result.data.id),
        'lifecycle_state',
        'RUNNING',
        max_wait_seconds=300
    )
    print('Launched Instance')

    return get_instance_response.data
    def update_image_and_wait_for_state(self, image_id, update_image_details, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
        """
        Calls :py:func:`~oci.core.ComputeClient.update_image` and waits for the :py:class:`~oci.core.models.Image` acted upon
        to enter the given state(s).

        :param str image_id: (required)
            The OCID of the image.

        :param UpdateImageDetails update_image_details: (required)
            Updates the image display name field. Avoid entering confidential information.

        :param list[str] wait_for_states:
            An array of states to wait on. These should be valid values for :py:attr:`~oci.core.models.Image.lifecycle_state`

        :param dict operation_kwargs:
            A dictionary of keyword arguments to pass to :py:func:`~oci.core.ComputeClient.update_image`

        :param dict waiter_kwargs:
            A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
            as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
        """
        operation_result = self.client.update_image(image_id, update_image_details, **operation_kwargs)
        if not wait_for_states:
            return operation_result

        lowered_wait_for_states = [w.lower() for w in wait_for_states]
        wait_for_resource_id = operation_result.data.id

        try:
            waiter_result = oci.wait_until(
                self.client,
                self.client.get_image(wait_for_resource_id),
                evaluate_response=lambda r: getattr(r.data, 'lifecycle_state') and getattr(r.data, 'lifecycle_state').lower() in lowered_wait_for_states,
                **waiter_kwargs
            )
            result_to_return = waiter_result

            return result_to_return
        except Exception as e:
            raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
    def terminate_db_system_and_wait_for_state(self, db_system_id, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
        """
        Calls :py:func:`~oci.database.DatabaseClient.terminate_db_system` and waits for the :py:class:`~oci.database.models.DbSystem` acted upon
        to enter the given state(s).

        :param str db_system_id: (required)
            The DB System `OCID`__.

            __ https://docs.us-phoenix-1.oraclecloud.com/Content/General/Concepts/identifiers.htm

        :param list[str] wait_for_states:
            An array of states to wait on. These should be valid values for :py:attr:`~oci.database.models.DbSystem.lifecycle_state`

        :param dict operation_kwargs:
            A dictionary of keyword arguments to pass to :py:func:`~oci.database.DatabaseClient.terminate_db_system`

        :param dict waiter_kwargs:
            A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
            as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
        """
        initial_get_result = self.client.get_db_system(db_system_id)
        operation_result = self.client.terminate_db_system(db_system_id, **operation_kwargs)
        if not wait_for_states:
            return operation_result

        lowered_wait_for_states = [w.lower() for w in wait_for_states]

        try:
            waiter_result = oci.wait_until(
                self.client,
                initial_get_result,
                evaluate_response=lambda r: getattr(r.data, 'lifecycle_state') and getattr(r.data, 'lifecycle_state').lower() in lowered_wait_for_states,
                succeed_on_not_found=True,
                **waiter_kwargs
            )
            result_to_return = waiter_result

            return result_to_return
        except Exception as e:
            raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
Beispiel #31
0
    launch_response = database_client.launch_db_system(launch_db_system_details)
    print('\nLaunched DB System')
    print('===========================')
    print('{}\n\n'.format(launch_response.data))

    # We can wait until the DB system is available. A DB system can take some time to launch (e.g. on the order
    # of magnitude of hours) so we can change the max_interval_seconds and max_wait_seconds to account for this.
    # The wait_until defaults of checking every 30 seconds and waiting for a maximum of 1200 seconds (20 minutes)
    # may not be sufficient.
    #
    # In the below example, we check every 900 seconds (15 minutes) and wait a max of 21600 seconds (6 hours)
    get_db_system_response = oci.wait_until(
        database_client,
        database_client.get_db_system(launch_response.data.id),
        'lifecycle_state',
        'AVAILABLE',
        max_interval_seconds=900,
        max_wait_seconds=21600
    )

    print('\nDB System Available')
    print('===========================')
    print('{}\n\n'.format(get_db_system_response.data))

    list_db_home_and_databases_under_db_system(database_client, compartment_id, get_db_system_response.data)

    # Once we're done with the DB system, we can terminate it and wait for it to be terminated. We also use
    # succeed_on_not_found for the waiter in case the DB system is no longer returned by get_db_system calls
    # as that implies our delete/termination has succeeded.
    #
    # In this basic scenario where we have a single DB system, DB home and database, terminating the DB system
Beispiel #32
0
def handle_create_volume(block_storage_client, module):
    create_volume_details = CreateVolumeDetails()
    create_volume_details.availability_domain = module.params[
        'availability_domain']
    create_volume_details.compartment_id = module.params['compartment_id']
    create_volume_details.display_name = module.params['display_name']
    create_volume_details.size_in_gbs = module.params['size_in_gbs']
    oci_utils.add_tags_to_model_from_module(create_volume_details, module)

    if module.params['source_details']:
        source_details = module.params['source_details']
        volume_source = None
        if 'type' in source_details:
            if source_details['type'] == "volume":
                volume_source = VolumeSourceFromVolumeDetails()
                volume_source.id = source_details["id"]

            elif source_details['type'] == "volumeBackup":
                volume_source = VolumeSourceFromVolumeBackupDetails()
                volume_source.id = source_details["id"]

            else:
                module.fail_json(
                    msg="value of state must be one of: volume, volumeBackup")

        else:
            module.fail_json(msg="missing required arguments: type")

        create_volume_details.source_details = volume_source

    result = oci_utils.create_and_wait(
        resource_type="volume",
        create_fn=block_storage_client.create_volume,
        kwargs_create={"create_volume_details": create_volume_details},
        client=block_storage_client,
        get_fn=block_storage_client.get_volume,
        get_param="volume_id",
        module=module)

    wait_for_copy = False
    copy_timeout = 1800
    WAIT_FOR_INITIALIZATION = "wait_for_copy"
    INITIALIZATION_TIMEOUT = "copy_timeout"

    if create_volume_details.source_details is not None:
        if WAIT_FOR_INITIALIZATION in source_details:
            wait_for_copy = source_details[WAIT_FOR_INITIALIZATION]
            if INITIALIZATION_TIMEOUT in source_details:
                copy_timeout = source_details[INITIALIZATION_TIMEOUT]

    try:
        response = oci_utils.call_with_backoff(
            block_storage_client.get_volume, volume_id=result['volume']['id'])

        if wait_for_copy:
            result['volume'] = to_dict(
                oci.wait_until(block_storage_client,
                               response,
                               'is_hydrated',
                               True,
                               max_wait_seconds=copy_timeout).data)

    except ServiceError as ex:
        module.fail_json(msg=ex.message)
    except MaximumWaitTimeExceeded as ex:
        module.fail_json(msg=str(ex))

    return result
Beispiel #33
0
def vcn_and_subnet(runner, config_file, config_profile, network_client):
    with test_config_container.create_vcr(cassette_library_dir=CASSETTE_LIBRARY_DIR).use_cassette('filestorage_vcn_and_subnet_fixture.yml'):
        # create VCN
        vcn_name = util.random_name('cli_db_test_vcn')
        cidr_block = "10.0.0.0/16"
        vcn_dns_label = util.random_name('vcn', insert_underscore=False)

        create_vcn_details = oci.core.models.CreateVcnDetails()
        create_vcn_details.cidr_block = cidr_block
        create_vcn_details.display_name = vcn_name
        create_vcn_details.compartment_id = util.COMPARTMENT_ID
        create_vcn_details.dns_label = vcn_dns_label

        result = network_client.create_vcn(create_vcn_details)
        vcn_ocid = result.data.id
        assert result.status == 200

        oci.wait_until(network_client, network_client.get_vcn(vcn_ocid), 'lifecycle_state', 'AVAILABLE', max_wait_seconds=300)

        # create subnet in first AD
        subnet_name = util.random_name('python_sdk_test_subnet')
        cidr_block = "10.0.1.0/24"
        subnet_dns_label = util.random_name('subnet', insert_underscore=False) + '1'

        create_subnet_details = oci.core.models.CreateSubnetDetails()
        create_subnet_details.compartment_id = util.COMPARTMENT_ID
        create_subnet_details.availability_domain = util.availability_domain()
        create_subnet_details.display_name = subnet_name
        create_subnet_details.vcn_id = vcn_ocid
        create_subnet_details.cidr_block = cidr_block
        create_subnet_details.dns_label = subnet_dns_label

        result = network_client.create_subnet(create_subnet_details)
        subnet_ocid = result.data.id
        assert result.status == 200

        oci.wait_until(network_client, network_client.get_subnet(subnet_ocid), 'lifecycle_state', 'AVAILABLE', max_wait_seconds=300)

    yield vcn_ocid, subnet_ocid

    # this code does not run inside the vcr_fixture because it is outside any test function
    # thus we are explicitly creating a separate cassette for it here
    with test_config_container.create_vcr(cassette_library_dir=CASSETTE_LIBRARY_DIR).use_cassette('filestorage_vcn_and_subnet_fixture_cleanup.yml'):
        # Sometimes we can't delete the subnet straight after the mount target because some VNIC is still
        # hanging around. If we get a conflict, try a few times before bailing out
        attempts = 0
        while attempts < 5:
            try:
                network_client.delete_subnet(subnet_ocid)
                test_config_container.do_wait(
                    network_client,
                    network_client.get_subnet(subnet_ocid),
                    'lifecycle_state',
                    'TERMINATED',
                    max_wait_seconds=600,
                    succeed_on_not_found=True
                )
                break
            except oci.exceptions.ServiceError as e:
                attempts += 1
                if e.status == 409 and attempts < 5:
                    time.sleep(5)
                else:
                    raise

        network_client.delete_vcn(vcn_ocid)
Beispiel #34
0
def update_rover_entitlement(ctx, from_json, force, wait_for_state, max_wait_seconds, wait_interval_seconds, rover_entitlement_id, display_name, tenant_id, requestor_name, requestor_email, entitlement_details, lifecycle_state, lifecycle_state_details, freeform_tags, defined_tags, system_tags, if_match):

    if isinstance(rover_entitlement_id, six.string_types) and len(rover_entitlement_id.strip()) == 0:
        raise click.UsageError('Parameter --rover-entitlement-id cannot be whitespace or empty string')
    if not force:
        if freeform_tags or defined_tags or system_tags:
            if not click.confirm("WARNING: Updates to freeform-tags and defined-tags and system-tags will replace any existing values. Are you sure you want to continue?"):
                ctx.abort()

    kwargs = {}
    if if_match is not None:
        kwargs['if_match'] = if_match
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])

    _details = {}

    if display_name is not None:
        _details['displayName'] = display_name

    if tenant_id is not None:
        _details['tenantId'] = tenant_id

    if requestor_name is not None:
        _details['requestorName'] = requestor_name

    if requestor_email is not None:
        _details['requestorEmail'] = requestor_email

    if entitlement_details is not None:
        _details['entitlementDetails'] = entitlement_details

    if lifecycle_state is not None:
        _details['lifecycleState'] = lifecycle_state

    if lifecycle_state_details is not None:
        _details['lifecycleStateDetails'] = lifecycle_state_details

    if freeform_tags is not None:
        _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags)

    if defined_tags is not None:
        _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags)

    if system_tags is not None:
        _details['systemTags'] = cli_util.parse_json_parameter("system_tags", system_tags)

    client = cli_util.build_client('rover', 'rover_entitlement', ctx)
    result = client.update_rover_entitlement(
        rover_entitlement_id=rover_entitlement_id,
        update_rover_entitlement_details=_details,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_rover_entitlement') and callable(getattr(client, 'get_rover_entitlement')):
            try:
                wait_period_kwargs = {}
                if max_wait_seconds is not None:
                    wait_period_kwargs['max_wait_seconds'] = max_wait_seconds
                if wait_interval_seconds is not None:
                    wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds

                click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_rover_entitlement(result.data.id), 'lifecycle_state', wait_for_state, **wait_period_kwargs)
            except oci.exceptions.MaximumWaitTimeExceeded as e:
                # If we fail, we should show an error, but we should still provide the information to the customer
                click.echo('Failed to wait until the resource entered the specified state. Outputting last known resource state', file=sys.stderr)
                cli_util.render_response(result, ctx)
                sys.exit(2)
            except Exception:
                click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr)
                cli_util.render_response(result, ctx)
                raise
        else:
            click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)
Beispiel #35
0
    def update_backend_and_wait_for_state(self,
                                          network_load_balancer_id,
                                          update_backend_details,
                                          backend_set_name,
                                          backend_name,
                                          wait_for_states=[],
                                          operation_kwargs={},
                                          waiter_kwargs={}):
        """
        Calls :py:func:`~oci.network_load_balancer.NetworkLoadBalancerClient.update_backend` and waits for the :py:class:`~oci.network_load_balancer.models.WorkRequest`
        to enter the given state(s).

        :param str network_load_balancer_id: (required)
            The `OCID`__ of the network load balancer to update.

            __ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm

        :param oci.network_load_balancer.models.UpdateBackendDetails update_backend_details: (required)
            Details for updating a backend server.

        :param str backend_set_name: (required)
            The name of the backend set associated with the backend server.

            Example: `example_backend_set`

        :param str backend_name: (required)
            The name of the backend server to update. This is specified as <ip>:<port>, or as <ip> <OCID>:<port>.

            Example: `10.0.0.3:8080` or `ocid1.privateip..oc1.<var>&lt;unique_ID&gt;</var>:8080`

        :param list[str] wait_for_states:
            An array of states to wait on. These should be valid values for :py:attr:`~oci.network_load_balancer.models.WorkRequest.status`

        :param dict operation_kwargs:
            A dictionary of keyword arguments to pass to :py:func:`~oci.network_load_balancer.NetworkLoadBalancerClient.update_backend`

        :param dict waiter_kwargs:
            A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
            as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
        """
        operation_result = self.client.update_backend(network_load_balancer_id,
                                                      update_backend_details,
                                                      backend_set_name,
                                                      backend_name,
                                                      **operation_kwargs)
        if not wait_for_states:
            return operation_result

        lowered_wait_for_states = [w.lower() for w in wait_for_states]
        wait_for_resource_id = operation_result.headers['opc-work-request-id']

        try:
            waiter_result = oci.wait_until(
                self.client,
                self.client.get_work_request(wait_for_resource_id),
                evaluate_response=lambda r: getattr(r.data, 'status') and
                getattr(r.data, 'status').lower() in lowered_wait_for_states,
                **waiter_kwargs)
            result_to_return = waiter_result

            return result_to_return
        except Exception as e:
            raise oci.exceptions.CompositeOperationError(
                partial_results=[operation_result], cause=e)
# errors). The retry strategy will also make requests with an opc-retry-token that it generates.
#
# If you do not use the retry_strategy (or have an alternate way of retrying you wish to use instead) we still
# recommend that you use an opc-retry-token in your service calls so that if you receive, say, a timeout or server error
# and need to retry/reissue the request you won't run the risk of creating multiple resources.
create_response = file_storage_client.create_file_system(
    oci.file_storage.models.CreateFileSystemDetails(
        display_name='py_sdk_example_fs',
        compartment_id=compartment_id,
        availability_domain=availability_domain),
    retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY)

# A file system has a lifecycle state, we should wait until it is active. Note that wait_until returns a response, so
# to access the model object we use the .data attribute
file_system = oci.wait_until(
    file_storage_client,
    file_storage_client.get_file_system(create_response.data.id),
    'lifecycle_state', 'ACTIVE').data
print('Created file system:\n{}'.format(file_system))
print('=============================\n')

# We can update the display name of the file system
update_response = file_storage_client.update_file_system(
    file_system.id,
    oci.file_storage.models.UpdateFileSystemDetails(
        display_name='updated_py_sdk_example_fs'))
print('Updated file system:\n{}'.format(update_response.data))
print('=============================\n')

# Listing file systems is a paginated operation, so we can use the functionality in the oci.pagination
# module to get all the results
all_file_systems = oci.pagination.list_call_get_all_results(
Beispiel #37
0
def create_transfer_appliance_extended(ctx, **kwargs):
    if 'job_id' in kwargs:
        kwargs['id'] = kwargs['job_id']
        kwargs.pop('job_id')
    kwargs['customer_shipping_address'] = {}
    for option, value in customer_address_options.items():
        if option in kwargs:
            kwargs['customer_shipping_address'][value] = kwargs[option]
            kwargs.pop(option)

    id = kwargs['id']
    customer_shipping_address = kwargs['customer_shipping_address']
    wait_for_state = kwargs['wait_for_state']
    max_wait_seconds = kwargs['max_wait_seconds']
    wait_interval_seconds = kwargs['wait_interval_seconds']
    setup_notifications = kwargs['setup_notifications']

    # Copied from the generated file because the result of the create is required to setup notifications
    if isinstance(id, six.string_types) and len(id.strip()) == 0:
        raise click.UsageError(
            'Parameter --id cannot be whitespace or empty string')

    kwargs = {}

    details = {}

    if customer_shipping_address is not None:
        details['customerShippingAddress'] = cli_util.parse_json_parameter(
            "customer_shipping_address", customer_shipping_address)

    client = cli_util.build_client('dts', 'transfer_appliance', ctx)
    result = client.create_transfer_appliance(
        id=id, create_transfer_appliance_details=details, **kwargs)
    if wait_for_state:
        if hasattr(client, 'get_transfer_appliance') and callable(
                getattr(client, 'get_transfer_appliance')):
            try:
                wait_period_kwargs = {}
                if max_wait_seconds is not None:
                    wait_period_kwargs['max_wait_seconds'] = max_wait_seconds
                if wait_interval_seconds is not None:
                    wait_period_kwargs[
                        'max_interval_seconds'] = wait_interval_seconds

                click.echo(
                    'Action completed. Waiting until the resource has entered state: {}'
                    .format(wait_for_state),
                    file=sys.stderr)
                result = oci.wait_until(
                    client, client.get_transfer_appliance(result.data.id),
                    'lifecycle_state', wait_for_state, **wait_period_kwargs)
            except oci.exceptions.MaximumWaitTimeExceeded as e:
                # If we fail, we should show an error, but we should still provide the information to the customer
                click.echo(
                    'Failed to wait until the resource entered the specified state. Outputting last known resource state',
                    file=sys.stderr)
                cli_util.render_response(result, ctx)
                sys.exit(2)
            except Exception:
                click.echo(
                    'Encountered error while waiting for resource to enter the specified state. Outputting last known resource state',
                    file=sys.stderr)
                cli_util.render_response(result, ctx)
                raise
        else:
            click.echo(
                'Unable to wait for the resource to enter the specified state',
                file=sys.stderr)

    cli_util.render_response(result, ctx)

    if setup_notifications:
        setup_import_notifications(ctx, result.data.label)
Beispiel #38
0
        'pyremote'
    )

    # Create a remote peering connection in the local region
    print('Creating remote peering connection in {}'.format(local_region))
    print('=====================================')
    result = virtual_network_client_local.create_remote_peering_connection(
        oci.core.models.CreateRemotePeeringConnectionDetails(
            compartment_id=compartment_id,
            drg_id=local_vcn_and_drg['drg'].id,
            display_name='Remote peering connection in local'
        )
    )
    remote_peering_connection_in_local_region = oci.wait_until(
        virtual_network_client_local,
        virtual_network_client_local.get_remote_peering_connection(result.data.id),
        'lifecycle_state',
        'AVAILABLE'
    ).data
    print(remote_peering_connection_in_local_region)
    print('\n\n')

    # Create a remote peering connection in the remote region
    print('Creating remote peering connection in {}'.format(remote_region))
    print('=====================================')
    result = virtual_network_client_remote.create_remote_peering_connection(
        oci.core.models.CreateRemotePeeringConnectionDetails(
            compartment_id=compartment_id,
            drg_id=remote_vcn_and_drg['drg'].id,
            display_name='Remote peering connection in remote'
        )
    )
Beispiel #39
0
def update_http_redirect(ctx, from_json, force, wait_for_state,
                         max_wait_seconds, wait_interval_seconds,
                         http_redirect_id, display_name, target, response_code,
                         freeform_tags, defined_tags, if_match):

    if isinstance(http_redirect_id, six.string_types) and len(
            http_redirect_id.strip()) == 0:
        raise click.UsageError(
            'Parameter --http-redirect-id cannot be whitespace or empty string'
        )
    if not force:
        if target or freeform_tags or defined_tags:
            if not click.confirm(
                    "WARNING: Updates to target and freeform-tags and defined-tags will replace any existing values. Are you sure you want to continue?"
            ):
                ctx.abort()

    kwargs = {}
    if if_match is not None:
        kwargs['if_match'] = if_match
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(
        ctx.obj['request_id'])

    _details = {}

    if display_name is not None:
        _details['displayName'] = display_name

    if target is not None:
        _details['target'] = cli_util.parse_json_parameter("target", target)

    if response_code is not None:
        _details['responseCode'] = response_code

    if freeform_tags is not None:
        _details['freeformTags'] = cli_util.parse_json_parameter(
            "freeform_tags", freeform_tags)

    if defined_tags is not None:
        _details['definedTags'] = cli_util.parse_json_parameter(
            "defined_tags", defined_tags)

    client = cli_util.build_client('waas', 'redirect', ctx)
    result = client.update_http_redirect(http_redirect_id=http_redirect_id,
                                         update_http_redirect_details=_details,
                                         **kwargs)
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(
                getattr(client, 'get_work_request')):
            try:
                wait_period_kwargs = {}
                if max_wait_seconds is not None:
                    wait_period_kwargs['max_wait_seconds'] = max_wait_seconds
                if wait_interval_seconds is not None:
                    wait_period_kwargs[
                        'max_interval_seconds'] = wait_interval_seconds

                click.echo(
                    'Action completed. Waiting until the work request has entered state: {}'
                    .format(wait_for_state),
                    file=sys.stderr)
                result = oci.wait_until(
                    client,
                    client.get_work_request(
                        result.headers['opc-work-request-id']), 'status',
                    wait_for_state, **wait_period_kwargs)
            except oci.exceptions.MaximumWaitTimeExceeded as e:
                # If we fail, we should show an error, but we should still provide the information to the customer
                click.echo(
                    'Failed to wait until the work request entered the specified state. Outputting last known resource state',
                    file=sys.stderr)
                cli_util.render_response(result, ctx)
                sys.exit(2)
            except Exception:
                click.echo(
                    'Encountered error while waiting for work request to enter the specified state. Outputting last known resource state',
                    file=sys.stderr)
                cli_util.render_response(result, ctx)
                raise
        else:
            click.echo(
                'Unable to wait for the work request to enter the specified state',
                file=sys.stderr)
    cli_util.render_response(result, ctx)
Beispiel #40
0
def create_http_redirect(ctx, from_json, wait_for_state, max_wait_seconds,
                         wait_interval_seconds, compartment_id, domain, target,
                         display_name, response_code, freeform_tags,
                         defined_tags):

    kwargs = {}
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(
        ctx.obj['request_id'])

    _details = {}
    _details['compartmentId'] = compartment_id
    _details['domain'] = domain
    _details['target'] = cli_util.parse_json_parameter("target", target)

    if display_name is not None:
        _details['displayName'] = display_name

    if response_code is not None:
        _details['responseCode'] = response_code

    if freeform_tags is not None:
        _details['freeformTags'] = cli_util.parse_json_parameter(
            "freeform_tags", freeform_tags)

    if defined_tags is not None:
        _details['definedTags'] = cli_util.parse_json_parameter(
            "defined_tags", defined_tags)

    client = cli_util.build_client('waas', 'redirect', ctx)
    result = client.create_http_redirect(create_http_redirect_details=_details,
                                         **kwargs)
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(
                getattr(client, 'get_work_request')):
            try:
                wait_period_kwargs = {}
                if max_wait_seconds is not None:
                    wait_period_kwargs['max_wait_seconds'] = max_wait_seconds
                if wait_interval_seconds is not None:
                    wait_period_kwargs[
                        'max_interval_seconds'] = wait_interval_seconds

                click.echo(
                    'Action completed. Waiting until the work request has entered state: {}'
                    .format(wait_for_state),
                    file=sys.stderr)
                result = oci.wait_until(
                    client,
                    client.get_work_request(
                        result.headers['opc-work-request-id']), 'status',
                    wait_for_state, **wait_period_kwargs)
            except oci.exceptions.MaximumWaitTimeExceeded as e:
                # If we fail, we should show an error, but we should still provide the information to the customer
                click.echo(
                    'Failed to wait until the work request entered the specified state. Outputting last known resource state',
                    file=sys.stderr)
                cli_util.render_response(result, ctx)
                sys.exit(2)
            except Exception:
                click.echo(
                    'Encountered error while waiting for work request to enter the specified state. Outputting last known resource state',
                    file=sys.stderr)
                cli_util.render_response(result, ctx)
                raise
        else:
            click.echo(
                'Unable to wait for the work request to enter the specified state',
                file=sys.stderr)
    cli_util.render_response(result, ctx)
Beispiel #41
0
def handle_create_volume(block_storage_client, module):
    create_volume_details = CreateVolumeDetails()

    for attribute in create_volume_details.attribute_map.keys():
        if attribute in module.params:
            setattr(create_volume_details, attribute, module.params[attribute])

    if module.params["source_details"]:
        source_details = module.params["source_details"]
        volume_source = None
        if "type" in source_details:
            if source_details["type"] == "volume":
                volume_source = VolumeSourceFromVolumeDetails()
                volume_source.id = source_details.get("id")

            elif source_details["type"] == "volumeBackup":
                volume_source = VolumeSourceFromVolumeBackupDetails()
                volume_source.id = source_details.get("id")

            else:
                module.fail_json(
                    msg="value of state must be one of: volume, volumeBackup"
                )

        else:
            module.fail_json(msg="missing required arguments: type")

        create_volume_details.source_details = volume_source

    result = oci_utils.create_and_wait(
        resource_type="volume",
        create_fn=block_storage_client.create_volume,
        kwargs_create={"create_volume_details": create_volume_details},
        client=block_storage_client,
        get_fn=block_storage_client.get_volume,
        get_param="volume_id",
        module=module,
    )

    wait_for_copy = False
    copy_timeout = 1800
    WAIT_FOR_INITIALIZATION = "wait_for_copy"
    INITIALIZATION_TIMEOUT = "copy_timeout"

    if create_volume_details.source_details is not None:
        if WAIT_FOR_INITIALIZATION in source_details:
            wait_for_copy = source_details[WAIT_FOR_INITIALIZATION]
            if INITIALIZATION_TIMEOUT in source_details:
                copy_timeout = source_details[INITIALIZATION_TIMEOUT]

    try:
        response = oci_utils.call_with_backoff(
            block_storage_client.get_volume, volume_id=result["volume"]["id"]
        )

        if wait_for_copy:
            result["volume"] = to_dict(
                oci.wait_until(
                    block_storage_client,
                    response,
                    "is_hydrated",
                    True,
                    max_wait_seconds=copy_timeout,
                ).data
            )

    except ServiceError as ex:
        module.fail_json(msg=ex.message)
    except MaximumWaitTimeExceeded as ex:
        module.fail_json(msg=str(ex))

    return result
Beispiel #42
0
def vcn_and_subnets(network_client):
    from tests import util

    with test_config_container.create_vcr().use_cassette(
            '_conftest_fixture_vcn_and_subnets.yml'):
        # create VCN
        vcn_name = util.random_name('cli_lb_test_vcn')
        cidr_block = "10.0.0.0/16"
        vcn_dns_label = util.random_name('vcn', insert_underscore=False)

        create_vcn_details = oci.core.models.CreateVcnDetails()
        create_vcn_details.cidr_block = cidr_block
        create_vcn_details.display_name = vcn_name
        create_vcn_details.compartment_id = os.environ[
            'OCI_CLI_COMPARTMENT_ID']
        create_vcn_details.dns_label = vcn_dns_label

        result = network_client.create_vcn(create_vcn_details)
        vcn_ocid = result.data.id
        assert result.status == 200

        oci.wait_until(network_client,
                       network_client.get_vcn(vcn_ocid),
                       'lifecycle_state',
                       'AVAILABLE',
                       max_wait_seconds=300,
                       max_interval_seconds=WAIT_INTERVAL_SECONDS)

        # create subnet in first AD
        subnet_name = util.random_name('cli_lb_test_subnet')
        cidr_block = "10.0.1.0/24"
        subnet_dns_label = util.random_name('subnet', insert_underscore=False)

        create_subnet_details = oci.core.models.CreateSubnetDetails()
        create_subnet_details.compartment_id = os.environ[
            'OCI_CLI_COMPARTMENT_ID']
        create_subnet_details.availability_domain = util.availability_domain()
        create_subnet_details.display_name = subnet_name
        create_subnet_details.vcn_id = vcn_ocid
        create_subnet_details.cidr_block = cidr_block
        create_subnet_details.dns_label = subnet_dns_label

        result = network_client.create_subnet(create_subnet_details)
        subnet_ocid_1 = result.data.id
        assert result.status == 200

        oci.wait_until(network_client,
                       network_client.get_subnet(subnet_ocid_1),
                       'lifecycle_state',
                       'AVAILABLE',
                       max_wait_seconds=300,
                       max_interval_seconds=WAIT_INTERVAL_SECONDS)

        # create subnet in second AD
        subnet_name = util.random_name('cli_lb_test_subnet')
        cidr_block = "10.0.0.0/24"
        subnet_dns_label = util.random_name('subnet2', insert_underscore=False)

        create_subnet_details = oci.core.models.CreateSubnetDetails()
        create_subnet_details.compartment_id = os.environ[
            'OCI_CLI_COMPARTMENT_ID']
        create_subnet_details.availability_domain = util.second_availability_domain(
        )
        create_subnet_details.display_name = subnet_name
        create_subnet_details.vcn_id = vcn_ocid
        create_subnet_details.cidr_block = cidr_block
        create_subnet_details.dns_label = subnet_dns_label

        result = network_client.create_subnet(create_subnet_details)
        subnet_ocid_2 = result.data.id
        assert result.status == 200

        oci.wait_until(network_client,
                       network_client.get_subnet(subnet_ocid_2),
                       'lifecycle_state',
                       'AVAILABLE',
                       max_wait_seconds=300,
                       max_interval_seconds=WAIT_INTERVAL_SECONDS)

    yield [vcn_ocid, subnet_ocid_1, subnet_ocid_2]

    # For some reason VCR doesn't like that the post-yield stuff here is all in one cassette. Splitting into different cassettes seems to work
    with test_config_container.create_vcr().use_cassette(
            '_conftest_fixture_vcn_and_subnets_delete.yml'):
        # delete VCN and subnets
        network_client.delete_subnet(subnet_ocid_1)

        try:
            oci.wait_until(network_client,
                           network_client.get_subnet(subnet_ocid_1),
                           'lifecycle_state',
                           'TERMINATED',
                           max_wait_seconds=600,
                           max_interval_seconds=WAIT_INTERVAL_SECONDS)
        except oci.exceptions.ServiceError as error:
            if not hasattr(error, 'status') or error.status != 404:
                util.print_latest_exception(error)

        network_client.delete_subnet(subnet_ocid_2)

        try:
            oci.wait_until(network_client,
                           network_client.get_subnet(subnet_ocid_2),
                           'lifecycle_state',
                           'TERMINATED',
                           max_wait_seconds=600,
                           max_interval_seconds=WAIT_INTERVAL_SECONDS)
        except oci.exceptions.ServiceError as error:
            if not hasattr(error, 'status') or error.status != 404:
                util.print_latest_exception(error)

        network_client.delete_vcn(vcn_ocid)
def start_instance(instance_id, instance_name, compute_client, wait):
    print("===============================\nStarting Instance %s\n===============================\n" %(instance_name))
    compute_client.instance_action(instance_id, "START")
    if wait:
        oci.wait_until(compute_client, compute_client.get_instance(instance_id), 'lifecycle_state', 'RUNNING')
    print("Instance Started:\n%s, %s\n\n" % (instance_name, instance_id))
Beispiel #44
0
def change_oce_instance_compartment(ctx, from_json, wait_for_state,
                                    max_wait_seconds, wait_interval_seconds,
                                    oce_instance_id, compartment_id, if_match):

    if isinstance(oce_instance_id, six.string_types) and len(
            oce_instance_id.strip()) == 0:
        raise click.UsageError(
            'Parameter --oce-instance-id cannot be whitespace or empty string')

    kwargs = {}
    if if_match is not None:
        kwargs['if_match'] = if_match
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(
        ctx.obj['request_id'])

    _details = {}
    _details['compartmentId'] = compartment_id

    client = cli_util.build_client('oce', 'oce_instance', ctx)
    result = client.change_oce_instance_compartment(
        oce_instance_id=oce_instance_id,
        change_oce_instance_compartment_details=_details,
        **kwargs)
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(
                getattr(client, 'get_work_request')):
            try:
                wait_period_kwargs = {}
                if max_wait_seconds is not None:
                    wait_period_kwargs['max_wait_seconds'] = max_wait_seconds
                if wait_interval_seconds is not None:
                    wait_period_kwargs[
                        'max_interval_seconds'] = wait_interval_seconds

                click.echo(
                    'Action completed. Waiting until the work request has entered state: {}'
                    .format(wait_for_state),
                    file=sys.stderr)
                result = oci.wait_until(
                    client,
                    client.get_work_request(
                        result.headers['opc-work-request-id']), 'status',
                    wait_for_state, **wait_period_kwargs)
            except oci.exceptions.MaximumWaitTimeExceeded as e:
                # If we fail, we should show an error, but we should still provide the information to the customer
                click.echo(
                    'Failed to wait until the work request entered the specified state. Outputting last known resource state',
                    file=sys.stderr)
                cli_util.render_response(result, ctx)
                sys.exit(2)
            except Exception:
                click.echo(
                    'Encountered error while waiting for work request to enter the specified state. Outputting last known resource state',
                    file=sys.stderr)
                cli_util.render_response(result, ctx)
                raise
        else:
            click.echo(
                'Unable to wait for the work request to enter the specified state',
                file=sys.stderr)
    cli_util.render_response(result, ctx)
Beispiel #45
0
                display_name='Python SDK tagging example VCN',
                dns_label='vcn{}'.format(random.randint(0, 1000000)),
                freeform_tags={
                    'free': 'form',
                    'another': 'item'
                },
                defined_tags={
                    tag_namespace.name: {
                        tag_one_name: 'hello',
                        tag_two_name: 'world'
                    }
                }))
        vcn_id = create_vcn_response.data.id
        vcn_after_wait_response = oci.wait_until(
            virtual_network,
            virtual_network.get_vcn(vcn_id),
            'lifecycle_state',
            'AVAILABLE',
            max_wait_seconds=300)
        print('Created VCN with tags: {}'.format(vcn_after_wait_response.data))
        break
    except oci.exceptions.ServiceError as e:
        if e.status == 404:
            print('Retrying on 404: {}'.format(e))
            num_tries += 1
            if num_tries >= 3:  # If we can't get it in 3 tries, something else may be going on
                raise
            else:
                time.sleep(2)
        else:
            raise
Beispiel #46
0
def create_oce_instance(ctx, from_json, wait_for_state, max_wait_seconds,
                        wait_interval_seconds, compartment_id, name,
                        tenancy_id, idcs_access_token, tenancy_name,
                        object_storage_namespace, admin_email, description,
                        identity_stripe, instance_usage_type, upgrade_schedule,
                        waf_primary_domain, instance_access_type,
                        instance_license_type, freeform_tags, defined_tags):

    kwargs = {}
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(
        ctx.obj['request_id'])

    _details = {}
    _details['compartmentId'] = compartment_id
    _details['name'] = name
    _details['tenancyId'] = tenancy_id
    _details['idcsAccessToken'] = idcs_access_token
    _details['tenancyName'] = tenancy_name
    _details['objectStorageNamespace'] = object_storage_namespace
    _details['adminEmail'] = admin_email

    if description is not None:
        _details['description'] = description

    if identity_stripe is not None:
        _details['identityStripe'] = cli_util.parse_json_parameter(
            "identity_stripe", identity_stripe)

    if instance_usage_type is not None:
        _details['instanceUsageType'] = instance_usage_type

    if upgrade_schedule is not None:
        _details['upgradeSchedule'] = upgrade_schedule

    if waf_primary_domain is not None:
        _details['wafPrimaryDomain'] = waf_primary_domain

    if instance_access_type is not None:
        _details['instanceAccessType'] = instance_access_type

    if instance_license_type is not None:
        _details['instanceLicenseType'] = instance_license_type

    if freeform_tags is not None:
        _details['freeformTags'] = cli_util.parse_json_parameter(
            "freeform_tags", freeform_tags)

    if defined_tags is not None:
        _details['definedTags'] = cli_util.parse_json_parameter(
            "defined_tags", defined_tags)

    client = cli_util.build_client('oce', 'oce_instance', ctx)
    result = client.create_oce_instance(create_oce_instance_details=_details,
                                        **kwargs)
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(
                getattr(client, 'get_work_request')):
            try:
                wait_period_kwargs = {}
                if max_wait_seconds is not None:
                    wait_period_kwargs['max_wait_seconds'] = max_wait_seconds
                if wait_interval_seconds is not None:
                    wait_period_kwargs[
                        'max_interval_seconds'] = wait_interval_seconds

                click.echo(
                    'Action completed. Waiting until the work request has entered state: {}'
                    .format(wait_for_state),
                    file=sys.stderr)
                result = oci.wait_until(
                    client,
                    client.get_work_request(
                        result.headers['opc-work-request-id']), 'status',
                    wait_for_state, **wait_period_kwargs)
            except oci.exceptions.MaximumWaitTimeExceeded as e:
                # If we fail, we should show an error, but we should still provide the information to the customer
                click.echo(
                    'Failed to wait until the work request entered the specified state. Outputting last known resource state',
                    file=sys.stderr)
                cli_util.render_response(result, ctx)
                sys.exit(2)
            except Exception:
                click.echo(
                    'Encountered error while waiting for work request to enter the specified state. Outputting last known resource state',
                    file=sys.stderr)
                cli_util.render_response(result, ctx)
                raise
        else:
            click.echo(
                'Unable to wait for the work request to enter the specified state',
                file=sys.stderr)
    cli_util.render_response(result, ctx)
Beispiel #47
0
def create_transfer_appliance_entitlement(ctx, from_json, wait_for_state,
                                          max_wait_seconds,
                                          wait_interval_seconds,
                                          compartment_id, display_name,
                                          requestor_name, requestor_email,
                                          freeform_tags, defined_tags):

    kwargs = {}
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(
        ctx.obj['request_id'])

    details = {}

    if compartment_id is not None:
        details['compartmentId'] = compartment_id

    if display_name is not None:
        details['displayName'] = display_name

    if requestor_name is not None:
        details['requestorName'] = requestor_name

    if requestor_email is not None:
        details['requestorEmail'] = requestor_email

    if freeform_tags is not None:
        details['freeformTags'] = cli_util.parse_json_parameter(
            "freeform_tags", freeform_tags)

    if defined_tags is not None:
        details['definedTags'] = cli_util.parse_json_parameter(
            "defined_tags", defined_tags)

    client = cli_util.build_client('transfer_appliance_entitlement', ctx)
    result = client.create_transfer_appliance_entitlement(
        create_transfer_appliance_entitlement_details=details, **kwargs)
    if wait_for_state:
        if hasattr(client, 'get_transfer_appliance_entitlement') and callable(
                getattr(client, 'get_transfer_appliance_entitlement')):
            try:
                wait_period_kwargs = {}
                if max_wait_seconds is not None:
                    wait_period_kwargs['max_wait_seconds'] = max_wait_seconds
                if wait_interval_seconds is not None:
                    wait_period_kwargs[
                        'max_interval_seconds'] = wait_interval_seconds

                click.echo(
                    'Action completed. Waiting until the resource has entered state: {}'
                    .format(wait_for_state),
                    file=sys.stderr)
                result = oci.wait_until(
                    client,
                    client.get_transfer_appliance_entitlement(result.data.id),
                    'lifecycle_state', wait_for_state, **wait_period_kwargs)
            except oci.exceptions.MaximumWaitTimeExceeded as e:
                # If we fail, we should show an error, but we should still provide the information to the customer
                click.echo(
                    'Failed to wait until the resource entered the specified state. Outputting last known resource state',
                    file=sys.stderr)
                cli_util.render_response(result, ctx)
                sys.exit(2)
            except Exception:
                click.echo(
                    'Encountered error while waiting for resource to enter the specified state. Outputting last known resource state',
                    file=sys.stderr)
                cli_util.render_response(result, ctx)
                raise
        else:
            click.echo(
                'Unable to wait for the resource to enter the specified state',
                file=sys.stderr)
    cli_util.render_response(result, ctx)
Beispiel #48
0
def delete_volume(block_storage, volume):
    block_storage.delete_volume(volume.id)
    oci.wait_until(block_storage, block_storage.get_volume(volume.id),
                   'lifecycle_state', 'TERMINATED')
source_config = oci.config.from_file()
destination_config = source_config.copy()
destination_config["region"] = destination_region
source_blockstorage_client = oci.core.BlockstorageClient(source_config)
destination_blockstorage_client = oci.core.BlockstorageClient(
    destination_config)

print(
    'Copying backup with ID {} from {} to {} using new display name: {} and kms key id: {} \n'
    .format(source_backup_id, source_config["region"], destination_region,
            display_name, kms_key_id))
result = source_blockstorage_client.copy_volume_backup(
    source_backup_id,
    oci.core.models.CopyVolumeBackupDetails(
        destination_region=destination_region,
        display_name=display_name,
        kms_key_id=kms_key_id))

print('Copy backup response status: {}, copied backup: {}\n'.format(
    result.status, result.data))
print('Waiting for the copied backup to be in available state...')

# query the destination region for the copied' backup's status and wait for it to be available.
copied_backup = oci.wait_until(
    destination_blockstorage_client,
    destination_blockstorage_client.get_volume_backup(result.data.id),
    'lifecycle_state', 'AVAILABLE').data

print('Backup successfully copied: {}'.format(copied_backup))
print('Example script done')
Beispiel #50
0
    print('')
    print('')

    paravirtualized_volume_attachment_response = compute_client.attach_volume(
        oci.core.models.AttachParavirtualizedVolumeDetails(
            display_name='ParavirtualizedVolAttachment',
            instance_id=instance.id,
            volume_id=volume.id,
            is_pv_encryption_in_transit_enabled=True))
    print('Attached paravirtualized volume')
    print('')

    # We can wait until the volume have attached
    oci.wait_until(
        compute_client,
        compute_client.get_volume_attachment(
            paravirtualized_volume_attachment_response.data.id),
        'lifecycle_state', 'ATTACHED')

    # Listing volume attachments is a paginated operation, so we can use the functions in the
    # oci.pagination module to get them all. We can also supply keyword argument filters - in
    # this case we are only interested in the volume attachments on our instance
    volume_attachments = oci.pagination.list_call_get_all_results(
        compute_client.list_volume_attachments,
        compartment_id,
        instance_id=instance.id).data

    # Note that each element could be a different attachment_type, denoting the different types of volume attachments
    # there are.
    #
    # These are all subclasses of oci.core.models.VolumeAttachment
Beispiel #51
0
def create_esxi_host(ctx, from_json, wait_for_state, max_wait_seconds,
                     wait_interval_seconds, sddc_id, display_name, current_sku,
                     next_sku, compute_availability_domain,
                     failed_esxi_host_id, host_shape_name, host_ocpu_count,
                     capacity_reservation_id, freeform_tags, defined_tags):

    kwargs = {}
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(
        ctx.obj['request_id'])

    _details = {}
    _details['sddcId'] = sddc_id

    if display_name is not None:
        _details['displayName'] = display_name

    if current_sku is not None:
        _details['currentSku'] = current_sku

    if next_sku is not None:
        _details['nextSku'] = next_sku

    if compute_availability_domain is not None:
        _details['computeAvailabilityDomain'] = compute_availability_domain

    if failed_esxi_host_id is not None:
        _details['failedEsxiHostId'] = failed_esxi_host_id

    if host_shape_name is not None:
        _details['hostShapeName'] = host_shape_name

    if host_ocpu_count is not None:
        _details['hostOcpuCount'] = host_ocpu_count

    if capacity_reservation_id is not None:
        _details['capacityReservationId'] = capacity_reservation_id

    if freeform_tags is not None:
        _details['freeformTags'] = cli_util.parse_json_parameter(
            "freeform_tags", freeform_tags)

    if defined_tags is not None:
        _details['definedTags'] = cli_util.parse_json_parameter(
            "defined_tags", defined_tags)

    client = cli_util.build_client('ocvp', 'esxi_host', ctx)
    result = client.create_esxi_host(create_esxi_host_details=_details,
                                     **kwargs)
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(
                getattr(client, 'get_work_request')):
            try:
                wait_period_kwargs = {}
                if max_wait_seconds is not None:
                    wait_period_kwargs['max_wait_seconds'] = max_wait_seconds
                if wait_interval_seconds is not None:
                    wait_period_kwargs[
                        'max_interval_seconds'] = wait_interval_seconds

                click.echo(
                    'Action completed. Waiting until the work request has entered state: {}'
                    .format(wait_for_state),
                    file=sys.stderr)
                result = oci.wait_until(
                    client,
                    client.get_work_request(
                        result.headers['opc-work-request-id']), 'status',
                    wait_for_state, **wait_period_kwargs)
            except oci.exceptions.MaximumWaitTimeExceeded as e:
                # If we fail, we should show an error, but we should still provide the information to the customer
                click.echo(
                    'Failed to wait until the work request entered the specified state. Outputting last known resource state',
                    file=sys.stderr)
                cli_util.render_response(result, ctx)
                sys.exit(2)
            except Exception:
                click.echo(
                    'Encountered error while waiting for work request to enter the specified state. Outputting last known resource state',
                    file=sys.stderr)
                cli_util.render_response(result, ctx)
                raise
        else:
            click.echo(
                'Unable to wait for the work request to enter the specified state',
                file=sys.stderr)
    cli_util.render_response(result, ctx)
Beispiel #52
0
def update_rover_cluster(
        ctx, from_json, force, wait_for_state, max_wait_seconds,
        wait_interval_seconds, rover_cluster_id, display_name, cluster_size,
        customer_shipping_address, cluster_workloads, super_user_password,
        lifecycle_state, lifecycle_state_details, unlock_passphrase,
        enclosure_type, point_of_contact, point_of_contact_phone_number,
        shipping_preference, oracle_shipping_tracking_url, shipping_vendor,
        time_pickup_expected, freeform_tags, defined_tags, system_tags,
        if_match):

    if isinstance(rover_cluster_id, six.string_types) and len(
            rover_cluster_id.strip()) == 0:
        raise click.UsageError(
            'Parameter --rover-cluster-id cannot be whitespace or empty string'
        )
    if not force:
        if customer_shipping_address or cluster_workloads or freeform_tags or defined_tags or system_tags:
            if not click.confirm(
                    "WARNING: Updates to customer-shipping-address and cluster-workloads and freeform-tags and defined-tags and system-tags will replace any existing values. Are you sure you want to continue?"
            ):
                ctx.abort()

    kwargs = {}
    if if_match is not None:
        kwargs['if_match'] = if_match
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(
        ctx.obj['request_id'])

    _details = {}

    if display_name is not None:
        _details['displayName'] = display_name

    if cluster_size is not None:
        _details['clusterSize'] = cluster_size

    if customer_shipping_address is not None:
        _details['customerShippingAddress'] = cli_util.parse_json_parameter(
            "customer_shipping_address", customer_shipping_address)

    if cluster_workloads is not None:
        _details['clusterWorkloads'] = cli_util.parse_json_parameter(
            "cluster_workloads", cluster_workloads)

    if super_user_password is not None:
        _details['superUserPassword'] = super_user_password

    if lifecycle_state is not None:
        _details['lifecycleState'] = lifecycle_state

    if lifecycle_state_details is not None:
        _details['lifecycleStateDetails'] = lifecycle_state_details

    if unlock_passphrase is not None:
        _details['unlockPassphrase'] = unlock_passphrase

    if enclosure_type is not None:
        _details['enclosureType'] = enclosure_type

    if point_of_contact is not None:
        _details['pointOfContact'] = point_of_contact

    if point_of_contact_phone_number is not None:
        _details['pointOfContactPhoneNumber'] = point_of_contact_phone_number

    if shipping_preference is not None:
        _details['shippingPreference'] = shipping_preference

    if oracle_shipping_tracking_url is not None:
        _details['oracleShippingTrackingUrl'] = oracle_shipping_tracking_url

    if shipping_vendor is not None:
        _details['shippingVendor'] = shipping_vendor

    if time_pickup_expected is not None:
        _details['timePickupExpected'] = time_pickup_expected

    if freeform_tags is not None:
        _details['freeformTags'] = cli_util.parse_json_parameter(
            "freeform_tags", freeform_tags)

    if defined_tags is not None:
        _details['definedTags'] = cli_util.parse_json_parameter(
            "defined_tags", defined_tags)

    if system_tags is not None:
        _details['systemTags'] = cli_util.parse_json_parameter(
            "system_tags", system_tags)

    client = cli_util.build_client('rover', 'rover_cluster', ctx)
    result = client.update_rover_cluster(rover_cluster_id=rover_cluster_id,
                                         update_rover_cluster_details=_details,
                                         **kwargs)
    if wait_for_state:

        if hasattr(client, 'get_rover_cluster') and callable(
                getattr(client, 'get_rover_cluster')):
            try:
                wait_period_kwargs = {}
                if max_wait_seconds is not None:
                    wait_period_kwargs['max_wait_seconds'] = max_wait_seconds
                if wait_interval_seconds is not None:
                    wait_period_kwargs[
                        'max_interval_seconds'] = wait_interval_seconds

                click.echo(
                    'Action completed. Waiting until the resource has entered state: {}'
                    .format(wait_for_state),
                    file=sys.stderr)
                result = oci.wait_until(
                    client, client.get_rover_cluster(result.data.id),
                    'lifecycle_state', wait_for_state, **wait_period_kwargs)
            except oci.exceptions.MaximumWaitTimeExceeded as e:
                # If we fail, we should show an error, but we should still provide the information to the customer
                click.echo(
                    'Failed to wait until the resource entered the specified state. Outputting last known resource state',
                    file=sys.stderr)
                cli_util.render_response(result, ctx)
                sys.exit(2)
            except Exception:
                click.echo(
                    'Encountered error while waiting for resource to enter the specified state. Outputting last known resource state',
                    file=sys.stderr)
                cli_util.render_response(result, ctx)
                raise
        else:
            click.echo(
                'Unable to wait for the resource to enter the specified state',
                file=sys.stderr)
    cli_util.render_response(result, ctx)
def do_wait(client, *args, **kwargs):
    if vcr_mode == 'none':
        kwargs['max_interval_seconds'] = 0

    oci.wait_until(client, *args, **kwargs)
Beispiel #54
0
def delete_rover_cluster(ctx, from_json, wait_for_state, max_wait_seconds,
                         wait_interval_seconds, rover_cluster_id, if_match):

    if isinstance(rover_cluster_id, six.string_types) and len(
            rover_cluster_id.strip()) == 0:
        raise click.UsageError(
            'Parameter --rover-cluster-id cannot be whitespace or empty string'
        )

    kwargs = {}
    if if_match is not None:
        kwargs['if_match'] = if_match
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(
        ctx.obj['request_id'])
    client = cli_util.build_client('rover', 'rover_cluster', ctx)
    result = client.delete_rover_cluster(rover_cluster_id=rover_cluster_id,
                                         **kwargs)
    if wait_for_state:

        if hasattr(client, 'get_rover_cluster') and callable(
                getattr(client, 'get_rover_cluster')):
            try:
                wait_period_kwargs = {}
                if max_wait_seconds is not None:
                    wait_period_kwargs['max_wait_seconds'] = max_wait_seconds
                if wait_interval_seconds is not None:
                    wait_period_kwargs[
                        'max_interval_seconds'] = wait_interval_seconds

                click.echo(
                    'Action completed. Waiting until the resource has entered state: {}'
                    .format(wait_for_state),
                    file=sys.stderr)
                oci.wait_until(client,
                               client.get_rover_cluster(rover_cluster_id),
                               'lifecycle_state',
                               wait_for_state,
                               succeed_on_not_found=True,
                               **wait_period_kwargs)
            except oci.exceptions.ServiceError as e:
                # We make an initial service call so we can pass the result to oci.wait_until(), however if we are waiting on the
                # outcome of a delete operation it is possible that the resource is already gone and so the initial service call
                # will result in an exception that reflects a HTTP 404. In this case, we can exit with success (rather than raising
                # the exception) since this would have been the behaviour in the waiter anyway (as for delete we provide the argument
                # succeed_on_not_found=True to the waiter).
                #
                # Any non-404 should still result in the exception being thrown.
                if e.status == 404:
                    pass
                else:
                    raise
            except oci.exceptions.MaximumWaitTimeExceeded as e:
                # If we fail, we should show an error, but we should still provide the information to the customer
                click.echo(
                    'Failed to wait until the resource entered the specified state. Please retrieve the resource to find its current state',
                    file=sys.stderr)
                cli_util.render_response(result, ctx)
                sys.exit(2)
            except Exception:
                click.echo(
                    'Encountered error while waiting for resource to enter the specified state. Outputting last known resource state',
                    file=sys.stderr)
                cli_util.render_response(result, ctx)
                raise
        else:
            click.echo(
                'Unable to wait for the resource to enter the specified state',
                file=sys.stderr)
    cli_util.render_response(result, ctx)
Beispiel #55
0
def create_alert_rule(ctx, from_json, wait_for_state, max_wait_seconds,
                      wait_interval_seconds, budget_id, type, threshold,
                      threshold_type, recipients, display_name, description,
                      message, freeform_tags, defined_tags):

    if isinstance(budget_id, six.string_types) and len(budget_id.strip()) == 0:
        raise click.UsageError(
            'Parameter --budget-id cannot be whitespace or empty string')

    kwargs = {}
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(
        ctx.obj['request_id'])

    details = {}
    details['type'] = type
    details['threshold'] = threshold
    details['thresholdType'] = threshold_type
    details['recipients'] = recipients

    if display_name is not None:
        details['displayName'] = display_name

    if description is not None:
        details['description'] = description

    if message is not None:
        details['message'] = message

    if freeform_tags is not None:
        details['freeformTags'] = cli_util.parse_json_parameter(
            "freeform_tags", freeform_tags)

    if defined_tags is not None:
        details['definedTags'] = cli_util.parse_json_parameter(
            "defined_tags", defined_tags)

    client = cli_util.build_client('budget', ctx)
    result = client.create_alert_rule(budget_id=budget_id,
                                      create_alert_rule_details=details,
                                      **kwargs)
    if wait_for_state:
        if hasattr(client, 'get_alert_rule') and callable(
                getattr(client, 'get_alert_rule')):
            try:
                wait_period_kwargs = {}
                if max_wait_seconds is not None:
                    wait_period_kwargs['max_wait_seconds'] = max_wait_seconds
                if wait_interval_seconds is not None:
                    wait_period_kwargs[
                        'max_interval_seconds'] = wait_interval_seconds

                click.echo(
                    'Action completed. Waiting until the resource has entered state: {}'
                    .format(wait_for_state),
                    file=sys.stderr)
                result = oci.wait_until(client,
                                        client.get_alert_rule(result.data.id),
                                        'lifecycle_state', wait_for_state,
                                        **wait_period_kwargs)
            except oci.exceptions.MaximumWaitTimeExceeded as e:
                # If we fail, we should show an error, but we should still provide the information to the customer
                click.echo(
                    'Failed to wait until the resource entered the specified state. Outputting last known resource state',
                    file=sys.stderr)
                cli_util.render_response(result, ctx)
                sys.exit(2)
            except Exception:
                click.echo(
                    'Encountered error while waiting for resource to enter the specified state. Outputting last known resource state',
                    file=sys.stderr)
                cli_util.render_response(result, ctx)
                raise
        else:
            click.echo(
                'Unable to wait for the resource to enter the specified state',
                file=sys.stderr)
    cli_util.render_response(result, ctx)
Beispiel #56
0
def create_rover_cluster(
        ctx, from_json, wait_for_state, max_wait_seconds,
        wait_interval_seconds, display_name, compartment_id, cluster_size,
        customer_shipping_address, cluster_workloads, super_user_password,
        enclosure_type, unlock_passphrase, point_of_contact,
        point_of_contact_phone_number, shipping_preference, shipping_vendor,
        time_pickup_expected, oracle_shipping_tracking_url, lifecycle_state,
        lifecycle_state_details, freeform_tags, defined_tags, system_tags):

    kwargs = {}
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(
        ctx.obj['request_id'])

    _details = {}
    _details['displayName'] = display_name
    _details['compartmentId'] = compartment_id
    _details['clusterSize'] = cluster_size

    if customer_shipping_address is not None:
        _details['customerShippingAddress'] = cli_util.parse_json_parameter(
            "customer_shipping_address", customer_shipping_address)

    if cluster_workloads is not None:
        _details['clusterWorkloads'] = cli_util.parse_json_parameter(
            "cluster_workloads", cluster_workloads)

    if super_user_password is not None:
        _details['superUserPassword'] = super_user_password

    if enclosure_type is not None:
        _details['enclosureType'] = enclosure_type

    if unlock_passphrase is not None:
        _details['unlockPassphrase'] = unlock_passphrase

    if point_of_contact is not None:
        _details['pointOfContact'] = point_of_contact

    if point_of_contact_phone_number is not None:
        _details['pointOfContactPhoneNumber'] = point_of_contact_phone_number

    if shipping_preference is not None:
        _details['shippingPreference'] = shipping_preference

    if shipping_vendor is not None:
        _details['shippingVendor'] = shipping_vendor

    if time_pickup_expected is not None:
        _details['timePickupExpected'] = time_pickup_expected

    if oracle_shipping_tracking_url is not None:
        _details['oracleShippingTrackingUrl'] = oracle_shipping_tracking_url

    if lifecycle_state is not None:
        _details['lifecycleState'] = lifecycle_state

    if lifecycle_state_details is not None:
        _details['lifecycleStateDetails'] = lifecycle_state_details

    if freeform_tags is not None:
        _details['freeformTags'] = cli_util.parse_json_parameter(
            "freeform_tags", freeform_tags)

    if defined_tags is not None:
        _details['definedTags'] = cli_util.parse_json_parameter(
            "defined_tags", defined_tags)

    if system_tags is not None:
        _details['systemTags'] = cli_util.parse_json_parameter(
            "system_tags", system_tags)

    client = cli_util.build_client('rover', 'rover_cluster', ctx)
    result = client.create_rover_cluster(create_rover_cluster_details=_details,
                                         **kwargs)
    if wait_for_state:

        if hasattr(client, 'get_rover_cluster') and callable(
                getattr(client, 'get_rover_cluster')):
            try:
                wait_period_kwargs = {}
                if max_wait_seconds is not None:
                    wait_period_kwargs['max_wait_seconds'] = max_wait_seconds
                if wait_interval_seconds is not None:
                    wait_period_kwargs[
                        'max_interval_seconds'] = wait_interval_seconds

                click.echo(
                    'Action completed. Waiting until the resource has entered state: {}'
                    .format(wait_for_state),
                    file=sys.stderr)
                result = oci.wait_until(
                    client, client.get_rover_cluster(result.data.id),
                    'lifecycle_state', wait_for_state, **wait_period_kwargs)
            except oci.exceptions.MaximumWaitTimeExceeded as e:
                # If we fail, we should show an error, but we should still provide the information to the customer
                click.echo(
                    'Failed to wait until the resource entered the specified state. Outputting last known resource state',
                    file=sys.stderr)
                cli_util.render_response(result, ctx)
                sys.exit(2)
            except Exception:
                click.echo(
                    'Encountered error while waiting for resource to enter the specified state. Outputting last known resource state',
                    file=sys.stderr)
                cli_util.render_response(result, ctx)
                raise
        else:
            click.echo(
                'Unable to wait for the resource to enter the specified state',
                file=sys.stderr)
    cli_util.render_response(result, ctx)
Beispiel #57
0
def power_action_on_instance_pool(compute_management_client, module):
    result = {}
    changed = False
    # The power action to execute on a compute instance pool to reach the desired 'state'
    state_action_map = {
        "stopped": "STOP",
        "running": "START",
        "reset": "RESET",
        "softreset": "SOFTRESET",
    }
    # The desired lifecycle state for the compute instance pool to reach the user specified 'state'
    desired_lifecycle_states = {
        "stopped": "STOPPED",
        "running": "RUNNING",
        "reset": "RUNNING",
        "softreset": "RUNNING",
    }

    desired_state = module.params["state"]
    instance_pool_id = module.params["id"]
    try:
        response = oci_utils.call_with_backoff(
            compute_management_client.get_instance_pool,
            instance_pool_id=instance_pool_id,
        )
        curr_state = response.data.lifecycle_state

        change_required = False

        # We need to perform a power action if the current state doesn't match the desired state
        if curr_state != desired_lifecycle_states[desired_state]:
            change_required = True

        # Resets also require a change
        if desired_state in ["softreset", "reset"]:
            change_required = True

        if change_required:
            changed = True
            instance_action_method_name = (
                state_action_map[desired_state].lower() + "_instance_pool")
            instance_action_method = getattr(compute_management_client,
                                             instance_action_method_name)
            oci_utils.call_with_backoff(instance_action_method,
                                        instance_pool_id=instance_pool_id)
            response = oci_utils.call_with_backoff(
                compute_management_client.get_instance_pool,
                instance_pool_id=instance_pool_id,
            )
            # for now the power actions on instances do not go through common utilities for wait.
            if module.params.get("wait", None):
                debug("waiting for lifecycle_state to reach {0}".format(
                    desired_lifecycle_states[desired_state]))
                oci.wait_until(
                    compute_management_client,
                    response,
                    "lifecycle_state",
                    desired_lifecycle_states[desired_state],
                    max_wait_seconds=module.params.get(
                        "wait_timeout", oci_utils.MAX_WAIT_TIMEOUT_IN_SECONDS),
                )
                response = oci_utils.call_with_backoff(
                    compute_management_client.get_instance_pool,
                    instance_pool_id=instance_pool_id,
                )
            else:
                debug(
                    "Not waiting for power action request {0} as 'wait' is false."
                    .format(desired_state))

        result["instance_pool"] = to_dict(response.data)
    except ServiceError as ex:
        module.fail_json(msg=ex.message)
    except MaximumWaitTimeExceeded as ex:
        module.fail_json(msg=str(ex))

    result["changed"] = changed
    return result
Beispiel #58
0
# The first argument is the name of the script, so start the index at 1
compartment_id = sys.argv[1]
target_compartment_id = sys.argv[2]
sender_address = sys.argv[3]
suppression_address = sys.argv[4]

create_sender_response = email_client.create_sender(
    oci.email.models.CreateSenderDetails(compartment_id=compartment_id,
                                         email_address=sender_address))
print('Created sender:\n{}'.format(create_sender_response.data))
print('\n=========================\n')

# A sender has a lifecycle state, so we can wait for it to become available
get_sender_response = oci.wait_until(
    email_client, email_client.get_sender(create_sender_response.data.id),
    'lifecycle_state', 'ACTIVE')
print('Waited for sender to become available:\n{}'.format(
    get_sender_response.data))
print('\n=========================\n')

# change sender compartment
change_sender_response = email_client.change_sender_compartment(
    create_sender_response.data.id,
    oci.email.models.ChangeSenderCompartmentDetails(
        compartment_id=target_compartment_id))
print('Moved sender:\n{}'.format(create_sender_response.data.id))
print('\n=========================\n')

# We can list all senders, and also provide optional filters and sorts. Here we'll list all
# senders sorted by their email address, and also demonstrate filtering by sender email
def stop_instance(instance_id, instance_name, compute_client, wait):
    print("===============================\nStopping Instance %s\n===============================\n" %(instance_name))
    compute_client.instance_action(instance_id, "STOP")
    if wait:
        oci.wait_until(compute_client, compute_client.get_instance(instance_id), 'lifecycle_state', 'STOPPED')
    print("Instance Stopped:\n%s, %s\n\n" % (instance_name, instance_id))
Beispiel #60
0
def detach_volume(compute, volume_attachment):
    compute.detach_volume(volume_attachment.id)
    oci.wait_until(compute,
                   compute.get_volume_attachment(volume_attachment.id),
                   'lifecycle_state', 'DETACHED')