Debian Codegraph @

asusrouter/modules/service.py

raw
1 """Service module."""
2
3 from __future__ import annotations
4
5 from collections.abc import Awaitable, Callable
6 import logging
7 from typing import Any
8
9 from asusrouter.error import AsusRouterServiceError
10 from asusrouter.tools.converters import safe_bool, safe_int
11
12 _LOGGER = logging.getLogger(__name__)
13
14
15 async def async_call_service(
16 callback: Callable[..., Awaitable[dict[str, Any]]],
17 service: str | None,
18 arguments: dict[str, Any] | None = None,
19 apply: bool = False,
20 expect_modify: bool = True,
21 ) -> tuple[bool, int | None, int | None]:
22 """Call a service."""
23
24 # Generate commands
25 commands = {}
26
27 # Service call provided
28 if service is not None:
29 commands["rc_service"] = service
30
31 # Check arguments
32 if not arguments:
33 arguments = {}
34
35 # Add apply command if requested
36 if apply:
37 arguments["action_mode"] = "apply"
38
39 # Add arguments to the commands
40 commands.update(arguments)
41
42 # Send the commands
43 try:
44 result = await callback(commands)
45 except Exception as ex: # pylint: disable=broad-except
46 raise ex
47
48 if service is not None:
49 # Check if the service is run
50 run_service = result.get("run_service", None)
51 if run_service != service:
52 raise AsusRouterServiceError(
53 f"Service not run. Raw result: {result}"
54 )
55
56 _LOGGER.debug(
57 "Service `%s` run with arguments `%s`. Result: `%s`",
58 service,
59 arguments,
60 result,
61 )
62
63 last_id = result.get("id") or arguments.get("id")
64 last_id = safe_int(last_id)
65
66 needed_time = safe_int(result.get("restart_needed_time"))
67 # For all the services with setting ID we better wait
68 # before we will get actual state change
69 if needed_time is None and last_id is not None:
70 needed_time = 5
71
72 # Special services that won't return any result
73 if arguments.get("action_mode") == "update_client_list":
74 return (True, needed_time, last_id)
75
76 if expect_modify:
77 return (safe_bool(result.get("modify")) or False, needed_time, last_id)
78
79 return (True, needed_time, last_id)