Debian Codegraph @

asynceapi/device.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 # Initially written by Jeremy Schulman at https://github.com/jeremyschulman/aio-eapi
5 """asynceapi.Device definition."""
6 # -----------------------------------------------------------------------------
7 # System Imports
8 # -----------------------------------------------------------------------------
9
10 from __future__ import annotations
11
12 from logging import getLogger
13 from socket import getservbyname
14 from typing import TYPE_CHECKING, Any, Literal, overload
15
16 # -----------------------------------------------------------------------------
17 # Public Imports
18 # -----------------------------------------------------------------------------
19 import httpx
20 from typing_extensions import deprecated
21
22 from ._auth import EapiSessionAuth
23
24 # -----------------------------------------------------------------------------
25 # Private Imports
26 # -----------------------------------------------------------------------------
27 from ._constants import EapiCommandFormat
28 from .aio_portcheck import port_check_url
29 from .config_session import SessionConfig
30 from .errors import EapiCommandError
31
32 if TYPE_CHECKING:
33 from types import TracebackType
34
35 from ._types import EapiComplexCommand, EapiJsonOutput, EapiSimpleCommand, EapiTextOutput, JsonRpc
36
37 # -----------------------------------------------------------------------------
38 # Exports
39 # -----------------------------------------------------------------------------
40
41 LOGGER = getLogger(__name__)
42 __all__ = ["Device"]
43
44
45 # -----------------------------------------------------------------------------
46 #
47 # CODE BEGINS
48 #
49 # -----------------------------------------------------------------------------
50
51
52 class Device(httpx.AsyncClient):
53 """Represent the async JSON-RPC client that communicates with an Arista EOS device.
54
55 This class inherits directly from the
56 httpx.AsyncClient, so any initialization options can be passed directly.
57 """
58
59 EAPI_COMMAND_API_URL = "/command-api"
60 EAPI_OFMT_OPTIONS = ("json", "text")
61 EAPI_DEFAULT_OFMT = "json"
62 EAPI_LOGIN_URL = "/login"
63 EAPI_LOGOUT_URL = "/logout"
64
65 def __init__(
66 self,
67 host: str | None = None,
68 username: str | None = None,
69 password: str | None = None,
70 proto: str = "https",
71 port: str | int | None = None,
72 *,
73 use_session_auth: bool = False,
74 **kwargs: Any, # noqa: ANN401
75 ) -> None:
76 """Initialize the Device class.
77
78 As a subclass to httpx.AsyncClient, the caller can provide any of those initializers.
79 Specific parameters for Device class are all optional and described below.
80
81 Parameters
82 ----------
83 host
84 The EOS target device, either hostname (DNS) or ipaddress.
85 username
86 The login user-name; requires the password parameter.
87 password
88 The login password; requires the username parameter.
89 proto
90 The protocol, http or https, to communicate eAPI with the device.
91 port
92 If not provided, the proto value is used to look up the associated
93 port (http=80, https=443). If provided, overrides the port used to
94 communicate with the device.
95 use_session_auth
96 When True, authenticate via eAPI cookie session (POST /login) instead
97 of HTTP Basic Auth on every request. Requires ``username``, ``password``, and ``host``.
98 kwargs
99 Other named keyword arguments, some of them are being used in the function
100 cf Other Parameters section below, others are just passed as is to the httpx.AsyncClient.
101
102 Other Parameters
103 ----------------
104 base_url : str
105 If provided, the complete URL to the device eAPI endpoint.
106
107 auth :
108 If provided, used as the httpx authentication initializer value. If
109 not provided, then username+password is assumed by the Caller and
110 used to create a BasicAuth instance or an EapiSessionAuth if ``use_session_auth`` is True.
111 """
112 self.port = port or getservbyname(proto)
113 self.host = host
114 self._use_session_auth = use_session_auth
115 self._session_auth: EapiSessionAuth | None = None
116 kwargs.setdefault("base_url", httpx.URL(f"{proto}://{self.host}:{self.port}"))
117 kwargs.setdefault("verify", False)
118 if self._use_session_auth:
119 if not (username and password):
120 msg = "username and password are required for session authentication"
121 raise ValueError(msg)
122 if not self.host:
123 msg = "host is required for session authentication"
124 raise ValueError(msg)
125 login_url = f"{proto}://{self.host}:{self.port}{self.EAPI_LOGIN_URL}"
126 self._session_auth = EapiSessionAuth(host=self.host, username=username, password=password, login_url=login_url)
127 kwargs.setdefault("auth", self._session_auth)
128 LOGGER.debug("Device %s: eAPI session-based authentication enabled", self.host)
129 else:
130 auth_object = httpx.BasicAuth(username, password) if username and password else None
131 kwargs.setdefault("auth", auth_object)
132 if auth_object is not None:
133 LOGGER.debug("Device %s: using HTTP basic authentication", self.host)
134
135 super().__init__(**kwargs)
136 self.headers["Content-Type"] = "application/json-rpc"
137
138 @deprecated("This method is deprecated, use `Device.check_api_endpoint` method instead. This will be removed in ANTA v2.0.0.", category=DeprecationWarning)
139 async def check_connection(self) -> bool:
140 """Check the target device to ensure that the eAPI port is open and accepting connections.
141
142 It is recommended that a Caller checks the connection before involving cli commands,
143 but this step is not required.
144
145 Returns
146 -------
147 bool
148 True when the device eAPI is accessible, False otherwise.
149 """
150 return await port_check_url(self.base_url)
151
152 async def check_api_endpoint(self) -> bool:
153 """Check the target device eAPI HTTP endpoint with a HEAD request.
154
155 It is recommended that a Caller checks the connection before involving cli commands,
156 but this step is not required.
157
158 Returns
159 -------
160 bool
161 True when the device eAPI HTTP endpoint is accessible (2xx status code),
162 otherwise an HTTPStatusError exception is raised.
163 """
164 response = await self.head(self.EAPI_COMMAND_API_URL, timeout=5)
165 response.raise_for_status()
166 return True
167
168 # Single command, JSON output, no suppression
169 @overload
170 async def cli(
171 self,
172 *,
173 command: EapiSimpleCommand | EapiComplexCommand,
174 commands: None = None,
175 ofmt: Literal["json"] = "json",
176 version: int | Literal["latest"] = "latest",
177 suppress_error: Literal[False] = False,
178 auto_complete: bool = False,
179 expand_aliases: bool = False,
180 req_id: int | str | None = None,
181 ) -> EapiJsonOutput: ...
182
183 # Multiple commands, JSON output, no suppression
184 @overload
185 async def cli(
186 self,
187 *,
188 command: None = None,
189 commands: list[EapiSimpleCommand | EapiComplexCommand],
190 ofmt: Literal["json"] = "json",
191 version: int | Literal["latest"] = "latest",
192 suppress_error: Literal[False] = False,
193 auto_complete: bool = False,
194 expand_aliases: bool = False,
195 req_id: int | str | None = None,
196 ) -> list[EapiJsonOutput]: ...
197
198 # Single command, TEXT output, no suppression
199 @overload
200 async def cli(
201 self,
202 *,
203 command: EapiSimpleCommand | EapiComplexCommand,
204 commands: None = None,
205 ofmt: Literal["text"],
206 version: int | Literal["latest"] = "latest",
207 suppress_error: Literal[False] = False,
208 auto_complete: bool = False,
209 expand_aliases: bool = False,
210 req_id: int | str | None = None,
211 ) -> EapiTextOutput: ...
212
213 # Multiple commands, TEXT output, no suppression
214 @overload
215 async def cli(
216 self,
217 *,
218 command: None = None,
219 commands: list[EapiSimpleCommand | EapiComplexCommand],
220 ofmt: Literal["text"],
221 version: int | Literal["latest"] = "latest",
222 suppress_error: Literal[False] = False,
223 auto_complete: bool = False,
224 expand_aliases: bool = False,
225 req_id: int | str | None = None,
226 ) -> list[EapiTextOutput]: ...
227
228 # Single command, JSON output, with suppression
229 @overload
230 async def cli(
231 self,
232 *,
233 command: EapiSimpleCommand | EapiComplexCommand,
234 commands: None = None,
235 ofmt: Literal["json"] = "json",
236 version: int | Literal["latest"] = "latest",
237 suppress_error: Literal[True],
238 auto_complete: bool = False,
239 expand_aliases: bool = False,
240 req_id: int | str | None = None,
241 ) -> EapiJsonOutput | None: ...
242
243 # Multiple commands, JSON output, with suppression
244 @overload
245 async def cli(
246 self,
247 *,
248 command: None = None,
249 commands: list[EapiSimpleCommand | EapiComplexCommand],
250 ofmt: Literal["json"] = "json",
251 version: int | Literal["latest"] = "latest",
252 suppress_error: Literal[True],
253 auto_complete: bool = False,
254 expand_aliases: bool = False,
255 req_id: int | str | None = None,
256 ) -> list[EapiJsonOutput] | None: ...
257
258 # Single command, TEXT output, with suppression
259 @overload
260 async def cli(
261 self,
262 *,
263 command: EapiSimpleCommand | EapiComplexCommand,
264 commands: None = None,
265 ofmt: Literal["text"],
266 version: int | Literal["latest"] = "latest",
267 suppress_error: Literal[True],
268 auto_complete: bool = False,
269 expand_aliases: bool = False,
270 req_id: int | str | None = None,
271 ) -> EapiTextOutput | None: ...
272
273 # Multiple commands, TEXT output, with suppression
274 @overload
275 async def cli(
276 self,
277 *,
278 command: None = None,
279 commands: list[EapiSimpleCommand | EapiComplexCommand],
280 ofmt: Literal["text"],
281 version: int | Literal["latest"] = "latest",
282 suppress_error: Literal[True],
283 auto_complete: bool = False,
284 expand_aliases: bool = False,
285 req_id: int | str | None = None,
286 ) -> list[EapiTextOutput] | None: ...
287
288 # Actual implementation
289 async def cli(
290 self,
291 command: EapiSimpleCommand | EapiComplexCommand | None = None,
292 commands: list[EapiSimpleCommand | EapiComplexCommand] | None = None,
293 ofmt: Literal["json", "text"] = "json",
294 version: int | Literal["latest"] = "latest",
295 *,
296 suppress_error: bool = False,
297 auto_complete: bool = False,
298 expand_aliases: bool = False,
299 req_id: int | str | None = None,
300 ) -> EapiJsonOutput | EapiTextOutput | list[EapiJsonOutput] | list[EapiTextOutput] | None:
301 """Execute one or more CLI commands.
302
303 Parameters
304 ----------
305 command
306 A single command to execute; results in a single output response.
307 commands
308 A list of commands to execute; results in a list of output responses.
309 ofmt
310 Either 'json' or 'text'; indicates the output format for the CLI commands.
311 eAPI defaults to 'json'.
312 version
313 By default the eAPI will use "version 1" for all API object models.
314 This driver will, by default, always set version to "latest" so
315 that the behavior matches the CLI of the device. The caller can
316 override the "latest" behavior by explicitly setting the version.
317 suppress_error
318 When not False, then if the execution of the command would-have
319 raised an EapiCommandError, rather than raising this exception this
320 routine will return the value None.
321
322 For example, if the following command had raised
323 EapiCommandError, now response would be set to None instead.
324
325 response = dev.cli(..., suppress_error=True)
326 auto_complete
327 Enabled/disables the command auto-compelete feature of the eAPI. Per the
328 documentation:
329 Allows users to use shorthand commands in eAPI calls. With this
330 parameter included a user can send 'sh ver' via eAPI to get the
331 output of 'show version'.
332 expand_aliases
333 Enables/disables the command use of user-defined alias. Per the
334 documentation:
335 Allowed users to provide the expandAliases parameter to eAPI
336 calls. This allows users to use aliased commands via the API.
337 For example if an alias is configured as 'sv' for 'show version'
338 then an API call with sv and the expandAliases parameter will
339 return the output of show version.
340 req_id
341 A unique identifier that will be echoed back by the switch. May be a string or number.
342
343 Returns
344 -------
345 dict[str, Any]
346 Single command, JSON output, suppress_error=False
347 list[dict[str, Any]]
348 Multiple commands, JSON output, suppress_error=False
349 str
350 Single command, TEXT output, suppress_error=False
351 list[str]
352 Multiple commands, TEXT output, suppress_error=False
353 dict[str, Any] | None
354 Single command, JSON output, suppress_error=True
355 list[dict[str, Any]] | None
356 Multiple commands, JSON output, suppress_error=True
357 str | None
358 Single command, TEXT output, suppress_error=True
359 list[str] | None
360 Multiple commands, TEXT output, suppress_error=True
361 """
362 if not any((command, commands)):
363 msg = "Required 'command' or 'commands'"
364 raise RuntimeError(msg)
365
366 jsonrpc = self._jsonrpc_command(
367 commands=[command] if command else commands or [],
368 ofmt=ofmt,
369 version=version,
370 auto_complete=auto_complete,
371 expand_aliases=expand_aliases,
372 req_id=req_id,
373 )
374
375 try:
376 res = await self.jsonrpc_exec(jsonrpc)
377 return res[0] if command else res
378 except EapiCommandError:
379 if suppress_error:
380 return None
381 raise
382
383 def _jsonrpc_command(
384 self,
385 commands: list[EapiSimpleCommand | EapiComplexCommand],
386 ofmt: Literal["json", "text"] = "json",
387 version: int | Literal["latest"] = "latest",
388 *,
389 auto_complete: bool = False,
390 expand_aliases: bool = False,
391 req_id: int | str | None = None,
392 ) -> JsonRpc:
393 """Create the JSON-RPC command dictionary object.
394
395 Parameters
396 ----------
397 commands
398 A list of commands to execute; results in a list of output responses.
399 ofmt
400 Either 'json' or 'text'; indicates the output format for the CLI commands.
401 eAPI defaults to 'json'.
402 version
403 By default the eAPI will use "version 1" for all API object models.
404 This driver will, by default, always set version to "latest" so
405 that the behavior matches the CLI of the device. The caller can
406 override the "latest" behavior by explicitly setting the version.
407 auto_complete
408 Enabled/disables the command auto-compelete feature of the EAPI. Per the
409 documentation:
410 Allows users to use shorthand commands in eAPI calls. With this
411 parameter included a user can send 'sh ver' via eAPI to get the
412 output of 'show version'.
413 expand_aliases
414 Enables/disables the command use of User defined alias. Per the
415 documentation:
416 Allowed users to provide the expandAliases parameter to eAPI
417 calls. This allows users to use aliased commands via the API.
418 For example if an alias is configured as 'sv' for 'show version'
419 then an API call with sv and the expandAliases parameter will
420 return the output of show version.
421 req_id
422 A unique identifier that will be echoed back by the switch. May be a string or number.
423
424 Returns
425 -------
426 dict[str, Any]:
427 dict containing the JSON payload to run the command.
428
429 """
430 return {
431 "jsonrpc": "2.0",
432 "method": "runCmds",
433 "params": {
434 "version": version,
435 "cmds": commands,
436 "format": EapiCommandFormat(ofmt),
437 "autoComplete": auto_complete,
438 "expandAliases": expand_aliases,
439 },
440 "id": req_id or id(self),
441 }
442
443 async def jsonrpc_exec(self, jsonrpc: JsonRpc) -> list[EapiJsonOutput] | list[EapiTextOutput]:
444 """Execute the JSON-RPC dictionary object.
445
446 Parameters
447 ----------
448 jsonrpc
449 The JSON-RPC as created by the `meth`:_jsonrpc_command().
450
451 Raises
452 ------
453 EapiCommandError
454 In the event that a command resulted in an error response.
455
456 Returns
457 -------
458 list[dict[str, Any] | str]
459 The list of command results; either dict or text depending on the
460 JSON-RPC format parameter.
461 """
462 res = await self.post(self.EAPI_COMMAND_API_URL, json=jsonrpc)
463 res.raise_for_status()
464 body = res.json()
465
466 commands = jsonrpc["params"]["cmds"]
467 ofmt = jsonrpc["params"].get("format", EapiCommandFormat.JSON)
468
469 get_output = (lambda _r: _r["output"]) if ofmt == "text" else (lambda _r: _r)
470
471 # if there are no errors then return the list of command results.
472 if (err_data := body.get("error")) is None:
473 return [get_output(cmd_res) for cmd_res in body["result"]]
474
475 # ---------------------------------------------------------------------
476 # if we are here, then there were some command errors. Raise a
477 # EapiCommandError exception with args (commands that failed, passed,
478 # not-executed).
479 # ---------------------------------------------------------------------
480
481 # -------------------------- eAPI specification ----------------------
482 # On an error, no result object is present, only an error object, which
483 # is guaranteed to have the following attributes: code, messages, and
484 # data. Similar to the result object in the successful response, the
485 # data object is a list of objects corresponding to the results of all
486 # commands up to, and including, the failed command. If there was a an
487 # error before any commands were executed (e.g. bad credentials), data
488 # will be empty. The last object in the data array will always
489 # correspond to the failed command. The command failure details are
490 # always stored in the errors array.
491
492 cmd_data = err_data["data"]
493 len_data = len(cmd_data)
494 err_at = len_data - 1
495 err_msg = err_data["message"]
496 failed_cmd = commands[err_at]
497
498 raise EapiCommandError(
499 passed=[get_output(cmd_data[i]) for i in range(err_at)],
500 failed=failed_cmd["cmd"] if isinstance(failed_cmd, dict) else failed_cmd,
501 errors=cmd_data[err_at]["errors"],
502 errmsg=err_msg,
503 not_exec=commands[err_at + 1 :],
504 )
505
506 async def logout(self) -> None:
507 """Log out of the device session and reset local state. No-op if not logged in."""
508 if self._session_auth is None or not self._session_auth.logged_in:
509 return
510 cookie = self._session_auth.session_cookie
511 try:
512 # Best-effort: we don't check the response — if the cookie was expired the session is already gone.
513 await self.post(self.EAPI_LOGOUT_URL, auth=httpx.Auth(), headers={"Cookie": f"Session={cookie}"})
514 except httpx.HTTPError as exc:
515 LOGGER.warning("Logout HTTP error for %s: %s", self.host, exc)
516 finally:
517 await self._session_auth.reset()
518 LOGGER.debug("Session authentication cleared for %s", self.host)
519
520 async def aclose(self) -> None:
521 """Log out and close the underlying HTTPX transport."""
522 if self._use_session_auth:
523 await self.logout()
524 await super().aclose()
525
526 async def __aexit__(
527 self,
528 exc_type: type[BaseException] | None = None,
529 exc_value: BaseException | None = None,
530 traceback: TracebackType | None = None,
531 ) -> None:
532 """Log out and close on context-manager exit."""
533 if self._use_session_auth:
534 await self.logout()
535 await super().__aexit__(exc_type, exc_value, traceback)
536
537 def config_session(self, name: str) -> SessionConfig:
538 """Return a SessionConfig instance bound to this device with the given session name.
539
540 Parameters
541 ----------
542 name
543 The config-session name.
544
545 Returns
546 -------
547 SessionConfig
548 SessionConfig instance bound to this device with the given session name.
549 """
550 return SessionConfig(self, name)