0

Device post-check

Published 5 days ago

One post-upgrade check of one switch against the pre-check snapshot of this flow run: when it matches, returns { running_version, uptime_seconds, snapshot_at, snapshot } (snapshot is the state read now, the same shape as Device pre-check's). Raises DeviceUnreachable while the switch is down or still on the boot the reload was sent on, NotStable while interfaces/LLDP/MLAG differ from the snapshot (differences in the message), AuthFailure when the credential is refused. Retry it from the workflow; it does not wait. 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 post-check: one attempt, after an upgrade (or rollback) of one switch. Compares the switch with the snapshot
8
# Device pre-check saved in this flow run, and raises a named error the workflow retries on:
9
# - DeviceUnreachable while the switch is down or still runs the boot a reload of this run was sent on;
10
# - NotStable while the state differs from the snapshot (the differences are in the message; ports stay errdisabled
11
#   until the MLAG reload-delay has run, the message says how much of it is left);
12
# - AuthFailure when the credential is refused (not worth retrying).
13
# No snapshot in this run is a plain error. On a match it returns the version, uptime and the state it read; the
14
# version is reported, not compared with a target.
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
from typing import TypedDict
26
from urllib.parse import urlsplit
27

28
import paramiko
29
import pyeapi
30
import wmill
31

32

33
class arista_eos(TypedDict):
34
    host: str
35
    username: str
36
    password: str
37
    port: int
38
    verify_tls: bool
39
    allow_http: bool
40

41

42
class NotStable(Exception):
43
    pass
44

45

46
def main(auth: arista_eos, host: str = ""):
47
    """
48
    Device post-check
49
    One post-upgrade check of one switch against the pre-check snapshot of this flow run: when it matches, returns { running_version, uptime_seconds, snapshot_at, snapshot } (snapshot is the state read now, the same shape as Device pre-check's). Raises DeviceUnreachable while the switch is down or still on the boot the reload was sent on, NotStable while interfaces/LLDP/MLAG differ from the snapshot (differences in the message), AuthFailure when the credential is refused. Retry it from the workflow; it does not wait. 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.
50
    """
51
    auth = with_host(auth, host)
52
    state = load_state(state_keys(auth)) or {}
53
    # Before probing the switch: without a snapshot, retrying through a reboot would only delay the same error.
54
    if not state.get("snapshot"):
55
        raise RuntimeError(
56
            f"No pre-check snapshot for {auth['host']} in this flow run: run Device pre-check first, in the same run"
57
        )
58
    version = returned(auth, state)
59
    current = snapshot(auth)
60
    problems = diff(state["snapshot"], current)
61
    if problems:
62
        [mlag] = eapi(auth, ["show mlag"])
63
        left = round(reload_delay(mlag) - version["uptime"])
64
        hint = f" (MLAG reload-delay still running: {left} s left)" if left > 0 else ""
65
        raise NotStable(f"{auth['host']}: {'; '.join(problems)}{hint}")
66
    return {
67
        "running_version": short_version(version["version"]),
68
        "uptime_seconds": round(version["uptime"]),
69
        "snapshot_at": state.get("snapshot_at"),
70
        "snapshot": current,
71
    }
72

73

74
# One resource can serve every switch that shares a login: the host input, when set, overrides the resource's host.
75
def with_host(auth: arista_eos, host: str):
76
    host = (host or "").strip() or (auth.get("host") or "").strip()
77
    if not host:
78
        raise ValueError("host is required: set it on the resource or pass host")
79
    return {**auth, "host": host}
80

81

82
# Same function in Get Reload Delay and Device post-check. One attempt: show version, raising DeviceUnreachable
83
# while the switch is down, and while it still runs the boot a reload of this run was sent on (reload now can answer
84
# before EOS goes down, and the old boot must not pass for the new one). AuthFailure is raised as is.
85
def returned(auth, state):
86
    try:
87
        # Short: a switch that is down holds the attempt for the whole timeout, and the workflow retries anyway.
88
        [v] = eapi(auth, ["show version"], timeout=15)
89
    except DeviceUnreachable as e:
90
        raise DeviceUnreachable(f"{e}: not back yet")
91
    for k in ("reload", "rollback"):
92
        m = state.get(k)
93
        if m and m["boot_timestamp"] == v["bootupTimestamp"]:
94
            raise DeviceUnreachable(
95
                f"{auth['host']}: still on the boot the {k} sent at {m['sent_at']} was sent on"
96
            )
97
    return v
98

99

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

105

106
def snapshot(auth):
107
    status, lldp, mlag, mlag_intf = eapi(
108
        auth,
109
        [
110
            "show interfaces status",
111
            "show lldp neighbors",
112
            "show mlag",
113
            "show mlag interfaces",
114
        ],
115
    )
116
    return {
117
        "interfaces_up": sorted(
118
            n
119
            for n, i in status["interfaceStatuses"].items()
120
            if i.get("linkStatus") == "connected"
121
        ),
122
        "lldp": [
123
            {
124
                "port": n["port"],
125
                "neighbor": f"{n['neighborDevice']} {n['neighborPort']}",
126
            }
127
            for n in lldp["lldpNeighbors"]
128
        ],
129
        "mlag": {
130
            "state": mlag.get("state"),
131
            "negStatus": mlag.get("negStatus"),
132
            "peerLinkStatus": mlag.get("peerLinkStatus"),
133
            "ports": {
134
                f"{i['localInterface']} (mlag {id})": i["status"]
135
                for id, i in (mlag_intf.get("interfaces") or {}).items()
136
            },
137
        },
138
    }
139

140

141
def diff(before, after):
142
    p = []
143
    for i in before["interfaces_up"]:
144
        if i not in after["interfaces_up"]:
145
            p.append(f"{i} down after the upgrade (up before)")
146
    for n in before["lldp"]:
147
        if not any(
148
            a["port"] == n["port"] and a["neighbor"] == n["neighbor"]
149
            for a in after["lldp"]
150
        ):
151
            p.append(f"LLDP neighbor {n['neighbor']} no longer seen on {n['port']}")
152
    for k in ("state", "negStatus", "peerLinkStatus"):
153
        if before["mlag"][k] != after["mlag"][k]:
154
            p.append(f"MLAG {k} {after['mlag'][k]} (was {before['mlag'][k]})")
155
    for port, s in before["mlag"]["ports"].items():
156
        if after["mlag"]["ports"].get(port) != s:
157
            p.append(f"{port} {after['mlag']['ports'].get(port, 'missing')} (was {s})")
158
    return p
159

160

161
# Without MLAG configured, show mlag still reports the default reload-delay, and nothing waits on it.
162
def reload_delay(mlag):
163
    if not mlag_configured(mlag):
164
        return 0
165
    return max(mlag.get("reloadDelay") or 0, mlag.get("reloadDelayNonMlag") or 0)
166

167

168
# Errors the workflow branches and retries on (retry_if: result.error.name == "DeviceUnreachable").
169
class DeviceUnreachable(Exception):
170
    pass
171

172

173
class AuthFailure(Exception):
174
    pass
175

176

177
# pyeapi logs a traceback for every socket error, and a rebooting switch gives many.
178
logging.getLogger("pyeapi").addHandler(logging.NullHandler())
179

180

181
# This script runs right after a reboot, when eAPI can answer before the EOS agents behind a show command have
182
# started: such an error answer counts as not back yet, so the workflow retries it. It only sends show commands.
183
def eapi(auth: arista_eos, cmds: list, fmt: str = "json", timeout: float = 60):
184
    eos = node(auth, timeout)
185
    try:
186
        return eos.run_commands(cmds, fmt)
187
    except pyeapi.eapilib.ConnectionError as e:
188
        raise connection_error(auth, eos, e)
189
    except pyeapi.eapilib.CommandError as e:
190
        raise DeviceUnreachable(f"{auth['host']}: not ready yet ({e.message})")
191

192

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

203

204
# 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
205
# resource ticks allow_http (Basic auth then crosses the network in cleartext). pyeapi skips certificate checks unless it
206
# is given a context, so one is always passed: verifying, or not when the resource unticks verify_tls (EOS ships a
207
# self-signed cert).
208
def switch_url(auth: arista_eos):
209
    host = auth["host"]
210
    if "://" not in host:
211
        host = (
212
            f"https://[{host}]"
213
            if host.count(":") > 1 and "[" not in host
214
            else f"https://{host}"
215
        )
216
    url = urlsplit(host)
217
    if not url.hostname or (
218
        url.scheme != "https" and not (url.scheme == "http" and auth.get("allow_http"))
219
    ):
220
        raise ValueError(
221
            f"host must be an address or an https:// URL (http:// needs allow_http on the resource): {auth['host']}"
222
        )
223
    return url
224

225

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

238
    # The TCP connection only, like eAPI's transport.connect(): if it fails, nothing was sent.
239
    def connect(self):
240
        self.sock = socket.create_connection(ssh_addr(self.auth), self.timeout)
241

242
    def lost(self, e):
243
        self.socket_error = e
244
        return pyeapi.eapilib.ConnectionError("ssh", f"SSH connection failed ({e})")
245

246
    def open(self):
247
        auth = self.auth
248
        try:
249
            if not self.sock:
250
                self.connect()
251
            t = paramiko.Transport(self.sock)
252
            t.start_client(timeout=self.timeout)
253
            key = t.get_remote_server_key()
254
        except (OSError, EOFError, paramiko.SSHException) as e:
255
            raise self.lost(e)
256
        fp = "SHA256:" + base64.b64encode(hashlib.sha256(key.asbytes()).digest()).decode().rstrip("=")
257
        if auth.get("ssh_host_key") and auth["ssh_host_key"].strip() != fp:
258
            t.close()
259
            raise RuntimeError(f"{auth['host']}: the SSH host key is {fp}, not the resource's ssh_host_key")
260
        try:
261
            try:
262
                t.auth_password(auth["username"], auth["password"])
263
            except paramiko.BadAuthenticationType:
264
                t.auth_interactive(
265
                    auth["username"], lambda _t, _i, prompts: [auth["password"]] * len(prompts)
266
                )
267
        except paramiko.AuthenticationException as e:
268
            t.close()
269
            raise pyeapi.eapilib.ConnectionError("ssh", str(e))
270
        except (OSError, EOFError, paramiko.SSHException) as e:
271
            raise self.lost(e)
272
        try:
273
            self.chan = t.open_session()
274
            self.chan.get_pty(width=4000)
275
            self.chan.invoke_shell()
276
            self.prompt = None
277
            out = self.read()
278
            self.prompt = re.escape(re.split(r"[(>#]", out.splitlines()[-1].strip())[0])
279
            if out.rstrip().endswith(">"):
280
                self.cli("enable")
281
            self.cli("terminal length 0")
282
            self.cli("terminal width 32767")
283
        except (OSError, EOFError, paramiko.SSHException) as e:
284
            raise self.lost(e)
285

286
    # Reads until the prompt. Questions eAPI never asks are answered as eAPI behaves: confirm, don't save.
287
    def read(self):
288
        buf, end = "", time.monotonic() + self.timeout
289
        prompt = (self.prompt or r"[\w.\-]+") + r"(\([^)\r\n]*\))?[>#] ?$"
290
        while True:
291
            self.chan.settimeout(max(end - time.monotonic(), 0.01))
292
            chunk = self.chan.recv(65536)
293
            if not chunk:
294
                raise self.lost("connection closed")
295
            buf += chunk.decode(errors="replace")
296
            tail = buf[-300:]
297
            if re.search(r"(^|\n)" + prompt, tail):
298
                return buf
299
            for question, answer in (
300
                # enable asks for a password on switches that land the user unprivileged: the login password.
301
                (r"(^|\n)Password:\s*$", self.auth["password"]),
302
                (r"\[confirm\]\s*$", ""),
303
                (r"Save\?.*\[yes/no[^\]]*\]:?\s*$", "no"),
304
                (r"\[(y|yes)/(n|no)\][:?]?\s*$", "y"),
305
            ):
306
                if re.search(question, tail, re.I):
307
                    self.chan.send(answer + "\r")
308
                    buf += "\n"
309

310
    # One command: its output without the echoed command and the prompt; progress lines keep their last state.
311
    def cli(self, cmd):
312
        try:
313
            self.chan.send(cmd + "\r")
314
            out = self.read()
315
        except (OSError, EOFError, paramiko.SSHException) as e:
316
            raise self.lost(e)
317
        self.mode = out.rstrip().splitlines()[-1]
318
        lines = [l.rstrip("\r").split("\r")[-1] for l in out.split("\n")]
319
        return "\n".join(lines[1:-1]).strip("\n")
320

321
    def run_commands(self, cmds, encoding="json", **_):
322
        try:
323
            if not self.chan:
324
                self.open()
325
            if "(config" in self.mode:
326
                self.cli("end")
327
            results = []
328
            for i, c in enumerate(cmds):
329
                # eAPI's { cmd, revision } form is the CLI's "| json revision N".
330
                cmd, rev = (c["cmd"], c.get("revision")) if isinstance(c, dict) else (c, None)
331
                show = encoding == "json" and (rev or re.match(r"\s*sh(ow)?\s", cmd)) and not re.search(r"\|\s*json", cmd)
332
                # pyeapi sends "<cmd> MULTILINE: <text>" (banners) as cmd + input; the CLI reads the text up to EOF.
333
                head, multi, text = cmd.partition("MULTILINE:")
334
                # The shell would run what follows a line break as another command; eAPI refuses it too.
335
                if re.search(r"[\r\n]", head):
336
                    raise ValueError(f"a command may not contain a line break: {head!r}")
337
                line = "\r".join([head.strip(), *text.strip().splitlines(), "EOF"]) if multi else cmd
338
                out = self.cli(f"{cmd} | json{f' revision {rev}' if rev else ''}" if show else line)
339
                errors = [l[2:] for l in out.splitlines() if l.startswith("% ")]
340
                code, kind = 1002, "invalid command"
341
                if show and not errors:
342
                    code, kind = 1000, "could not run command"
343
                    try:
344
                        result = json.loads(out)
345
                    except ValueError:
346
                        errors = [out[:200]]
347
                    else:
348
                        errors = result.get("errors") or []
349
                if errors:
350
                    raise pyeapi.eapilib.CommandError(
351
                        code,
352
                        f"CLI command {i + 2} of {len(cmds) + 1} '{cmd}' failed: {kind}",
353
                        command_error="; ".join(errors),
354
                        commands=cmds,
355
                        output=results,
356
                    )
357
                if encoding != "json":
358
                    result = {"output": out + "\n" if out else ""}
359
                elif not show:
360
                    # The CLI prints eAPI's warnings as "! " notices.
361
                    notices = [l[2:].strip() for l in out.splitlines() if l.startswith("! ")]
362
                    out = "\n".join(l for l in out.splitlines() if not l.startswith("! ")).strip()
363
                    result = {"messages": [out]} if out and not multi else {}
364
                    if notices:
365
                        result["warnings"] = notices
366
                results.append(result)
367
            return results
368
        except pyeapi.eapilib.ConnectionError:
369
            if self.chan:
370
                self.chan.close()
371
            self.sock = self.chan = None
372
            raise
373

374

375
# paramiko logs a traceback when a rebooting switch drops the session.
376
logging.getLogger("paramiko").addHandler(logging.NullHandler())
377

378

379
# host, or host:port ([v6]:port), else port, else 22.
380
def ssh_addr(auth: arista_eos):
381
    h = auth["host"]
382
    if "://" in h:
383
        raise ValueError(f"with transport ssh, host is an address or a hostname (with :port), not a URL: {h}")
384
    url = urlsplit(f"ssh://{h}" if h.count(":") <= 1 or h.startswith("[") else f"ssh://[{h}]")
385
    return url.hostname, url.port or int(auth.get("port") or 22)
386

387

388
def node(auth: arista_eos, timeout: float = 60):
389
    if auth.get("transport") == "ssh":
390
        return Ssh(auth, timeout)
391
    url = switch_url(auth)
392
    # ca_certificate: the PEM of a private CA, trusted instead of the system's CAs.
393
    context = ssl.create_default_context(cadata=(auth.get("ca_certificate") or "").strip() or None)
394
    if auth.get("verify_tls") is False:
395
        context.check_hostname = False
396
        context.verify_mode = ssl.CERT_NONE
397
    return pyeapi.connect(
398
        transport=url.scheme,
399
        host=url.hostname,
400
        port=url.port or auth.get("port") or None,
401
        username=auth["username"],
402
        password=auth["password"],
403
        context=context,
404
        timeout=timeout,
405
        return_node=True,
406
    )
407

408

409
# Shared by the Device scripts: the root flow run's user state, keyed by switch, holds the pre-check snapshot, the
410
# image activate replaced (rollback target), the image it booted and the reload markers. Every step of the run (nested
411
# subflows and retried attempts included) reads the same entry. Outside a flow the Device scripts share one state
412
# resource in the running user's home (a script's own state would keep the pre-check snapshot from the post-check).
413
# The endpoint is called through the client so an unreachable state raises (wmill.get_flow_user_state returns None).
414
# ponytail: the fallback is one map per user, so concurrent standalone runs can race; flows don't.
415
# The key is the switch's eAPI address: arista_eos-<host>-<port> with non-word characters in the host as _, the port
416
# always in (443 or 80 when unset). State written before the port was part of the key is read from arista_eos_<host>
417
# as a fallback (all word characters, so never a new key); writes go to the new key only.
418
def state_keys(auth: arista_eos):
419
    if auth.get("transport") == "ssh":
420
        host, port = ssh_addr(auth)
421
        return [f"arista_eos-{word(host)}-{port}"]
422
    url = switch_url(auth)
423
    port = int(url.port or auth.get("port") or {"https": 443, "http": 80}[url.scheme])
424
    return [
425
        f"arista_eos-{word(url.hostname)}-{port}",
426
        f"arista_eos_{word(auth['host'])}",
427
    ]
428

429

430
def word(s):
431
    return re.sub(r"\W", "_", s)
432

433

434
def load_state(keys):
435
    for key in keys:
436
        if os.environ.get("WM_FLOW_JOB_ID"):
437
            c = wmill.Windmill()
438
            value = c.get(
439
                f"/w/{c.workspace}/jobs/flow/user_states/{c.get_root_job_id()}/{key}"
440
            ).json()
441
        else:
442
            value = (wmill.get_state(standalone_state()) or {}).get(key)
443
        if value is not None:
444
            return value
445

446

447
def save_state(keys, value):
448
    if os.environ.get("WM_FLOW_JOB_ID"):
449
        c = wmill.Windmill()
450
        c.post(
451
            f"/w/{c.workspace}/jobs/flow/user_states/{c.get_root_job_id()}/{keys[0]}",
452
            json=value,
453
        )
454
    else:
455
        path = standalone_state()
456
        wmill.set_state({**(wmill.get_state(path) or {}), keys[0]: value}, path)
457

458

459
def standalone_state():
460
    return f"u/{os.environ['WM_USERNAME']}/arista_eos_state"
461

462

463
# "4.34.9M-51132493.4349M (engineering build)" on cEOS, "4.34.9M" on hardware.
464
def short_version(v):
465
    m = re.match(r"\d+\.\d+\.\d+(\.\d+)?[A-Z]*", v)
466
    return m.group(0) if m else v
467