Files
cloud-ip-validator/internal/dashboard/client.go
T

229 lines
8.1 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
}
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 int) (orchestratorSettingsDTO, error) {
var out orchestratorSettingsDTO
err := c.do(ctx, http.MethodPut, "/api/v1/admin/config/orchestrator",
orchestratorSettingsDTO{FIPSettleSeconds: fipSettleSeconds}, &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
}