Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 48 additions & 12 deletions packages/pyvelo-intent/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -442,6 +442,22 @@ its three keys, with the settings as the profile has them. A patch that raises
leaves the group as it was. `state.effective` shows each value an edge uses and
where it comes from; see "The effective view".

The QoS module works the same way. Its three module-level values
(`serviceRateLimit`, `qoe`, `qosClientConnector`) are stored by the edge or
inherited, and a segment's `cosMapping` is the edge's own when it is stored
with `override` true. A patch on one the edge inherits starts from the
profile's value (or the display default) and stores it whole:
`{"serviceRateLimit": {"enabled": false}}` stores the profile's rate limit with
`enabled` false, and `{"serviceRateLimit": null}` makes the edge inherit again.
`{"segments": {"Voice": {"cosMapping": {"realtime": {"high": {"value": 40}}}}}}`
on an edge that has no `Voice` entry makes the entry from the profile's
segment, with the profile's `cosMapping`, `override` true and that one value
changed; the plan lists the `cosMapping` as your change. The flag is never
patched: a patch naming `override` is refused, and `{"cosMapping": null}`
inherits. A segment's `defaults` belong to the profile: a patch of `defaults`
on an edge is refused (the VCO would add an edge's to the profile's); patch
the profile's state.

## What a save writes

A save sends each changed module's `data` as it was read, with only your
Expand All @@ -465,6 +481,16 @@ What disagrees in the refs as read is a `warning: <message>` line, and the
write leaves it as it is. `ConfigPlan.warnings` holds the same warnings as
data, each with its module's name before its path, and `save` and `dry_run`
copy them to `SaveResult.warnings`.
An edge module that stores an object the VCO uses although its flag says it
inherits (a segment's `cosMapping` with `override` false: the composer takes a
present edge object whatever its flag) has a `flag_off_in_use` warning, at the
object's path, in the same list and in `render()`, also when nothing else in
the module changes; its message gives the patch that inherits
(`{"segments": {"Voice": {"cosMapping": null}}}`) and the one that keeps the
object as stored with its flag turned on (`{"segments": {"Voice":
{"cosMapping": {}}}}`; `localize()` in Python). A patch that names values
inside such an object changes only those values and turns the flag on, so
the edge keeps running with the object `state.effective` showed as the edge's.

A DNS or authentication provider is set by assignment, with the service's
logical ID (`provider.service = uuid.UUID(...)`), or by `apply`, with the
Expand Down Expand Up @@ -594,10 +620,10 @@ firewall: update
- A missing edge firewall or QoS module starts empty. It is inserted once it
differs from that empty layer: patches that cancel out leave nothing to
insert. The insert holds the segment entries the save reconciles and what the
patches made local: a patch on a firewall value the edge would inherit copies
that value from the profile (or the display default) into the insert, as it
does for a module the edge has (see "The patch format"); no other profile
value is copied.
patches made local: a patch on a firewall or QoS value the edge would inherit
copies that value from the profile (or the display default) into the insert,
as it does for a module the edge has (see "The patch format"); no other
profile value is copied.
- A firewall segment has no `outboundOverride` key in the VCO or on the edge. If
an older version of this library wrote one into a module, writing that module
drops it from every segment entry and the plan lists each removal (`-
Expand Down Expand Up @@ -655,8 +681,9 @@ firewall: update

## The effective view

`state.effective.firewall` is what an edge uses, computed on the client from the
edge layer and the profile layer it inherits from. Each value is a `Resolved`
`state.effective.firewall` and `state.effective.qos` are what an edge uses,
computed on the client from the edge layer and the profile layer it inherits
from. Each value is a `Resolved`
with the value itself, its `origin` and its `source`:

| Origin | The value is |
Expand All @@ -676,12 +703,15 @@ stores.
fw = state.effective.firewall
fw.syslog_forwarding.origin # Origin.EDGE, Origin.PROFILE or Origin.FACTORY
fw.syslog_forwarding.value # the value the edge uses

state.effective.qos.service_rate_limit.origin # the same, for QoS
```

The view is the client's reading of rules the VCO applies on its own, so
`pipeline.compare_effective(state)` checks it against the VCO's answer. It reads
the modules the library has converted (`modules=None`, which is the firewall
now; another module raises `ValueError`) with
and QoS; name one with `modules=["QOS"]`, and another module raises
`ValueError`) with
`edge/getEdgeConfigurationModules` for the edge the state was loaded for, and
compares each with `state.effective`, by wire path and by value only, since the
VCO's answer has no origins. Before it compares, it reads the state's profile
Expand All @@ -707,7 +737,7 @@ There are six categories, and three of them are findings:
| `server_only` | the server's answer has a value the view lacks | yes |
| `factory` | the view gives a display default where the server has no value, or the same one | no, information |
| `ignored` | the path is on the ignore list, is a secret, or is a segment the composer left out; reported with its reason | no |
| `unconverted` | the path is not converted yet (`inbound`, `inboundV6`, a segment's `firewall_logging_enabled` and `etm`), so the view has no value to compare | no, information |
| `unconverted` | the path is not converted yet (the firewall's `inbound`, `inboundV6`, a segment's `firewall_logging_enabled` and `etm`, and a QoS segment's `webProxy`), so the view has no value to compare | no, information |

`comparison.findings` is the entries that are findings, and `entries` all of
them. A key is reported once, at the highest path that is absent from a side.
Expand All @@ -717,7 +747,12 @@ and a value it has that differs is `differs`. A list the view builds itself
empty list the server lacks is `client_only`. Segments are matched by
`segmentId` in any order (the view puts the profile's first and the composer
the edge's), and the rules of a segment, edge entries then profile entries, by
position.
position. For QoS the segments' `rules` are compared the same way, and a
segment's `cosMapping` is the edge's stored object even when its `override` flag
is off, because that is the object the composer takes; the module's
`serviceRateLimit`, `qoe` and `qosClientConnector` and a segment's `cosMapping`
are display defaults (`factory`) where neither layer stores one and the server
has none.

The VCO's composer keeps only the segments in use on the edge (an enabled
network with an interface, an enabled routed interface or subinterface, a
Expand All @@ -738,8 +773,8 @@ stores: `urlCategoryFiltering`, `urlReputationFiltering` and `atp_action`. They
are confirmed, not ignored. `compare_effective` reads the enterprise's security
objects (`enterprise/getSecurityObjects` for `securityServiceGroup`,
`urlCategoryFiltering`, `urlReputationFiltering` and `idps`: four reads, with
the state's enterprise ID) only when a rule of a compared module names a group,
and expects:
the state's enterprise ID) only when a rule of the firewall names a group (QoS
rules are not searched), and expects:

- `urlCategoryFiltering` and `urlReputationFiltering`: the `data` of the object
of that type the group names (its `data` holds `{"id": ...}` for each);
Expand Down Expand Up @@ -1437,7 +1472,8 @@ uv run ruff check packages/pyvelo-intent
`packages/pyvelo-intent/tests/test_layer_typing.py` is checked by basedpyright
with `reportUnnecessaryTypeIgnoreComment` on (see pyvelo's "Tests"): it fixes
the layer each `ConfigState` view gives (`state.edge.firewall` is
`FirewallData[Edge]`, `state.profile.firewall` is `FirewallData[Profile]`).
`FirewallData[Edge]`, `state.profile.firewall` is `FirewallData[Profile]`, and
`state.edge.qos` is `QosData[Edge]`).

The live comparison of "The effective view" is
`packages/pyvelo-intent/tests/integration/test_effective_live.py`. It only
Expand Down
20 changes: 15 additions & 5 deletions packages/pyvelo-intent/src/pyvelo_intent/config/effective.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@
- the items of any other list by position;
- a scalar by value, where ``True`` is not ``1``.

The keys the composer adds to a rule that names a security service group are
expected from the enterprise's security objects (``composed_security``) when
``compare_module`` is given them, and compared like the rule's own keys.
The keys the composer adds to a firewall rule that names a security service
group are expected from the enterprise's security objects
(``composed_security``) when ``compare_module`` is given them, and compared like
the rule's own keys.
"""

import json
Expand Down Expand Up @@ -59,6 +60,7 @@
"EffectiveDifference",
"EffectiveIgnore",
"compare_module",
"module_attribute",
]

OMITTED_SEGMENT = (
Expand Down Expand Up @@ -101,13 +103,21 @@
)
"""The categories that say the view and the VCO disagree."""

CONVERTED_MODULES: tuple[str, ...] = ("firewall",)
CONVERTED_MODULES: tuple[str, ...] = ("firewall", "QOS")
"""The modules whose effective view exists: what ``compare_effective`` compares when it is given none."""

UNMODELED_KEYS: Mapping[str, frozenset[str]] = {"firewall": frozenset({"etm"})}
UNMODELED_KEYS: Mapping[str, frozenset[str]] = {
"firewall": frozenset({"etm"}),
"QOS": frozenset(),
}
"""Keys of a module that no model declares, as paths (``[*]`` for any one list item): reported as ``unconverted`` and not as ``server_only``."""


def module_attribute(name: str) -> str:
"""The attribute of ``EffectiveView`` and of the VCO's composed-modules answer that holds the module *name* (a wire name): ``QOS`` is ``qos``, any other is its own."""
return "qos" if name == "QOS" else name


@dataclass(frozen=True)
class EffectiveIgnore:
"""A divergence that is known and understood: its module, the path it applies to, and why.
Expand Down Expand Up @@ -766,11 +776,11 @@
self.emit(path, EffectiveCategory.DIFFERS, client, server, cover=cover)


def _layered_items(inner: object) -> type[Layered[Any]] | None:

Check warning on line 779 in packages/pyvelo-intent/src/pyvelo_intent/config/effective.py

View workflow job for this annotation

GitHub Actions / types

Type `Any` is not allowed (reportExplicitAny)
"""The item class of a ``list[...]`` of ``Layered`` models, else ``None``."""
if get_origin(inner) is not list:
return None
args = get_args(inner)
if args and isinstance(args[0], type) and issubclass(args[0], Layered):
return cast("type[Layered[Any]]", args[0])

Check warning on line 785 in packages/pyvelo-intent/src/pyvelo_intent/config/effective.py

View workflow job for this annotation

GitHub Actions / types

Type `Any` is not allowed (reportExplicitAny)
return None
25 changes: 16 additions & 9 deletions packages/pyvelo-intent/src/pyvelo_intent/config/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
EffectiveComparison,
EffectiveDifference,
compare_module,
module_attribute,
)
from pyvelo_intent.config.hub_calls import (
HubServices,
Expand Down Expand Up @@ -1323,10 +1324,10 @@ async def compare_effective(
entry, and the ones that say the view and the VCO disagree are
``EffectiveComparison.findings``.

When a rule of the view names a security service group, the security
objects of the enterprise (the groups, and the URL category, URL
reputation and IDPS objects they name) are read too, one read for each
type, and the keys the composer adds to that rule are compared with
When a rule of the firewall view names a security service group, the
security objects of the enterprise (the groups, and the URL category,
URL reputation and IDPS objects they name) are read too, one read for
each type, and the keys the composer adds to that rule are compared with
what those objects give: see ``composed_security``.

Raises ``ValueError`` for a profile state (the VCO composes modules
Expand Down Expand Up @@ -1383,7 +1384,8 @@ async def compare_effective(
entries: list[EffectiveDifference] = []
objects: SecurityObjects | None = None
for name in names:
module: object = getattr(composed, name, None)
attribute = module_attribute(name)
module: object = getattr(composed, attribute, None)
data: object = getattr(module, "raw_data", MISSING)
if module is None or module is MISSING:
said = (
Expand All @@ -1407,16 +1409,20 @@ async def compare_effective(
+ "get_edge_configuration_modules to see what the VCO sent",
module=name,
)
module_view = cast("Layered[Effective]", getattr(view, name))
if objects is None and rules_naming_a_group(effective_dump(module_view)[0]):
module_view = cast("Layered[Effective]", getattr(view, attribute))
if (
name == "firewall"
and objects is None
and rules_naming_a_group(effective_dump(module_view)[0])
):
objects = await self._read_security_objects(enterprise_id)
entries.extend(
compare_module(
name,
module_view,
cast("dict[str, Any]", data),
ignores=EFFECTIVE_IGNORES,
security_objects=objects,
security_objects=objects if name == "firewall" else None,
)
)
return EffectiveComparison(tuple(entries))
Expand Down Expand Up @@ -1921,7 +1927,8 @@ def edit(copies: Mapping[str, AnyStoredModule]) -> None:

type _WritableModule = (
DeviceSettingsConfigurationModule
| QosConfigurationModule
| QosConfigurationModule[Edge]
| QosConfigurationModule[Profile]
| WanConfigurationModule
| FirewallConfigurationModule[Edge]
| FirewallConfigurationModule[Profile]
Expand Down
44 changes: 30 additions & 14 deletions packages/pyvelo-intent/src/pyvelo_intent/config/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
from pyvelo.config.resolver import ResolverContext, ResolverRegistry
from pyvelo.config.resolvers.hub import HubResolver
from pyvelo.config.validation import ValidationError
from pyvelo.core import ConfigContext, VcoModel
from pyvelo.core import ConfigContext, Layered, VcoModel
from pyvelo.core.base import is_dict, is_list
from pyvelo.core.effective import effective_view
from pyvelo.core.identity import (
Expand Down Expand Up @@ -289,7 +289,7 @@ def firewall(self) -> FirewallData[X]:
return cast(FirewallData[X], module.data) # the module is of this layer

@property
def qos(self) -> QosData:
def qos(self) -> QosData[X]:
"""The QoS data; an edge layer that has none starts it empty."""
module = _module_of(
self._config,
Expand All @@ -298,7 +298,7 @@ def qos(self) -> QosData:
profile=self._profile,
)
assert isinstance(module, QosConfigurationModule)
return module.data
return cast(QosData[X], module.data) # the module is of this layer

@property
def device_settings(self) -> DeviceSettingsData:
Expand Down Expand Up @@ -334,23 +334,39 @@ def __init__(
@property
def firewall(self) -> FirewallData[Effective]:
"""The firewall's effective data: the edge's local values over the profile's, then the display defaults."""
name = ConfigurationModuleName.FIREWALL
return self._view(
ConfigurationModuleName.FIREWALL,
FirewallData[Profile],
FirewallData[Effective],
)

@property
def qos(self) -> QosData[Effective]:
"""The QoS effective data: the edge's local values over the profile's, then the display defaults."""
return self._view(
ConfigurationModuleName.QOS, QosData[Profile], QosData[Effective]
)

def _view[M: Layered[Effective]](
self,
name: ConfigurationModuleName,
profile_class: type[Layered[Profile]],
effective_class: type[M],
) -> M:
"""The module *name* at the effective layer; neither layer's module is created.

A profile that has no such module is *profile_class* with no segments.
"""
edge_module = _find_module(self._edge, name)
profile_module = _find_module(self._profile, name)
edge_data = None
if edge_module is not None:
assert isinstance(edge_module, FirewallConfigurationModule)
edge_data = edge_module.data
edge_data = cast(Layered[Edge], cast(object, edge_module.data))
if profile_module is None:
profile_data = FirewallData[Profile].model_validate({"segments": []})
profile_data = profile_class.model_validate({"segments": []})
else:
assert isinstance(profile_module, FirewallConfigurationModule)
profile_data = profile_module.data
return effective_view(
cast("FirewallData[Edge] | None", edge_data),
cast("FirewallData[Profile]", profile_data),
FirewallData[Effective],
)
profile_data = cast(Layered[Profile], cast(object, profile_module.data))
return effective_view(edge_data, profile_data, effective_class)


type _Place = tuple[str | int, ...]
Expand Down
9 changes: 5 additions & 4 deletions packages/pyvelo-intent/tests/test_assign_segment.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import copy
import uuid
from collections.abc import Mapping
from typing import Any
from typing import Any, cast

import pytest
from profile_state import ( # pyright: ignore[reportImplicitRelativeImport]
Expand All @@ -27,6 +27,7 @@
)
from pyvelo.config.resolver import ResolverRegistry
from pyvelo.core.identity import ResolutionError
from pyvelo.core.layers import Profile
from pyvelo_intent.config.pipeline import ConfigPipeline
from pyvelo_intent.config.profile_segments import (
apply_assignment,
Expand Down Expand Up @@ -247,7 +248,7 @@ async def test_a_profile_without_qos_raises():
assert isinstance(qos, QosConfigurationModule)
modules = state.profile_config.modules
assert isinstance(modules, list)
modules.remove(qos)
modules.remove(cast(QosConfigurationModule[Profile], qos)) # the profile layer
pipeline, _ = module_store_pipeline(state)

with pytest.raises(ValueError, match="QOS"):
Expand Down Expand Up @@ -405,8 +406,8 @@ async def test_assign_holds_the_lock():

async def test_a_module_not_at_the_profile_level_raises_naming_the_fix():
state = await global_only()
qos = state.module(QOS)
qos._config_context = None # pyright: ignore[reportPrivateUsage]
ds = state.module(DS)
ds._config_context = None # pyright: ignore[reportPrivateUsage]

with pytest.raises(ValueError, match=r"load_profile.*for_profile"):
_ = segment_modules(state)
Expand Down
Loading
Loading