0

Device pre-check

Published 5 days ago

One pre-upgrade check of one switch: reads the running version, flash space for the target image (image_url, or EOS-<target_version>.swi on image_base_url) and MLAG health, and saves a snapshot of interfaces, LLDP neighbors and MLAG in the flow run's state for Device post-check. Returns { running_version, flash, mlag, snapshot, problems[{check: flash|mlag, message}], notes }; a failed check is a problem, not an error. 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.

Script arista_eos Verified

The script

Submitted by hugo989 Python3
Verified 4 days ago
1
# py312
2
# requirements:
3
# paramiko==5.1.0
4
# pyeapi==1.0.4
5
# wmill==1.851.0
6

7
# Device pre-check: one attempt, before an upgrade of one switch. Returns what it read and what it found:
8
# - flash: free_bytes, the target image (image_url, or image_base_url + EOS-<target_version>.swi), whether it is
9
#   already on flash, and required_bytes (its size on the image server; required_free_mb without an image server or
10
#   when its HEAD has no Content-Length). The HEAD checks the certificate and, if the worker doesn't trust it, sizes
11
#   the image anyway: notes says when either happens, and when activate will need its sha512 input.
12
# - mlag: state, negotiation, peer-link and local interface status, config-sanity inconsistencies, port counts,
13
#   errdisabled, reload-delay. { configured: false } without MLAG (notes says the reload is not hitless).
14
# - snapshot: interfaces up, LLDP neighbor per port, MLAG state and per-port status, also saved in the root flow
15
#   run's user state under arista_eos-<host>-<port> for Device post-check to compare with.
16
# - problems: [{ check: flash|mlag, message }], one per problem found: not enough flash, image not on the server, a
17
#   malformed image URL; MLAG not active/connected, peer-link or local interface down, config-sanity inconsistent,
18
#   ports active-partial or errdisabled (configured but down counts). Returned, not raised: the caller decides.
19
# Raises DeviceUnreachable or AuthFailure.
20

21

22
import base64
23
import hashlib
24
import json
25
import logging
26
import os
27
import re
28
import socket
29
import ssl
30
import time
31
import urllib.error
32
import urllib.request
33
from typing import TypedDict
34
from urllib.parse import urlsplit
35

36
import paramiko
37
import pyeapi
38
import wmill
39

40

41
class arista_eos(TypedDict):
42
    host: str
43
    username: str
44
    password: str
45
    port: int
46
    verify_tls: bool
47
    allow_http: bool
48

49

50
def main(
51
    auth: arista_eos,
52
    host: str = "",
53
    target_version: str = "",
54
    image_base_url: str = "",
55
    image_url: str = "",
56
    required_free_mb: int = 1024,
57
):
58
    """
59
    Device pre-check
60
    One pre-upgrade check of one switch: reads the running version, flash space for the target image (image_url, or EOS-<target_version>.swi on image_base_url) and MLAG health, and saves a snapshot of interfaces, LLDP neighbors and MLAG in the flow run\'s state for Device post-check. Returns { running_version, flash, mlag, snapshot, problems[{check: flash|mlag, message}], notes }; a failed check is a problem, not an error. 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.
61
    """
62
    auth = with_host(auth, host)
63
    key = state_keys(auth)
64
    state = load_state(key) or {}
65
    version, mlag = eapi(auth, ["show version", "show mlag"])
66
    problems, notes = [], []
67
    flash = flash_facts(auth, target_version, image_base_url, image_url, required_free_mb, notes)
68
    problems += [{"check": "flash", "message": m} for m in flash.pop("problems")]
69
    if mlag_configured(mlag):
70
        [sanity] = eapi(auth, ["show mlag config-sanity"])
71
        mlag_info = mlag_facts(mlag, sanity)
72
        problems += [{"check": "mlag", "message": m} for m in redundancy_problems(mlag, sanity)]
73
    else:
74
        mlag_info = {"configured": False}
75
        notes.append("MLAG is not configured: the reload is not hitless")
76
    snap = snapshot(auth)
77
    save_state(
78
        key,
79
        {
80
            **state,
81
            "snapshot": snap,
82
            "snapshot_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
83
        },
84
    )
85
    return {
86
        "running_version": short_version(version["version"]),
87
        "flash": flash,
88
        "mlag": mlag_info,
89
        "snapshot": snap,
90
        "problems": problems,
91
        "notes": notes,
92
    }
93

94

95
# One resource can serve every switch that shares a login: the host input, when set, overrides the resource's host.
96
def with_host(auth: arista_eos, host: str):
97
    host = (host or "").strip() or (auth.get("host") or "").strip()
98
    if not host:
99
        raise ValueError("host is required: set it on the resource or pass host")
100
    return {**auth, "host": host}
101

102

103
# Flash facts for the target image, and the problems found: { free_bytes, image, image_on_flash, required_bytes,
104
# problems }. required_bytes is the image size from the image server, else required_free_mb; 0 when on flash.
105
def flash_facts(auth, target, base, image_url, required_mb, notes):
106
    [d] = eapi(auth, [{"cmd": "dir flash:/", "revision": 2}])
107
    flash = d["urls"]["flash:/"]
108
    facts = {"free_bytes": flash["filesystem"]["freeBytes"], "image": "", "image_on_flash": False, "required_bytes": 0}
109
    try:
110
        image, url = image_source(target, base, image_url)
111
    except ValueError as e:
112
        return {**facts, "problems": [str(e)]}
113
    facts["image"] = image
114
    if image and image in flash["entries"]:
115
        if url:
116
            sidecar_note(url, image, notes)
117
        return {**facts, "image_on_flash": True, "problems": []}
118
    required = (required_mb or 1024) * 1e6
119
    if url:
120
        try:
121
            try:
122
                size = head(url, ssl.create_default_context())
123
                sidecar_note(url, image, notes)
124
            except urllib.error.URLError as e:
125
                if not isinstance(e.reason, ssl.SSLCertVerificationError):
126
                    raise
127
                # Only the size is read: the switch's copy doesn't check the certificate either, and activate
128
                # verifies the image's sha512. So an untrusted (self-signed) server is sized anyway, with a note.
129
                unverified = ssl.create_default_context()
130
                unverified.check_hostname = False
131
                unverified.verify_mode = ssl.CERT_NONE
132
                size = head(url, unverified)
133
                notes.append(
134
                    f"flash: the image server's certificate is not trusted on the worker ({e.reason.verify_message}), sized {image} without checking it; activate checks it when it fetches {image}.sha512, so pass it sha512"
135
                )
136
            if size:
137
                required = size
138
            else:
139
                notes.append(
140
                    f"flash: the image server gave no size for {image}, assumed required_free_mb ({mb(required)})"
141
                )
142
        except urllib.error.HTTPError as e:
143
            return {**facts, "problems": [f"Target image {image} not found on the image server ({e.code})"]}
144
        except OSError as e:
145
            return {**facts, "problems": [f"Image server unreachable from the worker: {getattr(e, 'reason', e)}"]}
146
    facts["required_bytes"] = int(required)
147
    free = facts["free_bytes"]
148
    if free < required:
149
        return {
150
            **facts,
151
            "problems": [
152
                f"Insufficient flash space ({mb(free)} free, {mb(required)} required{f' for {image}' if image else ''})"
153
            ],
154
        }
155
    return {**facts, "problems": []}
156

157

158
def mlag_facts(mlag, sanity):
159
    return {
160
        "configured": True,
161
        "domain_id": mlag.get("domainId"),
162
        "state": mlag.get("state"),
163
        "negotiation_status": mlag.get("negStatus"),
164
        "peer_link": mlag.get("peerLink"),
165
        "peer_link_status": mlag.get("peerLinkStatus"),
166
        "local_interface": mlag.get("localInterface"),
167
        "local_interface_status": mlag.get("localIntfStatus"),
168
        "config_sanity_inconsistent": [
169
            *(sanity.get("globalConfiguration") or {}),
170
            *(sanity.get("interfaceConfiguration") or {}),
171
        ],
172
        "ports": mlag.get("mlagPorts") or {},
173
        "ports_errdisabled": bool(mlag.get("portsErrdisabled")),
174
        "reload_delay_seconds": reload_delay(mlag),
175
    }
176

177

178
def head(url, context):
179
    with urllib.request.urlopen(
180
        urllib.request.Request(url, method="HEAD"), timeout=30, context=context
181
    ) as r:
182
        return int(r.headers.get("content-length") or 0)
183

184

185
# Activate reads the digest from the .sha512 file next to the image, certificate checked, unless given sha512.
186
def sidecar_note(url, image, notes):
187
    try:
188
        head(f"{url}.sha512", ssl.create_default_context())
189
    except OSError as e:
190
        reason = getattr(e, "code", None) or getattr(e, "reason", e)
191
        notes.append(
192
            f"flash: {image}.sha512 not reachable from the worker ({reason}): pass sha512 to activate"
193
        )
194

195

196
# Same function in Device pre-check and Device activate.
197
# image_url wins; else image_base_url + EOS-<target>.swi. Returns (file name on flash, URL or ""). The URL goes into
198
# the switch's copy command, so it is an allowlist: http(s), then only A-Z a-z 0-9 . _ ~ : / % + - (no query, no
199
# user:password@, nothing the CLI reads as a separator), ending in a plain .swi file name. Raises ValueError otherwise.
200
def image_source(target, base, image_url):
201
    if image_url:
202
        image, url = urlsplit(image_url).path.rsplit("/", 1)[-1], image_url
203
    else:
204
        image = f"EOS-{target}.swi" if target else ""
205
        url = f"{base.rstrip('/')}/{image}" if image and base else ""
206
    if not url:
207
        return image, url
208
    # Not echoed: it would put the password in the steps and errors.
209
    if "@" in url:
210
        raise ValueError("the image URL must not contain @ (no user:password@ in it)")
211
    if not re.match(r"https?://", url):
212
        raise ValueError(
213
            f"the image URL must start with http:// or https://: got {url!r}"
214
        )
215
    if not urlsplit(url).hostname:
216
        raise ValueError(f"the image URL has no host: got {url!r}")
217
    bad = sorted(set(re.sub(r"[A-Za-z0-9._~:/%+-]", "", url.split("://", 1)[1])))
218
    if bad:
219
        raise ValueError(
220
            f"the image URL may only contain A-Z a-z 0-9 . _ ~ : / % + -, not {' '.join(map(repr, bad))}: got {url!r}"
221
        )
222
    if not re.fullmatch(r"[\w.+-]+\.swi", image):
223
        raise ValueError(f"the image URL must end in a .swi file name: got {url!r}")
224
    return image, url
225

226

227
def redundancy_problems(mlag, sanity):
228
    p = []
229
    if mlag.get("state") != "active":
230
        p.append(f"MLAG state {mlag.get('state')} (expected active)")
231
    if mlag.get("negStatus") != "connected":
232
        p.append(f"MLAG negotiation {mlag.get('negStatus')} (expected connected)")
233
    if mlag.get("peerLinkStatus") != "up":
234
        p.append(f"peer-link {mlag.get('peerLink')} {mlag.get('peerLinkStatus')}")
235
    if mlag.get("localIntfStatus") != "up":
236
        p.append(
237
            f"MLAG local interface {mlag.get('localInterface')} {mlag.get('localIntfStatus')}"
238
        )
239
    inconsistent = [
240
        *(sanity.get("globalConfiguration") or {}),
241
        *(sanity.get("interfaceConfiguration") or {}),
242
    ]
243
    if inconsistent:
244
        p.append(f"config-sanity inconsistent: {', '.join(inconsistent)}")
245
    partial = (mlag.get("mlagPorts") or {}).get("Active-partial")
246
    if partial:
247
        p.append(f"{partial} MLAG port(s) active-partial")
248
    if mlag.get("portsErrdisabled"):
249
        p.append("MLAG ports errdisabled")
250
    return p
251

252

253
# show mlag reports state disabled both when MLAG was never configured and when it is configured but shut down;
254
# only the first has no domain-id, local interface or peer-link.
255
def mlag_configured(mlag):
256
    return any(mlag.get(k) for k in ("domainId", "localInterface", "peerLink"))
257

258

259
def snapshot(auth):
260
    status, lldp, mlag, mlag_intf = eapi(
261
        auth,
262
        [
263
            "show interfaces status",
264
            "show lldp neighbors",
265
            "show mlag",
266
            "show mlag interfaces",
267
        ],
268
    )
269
    return {
270
        "interfaces_up": sorted(
271
            n
272
            for n, i in status["interfaceStatuses"].items()
273
            if i.get("linkStatus") == "connected"
274
        ),
275
        "lldp": [
276
            {
277
                "port": n["port"],
278
                "neighbor": f"{n['neighborDevice']} {n['neighborPort']}",
279
            }
280
            for n in lldp["lldpNeighbors"]
281
        ],
282
        "mlag": {
283
            "state": mlag.get("state"),
284
            "negStatus": mlag.get("negStatus"),
285
            "peerLinkStatus": mlag.get("peerLinkStatus"),
286
            "ports": {
287
                f"{i['localInterface']} (mlag {id})": i["status"]
288
                for id, i in (mlag_intf.get("interfaces") or {}).items()
289
            },
290
        },
291
    }
292

293

294
# Without MLAG configured, show mlag still reports the default reload-delay, and nothing waits on it.
295
def reload_delay(mlag):
296
    if not mlag_configured(mlag):
297
        return 0
298
    return max(mlag.get("reloadDelay") or 0, mlag.get("reloadDelayNonMlag") or 0)
299

300

301
def mb(n):
302
    return f"{n / 1e9:.1f} GB" if n >= 1e9 else f"{round(n / 1e6)} MB"
303

304

305
# Errors the workflow branches and retries on (retry_if: result.error.name == "DeviceUnreachable").
306
class DeviceUnreachable(Exception):
307
    pass
308

309

310
class AuthFailure(Exception):
311
    pass
312

313

314
# pyeapi logs a traceback for every socket error, and a rebooting switch gives many.
315
logging.getLogger("pyeapi").addHandler(logging.NullHandler())
316

317

318
def eapi(auth: arista_eos, cmds: list, fmt: str = "json", timeout: float = 60):
319
    eos = node(auth, timeout)
320
    try:
321
        return eos.run_commands(cmds, fmt)
322
    except pyeapi.eapilib.ConnectionError as e:
323
        raise connection_error(auth, eos, e)
324

325

326
# pyeapi 1.0.4 raises ConnectionError for a socket error (kept in socket_error), an answer that isn't JSON (eAPI
327
# still starting, 5xx) and a 401, the only one with neither.
328
def connection_error(auth, eos, e):
329
    # A certificate the resource does not trust is a setting to fix (verify_tls, ca_certificate), not worth a retry.
330
    if isinstance(eos.connection.socket_error, ssl.SSLCertVerificationError):
331
        return RuntimeError(f"{auth['host']}: {eos.connection.socket_error}")
332
    if eos.connection.socket_error is None and e.message != "unable to connect to eAPI":
333
        return AuthFailure(f"{auth['host']}: {'SSH' if auth.get('transport') == 'ssh' else 'eAPI'} refused the credential ({e.message})")
334
    return DeviceUnreachable(f"{auth['host']}: {e.message}")
335

336

337
# host is an address or a URL (https://10.0.0.11:8443); a bare IPv6 address is bracketed. Only https, or http when the
338
# resource ticks allow_http (Basic auth then crosses the network in cleartext). pyeapi skips certificate checks unless it
339
# is given a context, so one is always passed: verifying, or not when the resource unticks verify_tls (EOS ships a
340
# self-signed cert).
341
def switch_url(auth: arista_eos):
342
    host = auth["host"]
343
    if "://" not in host:
344
        host = (
345
            f"https://[{host}]"
346
            if host.count(":") > 1 and "[" not in host
347
            else f"https://{host}"
348
        )
349
    url = urlsplit(host)
350
    if not url.hostname or (
351
        url.scheme != "https" and not (url.scheme == "http" and auth.get("allow_http"))
352
    ):
353
        raise ValueError(
354
            f"host must be an address or an https:// URL (http:// needs allow_http on the resource): {auth['host']}"
355
        )
356
    return url
357

358

359
# SSH transport (transport: ssh): the EOS CLI over an SSH shell, behind the part of pyeapi's Node the scripts use
360
# (run_commands, connection.socket_error, connection.transport.connect), raising pyeapi's own CommandError and
361
# ConnectionError, so the checks and the error mapping are the same for both transports. Show commands in json get
362
# "| json", which prints the eAPI JSON; other commands give { messages: [output] } like eAPI, or {} when silent.
363
# A line starting with "% " is an error, raised as eAPI's CommandError. The host key is checked when the resource
364
# has ssh_host_key (SHA256:... as ssh-keygen -lf prints it).
365
class Ssh:
366
    def __init__(self, auth: arista_eos, timeout: float):
367
        self.auth, self.timeout = auth, timeout
368
        self.connection = self.transport = self
369
        self.socket_error = self.sock = self.chan = None
370

371
    # The TCP connection only, like eAPI's transport.connect(): if it fails, nothing was sent.
372
    def connect(self):
373
        self.sock = socket.create_connection(ssh_addr(self.auth), self.timeout)
374

375
    def lost(self, e):
376
        self.socket_error = e
377
        return pyeapi.eapilib.ConnectionError("ssh", f"SSH connection failed ({e})")
378

379
    def open(self):
380
        auth = self.auth
381
        try:
382
            if not self.sock:
383
                self.connect()
384
            t = paramiko.Transport(self.sock)
385
            t.start_client(timeout=self.timeout)
386
            key = t.get_remote_server_key()
387
        except (OSError, EOFError, paramiko.SSHException) as e:
388
            raise self.lost(e)
389
        fp = "SHA256:" + base64.b64encode(hashlib.sha256(key.asbytes()).digest()).decode().rstrip("=")
390
        if auth.get("ssh_host_key") and auth["ssh_host_key"].strip() != fp:
391
            t.close()
392
            raise RuntimeError(f"{auth['host']}: the SSH host key is {fp}, not the resource's ssh_host_key")
393
        try:
394
            try:
395
                t.auth_password(auth["username"], auth["password"])
396
            except paramiko.BadAuthenticationType:
397
                t.auth_interactive(
398
                    auth["username"], lambda _t, _i, prompts: [auth["password"]] * len(prompts)
399
                )
400
        except paramiko.AuthenticationException as e:
401
            t.close()
402
            raise pyeapi.eapilib.ConnectionError("ssh", str(e))
403
        except (OSError, EOFError, paramiko.SSHException) as e:
404
            raise self.lost(e)
405
        try:
406
            self.chan = t.open_session()
407
            self.chan.get_pty(width=4000)
408
            self.chan.invoke_shell()
409
            self.prompt = None
410
            out = self.read()
411
            self.prompt = re.escape(re.split(r"[(>#]", out.splitlines()[-1].strip())[0])
412
            if out.rstrip().endswith(">"):
413
                self.cli("enable")
414
            self.cli("terminal length 0")
415
            self.cli("terminal width 32767")
416
        except (OSError, EOFError, paramiko.SSHException) as e:
417
            raise self.lost(e)
418

419
    # Reads until the prompt. Questions eAPI never asks are answered as eAPI behaves: confirm, don't save.
420
    def read(self):
421
        buf, end = "", time.monotonic() + self.timeout
422
        prompt = (self.prompt or r"[\w.\-]+") + r"(\([^)\r\n]*\))?[>#] ?$"
423
        while True:
424
            self.chan.settimeout(max(end - time.monotonic(), 0.01))
425
            chunk = self.chan.recv(65536)
426
            if not chunk:
427
                raise self.lost("connection closed")
428
            buf += chunk.decode(errors="replace")
429
            tail = buf[-300:]
430
            if re.search(r"(^|\n)" + prompt, tail):
431
                return buf
432
            for question, answer in (
433
                # enable asks for a password on switches that land the user unprivileged: the login password.
434
                (r"(^|\n)Password:\s*$", self.auth["password"]),
435
                (r"\[confirm\]\s*$", ""),
436
                (r"Save\?.*\[yes/no[^\]]*\]:?\s*$", "no"),
437
                (r"\[(y|yes)/(n|no)\][:?]?\s*$", "y"),
438
            ):
439
                if re.search(question, tail, re.I):
440
                    self.chan.send(answer + "\r")
441
                    buf += "\n"
442

443
    # One command: its output without the echoed command and the prompt; progress lines keep their last state.
444
    def cli(self, cmd):
445
        try:
446
            self.chan.send(cmd + "\r")
447
            out = self.read()
448
        except (OSError, EOFError, paramiko.SSHException) as e:
449
            raise self.lost(e)
450
        self.mode = out.rstrip().splitlines()[-1]
451
        lines = [l.rstrip("\r").split("\r")[-1] for l in out.split("\n")]
452
        return "\n".join(lines[1:-1]).strip("\n")
453

454
    def run_commands(self, cmds, encoding="json", **_):
455
        try:
456
            if not self.chan:
457
                self.open()
458
            if "(config" in self.mode:
459
                self.cli("end")
460
            results = []
461
            for i, c in enumerate(cmds):
462
                # eAPI's { cmd, revision } form is the CLI's "| json revision N".
463
                cmd, rev = (c["cmd"], c.get("revision")) if isinstance(c, dict) else (c, None)
464
                show = encoding == "json" and (rev or re.match(r"\s*sh(ow)?\s", cmd)) and not re.search(r"\|\s*json", cmd)
465
                # pyeapi sends "<cmd> MULTILINE: <text>" (banners) as cmd + input; the CLI reads the text up to EOF.
466
                head, multi, text = cmd.partition("MULTILINE:")
467
                # The shell would run what follows a line break as another command; eAPI refuses it too.
468
                if re.search(r"[\r\n]", head):
469
                    raise ValueError(f"a command may not contain a line break: {head!r}")
470
                line = "\r".join([head.strip(), *text.strip().splitlines(), "EOF"]) if multi else cmd
471
                out = self.cli(f"{cmd} | json{f' revision {rev}' if rev else ''}" if show else line)
472
                errors = [l[2:] for l in out.splitlines() if l.startswith("% ")]
473
                code, kind = 1002, "invalid command"
474
                if show and not errors:
475
                    code, kind = 1000, "could not run command"
476
                    try:
477
                        result = json.loads(out)
478
                    except ValueError:
479
                        errors = [out[:200]]
480
                    else:
481
                        errors = result.get("errors") or []
482
                if errors:
483
                    raise pyeapi.eapilib.CommandError(
484
                        code,
485
                        f"CLI command {i + 2} of {len(cmds) + 1} '{cmd}' failed: {kind}",
486
                        command_error="; ".join(errors),
487
                        commands=cmds,
488
                        output=results,
489
                    )
490
                if encoding != "json":
491
                    result = {"output": out + "\n" if out else ""}
492
                elif not show:
493
                    # The CLI prints eAPI's warnings as "! " notices.
494
                    notices = [l[2:].strip() for l in out.splitlines() if l.startswith("! ")]
495
                    out = "\n".join(l for l in out.splitlines() if not l.startswith("! ")).strip()
496
                    result = {"messages": [out]} if out and not multi else {}
497
                    if notices:
498
                        result["warnings"] = notices
499
                results.append(result)
500
            return results
501
        except pyeapi.eapilib.ConnectionError:
502
            if self.chan:
503
                self.chan.close()
504
            self.sock = self.chan = None
505
            raise
506

507

508
# paramiko logs a traceback when a rebooting switch drops the session.
509
logging.getLogger("paramiko").addHandler(logging.NullHandler())
510

511

512
# host, or host:port ([v6]:port), else port, else 22.
513
def ssh_addr(auth: arista_eos):
514
    h = auth["host"]
515
    if "://" in h:
516
        raise ValueError(f"with transport ssh, host is an address or a hostname (with :port), not a URL: {h}")
517
    url = urlsplit(f"ssh://{h}" if h.count(":") <= 1 or h.startswith("[") else f"ssh://[{h}]")
518
    return url.hostname, url.port or int(auth.get("port") or 22)
519

520

521
def node(auth: arista_eos, timeout: float = 60):
522
    if auth.get("transport") == "ssh":
523
        return Ssh(auth, timeout)
524
    url = switch_url(auth)
525
    # ca_certificate: the PEM of a private CA, trusted instead of the system's CAs.
526
    context = ssl.create_default_context(cadata=(auth.get("ca_certificate") or "").strip() or None)
527
    if auth.get("verify_tls") is False:
528
        context.check_hostname = False
529
        context.verify_mode = ssl.CERT_NONE
530
    return pyeapi.connect(
531
        transport=url.scheme,
532
        host=url.hostname,
533
        port=url.port or auth.get("port") or None,
534
        username=auth["username"],
535
        password=auth["password"],
536
        context=context,
537
        timeout=timeout,
538
        return_node=True,
539
    )
540

541

542
# Shared by the Device scripts: the root flow run's user state, keyed by switch, holds the pre-check snapshot, the
543
# image activate replaced (rollback target), the image it booted and the reload markers. Every step of the run (nested
544
# subflows and retried attempts included) reads the same entry. Outside a flow the Device scripts share one state
545
# resource in the running user's home (a script's own state would keep the pre-check snapshot from the post-check).
546
# The endpoint is called through the client so an unreachable state raises (wmill.get_flow_user_state returns None).
547
# ponytail: the fallback is one map per user, so concurrent standalone runs can race; flows don't.
548
# The key is the switch's eAPI address: arista_eos-<host>-<port> with non-word characters in the host as _, the port
549
# always in (443 or 80 when unset). State written before the port was part of the key is read from arista_eos_<host>
550
# as a fallback (all word characters, so never a new key); writes go to the new key only.
551
def state_keys(auth: arista_eos):
552
    if auth.get("transport") == "ssh":
553
        host, port = ssh_addr(auth)
554
        return [f"arista_eos-{word(host)}-{port}"]
555
    url = switch_url(auth)
556
    port = int(url.port or auth.get("port") or {"https": 443, "http": 80}[url.scheme])
557
    return [
558
        f"arista_eos-{word(url.hostname)}-{port}",
559
        f"arista_eos_{word(auth['host'])}",
560
    ]
561

562

563
def word(s):
564
    return re.sub(r"\W", "_", s)
565

566

567
def load_state(keys):
568
    for key in keys:
569
        if os.environ.get("WM_FLOW_JOB_ID"):
570
            c = wmill.Windmill()
571
            value = c.get(
572
                f"/w/{c.workspace}/jobs/flow/user_states/{c.get_root_job_id()}/{key}"
573
            ).json()
574
        else:
575
            value = (wmill.get_state(standalone_state()) or {}).get(key)
576
        if value is not None:
577
            return value
578

579

580
def save_state(keys, value):
581
    if os.environ.get("WM_FLOW_JOB_ID"):
582
        c = wmill.Windmill()
583
        c.post(
584
            f"/w/{c.workspace}/jobs/flow/user_states/{c.get_root_job_id()}/{keys[0]}",
585
            json=value,
586
        )
587
    else:
588
        path = standalone_state()
589
        wmill.set_state({**(wmill.get_state(path) or {}), keys[0]: value}, path)
590

591

592
def standalone_state():
593
    return f"u/{os.environ['WM_USERNAME']}/arista_eos_state"
594

595

596
# "4.34.9M-51132493.4349M (engineering build)" on cEOS, "4.34.9M" on hardware.
597
def short_version(v):
598
    m = re.match(r"\d+\.\d+\.\d+(\.\d+)?[A-Z]*", v)
599
    return m.group(0) if m else v
600