Update project description and enhance documentation for clarity

- Revised the project description in `pyproject.toml` to better reflect the functionality of the `oxipy` client.
- Improved the README.md by adding detailed explanations of the project structure, installation instructions, and usage examples.
- Updated documentation files to enhance clarity and organization, including sections on extending models and writing TTP templates.
- Adjusted various TTP templates to ensure consistency and accuracy in the parsing of device configurations.
This commit is contained in:
IluaAir
2026-05-25 16:01:38 +03:00
parent e8c33b0e64
commit 41c4cc48e9
17 changed files with 524 additions and 642 deletions

View File

@@ -1,86 +1,86 @@
# Написание TTP-шаблонов
# Writing TTP Templates
oxipy использует библиотеку [TTP (Template Text Parser)](https://ttp.readthedocs.io/) для парсинга конфигураций сетевых устройств в структурированные данные. Шаблоны хранятся в директории `oxi/interfaces/models/templates/`.
`oxipy` uses [TTP (Template Text Parser)](https://ttp.readthedocs.io/) to turn
network device configurations fetched from Oxidized into structured data.
Templates are stored in `oxi/interfaces/models/templates/`.
## Содержание
## Contents
- [Структура шаблона](#структура-шаблона)
- [Обязательные группы](#обязательные-группы)
- [Секция system](#секция-system)
- [Секция interfaces](#секция-interfaces)
- [Секция vlans](#секция-vlans)
- [TTP: основные возможности](#ttp-основные-возможности)
- [Переменные по умолчанию](#переменные-по-умолчанию)
- [Практические примеры](#практические-примеры)
- [Валидация шаблона](#валидация-шаблона)
- [Template Structure](#template-structure)
- [Required Groups](#required-groups)
- [The system Group](#the-system-group)
- [The interfaces Group](#the-interfaces-group)
- [The vlans Group](#the-vlans-group)
- [Useful TTP Features](#useful-ttp-features)
- [Default Variables](#default-variables)
- [Full Example](#full-example)
- [Validation](#validation)
---
## Template Structure
## Структура шаблона
Каждый шаблон — это `.ttp`-файл, состоящий из следующих блоков:
Each template is a `.ttp` file with a small set of conventional blocks:
```xml
<doc>
Описание шаблона (опционально)
Optional template documentation.
</doc>
<vars>
<!-- Переменные по умолчанию для групп -->
<!-- Default values for groups. -->
</vars>
<group name="system">
<!-- Правила для системной информации -->
<!-- Rules for system information. -->
</group>
<group name="interfaces">
<!-- Правила для интерфейсов -->
<!-- Rules for interfaces. -->
</group>
<group name="vlans">
<!-- Правила для VLAN (опционально) -->
<!-- Optional rules for VLANs. -->
</group>
```
Файл-заготовка находится в `oxi/interfaces/models/templates/_template.ttp`.
Use `oxi/interfaces/models/templates/_template.ttp` as the starting point for a
new parser.
---
## Required Groups
## Обязательные группы
The framework requires two groups in every template:
Фреймворк требует наличия в шаблоне **двух обязательных групп**:
| Group | Required | Description |
| --- | --- | --- |
| `system` | Yes | Device system information. |
| `interfaces` | Yes | Interface configuration. |
| `vlans` | No | VLAN configuration. |
| Группа | Обязательна | Описание |
|--------------|-------------|-------------------------------|
| `system` | Да | Системная информация |
| `interfaces` | Да | Конфигурация интерфейсов |
| `vlans` | Нет | Конфигурация VLAN |
If a required group is missing from the template or from the TTP result,
`BaseDevice` raises `ValueError`.
Если обязательная группа отсутствует в шаблоне или TTP не вернул её данные, будет выброшено `ValueError`.
If a template declares an optional `vlans` group, `oxipy` expects TTP to return
that group. Omit the group completely for devices where VLAN parsing is not
implemented.
---
## The system Group
## Секция system
The `system` group must return one dictionary with these fields:
Должна возвращать словарь со следующими полями:
| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `model` | `str` | Yes | Device model. |
| `serial_number` | `str` | Yes | Device serial number. |
| `version` | `str` | Yes | Firmware, software, or build version chosen by the parser. |
| Поле | Тип | Обязательное | Описание |
|-----------------|------|--------------|---------------------|
| `model` | str | Да | Модель устройства |
| `serial_number` | str | Да | Серийный номер |
| `version` | str | Да | Версия прошивки |
Example for MikroTik:
**Пример (MikroTik):**
Конфигурация:
```
```text
# version: 7.12.1 (stable)
# model = RB951Ui-2nD
# serial number = B88C0B31117B
```
Шаблон:
```
```xml
<group name="system">
# version: {{ version }}{{ ignore('.*') }}
# model = {{ model }}
@@ -88,17 +88,15 @@ oxipy использует библиотеку [TTP (Template Text Parser)](htt
</group>
```
**Пример (Keenetic):**
Example for Keenetic:
Конфигурация:
```
```text
! release: 4.1.7.1-1
! model: Keenetic Extra
! hw_version: F02B4E7A1C90
```
Шаблон:
```
```xml
<group name="system">
! release: {{ version }}
! model: {{ model | ORPHRASE }}
@@ -106,34 +104,34 @@ oxipy использует библиотеку [TTP (Template Text Parser)](htt
</group>
```
---
## The interfaces Group
## Секция interfaces
The `interfaces` group must return a list of dictionaries. Each dictionary
describes one interface.
Должна возвращать список словарей. Каждый словарь описывает один интерфейс.
The `Interfaces` contract expects these fields:
Поля, которые ожидает контракт `Interfaces`:
| Contract field | TTP name / alias | Type | Required |
| --- | --- | --- | --- |
| `name` | `interface` | `str` | Yes |
| `ip_address` | `ip_address` | `IPv4Address | None` | No |
| `mask` | `mask` | `int | None` | No |
| `description` | `description` | `str | None` | No |
| Поле | TTP-имя / alias | Тип | Обязательное |
|---------------|-----------------|------------------|--------------|
| `name` | `interface` | str | Да |
| `ip_address` | `ip_address` | IPv4Address | Нет |
| `mask` | `mask` | int (prefix len) | Нет |
| `description` | `description` | str | Нет |
The Pydantic field `name` has the alias `interface`, so templates should usually
emit `interface`. You can also emit `name` because the models allow population
by field name, or you can normalize keys in the device class by overriding
`interfaces()`.
> **Важно:** поле `name` в Pydantic-модели имеет алиас `interface`, поэтому в шаблоне переменную нужно называть именно `interface` **или** переопределить метод `interfaces()` в классе модели (см. [Расширение моделей](extending-models.md)).
Example for MikroTik:
**Пример (MikroTik):**
Конфигурация:
```
```text
/ip address
add address=192.168.1.1/24 interface=ether1 network=192.168.1.0
add address=10.0.0.1/30 comment="WAN link" interface=ether2 network=10.0.0.0
```
Шаблон:
```
```xml
<group name="interfaces">
/ip address
add address={{ ip_address | _start_ }}/{{ mask }} interface={{ interface }} network={{ network }}
@@ -141,108 +139,104 @@ add address={{ ip_address | _start_ }}/{{ mask }} comment={{ description | ORPHR
</group>
```
**Пример (Keenetic):**
Example for CLI-style devices:
Конфигурация:
```
interface GigabitEthernet0/0
description "WAN"
ip address 10.0.0.2 255.255.255.252
interface GigabitEthernet0/1
ip address 192.168.1.1 255.255.255.0
```text
interface Vlanif120
description SSH
ip address 10.26.196.254 255.255.255.0
```
Шаблон:
```
```xml
<group name="interfaces">
interface {{ name | _start_ | exclude("Vlan") }}
description {{ description | ORPHRASE }}
ip address {{ ip_address }} {{ netmask }}
interface {{ interface | _start_ }}
description {{ description | ORPHRASE }}
ip address {{ ip_address }} {{ mask | to_cidr }}
</group>
```
Здесь переменная называется `name`, а не `interface` — это покрывается переопределением метода `interfaces()` в классе `Keenetic`.
Use TTP's `to_cidr` formatter when the device uses dotted decimal masks.
---
## The vlans Group
## Секция vlans
The `vlans` group is optional. If it is declared, it must return a list of VLAN
dictionaries.
Необязательная группа. Если объявлена в шаблоне, фреймворк ожидает её наличия в результате TTP.
The `Vlans` contract expects these fields:
Поля контракта `Vlans`:
| Contract field | Alias | Type | Required |
| --- | --- | --- | --- |
| `vlan_id` | none | `int` | Yes |
| `name` | `description` | `str | None` | No |
| Поле | TTP-имя / alias | Тип | Обязательное |
|-----------|-----------------|------|--------------|
| `vlan_id` | `id` | int | Да |
| `name` | `description` | str | Нет |
`name` has the alias `description`, so either key is accepted. Existing parsers
use both forms depending on the vendor format.
> `vlan_id` имеет алиас `id`, поэтому в шаблоне переменная должна называться `id` либо переименовываться в методе `vlans()`.
Example:
**Пример (Keenetic):**
Конфигурация:
```
interface Bridge0/Vlan10
description "MGMT"
interface Bridge0/Vlan20
description "SERVERS"
```text
vlan 10
name MGMT
```
Шаблон:
```
```xml
<group name="vlans">
interface {{ ignore }}/Vlan{{ id }}
description {{ description | ORPHRASE | strip('"') }}
vlan {{ vlan_id | _start_ }}
name {{ name | ORPHRASE }}
</group>
```
---
For compressed vendor syntax such as `vlan batch 101 to 103 110`, parse the raw
range in the template and normalize it in the device class when needed.
## TTP: основные возможности
## Useful TTP Features
### Маркеры строк
### Line markers
| Маркер | Описание |
|-------------|---------------------------------------------------------------|
| `_start_` | Строка с этой переменной считается началом нового совпадения |
| `_end_` | Строка с этой переменной завершает совпадение группы |
| Marker | Description |
| --- | --- |
| `_start_` | Starts a new group match from the current line. |
| `_end_` | Ends the current group match. |
```
add address={{ ip_address | _start_ }}/{{ mask }} interface={{ name }}
```xml
interface {{ interface | _start_ }}
```
### Модификаторы переменных
### Variable modifiers
| Модификатор | Описание |
|------------------------|-----------------------------------------------------------|
| `ORPHRASE` | Захватывает одно слово или фразу (до конца строки) |
| `exclude("pattern")` | Пропускает строку, если захваченное значение содержит паттерн |
| `strip('"')` | Удаляет символ из начала и конца захваченного значения |
| `replace("old","new")` | Заменяет подстроку в захваченном значении |
| `re("pattern")` | Принимает значение, только если оно соответствует regex |
| `ignore` | Захватывает, но игнорирует значение (не включает в результат) |
| `ignore('.*')` | Игнорирует всё до конца строки |
| Modifier | Description |
| --- | --- |
| `ORPHRASE` | Captures a word or phrase to the end of the line. |
| `exclude("pattern")` | Skips the match when the captured value contains the pattern. |
| `strip('"')` | Removes a character from both ends of the captured value. |
| `replace("old","new")` | Replaces text inside the captured value. |
| `re("pattern")` | Accepts the value only if it matches the regex. |
| `ignore` | Captures and discards the value. |
| `ignore('.*')` | Discards the rest of the line. |
| `to_cidr` | Converts a dotted decimal netmask to a prefix length. |
| `unrange("-", ",")` | Expands ranges such as `10-12` using a comma separator. |
| `split(",")` | Splits a captured string into a list. |
### Комментарии в шаблоне
### Template comments
Строки, начинающиеся с `##`, — это комментарии TTP и не влияют на парсинг:
Lines beginning with `##` are TTP comments:
```
```xml
## disabled no comment
add address={{ ip_address | _start_ }}/{{ mask }} interface={{ name }}
add address={{ ip_address | _start_ }}/{{ mask }} interface={{ interface }}
```
---
## Default Variables
## Переменные по умолчанию
Блок `<vars>` позволяет задавать значения по умолчанию для группы через атрибут `default`:
The `<vars>` block can define default values for a group through the group's
`default` attribute:
```xml
<vars>
default_system = {
"model": "",
"serial_number": ""
"serial_number": "",
"version": ""
}
</vars>
@@ -253,17 +247,16 @@ default_system = {
</group>
```
Если шаблон не нашёл совпадений для группы, будет возвращён словарь из `default_system`.
If the group does not match anything, TTP returns the default dictionary.
---
## Full Example
## Практические примеры
### Полный шаблон для нового устройства (пример: Cisco IOS)
This simplified Cisco IOS-style example shows the expected shape of a complete
template:
```xml
<doc>
Шаблон для парсинга Cisco IOS running-config
Cisco IOS running-config parser.
</doc>
<vars>
@@ -283,24 +276,24 @@ System serial number : {{ serial_number }}
<group name="interfaces">
interface {{ interface | _start_ }}
description {{ description | ORPHRASE }}
ip address {{ ip_address }} {{ netmask }}
shutdown {{ shutdown | set("True") }}
ip address {{ ip_address }} {{ mask | to_cidr }}
</group>
<group name="vlans">
vlan {{ id | _start_ }}
name {{ description }}
vlan {{ vlan_id | _start_ }}
name {{ name | ORPHRASE }}
</group>
```
---
## Validation
## Валидация шаблона
`BaseDevice` performs two validation passes:
Фреймворк автоматически выполняет два уровня проверки:
1. Template structure validation checks that the template declares the required
`system` and `interfaces` groups.
2. Parse result validation checks that TTP actually returned the required groups
for the given configuration.
1. **Валидация структуры шаблона** — при создании объекта устройства парсятся XML-теги `<group>` и проверяется наличие обязательных секций (`system`, `interfaces`).
2. **Валидация результата парсинга** — после запуска TTP проверяется, что обязательные группы действительно присутствуют в результате (т.е. конфигурация содержала соответствующие строки).
При нарушении любого условия выбрасывается `ValueError` с подробным описанием проблемы.
After that, parsed data is validated by Pydantic models from
`oxi.interfaces.contract`. Invalid structures raise the original Pydantic
validation error.