Debian Codegraph @

asynceapi/config_session.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.SessionConfig definition."""
6
7 # -----------------------------------------------------------------------------
8 # System Imports
9 # -----------------------------------------------------------------------------
10 from __future__ import annotations
11
12 import re
13 from typing import TYPE_CHECKING
14
15 if TYPE_CHECKING:
16 from ._types import EapiComplexCommand, EapiJsonOutput, EapiSimpleCommand
17 from .device import Device
18
19 # -----------------------------------------------------------------------------
20 # Exports
21 # -----------------------------------------------------------------------------
22
23 __all__ = ["SessionConfig"]
24
25 # -----------------------------------------------------------------------------
26 #
27 # CODE BEGINS
28 #
29 # -----------------------------------------------------------------------------
30
31
32 class SessionConfig:
33 """Send configuration to a device using the EOS session mechanism.
34
35 This is the preferred way of managing configuration changes.
36
37 Notes
38 -----
39 This class definition is used by the parent Device class definition as
40 defined by `config_session`. A Caller can use the SessionConfig directly
41 as well, but it is not required.
42 """
43
44 CLI_CFG_FACTORY_RESET = "rollback clean-config"
45
46 def __init__(self, device: Device, name: str) -> None:
47 """Create a new instance of SessionConfig.
48
49 The session config instance bound
50 to the given device instance, and using the session `name`.
51
52 Parameters
53 ----------
54 device
55 The associated device instance.
56 name
57 The name of the config session.
58 """
59 self._device = device
60 self._cli = device.cli
61 self._name = name
62 self._cli_config_session = f"configure session {self.name}"
63
64 # -------------------------------------------------------------------------
65 # properties for read-only attributes
66 # -------------------------------------------------------------------------
67
68 @property
69 def name(self) -> str:
70 """Return read-only session name attribute."""
71 return self._name
72
73 @property
74 def device(self) -> Device:
75 """Return read-only device instance attribute."""
76 return self._device
77
78 # -------------------------------------------------------------------------
79 # Public Methods
80 # -------------------------------------------------------------------------
81
82 async def status_all(self) -> EapiJsonOutput:
83 """Get the status of all the session config on the device.
84
85 Run the following command on the device:
86 # show configuration sessions detail
87
88 Returns
89 -------
90 EapiJsonOutput
91 Dictionary of native EOS eAPI response; see `status` method for
92 details.
93
94 Examples
95 --------
96 Return example:
97
98 ```
99 {
100 "maxSavedSessions": 1,
101 "maxOpenSessions": 5,
102 "sessions": {
103 "jeremy1": {
104 "instances": {},
105 "state": "pending",
106 "commitUser": "",
107 "description": ""
108 },
109 "ansible_167510439362": {
110 "instances": {},
111 "state": "completed",
112 "commitUser": "joe.bob",
113 "description": "",
114 "completedTime": 1675104396.4500246
115 }
116 }
117 }
118 ```
119 """
120 return await self._cli(command="show configuration sessions detail")
121
122 async def status(self) -> EapiJsonOutput | None:
123 """Get the status of a session config on the device.
124
125 Run the following command on the device:
126 # show configuration sessions detail
127
128 And return only the status dictionary for this session. If you want
129 all sessions, then use the `status_all` method.
130
131 Returns
132 -------
133 EapiJsonOutput | None
134 Dictionary instance of the session status. If the session does not exist,
135 then this method will return None.
136
137 Examples
138 --------
139 The return is the native eAPI results from JSON output:
140
141 ```
142 all results:
143 {
144 "maxSavedSessions": 1,
145 "maxOpenSessions": 5,
146 "sessions": {
147 "jeremy1": {
148 "instances": {},
149 "state": "pending",
150 "commitUser": "",
151 "description": ""
152 },
153 "ansible_167510439362": {
154 "instances": {},
155 "state": "completed",
156 "commitUser": "joe.bob",
157 "description": "",
158 "completedTime": 1675104396.4500246
159 }
160 }
161 }
162 ```
163
164 If the session name was 'jeremy1', then this method would return:
165
166 ```
167 {
168 "instances": {},
169 "state": "pending",
170 "commitUser": "",
171 "description": ""
172 }
173 ```
174 """
175 res = await self.status_all()
176 return res["sessions"].get(self.name)
177
178 async def push(self, content: list[str] | str, *, replace: bool = False) -> None:
179 """Send the configuration content to the device.
180
181 If `replace` is true, then the command "rollback clean-config" is issued
182 before sending the configuration content.
183
184 Parameters
185 ----------
186 content
187 The text configuration CLI commands, as a list of strings, that
188 will be sent to the device. If the parameter is a string, and not
189 a list, then split the string across linebreaks. In either case
190 any empty lines will be discarded before they are send to the
191 device.
192 replace
193 When True, the content will replace the existing configuration
194 on the device.
195 """
196 # if given s string, we need to break it up into individual command
197 # lines.
198
199 if isinstance(content, str):
200 content = content.splitlines()
201
202 # prepare the initial set of command to enter the config session and
203 # rollback clean if the `replace` argument is True.
204
205 commands: list[EapiSimpleCommand | EapiComplexCommand] = [self._cli_config_session]
206 if replace:
207 commands.append(self.CLI_CFG_FACTORY_RESET)
208
209 # add the Caller's commands, filtering out any blank lines. any command
210 # lines (!) are still included.
211
212 commands.extend(filter(None, content))
213
214 await self._cli(commands=commands)
215
216 async def commit(self, timer: str | None = None) -> None:
217 """Commit the session config.
218
219 Run the following command on the device:
220 # configure session <name>
221 # commit
222
223 Parameters
224 ----------
225 timer
226 If the timer is specified, format is "hh:mm:ss", then a commit timer is
227 started. A second commit action must be made to confirm the config
228 session before the timer expires; otherwise the config-session is
229 automatically aborted.
230 """
231 command = f"{self._cli_config_session} commit"
232
233 if timer:
234 command += f" timer {timer}"
235
236 await self._cli(command=command)
237
238 async def abort(self) -> None:
239 """Abort the configuration session.
240
241 Run the following command on the device:
242 # configure session <name> abort
243 """
244 await self._cli(command=f"{self._cli_config_session} abort")
245
246 async def diff(self) -> str:
247 """Return the "diff" of the session config relative to the running config.
248
249 Run the following command on the device:
250 # show session-config named <name> diffs
251
252 Returns
253 -------
254 str
255 Return a string in diff-patch format.
256
257 References
258 ----------
259 * https://www.gnu.org/software/diffutils/manual/diffutils.txt
260 """
261 return await self._cli(command=f"show session-config named {self.name} diffs", ofmt="text")
262
263 async def load_file(self, filename: str, *, replace: bool = False) -> None:
264 """Load the configuration from <filename> into the session configuration.
265
266 If the replace parameter is True then the file contents will replace the existing session config (load-replace).
267
268 Parameters
269 ----------
270 filename
271 The name of the configuration file. The caller is required to
272 specify the filesystem, for example, the
273 filename="flash:thisfile.cfg".
274
275 replace
276 When True, the contents of the file will completely replace the
277 session config for a load-replace behavior.
278
279 Raises
280 ------
281 RuntimeError
282 If there are any issues with loading the configuration file then a
283 RuntimeError is raised with the error messages content.
284 """
285 commands: list[EapiSimpleCommand | EapiComplexCommand] = [self._cli_config_session]
286 if replace:
287 commands.append(self.CLI_CFG_FACTORY_RESET)
288
289 commands.append(f"copy {filename} session-config")
290 res = await self._cli(commands=commands)
291 checks_re = re.compile(r"error|abort|invalid", flags=re.IGNORECASE)
292 messages = res[-1]["messages"]
293
294 if any(map(checks_re.search, messages)):
295 raise RuntimeError("".join(messages))
296
297 async def write(self) -> None:
298 """Save the running config to the startup config by issuing the command "write" to the device."""
299 await self._cli(command="write")