0

Device rollback

Published 5 days ago

Boot the switch back to its previous image and reload, exactly once per flow run (a retry skips it). Returns { reloaded, reason, boot_image, steps } (same shape when skipped). Raises RollbackFailed, DeviceUnreachable or AuthFailure. Follow it with Get Reload Delay. Higher-level and opinionated (checks, snapshot comparison and reload-once state in the flow run); to build your own upgrade logic, use Get Facts, Get Flash, Get Boot Config, Copy Image, Set Boot Image, Reload and Delete File.

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 rollback: boot system back to the image Device activate recorded as the previous one (or, in a new run, the
8
# only other EOS image on flash), then reload now behind the same once-per-run guard as Device reload. It is the
9
# recovery path: no unsaved-config check. A boot that this run's reload caused doesn't count against
10
# min_uptime_seconds. A switch that doesn't answer raises DeviceUnreachable (retry it); anything else RollbackFailed.
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
class RollbackFailed(Exception):
39
    pass
40

41

42
def main(auth: arista_eos, host: str = "", min_uptime_seconds: int = 300):
43
    """
44
    Device rollback
45
    Boot the switch back to its previous image and reload, exactly once per flow run (a retry skips it). Returns { reloaded, reason, boot_image, steps } (same shape when skipped). Raises RollbackFailed, DeviceUnreachable or AuthFailure. Follow it with Get Reload Delay. Higher-level and opinionated (checks, snapshot comparison and reload-once state in the flow run); to build your own upgrade logic, use Get Facts, Get Flash, Get Boot Config, Copy Image, Set Boot Image, Reload and Delete File.
46
    """
47
    auth = with_host(auth, host)
48
    key = state_keys(auth)
49
    state = load_state(key) or {}
50
    min_uptime = 300 if min_uptime_seconds is None else min_uptime_seconds
51
    sw = read_switch(auth, state, min_uptime)
52
    sent = sw["marker"]("rollback")
53
    if sw.get("unreachable"):
54
        if sent:
55
            return skip(
56
                f"rollback sent at {sent['sent_at']}; the switch no longer answers: it is reloading",
57
                state.get("previous_image"),
58
            )
59
        raise DeviceUnreachable(sw["unreachable"])
60
    if sent and (sent["confirmed"] or sent["boot_timestamp"] != sw["boot"]):
61
        return skip(guard_reason("rollback", sent, sw), state.get("previous_image"))
62
    try:
63
        d, boot = eapi(
64
            auth, [{"cmd": "dir flash:/", "revision": 2}, "show boot-config"]
65
        )
66
        files = list(d["urls"]["flash:/"]["entries"])
67
        current = boot["softwareImage"].replace("flash:/", "")
68
        # Without a recorded previous image (new run), the only other EOS image on flash is unambiguous.
69
        others = [f for f in files if re.match(r"^EOS.*\.swi$", f) and f != current]
70
        previous = (state.get("previous_image") or "").replace("flash:/", "") or (
71
            others[0] if len(others) == 1 else ""
72
        )
73
        if not previous:
74
            raise RollbackFailed(
75
                f"previous image unknown (EOS images on flash: {', '.join(others) or 'none'})"
76
            )
77
        if previous not in files:
78
            raise RollbackFailed(f"previous image {previous} is no longer on flash")
79
        reload = sw["marker"]("reload")
80
        if reload and reload["confirmed"] and reload["boot_timestamp"] == sw["boot"]:
81
            raise RollbackFailed(
82
                f"the reload sent at {reload['sent_at']} has not happened yet (same boot as when it was sent): rolling back now would race it, check the switch"
83
            )
84
        steps = boot_system(auth, previous)
85
        forget_activated(key, state)
86
        if sw["running"] == image_version(previous):
87
            return skip(
88
                f"already running the previous image {previous}; boot-config set back to it",
89
                f"flash:/{previous}",
90
                steps,
91
            )
92
        # A recent boot that this run's reload caused doesn't block the rollback: the post-check that ran after it
93
        # can end well inside min_uptime_seconds.
94
        ours = reload and reload["boot_timestamp"] != sw["boot"]
95
        if not ours and sw["uptime"] < min_uptime:
96
            return skip(
97
                f"rebooted {round(sw['uptime'])} s ago, not by this run",
98
                f"flash:/{previous}",
99
                steps,
100
            )
101
        fire_reload(auth, key, "rollback", sw["boot"])
102
    except (DeviceUnreachable, AuthFailure, RollbackFailed):
103
        raise
104
    except Exception as e:
105
        raise RollbackFailed(f"{auth['host']}: {e}")
106
    return {
107
        "reloaded": True,
108
        "reason": None,
109
        "boot_image": f"flash:/{previous}",
110
        "steps": steps,
111
    }
112

113

114
# One resource can serve every switch that shares a login: the host input, when set, overrides the resource's host.
115
def with_host(auth: arista_eos, host: str):
116
    host = (host or "").strip() or (auth.get("host") or "").strip()
117
    if not host:
118
        raise ValueError("host is required: set it on the resource or pass host")
119
    return {**auth, "host": host}
120

121

122
def boot_system(auth, image):
123
    _, set_, _, after = eapi(
124
        auth, ["configure", f"boot system flash:{image}", "end", "show boot-config"]
125
    )
126
    if after["softwareImage"] != f"flash:/{image}":
127
        raise Exception(f"boot-config still points to {after['softwareImage']}")
128
    return [f"boot system flash:{image}", *(set_.get("warnings") or [])]
129

130

131
def forget_activated(key, state):
132
    if state.pop("activated_image", None):
133
        save_state(key, state)
134

135

136
# Every return has the same shape. boot_image is the image rollback boots (or set boot-config back to); before flash
137
# is read it is the recorded previous image, which is null in a new run.
138
def skip(reason, boot_image=None, steps=()):
139
    return {
140
        "reloaded": False,
141
        "reason": reason,
142
        "boot_image": boot_image,
143
        "steps": list(steps),
144
    }
145

146

147
def guard_reason(kind, m, sw):
148
    if m["boot_timestamp"] == sw["boot"]:
149
        return f"{kind} sent at {m['sent_at']}; the switch is going down"
150
    return f"{kind} sent at {m['sent_at']} already rebooted the switch"
151

152

153
# A reload is sent at most once per switch and flow run. Each one leaves a marker { sent_at, boot_timestamp,
154
# confirmed }: boot_timestamp is the boot it was sent on, so a later boot means it happened, and confirmed means
155
# the command reached the switch. An unconfirmed marker on the same boot (the worker died first) is sent again.
156
# Outside a flow, a marker is dropped once the reboot it caused is min_uptime_seconds old.
157
def read_switch(auth, state, min_uptime):
158
    try:
159
        version, boot = eapi(auth, ["show version", "show boot-config"])
160
    except DeviceUnreachable as e:
161
        return {"unreachable": str(e), "marker": lambda k: state.get(k)}
162
    sw = {
163
        "running": short_version(version["version"]),
164
        "image": boot["softwareImage"],
165
        "boot": version["bootupTimestamp"],
166
        "uptime": version["uptime"],
167
    }
168
    in_flow = bool(os.environ.get("WM_FLOW_JOB_ID"))
169

170
    def marker(k):
171
        m = state.get(k)
172
        return (
173
            m
174
            if m
175
            and (
176
                in_flow
177
                or m["boot_timestamp"] == sw["boot"]
178
                or sw["uptime"] < min_uptime
179
            )
180
            else None
181
        )
182

183
    return {**sw, "marker": marker}
184

185

186
# Fire and forget: the switch drops the connection while going down, which is not an error. A connection that
187
# never opened, or a refusal from the switch, means it did not reload: the marker goes and the error is raised.
188
def fire_reload(auth, key, kind, boot_ts):
189
    def mark(m):
190
        rest = {k: v for k, v in (load_state(key) or {}).items() if k != kind}
191
        save_state(key, {**rest, kind: m} if m else rest)
192

193
    m = {
194
        "sent_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
195
        "boot_timestamp": boot_ts,
196
        "confirmed": False,
197
    }
198
    mark(m)
199
    eos = node(auth, 15)
200
    try:
201
        # Opened before sending, so a failure here means the command never left.
202
        eos.connection.transport.connect()
203
    except OSError as e:
204
        mark(None)
205
        raise DeviceUnreachable(f"{auth['host']}: {e}")
206
    try:
207
        eos.run_commands(["reload now"])
208
    except pyeapi.eapilib.ConnectionError as e:
209
        # Sent, then the connection dropped or timed out as the switch went down. A 401 is a refusal.
210
        err = connection_error(auth, eos, e)
211
        if isinstance(err, AuthFailure):
212
            mark(None)
213
            raise err
214
    except Exception:
215
        mark(None)
216
        raise
217
    mark({**m, "confirmed": True})
218

219

220
# "EOS64-4.34.9M.swi" -> "4.34.9M"
221
def image_version(file):
222
    m = re.search(r"-(\d+\.\d+\.\d+(\.\d+)?[A-Z]*)\.swi$", file)
223
    return m.group(1) if m else None
224

225

226
# Errors the workflow branches and retries on (retry_if: result.error.name == "DeviceUnreachable").
227
class DeviceUnreachable(Exception):
228
    pass
229

230

231
class AuthFailure(Exception):
232
    pass
233

234

235
# pyeapi logs a traceback for every socket error, and a rebooting switch gives many.
236
logging.getLogger("pyeapi").addHandler(logging.NullHandler())
237

238

239
def eapi(auth: arista_eos, cmds: list, fmt: str = "json", timeout: float = 60):
240
    eos = node(auth, timeout)
241
    try:
242
        return eos.run_commands(cmds, fmt)
243
    except pyeapi.eapilib.ConnectionError as e:
244
        raise connection_error(auth, eos, e)
245

246

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

257

258
# 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
259
# resource ticks allow_http (Basic auth then crosses the network in cleartext). pyeapi skips certificate checks unless it
260
# is given a context, so one is always passed: verifying, or not when the resource unticks verify_tls (EOS ships a
261
# self-signed cert).
262
def switch_url(auth: arista_eos):
263
    host = auth["host"]
264
    if "://" not in host:
265
        host = (
266
            f"https://[{host}]"
267
            if host.count(":") > 1 and "[" not in host
268
            else f"https://{host}"
269
        )
270
    url = urlsplit(host)
271
    if not url.hostname or (
272
        url.scheme != "https" and not (url.scheme == "http" and auth.get("allow_http"))
273
    ):
274
        raise ValueError(
275
            f"host must be an address or an https:// URL (http:// needs allow_http on the resource): {auth['host']}"
276
        )
277
    return url
278

279

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

292
    # The TCP connection only, like eAPI's transport.connect(): if it fails, nothing was sent.
293
    def connect(self):
294
        self.sock = socket.create_connection(ssh_addr(self.auth), self.timeout)
295

296
    def lost(self, e):
297
        self.socket_error = e
298
        return pyeapi.eapilib.ConnectionError("ssh", f"SSH connection failed ({e})")
299

300
    def open(self):
301
        auth = self.auth
302
        try:
303
            if not self.sock:
304
                self.connect()
305
            t = paramiko.Transport(self.sock)
306
            t.start_client(timeout=self.timeout)
307
            key = t.get_remote_server_key()
308
        except (OSError, EOFError, paramiko.SSHException) as e:
309
            raise self.lost(e)
310
        fp = "SHA256:" + base64.b64encode(hashlib.sha256(key.asbytes()).digest()).decode().rstrip("=")
311
        if auth.get("ssh_host_key") and auth["ssh_host_key"].strip() != fp:
312
            t.close()
313
            raise RuntimeError(f"{auth['host']}: the SSH host key is {fp}, not the resource's ssh_host_key")
314
        try:
315
            try:
316
                t.auth_password(auth["username"], auth["password"])
317
            except paramiko.BadAuthenticationType:
318
                t.auth_interactive(
319
                    auth["username"], lambda _t, _i, prompts: [auth["password"]] * len(prompts)
320
                )
321
        except paramiko.AuthenticationException as e:
322
            t.close()
323
            raise pyeapi.eapilib.ConnectionError("ssh", str(e))
324
        except (OSError, EOFError, paramiko.SSHException) as e:
325
            raise self.lost(e)
326
        try:
327
            self.chan = t.open_session()
328
            self.chan.get_pty(width=4000)
329
            self.chan.invoke_shell()
330
            self.prompt = None
331
            out = self.read()
332
            self.prompt = re.escape(re.split(r"[(>#]", out.splitlines()[-1].strip())[0])
333
            if out.rstrip().endswith(">"):
334
                self.cli("enable")
335
            self.cli("terminal length 0")
336
            self.cli("terminal width 32767")
337
        except (OSError, EOFError, paramiko.SSHException) as e:
338
            raise self.lost(e)
339

340
    # Reads until the prompt. Questions eAPI never asks are answered as eAPI behaves: confirm, don't save.
341
    def read(self):
342
        buf, end = "", time.monotonic() + self.timeout
343
        prompt = (self.prompt or r"[\w.\-]+") + r"(\([^)\r\n]*\))?[>#] ?$"
344
        while True:
345
            self.chan.settimeout(max(end - time.monotonic(), 0.01))
346
            chunk = self.chan.recv(65536)
347
            if not chunk:
348
                raise self.lost("connection closed")
349
            buf += chunk.decode(errors="replace")
350
            tail = buf[-300:]
351
            if re.search(r"(^|\n)" + prompt, tail):
352
                return buf
353
            for question, answer in (
354
                # enable asks for a password on switches that land the user unprivileged: the login password.
355
                (r"(^|\n)Password:\s*$", self.auth["password"]),
356
                (r"\[confirm\]\s*$", ""),
357
                (r"Save\?.*\[yes/no[^\]]*\]:?\s*$", "no"),
358
                (r"\[(y|yes)/(n|no)\][:?]?\s*$", "y"),
359
            ):
360
                if re.search(question, tail, re.I):
361
                    self.chan.send(answer + "\r")
362
                    buf += "\n"
363

364
    # One command: its output without the echoed command and the prompt; progress lines keep their last state.
365
    def cli(self, cmd):
366
        try:
367
            self.chan.send(cmd + "\r")
368
            out = self.read()
369
        except (OSError, EOFError, paramiko.SSHException) as e:
370
            raise self.lost(e)
371
        self.mode = out.rstrip().splitlines()[-1]
372
        lines = [l.rstrip("\r").split("\r")[-1] for l in out.split("\n")]
373
        return "\n".join(lines[1:-1]).strip("\n")
374

375
    def run_commands(self, cmds, encoding="json", **_):
376
        try:
377
            if not self.chan:
378
                self.open()
379
            if "(config" in self.mode:
380
                self.cli("end")
381
            results = []
382
            for i, c in enumerate(cmds):
383
                # eAPI's { cmd, revision } form is the CLI's "| json revision N".
384
                cmd, rev = (c["cmd"], c.get("revision")) if isinstance(c, dict) else (c, None)
385
                show = encoding == "json" and (rev or re.match(r"\s*sh(ow)?\s", cmd)) and not re.search(r"\|\s*json", cmd)
386
                # pyeapi sends "<cmd> MULTILINE: <text>" (banners) as cmd + input; the CLI reads the text up to EOF.
387
                head, multi, text = cmd.partition("MULTILINE:")
388
                # The shell would run what follows a line break as another command; eAPI refuses it too.
389
                if re.search(r"[\r\n]", head):
390
                    raise ValueError(f"a command may not contain a line break: {head!r}")
391
                line = "\r".join([head.strip(), *text.strip().splitlines(), "EOF"]) if multi else cmd
392
                out = self.cli(f"{cmd} | json{f' revision {rev}' if rev else ''}" if show else line)
393
                errors = [l[2:] for l in out.splitlines() if l.startswith("% ")]
394
                code, kind = 1002, "invalid command"
395
                if show and not errors:
396
                    code, kind = 1000, "could not run command"
397
                    try:
398
                        result = json.loads(out)
399
                    except ValueError:
400
                        errors = [out[:200]]
401
                    else:
402
                        errors = result.get("errors") or []
403
                if errors:
404
                    raise pyeapi.eapilib.CommandError(
405
                        code,
406
                        f"CLI command {i + 2} of {len(cmds) + 1} '{cmd}' failed: {kind}",
407
                        command_error="; ".join(errors),
408
                        commands=cmds,
409
                        output=results,
410
                    )
411
                if encoding != "json":
412
                    result = {"output": out + "\n" if out else ""}
413
                elif not show:
414
                    # The CLI prints eAPI's warnings as "! " notices.
415
                    notices = [l[2:].strip() for l in out.splitlines() if l.startswith("! ")]
416
                    out = "\n".join(l for l in out.splitlines() if not l.startswith("! ")).strip()
417
                    result = {"messages": [out]} if out and not multi else {}
418
                    if notices:
419
                        result["warnings"] = notices
420
                results.append(result)
421
            return results
422
        except pyeapi.eapilib.ConnectionError:
423
            if self.chan:
424
                self.chan.close()
425
            self.sock = self.chan = None
426
            raise
427

428

429
# paramiko logs a traceback when a rebooting switch drops the session.
430
logging.getLogger("paramiko").addHandler(logging.NullHandler())
431

432

433
# host, or host:port ([v6]:port), else port, else 22.
434
def ssh_addr(auth: arista_eos):
435
    h = auth["host"]
436
    if "://" in h:
437
        raise ValueError(f"with transport ssh, host is an address or a hostname (with :port), not a URL: {h}")
438
    url = urlsplit(f"ssh://{h}" if h.count(":") <= 1 or h.startswith("[") else f"ssh://[{h}]")
439
    return url.hostname, url.port or int(auth.get("port") or 22)
440

441

442
def node(auth: arista_eos, timeout: float = 60):
443
    if auth.get("transport") == "ssh":
444
        return Ssh(auth, timeout)
445
    url = switch_url(auth)
446
    # ca_certificate: the PEM of a private CA, trusted instead of the system's CAs.
447
    context = ssl.create_default_context(cadata=(auth.get("ca_certificate") or "").strip() or None)
448
    if auth.get("verify_tls") is False:
449
        context.check_hostname = False
450
        context.verify_mode = ssl.CERT_NONE
451
    return pyeapi.connect(
452
        transport=url.scheme,
453
        host=url.hostname,
454
        port=url.port or auth.get("port") or None,
455
        username=auth["username"],
456
        password=auth["password"],
457
        context=context,
458
        timeout=timeout,
459
        return_node=True,
460
    )
461

462

463
# Shared by the Device scripts: the root flow run's user state, keyed by switch, holds the pre-check snapshot, the
464
# image activate replaced (rollback target), the image it booted and the reload markers. Every step of the run (nested
465
# subflows and retried attempts included) reads the same entry. Outside a flow the Device scripts share one state
466
# resource in the running user's home (a script's own state would keep the pre-check snapshot from the post-check).
467
# The endpoint is called through the client so an unreachable state raises (wmill.get_flow_user_state returns None).
468
# ponytail: the fallback is one map per user, so concurrent standalone runs can race; flows don't.
469
# The key is the switch's eAPI address: arista_eos-<host>-<port> with non-word characters in the host as _, the port
470
# always in (443 or 80 when unset). State written before the port was part of the key is read from arista_eos_<host>
471
# as a fallback (all word characters, so never a new key); writes go to the new key only.
472
def state_keys(auth: arista_eos):
473
    if auth.get("transport") == "ssh":
474
        host, port = ssh_addr(auth)
475
        return [f"arista_eos-{word(host)}-{port}"]
476
    url = switch_url(auth)
477
    port = int(url.port or auth.get("port") or {"https": 443, "http": 80}[url.scheme])
478
    return [
479
        f"arista_eos-{word(url.hostname)}-{port}",
480
        f"arista_eos_{word(auth['host'])}",
481
    ]
482

483

484
def word(s):
485
    return re.sub(r"\W", "_", s)
486

487

488
def load_state(keys):
489
    for key in keys:
490
        if os.environ.get("WM_FLOW_JOB_ID"):
491
            c = wmill.Windmill()
492
            value = c.get(
493
                f"/w/{c.workspace}/jobs/flow/user_states/{c.get_root_job_id()}/{key}"
494
            ).json()
495
        else:
496
            value = (wmill.get_state(standalone_state()) or {}).get(key)
497
        if value is not None:
498
            return value
499

500

501
def save_state(keys, value):
502
    if os.environ.get("WM_FLOW_JOB_ID"):
503
        c = wmill.Windmill()
504
        c.post(
505
            f"/w/{c.workspace}/jobs/flow/user_states/{c.get_root_job_id()}/{keys[0]}",
506
            json=value,
507
        )
508
    else:
509
        path = standalone_state()
510
        wmill.set_state({**(wmill.get_state(path) or {}), keys[0]: value}, path)
511

512

513
def standalone_state():
514
    return f"u/{os.environ['WM_USERNAME']}/arista_eos_state"
515

516

517
# "4.34.9M-51132493.4349M (engineering build)" on cEOS, "4.34.9M" on hardware.
518
def short_version(v):
519
    m = re.match(r"\d+\.\d+\.\d+(\.\d+)?[A-Z]*", v)
520
    return m.group(0) if m else v
521