lvi-script-sandbox-utils 0.6.0__tar.gz
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.
- lvi_script_sandbox_utils-0.6.0/LICENSE +202 -0
- lvi_script_sandbox_utils-0.6.0/PKG-INFO +120 -0
- lvi_script_sandbox_utils-0.6.0/README.md +107 -0
- lvi_script_sandbox_utils-0.6.0/VERSION +1 -0
- lvi_script_sandbox_utils-0.6.0/pyproject.toml +38 -0
- lvi_script_sandbox_utils-0.6.0/setup.cfg +4 -0
- lvi_script_sandbox_utils-0.6.0/src/lvi_script_sandbox_utils/__init__.py +307 -0
- lvi_script_sandbox_utils-0.6.0/src/lvi_script_sandbox_utils/py.typed +0 -0
- lvi_script_sandbox_utils-0.6.0/src/lvi_script_sandbox_utils.egg-info/PKG-INFO +120 -0
- lvi_script_sandbox_utils-0.6.0/src/lvi_script_sandbox_utils.egg-info/SOURCES.txt +16 -0
- lvi_script_sandbox_utils-0.6.0/src/lvi_script_sandbox_utils.egg-info/dependency_links.txt +1 -0
- lvi_script_sandbox_utils-0.6.0/src/lvi_script_sandbox_utils.egg-info/requires.txt +4 -0
- lvi_script_sandbox_utils-0.6.0/src/lvi_script_sandbox_utils.egg-info/top_level.txt +1 -0
- lvi_script_sandbox_utils-0.6.0/tests/test_device_data.py +72 -0
- lvi_script_sandbox_utils-0.6.0/tests/test_inputs.py +84 -0
- lvi_script_sandbox_utils-0.6.0/tests/test_loading.py +56 -0
- lvi_script_sandbox_utils-0.6.0/tests/test_outputs.py +39 -0
- lvi_script_sandbox_utils-0.6.0/tests/test_package.py +15 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 Jayde Hanley
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: lvi-script-sandbox-utils
|
|
3
|
+
Version: 0.6.0
|
|
4
|
+
Summary: Convenience utilities for LogicVein Script Sandbox Python scripts
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Requires-Python: >=3.9
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Provides-Extra: dev
|
|
10
|
+
Requires-Dist: pytest; extra == "dev"
|
|
11
|
+
Requires-Dist: pytest-cov; extra == "dev"
|
|
12
|
+
Dynamic: license-file
|
|
13
|
+
|
|
14
|
+
# LogicVein Script Sandbox Utils
|
|
15
|
+
|
|
16
|
+
Convenience helpers for Python scripts that LogicVein Playbooks run in the
|
|
17
|
+
Script Sandbox container. They wrap the sandbox's file-and-stdout contract:
|
|
18
|
+
a Playbook hands your script its inputs in `in.json`, and your script returns
|
|
19
|
+
results by printing JSON to stdout.
|
|
20
|
+
|
|
21
|
+
## Installation
|
|
22
|
+
|
|
23
|
+
From PyPI:
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
pip install lvi-script-sandbox-utils
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
From TestPyPI (pre-release / testing):
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install \
|
|
33
|
+
--index-url https://test.pypi.org/simple/ \
|
|
34
|
+
--extra-index-url https://pypi.org/simple/ \
|
|
35
|
+
lvi-script-sandbox-utils
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
The sandbox runs scripts in a container, so the package has to be available
|
|
39
|
+
inside it. If your sandbox mounts a packages directory (for example
|
|
40
|
+
`./packages:/packages`), install into it:
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
pip install --target ./packages lvi-script-sandbox-utils
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
The library has no third-party dependencies (standard library only).
|
|
47
|
+
|
|
48
|
+
### Upgrading from 0.1.x
|
|
49
|
+
|
|
50
|
+
0.1.x installed as `logicvein.lvi_script_sandbox_utils`. From 0.2.0 it is
|
|
51
|
+
the top-level package `lvi_script_sandbox_utils`, so change
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
from logicvein import lvi_script_sandbox_utils as lvi
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
to `import lvi_script_sandbox_utils as lvi`. The `logicvein` package is
|
|
58
|
+
left to `lvi-api-client`: when both shipped a `logicvein/` directory,
|
|
59
|
+
`pip install --target` skipped whichever was installed second (or, with
|
|
60
|
+
`--upgrade`, deleted the first).
|
|
61
|
+
|
|
62
|
+
## Usage
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
import lvi_script_sandbox_utils as lvi
|
|
66
|
+
|
|
67
|
+
device = lvi.get_device()
|
|
68
|
+
output = lvi.get_input("cli_output", default="") # "" in the Playbook's first script node
|
|
69
|
+
|
|
70
|
+
lvi.flush_output(hostname=device.device_hostname, line_count=len(output.splitlines()))
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### Functions
|
|
74
|
+
|
|
75
|
+
| Function | Purpose |
|
|
76
|
+
|----------|---------|
|
|
77
|
+
| `load_input(path=None, reload=False)` | The whole `in.json` as a dict, read once and cached. Treat it as read-only. |
|
|
78
|
+
| `get_input(input_type, default=...)` | Read an input from `in.json`. `"cli_output"` returns the previous node's result value; `"device"` returns the raw device dict. A missing input returns `default`, or raises `KeyError` if none was given; any other `input_type` raises `ValueError`. |
|
|
79
|
+
| `get_global(name, default=...)` | One Playbook global's value, e.g. `get_global("hostname")`. A missing global returns `default`, or raises `KeyError` naming the globals that are set. |
|
|
80
|
+
| `get_globals()` | Every Playbook global as `{name: value}`. |
|
|
81
|
+
| `get_metadata()` | Details of this run as an object: `playbook`, `execution_id`, `executor`, `job_id`, `node`, `started_at`, and so on. |
|
|
82
|
+
| `get_device(blank_none=True)` | The Playbook's device as an object with a basic set of properties (see below). |
|
|
83
|
+
| `get_full_device(blank_none=True)` | Like `get_device()`, with the additional properties included (`uuid`, `lastBackup`, `severity`, `memoSummary`, ...). |
|
|
84
|
+
| `set_output(key, value)` | Record a global for the next `flush_output()`. |
|
|
85
|
+
| `flush_output(**kwargs)` | Print the `set_output()` values plus `kwargs` (which win on a clash) to stdout as Playbook global variables (`output.globals`), then clear the `set_output()` values. Device and metadata objects print as their fields. |
|
|
86
|
+
| `flush_string_output(text)` | Print a string to stdout as base64-encoded raw output (`output.raw`). |
|
|
87
|
+
|
|
88
|
+
On the device objects:
|
|
89
|
+
|
|
90
|
+
- `hostname` and `network` are renamed to `device_hostname` and
|
|
91
|
+
`device_network`, so they don't collide with other Playbook variables.
|
|
92
|
+
- `traits` lists the device's capabilities from `metaJson` (`ssh`, `snmp`,
|
|
93
|
+
`ncm`, ...); `customFields` is dropped, since it repeats `custom1`..`custom5`.
|
|
94
|
+
- End-of-life/sale epochs (`endOfLife`, `endOfSale`, `softwareEndOfLife`,
|
|
95
|
+
`softwareEndOfSale`) become `YYYY-MM-DD` dates, and `lastBackup`,
|
|
96
|
+
`lastChange`, `lastDiscovery`, `lastTelemetry` become
|
|
97
|
+
`YYYY-MM-DDTHH:MM:SSZ` timestamps, all in UTC. `get_metadata().started_at`
|
|
98
|
+
is converted the same way.
|
|
99
|
+
- `None` values become `""`; pass `blank_none=False` to keep `None`.
|
|
100
|
+
- A property LogicVein doesn't send is simply absent from the object.
|
|
101
|
+
|
|
102
|
+
`vars(device)` gives the properties as a dict.
|
|
103
|
+
|
|
104
|
+
### Where the input comes from
|
|
105
|
+
|
|
106
|
+
`in.json` is read on first use, not at import, and only once; `load_input()`
|
|
107
|
+
returns it as a dict (pass `reload=True` to read it again). The module
|
|
108
|
+
attributes `device` and `device_full` are built the first time a script uses
|
|
109
|
+
them. By default the file is `in.json` in the working directory, where the
|
|
110
|
+
sandbox puts it; set `LVI_SANDBOX_INPUT` to read another file, e.g. a saved
|
|
111
|
+
`in.json` while developing a script outside a Playbook:
|
|
112
|
+
|
|
113
|
+
```bash
|
|
114
|
+
LVI_SANDBOX_INPUT=./samples/in.json python my_script.py
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
## Development and releases
|
|
118
|
+
|
|
119
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup and
|
|
120
|
+
[PUBLISHING.md](PUBLISHING.md) for how releases are published.
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
# LogicVein Script Sandbox Utils
|
|
2
|
+
|
|
3
|
+
Convenience helpers for Python scripts that LogicVein Playbooks run in the
|
|
4
|
+
Script Sandbox container. They wrap the sandbox's file-and-stdout contract:
|
|
5
|
+
a Playbook hands your script its inputs in `in.json`, and your script returns
|
|
6
|
+
results by printing JSON to stdout.
|
|
7
|
+
|
|
8
|
+
## Installation
|
|
9
|
+
|
|
10
|
+
From PyPI:
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
pip install lvi-script-sandbox-utils
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
From TestPyPI (pre-release / testing):
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
pip install \
|
|
20
|
+
--index-url https://test.pypi.org/simple/ \
|
|
21
|
+
--extra-index-url https://pypi.org/simple/ \
|
|
22
|
+
lvi-script-sandbox-utils
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
The sandbox runs scripts in a container, so the package has to be available
|
|
26
|
+
inside it. If your sandbox mounts a packages directory (for example
|
|
27
|
+
`./packages:/packages`), install into it:
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pip install --target ./packages lvi-script-sandbox-utils
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
The library has no third-party dependencies (standard library only).
|
|
34
|
+
|
|
35
|
+
### Upgrading from 0.1.x
|
|
36
|
+
|
|
37
|
+
0.1.x installed as `logicvein.lvi_script_sandbox_utils`. From 0.2.0 it is
|
|
38
|
+
the top-level package `lvi_script_sandbox_utils`, so change
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
from logicvein import lvi_script_sandbox_utils as lvi
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
to `import lvi_script_sandbox_utils as lvi`. The `logicvein` package is
|
|
45
|
+
left to `lvi-api-client`: when both shipped a `logicvein/` directory,
|
|
46
|
+
`pip install --target` skipped whichever was installed second (or, with
|
|
47
|
+
`--upgrade`, deleted the first).
|
|
48
|
+
|
|
49
|
+
## Usage
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
import lvi_script_sandbox_utils as lvi
|
|
53
|
+
|
|
54
|
+
device = lvi.get_device()
|
|
55
|
+
output = lvi.get_input("cli_output", default="") # "" in the Playbook's first script node
|
|
56
|
+
|
|
57
|
+
lvi.flush_output(hostname=device.device_hostname, line_count=len(output.splitlines()))
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### Functions
|
|
61
|
+
|
|
62
|
+
| Function | Purpose |
|
|
63
|
+
|----------|---------|
|
|
64
|
+
| `load_input(path=None, reload=False)` | The whole `in.json` as a dict, read once and cached. Treat it as read-only. |
|
|
65
|
+
| `get_input(input_type, default=...)` | Read an input from `in.json`. `"cli_output"` returns the previous node's result value; `"device"` returns the raw device dict. A missing input returns `default`, or raises `KeyError` if none was given; any other `input_type` raises `ValueError`. |
|
|
66
|
+
| `get_global(name, default=...)` | One Playbook global's value, e.g. `get_global("hostname")`. A missing global returns `default`, or raises `KeyError` naming the globals that are set. |
|
|
67
|
+
| `get_globals()` | Every Playbook global as `{name: value}`. |
|
|
68
|
+
| `get_metadata()` | Details of this run as an object: `playbook`, `execution_id`, `executor`, `job_id`, `node`, `started_at`, and so on. |
|
|
69
|
+
| `get_device(blank_none=True)` | The Playbook's device as an object with a basic set of properties (see below). |
|
|
70
|
+
| `get_full_device(blank_none=True)` | Like `get_device()`, with the additional properties included (`uuid`, `lastBackup`, `severity`, `memoSummary`, ...). |
|
|
71
|
+
| `set_output(key, value)` | Record a global for the next `flush_output()`. |
|
|
72
|
+
| `flush_output(**kwargs)` | Print the `set_output()` values plus `kwargs` (which win on a clash) to stdout as Playbook global variables (`output.globals`), then clear the `set_output()` values. Device and metadata objects print as their fields. |
|
|
73
|
+
| `flush_string_output(text)` | Print a string to stdout as base64-encoded raw output (`output.raw`). |
|
|
74
|
+
|
|
75
|
+
On the device objects:
|
|
76
|
+
|
|
77
|
+
- `hostname` and `network` are renamed to `device_hostname` and
|
|
78
|
+
`device_network`, so they don't collide with other Playbook variables.
|
|
79
|
+
- `traits` lists the device's capabilities from `metaJson` (`ssh`, `snmp`,
|
|
80
|
+
`ncm`, ...); `customFields` is dropped, since it repeats `custom1`..`custom5`.
|
|
81
|
+
- End-of-life/sale epochs (`endOfLife`, `endOfSale`, `softwareEndOfLife`,
|
|
82
|
+
`softwareEndOfSale`) become `YYYY-MM-DD` dates, and `lastBackup`,
|
|
83
|
+
`lastChange`, `lastDiscovery`, `lastTelemetry` become
|
|
84
|
+
`YYYY-MM-DDTHH:MM:SSZ` timestamps, all in UTC. `get_metadata().started_at`
|
|
85
|
+
is converted the same way.
|
|
86
|
+
- `None` values become `""`; pass `blank_none=False` to keep `None`.
|
|
87
|
+
- A property LogicVein doesn't send is simply absent from the object.
|
|
88
|
+
|
|
89
|
+
`vars(device)` gives the properties as a dict.
|
|
90
|
+
|
|
91
|
+
### Where the input comes from
|
|
92
|
+
|
|
93
|
+
`in.json` is read on first use, not at import, and only once; `load_input()`
|
|
94
|
+
returns it as a dict (pass `reload=True` to read it again). The module
|
|
95
|
+
attributes `device` and `device_full` are built the first time a script uses
|
|
96
|
+
them. By default the file is `in.json` in the working directory, where the
|
|
97
|
+
sandbox puts it; set `LVI_SANDBOX_INPUT` to read another file, e.g. a saved
|
|
98
|
+
`in.json` while developing a script outside a Playbook:
|
|
99
|
+
|
|
100
|
+
```bash
|
|
101
|
+
LVI_SANDBOX_INPUT=./samples/in.json python my_script.py
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
## Development and releases
|
|
105
|
+
|
|
106
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup and
|
|
107
|
+
[PUBLISHING.md](PUBLISHING.md) for how releases are published.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
0.6.0
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77.0", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "lvi-script-sandbox-utils"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Convenience utilities for LogicVein Script Sandbox Python scripts"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = "Apache-2.0"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
dependencies = []
|
|
14
|
+
|
|
15
|
+
[project.optional-dependencies]
|
|
16
|
+
dev = [
|
|
17
|
+
"pytest",
|
|
18
|
+
"pytest-cov",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[tool.setuptools.packages.find]
|
|
22
|
+
where = ["src"]
|
|
23
|
+
|
|
24
|
+
[tool.setuptools.package-data]
|
|
25
|
+
lvi_script_sandbox_utils = ["py.typed"]
|
|
26
|
+
|
|
27
|
+
[tool.setuptools.dynamic]
|
|
28
|
+
version = {file = "VERSION"}
|
|
29
|
+
|
|
30
|
+
[tool.black]
|
|
31
|
+
line-length = 120
|
|
32
|
+
|
|
33
|
+
[tool.isort]
|
|
34
|
+
line_length = 120
|
|
35
|
+
profile = "black"
|
|
36
|
+
|
|
37
|
+
[tool.pytest.ini_options]
|
|
38
|
+
pythonpath = ["src"]
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
"""Convenience utilities for LogicVein Script Sandbox scripts.
|
|
2
|
+
|
|
3
|
+
A Playbook hands a script its inputs in `in.json` (in the working directory
|
|
4
|
+
by default) and reads results from what the script prints to stdout.
|
|
5
|
+
Nothing is read at import time: `in.json` is loaded on first use, once.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import base64
|
|
9
|
+
import copy
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
from datetime import datetime, timezone
|
|
13
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
14
|
+
from types import SimpleNamespace
|
|
15
|
+
from typing import Any, Dict, Optional
|
|
16
|
+
|
|
17
|
+
try:
|
|
18
|
+
__version__ = version("lvi-script-sandbox-utils")
|
|
19
|
+
except PackageNotFoundError:
|
|
20
|
+
__version__ = "unknown"
|
|
21
|
+
|
|
22
|
+
INPUT_PATH_ENV = "LVI_SANDBOX_INPUT"
|
|
23
|
+
DEFAULT_INPUT_PATH = "in.json"
|
|
24
|
+
|
|
25
|
+
output: dict = {}
|
|
26
|
+
_cache: Dict[str, Dict[str, Any]] = {}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def input_path() -> str:
|
|
30
|
+
"""Return the path `in.json` is read from.
|
|
31
|
+
|
|
32
|
+
Returns:
|
|
33
|
+
The `LVI_SANDBOX_INPUT` environment variable if set, else `in.json`
|
|
34
|
+
(relative to the working directory, where the sandbox puts it).
|
|
35
|
+
"""
|
|
36
|
+
return os.environ.get(INPUT_PATH_ENV) or DEFAULT_INPUT_PATH
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def load_input(path: Optional[str] = None, reload: bool = False) -> Dict[str, Any]:
|
|
40
|
+
"""Return the Playbook's inputs, reading the file once per path.
|
|
41
|
+
|
|
42
|
+
Args:
|
|
43
|
+
path: File to read; defaults to `input_path()`.
|
|
44
|
+
reload: Read the file again even if it was already loaded.
|
|
45
|
+
|
|
46
|
+
Returns:
|
|
47
|
+
The parsed `in.json`. It is shared and cached, so don't modify it;
|
|
48
|
+
the `get_*` functions return copies.
|
|
49
|
+
|
|
50
|
+
Raises:
|
|
51
|
+
FileNotFoundError: The file doesn't exist (e.g. running outside a
|
|
52
|
+
Playbook without `LVI_SANDBOX_INPUT` set).
|
|
53
|
+
"""
|
|
54
|
+
path = path or input_path()
|
|
55
|
+
if reload or path not in _cache:
|
|
56
|
+
with open(path, "r", encoding="utf-8") as file:
|
|
57
|
+
_cache[path] = json.load(file)
|
|
58
|
+
return _cache[path]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
_MISSING: Any = object()
|
|
62
|
+
|
|
63
|
+
# Device fields holding epoch milliseconds: calendar dates, and points in time.
|
|
64
|
+
_DATE_FIELDS = ("endOfLife", "endOfSale", "softwareEndOfLife", "softwareEndOfSale")
|
|
65
|
+
_TIMESTAMP_FIELDS = ("lastBackup", "lastChange", "lastDiscovery", "lastTelemetry")
|
|
66
|
+
_TIMESTAMP_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
|
|
67
|
+
|
|
68
|
+
# Device fields only get_full_device() returns; get_device() leaves them out.
|
|
69
|
+
_FULL_ONLY_FIELDS = (
|
|
70
|
+
"backupElapsed",
|
|
71
|
+
"backupStatus",
|
|
72
|
+
"complianceState",
|
|
73
|
+
"lastBackup",
|
|
74
|
+
"lastChange",
|
|
75
|
+
"lastDiscovery",
|
|
76
|
+
"lastTelemetry",
|
|
77
|
+
"memoSummary",
|
|
78
|
+
"ncmEnabled",
|
|
79
|
+
"severity",
|
|
80
|
+
"sysObjectID",
|
|
81
|
+
"uuid",
|
|
82
|
+
"violationMessage",
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _output(**kwargs):
|
|
87
|
+
"""Format kwargs into an output dict usable as Playbook vars."""
|
|
88
|
+
data = {"output": {"globals": {**kwargs}}}
|
|
89
|
+
return data
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _raw_device() -> Dict[str, Any]:
|
|
93
|
+
data = load_input()
|
|
94
|
+
if "device" not in data:
|
|
95
|
+
raise KeyError("in.json has no 'device': the Playbook didn't pass a device to this script")
|
|
96
|
+
return data["device"]
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _epoch_ms(value: Any, fmt: str) -> Any:
|
|
100
|
+
"""Format epoch milliseconds in UTC, leaving anything else (None, "", 0) as is.
|
|
101
|
+
|
|
102
|
+
UTC, not the container's local time zone, so a date never shifts by a day.
|
|
103
|
+
"""
|
|
104
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)) or value == 0:
|
|
105
|
+
return value
|
|
106
|
+
return datetime.fromtimestamp(value / 1000, tz=timezone.utc).strftime(fmt)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def get_full_device(blank_none: bool = True) -> SimpleNamespace:
|
|
110
|
+
"""Return mostly all device properties as an object.
|
|
111
|
+
|
|
112
|
+
Fields LogicVein doesn't send are simply absent; nothing here requires a
|
|
113
|
+
particular field to exist. `hostname` and `network` become
|
|
114
|
+
`device_hostname` and `device_network`, `metaJson`'s traits become
|
|
115
|
+
`traits`, and `customFields` (a copy of `custom1`..`custom5`) is dropped.
|
|
116
|
+
End-of-life/sale epochs become `YYYY-MM-DD` dates and the `last*`
|
|
117
|
+
epochs `YYYY-MM-DDTHH:MM:SSZ` timestamps, both in UTC.
|
|
118
|
+
|
|
119
|
+
Args:
|
|
120
|
+
blank_none: Turn `None` values into `""` for easier handling in the
|
|
121
|
+
Playbook. Pass False to keep `None`, so "not set" stays
|
|
122
|
+
distinguishable from an empty string.
|
|
123
|
+
|
|
124
|
+
Raises:
|
|
125
|
+
KeyError: `in.json` has no device.
|
|
126
|
+
"""
|
|
127
|
+
# The JSON round trip is a deep copy, so the cached input is never changed.
|
|
128
|
+
device = json.loads(json.dumps(_raw_device()), object_hook=lambda d: SimpleNamespace(**d))
|
|
129
|
+
fields = vars(device)
|
|
130
|
+
meta = fields.pop("metaJson", None)
|
|
131
|
+
fields["traits"] = list(getattr(meta, "traits", None) or [])
|
|
132
|
+
fields.pop("customFields", None)
|
|
133
|
+
for old_name, new_name in (("hostname", "device_hostname"), ("network", "device_network")):
|
|
134
|
+
if old_name in fields:
|
|
135
|
+
fields[new_name] = fields.pop(old_name)
|
|
136
|
+
for field in _DATE_FIELDS:
|
|
137
|
+
if field in fields:
|
|
138
|
+
fields[field] = _epoch_ms(fields[field], "%Y-%m-%d")
|
|
139
|
+
for field in _TIMESTAMP_FIELDS:
|
|
140
|
+
if field in fields:
|
|
141
|
+
fields[field] = _epoch_ms(fields[field], _TIMESTAMP_FORMAT)
|
|
142
|
+
if blank_none:
|
|
143
|
+
for key, value in fields.items():
|
|
144
|
+
if value is None:
|
|
145
|
+
fields[key] = ""
|
|
146
|
+
return device
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def get_device(blank_none: bool = True) -> SimpleNamespace:
|
|
150
|
+
"""Return a basic set of device properties as an object.
|
|
151
|
+
|
|
152
|
+
Args:
|
|
153
|
+
blank_none: As for `get_full_device()`.
|
|
154
|
+
|
|
155
|
+
Raises:
|
|
156
|
+
KeyError: `in.json` has no device.
|
|
157
|
+
"""
|
|
158
|
+
device = get_full_device(blank_none)
|
|
159
|
+
for field in _FULL_ONLY_FIELDS:
|
|
160
|
+
vars(device).pop(field, None)
|
|
161
|
+
return device
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def get_input(input_type: str, default: Any = _MISSING) -> Any:
|
|
165
|
+
"""Get input from the previous node.
|
|
166
|
+
|
|
167
|
+
Args:
|
|
168
|
+
input_type: `"cli_output"` for the previous node's result value, or
|
|
169
|
+
`"device"` for the raw device dict.
|
|
170
|
+
default: Returned when that input isn't in `in.json` (e.g.
|
|
171
|
+
`"cli_output"` in the Playbook's first script node). Without it,
|
|
172
|
+
a missing input raises `KeyError`.
|
|
173
|
+
|
|
174
|
+
Returns:
|
|
175
|
+
The input, as a copy.
|
|
176
|
+
|
|
177
|
+
Raises:
|
|
178
|
+
ValueError: `input_type` isn't one of the above; use `get_global()`
|
|
179
|
+
for other Playbook globals.
|
|
180
|
+
KeyError: The input is missing and no default was given.
|
|
181
|
+
"""
|
|
182
|
+
data = load_input()
|
|
183
|
+
if input_type == "cli_output":
|
|
184
|
+
result = data.get("globals", {}).get("result")
|
|
185
|
+
value = result.get("value", _MISSING) if isinstance(result, dict) else _MISSING
|
|
186
|
+
missing = "no previous node result (globals.result)"
|
|
187
|
+
elif input_type == "device":
|
|
188
|
+
value = data.get("device", _MISSING)
|
|
189
|
+
missing = "no 'device'"
|
|
190
|
+
else:
|
|
191
|
+
raise ValueError(
|
|
192
|
+
f"Unknown input_type {input_type!r}: expected 'cli_output' or 'device'. "
|
|
193
|
+
"Use get_global() for other Playbook globals."
|
|
194
|
+
)
|
|
195
|
+
if value is _MISSING:
|
|
196
|
+
if default is _MISSING:
|
|
197
|
+
raise KeyError(f"in.json has {missing}")
|
|
198
|
+
return default
|
|
199
|
+
return copy.deepcopy(value)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _global_value(entry: Any) -> Any:
|
|
203
|
+
# in.json stores each global as {"type": ..., "value": ...}.
|
|
204
|
+
if isinstance(entry, dict) and "value" in entry:
|
|
205
|
+
return copy.deepcopy(entry["value"])
|
|
206
|
+
return copy.deepcopy(entry)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def get_globals() -> Dict[str, Any]:
|
|
210
|
+
"""Return every Playbook global passed to this script.
|
|
211
|
+
|
|
212
|
+
Returns:
|
|
213
|
+
`{name: value}`, with each global's `{"type", "value"}` wrapper
|
|
214
|
+
removed.
|
|
215
|
+
"""
|
|
216
|
+
return {name: _global_value(entry) for name, entry in load_input().get("globals", {}).items()}
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def get_global(name: str, default: Any = _MISSING) -> Any:
|
|
220
|
+
"""Return one Playbook global's value, e.g. `get_global("hostname")`.
|
|
221
|
+
|
|
222
|
+
Args:
|
|
223
|
+
name: The global's name.
|
|
224
|
+
default: Returned when the global isn't set. Without it, a missing
|
|
225
|
+
global raises `KeyError`.
|
|
226
|
+
|
|
227
|
+
Returns:
|
|
228
|
+
The global's value (its `{"type", "value"}` wrapper removed).
|
|
229
|
+
|
|
230
|
+
Raises:
|
|
231
|
+
KeyError: The global isn't set and no default was given.
|
|
232
|
+
"""
|
|
233
|
+
playbook_globals = load_input().get("globals", {})
|
|
234
|
+
if name not in playbook_globals:
|
|
235
|
+
if default is _MISSING:
|
|
236
|
+
available = ", ".join(sorted(playbook_globals)) or "none"
|
|
237
|
+
raise KeyError(f"No Playbook global {name!r} (in.json has: {available})")
|
|
238
|
+
return default
|
|
239
|
+
return _global_value(playbook_globals[name])
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def get_metadata() -> SimpleNamespace:
|
|
243
|
+
"""Return details of this Playbook run, e.g. `playbook`, `execution_id`, `executor`.
|
|
244
|
+
|
|
245
|
+
Returns:
|
|
246
|
+
The `metadata` section of `in.json` as an object; empty if absent.
|
|
247
|
+
`started_at` is a `YYYY-MM-DDTHH:MM:SSZ` UTC timestamp.
|
|
248
|
+
"""
|
|
249
|
+
metadata = copy.deepcopy(load_input().get("metadata", {}))
|
|
250
|
+
if "started_at" in metadata:
|
|
251
|
+
metadata["started_at"] = _epoch_ms(metadata["started_at"], _TIMESTAMP_FORMAT)
|
|
252
|
+
return SimpleNamespace(**metadata)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _json_default(value: Any) -> Any:
|
|
256
|
+
# Device and metadata objects print as their fields.
|
|
257
|
+
if isinstance(value, SimpleNamespace):
|
|
258
|
+
return vars(value)
|
|
259
|
+
raise TypeError(f"Object of type {type(value).__name__} is not JSON serializable")
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def set_output(key: str, value: Any) -> None:
|
|
263
|
+
"""Set a key and value in the global output dict, printed by the next `flush_output()`."""
|
|
264
|
+
output[key] = value
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def flush_output(**kwargs: Any) -> None:
|
|
268
|
+
"""Print Playbook globals (`output.globals`) to stdout.
|
|
269
|
+
|
|
270
|
+
Args:
|
|
271
|
+
**kwargs: Globals to print, alongside any set with `set_output()`;
|
|
272
|
+
a keyword wins over a `set_output()` value of the same name.
|
|
273
|
+
Values must be JSON-serializable; device and metadata objects
|
|
274
|
+
are printed as their fields.
|
|
275
|
+
|
|
276
|
+
The `set_output()` values are cleared once printed.
|
|
277
|
+
"""
|
|
278
|
+
data = _output(**{**output, **kwargs})
|
|
279
|
+
print(json.dumps(data, default=_json_default))
|
|
280
|
+
output.clear()
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def flush_string_output(text: Any) -> None:
|
|
284
|
+
"""Put a string output in the output.raw field and send to stdout.
|
|
285
|
+
|
|
286
|
+
Args:
|
|
287
|
+
text: The raw output; anything else is converted with `str()`.
|
|
288
|
+
"""
|
|
289
|
+
data = {"output": {"raw": base64.b64encode(f"{text}".encode("utf-8")).decode("utf-8")}}
|
|
290
|
+
print(json.dumps(data))
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
_LAZY_ATTRIBUTES = {"device": get_device, "device_full": get_full_device}
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def __getattr__(name: str) -> Any:
|
|
297
|
+
"""Build `device` and `device_full` on first access instead of at import.
|
|
298
|
+
|
|
299
|
+
The result is stored as a real module attribute, so later accesses (and
|
|
300
|
+
changes a script makes to it) see the same object, as when these were
|
|
301
|
+
built at import time.
|
|
302
|
+
"""
|
|
303
|
+
if name in _LAZY_ATTRIBUTES:
|
|
304
|
+
value = _LAZY_ATTRIBUTES[name]()
|
|
305
|
+
globals()[name] = value
|
|
306
|
+
return value
|
|
307
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
File without changes
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: lvi-script-sandbox-utils
|
|
3
|
+
Version: 0.6.0
|
|
4
|
+
Summary: Convenience utilities for LogicVein Script Sandbox Python scripts
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Requires-Python: >=3.9
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Provides-Extra: dev
|
|
10
|
+
Requires-Dist: pytest; extra == "dev"
|
|
11
|
+
Requires-Dist: pytest-cov; extra == "dev"
|
|
12
|
+
Dynamic: license-file
|
|
13
|
+
|
|
14
|
+
# LogicVein Script Sandbox Utils
|
|
15
|
+
|
|
16
|
+
Convenience helpers for Python scripts that LogicVein Playbooks run in the
|
|
17
|
+
Script Sandbox container. They wrap the sandbox's file-and-stdout contract:
|
|
18
|
+
a Playbook hands your script its inputs in `in.json`, and your script returns
|
|
19
|
+
results by printing JSON to stdout.
|
|
20
|
+
|
|
21
|
+
## Installation
|
|
22
|
+
|
|
23
|
+
From PyPI:
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
pip install lvi-script-sandbox-utils
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
From TestPyPI (pre-release / testing):
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install \
|
|
33
|
+
--index-url https://test.pypi.org/simple/ \
|
|
34
|
+
--extra-index-url https://pypi.org/simple/ \
|
|
35
|
+
lvi-script-sandbox-utils
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
The sandbox runs scripts in a container, so the package has to be available
|
|
39
|
+
inside it. If your sandbox mounts a packages directory (for example
|
|
40
|
+
`./packages:/packages`), install into it:
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
pip install --target ./packages lvi-script-sandbox-utils
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
The library has no third-party dependencies (standard library only).
|
|
47
|
+
|
|
48
|
+
### Upgrading from 0.1.x
|
|
49
|
+
|
|
50
|
+
0.1.x installed as `logicvein.lvi_script_sandbox_utils`. From 0.2.0 it is
|
|
51
|
+
the top-level package `lvi_script_sandbox_utils`, so change
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
from logicvein import lvi_script_sandbox_utils as lvi
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
to `import lvi_script_sandbox_utils as lvi`. The `logicvein` package is
|
|
58
|
+
left to `lvi-api-client`: when both shipped a `logicvein/` directory,
|
|
59
|
+
`pip install --target` skipped whichever was installed second (or, with
|
|
60
|
+
`--upgrade`, deleted the first).
|
|
61
|
+
|
|
62
|
+
## Usage
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
import lvi_script_sandbox_utils as lvi
|
|
66
|
+
|
|
67
|
+
device = lvi.get_device()
|
|
68
|
+
output = lvi.get_input("cli_output", default="") # "" in the Playbook's first script node
|
|
69
|
+
|
|
70
|
+
lvi.flush_output(hostname=device.device_hostname, line_count=len(output.splitlines()))
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### Functions
|
|
74
|
+
|
|
75
|
+
| Function | Purpose |
|
|
76
|
+
|----------|---------|
|
|
77
|
+
| `load_input(path=None, reload=False)` | The whole `in.json` as a dict, read once and cached. Treat it as read-only. |
|
|
78
|
+
| `get_input(input_type, default=...)` | Read an input from `in.json`. `"cli_output"` returns the previous node's result value; `"device"` returns the raw device dict. A missing input returns `default`, or raises `KeyError` if none was given; any other `input_type` raises `ValueError`. |
|
|
79
|
+
| `get_global(name, default=...)` | One Playbook global's value, e.g. `get_global("hostname")`. A missing global returns `default`, or raises `KeyError` naming the globals that are set. |
|
|
80
|
+
| `get_globals()` | Every Playbook global as `{name: value}`. |
|
|
81
|
+
| `get_metadata()` | Details of this run as an object: `playbook`, `execution_id`, `executor`, `job_id`, `node`, `started_at`, and so on. |
|
|
82
|
+
| `get_device(blank_none=True)` | The Playbook's device as an object with a basic set of properties (see below). |
|
|
83
|
+
| `get_full_device(blank_none=True)` | Like `get_device()`, with the additional properties included (`uuid`, `lastBackup`, `severity`, `memoSummary`, ...). |
|
|
84
|
+
| `set_output(key, value)` | Record a global for the next `flush_output()`. |
|
|
85
|
+
| `flush_output(**kwargs)` | Print the `set_output()` values plus `kwargs` (which win on a clash) to stdout as Playbook global variables (`output.globals`), then clear the `set_output()` values. Device and metadata objects print as their fields. |
|
|
86
|
+
| `flush_string_output(text)` | Print a string to stdout as base64-encoded raw output (`output.raw`). |
|
|
87
|
+
|
|
88
|
+
On the device objects:
|
|
89
|
+
|
|
90
|
+
- `hostname` and `network` are renamed to `device_hostname` and
|
|
91
|
+
`device_network`, so they don't collide with other Playbook variables.
|
|
92
|
+
- `traits` lists the device's capabilities from `metaJson` (`ssh`, `snmp`,
|
|
93
|
+
`ncm`, ...); `customFields` is dropped, since it repeats `custom1`..`custom5`.
|
|
94
|
+
- End-of-life/sale epochs (`endOfLife`, `endOfSale`, `softwareEndOfLife`,
|
|
95
|
+
`softwareEndOfSale`) become `YYYY-MM-DD` dates, and `lastBackup`,
|
|
96
|
+
`lastChange`, `lastDiscovery`, `lastTelemetry` become
|
|
97
|
+
`YYYY-MM-DDTHH:MM:SSZ` timestamps, all in UTC. `get_metadata().started_at`
|
|
98
|
+
is converted the same way.
|
|
99
|
+
- `None` values become `""`; pass `blank_none=False` to keep `None`.
|
|
100
|
+
- A property LogicVein doesn't send is simply absent from the object.
|
|
101
|
+
|
|
102
|
+
`vars(device)` gives the properties as a dict.
|
|
103
|
+
|
|
104
|
+
### Where the input comes from
|
|
105
|
+
|
|
106
|
+
`in.json` is read on first use, not at import, and only once; `load_input()`
|
|
107
|
+
returns it as a dict (pass `reload=True` to read it again). The module
|
|
108
|
+
attributes `device` and `device_full` are built the first time a script uses
|
|
109
|
+
them. By default the file is `in.json` in the working directory, where the
|
|
110
|
+
sandbox puts it; set `LVI_SANDBOX_INPUT` to read another file, e.g. a saved
|
|
111
|
+
`in.json` while developing a script outside a Playbook:
|
|
112
|
+
|
|
113
|
+
```bash
|
|
114
|
+
LVI_SANDBOX_INPUT=./samples/in.json python my_script.py
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
## Development and releases
|
|
118
|
+
|
|
119
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup and
|
|
120
|
+
[PUBLISHING.md](PUBLISHING.md) for how releases are published.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
VERSION
|
|
4
|
+
pyproject.toml
|
|
5
|
+
src/lvi_script_sandbox_utils/__init__.py
|
|
6
|
+
src/lvi_script_sandbox_utils/py.typed
|
|
7
|
+
src/lvi_script_sandbox_utils.egg-info/PKG-INFO
|
|
8
|
+
src/lvi_script_sandbox_utils.egg-info/SOURCES.txt
|
|
9
|
+
src/lvi_script_sandbox_utils.egg-info/dependency_links.txt
|
|
10
|
+
src/lvi_script_sandbox_utils.egg-info/requires.txt
|
|
11
|
+
src/lvi_script_sandbox_utils.egg-info/top_level.txt
|
|
12
|
+
tests/test_device_data.py
|
|
13
|
+
tests/test_inputs.py
|
|
14
|
+
tests/test_loading.py
|
|
15
|
+
tests/test_outputs.py
|
|
16
|
+
tests/test_package.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
lvi_script_sandbox_utils
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import time
|
|
3
|
+
|
|
4
|
+
import pytest
|
|
5
|
+
|
|
6
|
+
# 2026-10-27T00:30:00Z: shortly after midnight UTC, so a local-time conversion
|
|
7
|
+
# west of UTC would land on the 26th.
|
|
8
|
+
JUST_AFTER_MIDNIGHT_UTC = 1793061000000
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def write(path, data):
|
|
12
|
+
path.write_text(json.dumps(data), encoding="utf-8")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def test_none_becomes_blank_by_default(lvi):
|
|
16
|
+
device = lvi.get_device()
|
|
17
|
+
assert device.custom3 == ""
|
|
18
|
+
assert device.endOfLife == ""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def test_blank_none_false_keeps_none(lvi):
|
|
22
|
+
device = lvi.get_full_device(blank_none=False)
|
|
23
|
+
assert device.custom3 is None
|
|
24
|
+
assert device.endOfLife is None
|
|
25
|
+
assert lvi.get_device(blank_none=False).custom3 is None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@pytest.fixture
|
|
29
|
+
def los_angeles_time(monkeypatch):
|
|
30
|
+
monkeypatch.setenv("TZ", "America/Los_Angeles")
|
|
31
|
+
time.tzset()
|
|
32
|
+
yield
|
|
33
|
+
monkeypatch.undo()
|
|
34
|
+
time.tzset()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def test_dates_use_utc(lvi, in_json, sample, los_angeles_time):
|
|
38
|
+
sample["device"]["endOfLife"] = JUST_AFTER_MIDNIGHT_UTC
|
|
39
|
+
write(in_json, sample)
|
|
40
|
+
assert lvi.get_device().endOfLife == "2026-10-27"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def test_zero_date_left_alone(lvi, in_json, sample):
|
|
44
|
+
sample["device"]["endOfSale"] = 0
|
|
45
|
+
write(in_json, sample)
|
|
46
|
+
assert lvi.get_device().endOfSale == 0
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def test_timestamps_converted(lvi):
|
|
50
|
+
device = lvi.get_full_device()
|
|
51
|
+
assert device.lastBackup == "2026-10-27T16:00:10Z"
|
|
52
|
+
assert device.lastChange == "2026-10-15T12:00:11Z"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def test_booleans_are_not_epochs(lvi):
|
|
56
|
+
assert lvi.get_full_device().ncmEnabled is True
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def test_traits_kept(lvi):
|
|
60
|
+
assert "ssh" in lvi.get_device().traits
|
|
61
|
+
assert "ssh" in lvi.get_full_device().traits
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@pytest.mark.parametrize("meta", [None, {}, {"traits": None}])
|
|
65
|
+
def test_traits_without_meta(lvi, in_json, sample, meta):
|
|
66
|
+
sample["device"]["metaJson"] = meta
|
|
67
|
+
write(in_json, sample)
|
|
68
|
+
assert lvi.get_device().traits == []
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def test_metadata_started_at(lvi):
|
|
72
|
+
assert lvi.get_metadata().started_at == "2026-10-27T16:43:15Z"
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import json
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def write(path, data):
|
|
7
|
+
path.write_text(json.dumps(data), encoding="utf-8")
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def test_cli_output_missing_raises_clear_error(lvi):
|
|
11
|
+
# The sample is a first script node: globals has no `result`.
|
|
12
|
+
with pytest.raises(KeyError, match="no previous node result"):
|
|
13
|
+
lvi.get_input("cli_output")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def test_cli_output_default(lvi):
|
|
17
|
+
assert lvi.get_input("cli_output", default="") == ""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def test_cli_output_present(lvi, in_json, sample):
|
|
21
|
+
sample["globals"]["result"] = {"type": "string", "value": "line 1\nline 2"}
|
|
22
|
+
write(in_json, sample)
|
|
23
|
+
assert lvi.get_input("cli_output") == "line 1\nline 2"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def test_device_input_is_a_copy(lvi):
|
|
27
|
+
device = lvi.get_input("device")
|
|
28
|
+
device["hostname"] = "changed"
|
|
29
|
+
assert lvi.get_input("device")["hostname"] == "c1800"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def test_unknown_input_type(lvi):
|
|
33
|
+
with pytest.raises(ValueError, match="get_global"):
|
|
34
|
+
lvi.get_input("hostname")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def test_get_global_unwraps_value(lvi):
|
|
38
|
+
assert lvi.get_global("hostname") == "c1800"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def test_get_global_missing(lvi):
|
|
42
|
+
with pytest.raises(KeyError, match="has: hostname"):
|
|
43
|
+
lvi.get_global("nope")
|
|
44
|
+
assert lvi.get_global("nope", None) is None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def test_get_globals(lvi):
|
|
48
|
+
assert lvi.get_globals() == {"hostname": "c1800"}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def test_get_metadata(lvi):
|
|
52
|
+
metadata = lvi.get_metadata()
|
|
53
|
+
assert metadata.playbook == "Script - Simple Load"
|
|
54
|
+
assert metadata.execution_id == 40723
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def test_get_metadata_absent(lvi, in_json, sample):
|
|
58
|
+
del sample["metadata"]
|
|
59
|
+
write(in_json, sample)
|
|
60
|
+
assert vars(lvi.get_metadata()) == {}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def test_basic_and_full_device_fields(lvi):
|
|
64
|
+
basic = set(vars(lvi.get_device()))
|
|
65
|
+
full = set(vars(lvi.get_full_device()))
|
|
66
|
+
assert {"device_hostname", "device_network", "osVersion", "custom1"} <= basic
|
|
67
|
+
assert "uuid" in full and "uuid" not in basic
|
|
68
|
+
assert not {"hostname", "network", "metaJson", "customFields"} & full
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@pytest.mark.parametrize("field", ["uuid", "metaJson", "customFields", "hostname", "endOfLife"])
|
|
72
|
+
def test_device_tolerates_missing_field(lvi, in_json, sample, field):
|
|
73
|
+
del sample["device"][field]
|
|
74
|
+
write(in_json, sample)
|
|
75
|
+
lvi.get_device()
|
|
76
|
+
lvi.get_full_device()
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def test_no_device(lvi, in_json, sample):
|
|
80
|
+
del sample["device"]
|
|
81
|
+
write(in_json, sample)
|
|
82
|
+
with pytest.raises(KeyError, match="no 'device'"):
|
|
83
|
+
lvi.get_device()
|
|
84
|
+
assert lvi.get_input("device", default=None) is None
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import importlib
|
|
2
|
+
import json
|
|
3
|
+
import sys
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def test_import_reads_nothing(tmp_path, monkeypatch):
|
|
9
|
+
# No in.json here: importing must still work (e.g. for tests or tooling).
|
|
10
|
+
monkeypatch.chdir(tmp_path)
|
|
11
|
+
sys.modules.pop("lvi_script_sandbox_utils", None)
|
|
12
|
+
module = importlib.import_module("lvi_script_sandbox_utils")
|
|
13
|
+
try:
|
|
14
|
+
assert "device" not in vars(module)
|
|
15
|
+
with pytest.raises(FileNotFoundError):
|
|
16
|
+
module.device
|
|
17
|
+
finally:
|
|
18
|
+
sys.modules.pop("lvi_script_sandbox_utils", None)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def test_device_is_built_once(lvi):
|
|
22
|
+
assert lvi.device is lvi.device
|
|
23
|
+
lvi.device.note = "set by script"
|
|
24
|
+
assert lvi.device.note == "set by script"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def test_unknown_attribute_still_raises(lvi):
|
|
28
|
+
with pytest.raises(AttributeError):
|
|
29
|
+
lvi.not_a_thing
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def test_file_is_read_once(lvi, in_json):
|
|
33
|
+
assert lvi.load_input()["device"]["hostname"] == "c1800"
|
|
34
|
+
in_json.write_text(json.dumps({"device": {}}), encoding="utf-8")
|
|
35
|
+
assert lvi.load_input()["device"]["hostname"] == "c1800"
|
|
36
|
+
assert lvi.load_input(reload=True)["device"] == {}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def test_input_path_from_environment(lvi, tmp_path, monkeypatch, sample):
|
|
40
|
+
other = tmp_path / "other.json"
|
|
41
|
+
sample["device"]["hostname"] = "from-env"
|
|
42
|
+
other.write_text(json.dumps(sample), encoding="utf-8")
|
|
43
|
+
monkeypatch.setenv(lvi.INPUT_PATH_ENV, str(other))
|
|
44
|
+
assert lvi.input_path() == str(other)
|
|
45
|
+
assert lvi.device.device_hostname == "from-env"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def test_explicit_path(lvi, in_json):
|
|
49
|
+
assert lvi.load_input(str(in_json))["metadata"]["playbook"] == "Script - Simple Load"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def test_device_functions_do_not_change_cached_input(lvi):
|
|
53
|
+
lvi.get_device()
|
|
54
|
+
lvi.get_full_device()
|
|
55
|
+
device = lvi.load_input()["device"]
|
|
56
|
+
assert "hostname" in device and "metaJson" in device
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
import json
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def printed(capsys):
|
|
6
|
+
return json.loads(capsys.readouterr().out)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def test_flush_output(lvi, capsys):
|
|
10
|
+
lvi.flush_output(hostname="c1800", count=2)
|
|
11
|
+
assert printed(capsys) == {"output": {"globals": {"hostname": "c1800", "count": 2}}}
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def test_set_output_is_flushed_then_cleared(lvi, capsys):
|
|
15
|
+
lvi.set_output("a", 1)
|
|
16
|
+
lvi.set_output("b", 2)
|
|
17
|
+
lvi.flush_output(b=3)
|
|
18
|
+
assert printed(capsys) == {"output": {"globals": {"a": 1, "b": 3}}}
|
|
19
|
+
assert lvi.output == {}
|
|
20
|
+
lvi.flush_output()
|
|
21
|
+
assert printed(capsys) == {"output": {"globals": {}}}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def test_device_objects_are_serialized(lvi, capsys):
|
|
25
|
+
lvi.flush_output(device=lvi.get_device(), run=lvi.get_metadata())
|
|
26
|
+
data = printed(capsys)["output"]["globals"]
|
|
27
|
+
assert data["device"]["device_hostname"] == "c1800"
|
|
28
|
+
assert data["run"]["execution_id"] == 40723
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def test_flush_string_output(lvi, capsys):
|
|
32
|
+
lvi.flush_string_output("hi\nthere")
|
|
33
|
+
raw = printed(capsys)["output"]["raw"]
|
|
34
|
+
assert base64.b64decode(raw).decode("utf-8") == "hi\nthere"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def test_flush_string_output_converts_to_str(lvi, capsys):
|
|
38
|
+
lvi.flush_string_output(42)
|
|
39
|
+
assert base64.b64decode(printed(capsys)["output"]["raw"]) == b"42"
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def test_version_is_defined(lvi):
|
|
5
|
+
assert isinstance(lvi.__version__, str)
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def test_no_logicvein_package_is_shipped():
|
|
9
|
+
# A `logicvein/` directory would collide with lvi-api-client's on install.
|
|
10
|
+
assert not (Path(__file__).parents[1] / "src" / "logicvein").exists()
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def test_import_loads_device(lvi):
|
|
14
|
+
assert lvi.device.device_hostname == "c1800"
|
|
15
|
+
assert lvi.device_full.uuid == "00000000-0000-4000-8000-000000000001"
|