0

Device commit

Published today

Save the upgraded switch's config (write memory), refused while a config-session commit timer is pending. Keeps the previous image on flash; delete_old_images removes the other EOS images. Returns { status: done, saved, deleted }. Raises DeviceUnreachable or AuthFailure.

Script arista_eos Verified

The script

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

6
# Device commit: write memory once the upgrade passed its post-check. Refused while a config session's commit timer is
7
# pending, so a change about to roll back isn't saved. The previous image stays on flash for a later rollback;
8
# delete_old_images removes only the other EOS images.
9

10
import logging
11
import os
12
import re
13
import ssl
14
from typing import TypedDict
15
from urllib.parse import urlsplit
16

17
import pyeapi
18
import wmill
19

20

21
class arista_eos(TypedDict):
22
    host: str
23
    username: str
24
    password: str
25
    port: int
26
    verify_tls: bool
27
    allow_http: bool
28

29

30
def main(auth: arista_eos, delete_old_images: bool = False):
31
    """
32
    Device commit
33
    Save the upgraded switch's config (write memory), refused while a config-session commit timer is pending. Keeps the previous image on flash; delete_old_images removes the other EOS images. Returns { status: done, saved, deleted }. Raises DeviceUnreachable or AuthFailure.
34
    """
35
    state = load_state(state_keys(auth)) or {}
36
    [sessions] = eapi(auth, ["show configuration sessions detail"])
37
    if sessions.get("commitTimerSessionName"):
38
        raise RuntimeError(
39
            f"config session {sessions['commitTimerSessionName']} is pending under a commit timer: confirm or abort it before commit (write memory)"
40
        )
41
    _, boot, d = eapi(
42
        auth,
43
        ["write memory", "show boot-config", {"cmd": "dir flash:/", "revision": 2}],
44
    )
45
    deleted = []
46
    # Rollback needs the previous image: only images that are neither booted nor the recorded previous one go.
47
    if delete_old_images and state.get("previous_image"):
48
        keep = [
49
            i.replace("flash:/", "")
50
            for i in (boot["softwareImage"], state["previous_image"])
51
        ]
52
        for f in list(d["urls"]["flash:/"]["entries"]):
53
            if re.match(r"^EOS.*\.swi$", f) and f not in keep:
54
                eapi(auth, [f"delete flash:{f}"])
55
                deleted.append(f)
56
    return {"status": "done", "saved": True, "deleted": deleted}
57

58

59
# Errors the workflow branches and retries on (retry_if: result.error.name == "DeviceUnreachable").
60
class DeviceUnreachable(Exception):
61
    pass
62

63

64
class AuthFailure(Exception):
65
    pass
66

67

68
# pyeapi logs a traceback for every socket error, and a rebooting switch gives many.
69
logging.getLogger("pyeapi").addHandler(logging.NullHandler())
70

71

72
def eapi(auth: arista_eos, cmds: list, fmt: str = "json", timeout: float = 60):
73
    eos = node(auth, timeout)
74
    try:
75
        return eos.run_commands(cmds, fmt)
76
    except pyeapi.eapilib.ConnectionError as e:
77
        raise connection_error(auth, eos, e)
78

79

80
# pyeapi 1.0.4 raises ConnectionError for a socket error (kept in socket_error), an answer that isn't JSON (eAPI
81
# still starting, 5xx) and a 401, the only one with neither.
82
def connection_error(auth, eos, e):
83
    if eos.connection.socket_error is None and e.message != "unable to connect to eAPI":
84
        return AuthFailure(f"{auth['host']}: eAPI refused the credential ({e.message})")
85
    return DeviceUnreachable(f"{auth['host']}: {e.message}")
86

87

88
# 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
89
# resource ticks allow_http (Basic auth then crosses the network in cleartext). pyeapi skips certificate checks unless it
90
# is given a context, so one is always passed: verifying, or not when the resource unticks verify_tls (EOS ships a
91
# self-signed cert).
92
def switch_url(auth: arista_eos):
93
    host = auth["host"]
94
    if "://" not in host:
95
        host = (
96
            f"https://[{host}]"
97
            if host.count(":") > 1 and "[" not in host
98
            else f"https://{host}"
99
        )
100
    url = urlsplit(host)
101
    if not url.hostname or (
102
        url.scheme != "https" and not (url.scheme == "http" and auth.get("allow_http"))
103
    ):
104
        raise ValueError(
105
            f"host must be an address or an https:// URL (http:// needs allow_http on the resource): {auth['host']}"
106
        )
107
    return url
108

109

110
def node(auth: arista_eos, timeout: float = 60):
111
    url = switch_url(auth)
112
    context = ssl.create_default_context()
113
    if auth.get("verify_tls") is False:
114
        context.check_hostname = False
115
        context.verify_mode = ssl.CERT_NONE
116
    return pyeapi.connect(
117
        transport=url.scheme,
118
        host=url.hostname,
119
        port=url.port or auth.get("port") or None,
120
        username=auth["username"],
121
        password=auth["password"],
122
        context=context,
123
        timeout=timeout,
124
        return_node=True,
125
    )
126

127

128
# Shared by the Device scripts: the root flow run's user state, keyed by switch, holds the pre-check snapshot, the
129
# image activate replaced (rollback target), the image it booted and the reload markers. Every step of the run (nested
130
# subflows and retried attempts included) reads the same entry. Outside a flow the Device scripts share one state
131
# resource in the running user's home (a script's own state would keep the pre-check snapshot from the post-check).
132
# The endpoint is called through the client so an unreachable state raises (wmill.get_flow_user_state returns None).
133
# ponytail: the fallback is one map per user, so concurrent standalone runs can race; flows don't.
134
# The key is the switch's eAPI address: arista_eos-<host>-<port> with non-word characters in the host as _, the port
135
# always in (443 or 80 when unset). State written before the port was part of the key is read from arista_eos_<host>
136
# as a fallback (all word characters, so never a new key); writes go to the new key only.
137
def state_keys(auth: arista_eos):
138
    url = switch_url(auth)
139
    port = int(url.port or auth.get("port") or {"https": 443, "http": 80}[url.scheme])
140
    return [
141
        f"arista_eos-{word(url.hostname)}-{port}",
142
        f"arista_eos_{word(auth['host'])}",
143
    ]
144

145

146
def word(s):
147
    return re.sub(r"\W", "_", s)
148

149

150
def load_state(keys):
151
    for key in keys:
152
        if os.environ.get("WM_FLOW_JOB_ID"):
153
            c = wmill.Windmill()
154
            value = c.get(
155
                f"/w/{c.workspace}/jobs/flow/user_states/{c.get_root_job_id()}/{key}"
156
            ).json()
157
        else:
158
            value = (wmill.get_state(standalone_state()) or {}).get(key)
159
        if value is not None:
160
            return value
161

162

163
def save_state(keys, value):
164
    if os.environ.get("WM_FLOW_JOB_ID"):
165
        c = wmill.Windmill()
166
        c.post(
167
            f"/w/{c.workspace}/jobs/flow/user_states/{c.get_root_job_id()}/{keys[0]}",
168
            json=value,
169
        )
170
    else:
171
        path = standalone_state()
172
        wmill.set_state({**(wmill.get_state(path) or {}), keys[0]: value}, path)
173

174

175
def standalone_state():
176
    return f"u/{os.environ['WM_USERNAME']}/arista_eos_state"
177

178

179
# "4.34.9M-51132493.4349M (engineering build)" on cEOS, "4.34.9M" on hardware.
180
def short_version(v):
181
    m = re.match(r"\d+\.\d+\.\d+(\.\d+)?[A-Z]*", v)
182
    return m.group(0) if m else v
183