avi Module

Inmanta adapter for the AVI / VMware NSX Advanced Load Balancer controller, built on top of restbase.

The DSL model - the resource entities and their attributes - is generated from the controller’s own API schema, so an entity carries every field AVI documents for that object type. Only a thin layer is hand written: the session client, the registration token plugin and the CRUD handler. Of the model, only model/base.cf (the credentials and the base resource) is. Objects are read by name and created, updated and deleted by uuid; an update overlays the fields the model sets on the object currently on the controller, so fields nobody manages are left alone.

Scope

Feature

Entity / plugin

Tenant

avi::Tenant

Service engine group

avi::ServiceEngineGroup

Virtual service VIP

avi::VsVip

Virtual service (L4, SSL/TLS, HTTP, EVH/SNI, DNS)

avi::VirtualService

Pool, health monitor, analytics profile

avi::Pool, avi::HealthMonitor, avi::AnalyticsProfile

VRF context (route domain), BGP peers, static routes

avi::VrfContext

One BGP peer / static route of a VRF context

avi::vrf_context::BgpPeer / avi::vrf_context::StaticRoute

Service engine registration token

avi::create_token_reference (a Reference[str]) / avi::generate_token

Service engine (wait for / SE group / remove)

avi::service_engine::ServiceEngine

Service engine data interface (VRF context)

avi::service_engine::Interface

Service engine image (download)

avi::se_image::ServiceEngineImage

GSLB service (on the GSLB leader)

avi::GslbService

GSLB pool member lookups (site, virtual service)

avi::create_gslb_site_uuid_reference, avi::create_virtual_service_uuid_reference, avi::create_virtual_service_address_reference

Configuration

The model reads no environment variables. Everything a resource needs comes from the avi::base::Credentials instance it is given: the controller URL, the credentials, the API version and the default tenant. The agent a resource is deployed on is derived from the controller host, so no std::AgentConfig is required. (AVI_URL is only used when regenerating the model, see below.)

Every resource is scoped to a tenant through tenant_scope (default admin). To manage an object inside another tenant, set it and add a requires on the avi::Tenant, which orders the two.

Example

import avi
import avi::base
import avi::service_engine
import avi::tenant::definitions
import avi::vrf_context
import avi::vrf_context::bgp_peer::definitions
import avi::vrf_context::definitions
import avi::vrf_context::static_route::definitions
import avi::vs_vip::definitions

credentials = avi::base::Credentials(
    host="https://172.25.223.252",
    username="admin",
    password="secret",
)

tenant = avi::Tenant(
    credentials=credentials,
    name="my-tenant",
    local=true,
    # Give the tenant its own routing domain, so it can hold VRF contexts.
    config_settings=avi::tenant::definitions::TenantConfiguration(tenant_vrf=true),
)

seg = avi::ServiceEngineGroup(
    credentials=credentials,
    name="my-seg",
    tenant_scope="my-tenant",   # X-Avi-Tenant scope for this object
    max_se=4,
    min_scaleout_per_vs=2,
    ha_mode="HA_MODE_SHARED_PAIR",
    requires=[tenant],          # the group is created after the tenant
)

# Nested objects (here the vip list and its address) are generated entities too.
avi::VsVip(
    credentials=credentials,
    name="my-vip",
    tenant_scope="my-tenant",
    vip=[avi::vs_vip::definitions::Vip(
        vip_id="1",
        enabled=true,
        ip_address=avi::vs_vip::definitions::IpAddr(addr="42.42.42.42", type="V4"),
    )],
    requires=[tenant],
)

avi::VrfContext(
    credentials=credentials,
    name="my-vrf",
    tenant_scope="my-tenant",
    cloud="Default-Cloud",
    bgp_profile=avi::vrf_context::definitions::BgpProfile(
        ibgp=false,             # eBGP
        local_as=64979,
        num_as_path_prepend=2,
        community=["64979:19200", "64979:20"],
        send_community=true,
        # One peer per anchor leaf of the ACI floating l3out.
        peers=[avi::vrf_context::definitions::BgpPeer(
            peer_ip=avi::vrf_context::definitions::IpAddr(
                addr="10.1.1.3", type="V4"),
            subnet=avi::vrf_context::definitions::IpAddrPrefix(
                ip_addr=avi::vrf_context::definitions::IpAddr(
                    addr="10.1.1.0", type="V4"),
                mask=29,
            ),
            remote_as=65001,
            md5_secret="s3cr3t",
            advertise_vip=true,
            label="aci",        # the routing options to apply to this peer
        )],
        # What the peers carrying that label learn and advertise. The four
        # booleans form two pairs that can not be mixed (see below).
        routing_options=[avi::vrf_context::definitions::BgpRoutingOptions(
            label="aci",
            learn_routes=true,
            advertise_default_route=true,
            max_learn_limit=100,
        )],
    ),
    requires=[tenant],
)

# The same route domain with its peers and routes as resources of their own, one
# per connectivity, so each can sit in the resource set of the service adding it.
# The VRF context then leaves those lists alone (and refuses to set them).
other_vrf = avi::VrfContext(
    credentials=credentials,
    name="my-other-vrf",
    tenant_scope="my-tenant",
    cloud="Default-Cloud",
    bgp_profile=avi::vrf_context::definitions::BgpProfile(ibgp=false, local_as=64979),
    manage_bgp_peers=false,
    manage_static_routes=false,
    requires=[tenant],
)
avi::vrf_context::BgpPeer(
    credentials=credentials,
    name="leaf-101",            # identifies the resource; peer_ip the peer on AVI
    vrf_context="my-other-vrf", # the VRF context, found the way it finds itself
    tenant_scope="my-tenant",
    cloud="Default-Cloud",
    peer_ip=avi::vrf_context::bgp_peer::definitions::IpAddr(
        addr="10.1.1.3", type="V4"),
    remote_as=65001,
    requires=[other_vrf],
)
avi::vrf_context::StaticRoute(
    credentials=credentials,
    route_id="my-connectivity-1",  # identifies the route, in the model and on AVI
    vrf_context="my-other-vrf",
    tenant_scope="my-tenant",
    cloud="Default-Cloud",
    prefix=avi::vrf_context::static_route::definitions::IpAddrPrefix(
        ip_addr=avi::vrf_context::static_route::definitions::IpAddr(
            addr="192.168.50.0", type="V4"),
        mask=24,
    ),
    next_hop=avi::vrf_context::static_route::definitions::IpAddr(
        addr="10.1.1.1", type="V4"),
    requires=[other_vrf],
)

# The engine, moved into the service engine group of its service - the last step
# of the load balancer creation. It registers itself with the token it booted
# with, and is licensed a while after that; the controller refuses to move an
# engine it did not license yet.
engine = avi::service_engine::ServiceEngine(
    credentials=credentials,
    name="my-engine",           # identifies the resource
    engine_name="10.0.37.27",   # the engine as the controller names it
    tenant_scope="my-tenant",
    cloud="Default-Cloud",
    se_group_ref="/api/serviceenginegroup?name=my-seg",
    requires=[tenant, seg, licensed],  # the group it is moved into has to exist
)

# A waiter holds back what requires it until the engine is there and licensed:
# it is skipped until then, saying why. It finds the engine the way the engine
# resource does - endpoint, name, tenant, cloud, credentials - but does not
# require it: the engine requires the waiter.
licensed = avi::waiter::Waiter(
    resource=engine,
    name="licensed",            # identifies the waiter, per resource
    conditions={"license_state": "LICENSE_STATE_LICENSED"},
)

# The data interface the cloud attached to a service engine, in that VRF. Only
# the mac address of the port identifies it; it shows up on the controller a
# while after the port was attached, which is what the waiter waits for. The
# object a waiter on an interface checks is its engine.
interface = avi::service_engine::Interface(
    credentials=credentials,
    engine="10.0.37.27",        # the engine as the controller names it
    tenant_scope="my-tenant",
    cloud="Default-Cloud",
    name="my-data-port",        # identifies the interface on that engine
    mac_address="fa:16:3e:cd:ad:e3",
    vrf="my-vrf",               # null puts it back in "my-tenant-default"
    requires=[discovered],
)
discovered = avi::waiter::Waiter(
    resource=interface,
    name="discovered",
    conditions={"data_vnics[mac_address=fa:16:3e:cd:ad:e3]": null},
    requires=[licensed],        # an unlicensed engine reports no interfaces
)

Things worth knowing per resource

  • avi::Tenant takes the service engines registered in it along when it is purged. The controller refuses to delete a tenant anything still refers to (400 Cannot delete Tenant ... is referred by:  <engine>), and an engine is not created through the API - it registers itself into the tenant whose token it was given - so nothing guarantees the model holds one for every engine that ended up there. Purge the objects the model does hold before the tenant all the same: only the engines are cleaned up here.

  • avi::VrfContext is scoped to a cloud, not only to a tenant: every cloud has VRF contexts of its own and names only have to be unique within one, so cloud is mandatory and part of the resource identity. The tenant needs config_settings.tenant_vrf set, otherwise the controller refuses the write. Purge a VRF after everything that references it (a VIP’s vrf_context_ref, a service engine’s data vnics) and before its tenant. Its bgp_profile.peers, its bgp_profile.routing_options and its static_routes are what a connectivity adds to a route domain: a peer is identified by peer_ip/peer_ip6, a routing options object by its label and a route by route_id, so all three can be added and removed one at a time without rewriting the rest. A peer’s md5_secret is written but never read back (the controller answers "<sensitive>"), so it is not compared: a secret that changes and nothing else is only written along with the next change to the VRF. A peer’s label picks the routing options that apply to it. Those four booleans form two pairs that can not be mixed: learn_routes goes with advertise_default_route, and learn_only_default_route with advertise_learned_routes. The controller refuses any other combination with 400 "<one> cannot be enabled with <other>", and it holds max_learn_limit to the 50-250 range.

    Known limitation: taking the last item of a managed list away does not clear it on the controller, and neither does dropping the bgp_profile instance: an empty relation is left out of the desired state altogether, so no change is detected, no request is sent and the resource reports success. Adding, changing and removing items while at least one remains is correct, as is creating a VRF with or without BGP; only the transition to nothing is not.

    Set manage_bgp_peers=false (manage_static_routes=false) to manage the peers (routes) with the resources below instead: the VRF context then neither compares nor writes that list - an update writes back what the controller has in it - and setting it in the model fails the export.

  • avi::vrf_context::BgpPeer and avi::vrf_context::StaticRoute are one item of those lists, as a resource of their own: what a connectivity adds to a route domain, in that connectivity’s own resource set. They find their VRF context the way it finds itself (vrf_context is its name, plus cloud, tenant_scope and credentials). The controller has no endpoint for an item, so a deploy re-reads the whole VRF context, adds the item or updates the one with the same peer_ip/peer_ip6 (route_id), and writes it back; a purge takes it out. These writes, and an update of the VRF context, take turns on one agent (a lock per VRF context), so they do not drop each other’s change. In the model a peer is identified by name - its address is a nested object, which can not be part of an index - and a route by route_id; give each peer address one resource only. Only the fields the model sets are compared, and a peer’s md5_secret not at all (see above). An item of a VRF context that is not there is skipped until it is, a peer of a VRF context without a bgp_profile fails (configure BGP on the VRF context, the peer does not invent it), and an item whose VRF context is gone counts as purged. Their nested types are in avi::vrf_context::bgp_peer::definitions and avi::vrf_context::static_route::definitions, not in the VRF context’s own definitions. A waiter on an item checks its VRF context.

  • avi::service_engine::ServiceEngine is not created through the API: the engine VM boots with a single use token and registers itself. The resource covers the two ends of that lifecycle, driven by purged - it is skipped until the engine registered, or it removes the engine from the controller. Put an avi::waiter::Waiter in front of it to wait for the engine to register, and to be licensed before anything is written to it. Order it after its VM in both directions, and before the service engine group it sits in: removing it is skipped while the engine is still connected, i.e. until the controller noticed its VM is gone (see Removing a service engine). In between, the attributes the model sets on the engine are written to it, and se_group_ref is the one the load balancer creation needs: an engine registers into the default group of its cloud, and its own group is the last step. Point at that group the way a model points at any AVI object, by name (se_group_ref="/api/serviceenginegroup?name=my-seg"); the controller resolves it in the cloud the engine registered into and refuses a group that is not there, which is the scoping a group name needs - it is only unique within a cloud. Moving an engine between groups makes the controller deactivate and reactivate it, so it refuses to move an unlicensed engine (400 "Cannot perform deactivate/activate operation since SE is not licensed."): require a waiter on license_state (see the example above). An engine that registered where the model wants it is not written to, so it needs no license. The engine is replaced as a whole on a write, so attributes nobody sets are left alone, and its name, its interfaces (data_vnics/mgmt_vnic, which have avi::service_engine::Interface resources of their own) and its resources are never written.

  • avi::service_engine::Interface is one data interface of an engine, found by its mac_address, and the VRF context it belongs to. It is not created either - the cloud attaches a port to the engine’s VM and the controller discovers the interface - so the resource is skipped until it shows up (a waiter on data_vnics[mac_address=...] waits for it) and then configures it. vrf names the VRF context, looked up in the cloud the engine registered into; leaving it null (or purging the resource) puts the interface back in the tenant’s default VRF <tenant_scope>-default, which is where the controller puts a newly discovered one. The interface is a member of its engine, so writing it replaces the whole engine object: interfaces of one engine are written one at a time, and everything else on it is left alone.

  • avi::waiter::Waiter is a condition on the object of another resource (resource), not an object itself: it looks the object up the way that resource does - endpoint, name (which may be a reference), tenant, cloud and credentials; for an interface, its engine - and the object has to satisfy every one of conditions - a path in the object (license_state, data_vnics[mac_address=...], a.b.c) mapped to the value it must have, null meaning it only has to be there. A path with a wildcard (data_vnics[mac_address=*].mac_address) holds when any value it selects does, which is how a reference - a mac address that is a fact of a port - is matched in a list: a dict key can not be a reference. The paths and literal values are checked against the controller’s schema of the object when the model is exported, so a typo (licence_state) fails the compile rather than skipping forever. A dry run reports what is not met yet; a deploy checks once and is then skipped - the agent deploys it again later - or failed with skip_if_not_found=false, so what requires it is held back and the waiter says why. It never sleeps, so it never holds an agent slot; skip_if_not_found may be a reference, which is how it gives up after a while. Once met it reports the uuid/url of the object as facts. A purged waiter waits for nothing. An object that is not there meets its conditions when the resource the waiter is linked to is purged, and does not otherwise: on its way in the object is not there yet, on its way out it is already gone - an engine to disconnect before it is deleted must not hold back what requires it once it is gone, or when it never showed up. On its way out, the name an object is looked up with may no longer identify it - an engine’s is commonly a fact of a VM that is gone by then - so when no lookup finds it, the waiter looks it up once more by the uuid its resource reported as a fact while it was there, the way the engine resource does.

  • avi::se_image::ServiceEngineImage is a file the controller serves, not an API object. It downloads the image (1.8 GB) onto the agent for whatever uploads it to the hypervisor, re-downloads it when the controller serves another one, and resumes an interrupted download.

  • avi::GslbService is only ever written to on the GSLB leader, which replicates it to the other sites; the credentials it is given are the leader’s. Its domain_names have to fall within a subdomain of the GSLB configuration: the controller refuses any other one (400 "FQDN:<name> ... does not match with GLB dns_configs"). A pool member that is a virtual service names it by the cluster_uuid of its site and its vs_uuid there, and has to carry the address of its VIP as ip - the controller refuses the member without one. A model knows none of the three, so each is a reference resolved on the agent:

    avi::gslb_service::definitions::GslbPoolMember(
        ratio=1,
        cluster_uuid=avi::create_gslb_site_uuid_reference(credentials, "dc2"),
        vs_uuid=avi::create_virtual_service_uuid_reference(credentials, "dc2", "my-tenant", "app1"),
        ip=avi::gslb_service::definitions::IpAddr(
            addr=avi::create_virtual_service_address_reference(credentials, "dc2", "my-tenant", "app1"),
            type="V4",
        ),
    )
    

    The virtual service is looked up through the leader, even on another site: the leader forwards the request (header X-Avi-Internal-GSLB: <site cluster_uuid>, which is what its own UI sends) with the credentials the site was registered with, so that user needs access to the tenant of the virtual service on the site. That header is undocumented, and it has only been validated against the leader’s own site: the lookup on another site is unverified (solutions/modules/avi#6). A virtual service is only looked up on an AVI site, never on a third party one. A member is matched with its peer on the controller by site and virtual service, by its fqdn for an fqdn member (the controller overwrites the ip of such a member each time it resolves the fqdn), or by its ip; the fields the controller fills in on it are left alone.

  • avi::VirtualService, avi::Pool, avi::HealthMonitor and avi::AnalyticsProfile are what a load balancer service is made of, next to its avi::VsVip. They point at each other - and at what the controller already has: profiles, certificates, policies, datascripts - by name, through the generated *_ref attributes, which a diff compares by the name of what they point at:

    import avi::pool::definitions as pool
    import avi::virtual_service::definitions as vs
    
    monitor = avi::HealthMonitor(
        credentials=credentials,
        tenant_scope="my-tenant",
        name="app1-hm",
        type="HEALTH_MONITOR_TCP",
        requires=[tenant],
    )
    servers = avi::Pool(
        credentials=credentials,
        tenant_scope="my-tenant",
        name="app1-pool",
        cloud_ref="/api/cloud?name=Default-Cloud",
        vrf_ref="/api/vrfcontext?name=my-vrf",
        default_server_port=8080,
        health_monitor_refs=["/api/healthmonitor?name=app1-hm"],
        servers=[pool::Server(ip=pool::IpAddr(addr="10.0.0.1", type="V4"))],
        requires=[tenant, monitor],
    )
    avi::VirtualService(
        credentials=credentials,
        tenant_scope="my-tenant",
        name="app1",
        cloud_ref="/api/cloud?name=Default-Cloud",
        vrf_context_ref="/api/vrfcontext?name=my-vrf",
        se_group_ref="/api/serviceenginegroup?name=my-group",
        vsvip_ref="/api/vsvip?name=app1-vip",
        pool_ref="/api/pool?name=app1-pool",
        application_profile_ref="/api/applicationprofile?name=System-L4-Application",
        network_profile_ref="/api/networkprofile?name=System-TCP-Proxy",
        services=[vs::Service(port=80), vs::Service(port=1000, port_range_end=1010)],
        requires=[tenant, vip, servers],
    )
    

    A name based vrf_ref/vrf_context_ref is resolved by the controller in the cloud of the object, so set cloud_ref along with it: a VRF name alone is usually not unique, every cloud has a global one. The controller refuses to delete a VIP, pool or health monitor a virtual service still points at (403 Cannot delete, object is referred by: [...]), and a health monitor its pool points at: purge the virtual service first. A purged health monitor still needs its type (a required attribute). The authentication of a health monitor is written but never read back ("<sensitive>"), like a BGP peer’s secret. The items of the lists a load balancer service sets are matched with their peer on the controller, so adding or removing one does not rewrite the others: a service port by port, port_range_end and override_network_profile_ref (two ports 53, one of them over TCP, are two services), a pool member by ip and port, a static DNS record by fqdn and type and its data by its value, an EVH host by host and its rules by name, datascripts, HTTP and DNS policies by index. The controller fills in the end of a single port range (the port itself) and the target of a SRV record (default.host) when the model leaves them out; the body sent has them filled in the same way.

  • avi::create_token_reference yields a registration token as a Reference[str] resolved on the agent, to feed to an SE VM as its AVICNTRL_AUTHTOKEN metadata. Tokens are single use and expire after an hour, so they are generated at deploy time rather than at compile time.

Removing a service engine

The order matters for the license, not only for the controller’s references. An engine consumes a service core of the license per vCPU, and the controller gives those back when it deletes the engine. An engine that disappears any other way - with the tenant it is in, or a VM deleted behind the controller’s back and never removed - can keep its cores booked for good: on the lab, an engine deleted along with its tenant kept both cores of the license for days, until the controller was rebooted. Remove an engine in this order:

  1. Delete its VM in the cloud. An engine whose VM still runs registers itself again.

  2. Wait for the controller to notice: se_connected drops to false some time after the VM is gone. In a cloud the controller has no access to, it refuses to delete a connected engine (400 Service Engine connected to controller cannot be deleted with no access mode).

  3. Delete the engine on the controller - this is what releases its cores.

  4. Only then delete its service engine group and its tenant.

In a model, that is avi::service_engine::ServiceEngine with purged=true, required by the engine’s group and tenant and requiring the VM’s purge: it is skipped while the engine is still connected, and the agent deploys it again until it can delete it. A waiter can make step 2 show on its own, between the VM’s purge and the engine’s:

disconnected = avi::waiter::Waiter(
    resource=engine,
    name="disconnected",
    conditions={"se_connected": false},
    # Only on the way out: a live engine is connected. A purged waiter waits for
    # nothing.
    purged=not engine.purged,
    requires=[vm],
)
engine.requires += disconnected

Since engine is purged, an engine that never registered, or is already gone, meets the waiter’s conditions: it has nothing to disconnect. avi::Tenant deletes the engines left in it one by one, after waiting for them to disconnect, before it deletes itself - it never relies on the tenant taking its engines along.

To check for cores booked to engines that are gone, compare se_infos in GET /api/licensing/ledger/details with the engines that exist (show license ledger details on the controller’s CLI). Broadcom documents GET /api/licensing/ledger/clear/reservation to release them (KB 381957), but on 31.2.2 it only clears reservations: the cores of an engine deleted with its tenant were only given back by rebooting the controller (sudo reboot over ssh - the UI has no button for it), which keeps the license.

Regenerating the model from the controller

The entities under model/ and the cached schemas under files/schemas/ are generated. To refresh them against a controller:

pip install -e .[generator]
AVI_URL=https://172.25.223.252 make generate

This fetches the swagger document of each managed object type from <AVI_URL>/swagger/<ObjectType>.json (one document per type - the controller exposes no combined schema), caches it under files/schemas/ and rewrites the generated .cf files in place. Which object types those are is decided by the @generated_avi_resource classes in inmanta_plugins/avi/resources.py.

The same run emits the entities no swagger describes - how an object is found on the controller and how long it is waited for, the cloud a VRF context lives in, and the service engine image, which is a file rather than an API object. Those are declared with the same module factory in the last section of resources.py, so model/base.cf is the only model file that is not generated.

Running tests

pip install -e . -c requirements.txt -r requirements.dev.txt

pytest -m "not integration" tests   # offline
pytest -m integration tests         # live, against a controller

There is one test file per resource, each with offline tests and one live test_integration. The integration tests need the controller connection parameters, through environment variables or pytest arguments (see tests/conftest.py); CI provides them through .ci-integration-tests.yml.