File: config_session.py

package info (click to toggle)
anta 1.7.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 8,048 kB
  • sloc: python: 48,164; sh: 28; javascript: 9; makefile: 4
file content (299 lines) | stat: -rw-r--r-- 10,130 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# Copyright (c) 2024-2025 Arista Networks, Inc.
# Use of this source code is governed by the Apache License 2.0
# that can be found in the LICENSE file.
# Initially written by Jeremy Schulman at https://github.com/jeremyschulman/aio-eapi
"""asynceapi.SessionConfig definition."""

# -----------------------------------------------------------------------------
# System Imports
# -----------------------------------------------------------------------------
from __future__ import annotations

import re
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from ._types import EapiComplexCommand, EapiJsonOutput, EapiSimpleCommand
    from .device import Device

# -----------------------------------------------------------------------------
# Exports
# -----------------------------------------------------------------------------

__all__ = ["SessionConfig"]

# -----------------------------------------------------------------------------
#
#                                 CODE BEGINS
#
# -----------------------------------------------------------------------------


class SessionConfig:
    """Send configuration to a device using the EOS session mechanism.

    This is the preferred way of managing configuration changes.

    Notes
    -----
        This class definition is used by the parent Device class definition as
        defined by `config_session`. A Caller can use the SessionConfig directly
        as well, but it is not required.
    """

    CLI_CFG_FACTORY_RESET = "rollback clean-config"

    def __init__(self, device: Device, name: str) -> None:
        """Create a new instance of SessionConfig.

        The session config instance bound
        to the given device instance, and using the session `name`.

        Parameters
        ----------
        device
            The associated device instance.
        name
            The name of the config session.
        """
        self._device = device
        self._cli = device.cli
        self._name = name
        self._cli_config_session = f"configure session {self.name}"

    # -------------------------------------------------------------------------
    # properties for read-only attributes
    # -------------------------------------------------------------------------

    @property
    def name(self) -> str:
        """Return read-only session name attribute."""
        return self._name

    @property
    def device(self) -> Device:
        """Return read-only device instance attribute."""
        return self._device

    # -------------------------------------------------------------------------
    #                               Public Methods
    # -------------------------------------------------------------------------

    async def status_all(self) -> EapiJsonOutput:
        """Get the status of all the session config on the device.

        Run the following command on the device:
            # show configuration sessions detail

        Returns
        -------
        EapiJsonOutput
            Dictionary of native EOS eAPI response; see `status` method for
            details.

        Examples
        --------
        Return example:

        ```
        {
            "maxSavedSessions": 1,
            "maxOpenSessions": 5,
            "sessions": {
                "jeremy1": {
                    "instances": {},
                    "state": "pending",
                    "commitUser": "",
                    "description": ""
                },
                "ansible_167510439362": {
                    "instances": {},
                    "state": "completed",
                    "commitUser": "joe.bob",
                    "description": "",
                    "completedTime": 1675104396.4500246
                }
            }
        }
        ```
        """
        return await self._cli(command="show configuration sessions detail")

    async def status(self) -> EapiJsonOutput | None:
        """Get the status of a session config on the device.

        Run the following command on the device:
            # show configuration sessions detail

        And return only the status dictionary for this session. If you want
        all sessions, then use the `status_all` method.

        Returns
        -------
        EapiJsonOutput | None
            Dictionary instance of the session status. If the session does not exist,
            then this method will return None.

        Examples
        --------
        The return is the native eAPI results from JSON output:

        ```
        all results:
            {
                "maxSavedSessions": 1,
                "maxOpenSessions": 5,
                "sessions": {
                    "jeremy1": {
                        "instances": {},
                        "state": "pending",
                        "commitUser": "",
                        "description": ""
                    },
                    "ansible_167510439362": {
                        "instances": {},
                        "state": "completed",
                        "commitUser": "joe.bob",
                        "description": "",
                        "completedTime": 1675104396.4500246
                    }
                }
            }
        ```

        If the session name was 'jeremy1', then this method would return:

        ```
        {
            "instances": {},
            "state": "pending",
            "commitUser": "",
            "description": ""
        }
        ```
        """
        res = await self.status_all()
        return res["sessions"].get(self.name)

    async def push(self, content: list[str] | str, *, replace: bool = False) -> None:
        """Send the configuration content to the device.

        If `replace` is true, then the command "rollback clean-config" is issued
        before sending the configuration content.

        Parameters
        ----------
        content
            The text configuration CLI commands, as a list of strings, that
            will be sent to the device.  If the parameter is a string, and not
            a list, then split the string across linebreaks.  In either case
            any empty lines will be discarded before they are send to the
            device.
        replace
            When True, the content will replace the existing configuration
            on the device.
        """
        # if given s string, we need to break it up into individual command
        # lines.

        if isinstance(content, str):
            content = content.splitlines()

        # prepare the initial set of command to enter the config session and
        # rollback clean if the `replace` argument is True.

        commands: list[EapiSimpleCommand | EapiComplexCommand] = [self._cli_config_session]
        if replace:
            commands.append(self.CLI_CFG_FACTORY_RESET)

        # add the Caller's commands, filtering out any blank lines. any command
        # lines (!) are still included.

        commands.extend(filter(None, content))

        await self._cli(commands=commands)

    async def commit(self, timer: str | None = None) -> None:
        """Commit the session config.

        Run the following command on the device:
            # configure session <name>
            # commit

        Parameters
        ----------
        timer
            If the timer is specified, format is "hh:mm:ss", then a commit timer is
            started.  A second commit action must be made to confirm the config
            session before the timer expires; otherwise the config-session is
            automatically aborted.
        """
        command = f"{self._cli_config_session} commit"

        if timer:
            command += f" timer {timer}"

        await self._cli(command=command)

    async def abort(self) -> None:
        """Abort the configuration session.

        Run the following command on the device:
            # configure session <name> abort
        """
        await self._cli(command=f"{self._cli_config_session} abort")

    async def diff(self) -> str:
        """Return the "diff" of the session config relative to the running config.

        Run the following command on the device:
            # show session-config named <name> diffs

        Returns
        -------
        str
            Return a string in diff-patch format.

        References
        ----------
            * https://www.gnu.org/software/diffutils/manual/diffutils.txt
        """
        return await self._cli(command=f"show session-config named {self.name} diffs", ofmt="text")

    async def load_file(self, filename: str, *, replace: bool = False) -> None:
        """Load the configuration from <filename> into the session configuration.

        If the replace parameter is True then the file contents will replace the existing session config (load-replace).

        Parameters
        ----------
        filename
            The name of the configuration file.  The caller is required to
            specify the filesystem, for example, the
            filename="flash:thisfile.cfg".

        replace
            When True, the contents of the file will completely replace the
            session config for a load-replace behavior.

        Raises
        ------
        RuntimeError
            If there are any issues with loading the configuration file then a
            RuntimeError is raised with the error messages content.
        """
        commands: list[EapiSimpleCommand | EapiComplexCommand] = [self._cli_config_session]
        if replace:
            commands.append(self.CLI_CFG_FACTORY_RESET)

        commands.append(f"copy {filename} session-config")
        res = await self._cli(commands=commands)
        checks_re = re.compile(r"error|abort|invalid", flags=re.IGNORECASE)
        messages = res[-1]["messages"]

        if any(map(checks_re.search, messages)):
            raise RuntimeError("".join(messages))

    async def write(self) -> None:
        """Save the running config to the startup config by issuing the command "write" to the device."""
        await self._cli(command="write")