Metadata-Version: 2.4
Name: lvi-api-client
Version: 0.22.0
Summary: LogicVein API Client Library
Author: LogicVein Inc.
License-Expression: Apache-2.0
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.14
Classifier: Operating System :: OS Independent
Classifier: Typing :: Typed
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.34.2
Requires-Dist: urllib3>=2.8.0
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Requires-Dist: pytest-cov; extra == "dev"
Dynamic: license-file

# LogicVein API Client

A Python client for interacting with the LogicVein API.

## Installation

From PyPI:

```bash
pip install lvi-api-client
```

From TestPyPI (pre-release / testing):

```bash
pip install \
  --index-url https://test.pypi.org/simple/ \
  --extra-index-url https://pypi.org/simple/ \
  lvi-api-client
```

See [PUBLISHING.md](PUBLISHING.md) for instructions on publishing new releases.

## Usage

```python
from logicvein import LogicVeinAPIClient

client = LogicVeinAPIClient(host="your-lvi-server", api_token="your-token")
devices = client.search_devices_in_network()
```

The arguments are `host`, `api_token`, `username`, `password`, `verify`, `timeout` and
`ignore_env_vars`, all keyword-only; any other keyword is a `TypeError`. A setting that is not
passed, or is empty, is read from `LVI_HOST`, `LVI_API_TOKEN` (or `LVI_USERNAME` and
`LVI_PASSWORD`), `LVI_VERIFY_SSL` and `LVI_TIMEOUT`; `ignore_env_vars=True` reads none of them.
There is no default host: a client with no host, or with neither an API token nor both a
username and a password, raises `ValueError` before anything is sent.

### Searching devices and groups

`search_devices_in_network(network=["Default"], query="...", scheme="tag")`
returns all matching devices, fetching pages automatically. Pass `max_rows=10` to return at most
10 rows and stop fetching when the bound is reached.
`search_incidents` accepts the same optional bound. Both methods accept `page_size` to set
the maximum rows per request; the final request is reduced to the remaining bound.
The default scheme remains `"tag"`.

Use `get_group_devices(group_id, networks)` for group membership:

```python
networks = ["Default", "Production"]
groups = client.get_all_groups(networks)
if groups:
    devices = client.get_group_devices(groups[0]["deviceGroupId"], networks)
```

Both arguments must be non-empty (a blank group ID also raises `ValueError`).
The method reads the groups again before searching and raises `LogicVeinAPIError`
if the ID is not listed: the server treats an unknown ID as every device in a network.
It searches each network using the quoted scheme `'"group"'` and checks the returned
count against `networkDeviceCounts` (a missing network entry means zero). A mismatch
raises `LogicVeinAPIError` naming the group ID, network, expected count and actual count;
membership changes during the calls can cause this. A known empty group returns `[]`.
Results retain `network` and `ipAddress`; together these identify a device.

### Paging

These methods fetch every page for you and return one list: `search_devices_in_network`,
`search_incidents`, `search_term_logs`, `search_jobs`, `search_jobs_with_queries`,
`search_job_executions`, `search_monitor_sets`, `search_monitor_templates`, `search_alert_policies`,
`get_device_configuration_change_logs`, `get_config_history`, `search_device_interfaces`,
`get_device_arp_table`, `get_arp_entries`, `get_device_mac_table`, `get_credential_sets` and
`get_playbooks`. They share one helper that asks for `offset` 0, `page_size`, 2 `page_size` and so
on, and stops at the first page shorter than it asked for.

- `page_size` is how many records one API call asks for. It does not cap the result: with 1200
  matches and `page_size=500` you get all 1200, in three search calls. A method called without
  `networks` first makes one more call to list them.
- `max_rows` is the cap, and only `search_devices_in_network`, `search_incidents` and
  `search_term_logs` have it. It stops the fetching once that many rows are collected, and the
  last request asks for no more than the rows still wanted.
- Both must be positive integers, or the call raises `ValueError` before the first page is asked
  for. `get_arp_entries` called without `networks` lists the networks first and checks
  `page_size` only once it has some to search, so with no networks it returns `[]` instead.
- A page that is malformed, repeats the one before it, or runs far past the total the server
  reported raises `LogicVeinResponseError` (its `offset` says where) rather than returning a
  partial list.

`get_device_file_store_entries` and `search_zero_touch_history` return a single page instead:
they take `offset` and `page_size`, and you call them again with a higher `offset` for the next
page.

```python
first = client.search_term_logs(networks=["Default"], page_size=100, max_rows=250)  # up to 3 calls, 250 rows
page = client.get_device_file_store_entries("192.0.2.1", "Default", offset=1000, page_size=1000)
```

### What the methods cover

`LogicVeinAPIClient` has 161 public methods. It is one class, made of one mixin per area, each
in a private module under `src/logicvein/` (named in the table); `src/logicvein/lvi_api_client.py`
combines them, and it and `logicvein` are where to import from. The table groups the methods by
the headings in those modules; `dir(client)` or the docstrings list them all.

| Area | Module | Methods | Some of them |
|------|--------|---------|--------------|
| Core / Authentication | `_core.py` | 3 | `authenticate`, `test_connection`, `call` |
| Networks | `_core.py` | 1 | `get_networks` |
| Networks - Managed Network Methods | `_networks.py` | 7 | `define_managed_network`, `get_managed_network`, `get_all_managed_networks`, `delete_managed_network` |
| Inventory / Devices | `_devices.py` | 10 | `search_devices_in_network`, `get_device_by_ip`, `create_device`, `update_device` |
| Memos | `_devices.py` | 6 | `get_memo`, `create_memo`, `get_device_memo`, `set_device_memo` |
| Device Groups | `_devices.py` | 2 | `get_all_groups`, `get_group_devices` |
| Adapters | `_devices.py` | 1 | `get_available_adapters` |
| Configuration | `_configuration.py` | 6 | `get_config_history`, `get_device_configuration_revision`, `get_config_revision_word_diff` |
| Interfaces | `_telemetry.py` | 4 | `get_device_interfaces`, `get_device_vlan_port_mappings`, `search_device_interfaces`, `get_device_hardware` |
| Telemetry (ARP, MAC, Neighbors) | `_telemetry.py` | 5 | `get_device_arp_table`, `get_device_mac_table`, `get_device_neighbors`, `find_switch_port_for_host` |
| Compliance (Rule Sets, Policies, Violations) | `_compliance.py` | 20 | `get_all_rule_sets`, `create_rule_set`, `get_all_policies`, `get_policy` |
| Incidents | `_incidents.py` | 5 | `save_incident`, `get_incident_by_id`, `search_incidents`, `get_webhook_templates` |
| Credentials | `_credentials.py` | 10 | `get_all_credential_configs`, `save_credential_config`, `get_credential_sets`, `save_credential_sets` |
| Playbooks (Visual Scripts) | `_playbooks.py` | 9 | `get_playbooks`, `get_playbook`, `save_playbook`, `delete_playbook` |
| Scheduler - Job Methods | `_scheduler.py` | 14 | `run_job_now`, `save_job`, `get_job`, `search_jobs` |
| Bridges | `_networks.py` | 3 | `define_bridge`, `update_bridge`, `delete_bridge` |
| Security (Users, Roles) | `_security.py` | 11 | `get_users`, `get_user_by_name`, `create_user`, `update_user` |
| Jumphosts | `_networks.py` | 2 | `get_jumphost_for_network`, `save_jumphost` |
| Terminal Logs | `_logs.py` | 1 | `search_term_logs` |
| Mibs | `_collection.py` | 2 | `find_mib_children`, `find_mib_nodes_by_oid` |
| Collection (Monitor Sets, Alert Policies) | `_collection.py` | 27 | `get_monitor_set`, `search_monitor_sets`, `search_monitor_templates`, `save_alert_actions` |
| Maps / Topology | `_maps.py` | 4 | `get_map`, `get_map_tree`, `save_map`, `delete_maps` |
| Dashboard | `_maps.py` | 3 | `get_all_dashboards`, `save_dashboard`, `delete_dashboard` |
| FileStore | `_configuration.py` | 1 | `get_device_file_store_entries` |
| Plugins/Execution | `_scheduler.py` | 3 | `get_execution_details`, `get_execution_record`, `get_execution_output` |
| ZeroTouch | `_logs.py` | 1 | `search_zero_touch_history` |

### Logging in

With an API token there is no login: the token goes in a header of every call. If you give both
a token and a username and password, the token is used and the client does not log in. With a
username and password and no token, the client logs in as it is created, and `authenticate()` logs in
again. A login that does not work raises:

- `LogicVeinAuthenticationError`: the server rejected the username or password (HTTP 401). It
  has `host` and `username`.
- `LogicVeinConnectionError`: the server could not be reached or did not answer as it should:
  connection refused, host name not found, TLS failure, timeout, a redirect, a request for a
  one-time code, no `/auth` login, a success that leaves the session with no cookie, any
  other HTTP error status, or a CA bundle path that does not exist. It has `host`, `reason`
  and, if the server answered, `status_code`.

```python
from logicvein import LogicVeinAPIClient, LogicVeinAuthenticationError, LogicVeinConnectionError

try:
    client = LogicVeinAPIClient(host="your-lvi-server", username="your-user", password="your-password")
except LogicVeinAuthenticationError as error:
    print(f"Wrong username or password: {error}")
except LogicVeinConnectionError as error:
    print(f"Server problem: {error}")
```

Neither error holds the password, the request or its URL, so both are safe to print and log.

### Errors from a call

Methods follow one rule for what they return and raise, except the few listed after it:

- **A call that did not work raises.** It never returns something that reads as "nothing found",
  such as `False`, `None`, `""` or `[]`.
- **"Not found" is `None` for one object and `[]` for a list**, and only when the server said so.
- **A write returns what the server stored, or raises.** A write whose server method returns
  nothing (most deletes, updates and enables) returns `True`; read the object back to see what was
  stored. A write that answers `null`, `true` or its record is done. One whose result reports a failure
  (`{"success": false, "error": ...}`, or an error message in place of `null`) raises
  `LogicVeinAPIError` with the server's message, and any other result raises
  `LogicVeinResponseError`.
- **Arguments are checked before anything is sent.** An empty IP address, a custom field that does
  not exist or a request that sets nothing is a `ValueError`, and no call is made.

Where the rule leaves a choice, this is what the methods do:

- A write that reads its target first, and finds none, sends nothing and says so with the falsy
  form of its return type: `update_device()` and `update_role()` return `None`, and
  `update_custom_fields()`, `update_end_of_dates()`, `update_bridge()` and `update_user()` (when it
  needs a stored value to keep) return `False`.
  `update_device_hardware()` returns `False` when the server answers "hardware not found", and
  `delete_job()` returns `False` when the server answers `false`.
- `test_connection()` returns `False` rather than raising: it is the question "can I reach the
  server?".
- `enable_monitor_for_host()`, `disable_monitor_for_host()` and `delete_alert_policy()` read the
  server back and return whether the change shows there.
- A method that passes the server's result on returns it as it comes, so a `null` result is
  `None`. Whether some server methods answer `null` for "none" rather than an empty list has not
  been measured for every method.
- These still break the rule, because their request shapes are pinned by tests and what their
  server methods answer has not been measured; until it is, treat their falsy return as "did not
  work", not as "nothing there":
  - `delete_managed_network()` returns `False` when the server answers `{"error": "Failed"}`.
  - `delete_monitor_sets()` returns `False` for any answer but `null`, and `delete_monitor_template()`
    and `delete_maps()` for any answer but `true`. `delete_trigger()` returns `bool(result)`.
  - `create_rule_set()` returns `True` or `False`, not the stored rule set.
  - `save_alert_actions()` and `add_monitors_to_set()` return `[]` for a result that is not a list.
- A few older reads raise `ValueError`, not `LogicVeinResponseError`, for an answer they cannot
  use: `get_job_triggers()`, `get_monitors_for_host()`, `get_rule_sets_scoped_only_to()`, the
  monitor set and alert policy name and reference checks, and a strict violation or alert policy
  read.

The exceptions:

- `LogicVeinAPIError`: the server answered with a JSON-RPC `error`. It has `method`, `code`,
  `message`, `data` and `status_code` (the HTTP status; the server answers a failed call with
  500, and the reason is usually in `data`). The message reads
  `<method>: <message> (code <code>): <data>`, with `data` cut to 500 characters and the client's
  API token and password removed from the message and the attributes. A reply that echoes other
  secret parameters of the request, such as a credential being saved, would still show them, so
  treat the message as you would the request. A write whose result reports a failure raises it
  too, with the server's message and `status_code` None.
- `LogicVeinResponseError`: the server answered HTTP 200 with something that is not a JSON-RPC
  answer, as a login page, a proxy's error page or the wrong host does: a body that is not
  JSON, JSON that is not an object, or an object with neither `result` nor `error`. It has
  `method`, `reason`, `status_code`, `content_type` and `body` (the first 200 characters).
  The client's API token and password (the constructor's, or the one last given to
  `authenticate()`) are removed from that text, as written, JSON-escaped and percent-encoded,
  and from the line logged for an HTTP error status. A reply that echoes other secret
  parameters of the request, such as a credential being saved, would still show them. A method
  that cannot use a result raises it too, with `status_code` None and a message that names the
  method and the kind of result (`false`, `a list`), not its contents.
- `requests.HTTPError`: an HTTP error status whose body is not a JSON-RPC error, such as a
  proxy's 502 page or a 401.

The password login is a POST to `https://<host>/auth` with the username and password in a form
body. The URL has no query string, so the password is not in the request line that servers and
reverse proxies commonly write to their access logs. The response `authenticate()` returns
holds the login request, and so the password, in `request.body`: do not log or print that.

Four answers to the login are a `LogicVeinConnectionError` whose `reason` says what they mean:

| Answer | Meaning | What to do |
|--------|---------|------------|
| HTTP 202 | The account needs a one-time code, which the client cannot supply. | Use an API token. |
| HTTP 404 or 405 | The server has no `/auth` login. The client has no other password login. | Use an API token. |
| Any HTTP 3xx | The login was redirected. The client never follows a login's redirect, because that can send the password to another address. | Set `host` to the name the server itself answers on. |
| HTTP 2xx (not 202) and no cookie in the session | A cookie login with no cookie logged nothing in: the answer came from a proxy's page or a host that is not a LogicVein server. | Check `host` and any proxy in front of the server. |

`authenticate()` passes extra keyword arguments on to the session's `post()`, except the ones
the login sets itself, which are a `TypeError`: `allow_redirects`, `data`, `files`, `headers`,
`json`, `params` and `timeout`.

A redirect whose `Location` header cannot be parsed is a `LogicVeinConnectionError` too, but
without the status: `requests` fails on it before the client sees the answer, so the `reason`
names that failure, as in `request failed (ValueError)`, and `status_code` is `None`.

The login is judged by its HTTP status and by the session's cookies. Any 2xx but 202 is taken as
a login if the session holds a cookie afterwards, and raises if it holds none. The session's
cookie jar is what is checked, not the answer's `Set-Cookie` header: the server answers a second
login on a session that is already logged in without a new cookie, and that login returns. The
check is a necessary condition only. Any cookie in the jar counts: its name, the host it is for
and whether it has expired are not checked. A proxy's page that sets a cookie of its own passes,
and so does a session that already held a cookie from somewhere else, so `test_connection()` is
still what tells a LogicVein server from a host that is not one.

An API token needs no login and works where a password login does not: prefer one where you
can.

### TLS verification

The client verifies the server's TLS certificate by default. For a server whose certificate
comes from a private CA, keep verification on and either pass the CA's certificate file as
`verify="/path/to/ca.pem"` (it reaches the session unchanged, as in requests) or point
`REQUESTS_CA_BUNDLE` at it. `verify=False`, or `LVI_VERIFY_SSL=false`, turns verification off,
and the API token or password is then sent to whichever server answers. `LVI_VERIFY_SSL`
accepts true/false, 1/0, yes/no and on/off in any case; unset or empty means verify, and
anything else, a path included, is an error: use the `verify=` argument for a path. With
verification off, urllib3's "unverified HTTPS request" warning is hidden for this client's host
only, not for the process.
