1 | # py312 |
2 | # requirements: |
3 | # paramiko==5.1.0 |
4 | # pyeapi==1.0.4 |
5 | # wmill==1.851.0 |
6 |
|
7 | # Device reload: reload now, at most once per switch and flow run, so a retried step never reboots it twice. |
8 | # Skipped (reloaded false, with the reason) when this run already sent it, the switch already runs target_version, or |
9 | # it rebooted less than min_uptime_seconds ago. boot-config must be the image Device activate set in this run, or |
10 | # flash:/EOS-<target_version>.swi. ReloadRefused while show running-config diffs changes anything but its ! headers, |
11 | # or there is no startup-config (reload now doesn't prompt, so unsaved changes would be lost), unless allow_unsaved. |
12 | # Reload markers are the root flow run's user state under arista_eos-<host>-<port>; Get Reload Delay and Device |
13 | # post-check read them to tell the new boot from the old one. |
14 |
|
15 | import base64 |
16 | import hashlib |
17 | import json |
18 | import logging |
19 | import os |
20 | import re |
21 | import socket |
22 | import ssl |
23 | import time |
24 | from typing import TypedDict |
25 | from urllib.parse import urlsplit |
26 |
|
27 | import paramiko |
28 | import pyeapi |
29 | import wmill |
30 |
|
31 |
|
32 | class arista_eos(TypedDict): |
33 | host: str |
34 | username: str |
35 | password: str |
36 | port: int |
37 | verify_tls: bool |
38 | allow_http: bool |
39 |
|
40 |
|
41 | class ReloadRefused(Exception): |
42 | pass |
43 |
|
44 |
|
45 | def main( |
46 | auth: arista_eos, |
47 | target_version: str, |
48 | host: str = "", |
49 | min_uptime_seconds: int = 300, |
50 | allow_unsaved: bool = False, |
51 | ): |
52 | """ |
53 | Device reload |
54 | Reload the switch onto the image Device activate set: exactly once per flow run (a retry skips it), refused with unsaved config unless allow_unsaved. Returns { reloaded, reason } (why it skipped, null when it reloaded). Raises ReloadRefused (unsaved config, boot-config not the activated image), DeviceUnreachable or AuthFailure. Follow it with Get Reload Delay. 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. |
55 | """ |
56 | auth = with_host(auth, host) |
57 | key = state_keys(auth) |
58 | state = load_state(key) or {} |
59 | min_uptime = 300 if min_uptime_seconds is None else min_uptime_seconds |
60 | if not target_version: |
61 | raise ReloadRefused("target_version is required for the reload guard") |
62 | sw = read_switch(auth, state, min_uptime) |
63 | sent = sw["marker"]("reload") |
64 | if sw.get("unreachable"): |
65 | if sent: |
66 | return skip( |
67 | f"reload sent at {sent['sent_at']}; the switch no longer answers: it is reloading" |
68 | ) |
69 | raise DeviceUnreachable(sw["unreachable"]) |
70 | if sent and (sent["confirmed"] or sent["boot_timestamp"] != sw["boot"]): |
71 | return skip(guard_reason("reload", sent, sw)) |
72 | if sw["running"] == target_version: |
73 | return skip(f"already running {target_version}") |
74 | # The image activate set in this run (state), or exactly EOS-<target_version>.swi. |
75 | activated = state.get("activated_image") |
76 | if sw["image"] not in (activated, f"flash:/EOS-{target_version}.swi"): |
77 | raise ReloadRefused( |
78 | f"boot-config points to {sw['image']}, neither the image activate set ({activated or 'none in this run'}) nor flash:/EOS-{target_version}.swi: run Device activate first" |
79 | ) |
80 | if sw["uptime"] < min_uptime: |
81 | return skip(f"rebooted {round(sw['uptime'])} s ago") |
82 | if not allow_unsaved and unsaved(auth): |
83 | raise ReloadRefused( |
84 | "unsaved config: run Save Config first, or pass allow_unsaved: true" |
85 | ) |
86 | fire_reload(auth, key, "reload", sw["boot"]) |
87 | return {"reloaded": True, "reason": None} |
88 |
|
89 |
|
90 | # One resource can serve every switch that shares a login: the host input, when set, overrides the resource's host. |
91 | def with_host(auth: arista_eos, host: str): |
92 | host = (host or "").strip() or (auth.get("host") or "").strip() |
93 | if not host: |
94 | raise ValueError("host is required: set it on the resource or pass host") |
95 | return {**auth, "host": host} |
96 |
|
97 |
|
98 | # reload now doesn't prompt to save. show running-config diffs is a unified diff of startup-config against |
99 | # running-config, empty when they match. Its two file-header lines come before the first @@. Changed lines that |
100 | # start with a single "!" are headers EOS writes itself (boot system shows there, so every activate changes one); |
101 | # "!!" comments are config. With no startup-config every line shows as added: unsaved, it would boot into ZTP. |
102 | # A refused command (AAA authorization, an older EOS) is not unsaved config: saving wouldn't clear it. |
103 | def unsaved(auth): |
104 | try: |
105 | [d] = eapi(auth, ["show running-config diffs"], "text") |
106 | except pyeapi.eapilib.CommandError as e: |
107 | raise ReloadRefused(f"cannot compare running and startup config: {e}") |
108 | hunks, changed = False, [] |
109 | for l in d["output"].splitlines(): |
110 | hunks = hunks or l.startswith("@@") |
111 | if hunks and l[:1] in ("+", "-") and l[1:].strip(): |
112 | changed.append(l[1:].strip()) |
113 | return any(not re.match(r"!(?!!)", l) for l in changed) |
114 |
|
115 |
|
116 | def skip(reason): |
117 | return {"reloaded": False, "reason": reason} |
118 |
|
119 |
|
120 | def guard_reason(kind, m, sw): |
121 | if m["boot_timestamp"] == sw["boot"]: |
122 | return f"{kind} sent at {m['sent_at']}; the switch is going down" |
123 | return f"{kind} sent at {m['sent_at']} already rebooted the switch" |
124 |
|
125 |
|
126 | # A reload is sent at most once per switch and flow run. Each one leaves a marker { sent_at, boot_timestamp, |
127 | # confirmed }: boot_timestamp is the boot it was sent on, so a later boot means it happened, and confirmed means |
128 | # the command reached the switch. An unconfirmed marker on the same boot (the worker died first) is sent again. |
129 | # Outside a flow, a marker is dropped once the reboot it caused is min_uptime_seconds old. |
130 | def read_switch(auth, state, min_uptime): |
131 | try: |
132 | version, boot = eapi(auth, ["show version", "show boot-config"]) |
133 | except DeviceUnreachable as e: |
134 | return {"unreachable": str(e), "marker": lambda k: state.get(k)} |
135 | sw = { |
136 | "running": short_version(version["version"]), |
137 | "image": boot["softwareImage"], |
138 | "boot": version["bootupTimestamp"], |
139 | "uptime": version["uptime"], |
140 | } |
141 | in_flow = bool(os.environ.get("WM_FLOW_JOB_ID")) |
142 |
|
143 | def marker(k): |
144 | m = state.get(k) |
145 | return ( |
146 | m |
147 | if m |
148 | and ( |
149 | in_flow |
150 | or m["boot_timestamp"] == sw["boot"] |
151 | or sw["uptime"] < min_uptime |
152 | ) |
153 | else None |
154 | ) |
155 |
|
156 | return {**sw, "marker": marker} |
157 |
|
158 |
|
159 | # Fire and forget: the switch drops the connection while going down, which is not an error. A connection that |
160 | # never opened, or a refusal from the switch, means it did not reload: the marker goes and the error is raised. |
161 | def fire_reload(auth, key, kind, boot_ts): |
162 | def mark(m): |
163 | rest = {k: v for k, v in (load_state(key) or {}).items() if k != kind} |
164 | save_state(key, {**rest, kind: m} if m else rest) |
165 |
|
166 | m = { |
167 | "sent_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), |
168 | "boot_timestamp": boot_ts, |
169 | "confirmed": False, |
170 | } |
171 | mark(m) |
172 | eos = node(auth, 15) |
173 | try: |
174 | # Opened before sending, so a failure here means the command never left. |
175 | eos.connection.transport.connect() |
176 | except OSError as e: |
177 | mark(None) |
178 | raise DeviceUnreachable(f"{auth['host']}: {e}") |
179 | try: |
180 | eos.run_commands(["reload now"]) |
181 | except pyeapi.eapilib.ConnectionError as e: |
182 | # Sent, then the connection dropped or timed out as the switch went down. A 401 is a refusal. |
183 | err = connection_error(auth, eos, e) |
184 | if isinstance(err, AuthFailure): |
185 | mark(None) |
186 | raise err |
187 | except Exception: |
188 | mark(None) |
189 | raise |
190 | mark({**m, "confirmed": True}) |
191 |
|
192 |
|
193 | # Errors the workflow branches and retries on (retry_if: result.error.name == "DeviceUnreachable"). |
194 | class DeviceUnreachable(Exception): |
195 | pass |
196 |
|
197 |
|
198 | class AuthFailure(Exception): |
199 | pass |
200 |
|
201 |
|
202 | # pyeapi logs a traceback for every socket error, and a rebooting switch gives many. |
203 | logging.getLogger("pyeapi").addHandler(logging.NullHandler()) |
204 |
|
205 |
|
206 | def eapi(auth: arista_eos, cmds: list, fmt: str = "json", timeout: float = 60): |
207 | eos = node(auth, timeout) |
208 | try: |
209 | return eos.run_commands(cmds, fmt) |
210 | except pyeapi.eapilib.ConnectionError as e: |
211 | raise connection_error(auth, eos, e) |
212 |
|
213 |
|
214 | # pyeapi 1.0.4 raises ConnectionError for a socket error (kept in socket_error), an answer that isn't JSON (eAPI |
215 | # still starting, 5xx) and a 401, the only one with neither. |
216 | def connection_error(auth, eos, e): |
217 | # A certificate the resource does not trust is a setting to fix (verify_tls, ca_certificate), not worth a retry. |
218 | if isinstance(eos.connection.socket_error, ssl.SSLCertVerificationError): |
219 | return RuntimeError(f"{auth['host']}: {eos.connection.socket_error}") |
220 | if eos.connection.socket_error is None and e.message != "unable to connect to eAPI": |
221 | return AuthFailure(f"{auth['host']}: {'SSH' if auth.get('transport') == 'ssh' else 'eAPI'} refused the credential ({e.message})") |
222 | return DeviceUnreachable(f"{auth['host']}: {e.message}") |
223 |
|
224 |
|
225 | # host is an address or a URL (https: |
226 | # resource ticks allow_http (Basic auth then crosses the network in cleartext). pyeapi skips certificate checks unless it |
227 | # is given a context, so one is always passed: verifying, or not when the resource unticks verify_tls (EOS ships a |
228 | # self-signed cert). |
229 | def switch_url(auth: arista_eos): |
230 | host = auth["host"] |
231 | if "://" not in host: |
232 | host = ( |
233 | f"https://[{host}]" |
234 | if host.count(":") > 1 and "[" not in host |
235 | else f"https://{host}" |
236 | ) |
237 | url = urlsplit(host) |
238 | if not url.hostname or ( |
239 | url.scheme != "https" and not (url.scheme == "http" and auth.get("allow_http")) |
240 | ): |
241 | raise ValueError( |
242 | f"host must be an address or an https:// URL (http:// needs allow_http on the resource): {auth['host']}" |
243 | ) |
244 | return url |
245 |
|
246 |
|
247 | # SSH transport (transport: ssh): the EOS CLI over an SSH shell, behind the part of pyeapi's Node the scripts use |
248 | # (run_commands, connection.socket_error, connection.transport.connect), raising pyeapi's own CommandError and |
249 | # ConnectionError, so the checks and the error mapping are the same for both transports. Show commands in json get |
250 | # "| json", which prints the eAPI JSON; other commands give { messages: [output] } like eAPI, or {} when silent. |
251 | # A line starting with "% " is an error, raised as eAPI's CommandError. The host key is checked when the resource |
252 | # has ssh_host_key (SHA256:... as ssh-keygen -lf prints it). |
253 | class Ssh: |
254 | def __init__(self, auth: arista_eos, timeout: float): |
255 | self.auth, self.timeout = auth, timeout |
256 | self.connection = self.transport = self |
257 | self.socket_error = self.sock = self.chan = None |
258 |
|
259 | # The TCP connection only, like eAPI's transport.connect(): if it fails, nothing was sent. |
260 | def connect(self): |
261 | self.sock = socket.create_connection(ssh_addr(self.auth), self.timeout) |
262 |
|
263 | def lost(self, e): |
264 | self.socket_error = e |
265 | return pyeapi.eapilib.ConnectionError("ssh", f"SSH connection failed ({e})") |
266 |
|
267 | def open(self): |
268 | auth = self.auth |
269 | try: |
270 | if not self.sock: |
271 | self.connect() |
272 | t = paramiko.Transport(self.sock) |
273 | t.start_client(timeout=self.timeout) |
274 | key = t.get_remote_server_key() |
275 | except (OSError, EOFError, paramiko.SSHException) as e: |
276 | raise self.lost(e) |
277 | fp = "SHA256:" + base64.b64encode(hashlib.sha256(key.asbytes()).digest()).decode().rstrip("=") |
278 | if auth.get("ssh_host_key") and auth["ssh_host_key"].strip() != fp: |
279 | t.close() |
280 | raise RuntimeError(f"{auth['host']}: the SSH host key is {fp}, not the resource's ssh_host_key") |
281 | try: |
282 | try: |
283 | t.auth_password(auth["username"], auth["password"]) |
284 | except paramiko.BadAuthenticationType: |
285 | t.auth_interactive( |
286 | auth["username"], lambda _t, _i, prompts: [auth["password"]] * len(prompts) |
287 | ) |
288 | except paramiko.AuthenticationException as e: |
289 | t.close() |
290 | raise pyeapi.eapilib.ConnectionError("ssh", str(e)) |
291 | except (OSError, EOFError, paramiko.SSHException) as e: |
292 | raise self.lost(e) |
293 | try: |
294 | self.chan = t.open_session() |
295 | self.chan.get_pty(width=4000) |
296 | self.chan.invoke_shell() |
297 | self.prompt = None |
298 | out = self.read() |
299 | self.prompt = re.escape(re.split(r"[(>#]", out.splitlines()[-1].strip())[0]) |
300 | if out.rstrip().endswith(">"): |
301 | self.cli("enable") |
302 | self.cli("terminal length 0") |
303 | self.cli("terminal width 32767") |
304 | except (OSError, EOFError, paramiko.SSHException) as e: |
305 | raise self.lost(e) |
306 |
|
307 | # Reads until the prompt. Questions eAPI never asks are answered as eAPI behaves: confirm, don't save. |
308 | def read(self): |
309 | buf, end = "", time.monotonic() + self.timeout |
310 | prompt = (self.prompt or r"[\w.\-]+") + r"(\([^)\r\n]*\))?[>#] ?$" |
311 | while True: |
312 | self.chan.settimeout(max(end - time.monotonic(), 0.01)) |
313 | chunk = self.chan.recv(65536) |
314 | if not chunk: |
315 | raise self.lost("connection closed") |
316 | buf += chunk.decode(errors="replace") |
317 | tail = buf[-300:] |
318 | if re.search(r"(^|\n)" + prompt, tail): |
319 | return buf |
320 | for question, answer in ( |
321 | # enable asks for a password on switches that land the user unprivileged: the login password. |
322 | (r"(^|\n)Password:\s*$", self.auth["password"]), |
323 | (r"\[confirm\]\s*$", ""), |
324 | (r"Save\?.*\[yes/no[^\]]*\]:?\s*$", "no"), |
325 | (r"\[(y|yes)/(n|no)\][:?]?\s*$", "y"), |
326 | ): |
327 | if re.search(question, tail, re.I): |
328 | self.chan.send(answer + "\r") |
329 | buf += "\n" |
330 |
|
331 | # One command: its output without the echoed command and the prompt; progress lines keep their last state. |
332 | def cli(self, cmd): |
333 | try: |
334 | self.chan.send(cmd + "\r") |
335 | out = self.read() |
336 | except (OSError, EOFError, paramiko.SSHException) as e: |
337 | raise self.lost(e) |
338 | self.mode = out.rstrip().splitlines()[-1] |
339 | lines = [l.rstrip("\r").split("\r")[-1] for l in out.split("\n")] |
340 | return "\n".join(lines[1:-1]).strip("\n") |
341 |
|
342 | def run_commands(self, cmds, encoding="json", **_): |
343 | try: |
344 | if not self.chan: |
345 | self.open() |
346 | if "(config" in self.mode: |
347 | self.cli("end") |
348 | results = [] |
349 | for i, c in enumerate(cmds): |
350 | # eAPI's { cmd, revision } form is the CLI's "| json revision N". |
351 | cmd, rev = (c["cmd"], c.get("revision")) if isinstance(c, dict) else (c, None) |
352 | show = encoding == "json" and (rev or re.match(r"\s*sh(ow)?\s", cmd)) and not re.search(r"\|\s*json", cmd) |
353 | # pyeapi sends "<cmd> MULTILINE: <text>" (banners) as cmd + input; the CLI reads the text up to EOF. |
354 | head, multi, text = cmd.partition("MULTILINE:") |
355 | # The shell would run what follows a line break as another command; eAPI refuses it too. |
356 | if re.search(r"[\r\n]", head): |
357 | raise ValueError(f"a command may not contain a line break: {head!r}") |
358 | line = "\r".join([head.strip(), *text.strip().splitlines(), "EOF"]) if multi else cmd |
359 | out = self.cli(f"{cmd} | json{f' revision {rev}' if rev else ''}" if show else line) |
360 | errors = [l[2:] for l in out.splitlines() if l.startswith("% ")] |
361 | code, kind = 1002, "invalid command" |
362 | if show and not errors: |
363 | code, kind = 1000, "could not run command" |
364 | try: |
365 | result = json.loads(out) |
366 | except ValueError: |
367 | errors = [out[:200]] |
368 | else: |
369 | errors = result.get("errors") or [] |
370 | if errors: |
371 | raise pyeapi.eapilib.CommandError( |
372 | code, |
373 | f"CLI command {i + 2} of {len(cmds) + 1} '{cmd}' failed: {kind}", |
374 | command_error="; ".join(errors), |
375 | commands=cmds, |
376 | output=results, |
377 | ) |
378 | if encoding != "json": |
379 | result = {"output": out + "\n" if out else ""} |
380 | elif not show: |
381 | # The CLI prints eAPI's warnings as "! " notices. |
382 | notices = [l[2:].strip() for l in out.splitlines() if l.startswith("! ")] |
383 | out = "\n".join(l for l in out.splitlines() if not l.startswith("! ")).strip() |
384 | result = {"messages": [out]} if out and not multi else {} |
385 | if notices: |
386 | result["warnings"] = notices |
387 | results.append(result) |
388 | return results |
389 | except pyeapi.eapilib.ConnectionError: |
390 | if self.chan: |
391 | self.chan.close() |
392 | self.sock = self.chan = None |
393 | raise |
394 |
|
395 |
|
396 | # paramiko logs a traceback when a rebooting switch drops the session. |
397 | logging.getLogger("paramiko").addHandler(logging.NullHandler()) |
398 |
|
399 |
|
400 | # host, or host:port ([v6]:port), else port, else 22. |
401 | def ssh_addr(auth: arista_eos): |
402 | h = auth["host"] |
403 | if "://" in h: |
404 | raise ValueError(f"with transport ssh, host is an address or a hostname (with :port), not a URL: {h}") |
405 | url = urlsplit(f"ssh://{h}" if h.count(":") <= 1 or h.startswith("[") else f"ssh://[{h}]") |
406 | return url.hostname, url.port or int(auth.get("port") or 22) |
407 |
|
408 |
|
409 | def node(auth: arista_eos, timeout: float = 60): |
410 | if auth.get("transport") == "ssh": |
411 | return Ssh(auth, timeout) |
412 | url = switch_url(auth) |
413 | # ca_certificate: the PEM of a private CA, trusted instead of the system's CAs. |
414 | context = ssl.create_default_context(cadata=(auth.get("ca_certificate") or "").strip() or None) |
415 | if auth.get("verify_tls") is False: |
416 | context.check_hostname = False |
417 | context.verify_mode = ssl.CERT_NONE |
418 | return pyeapi.connect( |
419 | transport=url.scheme, |
420 | host=url.hostname, |
421 | port=url.port or auth.get("port") or None, |
422 | username=auth["username"], |
423 | password=auth["password"], |
424 | context=context, |
425 | timeout=timeout, |
426 | return_node=True, |
427 | ) |
428 |
|
429 |
|
430 | # Shared by the Device scripts: the root flow run's user state, keyed by switch, holds the pre-check snapshot, the |
431 | # image activate replaced (rollback target), the image it booted and the reload markers. Every step of the run (nested |
432 | # subflows and retried attempts included) reads the same entry. Outside a flow the Device scripts share one state |
433 | # resource in the running user's home (a script's own state would keep the pre-check snapshot from the post-check). |
434 | # The endpoint is called through the client so an unreachable state raises (wmill.get_flow_user_state returns None). |
435 | # ponytail: the fallback is one map per user, so concurrent standalone runs can race; flows don't. |
436 | # The key is the switch's eAPI address: arista_eos-<host>-<port> with non-word characters in the host as _, the port |
437 | # always in (443 or 80 when unset). State written before the port was part of the key is read from arista_eos_<host> |
438 | # as a fallback (all word characters, so never a new key); writes go to the new key only. |
439 | def state_keys(auth: arista_eos): |
440 | if auth.get("transport") == "ssh": |
441 | host, port = ssh_addr(auth) |
442 | return [f"arista_eos-{word(host)}-{port}"] |
443 | url = switch_url(auth) |
444 | port = int(url.port or auth.get("port") or {"https": 443, "http": 80}[url.scheme]) |
445 | return [ |
446 | f"arista_eos-{word(url.hostname)}-{port}", |
447 | f"arista_eos_{word(auth['host'])}", |
448 | ] |
449 |
|
450 |
|
451 | def word(s): |
452 | return re.sub(r"\W", "_", s) |
453 |
|
454 |
|
455 | def load_state(keys): |
456 | for key in keys: |
457 | if os.environ.get("WM_FLOW_JOB_ID"): |
458 | c = wmill.Windmill() |
459 | value = c.get( |
460 | f"/w/{c.workspace}/jobs/flow/user_states/{c.get_root_job_id()}/{key}" |
461 | ).json() |
462 | else: |
463 | value = (wmill.get_state(standalone_state()) or {}).get(key) |
464 | if value is not None: |
465 | return value |
466 |
|
467 |
|
468 | def save_state(keys, value): |
469 | if os.environ.get("WM_FLOW_JOB_ID"): |
470 | c = wmill.Windmill() |
471 | c.post( |
472 | f"/w/{c.workspace}/jobs/flow/user_states/{c.get_root_job_id()}/{keys[0]}", |
473 | json=value, |
474 | ) |
475 | else: |
476 | path = standalone_state() |
477 | wmill.set_state({**(wmill.get_state(path) or {}), keys[0]: value}, path) |
478 |
|
479 |
|
480 | def standalone_state(): |
481 | return f"u/{os.environ['WM_USERNAME']}/arista_eos_state" |
482 |
|
483 |
|
484 | # "4.34.9M-51132493.4349M (engineering build)" on cEOS, "4.34.9M" on hardware. |
485 | def short_version(v): |
486 | m = re.match(r"\d+\.\d+\.\d+(\.\d+)?[A-Z]*", v) |
487 | return m.group(0) if m else v |
488 |
|