1 | # py312 |
2 | # requirements: |
3 | # paramiko==5.1.0 |
4 | # pyeapi==1.0.4 |
5 | # wmill==1.851.0 |
6 |
|
7 | # Device commit: write memory once the upgrade passed its post-check. Refused while a config session's commit timer is |
8 | # pending, so a change about to roll back isn't saved. The previous image stays on flash for a later rollback; |
9 | # delete_old_images removes only the other EOS images. |
10 |
|
11 | import base64 |
12 | import hashlib |
13 | import json |
14 | import logging |
15 | import os |
16 | import re |
17 | import socket |
18 | import ssl |
19 | import time |
20 | from typing import TypedDict |
21 | from urllib.parse import urlsplit |
22 |
|
23 | import paramiko |
24 | import pyeapi |
25 | import wmill |
26 |
|
27 |
|
28 | class arista_eos(TypedDict): |
29 | host: str |
30 | username: str |
31 | password: str |
32 | port: int |
33 | verify_tls: bool |
34 | allow_http: bool |
35 |
|
36 |
|
37 | def main(auth: arista_eos, host: str = "", delete_old_images: bool = False): |
38 | """ |
39 | Device commit |
40 | Save the upgraded switch's config (write memory), refused while a config-session commit timer is pending. Keeps the previous image on flash; delete_old_images removes the other EOS images. Returns { saved, deleted }. Raises DeviceUnreachable or AuthFailure. Higher-level and opinionated (checks, snapshot comparison and reload-once state in the flow run); to build your own upgrade logic, use Get Facts, Get Flash, Get Boot Config, Copy Image, Set Boot Image, Reload and Delete File. |
41 | """ |
42 | auth = with_host(auth, host) |
43 | state = load_state(state_keys(auth)) or {} |
44 | [sessions] = eapi(auth, ["show configuration sessions detail"]) |
45 | if sessions.get("commitTimerSessionName"): |
46 | raise RuntimeError( |
47 | f"config session {sessions['commitTimerSessionName']} is pending under a commit timer: confirm or abort it before commit (write memory)" |
48 | ) |
49 | _, boot, d = eapi( |
50 | auth, |
51 | ["write memory", "show boot-config", {"cmd": "dir flash:/", "revision": 2}], |
52 | ) |
53 | deleted = [] |
54 | # Rollback needs the previous image: only images that are neither booted nor the recorded previous one go. |
55 | if delete_old_images and state.get("previous_image"): |
56 | keep = [ |
57 | i.replace("flash:/", "") |
58 | for i in (boot["softwareImage"], state["previous_image"]) |
59 | ] |
60 | for f in list(d["urls"]["flash:/"]["entries"]): |
61 | if re.match(r"^EOS.*\.swi$", f) and f not in keep: |
62 | eapi(auth, [f"delete flash:{f}"]) |
63 | deleted.append(f) |
64 | return {"saved": True, "deleted": deleted} |
65 |
|
66 |
|
67 | # One resource can serve every switch that shares a login: the host input, when set, overrides the resource's host. |
68 | def with_host(auth: arista_eos, host: str): |
69 | host = (host or "").strip() or (auth.get("host") or "").strip() |
70 | if not host: |
71 | raise ValueError("host is required: set it on the resource or pass host") |
72 | return {**auth, "host": host} |
73 |
|
74 |
|
75 | # Errors the workflow branches and retries on (retry_if: result.error.name == "DeviceUnreachable"). |
76 | class DeviceUnreachable(Exception): |
77 | pass |
78 |
|
79 |
|
80 | class AuthFailure(Exception): |
81 | pass |
82 |
|
83 |
|
84 | # pyeapi logs a traceback for every socket error, and a rebooting switch gives many. |
85 | logging.getLogger("pyeapi").addHandler(logging.NullHandler()) |
86 |
|
87 |
|
88 | def eapi(auth: arista_eos, cmds: list, fmt: str = "json", timeout: float = 60): |
89 | eos = node(auth, timeout) |
90 | try: |
91 | return eos.run_commands(cmds, fmt) |
92 | except pyeapi.eapilib.ConnectionError as e: |
93 | raise connection_error(auth, eos, e) |
94 |
|
95 |
|
96 | # pyeapi 1.0.4 raises ConnectionError for a socket error (kept in socket_error), an answer that isn't JSON (eAPI |
97 | # still starting, 5xx) and a 401, the only one with neither. |
98 | def connection_error(auth, eos, e): |
99 | # A certificate the resource does not trust is a setting to fix (verify_tls, ca_certificate), not worth a retry. |
100 | if isinstance(eos.connection.socket_error, ssl.SSLCertVerificationError): |
101 | return RuntimeError(f"{auth['host']}: {eos.connection.socket_error}") |
102 | if eos.connection.socket_error is None and e.message != "unable to connect to eAPI": |
103 | return AuthFailure(f"{auth['host']}: {'SSH' if auth.get('transport') == 'ssh' else 'eAPI'} refused the credential ({e.message})") |
104 | return DeviceUnreachable(f"{auth['host']}: {e.message}") |
105 |
|
106 |
|
107 | # host is an address or a URL (https: |
108 | # resource ticks allow_http (Basic auth then crosses the network in cleartext). pyeapi skips certificate checks unless it |
109 | # is given a context, so one is always passed: verifying, or not when the resource unticks verify_tls (EOS ships a |
110 | # self-signed cert). |
111 | def switch_url(auth: arista_eos): |
112 | host = auth["host"] |
113 | if "://" not in host: |
114 | host = ( |
115 | f"https://[{host}]" |
116 | if host.count(":") > 1 and "[" not in host |
117 | else f"https://{host}" |
118 | ) |
119 | url = urlsplit(host) |
120 | if not url.hostname or ( |
121 | url.scheme != "https" and not (url.scheme == "http" and auth.get("allow_http")) |
122 | ): |
123 | raise ValueError( |
124 | f"host must be an address or an https:// URL (http:// needs allow_http on the resource): {auth['host']}" |
125 | ) |
126 | return url |
127 |
|
128 |
|
129 | # SSH transport (transport: ssh): the EOS CLI over an SSH shell, behind the part of pyeapi's Node the scripts use |
130 | # (run_commands, connection.socket_error, connection.transport.connect), raising pyeapi's own CommandError and |
131 | # ConnectionError, so the checks and the error mapping are the same for both transports. Show commands in json get |
132 | # "| json", which prints the eAPI JSON; other commands give { messages: [output] } like eAPI, or {} when silent. |
133 | # A line starting with "% " is an error, raised as eAPI's CommandError. The host key is checked when the resource |
134 | # has ssh_host_key (SHA256:... as ssh-keygen -lf prints it). |
135 | class Ssh: |
136 | def __init__(self, auth: arista_eos, timeout: float): |
137 | self.auth, self.timeout = auth, timeout |
138 | self.connection = self.transport = self |
139 | self.socket_error = self.sock = self.chan = None |
140 |
|
141 | # The TCP connection only, like eAPI's transport.connect(): if it fails, nothing was sent. |
142 | def connect(self): |
143 | self.sock = socket.create_connection(ssh_addr(self.auth), self.timeout) |
144 |
|
145 | def lost(self, e): |
146 | self.socket_error = e |
147 | return pyeapi.eapilib.ConnectionError("ssh", f"SSH connection failed ({e})") |
148 |
|
149 | def open(self): |
150 | auth = self.auth |
151 | try: |
152 | if not self.sock: |
153 | self.connect() |
154 | t = paramiko.Transport(self.sock) |
155 | t.start_client(timeout=self.timeout) |
156 | key = t.get_remote_server_key() |
157 | except (OSError, EOFError, paramiko.SSHException) as e: |
158 | raise self.lost(e) |
159 | fp = "SHA256:" + base64.b64encode(hashlib.sha256(key.asbytes()).digest()).decode().rstrip("=") |
160 | if auth.get("ssh_host_key") and auth["ssh_host_key"].strip() != fp: |
161 | t.close() |
162 | raise RuntimeError(f"{auth['host']}: the SSH host key is {fp}, not the resource's ssh_host_key") |
163 | try: |
164 | try: |
165 | t.auth_password(auth["username"], auth["password"]) |
166 | except paramiko.BadAuthenticationType: |
167 | t.auth_interactive( |
168 | auth["username"], lambda _t, _i, prompts: [auth["password"]] * len(prompts) |
169 | ) |
170 | except paramiko.AuthenticationException as e: |
171 | t.close() |
172 | raise pyeapi.eapilib.ConnectionError("ssh", str(e)) |
173 | except (OSError, EOFError, paramiko.SSHException) as e: |
174 | raise self.lost(e) |
175 | try: |
176 | self.chan = t.open_session() |
177 | self.chan.get_pty(width=4000) |
178 | self.chan.invoke_shell() |
179 | self.prompt = None |
180 | out = self.read() |
181 | self.prompt = re.escape(re.split(r"[(>#]", out.splitlines()[-1].strip())[0]) |
182 | if out.rstrip().endswith(">"): |
183 | self.cli("enable") |
184 | self.cli("terminal length 0") |
185 | self.cli("terminal width 32767") |
186 | except (OSError, EOFError, paramiko.SSHException) as e: |
187 | raise self.lost(e) |
188 |
|
189 | # Reads until the prompt. Questions eAPI never asks are answered as eAPI behaves: confirm, don't save. |
190 | def read(self): |
191 | buf, end = "", time.monotonic() + self.timeout |
192 | prompt = (self.prompt or r"[\w.\-]+") + r"(\([^)\r\n]*\))?[>#] ?$" |
193 | while True: |
194 | self.chan.settimeout(max(end - time.monotonic(), 0.01)) |
195 | chunk = self.chan.recv(65536) |
196 | if not chunk: |
197 | raise self.lost("connection closed") |
198 | buf += chunk.decode(errors="replace") |
199 | tail = buf[-300:] |
200 | if re.search(r"(^|\n)" + prompt, tail): |
201 | return buf |
202 | for question, answer in ( |
203 | # enable asks for a password on switches that land the user unprivileged: the login password. |
204 | (r"(^|\n)Password:\s*$", self.auth["password"]), |
205 | (r"\[confirm\]\s*$", ""), |
206 | (r"Save\?.*\[yes/no[^\]]*\]:?\s*$", "no"), |
207 | (r"\[(y|yes)/(n|no)\][:?]?\s*$", "y"), |
208 | ): |
209 | if re.search(question, tail, re.I): |
210 | self.chan.send(answer + "\r") |
211 | buf += "\n" |
212 |
|
213 | # One command: its output without the echoed command and the prompt; progress lines keep their last state. |
214 | def cli(self, cmd): |
215 | try: |
216 | self.chan.send(cmd + "\r") |
217 | out = self.read() |
218 | except (OSError, EOFError, paramiko.SSHException) as e: |
219 | raise self.lost(e) |
220 | self.mode = out.rstrip().splitlines()[-1] |
221 | lines = [l.rstrip("\r").split("\r")[-1] for l in out.split("\n")] |
222 | return "\n".join(lines[1:-1]).strip("\n") |
223 |
|
224 | def run_commands(self, cmds, encoding="json", **_): |
225 | try: |
226 | if not self.chan: |
227 | self.open() |
228 | if "(config" in self.mode: |
229 | self.cli("end") |
230 | results = [] |
231 | for i, c in enumerate(cmds): |
232 | # eAPI's { cmd, revision } form is the CLI's "| json revision N". |
233 | cmd, rev = (c["cmd"], c.get("revision")) if isinstance(c, dict) else (c, None) |
234 | show = encoding == "json" and (rev or re.match(r"\s*sh(ow)?\s", cmd)) and not re.search(r"\|\s*json", cmd) |
235 | # pyeapi sends "<cmd> MULTILINE: <text>" (banners) as cmd + input; the CLI reads the text up to EOF. |
236 | head, multi, text = cmd.partition("MULTILINE:") |
237 | # The shell would run what follows a line break as another command; eAPI refuses it too. |
238 | if re.search(r"[\r\n]", head): |
239 | raise ValueError(f"a command may not contain a line break: {head!r}") |
240 | line = "\r".join([head.strip(), *text.strip().splitlines(), "EOF"]) if multi else cmd |
241 | out = self.cli(f"{cmd} | json{f' revision {rev}' if rev else ''}" if show else line) |
242 | errors = [l[2:] for l in out.splitlines() if l.startswith("% ")] |
243 | code, kind = 1002, "invalid command" |
244 | if show and not errors: |
245 | code, kind = 1000, "could not run command" |
246 | try: |
247 | result = json.loads(out) |
248 | except ValueError: |
249 | errors = [out[:200]] |
250 | else: |
251 | errors = result.get("errors") or [] |
252 | if errors: |
253 | raise pyeapi.eapilib.CommandError( |
254 | code, |
255 | f"CLI command {i + 2} of {len(cmds) + 1} '{cmd}' failed: {kind}", |
256 | command_error="; ".join(errors), |
257 | commands=cmds, |
258 | output=results, |
259 | ) |
260 | if encoding != "json": |
261 | result = {"output": out + "\n" if out else ""} |
262 | elif not show: |
263 | # The CLI prints eAPI's warnings as "! " notices. |
264 | notices = [l[2:].strip() for l in out.splitlines() if l.startswith("! ")] |
265 | out = "\n".join(l for l in out.splitlines() if not l.startswith("! ")).strip() |
266 | result = {"messages": [out]} if out and not multi else {} |
267 | if notices: |
268 | result["warnings"] = notices |
269 | results.append(result) |
270 | return results |
271 | except pyeapi.eapilib.ConnectionError: |
272 | if self.chan: |
273 | self.chan.close() |
274 | self.sock = self.chan = None |
275 | raise |
276 |
|
277 |
|
278 | # paramiko logs a traceback when a rebooting switch drops the session. |
279 | logging.getLogger("paramiko").addHandler(logging.NullHandler()) |
280 |
|
281 |
|
282 | # host, or host:port ([v6]:port), else port, else 22. |
283 | def ssh_addr(auth: arista_eos): |
284 | h = auth["host"] |
285 | if "://" in h: |
286 | raise ValueError(f"with transport ssh, host is an address or a hostname (with :port), not a URL: {h}") |
287 | url = urlsplit(f"ssh://{h}" if h.count(":") <= 1 or h.startswith("[") else f"ssh://[{h}]") |
288 | return url.hostname, url.port or int(auth.get("port") or 22) |
289 |
|
290 |
|
291 | def node(auth: arista_eos, timeout: float = 60): |
292 | if auth.get("transport") == "ssh": |
293 | return Ssh(auth, timeout) |
294 | url = switch_url(auth) |
295 | # ca_certificate: the PEM of a private CA, trusted instead of the system's CAs. |
296 | context = ssl.create_default_context(cadata=(auth.get("ca_certificate") or "").strip() or None) |
297 | if auth.get("verify_tls") is False: |
298 | context.check_hostname = False |
299 | context.verify_mode = ssl.CERT_NONE |
300 | return pyeapi.connect( |
301 | transport=url.scheme, |
302 | host=url.hostname, |
303 | port=url.port or auth.get("port") or None, |
304 | username=auth["username"], |
305 | password=auth["password"], |
306 | context=context, |
307 | timeout=timeout, |
308 | return_node=True, |
309 | ) |
310 |
|
311 |
|
312 | # Shared by the Device scripts: the root flow run's user state, keyed by switch, holds the pre-check snapshot, the |
313 | # image activate replaced (rollback target), the image it booted and the reload markers. Every step of the run (nested |
314 | # subflows and retried attempts included) reads the same entry. Outside a flow the Device scripts share one state |
315 | # resource in the running user's home (a script's own state would keep the pre-check snapshot from the post-check). |
316 | # The endpoint is called through the client so an unreachable state raises (wmill.get_flow_user_state returns None). |
317 | # ponytail: the fallback is one map per user, so concurrent standalone runs can race; flows don't. |
318 | # The key is the switch's eAPI address: arista_eos-<host>-<port> with non-word characters in the host as _, the port |
319 | # always in (443 or 80 when unset). State written before the port was part of the key is read from arista_eos_<host> |
320 | # as a fallback (all word characters, so never a new key); writes go to the new key only. |
321 | def state_keys(auth: arista_eos): |
322 | if auth.get("transport") == "ssh": |
323 | host, port = ssh_addr(auth) |
324 | return [f"arista_eos-{word(host)}-{port}"] |
325 | url = switch_url(auth) |
326 | port = int(url.port or auth.get("port") or {"https": 443, "http": 80}[url.scheme]) |
327 | return [ |
328 | f"arista_eos-{word(url.hostname)}-{port}", |
329 | f"arista_eos_{word(auth['host'])}", |
330 | ] |
331 |
|
332 |
|
333 | def word(s): |
334 | return re.sub(r"\W", "_", s) |
335 |
|
336 |
|
337 | def load_state(keys): |
338 | for key in keys: |
339 | if os.environ.get("WM_FLOW_JOB_ID"): |
340 | c = wmill.Windmill() |
341 | value = c.get( |
342 | f"/w/{c.workspace}/jobs/flow/user_states/{c.get_root_job_id()}/{key}" |
343 | ).json() |
344 | else: |
345 | value = (wmill.get_state(standalone_state()) or {}).get(key) |
346 | if value is not None: |
347 | return value |
348 |
|
349 |
|
350 | def save_state(keys, value): |
351 | if os.environ.get("WM_FLOW_JOB_ID"): |
352 | c = wmill.Windmill() |
353 | c.post( |
354 | f"/w/{c.workspace}/jobs/flow/user_states/{c.get_root_job_id()}/{keys[0]}", |
355 | json=value, |
356 | ) |
357 | else: |
358 | path = standalone_state() |
359 | wmill.set_state({**(wmill.get_state(path) or {}), keys[0]: value}, path) |
360 |
|
361 |
|
362 | def standalone_state(): |
363 | return f"u/{os.environ['WM_USERNAME']}/arista_eos_state" |
364 |
|
365 |
|
366 | # "4.34.9M-51132493.4349M (engineering build)" on cEOS, "4.34.9M" on hardware. |
367 | def short_version(v): |
368 | m = re.match(r"\d+\.\d+\.\d+(\.\d+)?[A-Z]*", v) |
369 | return m.group(0) if m else v |
370 |
|