Skip to content

fmgbase

FMGBase connection

logger module-attribute #

logger = logging.getLogger(__name__)

FMGBase #

FMGBase(settings: Optional[FMGSettings] = None, **kwargs)

Fortimanager connection class

This can be used as a connection handler for the FortiManager. It maintains state of operation and provides functions to communicate with the FMG.

Attributes:

Name Type Description
lock FMGLockContext

Workspace lock handler

Examples:

Possible arguments to initialize: FMGSettings

Using as context manager#
>>> settings = {...}
>>> with FMGBase(**settings) as conn:
...     print(conn.get_version())
Using as function:#
>>> from pyfortinet.exceptions import FMGException
>>> settings = {...}
>>> conn = FMGBase(**settings)
>>> try:
...     conn.open()
...     print(conn.get_version())
... except FMGException as err:
...     print(f"Error: {err}")
... finally:
...     conn.close()

Parameters:

Name Type Description Default
settings Settings

FortiManager settings

None

Other Parameters:

Name Type Description
base_url str

Base URL to access FMG (e.g.: https://myfmg)

username str

User to authenticate

password str

Password for authentication

adom str

ADOM to use for this connection

verify bool

Verify SSL certificate (REQUESTS_CA_BUNDLE can set accepted CA cert)

timeout float

Connect/read inactivity timeout per transport attempt, in seconds

raise_on_error bool

Raise exception on error

discard_on_close bool

Discard changes after connection close (workspace mode)

discard_on_error bool

Discard changes when exception occurs (workspace mode)

Source code in pyfortinet/fmg_api/fmgbase.py
def __init__(self, settings: Optional[FMGSettings] = None, **kwargs):
    """Initializes FMGBase

    Args:
        settings (Settings): FortiManager settings

    Keyword Args:
        base_url (str): Base URL to access FMG (e.g.: https://myfmg)
        username (str): User to authenticate
        password (str): Password for authentication
        adom (str): ADOM to use for this connection
        verify (bool): Verify SSL certificate (REQUESTS_CA_BUNDLE can set accepted CA cert)
        timeout (float): Connect/read inactivity timeout per transport attempt, in seconds
        raise_on_error (bool): Raise exception on error
        discard_on_close (bool): Discard changes after connection close (workspace mode)
        discard_on_error (bool): Discard changes when exception occurs (workspace mode)
    """
    if not settings:
        settings = FMGSettings(**kwargs)
    self._settings = settings
    self._token: Optional[SecretStr] = None
    self._session: Optional[requests.Session] = None
    self.lock = FMGLockContext(self)
    self._raise_on_error: bool = settings.raise_on_error
    self._id: int = randint(1, 256)  # pick a random id for this session (check logs for a particular session)

adom property writable #

adom: str

Returns current selected adom

discard_on_close property writable #

discard_on_close: bool

Returns discard_on_close value

raise_on_error property writable #

raise_on_error

Returns raise_on_error value

add #

add(request: Union[dict[str, Any], List[dict[str, Any]]]) -> FMGResponse

Add operation

Notes

Multiple requests in one call is supported

Parameters:

Name Type Description Default
request Union[dict[str, Any], List[dict[str, Any]]]

Add operation's data structure

required

Examples:

>>> settings = {...}
>>> address_request = {
...     "url": "/pm/config/global/obj/firewall/address",
...     "data": {
...         "name": "test-address",
...         "associated-interface": "inside",
...         "obj-type": "ip",
...         "type": "ipmask",
...         "start-ip": "10.0.0.1/24"
...     }
... }
>>> with FMGBase(**settings) as fmg:
...     fmg.add(address_request)

Returns:

Type Description
FMGResponse

Result of operation

Source code in pyfortinet/fmg_api/fmgbase.py
@error_handling
@auth_required
@lock
def add(self, request: Union[dict[str, Any], List[dict[str, Any]]]) -> FMGResponse:
    """Add operation

    Notes:
        Multiple requests in one call is supported

    Args:
        request: Add operation's data structure

    Examples:
        ```pycon

        >>> settings = {...}
        >>> address_request = {
        ...     "url": "/pm/config/global/obj/firewall/address",
        ...     "data": {
        ...         "name": "test-address",
        ...         "associated-interface": "inside",
        ...         "obj-type": "ip",
        ...         "type": "ipmask",
        ...         "start-ip": "10.0.0.1/24"
        ...     }
        ... }
        >>> with FMGBase(**settings) as fmg:
        ...     fmg.add(address_request)
        ```

    Returns:
        (FMGResponse): Result of operation
    """
    response = FMGResponse(fmg=self)
    request = prepare_batch(request)
    body = {
        "method": "add",
        "params": [
            {
                "data": req.get("data"),
                "url": req.get("url"),
            }
            for req in request
        ],
        "session": self._token.get_secret_value(),
        "id": self._id,
    }
    api_result = self._post(request=body)
    if isinstance(api_result, dict):
        api_result = [api_result]
    response.success = all(result.get("status", {}).get("code") == 0 for result in api_result)
    response.data = api_result
    return response

clone #

clone(request: Union[dict[str, Any], List[dict[str, Any]]], create_task: bool = False) -> FMGResponse

Clone operation

Notes

Multiple requests in one call is supported

Parameters:

Name Type Description Default
request dict

Clone operation's data structure

required
create_task bool

Wheter to create task

False

Examples:

>>> settings = {...}
>>> clone_request = {
...     "url": "/pm/config/global/obj/firewall/address/test-address",  # source object
...     "data": {
....         "name": "clone-address",  # destination object
...     }
... }
>>> with FMGBase(**settings) as fmg:
...     fmg.clone(clone_request)

Returns:

Type Description
FMGResponse

Result of operation

Source code in pyfortinet/fmg_api/fmgbase.py
@error_handling
@auth_required
@lock
def clone(self, request: Union[dict[str, Any], List[dict[str, Any]]], create_task: bool = False) -> FMGResponse:
    """Clone operation

    Notes:
        Multiple requests in one call is supported

    Args:
        request (dict): Clone operation's data structure
        create_task (bool): Wheter to create task

    Examples:
        ```pycon

        >>> settings = {...}
        >>> clone_request = {
        ...     "url": "/pm/config/global/obj/firewall/address/test-address",  # source object
        ...     "data": {
        ....         "name": "clone-address",  # destination object
        ...     }
        ... }
        >>> with FMGBase(**settings) as fmg:
        ...     fmg.clone(clone_request)
        ```

    Returns:
        (FMGResponse): Result of operation
    """
    response = FMGResponse(fmg=self)
    request = prepare_batch(request)
    body = {
        "method": "clone",
        "params": [
            {
                "url": req.get("url"),
                "data": req.get("data"),
            }
            for req in request
        ],
        "session": self._token.get_secret_value(),
        "id": self._id,
    }
    adom = self.adom if self.adom != "global" else "root"
    if create_task:
        body["create_task"] = {
            "adom": adom,
            # name task after this request object
            "name": f"cloning task of {', '.join(req.get('url').split('/')[-1] for req in request)}",
        }
    api_result = self._post(request=body)
    if isinstance(api_result, dict):
        api_result = [api_result]
    response.success = all(result.get("status", {}).get("code") == 0 for result in api_result)
    response.data = api_result
    return response

close #

close(discard_changes: bool = False)

close connection

Source code in pyfortinet/fmg_api/fmgbase.py
def close(self, discard_changes: bool = False):
    """close connection"""
    session = self._session
    workspace_error = None
    try:
        if session is None or self._token is None:
            return
        request = {
            "id": self._id,
            "method": "exec",
            "params": [{"url": "/sys/logout"}],
            "session": self._token.get_secret_value(),
        }
        if self.lock.locked_adoms or self.lock.uses_workspace:
            if not (self.discard_on_close or discard_changes):
                try:
                    responses = self.lock.commit_changes()
                    if any(not response.success for response in responses):
                        raise FMGLockException("Failed to commit workspace changes")
                except FMGException as err:
                    workspace_error = err
                    logger.exception("Failed to commit workspace changes")
            try:
                self.lock.unlock_adoms()
            except FMGException as err:
                workspace_error = workspace_error or err
                logger.exception("Failed to unlock workspaces")
        payload = request_json(session, self._settings, request)
        status = payload.get("result", [{}])[0].get("status", {})
        if status.get("code") != 0:
            logger.warning("Logout failed!")
    except requests.exceptions.ConnectionError:
        logger.warning("Logout failed!")
    except (FMGException, requests.RequestException):
        if workspace_error is None:
            raise
        logger.exception("Logout failed after workspace cleanup failed")
    finally:
        try:
            if session is not None:
                session.close()
        finally:
            self._session = None
            self._token = None
            self.lock.locked_adoms.clear()
            self.lock._uses_workspace = None
            self.lock._uses_adoms = None
        logger.debug("Closed session")
    if workspace_error is not None:
        raise workspace_error

delete #

delete(request: Union[dict[str, Any], List[dict[str, Any]]]) -> FMGResponse

Delete operation

Notes

Multiple requests in one call is supported

Parameters:

Name Type Description Default
request Union[dict[str, Any], List[dict[str, Any]]]

Delete operation's data structure

required

Examples:

>>> settings = {...}
>>> address_request = {
...     "url": "/pm/config/global/obj/firewall/address/test-address",
... }
>>> with FMGBase(**settings) as fmg:
...     fmg.delete(address_request)

Returns:

Type Description
FMGResponse

Result of operation

Source code in pyfortinet/fmg_api/fmgbase.py
@error_handling
@auth_required
@lock
def delete(self, request: Union[dict[str, Any], List[dict[str, Any]]]) -> FMGResponse:
    """Delete operation

    Notes:
        Multiple requests in one call is supported

    Args:
        request: Delete operation's data structure

    Examples:
        ```pycon

        >>> settings = {...}
        >>> address_request = {
        ...     "url": "/pm/config/global/obj/firewall/address/test-address",
        ... }
        >>> with FMGBase(**settings) as fmg:
        ...     fmg.delete(address_request)
        ```

    Returns:
        (FMGResponse): Result of operation
    """
    response = FMGResponse(fmg=self)
    request = prepare_batch(request)
    body = {
        "method": "delete",
        "params": [
            {
                "url": req.get("url"),
                **({"data": req["data"]} if "data" in req else {}),
            }
            for req in request
        ],
        "session": self._token.get_secret_value(),
        "id": self._id,
    }
    api_result = self._post(request=body)
    if isinstance(api_result, dict):
        api_result = [api_result]
    response.success = all(result.get("status", {}).get("code") == 0 for result in api_result)
    response.data = api_result
    return response

exec #

exec(request: dict[str, str]) -> FMGResponse

Execute on FMG

This method currently does not support multiple requests in one call!

Source code in pyfortinet/fmg_api/fmgbase.py
@error_handling
@auth_required
@lock
def exec(self, request: dict[str, str]) -> FMGResponse:
    """Execute on FMG

    This method currently does not support multiple requests in one call!
    """
    logger.info("requesting exec with low-level op to %s", request.get("url"))
    body = {
        "method": "exec",
        "params": [
            {
                "data": request.get("data"),
                "url": request.get("url"),
            }
        ],
        "session": self._token.get_secret_value(),
        "id": self._id,
    }
    api_result = self._post(request=body)
    if isinstance(api_result, dict):
        api_result = [api_result]
    result = FMGResponse(fmg=self, data=api_result, success=api_result[0].get("status", {}).get("code") == 0)
    return result

get #

get(request: dict[str, Any]) -> FMGResponse

Get info from FMG

This method currently does not support multiple requests in one call!

Parameters:

Name Type Description Default
request dict[str, Any]

Get operation's param structure

required

Examples:

>>> address_request = {
...    "url": "/pm/config/global/obj/firewall/address",
...    "filter": [ ["name", "==", "test-address"] ],
...    "fields": [ "name", "subnet" ]
... }
>>> settings = {...}
>>> with FMGBase(**settings) as fmg:
...    fmg.get(address_request)

Returns:

Type Description
FMGResponse

response object with data

Source code in pyfortinet/fmg_api/fmgbase.py
@error_handling
@auth_required
def get(self, request: dict[str, Any]) -> FMGResponse:  # noqa: PLR0912 - Too many branches
    """Get info from FMG

    This method currently does not support multiple requests in one call!

    Args:
        request: Get operation's param structure

    Examples:
        ```pycon

        >>> address_request = {
        ...    "url": "/pm/config/global/obj/firewall/address",
        ...    "filter": [ ["name", "==", "test-address"] ],
        ...    "fields": [ "name", "subnet" ]
        ... }
        >>> settings = {...}
        >>> with FMGBase(**settings) as fmg:
        ...    fmg.get(address_request)
        ```

    Returns:
        (FMGResponse): response object with data
    """
    body = {
        "method": "get",
        "params": [request],
        "verbose": 1,  # get string values instead of numeric
        "session": self._token.get_secret_value(),
        "id": self._id,
    }
    result = FMGResponse(fmg=self)
    try:
        api_result = self._post(request=body)
    except FMGObjectNotExistException:
        # handling when specific requested object doesn't exist
        # we don't error out, but give an empty list
        result.data = [{"data": [], "status": {"code": 0}}]
        result.success = True
        return result

    # handling empty result list
    if not api_result:
        result.data = [{"data": [], "status": {"code": 0}}]
        result.success = True
        return result

    # processing result list
    result.data = api_result if isinstance(api_result, list) else [api_result]
    result.success = True
    # result.status = api_result.get("status", {}).get("code", 400)

    return result

get_version #

get_version() -> str

Gather FMG version

Source code in pyfortinet/fmg_api/fmgbase.py
@error_handling
@auth_required
def get_version(self) -> str:
    """Gather FMG version"""
    request = {
        "method": "get",
        "params": [{"url": "/sys/status"}],
        "id": self._id,
        "session": self._token.get_secret_value(),
    }
    req = self._post(request)
    return req["data"]["Version"]

lock_adom #

lock_adom(adom: Optional[str] = None, keep_locked: bool = False)

Locks specified ADOM explicitly

The usual error based locking not always work. For example FMG replies authentication error while running a job to create new Device in device database. This makes error handling unusable and therefore this context manager can be used to lock ADOM for the job run duration.

If adom was already locked, this function won't lock it again and won't unlock it either.

Parameters:

Name Type Description Default
adom Optional[str]

ADOM to be locked as string. If not specified, currently used ADOM will be used.

None
keep_locked bool

If True, the lock is not released after operation. (default: False)

False

Yields:

Type Description
str

adom name (not used normally)

Source code in pyfortinet/fmg_api/fmgbase.py
@contextmanager
def lock_adom(self, adom: Optional[str] = None, keep_locked: bool = False):
    """Locks specified ADOM explicitly

    The usual error based locking not always work. For example FMG replies authentication error while running
    a job to create new Device in device database. This makes error handling unusable and therefore this
    context manager can be used to lock ADOM for the job run duration.

    If adom was already locked, this function won't lock it again and won't unlock it either.

    Args:
        adom: ADOM to be locked as string. If not specified, currently used ADOM will be used.
        keep_locked: If True, the lock is not released after operation. (default: False)

    Yields:
        (str): adom name (not used normally)
    """
    if not adom:
        adom = self.adom
    if not adom:
        raise ValueError("ADOM must be specified!")
    self.lock.check_mode(adom)
    did_lock = False
    if self.lock.uses_workspace and adom not in self.lock.locked_adoms:
        self.lock.lock_adoms(adom)
        did_lock = True
    try:
        yield adom
    finally:
        if did_lock and not keep_locked:
            self.lock.unlock_adoms(adom)

open #

open() -> FMGBase

open connection

Source code in pyfortinet/fmg_api/fmgbase.py
def open(self) -> "FMGBase":
    """open connection"""
    # TODO: token and cloud auth
    # https://how-to-fortimanager-api.readthedocs.io/en/latest/001_fmg_json_api_introduction.html#token-based-authentication
    if self._session is not None and self._token is not None:
        return self
    logger.debug("Initializing connection to %s with id: %s", self._settings.base_url, self._id)
    self._session = requests.Session()
    try:
        self._token = self._get_token()
    except BaseException:
        session, self._session = self._session, None
        self._token = None
        session.close()
        raise
    return self

set #

set(request: Union[dict[str, Any], List[dict[str, Any]]]) -> FMGResponse

Set operation

Notes

Multiple requests in one call is supported

Parameters:

Name Type Description Default
request Union[dict[str, Any], List[dict[str, Any]]]

Set operation's data structure

required

Examples:

>>> settings = {...}
>>> address_request = {
...     "url": "/pm/config/global/obj/firewall/address",
...     "data": {
...         "name": "test-address",
...         "associated-interface": "inside",
...         "obj-type": "ip",
...         "type": "ipmask",
...         "start-ip": "10.0.0.1/24"
...     }
... }
>>> with FMGBase(**settings) as fmg:
>>>     fmg.set(address_request)

Returns:

Type Description
FMGResponse

Result of operation

Source code in pyfortinet/fmg_api/fmgbase.py
@error_handling
@auth_required
@lock
def set(self, request: Union[dict[str, Any], List[dict[str, Any]]]) -> FMGResponse:
    """Set operation

    Notes:
        Multiple requests in one call is supported

    Args:
        request: Set operation's data structure

    Examples:
        ```pycon

        >>> settings = {...}
        >>> address_request = {
        ...     "url": "/pm/config/global/obj/firewall/address",
        ...     "data": {
        ...         "name": "test-address",
        ...         "associated-interface": "inside",
        ...         "obj-type": "ip",
        ...         "type": "ipmask",
        ...         "start-ip": "10.0.0.1/24"
        ...     }
        ... }
        >>> with FMGBase(**settings) as fmg:
        >>>     fmg.set(address_request)
        ```

    Returns:
        (FMGResponse): Result of operation
    """
    response = FMGResponse(fmg=self)
    request = prepare_batch(request)
    body = {
        "method": "set",
        "params": [
            {
                "data": req.get("data"),
                "url": req.get("url"),
            }
            for req in request
        ],
        "session": self._token.get_secret_value(),
        "id": self._id,
    }
    api_result = self._post(request=body)
    if isinstance(api_result, dict):
        api_result = [api_result]
    response.success = all(result.get("status", {}).get("code") == 0 for result in api_result)
    response.data = api_result
    return response

unset #

unset(request: Union[dict[str, Any], list[dict[str, Any]]]) -> FMGResponse

Unset the tables identified by low-level request dictionaries.

Source code in pyfortinet/fmg_api/fmgbase.py
@error_handling
@auth_required
@lock
def unset(self, request: Union[dict[str, Any], list[dict[str, Any]]]) -> FMGResponse:
    """Unset the tables identified by low-level request dictionaries."""
    request = prepare_batch(request)
    body = {
        "method": "unset",
        "params": [{"url": req.get("url")} for req in request],
        "session": self._token.get_secret_value(),
        "id": self._id,
    }
    api_result = self._post(request=body)
    if isinstance(api_result, dict):
        api_result = [api_result]
    return FMGResponse(
        fmg=self,
        success=all(result.get("status", {}).get("code") == 0 for result in api_result),
        data=api_result,
    )

update #

update(request: Union[dict[str, Any], List[dict[str, Any]]]) -> FMGResponse

Update operation

Notes

Multiple requests in one call is supported

Parameters:

Name Type Description Default
request Union[dict[str, Any], List[dict[str, Any]]]

Update operation's data structure

required

Examples:

>>> settings = {...}
>>> address_request = {
...     "url": "/pm/config/global/obj/firewall/address",
...     "data": {
...         "name": "test-address",
...         "associated-interface": "inside",
...         "obj-type": "ip",
...         "type": "ipmask",
...         "start-ip": "10.0.0.1/24"
...     }
... }
>>> with FMGBase(**settings) as fmg:
>>>     fmg.update(address_request)

Returns:

Type Description
FMGResponse

Result of operation

Source code in pyfortinet/fmg_api/fmgbase.py
@error_handling
@auth_required
@lock
def update(self, request: Union[dict[str, Any], List[dict[str, Any]]]) -> FMGResponse:
    """Update operation

    Notes:
        Multiple requests in one call is supported

    Args:
        request: Update operation's data structure

    Examples:
        ```pycon

        >>> settings = {...}
        >>> address_request = {
        ...     "url": "/pm/config/global/obj/firewall/address",
        ...     "data": {
        ...         "name": "test-address",
        ...         "associated-interface": "inside",
        ...         "obj-type": "ip",
        ...         "type": "ipmask",
        ...         "start-ip": "10.0.0.1/24"
        ...     }
        ... }
        >>> with FMGBase(**settings) as fmg:
        >>>     fmg.update(address_request)
        ```

    Returns:
        (FMGResponse): Result of operation
    """
    response = FMGResponse(fmg=self)
    request = prepare_batch(request)
    body = {
        "method": "update",
        "params": [
            {
                "data": req.get("data"),
                "url": req.get("url"),
            }
            for req in request
        ],
        "session": self._token.get_secret_value(),
        "id": self._id,
    }
    api_result = self._post(request=body)
    if isinstance(api_result, dict):
        api_result = [api_result]
    response.success = all(result.get("status", {}).get("code") == 0 for result in api_result)
    response.data = api_result
    return response

wait_for_task #

wait_for_task(
    task_res: Union[int, FMGResponse],
    callback: Callable[[int, str], None] = None,
    timeout: int = 60,
    loop_interval: int = 2,
) -> Union[str, None]

Poll a FortiManager task until it reaches a terminal state.

Parameters:

Name Type Description Default
task_res Union[int, FMGResponse]

Task ID or a response containing task metadata.

required
callback Callable[[int, str], None]

Optional callable receiving the completion percentage and latest log line.

None
timeout int

Polling timeout in seconds.

60
loop_interval int

Delay between status reads in seconds.

2

Returns:

Type Description
Union[str, None]

str or None: Terminal task state, or None if no task can be polled or a status read fails.

Union[str, None]

Check for "done" before treating the task as completed successfully.

Examples:

Inside an open connection, use a task ID returned by an earlier execution request:

state = fmg.wait_for_task(task_id, callback=lambda percent, log: print(percent, log))
Source code in pyfortinet/fmg_api/fmgbase.py
def wait_for_task(
    self,
    task_res: Union[int, FMGResponse],
    callback: Callable[[int, str], None] = None,
    timeout: int = 60,
    loop_interval: int = 2,
) -> Union[str, None]:
    """Poll a FortiManager task until it reaches a terminal state.

    Args:
        task_res: Task ID or a response containing task metadata.
        callback: Optional callable receiving the completion percentage and latest log line.
        timeout: Polling timeout in seconds.
        loop_interval: Delay between status reads in seconds.

    Returns:
        str or None: Terminal task state, or None if no task can be polled or a status read fails.
        Check for "done" before treating the task as completed successfully.

    Examples:
        Inside an open connection, use a task ID returned by an earlier execution request:

        ```python
        state = fmg.wait_for_task(task_id, callback=lambda percent, log: print(percent, log))
        ```
    """
    task_id = task_id_from_response(task_res)
    if task_id is None:
        return
    start_time = time.monotonic()
    while True:
        try:
            response = self.get({"url": Task._url.default, "filter": ["id", "==", task_id]})
            task: Task = task_from_response(response)
        except ConnectionError:  # avoid error out, let requests retry
            time.sleep(loop_interval)
            if time.monotonic() - start_time > timeout:
                raise TimeoutError(f"Timed out waiting {timeout} seconds for the task {task_id}!") from None
            continue
        if not task:
            return
        if time.monotonic() - start_time > timeout:
            raise TimeoutError(f"Timed out waiting {timeout} seconds for the task {task_id}!")
        if callable(callback):
            callback(task.percent, task.line[-1].detail if task.line else "")
        # exit on the following states
        if task.state in TERMINAL_TASK_STATES:
            return task.state
        time.sleep(loop_interval)

FMGLockContext #

FMGLockContext(fmg: FMGBase)

Lock FMG workspace

Source code in pyfortinet/fmg_api/fmgbase.py
def __init__(self, fmg: "FMGBase"):
    self._fmg = fmg
    self._locked_adoms = set()
    self._uses_workspace = None
    self._uses_adoms = None

locked_adoms property #

locked_adoms: set[str]

returns locked adom set

uses_workspace property #

uses_workspace: bool

returns workspace usage

check_mode #

check_mode(adom: Optional[str] = None) -> None

Discover the effective workspace mode for the requested or selected ADOM.

Source code in pyfortinet/fmg_api/fmgbase.py
def check_mode(self, adom: Optional[str] = None) -> None:
    """Discover the effective workspace mode for the requested or selected ADOM."""
    self._uses_workspace = None
    result = self._fmg.get({"url": "/cli/global/system/global", "fields": ["workspace-mode"]})
    if workspace_mode(result) == "per-adom":
        adom = adom or self._fmg.adom or "root"
        if adom.lower() == "global":
            # FMG 7.4.6 exposes no global ADOM metadata and disables its workspace in per-ADOM mode.
            enabled = False
        else:
            result = self._fmg.get({"url": f"/dvmdb/adom/{adom}", "fields": ["workspace_mode"]})
            enabled = workspace_enabled(result, "workspace_mode")
    else:
        enabled = workspace_enabled(result)
    self._uses_workspace = enabled

commit_changes #

commit_changes(adoms: Optional[list] = None, aux: bool = False) -> list[FMGResponse]

Commit workspace changes in FortiManager's database.

Parameters:

Name Type Description Default
adoms Optional[list]

ADOM names to commit. If omitted or empty, use the ADOMs locked by this client.

None
aux bool

Use the policy/object database workspace commit route.

False

Returns:

Name Type Description
list list[FMGResponse]

Responses for the commit operations. This does not install configuration onto devices.

Source code in pyfortinet/fmg_api/fmgbase.py
def commit_changes(self, adoms: Optional[list] = None, aux: bool = False) -> list[FMGResponse]:
    """Commit workspace changes in FortiManager's database.

    Args:
        adoms: ADOM names to commit. If omitted or empty, use the ADOMs locked by this client.
        aux: Use the policy/object database workspace commit route.

    Returns:
        list: Responses for the commit operations. This does not install configuration onto devices.
    """
    results = []
    if not adoms:
        adoms = self._locked_adoms
    for adom in adoms:
        if aux:
            url = f"/pm/config/adom/{adom}/workspace/commit"
        elif adom.lower() == "global":
            url = "/dvmdb/global/workspace/commit/"
        else:
            url = f"/dvmdb/adom/{adom}/workspace/commit"
        results.append(self._fmg.exec({"url": url}))
    return results

lock_adoms #

lock_adoms(*adoms: str) -> FMGResponse

Lock adom list

If no adom specified, global workspace will be locked

Parameters:

Name Type Description Default
*adoms str

list of adom names

()

Returns:

Type Description
FMGResponse

Response object

Source code in pyfortinet/fmg_api/fmgbase.py
def lock_adoms(self, *adoms: str) -> FMGResponse:
    """Lock adom list

    If no adom specified, global workspace will be locked

    Args:
        *adoms (str): list of adom names

    Returns:
        Response object
    """
    result = FMGResponse(fmg=self._fmg, data=[], success=True)
    if not adoms:
        adoms = ["root"]
    for adom in adoms:
        url = "/dvmdb/global/workspace/lock/" if adom.lower() == "global" else f"/dvmdb/adom/{adom}/workspace/lock/"
        operation = self._fmg.exec(request={"url": url})
        result.data.append({adom: operation})
        if not operation.success:
            raise FMGLockException(operation.data)
        self._locked_adoms.add(adom)
    return result

unlock_adoms #

unlock_adoms(*adoms) -> FMGResponse

unlock ADOMs

Source code in pyfortinet/fmg_api/fmgbase.py
def unlock_adoms(self, *adoms) -> FMGResponse:
    """unlock ADOMs"""
    result = FMGResponse(fmg=self._fmg, data=[], success=True)
    if not adoms:
        adoms = copy(self._locked_adoms)
    failed_adoms = set()
    for adom in adoms:
        if adom.lower() == "global":
            url = "/dvmdb/global/workspace/unlock/"
        else:
            url = f"/dvmdb/adom/{adom}/workspace/unlock/"
        operation = self._fmg.exec(request={"url": url})
        result.data.append({adom: operation})
        if operation.success:
            self._locked_adoms.discard(adom)
        else:
            failed_adoms.add(adom)

    if failed_adoms:
        raise FMGException(f"Failed to unlock ADOMs: {failed_adoms}")
    return result

FMGResponse dataclass #

FMGResponse(
    data: Union[Dict[str, str], List[dict], List[FMGObject]] = dict(), success: bool = False, fmg: FMGBase = None
)

Response to a request

Attributes:

Name Type Description
data dict | List[FMGObject]

response data

success bool

True on success

fmg FMGBase

FMG object tied to this response

first #

first() -> Optional[Union[FMGObject, dict]]

Return first data or None if result is empty

Source code in pyfortinet/fmg_api/fmgbase.py
def first(self) -> Optional[Union[FMGObject, dict]]:
    """Return first data or None if result is empty"""
    if isinstance(self.data, dict):
        if isinstance(self.data.get("data"), list):
            return self.data.get("data")[0] if self.data.get("data") else None
        else:
            return self.data.get("data")
    elif isinstance(self.data, list) and self.data:  # non-empty list
        return self.data[0]
    return None

auth_required #

auth_required(func: Callable) -> Callable

Decorator to provide authentication for the method

Parameters:

Name Type Description Default
func Callable

function to handle authentication errors

required

Returns:

Type Description
Callable

function with authentication handling enabled

Source code in pyfortinet/fmg_api/fmgbase.py
def auth_required(func: Callable) -> Callable:
    """Decorator to provide authentication for the method

    Args:
        func: function to handle authentication errors

    Returns:
        (Callable): function with authentication handling enabled
    """

    @functools.wraps(func)
    def auth_decorated(self: Union[dict, "FMGBase"] = None, *args, **kwargs):
        """method which needs authentication"""
        if not self._token:
            raise FMGTokenException("No token was obtained. Open connection first!")
        try:
            return func(self, *args, **kwargs)
        except FMGAuthenticationException as err:
            try:  # try again after refreshing token
                self._token = self._get_token()
                return func(self, *args, **kwargs)
            except FMGException as err2:
                raise err2 from err

    return auth_decorated

error_handling #

error_handling(func: Callable) -> Callable

Decorator to provide error handling for the methods

Source code in pyfortinet/fmg_api/fmgbase.py
def error_handling(func: Callable) -> Callable:
    """Decorator to provide error handling for the methods"""

    @functools.wraps(func)
    def error_decorated(self: "FMGBase", *args, **kwargs):
        try:
            return func(self, *args, **kwargs)
        except FMGException as err:
            if self.raise_on_error:
                raise
            result = FMGResponse(data=[{"error": str(err)}], success=False)
            return result

    return error_decorated

lock #

lock(func: Callable) -> Callable

Decorator to provide ADOM locking if needed

Parameters:

Name Type Description Default
func Callable

function to handle errors complaining about no locking

required

Returns:

Type Description
Callable

function with lock handling enabled

Source code in pyfortinet/fmg_api/fmgbase.py
def lock(func: Callable) -> Callable:
    """Decorator to provide ADOM locking if needed

    Args:
        func: function to handle errors complaining about no locking

    Returns:
        (Callable): function with lock handling enabled
    """

    @functools.wraps(func)
    def lock_decorated(self: "FMGBase" = None, *args, **kwargs):
        """method which needs locking"""
        try:
            return func(self, *args, **kwargs)
        except (FMGLockNeededException, FMGAuthenticationException) as err:
            try:  # try again after locking
                if not args:  # in case we got kwargs request
                    args = [kwargs.get("request")]
                    del kwargs["request"]
                # ensure args[0] is a list of request dict or obj to support multiple request in one API call
                if isinstance(args[0], list):
                    args_to_check = args[0]
                else:
                    args_to_check = [args[0]]
                for arg in args_to_check:
                    if isinstance(arg, dict):
                        url = arg.get("url")
                        adom_match = re.search(r"^(?:/\w+){,3}/(?P<adom>global\b|(?<=adom/)[\w-]+)/?", url)
                        if adom_match:
                            adom = adom_match.group("adom")
                        elif self.adom:
                            adom = self.adom
                        else:
                            raise FMGException(f"No ADOM found to lock in url '{url}'") from err
                    elif isinstance(arg, FMGObject):
                        adom = arg.fmg_scope
                    else:
                        raise ValueError(f"Unknown request: {arg}")
                    if adom not in self.lock.locked_adoms:
                        self.lock(adom)
                    # else:  # ADOM already locked, do not try to lock it again
                    #     raise
                return func(self, *args, **kwargs)
            except FMGException as err2:
                raise err2 from err

    return lock_decorated