def verify_work_request(lb_client, response):
    work_request_id = None
    if response is not None:
        work_request_id = response.headers.get('opc-work-request-id')
    oci.wait_until(lb_client,
                   lb_client.get_work_request(work_request_id),
                   evaluate_response=lambda r: r.data.lifecycle_state in
                   ['SUCCEEDED', 'FAILED'])
    response = lb_client.get_work_request(work_request_id)
    if response.data.lifecycle_state == 'FAILED':
        raise ClientError(Exception(response.data.error_details))
    return response
Esempio n. 2
0
def update_load_balancer(lb_client, module, load_balancer):
    if load_balancer is None:
        raise ClientError(
            Exception("No Load Balancer with id " +
                      module.params.get("load_balancer_id") +
                      " is found for update"))
    result = dict(load_balancer=to_dict(load_balancer), changed=False)
    name = module.params["display_name"]
    defined_tags = module.params["defined_tags"]
    freeform_tags = module.params["freeform_tags"]
    update_load_balancer_details = UpdateLoadBalancerDetails()
    changed = False
    if name is not None and load_balancer.display_name.strip() != name.strip():
        get_logger().info(
            "Updating the display name of load balancer from %s to %s",
            load_balancer.display_name,
            name,
        )
        changed = True
    if freeform_tags is not None and load_balancer.freeform_tags != freeform_tags:
        get_logger().info(
            "Updating the freeform_tags of load balancer from {0} to {1}".
            format(load_balancer.freeform_tags, freeform_tags))
        changed = True
    if defined_tags is not None and load_balancer.defined_tags != defined_tags:
        get_logger().info(
            "Updating the defined_tags of load balancer from {0} to {1}".
            format(load_balancer.defined_tags, defined_tags))
        changed = True

    if changed is True:
        update_load_balancer_details.display_name = name
        update_load_balancer_details.freeform_tags = freeform_tags
        update_load_balancer_details.defined_tags = defined_tags
        result = oci_lb_utils.create_or_update_lb_resources_and_wait(
            resource_type="load_balancer",
            function=lb_client.update_load_balancer,
            kwargs_function={
                "update_load_balancer_details": update_load_balancer_details,
                "load_balancer_id": load_balancer.id,
            },
            lb_client=lb_client,
            get_fn=lb_client.get_load_balancer,
            kwargs_get={"load_balancer_id": load_balancer.id},
            module=module,
        )
        get_logger().info(
            "Successfully updated the parameters of load balancer")
    if not result["changed"]:
        get_logger().info(
            "Unable to update load balancer as the new parameter is same as old one"
        )
    return result
def create_db_home_from_backup_details(db_home_dict):
    if db_home_dict is None:
        raise ClientError(
            Exception(
                "Proper value for attribute db_home is mandatory for creating DB System"
            ))
    create_db_home_for_backup_details = CreateDbHomeFromBackupDetails()
    create_db_home_for_backup_details.database = oci_db_utils.create_database_from_backup_details(
        db_home_dict.get("database", None))
    create_db_home_for_backup_details.display_name = db_home_dict.get(
        "display_name")
    return create_db_home_for_backup_details
def test_create_or_update_autonomous_data_warehousee_client_error(
    db_client, check_and_create_resource_patch
):
    error_message = "databse attribute has no value"
    module = get_module()
    check_and_create_resource_patch.side_effect = ClientError(Exception(error_message))
    try:
        oci_autonomous_data_warehouse.create_or_update_autonomous_data_warehouse(
            db_client, module
        )
    except Exception as ex:
        assert error_message in ex.args[0]
def test_create_or_update_backend_client_error(lb_client,
                                               check_and_create_resource_patch,
                                               get_existing_resource_patch):
    module = get_module()
    error_message = 'Work Request Failed'
    check_and_create_resource_patch.side_effect = ClientError(
        Exception('Work Request Failed'))
    get_existing_resource_patch.return_value = None
    try:
        oci_load_balancer_backend.create_or_update_backend(lb_client, module)
    except Exception as ex:
        assert error_message in ex.args[0]
def create_db_home(db_home_dict):
    if db_home_dict is None:
        raise ClientError(
            Exception(
                'Proper value for attribute db_home is mandatory for creating DB System'
            ))
    create_db_home_details = CreateDbHomeDetails()
    create_db_home_details.database = oci_db_utils.create_database_details(
        db_home_dict.get('database', None))
    create_db_home_details.db_version = db_home_dict.get('db_version')
    create_db_home_details.display_name = db_home_dict.get('display_name')
    return create_db_home_details
def test_delete_backend_client_error(lb_client, verify_work_request_patch, get_existing_backend_set_patch):
    error_message = "Work Request Failed"
    module = get_module(dict())
    backend_set = create_default_backend_set()
    lb_client.delete_backend_set.return_value = get_response(
        200, None, backend_set, None)
    get_existing_backend_set_patch.return_value = backend_set
    verify_work_request_patch.side_effect = ClientError(Exception('Work Request Failed'))
    try:
        oci_load_balancer_backend_set.delete_backend_set(lb_client, module)
    except Exception as ex:
        assert error_message in ex.args[0]
def create_database_from_backup_details(database_dict):
    if database_dict is None:
        raise ClientError(
            Exception(
                "Proper value for attribute database is mandatory for creating this component"
            ))
    create_database_from_backup_details = CreateDatabaseFromBackupDetails()
    for attribute in create_database_from_backup_details.attribute_map.keys():
        create_database_from_backup_details.__setattr__(
            attribute, database_dict.get(attribute, None))

    return create_database_from_backup_details
def start_or_stop_autonomous_database(db_client, module):
    autonomous_database_id = module.params.get('autonomous_database_id')
    autonomous_database = oci_utils.get_existing_resource(
        db_client.get_autonomous_database,
        module,
        autonomous_database_id=autonomous_database_id)
    if autonomous_database is None:
        raise ClientError(
            Exception("No Autonomous Database with id " +
                      autonomous_database_id + " is found for update"))

    return perform_start_or_stop(db_client, autonomous_database,
                                 autonomous_database_id, module)
Esempio n. 10
0
def get_user_ids_from_user_names(identity_client, user_names, module):
    user_ids = []
    users = oci_utils.list_all_resources(
        identity_client.list_users,
        compartment_id=module.params.get("compartment_id"))
    user_id_dict = dict((user_name, user.id) for user in users
                        for user_name in user_names
                        if user.name.strip() == user_name.strip())
    try:
        user_ids = [user_id_dict[user_name] for user_name in user_names]
    except KeyError as ex:
        raise ClientError("User " + ex.args[0] + " does not exists")
    return user_ids
Esempio n. 11
0
def test_create_or_update_path_route_set_client_error(
        lb_client, check_and_create_resource_patch,
        get_existing_resource_patch):
    module = get_module(dict())
    error_message = "Work Request Failed"
    check_and_create_resource_patch.side_effect = ClientError(
        Exception("Work Request Failed"))
    get_existing_resource_patch.return_value = None
    try:
        oci_load_balancer_path_route_set.create_or_update_path_route_set(
            lb_client, module)
    except Exception as ex:
        assert error_message in ex.args[0]
Esempio n. 12
0
def create_connection_configuration(connection_configuration_details):
    if connection_configuration_details is None:
        return None
    HashedConnectionConfiguration = oci_utils.generate_subclass(ConnectionConfiguration)
    result_connection_configuration = HashedConnectionConfiguration()
    idle_timeout = connection_configuration_details.get("idle_timeout")
    if idle_timeout is None:
        raise ClientError(
            Exception(
                "idle_timeout is mandatory attributes for connection_configuration and can not be empty."
            )
        )
    result_connection_configuration.idle_timeout = idle_timeout
    return result_connection_configuration
Esempio n. 13
0
def test_create_or_update_listener_client_error(
        lb_client, check_and_create_resource_patch):
    error_message = "Work Request Failed"
    module = get_module()
    load_balancer = LoadBalancer()
    load_balancer.listeners = dict()
    lb_client.get_load_balancer.return_value = get_response(
        200, None, load_balancer, None)
    check_and_create_resource_patch.side_effect = ClientError(
        Exception("Work Request Failed"))
    try:
        oci_load_balancer_listener.create_or_update_listener(lb_client, module)
    except Exception as ex:
        assert error_message in ex.args[0]
Esempio n. 14
0
def get_existing_load_balancer(lb_client, module, load_balancer_id):
    existing_lb = None
    if load_balancer_id is None:
        raise ClientError(
            Exception(
                "load_balancer_id is mandatory for update and delete use cases \
                      and must not be empty"))
    try:
        response = lb_client.get_load_balancer(load_balancer_id)
        existing_lb = response.data
    except ServiceError as ex:
        if ex.status != 404:
            module.fail_json(msg=ex.message)
    return existing_lb
Esempio n. 15
0
def is_patch_already_applied(patch_getter_method, current_version,
                             input_version_dict, **kwargs):
    if input_version_dict is None:
        return True
    patch_id = input_version_dict.get("patch_id")
    kwargs.update(patch_id=patch_id)
    existing_patch = oci_utils.call_with_backoff(patch_getter_method,
                                                 **kwargs).data
    if existing_patch is None:
        raise ClientError(
            Exception("No Patch with id " + patch_id + " is available"))
    if existing_patch.version != current_version:
        return False
    return True
Esempio n. 16
0
def get_group_ids_from_group_names(identity_client,
                                   group_names, module):
    group_ids = []
    compartment_id = module.params.get('compartment_id')
    all_existing_groups = oci_utils.list_all_resources(
        identity_client.list_groups, compartment_id=compartment_id)
    group_id_dict = {group_name: group.id for group in all_existing_groups
                     for group_name in group_names if group.name == group_name}
    try:
        group_ids = [group_id_dict[group_name] for group_name in group_names]
    except KeyError as ex:
        raise ClientError("Group " + ex.args[0] + " does not exists")

    return group_ids
def update_dhcp_options(virtual_network_client, existing_dhcp_options, module):
    if existing_dhcp_options is None:
        raise ClientError(
            Exception("No Dhcp Options with id " +
                      module.params.get("dhcp_id") + " is found for update"))
    result = dict(dhcp_options=to_dict(existing_dhcp_options), changed=False)
    name_tag_changed = False
    options_changed = False
    input_options = module.params.get("options")
    update_dhcp_details = UpdateDhcpDetails()
    existing_options = existing_dhcp_options.options
    attributes_to_compare = ["display_name", "freeform_tags", "defined_tags"]
    for attribute in attributes_to_compare:
        name_tag_changed = oci_utils.check_and_update_attributes(
            update_dhcp_details,
            attribute,
            module.params.get(attribute),
            getattr(existing_dhcp_options, attribute),
            name_tag_changed,
        )
    if input_options is not None:
        if input_options:
            options, options_changed = oci_utils.get_component_list_difference(
                get_options_objects(input_options),
                get_hashed_options(existing_options),
                module.params.get("purge_dhcp_options"),
                module.params.get("delete_dhcp_options"),
            )
    if options_changed:
        update_dhcp_details.options = options
    else:
        update_dhcp_details.options = existing_options

    if name_tag_changed or options_changed:
        result = oci_utils.update_and_wait(
            resource_type="dhcp_options",
            update_fn=virtual_network_client.update_dhcp_options,
            kwargs_update={
                "dhcp_id": existing_dhcp_options.id,
                "update_dhcp_details": update_dhcp_details,
            },
            client=virtual_network_client,
            get_fn=virtual_network_client.get_dhcp_options,
            get_param="dhcp_id",
            module=module,
        )

    return result
def test_delete_certificate_client_error(lb_client,
                                         get_existing_certificate_patch,
                                         verify_work_request_patch):
    error_message = 'Work Request Failed'
    module = get_module(dict())
    certificate = get_certificate(dict())
    get_existing_certificate_patch.return_value = None
    lb_client.delete_certificate.return_value = get_response(
        204, None, None, None)
    verify_work_request_patch.side_effect = ClientError(
        Exception('Work Request Failed'))
    try:
        result = oci_load_balancer_certificate.delete_certificate(
            lb_client, module)
    except Exception as ex:
        assert error_message in ex.args[0]
def test_update_health_checker_client_error(lb_client,
                                            verify_work_request_patch,
                                            get_existing_health_checker_patch):
    error_message = 'Work Request Failed'
    module = get_module()
    health_checker = get_health_checker()
    get_existing_health_checker_patch.return_value = health_checker
    lb_client.update_health_checker.return_value = get_response(
        204, None, health_checker, None)
    verify_work_request_patch.side_effect = ClientError(
        Exception('Work Request Failed'))
    try:
        oci_load_balancer_health_checker.update_health_checker(
            lb_client, module)
    except Exception as ex:
        assert error_message in ex.args[0]
def update_route_table(virtual_network_client, existing_route_table, module):
    if existing_route_table is None:
        raise ClientError(
            Exception("No Route Table with id " + module.params.get('rt_id') +
                      " is found for update"))
    result = dict(route_table=to_dict(existing_route_table), changed=False)
    input_route_rules = module.params.get('route_rules')
    purge_route_rules = module.params['purge_route_rules']
    name_tag_changed = False
    route_rules_changed = False
    existing_route_rules = existing_route_table.route_rules
    update_route_table_details = UpdateRouteTableDetails()
    attributes_to_compare = ['display_name', 'freeform_tags', 'defined_tags']
    for attribute in attributes_to_compare:
        name_tag_changed = oci_utils.check_and_update_attributes(
            update_route_table_details, attribute,
            module.params.get(attribute),
            getattr(existing_route_table, attribute), name_tag_changed)
    if input_route_rules is not None:
        if input_route_rules:
            route_rules_object_list = get_route_rules(input_route_rules)
            route_rules, route_rules_changed = oci_utils.get_component_list_difference(
                get_hashed_route_rules(route_rules_object_list),
                get_hashed_route_rules(existing_route_rules),
                purge_route_rules)
        else:
            route_rules = []
            route_rules_changed = True
    if route_rules_changed:
        update_route_table_details.route_rules = route_rules
    else:
        update_route_table_details.route_rules = existing_route_rules

    if name_tag_changed or route_rules_changed:
        result = oci_utils.update_and_wait(
            resource_type='route_table',
            update_fn=virtual_network_client.update_route_table,
            kwargs_update={
                'rt_id': existing_route_table.id,
                'update_route_table_details': update_route_table_details
            },
            client=virtual_network_client,
            get_fn=virtual_network_client.get_route_table,
            get_param='rt_id',
            module=module)

    return result
Esempio n. 21
0
def get_export_options(export_options):
    if export_options is None:
        return None
    HashedClientOptions = oci_utils.generate_subclass(ClientOptions)
    result_client_options = []
    for export_option_entry in export_options:
        client_options = HashedClientOptions()
        if export_option_entry.get('source') is None:
            raise ClientError('Export Options attribute source must contain a valid value')
        client_options.source = export_option_entry.get('source')
        client_options.require_privileged_source_port = export_option_entry.get('require_privileged_source_port', True)
        client_options.access = export_option_entry.get('access', 'READ_ONLY')
        client_options.identity_squash = export_option_entry.get('identity_squash', 'ROOT')
        client_options.anonymous_uid = export_option_entry.get('anonymous_uid', 65534)
        client_options.anonymous_gid = export_option_entry.get('anonymous_gid', 65534)
        result_client_options.append(client_options)
    return result_client_options
Esempio n. 22
0
def create_hostnames(hostnames_dicts):
    if hostnames_dicts is None:
        return None
    result_hostnames = dict()
    for key, value in six.iteritems(hostnames_dicts):
        hostname_details = HostnameDetails()
        name = value.get('name', None)
        hostname = value.get('hostname', None)
        if name is None or hostname is None:
            raise ClientError(
                Exception(
                    "name and hostname are mandatory attributes for hostnames and can not be empty."
                ))
        hostname_details.name = name
        hostname_details.hostname = hostname
        result_hostnames.update({key: hostname_details})
    return result_hostnames
Esempio n. 23
0
def create_session_persistence_configuration(
        session_persistence_configuration):
    if session_persistence_configuration is None:
        return None
    HashedSessionPersistenceConfigurationDetails = oci_utils.generate_subclass(
        SessionPersistenceConfigurationDetails)
    result_session_persistence_configuration = HashedSessionPersistenceConfigurationDetails(
    )
    cookie_name = session_persistence_configuration.get('cookie_name')
    if cookie_name is None:
        raise ClientError(
            Exception(
                "cookie_name is mandatory attributes for session_persistence_configuration and can not be empty."
            ))
    result_session_persistence_configuration.cookie_name = cookie_name
    result_session_persistence_configuration.disable_fallback = session_persistence_configuration.get(
        'disable_fallback', False)
    return result_session_persistence_configuration
Esempio n. 24
0
def create_ssl_configuration(ssl_configuration_details):
    if ssl_configuration_details is None:
        return None
    HashedSSLConfigurationDetails = oci_utils.generate_subclass(
        SSLConfigurationDetails)
    result_ssl_configuration = HashedSSLConfigurationDetails()
    attributes = ['verify_depth', 'verify_peer_certificate']
    certificate_name = ssl_configuration_details.get('certificate_name')
    if certificate_name is None:
        raise ClientError(
            Exception(
                "certificate_name is mandatory attributes for ssl_configuration and can not be empty."
            ))
    result_ssl_configuration.certificate_name = certificate_name
    for attribute in attributes:
        result_ssl_configuration.__setattr__(
            attribute, ssl_configuration_details.get(attribute))
    return result_ssl_configuration
Esempio n. 25
0
def create_database_details(database_dict):
    if database_dict is None:
        raise ClientError(
            Exception(
                "Proper value for attribute database is mandatory for creating this component"
            ))
    create_database_details = CreateDatabaseDetails()
    for attribute in create_database_details.attribute_map.keys():
        if attribute != "db_backup_config":
            create_database_details.__setattr__(
                attribute, database_dict.get(attribute, None))
    input_db_backup_config = database_dict.get("db_backup_config")
    if input_db_backup_config is not None:
        db_backup_config = DbBackupConfig()
        db_backup_config.auto_backup_enabled = input_db_backup_config.get(
            "auto_backup_enabled")
        create_database_details.db_backup_config = db_backup_config

    return create_database_details
def update_dhcp_options(virtual_network_client, existing_dhcp_options, module):
    if existing_dhcp_options is None:
        raise ClientError(
            Exception("No Dhcp Options with id " +
                      module.params.get('dhcp_id') + " is found for update"))
    result = dict(dhcp_options=to_dict(existing_dhcp_options), changed=False)
    name_tag_changed = False
    options_changed = False
    input_options = module.params.get('options')
    update_dhcp_details = UpdateDhcpDetails()
    existing_options = existing_dhcp_options.options
    attributes_to_compare = ['display_name', 'freeform_tags', 'defined_tags']
    for attribute in attributes_to_compare:
        name_tag_changed = oci_utils.check_and_update_attributes(
            update_dhcp_details, attribute, module.params.get(attribute),
            getattr(existing_dhcp_options, attribute), name_tag_changed)
    if input_options is not None:
        if input_options:
            options, options_changed = get_options_difference(
                get_options_objects(input_options), existing_options,
                module.params.get('purge_dhcp_options'))

    if options_changed:
        update_dhcp_details.options = options
    else:
        update_dhcp_details.options = existing_options

    if name_tag_changed or options_changed:
        result = oci_utils.update_and_wait(
            resource_type='dhcp_options',
            update_fn=virtual_network_client.update_dhcp_options,
            kwargs_update={
                'dhcp_id': existing_dhcp_options.id,
                'update_dhcp_details': update_dhcp_details
            },
            client=virtual_network_client,
            get_fn=virtual_network_client.get_dhcp_options,
            get_param='dhcp_id',
            module=module)

    return result
Esempio n. 27
0
def create_certificates(certificate_details_dict):
    if certificate_details_dict is None:
        return None
    result_certificates = dict()
    attributes = ['ca_certificate', 'private_key', 'public_certificate']
    for key, value in six.iteritems(certificate_details_dict):
        certificate_details = CertificateDetails()
        certificate_name = value.get('certificate_name')
        if certificate_name is None:
            raise ClientError(
                Exception(
                    "certificate_name is mandatory and must not be empty for certificate creation"
                ))
        certificate_details.certificate_name = certificate_name
        certificate_details.passphrase = value.get('passphrase', None)
        for attribute in attributes:
            if value.get(attribute) is not None:
                certificate_details.__setattr__(
                    attribute, get_file_content(value.get(attribute, None)))
        result_certificates.update({key: certificate_details})
    return result_certificates
Esempio n. 28
0
def update_user(identity_client, existing_user, module):
    if existing_user is None:
        raise ClientError(Exception("No User with id " +
                                    module.params.get('user_id') + " is found for update"))
    groups = module.params['user_groups']
    reset_password = module.params['create_or_reset_ui_password']
    blocked = module.params['blocked']
    ui_password = None

    group_changed = modify_group_memberships(identity_client, groups, existing_user, module)
    existing_user, state_changed = unblock_user(identity_client, blocked, existing_user)
    ui_password, password_changed = reset_ui_password(identity_client, existing_user, reset_password)
    existing_user, description_tags_changed = update_user_description_and_tags(identity_client, existing_user, module)

    if not description_tags_changed:
        existing_user = to_dict(existing_user)
    if password_changed:
        existing_user.update({'password': ui_password})
    user_changed = description_tags_changed or group_changed \
        or password_changed or state_changed
    return user_changed, existing_user
def update_load_balancer(lb_client, module, load_balancer):
    if load_balancer is None:
        raise ClientError(
            Exception("No Load Balancer with id " +
                      module.params.get("load_balancer_id") +
                      " is found for update"))
    result = dict(load_balancer=to_dict(load_balancer), changed=False)
    name = module.params["display_name"]
    update_load_balancer_details = UpdateLoadBalancerDetails()
    if load_balancer.display_name.strip() != name.strip():
        get_logger().info(
            "Updating the display name of load balancer from %s to %s",
            load_balancer.display_name,
            name,
        )
        update_load_balancer_details.display_name = name
        result = oci_lb_utils.create_or_update_lb_resources_and_wait(
            resource_type="load_balancer",
            function=lb_client.update_load_balancer,
            kwargs_function={
                "update_load_balancer_details": update_load_balancer_details,
                "load_balancer_id": load_balancer.id,
            },
            lb_client=lb_client,
            get_fn=lb_client.get_load_balancer,
            kwargs_get={"load_balancer_id": load_balancer.id},
            module=module,
        )

        get_logger().info(
            "Successfully updated the display name of load balancer from %s to %s",
            load_balancer.display_name,
            name,
        )
    if not result["changed"]:
        get_logger().info(
            "Unable to update display name of load balancer as the new name is same as old"
        )
    return result
Esempio n. 30
0
def get_export_options(export_options):
    if export_options is None:
        return None
    HashedClientOptions = oci_utils.generate_subclass(ClientOptions)
    result_client_options = []
    for export_option_entry in export_options:
        client_options = HashedClientOptions()
        if export_option_entry.get("source") is None:
            raise ClientError(
                "Export Options attribute source must contain a valid value")
        client_options.source = export_option_entry.get("source")
        client_options.require_privileged_source_port = export_option_entry.get(
            "require_privileged_source_port", True)
        client_options.access = export_option_entry.get("access", "READ_ONLY")
        client_options.identity_squash = export_option_entry.get(
            "identity_squash", "ROOT")
        client_options.anonymous_uid = export_option_entry.get(
            "anonymous_uid", 65534)
        client_options.anonymous_gid = export_option_entry.get(
            "anonymous_gid", 65534)
        result_client_options.append(client_options)
    return result_client_options