Pular para conteúdo

Criando um plugin de coleta

Este guia cria, passo a passo, um plugin para um fabricante fictício (ACME Array, REST). O código e o teste abaixo foram executados contra o pacote quantix da v1.0.0 (o teste passa). Leia antes Coleta (contrato e convenções) e o backend/quantix/collector/plugins/README.md (exemplos reais por fabricante).

1. Planeje o mapeamento

Pergunta No exemplo
Interface, porta, autenticação REST HTTPS 443; POST /api/v1/session com Basic → X-Auth-Token
Hierarquia (tipos do catálogo) storage_system > pool > volume; storage_system > host > initiator
Relações volume -maps_to-> host; host -has_initiator-> initiator (contains é criada automaticamente pelo parent)
Identificadores de correlação WWPN do iniciador (inv.wwpn), NAA do volume (inv.naa)
Métricas e unidades contadores cumulativos de I/O → ctx.rate (IO/s, bytes/s → MB/s); latência µs → ms; capacidade em bytes
IDs nativos estáveis serial do sistema, id de pool/volume/host, WWPN do iniciador

2. Implemente o módulo

backend/quantix/collector/plugins/acme_array.py:

"""ACME Array (exemplo) via REST.

Interface
---------
HTTPS (443). ``POST /api/v1/session`` com Basic devolve ``{"token": ...}``, enviado depois em
``X-Auth-Token``.

Endpoints usados
----------------
``/api/v1/system``, ``/api/v1/pools``, ``/api/v1/volumes``, ``/api/v1/hosts``,
``/api/v1/metrics/volumes`` (contadores cumulativos de I/O).

Validação: exemplo da documentação; não corresponde a um produto real.
"""
from __future__ import annotations

import time
from typing import Any

from ._util import capacity_metrics, io_metrics
from .base import (
    CollectorPlugin,
    Inventory,
    PerfBatch,
    RestClient,
    TestResult,
    to_float,
)


class AcmeArrayPlugin(CollectorPlugin):
    key = "acme_array"
    vendor = "ACME"
    product = "ACME Array"
    category = "storage"
    interface = "rest"
    default_port = 443
    description = "ACME Array via REST (sistema, pools, volumes, hosts e performance por volume)."
    credential_kinds = ["userpass"]
    min_perf_interval_s = 60
    option_fields = [
        {"name": "volume_perf", "label": "Coletar performance por volume", "type": "bool", "default": True},
    ]
    requirements = "Usuário do ACME Manager com papel 'monitor' (somente leitura)."

    async def _client(self) -> RestClient:
        c = RestClient(self.ctx, self.ctx.base_url(self.default_port))
        r = await c.post("/api/v1/session", auth=(self.ctx.username, self.ctx.password))
        c.client.headers["X-Auth-Token"] = r["token"]
        return c

    async def test_connection(self) -> TestResult:
        async with await self._client() as c:
            s = await c.get("/api/v1/system")
        return TestResult(True, f"Conectado a {s['name']}", vendor=self.vendor, model=s.get("model"),
                          serial=s.get("serial"), firmware=s.get("version"))

    async def collect_inventory(self) -> Inventory:
        inv = Inventory()
        async with await self._client() as c:
            s = await c.get("/api/v1/system")
            pools = await c.get("/api/v1/pools")
            vols = await c.get("/api/v1/volumes")
            hosts = await c.get("/api/v1/hosts")
        sid = s["serial"]
        inv.device_info = {"vendor": self.vendor, "model": s.get("model"), "serial": sid, "firmware": s.get("version")}
        inv.add("storage_system", sid, s["name"], model=s.get("model"), media="flash",
                capacity_bytes=to_float(s.get("capacity_bytes")))
        for p in pools:
            inv.add("pool", p["id"], p["name"], ("storage_system", sid), capacity_bytes=to_float(p.get("total_bytes")))
        for h in hosts:
            inv.add("host", h["id"], h["name"], ("storage_system", sid))
            for w in h.get("wwpns", []):
                ini = inv.add("initiator", w, w, ("host", h["id"]), protocol="fc")
                inv.wwpn(ini, w)                                  # correlação com a SAN
                inv.relate(("host", h["id"]), ("initiator", w), "has_initiator")
        for v in vols:
            rec = inv.add("volume", v["id"], v["name"], ("pool", v["pool_id"]), size_bytes=to_float(v.get("size_bytes")))
            inv.naa(rec, v.get("wwn"))                            # correlação com datastores
            for hid in v.get("mapped_hosts", []):
                inv.relate(("volume", v["id"]), ("host", hid), "maps_to")
        return inv

    async def collect_performance(self, ts: float | None = None) -> PerfBatch:
        ts = ts or time.time()
        b = PerfBatch(ts)
        async with await self._client() as c:
            s = await c.get("/api/v1/system")
            pools = await c.get("/api/v1/pools")
            stats: list[dict[str, Any]] = await c.get("/api/v1/metrics/volumes") if self.ctx.options.get("volume_perf", True) else []
        sid = s["serial"]
        b.add_many("storage_system", sid, capacity_metrics(to_float(s.get("capacity_bytes")), used=to_float(s.get("used_bytes"))))
        for p in pools:
            b.add_many("pool", p["id"], capacity_metrics(to_float(p.get("total_bytes")), used=to_float(p.get("used_bytes"))))
        for st in stats:
            k = f"acme:{st['volume_id']}"
            r_iops = self.ctx.rate(f"{k}:r", to_float(st.get("reads")), ts)          # contador → taxa/s
            w_iops = self.ctx.rate(f"{k}:w", to_float(st.get("writes")), ts)
            r_bps = self.ctx.rate(f"{k}:rb", to_float(st.get("read_bytes")), ts)
            w_bps = self.ctx.rate(f"{k}:wb", to_float(st.get("write_bytes")), ts)
            b.add_many("volume", st["volume_id"], io_metrics(
                r_iops=r_iops, w_iops=w_iops,
                r_mbps=r_bps / 1e6 if r_bps is not None else None, w_mbps=w_bps / 1e6 if w_bps is not None else None,
                r_lat=to_float(st.get("read_latency_us")) / 1000 if st.get("read_latency_us") is not None else None,
                w_lat=to_float(st.get("write_latency_us")) / 1000 if st.get("write_latency_us") is not None else None))
        return b

Pontos de atenção:

  • RestClient já faz retry (2× em 5xx e erros de conexão), timeout (collection.request_timeout_s), verify conforme o cadastro e converte 401/403 em AuthError com mensagem para a GUI. Use sempre async with para fechar as conexões (e faça logout se a API tiver sessão).
  • ctx.rate / ctx.delta guardam o contador anterior em ctx.state (mantido pelo coletor entre ciclos). No 1º ciclo devolvem None, que o PerfBatch ignora.
  • Utilitários de _util.py: io_metrics() (deriva totais, latência ponderada e tamanho de I/O), capacity_metrics() (deriva livre/usado/% e aceita provisioned e drr), optional() (endpoint opcional sem abortar o ciclo), gather_limited() (concorrência limitada ao array), dig(), pick(), fnum(), conversões (usec_to_ms, bytes_to_mb…).
  • Atributos úteis para a engine: media (flash/hybrid) e model no storage_system (thresholds de latência e modelo de capacidade), max_iops/max_mbps/controllers se o fabricante informar, speed_gbps em portas (utilização), role em portas (frontend) e em volumes de réplica (replica/target/snapshot, para não contarem como órfãos).
  • Para SSH, use SSHClient e parse_delimited() de base.py. Para SDKs bloqueantes, use asyncio.to_thread.

3. Registre o plugin

Inclua o nome do módulo em _MODULES em backend/quantix/collector/plugins/__init__.py. A GUI passa a oferecer o plugin no assistente de dispositivos (cartão, opções e requisitos vêm de describe()), e docs/gen_reference.py o inclui em Plataformas suportadas.

4. Teste com respostas gravadas (respx)

backend/tests/plugins/test_acme_array.py:

from __future__ import annotations

import pytest
import respx

from quantix.collector.plugins.acme_array import AcmeArrayPlugin

from .conftest import assert_catalog, base, count, make_ctx, metrics_of

W = "10:00:00:00:c9:aa:bb:01"


def mock_api(m: respx.MockRouter, reads: int) -> None:
    m.post("/api/v1/session").respond(json={"token": "T"})
    m.get("/api/v1/system").respond(json={"name": "acme-01", "serial": "AC123", "model": "ACME 9000",
                                          "version": "5.2", "capacity_bytes": 100e12, "used_bytes": 40e12})
    m.get("/api/v1/pools").respond(json=[{"id": "p1", "name": "Pool1", "total_bytes": 80e12, "used_bytes": 20e12}])
    m.get("/api/v1/hosts").respond(json=[{"id": "h1", "name": "esx01", "wwpns": [W]}])
    m.get("/api/v1/volumes").respond(json=[{"id": "v1", "name": "vol01", "pool_id": "p1", "size_bytes": 1e12,
                                            "wwn": "naa.6000acme0000000000000000000000a1", "mapped_hosts": ["h1"]}])
    m.get("/api/v1/metrics/volumes").respond(json=[{"volume_id": "v1", "reads": reads, "writes": 0, "read_bytes": reads * 8192,
                                                    "write_bytes": 0, "read_latency_us": 500, "write_latency_us": 800}])


@pytest.mark.asyncio
async def test_acme_array():
    p = AcmeArrayPlugin(make_ctx("acme_array"))
    with respx.mock(base_url=base(443), assert_all_called=False) as m:
        mock_api(m, reads=1000)
        tr = await p.test_connection()
        inv = await p.collect_inventory()
        b1 = await p.collect_performance(ts=1000.0)  # 1º ciclo: só grava a base dos contadores
    with respx.mock(base_url=base(443), assert_all_called=False) as m:
        mock_api(m, reads=7000)                     # +6000 leituras em 60 s
        b2 = await p.collect_performance(ts=1060.0)
    assert tr.ok and tr.serial == "AC123"
    assert_catalog(inv, b2)
    assert count(inv, "volume") == 1 and count(inv, "initiator") == 1
    assert ("wwpn", "10000000c9aabb01", "self") in inv.entities[("initiator", W)].identifiers
    assert "iops_read" not in metrics_of(b1, "volume", "v1")       # contador: sem taxa no 1º ciclo
    v = metrics_of(b2, "volume", "v1")
    assert v["iops_read"] == pytest.approx(100.0) and v["lat_read_ms"] == pytest.approx(0.5)
    assert metrics_of(b2, "pool", "p1")["cap_used_pct"] == pytest.approx(25.0)
cd backend && QV_DATA_DIR=/tmp/qvdata python -m pytest -q tests/plugins/test_acme_array.py

Fixtures de tests/plugins/conftest.py:

Fixture / função Uso
make_ctx(plugin, port=None, credential=None, options=None, state=None) PluginContext com host array.test
base(port, scheme="https") URL base para o respx.mock(base_url=...)
assert_catalog(inv, batch) obrigatório: só nomes do catálogo, pais e relações apontando para entidades existentes
count(inv, tipo), rels(inv, kind), idents(inv, tipo, id), metrics_of(batch, tipo, id) asserções
FakeSSH / patch_ssh(monkeypatch, módulo, respostas) plugins SSH: respostas por comando (match exato ou prefixo)

Grave as respostas a partir da documentação e, quando possível, de um equipamento real (remova dados sensíveis). Teste também versões diferentes de firmware e endpoints ausentes.

5. Valide de ponta a ponta

  1. Rode a suíte python -m pytest -q -m "not integration".
  2. Cadastre um dispositivo de laboratório e use Testar conexão.
  3. Confira o inventário (abas Storage/SAN), a página do objeto (atributos, identificadores) e as métricas contra a ferramenta do fabricante.
  4. Verifique se a topologia correlaciona com switches e vCenter (WWPN/NAA iguais nos dois lados).
  5. Documente as limitações no README.md dos plugins (endpoints, permissão mínima, unidades).