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