Metadata-Version: 2.4
Name: eduruckus-node-ui
Version: 0.1.0
Summary: Modular terminal UI for network diagnostics and IP configuration
Requires-Python: >=3.11
Description-Content-Type: text/markdown
Requires-Dist: textual<7,>=6.12
Requires-Dist: icmplib<4,>=3.0.4
Requires-Dist: pyte<0.9,>=0.8.2
Requires-Dist: pyroute2<1,>=0.9.7; sys_platform == "linux"
Provides-Extra: dev
Requires-Dist: pytest<10,>=8; extra == "dev"
Requires-Dist: pytest-asyncio<2,>=0.24; extra == "dev"
Requires-Dist: build<2,>=1; extra == "dev"

# EduRuckus Node UI

A modular Python terminal application for IPv4/IPv6 ping, mtr traceroutes,
tcpdump capture, an embedded bash shell, and Linux `eth0` address and static-route management.

The interface follows [layout.svg](layout.svg): the tool selector is at the upper
left, the selected tool's scrollable form is at the upper right, and a full-width,
scrollable output text box sits below. Mouse and keyboard navigation both work.

## Install and run

Requires Python 3.11 or newer. IP management requires Linux.

```sh
python3 -m venv .venv
.venv/bin/python -m pip install -e .
.venv/bin/eduruckus-node-ui
```

Alternatively, after installing the package:

```sh
.venv/bin/python -m eduruckus_node_ui
```

Traceroute needs a system `mtr` build with JSON support. Packet capture additionally
needs `tcpdump`. For Debian/Ubuntu:

```sh
sudo apt install mtr-tiny tcpdump
```

The menu is **Ping, Ping6, Traceroute, Traceroute6, TCP dump, CLI, IP management,
Logout**, as specified. All tools are available without extra CLI flags.

## Using the application

- Use the mouse or **Up/Down, Enter** to select a tool. **Tab/Shift+Tab** moves
  between controls. Radio buttons and checkboxes support keyboard selection.
- Enter an address and press **Run test**, or **F5**. Numeric defaults are
  preloaded. **Default setting** resets every field, including the blank address.
- Press **Escape** to abort a diagnostic or packet capture. Ping sockets are
  closed; subprocesses and their helper processes are terminated and reaped.
- **Word wrap** toggles output wrapping. **Copy all** copies the entire retained
  output, including pending output, using Textual's terminal clipboard support. Clipboard
  availability depends on the terminal. **Clear** clears the retained output.
- Choose **Logout** or press **Ctrl+Q** to exit. Active diagnostics are cancelled
  and cleaned up first.

Forms scroll independently, so the longer traceroute and IP management forms remain
usable in an 80×24 terminal. Larger terminals provide more room. Output history is
bounded to approximately 256 KiB to keep large-count tests and captures responsive.
The CLI has its own terminal display and retains up to 2000 lines of scrollback.

### Ping and Ping6

Uses icmplib's asynchronous ping API with live per-probe replies/timeouts and a
final transmission, loss, and min/average/max RTT summary. Partial statistics are
kept on cancellation. IPv4 and IPv6 addresses are validated separately; DNS names
are intentionally not accepted by these address-only forms.

| Field | Default | Accepted range |
| --- | --- | --- |
| IP address | blank (required) | IPv4: 1.1.1.1–255.255.255.255; Ping6: valid IPv6 |
| Count | 3 | 1–100000 |
| Packet size | 56 | 1–9000 payload bytes |
| Interval | 1 | 0.01–10 seconds |
| Timeout | 1 | 1–10 whole seconds |

The brief labels interval as an integer but requires a minimum of `0.01`; it is
therefore parsed as a finite floating-point number.

Ping requests use `privileged=False`. Linux must permit ICMP datagram sockets for
the user's group (`net.ipv4.ping_group_range`); otherwise an error appears in the
output. The application does not change system permissions or invoke sudo.

### Traceroute and Traceroute6

Runs `mtr` with an argument list through `asyncio` subprocess, with `--json`,
report mode, numeric hosts, and explicit IPv4/IPv6 selection. The tool waits for
the completed report, then shows a hop summary and the formatted original JSON.

The form includes the ping numeric settings plus **ICMP/TCP/UDP** radio buttons,
**Port** (443; 1–65535), **Max TTL** (30; 1–30), and **Display AS number** (off).
Count maps to `--report-cycles`; timeout maps to `--timeout` and the final
`--gracetime`. Port is disabled and ignored for ICMP. AS lookup maps to
`--aslookup`. Fractional intervals may require root, depending on the installed
mtr. mtr packet size includes headers; its TCP mode may ignore packet size.

### CLI

Select **CLI**, directly above IP management, to start an interactive bash shell
inside the output pane. The cursor moves into the shell automatically. Bash uses
the application's working directory and environment, reads its normal interactive
startup configuration, and runs with the application's user permissions.

The shell runs on a pseudo-terminal with terminal escape-sequence handling,
colors, interactive input, and resize support. History, Tab completion, and normal
bash editing shortcuts are forwarded to the shell. **Ctrl+C** interrupts a shell
command; **Escape** is passed to bash. **Shift+PageUp/PageDown** or the scrollbar
scrolls shell history. **Copy all** copies the shell display and its retained
history, and **Clear** clears that display. Word wrap is disabled while viewing
the terminal because bash manages its terminal columns.

Type `exit` or press **Ctrl+D** at an empty prompt to end bash and return focus to
the **Tools** menu. Shell output remains visible until another tool is selected.
Selecting CLI again starts a fresh shell. **Ctrl+Q** closes the shell and logs out
of the application. The menu is disabled while bash runs. CLI requires a POSIX
system with `bash` available on `PATH`.

### IP management

Loads `eth0` addresses and main-table routes through pyroute2 when selected. Masks
are decimal **prefix lengths** (IPv4 0–32; IPv6 0–128), matching the integer mask
fields in the brief. The form edits one primary global address per family.
Leaving both address and mask blank removes that primary address on Apply.

Routes appear in a table with destination, next hop, weight, and editability.
Select a row and press Enter to populate the route editor. **Add / update route**
updates the loaded route, or adds a new route if none was loaded from the table.
Saving or removing a route clears the editor for another new entry.
**Remove route** stages removal of the loaded route.
**Apply changes** commits the address fields and staged routes. **Reload**
discards staged edits and reads the current configuration. Route editor fields
must be saved with Add / update route before applying.

The editable route data uses the brief's dictionary shape:

```json
{
  "10.0.0.0/24": {"nexthop": "192.168.1.254", "weight": 200},
  "172.20.14.0/23": {"nexthop": "192.168.1.200", "weight": 10}
}
```

Because each entry has a single next hop, `weight` maps to Linux route priority
(metric), with lower values preferred; it is not an ECMP nexthop weight. Default
routes use `0.0.0.0/0` or `::/0`.

Only unicast, single-gateway static/boot routes for `eth0` in the main table are
editable. Connected, dynamic and duplicate-destination routes are read-only;
other interfaces, tables, and multipath routes are outside the editor's scope.
The application never flushes all addresses or routes. Before writing, it checks
that the loaded configuration is still current. If a kernel operation fails, it
attempts to reverse completed operations and reports any rollback failure.
Replacing a primary IPv4 address is refused if secondary IPv4 addresses are
present, because Linux may otherwise remove those secondary addresses implicitly.
Changes are not an atomic kernel transaction and may temporarily interrupt
connectivity. They affect the running system and are not saved to the OS network
manager; a network manager may subsequently replace them.

Applying configuration needs root or `CAP_NET_ADMIN`. If appropriate for your
machine, launch the installed environment with:

```sh
sudo .venv/bin/eduruckus-node-ui
```

Kernel writes run off the UI thread. Escape and Logout are disabled while an Apply
is in progress, allowing the write/rollback sequence to finish. Merely opening the tool
performs read operations only.

### TCP dump

The TCP dump form has a single, initially blank capture-filter field. Enter a BPF
filter such as `tcp port 443`, or leave it blank to capture all traffic on tcpdump's
default interface. Press **Run test** to start capture and **Escape** to stop it,
even if no packets arrive. There is no packet-count limit. The subprocess uses
numeric addresses and line-buffered live output. Appropriate capture privileges are required, typically
root or system-configured `CAP_NET_RAW`/`CAP_NET_ADMIN` permissions.

## Add a tool

Diagnostic implementations do not depend on Textual. Subclass `Tool`, describe its
fields, and implement the cancellable async `run(values, emit)` method:

```python
from eduruckus_node_ui.app import NetworkApp
from eduruckus_node_ui.tools import default_tools
from eduruckus_node_ui.tools.base import Field, Tool


class ExampleTool(Tool):
    key = "example"
    name = "Example"
    description = "An example diagnostic"
    fields = (Field("count", "Count", "3", "int", 1, 10),)

    async def run(self, values, emit):
        emit(f"Requested count: {values['count']}")


NetworkApp(tools=[*default_tools(), ExampleTool()]).run()
```

`Field` supports text, int, float, bool (checkbox), and radio choices. Override
`validate()` for cross-field rules. Use nonblocking I/O or `asyncio.to_thread` for
blocking calls, and release resources in `finally` on cancellation. Alternatively,
register the instance in `tools.default_tools()` to include it in the CLI.

Source modules:

- `app.py`: layout, output, actions, and async operation lifecycle.
- `forms.py`: metadata-driven diagnostic forms and the network route editor.
- `tools/`: validation contract, registry, ping, traceroute, capture, process cleanup.
- `network.py`: pyroute2 reads, validation, exact configuration differences, rollback.
- `shell.py` and `_shell_child.py`: embedded terminal, PTY lifecycle, and bash startup.

## Development and verification

```sh
.venv/bin/python -m pip install -e '.[dev]'
.venv/bin/python -m pytest
.venv/bin/python -m build
```

Tests exercise input limits, IPv4/IPv6 separation, protocol arguments, JSON/error
handling, cancellation, real child-process cleanup, mocked kernel changes and
rollback, plus Textual's headless UI pilot for navigation, defaults, output,
route editing, and multiple terminal sizes. Shell tests exercise a real local
bash PTY, keyboard input, history, resizing, interruption, exit focus, and cleanup.
Tests never change the host's network
configuration and do not require external connectivity or root.

API references: [Textual TextArea](https://textual.textualize.io/widgets/text_area/),
[icmplib](https://github.com/ValentinBELYN/icmplib),
[mtr manual](https://github.com/traviscross/mtr/blob/master/man/mtr.8.in), and
[pyroute2 Linux API](https://docs.pyroute2.org/iproute_linux.html), and
[pyte terminal emulation](https://pyte.readthedocs.io/).
