Debian Codegraph @

asynceapi/_models.py

raw symbols SCIP
1 # Copyright (c) 2024-2026 Arista Networks, Inc.
2 # Use of this source code is governed by the Apache License 2.0
3 # that can be found in the LICENSE file.
4 """Models for the asynceapi package."""
5
6 from __future__ import annotations
7
8 from dataclasses import dataclass, field
9 from json import JSONDecodeError, loads
10 from logging import getLogger
11 from typing import TYPE_CHECKING, Any, Literal
12 from uuid import uuid4
13
14 from ._constants import EapiCommandFormat
15 from ._errors import EapiReponseError
16
17 if TYPE_CHECKING:
18 from collections.abc import Iterator
19
20 from ._types import EapiComplexCommand, EapiJsonOutput, EapiSimpleCommand, EapiTextOutput, JsonRpc
21
22 LOGGER = getLogger(__name__)
23
24
25 @dataclass(frozen=True)
26 class EapiRequest:
27 """Model for an eAPI request.
28
29 Attributes
30 ----------
31 commands : list[EapiSimpleCommand | EapiComplexCommand]
32 A list of commands to execute.
33 version : int | Literal["latest"]
34 The eAPI version to use. Defaults to "latest".
35 format : EapiCommandFormat
36 The command output format. Defaults "json".
37 timestamps : bool
38 Include timestamps in the command output. Defaults to False.
39 auto_complete : bool
40 Enable command auto-completion. Defaults to False.
41 expand_aliases : bool
42 Expand command aliases. Defaults to False.
43 stop_on_error : bool
44 Stop command execution on first error. Defaults to True.
45 id : int | str
46 The request ID. Defaults to a random hex string.
47 """
48
49 commands: list[EapiSimpleCommand | EapiComplexCommand]
50 version: int | Literal["latest"] = "latest"
51 format: EapiCommandFormat = EapiCommandFormat.JSON
52 timestamps: bool = False
53 auto_complete: bool = False
54 expand_aliases: bool = False
55 stop_on_error: bool = True
56 id: int | str = field(default_factory=lambda: uuid4().hex)
57
58 def to_jsonrpc(self) -> JsonRpc:
59 """Return the JSON-RPC dictionary payload for the request."""
60 return {
61 "jsonrpc": "2.0",
62 "method": "runCmds",
63 "params": {
64 "version": self.version,
65 "cmds": self.commands,
66 "format": self.format,
67 "timestamps": self.timestamps,
68 "autoComplete": self.auto_complete,
69 "expandAliases": self.expand_aliases,
70 "stopOnError": self.stop_on_error,
71 },
72 "id": self.id,
73 }
74
75
76 @dataclass(frozen=True)
77 class EapiResponse:
78 """Model for an eAPI response.
79
80 Construct an EapiResponse from a JSON-RPC response dictionary using the `from_jsonrpc` class method.
81
82 Can be iterated over to access command results in order of execution.
83
84 Attributes
85 ----------
86 request_id : str
87 The ID of the original request this response corresponds to.
88 _results : dict[int, EapiCommandResult]
89 Dictionary mapping request command indices to their respective results.
90 error_code : int | None
91 The JSON-RPC error code, if any.
92 error_message : str | None
93 The JSON-RPC error message, if any.
94 """
95
96 request_id: str
97 _results: dict[int, EapiCommandResult] = field(default_factory=dict)
98 error_code: int | None = None
99 error_message: str | None = None
100
101 @property
102 def success(self) -> bool:
103 """Return True if the response has no errors."""
104 return self.error_code is None
105
106 @property
107 def results(self) -> list[EapiCommandResult]:
108 """Get all results as a list. Results are ordered by the command indices in the request."""
109 return list(self._results.values())
110
111 def __len__(self) -> int:
112 """Return the number of results."""
113 return len(self._results)
114
115 def __iter__(self) -> Iterator[EapiCommandResult]:
116 """Enable iteration over the results. Results are yielded in the same order as provided in the request."""
117 yield from self._results.values()
118
119 @classmethod
120 def from_jsonrpc(cls, response: dict[str, Any], request: EapiRequest, *, raise_on_error: bool = False) -> EapiResponse:
121 """Build an EapiResponse from a JSON-RPC eAPI response.
122
123 Parameters
124 ----------
125 response
126 The JSON-RPC eAPI response dictionary.
127 request
128 The corresponding EapiRequest.
129 raise_on_error
130 Raise an EapiReponseError if the response contains errors, by default False.
131
132 Returns
133 -------
134 EapiResponse
135 The EapiResponse object.
136 """
137 has_error = "error" in response
138 response_data = response["error"]["data"] if has_error else response["result"]
139
140 # Handle case where we have fewer results than commands (stop_on_error=True)
141 executed_count = min(len(response_data), len(request.commands))
142
143 # Process the results we have
144 results = {}
145 for i in range(executed_count):
146 cmd = request.commands[i]
147 cmd_str = cmd["cmd"] if isinstance(cmd, dict) else cmd
148 data = response_data[i]
149
150 output = None
151 errors = []
152 success = True
153 start_time = None
154 duration = None
155
156 # Parse the output based on the data type, no output when errors are present
157 if isinstance(data, dict):
158 if "errors" in data:
159 errors = data["errors"]
160 success = False
161 else:
162 output = data["output"] if request.format == EapiCommandFormat.TEXT and "output" in data else data
163
164 # Add timestamps if available
165 if request.timestamps and "_meta" in data:
166 meta = data.pop("_meta")
167 start_time = meta.get("execStartTime")
168 duration = meta.get("execDuration")
169
170 elif isinstance(data, str):
171 # Handle case where eAPI returns a JSON string response (serialized JSON) for certain commands
172 try:
173 output = loads(data)
174 except (JSONDecodeError, TypeError):
175 # If it's not valid JSON, store as is
176 LOGGER.warning("Invalid JSON response for command: %s. Storing as text: %s", cmd_str, data)
177 output = data
178
179 results[i] = EapiCommandResult(
180 command=cmd_str,
181 output=output,
182 errors=errors,
183 success=success,
184 start_time=start_time,
185 duration=duration,
186 )
187
188 # If stop_on_error is True and we have an error, indicate commands not executed
189 if has_error and request.stop_on_error and executed_count < len(request.commands):
190 for i in range(executed_count, len(request.commands)):
191 cmd = request.commands[i]
192 cmd_str = cmd["cmd"] if isinstance(cmd, dict) else cmd
193 results[i] = EapiCommandResult(command=cmd_str, output=None, errors=["Command not executed due to previous error"], success=False, executed=False)
194
195 response_obj = cls(
196 request_id=response["id"],
197 _results=results,
198 error_code=response["error"]["code"] if has_error else None,
199 error_message=response["error"]["message"] if has_error else None,
200 )
201
202 if raise_on_error and has_error:
203 raise EapiReponseError(response_obj)
204
205 return response_obj
206
207
208 @dataclass(frozen=True)
209 class EapiCommandResult:
210 """Model for an eAPI command result.
211
212 Attributes
213 ----------
214 command : str
215 The command that was executed.
216 output : EapiJsonOutput | EapiTextOutput | None
217 The command result output. None if the command returned errors.
218 errors : list[str]
219 A list of error messages, if any.
220 success : bool
221 True if the command was successful.
222 executed : bool
223 True if the command was executed. When `stop_on_error` is True in the request, some commands may not be executed.
224 start_time : float | None
225 Command execution start time in seconds. Uses Unix epoch format. `timestamps` must be True in the request.
226 duration : float | None
227 Command execution duration in seconds. `timestamps` must be True in the request.
228 """
229
230 command: str
231 output: EapiJsonOutput | EapiTextOutput | None
232 errors: list[str] = field(default_factory=list)
233 success: bool = True
234 executed: bool = True
235 start_time: float | None = None
236 duration: float | None = None
237
238
239 @dataclass(frozen=True)
240 class EAPIClientConnectionOptions:
241 """Model for eAPI client connection options.
242
243 Attributes
244 ----------
245 host : str
246 Device FQDN or IP address.
247 username : str
248 Username for eAPI authentication.
249 password : str
250 Password for eAPI authentication.
251 port : int | None
252 eAPI port. Defaults to 80 for HTTP or 443 for HTTPS.
253 proto : Literal["http", "https"]
254 eAPI protocol.
255 timeout : float | None
256 Global timeout in seconds for outgoing eAPI calls. None means no timeout.
257 use_session_auth: bool
258 Use eAPI cookie-session authentication.
259 """
260
261 host: str
262 username: str
263 password: str
264 port: int | None = None
265 proto: Literal["http", "https"] = "https"
266 timeout: float | None = None
267 use_session_auth: bool = False