Files
cloud-ip-validator/internal/dashboard/client.go
T
ayurishchevandClaude Sonnet 5.5 cd37b10f3b Add optional automatic check cycle (clear queue -> scan FIPs -> wait -> repeat)
An admin-controlled scenario that repeats what the operator does by hand:
clear the IP queue, scan and enqueue all free Floating IPs, wait until every
queued address reaches a terminal state (so results are in the Registry),
then wait a configurable interval and start over.

- control-api: new auto_cycle singleton table (migration 0008) holding
  enabled/interval/max-run settings and persisted phase state, so the cycle
  survives restarts; engine in orchestrator/autocycle.go driven from the
  existing loop tick with an injectable "now" for deterministic tests.
- Interval (default 1h, min 60s) and max wait (default unlimited, timeout
  outcome) are runtime settings, never hardcoded.
- The periodic fip_scan_interval_seconds scan is skipped while the cycle is
  enabled. An emptied queue mid-cycle counts as finished; stopping during
  the pause keeps the last cycle's outcome.
- API: GET/PUT /api/v1/admin/auto-cycle, POST .../start, POST .../stop.
- admin-dashboard: "Автоматический цикл" panel on /settings and an
  "Автоцикл активен" indicator on /overview.
- Tests for db, orchestrator, httpapi and dashboard; run-local-e2e.sh now
  exercises a full auto cycle; docs updated; bin/ rebuilt with refreshed
  SHA256SUMS.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-01 10:28:53 +03:00

280 lines
10 KiB
Go

package dashboard
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"time"
)
// apiErr is returned by every client method for a non-2xx response from
// control-api, or for a transport-level failure (control-api unreachable/
// timeout, Status==0). Handlers use it (via errors.As) to render an error
// banner with the right status/severity instead of a raw 500 — see
// writeErrorBanner in render.go.
type apiErr struct {
Status int
Message string
}
func (e *apiErr) Error() string {
if e.Status == 0 {
return fmt.Sprintf("control-api недоступен: %s", e.Message)
}
return fmt.Sprintf("control-api: %d %s", e.Status, e.Message)
}
// client is a thin, dashboard-local JSON client for control-api's
// /api/v1/admin/* surface. It intentionally doesn't reuse
// internal/apiclient.Client (shared by validator-agent/prober): that
// client's Do only returns an opaque error, with no way to recover the
// HTTP status code — which the dashboard needs to render 400 vs 404 vs 409
// vs 5xx differently. Duplicating ~30 lines here avoids widening
// apiclient's contract (and its blast radius on the other two binaries)
// for a need only this package has.
type client struct {
baseURL string
http *http.Client
}
func newClient(baseURL string, timeout time.Duration) *client {
return &client{baseURL: baseURL, http: &http.Client{Timeout: timeout}}
}
func (c *client) do(ctx context.Context, method, path string, body, out interface{}) error {
var reader io.Reader
if body != nil {
b, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("marshal request: %w", err)
}
reader = bytes.NewReader(b)
}
req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, reader)
if err != nil {
return fmt.Errorf("build request: %w", err)
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := c.http.Do(req)
if err != nil {
return &apiErr{Status: 0, Message: err.Error()}
}
defer resp.Body.Close()
respBody, _ := io.ReadAll(resp.Body)
if resp.StatusCode >= 300 {
msg := string(respBody)
var er errorResponse
if json.Unmarshal(respBody, &er) == nil && er.Error != "" {
msg = er.Error
}
return &apiErr{Status: resp.StatusCode, Message: msg}
}
if out != nil && len(respBody) > 0 {
if err := json.Unmarshal(respBody, out); err != nil {
return fmt.Errorf("decode response from %s %s: %w", method, path, err)
}
}
return nil
}
func (c *client) Status(ctx context.Context) (statusResponse, error) {
var out statusResponse
err := c.do(ctx, http.MethodGet, "/api/v1/admin/status", nil, &out)
return out, err
}
func (c *client) ListIPs(ctx context.Context) ([]ipQueueItem, error) {
var out []ipQueueItem
err := c.do(ctx, http.MethodGet, "/api/v1/admin/ips", nil, &out)
return out, err
}
func (c *client) GetIP(ctx context.Context, ip string) (ipDetailResponse, error) {
var out ipDetailResponse
err := c.do(ctx, http.MethodGet, "/api/v1/admin/ips/"+url.PathEscape(ip), nil, &out)
return out, err
}
// SubmitIPs is the single entry point for both adding new addresses and
// forcing a recheck of already-finished ones — see docs/API.md.
func (c *client) SubmitIPs(ctx context.Context, addresses []string) (submitIPsResponse, error) {
var out submitIPsResponse
err := c.do(ctx, http.MethodPost, "/api/v1/admin/ips", map[string][]string{"addresses": addresses}, &out)
return out, err
}
func (c *client) CancelIP(ctx context.Context, ip string) error {
return c.do(ctx, http.MethodPost, "/api/v1/admin/ips/"+url.PathEscape(ip)+"/cancel", nil, nil)
}
// DeleteIP permanently removes one address and its full history — unlike
// CancelIP, there's nothing left to look up afterward.
func (c *client) DeleteIP(ctx context.Context, ip string) error {
return c.do(ctx, http.MethodDelete, "/api/v1/admin/ips/"+url.PathEscape(ip), nil, nil)
}
// DeleteIPs permanently removes a specific list of addresses in one call.
func (c *client) DeleteIPs(ctx context.Context, addresses []string) (deleteIPsResponse, error) {
var out deleteIPsResponse
err := c.do(ctx, http.MethodPost, "/api/v1/admin/ips/delete", map[string][]string{"addresses": addresses}, &out)
return out, err
}
// ClearQueue permanently removes every address currently in the queue,
// including those actively being checked.
func (c *client) ClearQueue(ctx context.Context) (clearQueueResponse, error) {
var out clearQueueResponse
err := c.do(ctx, http.MethodPost, "/api/v1/admin/ips/clear", nil, &out)
return out, err
}
// ScanFloatingIPs lists the OpenStack project's free (unassociated)
// floating IPs and submits them to the check queue — see
// orchestrator.ScanFloatingIPs.
func (c *client) ScanFloatingIPs(ctx context.Context) (scanIPsResponse, error) {
var out scanIPsResponse
err := c.do(ctx, http.MethodPost, "/api/v1/admin/ips/scan", nil, &out)
return out, err
}
// ListRegistry returns every address ever submitted to the check queue,
// each with a summary of its accumulated check history — survives an
// address being deleted from the queue and later re-added.
func (c *client) ListRegistry(ctx context.Context) ([]registryItem, error) {
var out []registryItem
err := c.do(ctx, http.MethodGet, "/api/v1/admin/registry", nil, &out)
return out, err
}
// GetRegistryHistory returns one address's registry record plus its full
// retained check history across every cycle still kept.
func (c *client) GetRegistryHistory(ctx context.Context, ip string) (registryHistoryResponse, error) {
var out registryHistoryResponse
err := c.do(ctx, http.MethodGet, "/api/v1/admin/registry/"+url.PathEscape(ip), nil, &out)
return out, err
}
func (c *client) ListValidators(ctx context.Context) ([]validatorDTO, error) {
var out []validatorDTO
err := c.do(ctx, http.MethodGet, "/api/v1/admin/config/validators", nil, &out)
return out, err
}
func (c *client) CreateValidator(ctx context.Context, id, osPortID string) error {
body := map[string]string{"validator_id": id, "os_port_id": osPortID}
return c.do(ctx, http.MethodPost, "/api/v1/admin/config/validators", body, nil)
}
func (c *client) UpdateValidator(ctx context.Context, id, osPortID string) error {
body := map[string]string{"os_port_id": osPortID}
return c.do(ctx, http.MethodPut, "/api/v1/admin/config/validators/"+url.PathEscape(id), body, nil)
}
func (c *client) DeleteValidator(ctx context.Context, id string) error {
return c.do(ctx, http.MethodDelete, "/api/v1/admin/config/validators/"+url.PathEscape(id), nil, nil)
}
func (c *client) ListSites(ctx context.Context) ([]siteDTO, error) {
var out []siteDTO
err := c.do(ctx, http.MethodGet, "/api/v1/admin/config/sites", nil, &out)
return out, err
}
func (c *client) PutSite(ctx context.Context, index int, siteID string) error {
body := map[string]string{"site_id": siteID}
return c.do(ctx, http.MethodPut, fmt.Sprintf("/api/v1/admin/config/sites/%d", index), body, nil)
}
func (c *client) DeleteSite(ctx context.Context, index int) error {
return c.do(ctx, http.MethodDelete, fmt.Sprintf("/api/v1/admin/config/sites/%d", index), nil, nil)
}
func (c *client) ListTargetGroups(ctx context.Context) ([]targetGroupDTO, error) {
var out []targetGroupDTO
err := c.do(ctx, http.MethodGet, "/api/v1/admin/config/targets", nil, &out)
return out, err
}
func (c *client) PutTargetGroup(ctx context.Context, name string, targets []string) error {
body := map[string][]string{"targets": targets}
return c.do(ctx, http.MethodPut, "/api/v1/admin/config/targets/"+url.PathEscape(name), body, nil)
}
func (c *client) DeleteTargetGroup(ctx context.Context, name string) error {
return c.do(ctx, http.MethodDelete, "/api/v1/admin/config/targets/"+url.PathEscape(name), nil, nil)
}
func (c *client) ListCheckTypes(ctx context.Context) ([]checkTypeDTO, error) {
var out []checkTypeDTO
err := c.do(ctx, http.MethodGet, "/api/v1/admin/config/check-types", nil, &out)
return out, err
}
func (c *client) PutCheckType(ctx context.Context, name string, enabled bool, targets []string) error {
body := map[string]interface{}{"enabled": enabled, "targets": targets}
return c.do(ctx, http.MethodPut, "/api/v1/admin/config/check-types/"+url.PathEscape(name), body, nil)
}
func (c *client) DeleteCheckType(ctx context.Context, name string) error {
return c.do(ctx, http.MethodDelete, "/api/v1/admin/config/check-types/"+url.PathEscape(name), nil, nil)
}
func (c *client) GetOrchestratorSettings(ctx context.Context) (orchestratorSettingsDTO, error) {
var out orchestratorSettingsDTO
err := c.do(ctx, http.MethodGet, "/api/v1/admin/config/orchestrator", nil, &out)
return out, err
}
func (c *client) PutOrchestratorSettings(ctx context.Context, fipSettleSeconds, historyRetentionCycles int) (orchestratorSettingsDTO, error) {
var out orchestratorSettingsDTO
err := c.do(ctx, http.MethodPut, "/api/v1/admin/config/orchestrator",
orchestratorSettingsDTO{FIPSettleSeconds: fipSettleSeconds, HistoryRetentionCycles: historyRetentionCycles}, &out)
return out, err
}
func (c *client) GetInboundChecks(ctx context.Context) (inboundChecksDTO, error) {
var out inboundChecksDTO
err := c.do(ctx, http.MethodGet, "/api/v1/admin/config/inbound-checks", nil, &out)
return out, err
}
func (c *client) PutInboundChecks(ctx context.Context, ports []int, icmp bool) (inboundChecksDTO, error) {
var out inboundChecksDTO
err := c.do(ctx, http.MethodPut, "/api/v1/admin/config/inbound-checks",
inboundChecksDTO{Ports: ports, ICMP: icmp}, &out)
return out, err
}
func (c *client) GetAutoCycle(ctx context.Context) (autoCycleDTO, error) {
var out autoCycleDTO
err := c.do(ctx, http.MethodGet, "/api/v1/admin/auto-cycle", nil, &out)
return out, err
}
func (c *client) PutAutoCycle(ctx context.Context, intervalSeconds, maxRunSeconds int) (autoCycleDTO, error) {
var out autoCycleDTO
err := c.do(ctx, http.MethodPut, "/api/v1/admin/auto-cycle",
map[string]int{"interval_seconds": intervalSeconds, "max_run_seconds": maxRunSeconds}, &out)
return out, err
}
func (c *client) StartAutoCycle(ctx context.Context) (autoCycleDTO, error) {
var out autoCycleDTO
err := c.do(ctx, http.MethodPost, "/api/v1/admin/auto-cycle/start", nil, &out)
return out, err
}
func (c *client) StopAutoCycle(ctx context.Context) (autoCycleDTO, error) {
var out autoCycleDTO
err := c.do(ctx, http.MethodPost, "/api/v1/admin/auto-cycle/stop", nil, &out)
return out, err
}