enodix 0.7.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
enodix/__init__.py ADDED
@@ -0,0 +1,180 @@
1
+ """The workspace of the app, for Python scripts.
2
+
3
+ Everything goes through the app's headless binary (``enodix-cli``), found
4
+ by :func:`find_cli`: the resolved inventory, a host's login from its
5
+ credential profile, and named secrets. Credentials travel only over the
6
+ binary's output pipe to this process; nothing is written to disk or put in
7
+ the environment.
8
+
9
+ Hosts behind the app's jump hosts are reached through loopback tunnels the
10
+ binary opens (:func:`tunnels`), for their SSH port and any other device
11
+ port a script names; :func:`endpoint` says where to connect for a port of
12
+ a host, tunnelled or not. The Nornir plugin opens them itself.
13
+
14
+ The Nornir inventory plugin is :class:`enodix.nornir.EnodixInventory`
15
+ (registered as ``EnodixInventory``); it needs Nornir, which this package
16
+ does not install.
17
+
18
+ Run by the app as a script job, a script finds its workspace in
19
+ ``ENODIX_WORKSPACE`` (the default of every ``workspace`` argument here), and
20
+ the binary shows it only the job's hosts and hands over only their logins.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import os
26
+ from os import PathLike, fspath
27
+ from typing import Any, Dict, Iterable, List, Optional, Union
28
+
29
+ from ._cli import (
30
+ CliFailed,
31
+ CliNotFound,
32
+ EnodixError,
33
+ VersionWarning,
34
+ default_location,
35
+ find_cli,
36
+ option,
37
+ run,
38
+ values,
39
+ )
40
+ from ._tunnel import Endpoint, Tunnels, Unreachable, endpoint, host_key_options, ports_of
41
+
42
+ try:
43
+ from ._build import VERSION as __version__
44
+ except ImportError: # the source tree
45
+ __version__ = "0+source"
46
+
47
+ __all__ = [
48
+ "CliFailed",
49
+ "CliNotFound",
50
+ "Endpoint",
51
+ "EnodixError",
52
+ "Tunnels",
53
+ "Unreachable",
54
+ "VersionWarning",
55
+ "credentials",
56
+ "default_location",
57
+ "endpoint",
58
+ "job_workspace",
59
+ "find_cli",
60
+ "host_key_options",
61
+ "inventory",
62
+ "secret",
63
+ "tunnels",
64
+ ]
65
+
66
+ Folder = Union[str, "PathLike[str]"]
67
+
68
+ #: The variable the app sets for a script job: the workspace folder.
69
+ WORKSPACE_VARIABLE = "ENODIX_WORKSPACE"
70
+
71
+
72
+ def job_workspace() -> Optional[str]:
73
+ """The workspace folder of the script job this script runs in (the app
74
+ sets ``ENODIX_WORKSPACE``), or ``None`` when it was not started by one."""
75
+ return os.environ.get(WORKSPACE_VARIABLE) or None
76
+
77
+
78
+ def _workspace(workspace: Optional[Folder]) -> str:
79
+ if workspace is not None:
80
+ return fspath(workspace)
81
+ found = job_workspace()
82
+ if found is None:
83
+ raise EnodixError(
84
+ "no workspace given: pass the workspace folder (it is only known by itself "
85
+ f"in a script job, which sets {WORKSPACE_VARIABLE})"
86
+ )
87
+ return found
88
+
89
+
90
+ def inventory(
91
+ workspace: Optional[Folder] = None,
92
+ *,
93
+ folder: Optional[str] = None,
94
+ filter: Optional[str] = None,
95
+ hosts: Optional[Iterable[str]] = None,
96
+ ) -> Dict[str, Any]:
97
+ """The workspace's resolved inventory, as the binary exports it
98
+ (``enodix-cli inventory``, format 1): every host with the settings
99
+ that apply to it, its jump hosts, folders, tags and custom fields; no
100
+ secrets. Limit it to one of: the hosts in ``folder`` and below, those
101
+ of the saved filter ``filter``, or the host ids in ``hosts``. In a
102
+ script job, only the job's hosts are ever given, and ``workspace``
103
+ defaults to the job's."""
104
+ return run(["inventory", *_workspace_and_limit(workspace, folder, filter, hosts)])
105
+
106
+
107
+ def _workspace_and_limit(
108
+ workspace: Optional[Folder],
109
+ folder: Optional[str],
110
+ filter: Optional[str],
111
+ hosts: Optional[Iterable[str]],
112
+ ) -> List[str]:
113
+ """``<workspace> [limit]`` for ``inventory`` and ``tunnel``; the limit
114
+ options first and the workspace after ``--`` when its name starts with
115
+ ``-``."""
116
+ root = _workspace(workspace)
117
+ limit = _limit(folder, filter, hosts)
118
+ if root.startswith("-"):
119
+ return [*limit, *values(root)]
120
+ return [root, *limit]
121
+
122
+
123
+ def _limit(folder: Optional[str], filter: Optional[str], hosts: Optional[Iterable[str]]) -> List[str]:
124
+ """The binary's limit options (``--folder=<value>`` for a value that
125
+ starts with ``-``)."""
126
+ args: List[str] = []
127
+ host_ids = [hosts] if isinstance(hosts, str) else list(hosts or [])
128
+ given = [name for name, value in (("folder", folder), ("filter", filter)) if value is not None]
129
+ if host_ids:
130
+ given.append("hosts")
131
+ if len(given) > 1:
132
+ raise ValueError(f"give only one of folder, filter and hosts, not {' and '.join(given)}")
133
+ if folder is not None:
134
+ args += option("--folder", folder)
135
+ if filter is not None:
136
+ args += option("--filter", filter)
137
+ for host in host_ids:
138
+ args += option("--host", host)
139
+ return args
140
+
141
+
142
+ def tunnels(
143
+ workspace: Optional[Folder] = None,
144
+ *,
145
+ folder: Optional[str] = None,
146
+ filter: Optional[str] = None,
147
+ hosts: Optional[Iterable[str]] = None,
148
+ ports: Optional[Iterable[int]] = None,
149
+ ) -> Tunnels:
150
+ """Loopback tunnels to the hosts behind jump hosts among those
151
+ :func:`inventory` gives with the same limit (``enodix-cli tunnel``):
152
+ each jump chain is connected as the app would, with the jump hosts'
153
+ stored logins and the host keys the app trusts, and nothing is asked.
154
+ The result's ``hosts`` maps each such host id to where to connect
155
+ instead (``address`` ``127.0.0.1``, ``port``) with a ``known_hosts``
156
+ file of the device's trusted keys, or to an ``error`` saying why it is
157
+ not tunnelled. ``ports`` are other device ports to carry for every
158
+ such host (``[830, 443]``: NETCONF, an HTTPS API); each tunnelled
159
+ host's entry then has ``extra_ports``, device port -> loopback port.
160
+ :func:`endpoint` answers where to connect for any host and port. They
161
+ stay open until closed or this process ends."""
162
+ named = ports_of(ports)
163
+ return Tunnels(_workspace_and_limit(workspace, folder, filter, hosts), named)
164
+
165
+
166
+ def credentials(workspace: Optional[Folder], host: str) -> Dict[str, Any]:
167
+ """The login of the credential profile the host ``host`` (a host id)
168
+ uses (``enodix-cli credentials``, format 1): ``username``, ``auth``
169
+ (``{"kind": "password", "password"}``, ``{"kind": "private_key",
170
+ "key_file", "passphrase"}`` or ``{"kind": "agent"}``) and
171
+ ``enable_secret``. From the running app, else the store itself (the
172
+ vault asks for its master password on the terminal). ``None`` is the
173
+ script job's workspace; a job hands over only its hosts' logins."""
174
+ return run(["credentials", *values(_workspace(workspace), host)])
175
+
176
+
177
+ def secret(workspace: Optional[Folder], name: str) -> str:
178
+ """The value of the workspace's named secret ``name``, from the
179
+ running app or the store, as :func:`credentials`."""
180
+ return run(["secret", *values(_workspace(workspace), name)])["value"]
enodix/_build.py ADDED
@@ -0,0 +1,5 @@
1
+ """Written by scripts/build-wheel.mjs: what the wheel was built for."""
2
+
3
+ VERSION = "0.7.1"
4
+ PRODUCT_NAME = "enodix"
5
+ CLI_NAME = "enodix-cli"
enodix/_cli.py ADDED
@@ -0,0 +1,237 @@
1
+ """Finding and running the headless binary, the package's only way to the
2
+ workspace and the credential store."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import os
8
+ import re
9
+ import subprocess
10
+ import sys
11
+ import threading
12
+ import warnings
13
+ from pathlib import Path
14
+ from typing import Any, List, Optional, Sequence, Set
15
+
16
+ try:
17
+ from . import _build # written into the wheel by scripts/build-wheel.mjs
18
+ except ImportError: # the source tree, not an installed wheel
19
+ _build = None # type: ignore[assignment]
20
+
21
+ #: The variable naming the binary (the app sets it for scripts it starts).
22
+ CLI_VARIABLE = "ENODIX_CLI"
23
+ #: The binary's name, without ``.exe``.
24
+ CLI_NAME: str = getattr(_build, "CLI_NAME", "enodix-cli")
25
+ #: The app's name, as the installer names its folder (``None`` in the
26
+ #: source tree, which then has no default location).
27
+ PRODUCT_NAME: Optional[str] = getattr(_build, "PRODUCT_NAME", None)
28
+ #: The version of the binary's JSON this package reads.
29
+ FORMAT = 1
30
+ #: This package's version as the wheel has it (``None`` in the source tree,
31
+ #: which is never compared with the binary's).
32
+ PACKAGE_VERSION: Optional[str] = getattr(_build, "VERSION", None)
33
+ #: Ends the binary's options: what follows is a value even when it starts
34
+ #: with ``-``. Passed only when a value needs it, so that a binary older
35
+ #: than ``--`` still runs every command line it understood.
36
+ END_OF_OPTIONS = "--"
37
+
38
+ #: The binaries whose version was compared with the package's already.
39
+ _COMPARED: Set[str] = set()
40
+ _COMPARED_LOCK = threading.Lock()
41
+
42
+
43
+ class EnodixError(Exception):
44
+ """Something the headless binary could not do, or that went wrong
45
+ talking to it. The message says why."""
46
+
47
+
48
+ class CliNotFound(EnodixError):
49
+ """The headless binary is in none of the places looked at."""
50
+
51
+
52
+ class VersionWarning(UserWarning):
53
+ """The headless binary is another version than this package: it was
54
+ left behind when the app was upgraded (or the other way round). Things
55
+ may still work; the message says what to install."""
56
+
57
+
58
+ class CliFailed(EnodixError):
59
+ """The headless binary refused or failed. ``status`` is its exit
60
+ status, ``reason`` what it said."""
61
+
62
+ def __init__(self, message: str, status: int, reason: str) -> None:
63
+ super().__init__(message)
64
+ self.status = status
65
+ self.reason = reason
66
+
67
+
68
+ def _executable(name: str) -> str:
69
+ return f"{name}.exe" if sys.platform == "win32" else name
70
+
71
+
72
+ def default_location() -> Optional[Path]:
73
+ """Where the installer puts the binary: on Windows, beside the app in
74
+ ``%LOCALAPPDATA%\\<app name>`` (the per-user install). ``None``
75
+ elsewhere, where the binary is looked for on ``PATH`` (the Linux
76
+ packages install it in ``/usr/bin``; the AppImage needs ``ENODIX_CLI``)."""
77
+ if sys.platform != "win32" or PRODUCT_NAME is None:
78
+ return None
79
+ local = os.environ.get("LOCALAPPDATA")
80
+ if not local:
81
+ return None
82
+ return Path(local) / PRODUCT_NAME / _executable(CLI_NAME)
83
+
84
+
85
+ def _on_path(file_name: str) -> Optional[Path]:
86
+ """The program ``file_name`` in the first ``PATH`` folder that has it,
87
+ never in the current folder. A script job runs in the workspace's folder,
88
+ and on Windows ``shutil.which`` looks in the current folder first (and,
89
+ before Python 3.12, even when given a path): a shared workspace could
90
+ put its own ``enodix-cli.exe`` there. Only the binary's own name is
91
+ looked for, not ``.bat`` or ``.cmd``."""
92
+ here = os.path.normcase(os.path.abspath(os.curdir))
93
+ for folder in os.environ.get("PATH", os.defpath).split(os.pathsep):
94
+ folder = folder.strip().strip('"')
95
+ if not folder or folder == os.curdir:
96
+ continue
97
+ if os.path.normcase(os.path.abspath(folder)) == here:
98
+ continue
99
+ candidate = Path(folder) / file_name
100
+ if candidate.is_file() and (sys.platform == "win32" or os.access(candidate, os.X_OK)):
101
+ return candidate
102
+ return None
103
+
104
+
105
+ def find_cli() -> Path:
106
+ """The headless binary: ``ENODIX_CLI`` if set, else the default
107
+ install location, else ``PATH``. Raises :class:`CliNotFound` saying
108
+ where it looked."""
109
+ configured = os.environ.get(CLI_VARIABLE, "").strip()
110
+ if configured:
111
+ path = Path(configured)
112
+ if path.is_file():
113
+ return path
114
+ raise CliNotFound(
115
+ f"{CLI_VARIABLE} is set to {configured}, which is not a file: "
116
+ f"point it at {_executable(CLI_NAME)}"
117
+ )
118
+ tried = [f"{CLI_VARIABLE} (not set)"]
119
+ default = default_location()
120
+ if default is not None:
121
+ if default.is_file():
122
+ return default
123
+ tried.append(str(default))
124
+ found = _on_path(_executable(CLI_NAME))
125
+ if found is not None:
126
+ return found
127
+ tried.append(f"{CLI_NAME} on PATH")
128
+ app = PRODUCT_NAME or "the app"
129
+ raise CliNotFound(
130
+ f"cannot find {_executable(CLI_NAME)}, the headless binary that comes "
131
+ f"with {app} (looked at: {'; '.join(tried)}). Set {CLI_VARIABLE} to its "
132
+ f"path: it is installed beside the app."
133
+ )
134
+
135
+
136
+ def python_version(version: str) -> str:
137
+ """An app version as Python writes it (PEP 440, as the wheel is named:
138
+ ``1.2.3-beta.1`` -> ``1.2.3b1``, build details dropped)."""
139
+ match = re.fullmatch(r"(\d+\.\d+\.\d+)(?:-(alpha|beta|rc)\.(\d+))?(?:\+[0-9A-Za-z.-]+)?", version)
140
+ if not match:
141
+ return version
142
+ release, stage, number = match.groups()
143
+ short = {"alpha": "a", "beta": "b", "rc": "rc"}
144
+ return f"{release}{short[stage]}{number}" if stage else release
145
+
146
+
147
+ def compare_version(cli: Path) -> None:
148
+ """Warns (:class:`VersionWarning`, once per binary and process) when the
149
+ binary's version (``--version``) is not this package's. Nothing is
150
+ refused: the JSON format is what decides whether they understand each
151
+ other. Says nothing when either version cannot be told (the source
152
+ tree, a binary that does not answer)."""
153
+ if PACKAGE_VERSION is None:
154
+ return
155
+ with _COMPARED_LOCK:
156
+ if str(cli) in _COMPARED:
157
+ return
158
+ _COMPARED.add(str(cli))
159
+ try:
160
+ done = subprocess.run(
161
+ [str(cli), "--version"],
162
+ stdin=subprocess.DEVNULL,
163
+ stdout=subprocess.PIPE,
164
+ stderr=subprocess.DEVNULL,
165
+ timeout=30,
166
+ check=False,
167
+ )
168
+ except (OSError, subprocess.SubprocessError):
169
+ return
170
+ words = done.stdout.decode("utf-8", errors="replace").split()
171
+ if done.returncode != 0 or len(words) < 2:
172
+ return
173
+ binary = python_version(words[1])
174
+ if binary == PACKAGE_VERSION:
175
+ return
176
+ app = PRODUCT_NAME or "the app"
177
+ warnings.warn(
178
+ VersionWarning(
179
+ f"{cli} is version {binary} of {app}'s headless binary, and this enodix "
180
+ f"package is version {PACKAGE_VERSION}: install the package that ships with "
181
+ f"the app (pip install the wheel in the python folder beside it), or point "
182
+ f"{CLI_VARIABLE} at the binary of this package's version"
183
+ ),
184
+ stacklevel=4,
185
+ )
186
+
187
+
188
+ def values(*given: str) -> List[str]:
189
+ """Values for the binary's command line (a workspace folder, a host id, a
190
+ secret's name), behind ``--`` if one of them starts with ``-``."""
191
+ if any(value.startswith("-") for value in given):
192
+ return [END_OF_OPTIONS, *given]
193
+ return list(given)
194
+
195
+
196
+ def option(name: str, value: str) -> List[str]:
197
+ """An option and its value, as ``--name=<value>`` when the value starts
198
+ with ``-``."""
199
+ if value.startswith("-"):
200
+ return [f"{name}={value}"]
201
+ return [name, value]
202
+
203
+
204
+ def run(args: Sequence[str]) -> Any:
205
+ """Runs the binary with ``args`` and returns the JSON it printed.
206
+
207
+ The terminal stays the binary's: with the app's vault locked or closed
208
+ it asks for the master password there, hidden, never through this
209
+ process. What it prints goes nowhere but the returned value."""
210
+ cli = find_cli()
211
+ compare_version(cli)
212
+ try:
213
+ done = subprocess.run(
214
+ [str(cli), *args],
215
+ stdout=subprocess.PIPE,
216
+ stderr=subprocess.PIPE,
217
+ check=False,
218
+ )
219
+ except OSError as error:
220
+ raise EnodixError(f"cannot start {cli}: {error}") from error
221
+ reason = done.stderr.decode("utf-8", errors="replace").strip()
222
+ if done.returncode != 0:
223
+ prefix = f"{CLI_NAME}: error: "
224
+ lines = [line.removeprefix(prefix) for line in reason.splitlines()]
225
+ said = " ".join(lines) or f"it exited with status {done.returncode}"
226
+ raise CliFailed(said, done.returncode, reason)
227
+ try:
228
+ answer = json.loads(done.stdout.decode("utf-8"))
229
+ except ValueError as error:
230
+ raise EnodixError(f"{cli} printed something that is not JSON: {error}") from None
231
+ if not isinstance(answer, dict) or answer.get("format") != FORMAT:
232
+ found = answer.get("format") if isinstance(answer, dict) else None
233
+ raise EnodixError(
234
+ f"{cli} speaks format {found}, this package reads format {FORMAT}: "
235
+ "install the package that ships with that version of the app"
236
+ )
237
+ return answer