Edits history of script submission #24214 for ' Device commit (arista_eos)'

  • python3
    One script reply has been approved by the moderators
    Ap­pro­ved
    # py312
    # requirements:
    # pyeapi==1.0.4
    # wmill==1.851.0
    
    # Device commit: write memory once the upgrade passed its post-check. Refused while a config session's commit timer is
    # pending, so a change about to roll back isn't saved. The previous image stays on flash for a later rollback;
    # delete_old_images removes only the other EOS images.
    
    import logging
    import os
    import re
    import ssl
    from typing import TypedDict
    from urllib.parse import urlsplit
    
    import pyeapi
    import wmill
    
    
    class arista_eos(TypedDict):
        host: str
        username: str
        password: str
        port: int
        verify_tls: bool
        allow_http: bool
    
    
    def main(auth: arista_eos, delete_old_images: bool = False):
        """
        Device commit
        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.
        """
        state = load_state(state_keys(auth)) or {}
        [sessions] = eapi(auth, ["show configuration sessions detail"])
        if sessions.get("commitTimerSessionName"):
            raise RuntimeError(
                f"config session {sessions['commitTimerSessionName']} is pending under a commit timer: confirm or abort it before commit (write memory)"
            )
        _, boot, d = eapi(
            auth,
            ["write memory", "show boot-config", {"cmd": "dir flash:/", "revision": 2}],
        )
        deleted = []
        # Rollback needs the previous image: only images that are neither booted nor the recorded previous one go.
        if delete_old_images and state.get("previous_image"):
            keep = [
                i.replace("flash:/", "")
                for i in (boot["softwareImage"], state["previous_image"])
            ]
            for f in list(d["urls"]["flash:/"]["entries"]):
                if re.match(r"^EOS.*\.swi$", f) and f not in keep:
                    eapi(auth, [f"delete flash:{f}"])
                    deleted.append(f)
        return {"status": "done", "saved": True, "deleted": deleted}
    
    
    # Errors the workflow branches and retries on (retry_if: result.error.name == "DeviceUnreachable").
    class DeviceUnreachable(Exception):
        pass
    
    
    class AuthFailure(Exception):
        pass
    
    
    # pyeapi logs a traceback for every socket error, and a rebooting switch gives many.
    logging.getLogger("pyeapi").addHandler(logging.NullHandler())
    
    
    def eapi(auth: arista_eos, cmds: list, fmt: str = "json", timeout: float = 60):
        eos = node(auth, timeout)
        try:
            return eos.run_commands(cmds, fmt)
        except pyeapi.eapilib.ConnectionError as e:
            raise connection_error(auth, eos, e)
    
    
    # pyeapi 1.0.4 raises ConnectionError for a socket error (kept in socket_error), an answer that isn't JSON (eAPI
    # still starting, 5xx) and a 401, the only one with neither.
    def connection_error(auth, eos, e):
        if eos.connection.socket_error is None and e.message != "unable to connect to eAPI":
            return AuthFailure(f"{auth['host']}: eAPI refused the credential ({e.message})")
        return DeviceUnreachable(f"{auth['host']}: {e.message}")
    
    
    # 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
    # resource ticks allow_http (Basic auth then crosses the network in cleartext). pyeapi skips certificate checks unless it
    # is given a context, so one is always passed: verifying, or not when the resource unticks verify_tls (EOS ships a
    # self-signed cert).
    def switch_url(auth: arista_eos):
        host = auth["host"]
        if "://" not in host:
            host = (
                f"https://[{host}]"
                if host.count(":") > 1 and "[" not in host
                else f"https://{host}"
            )
        url = urlsplit(host)
        if not url.hostname or (
            url.scheme != "https" and not (url.scheme == "http" and auth.get("allow_http"))
        ):
            raise ValueError(
                f"host must be an address or an https:// URL (http:// needs allow_http on the resource): {auth['host']}"
            )
        return url
    
    
    def node(auth: arista_eos, timeout: float = 60):
        url = switch_url(auth)
        context = ssl.create_default_context()
        if auth.get("verify_tls") is False:
            context.check_hostname = False
            context.verify_mode = ssl.CERT_NONE
        return pyeapi.connect(
            transport=url.scheme,
            host=url.hostname,
            port=url.port or auth.get("port") or None,
            username=auth["username"],
            password=auth["password"],
            context=context,
            timeout=timeout,
            return_node=True,
        )
    
    
    # Shared by the Device scripts: the root flow run's user state, keyed by switch, holds the pre-check snapshot, the
    # image activate replaced (rollback target), the image it booted and the reload markers. Every step of the run (nested
    # subflows and retried attempts included) reads the same entry. Outside a flow the Device scripts share one state
    # resource in the running user's home (a script's own state would keep the pre-check snapshot from the post-check).
    # The endpoint is called through the client so an unreachable state raises (wmill.get_flow_user_state returns None).
    # ponytail: the fallback is one map per user, so concurrent standalone runs can race; flows don't.
    # The key is the switch's eAPI address: arista_eos-<host>-<port> with non-word characters in the host as _, the port
    # always in (443 or 80 when unset). State written before the port was part of the key is read from arista_eos_<host>
    # as a fallback (all word characters, so never a new key); writes go to the new key only.
    def state_keys(auth: arista_eos):
        url = switch_url(auth)
        port = int(url.port or auth.get("port") or {"https": 443, "http": 80}[url.scheme])
        return [
            f"arista_eos-{word(url.hostname)}-{port}",
            f"arista_eos_{word(auth['host'])}",
        ]
    
    
    def word(s):
        return re.sub(r"\W", "_", s)
    
    
    def load_state(keys):
        for key in keys:
            if os.environ.get("WM_FLOW_JOB_ID"):
                c = wmill.Windmill()
                value = c.get(
                    f"/w/{c.workspace}/jobs/flow/user_states/{c.get_root_job_id()}/{key}"
                ).json()
            else:
                value = (wmill.get_state(standalone_state()) or {}).get(key)
            if value is not None:
                return value
    
    
    def save_state(keys, value):
        if os.environ.get("WM_FLOW_JOB_ID"):
            c = wmill.Windmill()
            c.post(
                f"/w/{c.workspace}/jobs/flow/user_states/{c.get_root_job_id()}/{keys[0]}",
                json=value,
            )
        else:
            path = standalone_state()
            wmill.set_state({**(wmill.get_state(path) or {}), keys[0]: value}, path)
    
    
    def standalone_state():
        return f"u/{os.environ['WM_USERNAME']}/arista_eos_state"
    
    
    # "4.34.9M-51132493.4349M (engineering build)" on cEOS, "4.34.9M" on hardware.
    def short_version(v):
        m = re.match(r"\d+\.\d+\.\d+(\.\d+)?[A-Z]*", v)
        return m.group(0) if m else v
    

    Submitted by hugo989 1 day ago