mrs_plugin/services.py
def change_service(**kwargs):
    """Makes a given change to a MRS service

    Args:
        **kwargs: Additional options

    Keyword Args:
        service_id (int): The id of the service
        change_type (int): Type of change
        url_context_root (str): The context root for this service
        url_host_name (str): The host name for this service
        value (str): The value to be set as string or a dict if all are set
        session (object): The database session to use
        interactive (bool): Indicates whether to execute in interactive mode
        raise_exceptions (bool): If set to true exceptions are raised

    Returns:
        The result message as string
    """
    import json

    service_id = kwargs.get("service_id")

    change_type = kwargs.get("change_type")
    url_context_root = kwargs.get("url_context_root")
    url_host_name = kwargs.get("url_host_name")
    value = kwargs.get("value")

    session = kwargs.get("session")

    interactive = kwargs.get("interactive", core.get_interactive_default())
    raise_exceptions = kwargs.get("raise_exceptions", not interactive)

    try:
        session = core.get_current_session(session)

        # Make sure the MRS metadata schema exists and has the right version
        core.ensure_rds_metadata_schema(session)

        # List of services to be changed, initialized with service_id if given
        service_ids = [service_id] if service_id else []

        # Get the right service_id(s) if service_id is not given
        if not url_context_root and not service_id:
            # Check if there already is at least one service
            res = session.run_sql("""
                SELECT COUNT(*) AS service_count, MAX(id) AS id
                FROM `mysql_rest_service_metadata`.`service`
                """)
            row = res.fetch_one()
            service_count = row.get_field("service_count") if row else 0

            # If there is no service to change, error out.
            if service_count == 0:
                Exception("No service available.")
            # If there is exactly 1 service, use that one
            # elif service_count == 1:
            #    service_ids.append(row.get_field("id"))

            # If there are more services, let the user select one or all
            if interactive:
                allow_multi_select = (
                    change_type == SERVICE_DISABLE or
                    change_type == SERVICE_ENABLE or
                    change_type == SERVICE_DELETE)

                if allow_multi_select:
                    caption = ("Please select a service index, type "
                               "'hostname/root_context' or type '*' "
                               "to select all: ")
                else:
                    caption = ("Please select a service index or type "
                               "'hostname/root_context'")

                services = get_services(session=session, interactive=False)
                selection = core.prompt_for_list_item(
                    item_list=services,
                    prompt_caption=caption,
                    item_name_property="host_ctx",
                    given_value=None,
                    print_list=True,
                    allow_multi_select=allow_multi_select)
                if not selection or selection == "":
                    raise ValueError("Operation cancelled.")

                if allow_multi_select:
                    service_ids = [item["id"] for item in selection]
                else:
                    service_ids.append(selection["id"])

            # Lookup the service id
            res = session.run_sql(
                """
                SELECT se.id FROM `mysql_rest_service_metadata`.`service` se
                    LEFT JOIN `mysql_rest_service_metadata`.url_host h
                        ON se.url_host_id = h.id
                WHERE h.name = ? AND se.url_context_root = ?
                """,
                [url_host_name if url_host_name else "", url_context_root])
            row = res.fetch_one()
            if row:
                service_ids.append(row.get_field("id"))

        if len(service_ids) == 0:
            raise ValueError("The specified service was not found.")

        # Check the given value
        if interactive and not value:
            if change_type == SERVICE_SET_PROTOCOL:
                value = prompt_for_service_protocol()
            elif change_type == SERVICE_SET_COMMENTS:
                value = core.prompt_for_comments()

        if change_type == SERVICE_SET_PROTOCOL and not value:
            raise ValueError("No value given.")

        # Update all given services
        for service_id in service_ids:
            service = get_service(
                service_id=service_id, session=session, interactive=False,
                return_formatted=False)

            if change_type == SERVICE_SET_CONTEXT_ROOT:
                url_ctx_root = value
            elif change_type == SERVICE_SET_ALL:
                if type(value) == str: # TODO: Check why dicts cannot be used
                    value = json.loads(value)

                url_ctx_root = value.get("url_context_root")

            if (change_type == SERVICE_SET_CONTEXT_ROOT or
               change_type == SERVICE_SET_ALL):
                if interactive and not url_ctx_root:
                    url_ctx_root = prompt_for_url_context_root(
                        default=service.get('url_context_root'))

                # If the context root has changed, check if the new one is valid
                if service.get("url_context_root") != url_ctx_root:
                    if (not url_ctx_root or not url_ctx_root.startswith('/')):
                        raise ValueError(
                            "The url_context_root has to start with '/'.")

                    core.check_request_path(
                        url_ctx_root, session=session)

            params = [service_id]
            if change_type == SERVICE_DISABLE:
                sql = """
                    UPDATE `mysql_rest_service_metadata`.`service`
                    SET enabled = FALSE
                    WHERE id = ?
                    """
            elif change_type == SERVICE_ENABLE:
                sql = """
                    UPDATE `mysql_rest_service_metadata`.`service`
                    SET enabled = TRUE
                    WHERE id = ?
                    """
            elif change_type == SERVICE_DELETE:
                sql = """
                    DELETE FROM `mysql_rest_service_metadata`.`service`
                    WHERE id = ?
                    """
            elif change_type == SERVICE_SET_DEFAULT:
                res = session.run_sql("""
                    UPDATE `mysql_rest_service_metadata`.`service`
                    SET is_default = FALSE
                    """)
                sql = """
                    UPDATE `mysql_rest_service_metadata`.`service`
                    SET is_default = TRUE
                    WHERE id = ?
                    """
            elif change_type == SERVICE_SET_CONTEXT_ROOT:
                sql = """
                    UPDATE `mysql_rest_service_metadata`.`service`
                    SET url_context_root = ?
                    WHERE id = ?
                    """
                params.insert(0, url_ctx_root)
            elif change_type == SERVICE_SET_PROTOCOL:
                sql = """
                    UPDATE `mysql_rest_service_metadata`.`service`
                    SET url_protocol = ?
                    WHERE id = ?
                    """
                params.insert(0, value)
            elif change_type == SERVICE_SET_COMMENTS:
                sql = """
                    UPDATE `mysql_rest_service_metadata`.`service`
                    SET comments = ?
                    WHERE id = ?
                    """
                params.insert(0, value)
            elif change_type == SERVICE_SET_ALL:
                sql = """
                    UPDATE `mysql_rest_service_metadata`.`service`
                    SET enabled = ?,
                        url_context_root = ?,
                        url_protocol = ?,
                        comments = ?,
                        is_default = ?
                    WHERE id = ?
                    """
                if str(value.get("is_default")).lower() == "true":
                    res = session.run_sql("""
                        UPDATE `mysql_rest_service_metadata`.`service`
                        SET is_default = FALSE
                        """)

                params.insert(
                    0, (str(value.get("enabled")).lower() == "true" or
                    str(value.get("enabled")) == "1"))
                params.insert(1, url_ctx_root)
                params.insert(2, value.get("url_protocol", ""))
                params.insert(3, value.get("comments", ""))
                params.insert(
                    4, (str(value.get("is_default")).lower() == "true" or
                    str(value.get("is_default")) == "1"))
            else:
                raise Exception("Operation not supported")

            res = session.run_sql(sql, params)
            if res.get_affected_row_count() == 0:
                raise Exception(
                    f"The specified service with id {service_id} was not "
                    "found.")

        if change_type == SERVICE_SET_DEFAULT:
            return "The service has been made the default."

        if len(service_ids) == 1:
            msg = "The service has been "
        else:
            msg = "The services have been "

        if change_type == SERVICE_DISABLE:
            msg += "disabled."
        elif change_type == SERVICE_ENABLE:
            msg += "enabled."
        elif change_type == SERVICE_DELETE:
            msg += "deleted."
        else:
            msg += "updated."

        return msg

    except Exception as e:
        if raise_exceptions:
            raise
        else:
            print(f"Error: {str(e)}")
Makes a given change to a MRS service

    Args:
        **kwargs: Additional options

    Keyword Args:
        service_id (int): The id of the service
        change_type (int): Type of change
        url_context_root (str): The context root for this service
        url_host_name (str): The host name for this service
        value (str): The value to be set as string or a dict if all are set
        session (object): The database session to use
        interactive (bool): Indicates whether to execute in interactive mode
        raise_exceptions (bool): If set to true exceptions are raised

    Returns:
        The result message as string
    
Makes a given change to a MRS service
Makes a given change to a MRS service
def change_service(**kwargs):
    import json
    service_id = kwargs.get("service_id")
    change_type = kwargs.get("change_type")
    url_context_root = kwargs.get("url_context_root")
    url_host_name = kwargs.get("url_host_name")
    value = kwargs.get("value")
    session = kwargs.get("session")
    interactive = kwargs.get("interactive", core.get_interactive_default())
    raise_exceptions = kwargs.get("raise_exceptions", not interactive)
    try:
        session = core.get_current_session(session)
        core.ensure_rds_metadata_schema(session)
        service_ids = [service_id] if service_id else []
        if not url_context_root and not service_id:
            res = session.run_sql("""
                SELECT COUNT(*) AS service_count, MAX(id) AS id
                FROM `mysql_rest_service_metadata`.`service`
                """)
            row = res.fetch_one()
            service_count = row.get_field("service_count") if row else 0
            if service_count == 0:
                Exception("No service available.")
            if interactive:
                allow_multi_select = (
                    change_type == SERVICE_DISABLE or
                    change_type == SERVICE_ENABLE or
                    change_type == SERVICE_DELETE)
                if allow_multi_select:
                    caption = ("Please select a service index, type "
                               "'hostname/root_context' or type '*' "
                               "to select all: ")
                else:
                    caption = ("Please select a service index or type "
                               "'hostname/root_context'")
                services = get_services(session=session, interactive=False)
                selection = core.prompt_for_list_item(
                    item_list=services,
                    prompt_caption=caption,
                    item_name_property="host_ctx",
                    given_value=None,
                    print_list=True,
                    allow_multi_select=allow_multi_select)
                if not selection or selection == "":
                    raise ValueError("Operation cancelled.")
                if allow_multi_select:
                    service_ids = [item["id"] for item in selection]
                else:
                    service_ids.append(selection["id"])
            res = session.run_sql(
                """
                SELECT se.id FROM `mysql_rest_service_metadata`.`service` se
                    LEFT JOIN `mysql_rest_service_metadata`.url_host h
                        ON se.url_host_id = h.id
                WHERE h.name = ? AND se.url_context_root = ?
                """,
                [url_host_name if url_host_name else "", url_context_root])
            row = res.fetch_one()
            if row:
                service_ids.append(row.get_field("id"))
        if len(service_ids) == 0:
            raise ValueError("The specified service was not found.")
        if interactive and not value:
            if change_type == SERVICE_SET_PROTOCOL:
                value = prompt_for_service_protocol()
            elif change_type == SERVICE_SET_COMMENTS:
                value = core.prompt_for_comments()
        if change_type == SERVICE_SET_PROTOCOL and not value:
            raise ValueError("No value given.")
        for service_id in service_ids:
            service = get_service(
                service_id=service_id, session=session, interactive=False,
                return_formatted=False)
            if change_type == SERVICE_SET_CONTEXT_ROOT:
                url_ctx_root = value
            elif change_type == SERVICE_SET_ALL:
                if type(value) == str: 
                    value = json.loads(value)
                url_ctx_root = value.get("url_context_root")
            if (change_type == SERVICE_SET_CONTEXT_ROOT or
               change_type == SERVICE_SET_ALL):
                if interactive and not url_ctx_root:
                    url_ctx_root = prompt_for_url_context_root(
                        default=service.get('url_context_root'))
                if service.get("url_context_root") != url_ctx_root:
                    if (not url_ctx_root or not url_ctx_root.startswith('/')):
                        raise ValueError(
                            "The url_context_root has to start with '/'.")
                    core.check_request_path(
                        url_ctx_root, session=session)
            params = [service_id]
            if change_type == SERVICE_DISABLE:
                sql = """
                    UPDATE `mysql_rest_service_metadata`.`service`
                    SET enabled = FALSE
                    WHERE id = ?
                    """
            elif change_type == SERVICE_ENABLE:
                sql = """
                    UPDATE `mysql_rest_service_metadata`.`service`
                    SET enabled = TRUE
                    WHERE id = ?
                    """
            elif change_type == SERVICE_DELETE:
                sql = """
                    DELETE FROM `mysql_rest_service_metadata`.`service`
                    WHERE id = ?
                    """
            elif change_type == SERVICE_SET_DEFAULT:
                res = session.run_sql("""
                    UPDATE `mysql_rest_service_metadata`.`service`
                    SET is_default = FALSE
                    """)
                sql = """
                    UPDATE `mysql_rest_service_metadata`.`service`
                    SET is_default = TRUE
                    WHERE id = ?
                    """
            elif change_type == SERVICE_SET_CONTEXT_ROOT:
                sql = """
                    UPDATE `mysql_rest_service_metadata`.`service`
                    SET url_context_root = ?
                    WHERE id = ?
                    """
                params.insert(0, url_ctx_root)
            elif change_type == SERVICE_SET_PROTOCOL:
                sql = """
                    UPDATE `mysql_rest_service_metadata`.`service`
                    SET url_protocol = ?
                    WHERE id = ?
                    """
                params.insert(0, value)
            elif change_type == SERVICE_SET_COMMENTS:
                sql = """
                    UPDATE `mysql_rest_service_metadata`.`service`
                    SET comments = ?
                    WHERE id = ?
                    """
                params.insert(0, value)
            elif change_type == SERVICE_SET_ALL:
                sql = """
                    UPDATE `mysql_rest_service_metadata`.`service`
                    SET enabled = ?,
                        url_context_root = ?,
                        url_protocol = ?,
                        comments = ?,
                        is_default = ?
                    WHERE id = ?
                    """
                if str(value.get("is_default")).lower() == "true":
                    res = session.run_sql("""
                        UPDATE `mysql_rest_service_metadata`.`service`
                        SET is_default = FALSE
                        """)
                params.insert(
                    0, (str(value.get("enabled")).lower() == "true" or
                    str(value.get("enabled")) == "1"))
                params.insert(1, url_ctx_root)
                params.insert(2, value.get("url_protocol", ""))
                params.insert(3, value.get("comments", ""))
                params.insert(
                    4, (str(value.get("is_default")).lower() == "true" or
                    str(value.get("is_default")) == "1"))
            else:
                raise Exception("Operation not supported")
            res = session.run_sql(sql, params)
            if res.get_affected_row_count() == 0:
                raise Exception(
                    f"The specified service with id {service_id} was not "
                    "found.")
        if change_type == SERVICE_SET_DEFAULT:
            return "The service has been made the default."
        if len(service_ids) == 1:
            msg = "The service has been "
        else:
            msg = "The services have been "
        if change_type == SERVICE_DISABLE:
            msg += "disabled."
        elif change_type == SERVICE_ENABLE:
            msg += "enabled."
        elif change_type == SERVICE_DELETE:
            msg += "deleted."
        else:
            msg += "updated."
        return msg
    except Exception as e:
        if raise_exceptions:
            raise
        else:
            print(f"Error: {str(e)}")
def change_service ( ** kwargs ) : import json service_id = kwargs . get ( "service_id" ) change_type = kwargs . get ( "change_type" ) url_context_root = kwargs . get ( "url_context_root" ) url_host_name = kwargs . get ( "url_host_name" ) value = kwargs . get ( "value" ) session = kwargs . get ( "session" ) interactive = kwargs . get ( "interactive" , core . get_interactive_default ( ) ) raise_exceptions = kwargs . get ( "raise_exceptions" , not interactive ) try : session = core . get_current_session ( session ) core . ensure_rds_metadata_schema ( session ) service_ids = [ service_id ] if service_id else [ ] if not url_context_root and not service_id : res = session . run_sql ( """
                SELECT COUNT(*) AS service_count, MAX(id) AS id
                FROM `mysql_rest_service_metadata`.`service`
                """ ) row = res . fetch_one ( ) service_count = row . get_field ( "service_count" ) if row else 0 if service_count == 0 : Exception ( "No service available." ) if interactive : allow_multi_select = ( change_type == SERVICE_DISABLE or change_type == SERVICE_ENABLE or change_type == SERVICE_DELETE ) if allow_multi_select : caption = ( "Please select a service index, type " "'hostname/root_context' or type '*' " "to select all: " ) else : caption = ( "Please select a service index or type " "'hostname/root_context'" ) services = get_services ( session = session , interactive = False ) selection = core . prompt_for_list_item ( item_list = services , prompt_caption = caption , item_name_property = "host_ctx" , given_value = None , print_list = True , allow_multi_select = allow_multi_select ) if not selection or selection == "" : raise ValueError ( "Operation cancelled." ) if allow_multi_select : service_ids = [ item [ "id" ] for item in selection ] else : service_ids . append ( selection [ "id" ] ) res = session . run_sql ( """
                SELECT se.id FROM `mysql_rest_service_metadata`.`service` se
                    LEFT JOIN `mysql_rest_service_metadata`.url_host h
                        ON se.url_host_id = h.id
                WHERE h.name = ? AND se.url_context_root = ?
                """ , [ url_host_name if url_host_name else "" , url_context_root ] ) row = res . fetch_one ( ) if row : service_ids . append ( row . get_field ( "id" ) ) if len ( service_ids ) == 0 : raise ValueError ( "The specified service was not found." ) if interactive and not value : if change_type == SERVICE_SET_PROTOCOL : value = prompt_for_service_protocol ( ) elif change_type == SERVICE_SET_COMMENTS : value = core . prompt_for_comments ( ) if change_type == SERVICE_SET_PROTOCOL and not value : raise ValueError ( "No value given." ) for service_id in service_ids : service = get_service ( service_id = service_id , session = session , interactive = False , return_formatted = False ) if change_type == SERVICE_SET_CONTEXT_ROOT : url_ctx_root = value elif change_type == SERVICE_SET_ALL : if type ( value ) == str : value = json . loads ( value ) url_ctx_root = value . get ( "url_context_root" ) if ( change_type == SERVICE_SET_CONTEXT_ROOT or change_type == SERVICE_SET_ALL ) : if interactive and not url_ctx_root : url_ctx_root = prompt_for_url_context_root ( default = service . get ( 'url_context_root' ) ) if service . get ( "url_context_root" ) != url_ctx_root : if ( not url_ctx_root or not url_ctx_root . startswith ( '/' ) ) : raise ValueError ( "The url_context_root has to start with '/'." ) core . check_request_path ( url_ctx_root , session = session ) params = [ service_id ] if change_type == SERVICE_DISABLE : sql = """
                    UPDATE `mysql_rest_service_metadata`.`service`
                    SET enabled = FALSE
                    WHERE id = ?
                    """ elif change_type == SERVICE_ENABLE : sql = """
                    UPDATE `mysql_rest_service_metadata`.`service`
                    SET enabled = TRUE
                    WHERE id = ?
                    """ elif change_type == SERVICE_DELETE : sql = """
                    DELETE FROM `mysql_rest_service_metadata`.`service`
                    WHERE id = ?
                    """ elif change_type == SERVICE_SET_DEFAULT : res = session . run_sql ( """
                    UPDATE `mysql_rest_service_metadata`.`service`
                    SET is_default = FALSE
                    """ ) sql = """
                    UPDATE `mysql_rest_service_metadata`.`service`
                    SET is_default = TRUE
                    WHERE id = ?
                    """ elif change_type == SERVICE_SET_CONTEXT_ROOT : sql = """
                    UPDATE `mysql_rest_service_metadata`.`service`
                    SET url_context_root = ?
                    WHERE id = ?
                    """ params . insert ( 0 , url_ctx_root ) elif change_type == SERVICE_SET_PROTOCOL : sql = """
                    UPDATE `mysql_rest_service_metadata`.`service`
                    SET url_protocol = ?
                    WHERE id = ?
                    """ params . insert ( 0 , value ) elif change_type == SERVICE_SET_COMMENTS : sql = """
                    UPDATE `mysql_rest_service_metadata`.`service`
                    SET comments = ?
                    WHERE id = ?
                    """ params . insert ( 0 , value ) elif change_type == SERVICE_SET_ALL : sql = """
                    UPDATE `mysql_rest_service_metadata`.`service`
                    SET enabled = ?,
                        url_context_root = ?,
                        url_protocol = ?,
                        comments = ?,
                        is_default = ?
                    WHERE id = ?
                    """ if str ( value . get ( "is_default" ) ) . lower ( ) == "true" : res = session . run_sql ( """
                        UPDATE `mysql_rest_service_metadata`.`service`
                        SET is_default = FALSE
                        """ ) params . insert ( 0 , ( str ( value . get ( "enabled" ) ) . lower ( ) == "true" or str ( value . get ( "enabled" ) ) == "1" ) ) params . insert ( 1 , url_ctx_root ) params . insert ( 2 , value . get ( "url_protocol" , "" ) ) params . insert ( 3 , value . get ( "comments" , "" ) ) params . insert ( 4 , ( str ( value . get ( "is_default" ) ) . lower ( ) == "true" or str ( value . get ( "is_default" ) ) == "1" ) ) else : raise Exception ( "Operation not supported" ) res = session . run_sql ( sql , params ) if res . get_affected_row_count ( ) == 0 : raise Exception ( f"The specified service with id {service_id} was not " "found." ) if change_type == SERVICE_SET_DEFAULT : return "The service has been made the default." if len ( service_ids ) == 1 : msg = "The service has been " else : msg = "The services have been " if change_type == SERVICE_DISABLE : msg += "disabled." elif change_type == SERVICE_ENABLE : msg += "enabled." elif change_type == SERVICE_DELETE : msg += "deleted." else : msg += "updated." return msg except Exception as e : if raise_exceptions : raise else : print ( f"Error: {str(e)}" )
Makes a given change to a MRS service
Makes a given change to a MRS service
"""Makes a given change to a MRS service

    Args:
        **kwargs: Additional options

    Keyword Args:
        service_id (int): The id of the service
        change_type (int): Type of change
        url_context_root (str): The context root for this service
        url_host_name (str): The host name for this service
        value (str): The value to be set as string or a dict if all are set
        session (object): The database session to use
        interactive (bool): Indicates whether to execute in interactive mode
        raise_exceptions (bool): If set to true exceptions are raised

    Returns:
        The result message as string
    """ # Make sure the MRS metadata schema exists and has the right version # List of services to be changed, initialized with service_id if given # Get the right service_id(s) if service_id is not given # Check if there already is at least one service # If there is no service to change, error out. # If there is exactly 1 service, use that one # elif service_count == 1: #    service_ids.append(row.get_field("id")) # If there are more services, let the user select one or all # Lookup the service id # Check the given value # Update all given services # TODO: Check why dicts cannot be used # If the context root has changed, check if the new one is valid
The result message as string
The result message as string
**kwargs
None