1 | # py312 |
2 | # requirements: |
3 | # paramiko==5.1.0 |
4 | # pyeapi==1.0.4 |
5 | # wmill==1.851.0 |
6 |
|
7 | # Device activate: one attempt at staging the target image on one switch, no reload. |
8 | # Records the image of the running version as the rollback target (once per run, before any change), copies the |
9 | # image to flash (skipped when already there), compares verify /sha512 with the expected digest, then boot system. |
10 | # The image is image_url, or image_base_url + EOS-<target_version>.swi; the digest is sha512, or the .sha512 file next |
11 | # to the image. A file already on flash that doesn't match (a partial copy left by a killed run) is replaced by one |
12 | # copy; a freshly copied file that doesn't match is deleted and ActivateFailed raised, so a retry copies it again. |
13 | # An image file name that carries a version must carry target_version. Device reload checks boot-config against the |
14 | # image recorded here. State is the root flow run's user state under arista_eos-<host>-<port>. |
15 |
|
16 | import base64 |
17 | import hashlib |
18 | import json |
19 | import logging |
20 | import os |
21 | import re |
22 | import socket |
23 | import ssl |
24 | import time |
25 | import urllib.error |
26 | import urllib.request |
27 | from typing import TypedDict |
28 | from urllib.parse import urlsplit |
29 |
|
30 | import paramiko |
31 | import pyeapi |
32 | import wmill |
33 |
|
34 |
|
35 | class arista_eos(TypedDict): |
36 | host: str |
37 | username: str |
38 | password: str |
39 | port: int |
40 | verify_tls: bool |
41 | allow_http: bool |
42 |
|
43 |
|
44 | class ActivateFailed(Exception): |
45 | pass |
46 |
|
47 |
|
48 | def main( |
49 | auth: arista_eos, |
50 | target_version: str, |
51 | host: str = "", |
52 | image_base_url: str = "", |
53 | image_url: str = "", |
54 | sha512: str = "", |
55 | vrf: str = "", |
56 | ): |
57 | """ |
58 | Device activate |
59 | Copy the target image to the switch's flash (image_url, or EOS-<target_version>.swi from image_base_url), verify its sha512 (the sha512 input or the .sha512 file next to the image), and boot system it. No reload. Returns { steps, previous_image }: what it did, and the image boot-config pointed to before (Device rollback's target). Raises ActivateFailed, 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. |
60 | """ |
61 | auth = with_host(auth, host) |
62 | key = state_keys(auth) |
63 | state = load_state(key) or {} |
64 | # Set again only once this activate has booted the image: a stale one would let reload through. |
65 | forget_activated(key, state) |
66 | if not target_version or not (image_base_url or image_url): |
67 | raise ActivateFailed( |
68 | "target_version and image_base_url (or image_url) are required" |
69 | ) |
70 | try: |
71 | image, url = image_source(target_version, image_base_url, image_url) |
72 | except ValueError as e: |
73 | raise ActivateFailed(str(e)) |
74 | # A file name that carries a version must carry this one; one without (a lab image) is taken as is. |
75 | if image_version(image) not in (None, target_version): |
76 | raise ActivateFailed( |
77 | f"{image} is named for {image_version(image)}, not target_version {target_version}" |
78 | ) |
79 | steps = [] |
80 | previous = state.get("previous_image") or "" |
81 | try: |
82 | if sha512: |
83 | expected = digest(sha512) |
84 | if not expected: |
85 | raise ActivateFailed("sha512 must be the 128-hex digest of the image") |
86 | else: |
87 | try: |
88 | with urllib.request.urlopen(f"{url}.sha512", timeout=60) as r: |
89 | expected = digest(r.read().decode(errors="replace")) |
90 | except urllib.error.HTTPError as e: |
91 | raise ActivateFailed( |
92 | f"cannot read {url}.sha512 ({e.code}): pass sha512" |
93 | ) |
94 | except OSError as e: |
95 | reason = getattr(e, "reason", e) |
96 | # Unlike the switch's copy, this fetch checks the certificate: the digest is what activate trusts. |
97 | trust = ( |
98 | ", or trust the image server's CA on the worker (SSL_CERT_FILE)" |
99 | if isinstance(reason, ssl.SSLCertVerificationError) |
100 | else "" |
101 | ) |
102 | raise ActivateFailed( |
103 | f"cannot read {url}.sha512 ({reason}): pass sha512{trust}" |
104 | ) |
105 | if not expected: |
106 | raise ActivateFailed(f"no sha512 hash in {url}.sha512") |
107 |
|
108 | d, boot, version = eapi( |
109 | auth, |
110 | [ |
111 | {"cmd": "dir flash:/", "revision": 2}, |
112 | "show boot-config", |
113 | "show version", |
114 | ], |
115 | ) |
116 | files = list(d["urls"]["flash:/"]["entries"]) |
117 | running = short_version(version["version"]) |
118 | booted = boot["softwareImage"].replace("flash:/", "") |
119 | # boot-config is the running image (first run) or the target (an earlier run got past boot system). |
120 | # Anything else is a stale boot-config this step won't guess around. |
121 | if image_version(booted) != running and booted != image: |
122 | raise ActivateFailed( |
123 | f"boot-config points to {boot['softwareImage']}, neither the running version {running} nor {image}: fix boot-config first" |
124 | ) |
125 | # The rollback target is the image of the running version, recorded once per run before anything changes. |
126 | if not previous and running != target_version: |
127 | candidates = ( |
128 | [booted] |
129 | if booted != image |
130 | else [ |
131 | f |
132 | for f in files |
133 | if f.endswith(".swi") and image_version(f) == running |
134 | ] |
135 | ) |
136 | if len(candidates) != 1 or candidates[0] not in files: |
137 | raise ActivateFailed( |
138 | f"cannot tell which image on flash runs {running} (candidates: {', '.join(candidates) or 'none'}): no rollback target" |
139 | ) |
140 | previous = f"flash:/{candidates[0]}" |
141 | save_state(key, {**state, "previous_image": previous}) |
142 |
|
143 | def copy(): |
144 | # The copy runs on the switch and can take minutes for a ~1 GB image. |
145 | eapi( |
146 | auth, |
147 | [*([f"cli vrf {vrf}"] if vrf else []), f"copy {url} flash:{image}"], |
148 | "json", |
149 | 3600, |
150 | ) |
151 | steps.append(f"copied {url}") |
152 |
|
153 | def verify(): |
154 | [v] = eapi(auth, [f"verify /sha512 flash:{image}"]) |
155 | return digest((v.get("messages") or [""])[0]) |
156 |
|
157 | copied = image not in files |
158 | if copied: |
159 | copy() |
160 | actual = verify() |
161 | if actual != expected and not copied: |
162 | # Most likely a partial copy left by a killed run: replace it. |
163 | eapi(auth, [f"delete flash:{image}"]) |
164 | copy() |
165 | actual = verify() |
166 | if actual != expected: |
167 | # An earlier run may have booted it already: never leave boot-config on a deleted image. |
168 | restored = booted == image and previous |
169 | if restored: |
170 | boot_system(auth, previous.replace("flash:/", "")) |
171 | eapi(auth, [f"delete flash:{image}"]) |
172 | raise ActivateFailed( |
173 | f"sha512 mismatch for {image} (switch {actual or 'none'}, expected {expected}), deleted it" |
174 | + (f", boot-config back on {previous}" if restored else "") |
175 | ) |
176 | steps.append("sha512 verified") |
177 | steps.extend(boot_system(auth, image)) |
178 | except (DeviceUnreachable, AuthFailure, ActivateFailed): |
179 | raise |
180 | except Exception as e: |
181 | raise ActivateFailed(str(e)) |
182 | # Device reload checks boot-config against this, so it needs no image_url of its own. |
183 | save_state( |
184 | key, |
185 | {**state, "previous_image": previous, "activated_image": f"flash:/{image}"}, |
186 | ) |
187 | return {"steps": steps, "previous_image": previous} |
188 |
|
189 |
|
190 | # One resource can serve every switch that shares a login: the host input, when set, overrides the resource's host. |
191 | def with_host(auth: arista_eos, host: str): |
192 | host = (host or "").strip() or (auth.get("host") or "").strip() |
193 | if not host: |
194 | raise ValueError("host is required: set it on the resource or pass host") |
195 | return {**auth, "host": host} |
196 |
|
197 |
|
198 | # Same function in Device pre-check and Device activate. |
199 | # image_url wins; else image_base_url + EOS-<target>.swi. Returns (file name on flash, URL or ""). The URL goes into |
200 | # the switch's copy command, so it is an allowlist: http(s), then only A-Z a-z 0-9 . _ ~ : / % + - (no query, no |
201 | # user:password@, nothing the CLI reads as a separator), ending in a plain .swi file name. Raises ValueError otherwise. |
202 | def image_source(target, base, image_url): |
203 | if image_url: |
204 | image, url = urlsplit(image_url).path.rsplit("/", 1)[-1], image_url |
205 | else: |
206 | image = f"EOS-{target}.swi" if target else "" |
207 | url = f"{base.rstrip('/')}/{image}" if image and base else "" |
208 | if not url: |
209 | return image, url |
210 | # Not echoed: it would put the password in the steps and errors. |
211 | if "@" in url: |
212 | raise ValueError("the image URL must not contain @ (no user:password@ in it)") |
213 | if not re.match(r"https?://", url): |
214 | raise ValueError( |
215 | f"the image URL must start with http:// or https://: got {url!r}" |
216 | ) |
217 | if not urlsplit(url).hostname: |
218 | raise ValueError(f"the image URL has no host: got {url!r}") |
219 | bad = sorted(set(re.sub(r"[A-Za-z0-9._~:/%+-]", "", url.split("://", 1)[1]))) |
220 | if bad: |
221 | raise ValueError( |
222 | f"the image URL may only contain A-Z a-z 0-9 . _ ~ : / % + -, not {' '.join(map(repr, bad))}: got {url!r}" |
223 | ) |
224 | if not re.fullmatch(r"[\w.+-]+\.swi", image): |
225 | raise ValueError(f"the image URL must end in a .swi file name: got {url!r}") |
226 | return image, url |
227 |
|
228 |
|
229 | def boot_system(auth, image): |
230 | _, set_, _, after = eapi( |
231 | auth, ["configure", f"boot system flash:{image}", "end", "show boot-config"] |
232 | ) |
233 | if after["softwareImage"] != f"flash:/{image}": |
234 | raise Exception(f"boot-config still points to {after['softwareImage']}") |
235 | return [f"boot system flash:{image}", *(set_.get("warnings") or [])] |
236 |
|
237 |
|
238 | def forget_activated(key, state): |
239 | if state.pop("activated_image", None): |
240 | save_state(key, state) |
241 |
|
242 |
|
243 | # "EOS64-4.34.9M.swi" -> "4.34.9M" |
244 | def image_version(file): |
245 | m = re.search(r"-(\d+\.\d+\.\d+(\.\d+)?[A-Z]*)\.swi$", file) |
246 | return m.group(1) if m else None |
247 |
|
248 |
|
249 | # The 128-hex digest in a sha512sum line, a BSD "SHA512 (f) = <hash>" line or verify /sha512 output. |
250 | def digest(text): |
251 | m = re.search(r"\b[0-9a-fA-F]{128}\b", text) |
252 | return m.group(0).lower() if m else "" |
253 |
|
254 |
|
255 | # Errors the workflow branches and retries on (retry_if: result.error.name == "DeviceUnreachable"). |
256 | class DeviceUnreachable(Exception): |
257 | pass |
258 |
|
259 |
|
260 | class AuthFailure(Exception): |
261 | pass |
262 |
|
263 |
|
264 | # pyeapi logs a traceback for every socket error, and a rebooting switch gives many. |
265 | logging.getLogger("pyeapi").addHandler(logging.NullHandler()) |
266 |
|
267 |
|
268 | def eapi(auth: arista_eos, cmds: list, fmt: str = "json", timeout: float = 60): |
269 | eos = node(auth, timeout) |
270 | try: |
271 | return eos.run_commands(cmds, fmt) |
272 | except pyeapi.eapilib.ConnectionError as e: |
273 | raise connection_error(auth, eos, e) |
274 |
|
275 |
|
276 | # pyeapi 1.0.4 raises ConnectionError for a socket error (kept in socket_error), an answer that isn't JSON (eAPI |
277 | # still starting, 5xx) and a 401, the only one with neither. |
278 | def connection_error(auth, eos, e): |
279 | # A certificate the resource does not trust is a setting to fix (verify_tls, ca_certificate), not worth a retry. |
280 | if isinstance(eos.connection.socket_error, ssl.SSLCertVerificationError): |
281 | return RuntimeError(f"{auth['host']}: {eos.connection.socket_error}") |
282 | if eos.connection.socket_error is None and e.message != "unable to connect to eAPI": |
283 | return AuthFailure(f"{auth['host']}: {'SSH' if auth.get('transport') == 'ssh' else 'eAPI'} refused the credential ({e.message})") |
284 | return DeviceUnreachable(f"{auth['host']}: {e.message}") |
285 |
|
286 |
|
287 | # host is an address or a URL (https: |
288 | # resource ticks allow_http (Basic auth then crosses the network in cleartext). pyeapi skips certificate checks unless it |
289 | # is given a context, so one is always passed: verifying, or not when the resource unticks verify_tls (EOS ships a |
290 | # self-signed cert). |
291 | def switch_url(auth: arista_eos): |
292 | host = auth["host"] |
293 | if "://" not in host: |
294 | host = ( |
295 | f"https://[{host}]" |
296 | if host.count(":") > 1 and "[" not in host |
297 | else f"https://{host}" |
298 | ) |
299 | url = urlsplit(host) |
300 | if not url.hostname or ( |
301 | url.scheme != "https" and not (url.scheme == "http" and auth.get("allow_http")) |
302 | ): |
303 | raise ValueError( |
304 | f"host must be an address or an https:// URL (http:// needs allow_http on the resource): {auth['host']}" |
305 | ) |
306 | return url |
307 |
|
308 |
|
309 | # SSH transport (transport: ssh): the EOS CLI over an SSH shell, behind the part of pyeapi's Node the scripts use |
310 | # (run_commands, connection.socket_error, connection.transport.connect), raising pyeapi's own CommandError and |
311 | # ConnectionError, so the checks and the error mapping are the same for both transports. Show commands in json get |
312 | # "| json", which prints the eAPI JSON; other commands give { messages: [output] } like eAPI, or {} when silent. |
313 | # A line starting with "% " is an error, raised as eAPI's CommandError. The host key is checked when the resource |
314 | # has ssh_host_key (SHA256:... as ssh-keygen -lf prints it). |
315 | class Ssh: |
316 | def __init__(self, auth: arista_eos, timeout: float): |
317 | self.auth, self.timeout = auth, timeout |
318 | self.connection = self.transport = self |
319 | self.socket_error = self.sock = self.chan = None |
320 |
|
321 | # The TCP connection only, like eAPI's transport.connect(): if it fails, nothing was sent. |
322 | def connect(self): |
323 | self.sock = socket.create_connection(ssh_addr(self.auth), self.timeout) |
324 |
|
325 | def lost(self, e): |
326 | self.socket_error = e |
327 | return pyeapi.eapilib.ConnectionError("ssh", f"SSH connection failed ({e})") |
328 |
|
329 | def open(self): |
330 | auth = self.auth |
331 | try: |
332 | if not self.sock: |
333 | self.connect() |
334 | t = paramiko.Transport(self.sock) |
335 | t.start_client(timeout=self.timeout) |
336 | key = t.get_remote_server_key() |
337 | except (OSError, EOFError, paramiko.SSHException) as e: |
338 | raise self.lost(e) |
339 | fp = "SHA256:" + base64.b64encode(hashlib.sha256(key.asbytes()).digest()).decode().rstrip("=") |
340 | if auth.get("ssh_host_key") and auth["ssh_host_key"].strip() != fp: |
341 | t.close() |
342 | raise RuntimeError(f"{auth['host']}: the SSH host key is {fp}, not the resource's ssh_host_key") |
343 | try: |
344 | try: |
345 | t.auth_password(auth["username"], auth["password"]) |
346 | except paramiko.BadAuthenticationType: |
347 | t.auth_interactive( |
348 | auth["username"], lambda _t, _i, prompts: [auth["password"]] * len(prompts) |
349 | ) |
350 | except paramiko.AuthenticationException as e: |
351 | t.close() |
352 | raise pyeapi.eapilib.ConnectionError("ssh", str(e)) |
353 | except (OSError, EOFError, paramiko.SSHException) as e: |
354 | raise self.lost(e) |
355 | try: |
356 | self.chan = t.open_session() |
357 | self.chan.get_pty(width=4000) |
358 | self.chan.invoke_shell() |
359 | self.prompt = None |
360 | out = self.read() |
361 | self.prompt = re.escape(re.split(r"[(>#]", out.splitlines()[-1].strip())[0]) |
362 | if out.rstrip().endswith(">"): |
363 | self.cli("enable") |
364 | self.cli("terminal length 0") |
365 | self.cli("terminal width 32767") |
366 | except (OSError, EOFError, paramiko.SSHException) as e: |
367 | raise self.lost(e) |
368 |
|
369 | # Reads until the prompt. Questions eAPI never asks are answered as eAPI behaves: confirm, don't save. |
370 | def read(self): |
371 | buf, end = "", time.monotonic() + self.timeout |
372 | prompt = (self.prompt or r"[\w.\-]+") + r"(\([^)\r\n]*\))?[>#] ?$" |
373 | while True: |
374 | self.chan.settimeout(max(end - time.monotonic(), 0.01)) |
375 | chunk = self.chan.recv(65536) |
376 | if not chunk: |
377 | raise self.lost("connection closed") |
378 | buf += chunk.decode(errors="replace") |
379 | tail = buf[-300:] |
380 | if re.search(r"(^|\n)" + prompt, tail): |
381 | return buf |
382 | for question, answer in ( |
383 | # enable asks for a password on switches that land the user unprivileged: the login password. |
384 | (r"(^|\n)Password:\s*$", self.auth["password"]), |
385 | (r"\[confirm\]\s*$", ""), |
386 | (r"Save\?.*\[yes/no[^\]]*\]:?\s*$", "no"), |
387 | (r"\[(y|yes)/(n|no)\][:?]?\s*$", "y"), |
388 | ): |
389 | if re.search(question, tail, re.I): |
390 | self.chan.send(answer + "\r") |
391 | buf += "\n" |
392 |
|
393 | # One command: its output without the echoed command and the prompt; progress lines keep their last state. |
394 | def cli(self, cmd): |
395 | try: |
396 | self.chan.send(cmd + "\r") |
397 | out = self.read() |
398 | except (OSError, EOFError, paramiko.SSHException) as e: |
399 | raise self.lost(e) |
400 | self.mode = out.rstrip().splitlines()[-1] |
401 | lines = [l.rstrip("\r").split("\r")[-1] for l in out.split("\n")] |
402 | return "\n".join(lines[1:-1]).strip("\n") |
403 |
|
404 | def run_commands(self, cmds, encoding="json", **_): |
405 | try: |
406 | if not self.chan: |
407 | self.open() |
408 | if "(config" in self.mode: |
409 | self.cli("end") |
410 | results = [] |
411 | for i, c in enumerate(cmds): |
412 | # eAPI's { cmd, revision } form is the CLI's "| json revision N". |
413 | cmd, rev = (c["cmd"], c.get("revision")) if isinstance(c, dict) else (c, None) |
414 | show = encoding == "json" and (rev or re.match(r"\s*sh(ow)?\s", cmd)) and not re.search(r"\|\s*json", cmd) |
415 | # pyeapi sends "<cmd> MULTILINE: <text>" (banners) as cmd + input; the CLI reads the text up to EOF. |
416 | head, multi, text = cmd.partition("MULTILINE:") |
417 | # The shell would run what follows a line break as another command; eAPI refuses it too. |
418 | if re.search(r"[\r\n]", head): |
419 | raise ValueError(f"a command may not contain a line break: {head!r}") |
420 | line = "\r".join([head.strip(), *text.strip().splitlines(), "EOF"]) if multi else cmd |
421 | out = self.cli(f"{cmd} | json{f' revision {rev}' if rev else ''}" if show else line) |
422 | errors = [l[2:] for l in out.splitlines() if l.startswith("% ")] |
423 | code, kind = 1002, "invalid command" |
424 | if show and not errors: |
425 | code, kind = 1000, "could not run command" |
426 | try: |
427 | result = json.loads(out) |
428 | except ValueError: |
429 | errors = [out[:200]] |
430 | else: |
431 | errors = result.get("errors") or [] |
432 | if errors: |
433 | raise pyeapi.eapilib.CommandError( |
434 | code, |
435 | f"CLI command {i + 2} of {len(cmds) + 1} '{cmd}' failed: {kind}", |
436 | command_error="; ".join(errors), |
437 | commands=cmds, |
438 | output=results, |
439 | ) |
440 | if encoding != "json": |
441 | result = {"output": out + "\n" if out else ""} |
442 | elif not show: |
443 | # The CLI prints eAPI's warnings as "! " notices. |
444 | notices = [l[2:].strip() for l in out.splitlines() if l.startswith("! ")] |
445 | out = "\n".join(l for l in out.splitlines() if not l.startswith("! ")).strip() |
446 | result = {"messages": [out]} if out and not multi else {} |
447 | if notices: |
448 | result["warnings"] = notices |
449 | results.append(result) |
450 | return results |
451 | except pyeapi.eapilib.ConnectionError: |
452 | if self.chan: |
453 | self.chan.close() |
454 | self.sock = self.chan = None |
455 | raise |
456 |
|
457 |
|
458 | # paramiko logs a traceback when a rebooting switch drops the session. |
459 | logging.getLogger("paramiko").addHandler(logging.NullHandler()) |
460 |
|
461 |
|
462 | # host, or host:port ([v6]:port), else port, else 22. |
463 | def ssh_addr(auth: arista_eos): |
464 | h = auth["host"] |
465 | if "://" in h: |
466 | raise ValueError(f"with transport ssh, host is an address or a hostname (with :port), not a URL: {h}") |
467 | url = urlsplit(f"ssh://{h}" if h.count(":") <= 1 or h.startswith("[") else f"ssh://[{h}]") |
468 | return url.hostname, url.port or int(auth.get("port") or 22) |
469 |
|
470 |
|
471 | def node(auth: arista_eos, timeout: float = 60): |
472 | if auth.get("transport") == "ssh": |
473 | return Ssh(auth, timeout) |
474 | url = switch_url(auth) |
475 | # ca_certificate: the PEM of a private CA, trusted instead of the system's CAs. |
476 | context = ssl.create_default_context(cadata=(auth.get("ca_certificate") or "").strip() or None) |
477 | if auth.get("verify_tls") is False: |
478 | context.check_hostname = False |
479 | context.verify_mode = ssl.CERT_NONE |
480 | return pyeapi.connect( |
481 | transport=url.scheme, |
482 | host=url.hostname, |
483 | port=url.port or auth.get("port") or None, |
484 | username=auth["username"], |
485 | password=auth["password"], |
486 | context=context, |
487 | timeout=timeout, |
488 | return_node=True, |
489 | ) |
490 |
|
491 |
|
492 | # Shared by the Device scripts: the root flow run's user state, keyed by switch, holds the pre-check snapshot, the |
493 | # image activate replaced (rollback target), the image it booted and the reload markers. Every step of the run (nested |
494 | # subflows and retried attempts included) reads the same entry. Outside a flow the Device scripts share one state |
495 | # resource in the running user's home (a script's own state would keep the pre-check snapshot from the post-check). |
496 | # The endpoint is called through the client so an unreachable state raises (wmill.get_flow_user_state returns None). |
497 | # ponytail: the fallback is one map per user, so concurrent standalone runs can race; flows don't. |
498 | # The key is the switch's eAPI address: arista_eos-<host>-<port> with non-word characters in the host as _, the port |
499 | # always in (443 or 80 when unset). State written before the port was part of the key is read from arista_eos_<host> |
500 | # as a fallback (all word characters, so never a new key); writes go to the new key only. |
501 | def state_keys(auth: arista_eos): |
502 | if auth.get("transport") == "ssh": |
503 | host, port = ssh_addr(auth) |
504 | return [f"arista_eos-{word(host)}-{port}"] |
505 | url = switch_url(auth) |
506 | port = int(url.port or auth.get("port") or {"https": 443, "http": 80}[url.scheme]) |
507 | return [ |
508 | f"arista_eos-{word(url.hostname)}-{port}", |
509 | f"arista_eos_{word(auth['host'])}", |
510 | ] |
511 |
|
512 |
|
513 | def word(s): |
514 | return re.sub(r"\W", "_", s) |
515 |
|
516 |
|
517 | def load_state(keys): |
518 | for key in keys: |
519 | if os.environ.get("WM_FLOW_JOB_ID"): |
520 | c = wmill.Windmill() |
521 | value = c.get( |
522 | f"/w/{c.workspace}/jobs/flow/user_states/{c.get_root_job_id()}/{key}" |
523 | ).json() |
524 | else: |
525 | value = (wmill.get_state(standalone_state()) or {}).get(key) |
526 | if value is not None: |
527 | return value |
528 |
|
529 |
|
530 | def save_state(keys, value): |
531 | if os.environ.get("WM_FLOW_JOB_ID"): |
532 | c = wmill.Windmill() |
533 | c.post( |
534 | f"/w/{c.workspace}/jobs/flow/user_states/{c.get_root_job_id()}/{keys[0]}", |
535 | json=value, |
536 | ) |
537 | else: |
538 | path = standalone_state() |
539 | wmill.set_state({**(wmill.get_state(path) or {}), keys[0]: value}, path) |
540 |
|
541 |
|
542 | def standalone_state(): |
543 | return f"u/{os.environ['WM_USERNAME']}/arista_eos_state" |
544 |
|
545 |
|
546 | # "4.34.9M-51132493.4349M (engineering build)" on cEOS, "4.34.9M" on hardware. |
547 | def short_version(v): |
548 | m = re.match(r"\d+\.\d+\.\d+(\.\d+)?[A-Z]*", v) |
549 | return m.group(0) if m else v |
550 |
|