Files
haproxy-openmanager/frontend/src/components/Configuration.js
T
taylanbakircioglu 02b1cb2bca feat: v1.5.0 — Site Wizard (Issue #14) + ACME Diagnostic Panel (Issue #13)
Closes #13, Closes #14.

This release squashes the v1.4.0 → v1.5.0 development line. v1.4.0
shipped the ACME stability & enterprise audit (Issues #10/#11/#12).
v1.5.0 builds on that foundation with two co-equal headline features
plus a 22-round audit campaign hardening the prior configuration
surface. License remains MIT for v1.5.0 (relicense to AGPL-3.0
lands in v1.5.2).

------------------------------------------------------------------
HEADLINE FEATURE A — ACME Diagnostic Panel (Issue #13)
------------------------------------------------------------------
A live pre-flight + post-failure diagnostic surface for every ACME
order, reachable from the ACME Automation page. The panel exists
to make ACME failures legible to operators who do NOT have shell
access to the API host.

Endpoints (`backend/routers/acme_diagnostics.py`):
  POST /api/letsencrypt/orders/{order_id}/diagnostics
       Run the full 5-check suite (DNS / port-80 / routing /
       account / agents) and humanize the order's `error_detail`
       (>=11 RFC-8555 problem types, backwards compatible with
       legacy plain-string failures).
  POST /api/letsencrypt/orders/{order_id}/diagnostics/
                                {check_id}/rerun
       Re-run a single check in place — used by the "Re-run"
       button on every row of the modal's pre-flight table.
  GET  /api/letsencrypt/orders/{order_id}/events
       Merged event timeline combining the typed
       `acme_order_events` rows with correlated
       `user_activity_logs` entries (resource_type =
       'letsencrypt_order' AND resource_id = order_id). The
       diagnostic modal auto-tails this timeline every 5 seconds
       while open.

Service-level checks (`backend/services/acme_diagnostics.py`):
  * DNS resolution via stdlib socket.gethostbyname_ex through
    run_in_executor (intentionally avoiding an aiodns runtime
    dep for v1.5.0).
  * Port-80 HEAD probe, target locked to the order's domains,
    success on HTTP 200 OR 404, warns on egress timeout
    (corp egress policies routinely blackhole outbound 80 —
    fail-hard would be too noisy).
  * SSRF guard: probe refuses non-public IPs and surfaces the
    skip in the diagnostic result; IPv4-mapped IPv6 normalisation
    closes the `::ffff:169.254.169.254` cloud-metadata vector.
  * HAProxy routing presence check: matches the order's
    cluster_ids to a port-80 HTTP frontend.
  * ACME account validity check against `letsencrypt_accounts`.
  * Agent presence check (>=1 active agent in target cluster).
  * Every sub-check wrapped in a wall-clock timeout to bound
    impact on the API event loop.

RBAC: ssl.read for run, ssl.read for events. Per-user 5/min rate
limit on both run and rerun, backed by the (user_id, action,
created_at DESC) composite index.

Frontend (`frontend/src/components/ACMEAutomation.js`):
  * "Diagnose" button on every order row + the existing
    "stuck order" warning row.
  * Modal with two tabs:
    - Pre-flight Checks (Antd Table with status pills + Re-run
      buttons + humanized error banner)
    - Event Log (Antd Timeline with auto-tail polling, scroll-
      to-bottom, pause-on-hover)
  * Correlation IDs surfaced in error banners and individual
    check fail details for backend-log lookup.

------------------------------------------------------------------
HEADLINE FEATURE B — Site Setup Wizard (Issue #14)
------------------------------------------------------------------
A single guided flow that creates a Backend + Servers + HTTP
Frontend (and optional HTTPS Frontend) in one atomic transaction.

Endpoints (`backend/routers/site_wizard.py`):
  POST /api/site-wizard/preview     — diff-preview the changeset
  POST /api/site-wizard/create      — atomic execute
  POST /api/site-wizard/reject      — clean rollback (including
                                       any wizard_staged ACME
                                       orders)
  GET  /api/site-wizard/drafts      — draft persistence
  PUT  /api/site-wizard/drafts/{id} — save/update
  DELETE /api/site-wizard/drafts/{id}

Feature surface:
  * One screen captures both backend (mode + servers) AND
    frontend (http + optional https + SSL mode) inputs.
  * SSL modes: ACME (new order, HTTP-01 only for v1.5.0),
    Upload (existing PEM), Existing (link to a stored cert),
    or None.
  * ACME-staged path: wizard_staged_until watermark on the
    `letsencrypt_orders` row defers finalisation until agent
    confirmation; per-mode reject cleanly cancels and rolls
    back the staged order.
  * Live diff preview against the cluster's current generated
    config (renderer-evolution noise stripped — track-sc<N>
    dedup, per-server cookie strip, defaults-cookie
    inheritance, listen-block flattening).
  * Draft persistence with PEM stripped at save time (private
    keys never round-trip through the drafts table).
  * Per-cluster multi-tenancy: drafts and wizard_staged orders
    are isolated to the creating user's cluster scope.

Frontend (`frontend/src/components/SiteWizard.js`):
  * 4-step Antd Steps flow: Backend → Frontend → SSL → Review.
  * Render the live diff preview inline before commit.
  * Antd Form-level validation mirrors backend Pydantic
    validators (numeric bounds, HAProxy reserved keywords, ALPN
    consistency, IPv6 scope-id, domain regex, server name
    dedup).

------------------------------------------------------------------
AUDIT CAMPAIGN — Rounds 1 → 22 (Bulgu #1#82)
------------------------------------------------------------------
v1.5.0 includes 22 adversarial review passes. Each round produced
its own commit set in the corporate development line; this squash
collapses those into the v1.5.0 release artefact. Highlights:

  Round 1-4   Site Wizard core: dry-run parity, single-line
              value injection guard, ACL -f pattern-file block,
              SSL parity, timeout regex, form-state pin.
  Round 5-7   defaults-cookie inheritance, server-named-cookie
              guard, fe/be mode mismatch, duplicate server
              names, health_check_uri + server_address
              validators.
  Round 8-10  cookie_name / cookie_options newline-injection
              guard, dry-run parity (round 9), TCP-mode HTTP-only
              feature blockers.
  Round 11    SSL name path traversal + health-check >= 1.
  Round 12-13 SSL & ACME deep dive (Bulgu #23-#32).
  Round 14    single-line value injection (Bulgu #33).
  Round 15-17 ACME multi-tenant UX, numeric bounds, HAProxy
              reserved keywords, ALPN/TLS consistency,
              all-backup, multi-domain & multi-user enterprise
              edges, drain/HSTS/post-completion (Bulgu
              #34-#53).
  Round 18-21 concurrency, agent state, TCP-mode HTTP-only,
              list size caps, IPv6 scope-id, preview account
              validation, TCP backend + balance uri reject
              (Bulgu #54-#61).
  Round 22    FE error visibility + 3x stale-data lockouts,
              referential integrity + cascade safety,
              authentication & authorization, multi-cluster
              isolation, apply_pending_changes concurrency,
              script injection + bulk import multi-tenancy,
              prefix-stripped signature comparison
              (Bulgu #62-#82).

------------------------------------------------------------------
NO CORPORATE-SPECIFIC ARTIFACTS
------------------------------------------------------------------
This squash deliberately sanitises corporate hostnames, container
registry references, and TLS secret names into generic
placeholders (`your-registry.example.com/your-org`,
`haproxy-openmanager*.example.com`, `wildcard-tls`,
`taylanbakircioglu/haproxy-openmanager-*`) so the public artefact
contains no internal infrastructure detail. Pilot / development
history that retained those values stays in the corporate fork
and is NOT part of this commit.
2026-05-14 00:04:19 +03:00

832 lines
26 KiB
JavaScript

// Configuration Management Component - Agent haproxy.cfg viewer
import React, { useState, useEffect, useCallback, useRef } from 'react';
import {
Card,
Table,
Button,
Space,
Tag,
message,
Badge,
Typography,
Alert,
Tooltip,
Spin,
Modal,
Input,
Progress,
theme
} from 'antd';
import {
DesktopOutlined,
EyeOutlined,
DownloadOutlined,
ReloadOutlined,
HeartTwoTone,
WarningOutlined,
CheckCircleOutlined,
CloseCircleOutlined,
ClockCircleOutlined,
LinuxOutlined,
AppleOutlined,
WifiOutlined,
DisconnectOutlined,
InfoCircleOutlined,
FileTextOutlined,
SyncOutlined
} from '@ant-design/icons';
import axios from 'axios';
import { useCluster } from '../contexts/ClusterContext';
import { extractApiError } from '../utils/apiError';
const { Text, Title, Paragraph } = Typography;
const { TextArea } = Input;
const Configuration = () => {
// === State Management ===
const [agents, setAgents] = useState([]);
const [filteredAgents, setFilteredAgents] = useState([]);
const [searchText, setSearchText] = useState('');
const [loading, setLoading] = useState(false);
const [configModalVisible, setConfigModalVisible] = useState(false);
const [selectedAgent, setSelectedAgent] = useState(null);
const [configContent, setConfigContent] = useState('');
const [configLoading, setConfigLoading] = useState(false);
const [requestId, setRequestId] = useState(null);
const [progressPercent, setProgressPercent] = useState(0);
const [timeRemaining, setTimeRemaining] = useState(60);
// Use refs to store interval and timeout IDs to avoid stale closures
const pollingIntervalRef = useRef(null);
const timeoutRef = useRef(null);
const pollCountRef = useRef(0);
const { selectedCluster, loading: clustersLoading } = useCluster();
const { token } = theme.useToken();
// Platform configuration
const platformConfig = {
linux: {
name: 'Linux',
icon: <LinuxOutlined style={{ fontSize: '24px', color: '#1890ff' }} />,
color: '#1890ff'
},
darwin: {
name: 'macOS',
icon: <AppleOutlined style={{ fontSize: '24px', color: '#722ed1' }} />,
color: '#722ed1'
}
};
// Fetch agents from API
const fetchAgents = useCallback(async () => {
if (!selectedCluster) {
setAgents([]);
setFilteredAgents([]);
return;
}
setLoading(true);
try {
const params = { pool_id: selectedCluster.pool_id };
const response = await axios.get('/api/agents', {
params,
timeout: 10000,
headers: {
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Pragma': 'no-cache'
}
});
const agentsData = response.data.agents || [];
setAgents(agentsData);
setFilteredAgents(agentsData);
} catch (error) {
console.error('Failed to fetch agents:', error);
message.error('Failed to fetch agents: ' + (extractApiError(error, error.message)));
} finally {
setLoading(false);
}
}, [selectedCluster]);
// Search/filter agents
const handleSearch = (value) => {
setSearchText(value);
if (!value) {
setFilteredAgents(agents);
} else {
const filtered = agents.filter(agent =>
agent.name.toLowerCase().includes(value.toLowerCase()) ||
agent.hostname?.toLowerCase().includes(value.toLowerCase()) ||
agent.pool_name?.toLowerCase().includes(value.toLowerCase()) ||
agent.platform?.toLowerCase().includes(value.toLowerCase()) ||
agent.ip_address?.toLowerCase().includes(value.toLowerCase())
);
setFilteredAgents(filtered);
}
};
// Update filteredAgents when agents change
useEffect(() => {
handleSearch(searchText);
}, [agents, searchText]);
// CRITICAL FIX: Clear agents immediately when cluster changes (prevent cache/mixing)
useEffect(() => {
if (selectedCluster) {
console.log(`🔄 CLUSTER CHANGED: ${selectedCluster.name} (ID: ${selectedCluster.id}) - Clearing agents to prevent mixing...`);
setAgents([]);
setFilteredAgents([]);
}
}, [selectedCluster?.id]); // Trigger on cluster ID change only
// Initial load
useEffect(() => {
fetchAgents();
}, [fetchAgents, selectedCluster]);
// Get platform icon
const getPlatformIcon = (platform) => {
return platformConfig[platform]?.icon || <DesktopOutlined style={{ fontSize: '16px' }} />;
};
// Enhanced status badge
const getStatusBadge = (health, status, lastSeen) => {
const statusConfig = {
healthy: {
status: 'success',
icon: <CheckCircleOutlined />,
text: 'Online',
color: '#52c41a'
},
warning: {
status: 'warning',
icon: <WarningOutlined />,
text: 'Warning',
color: '#faad14'
},
offline: {
status: 'error',
icon: <CloseCircleOutlined />,
text: 'Offline',
color: '#ff4d4f'
},
unknown: {
status: 'default',
icon: <ClockCircleOutlined />,
text: 'Unknown',
color: '#d9d9d9'
}
};
const config = statusConfig[health] || statusConfig.unknown;
const getLastSeenText = () => {
if (!lastSeen) return 'Never connected';
const date = new Date(lastSeen);
const now = new Date();
const diffMinutes = Math.floor((now - date) / (1000 * 60));
if (diffMinutes < 1) return 'Just now';
if (diffMinutes < 60) return `${diffMinutes}m ago`;
if (diffMinutes < 1440) return `${Math.floor(diffMinutes / 60)}h ago`;
return `${Math.floor(diffMinutes / 1440)}d ago`;
};
return (
<Tooltip title={`Status: ${config.text} | Last seen: ${getLastSeenText()}`}>
<Badge
status={config.status}
text={config.text}
style={{ color: config.color }}
/>
</Tooltip>
);
};
// Cancel config request
const cancelConfigRequest = () => {
if (pollingIntervalRef.current) {
clearInterval(pollingIntervalRef.current);
pollingIntervalRef.current = null;
}
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
setConfigLoading(false);
setProgressPercent(0);
setTimeRemaining(60);
pollCountRef.current = 0;
message.info('Configuration request cancelled');
};
// Poll for config response
const pollConfigResponse = useCallback(async (reqId) => {
try {
pollCountRef.current += 1;
const response = await axios.get(`/api/configuration/response/${reqId}`);
const data = response.data;
if (data.status === 'completed' && data.config_content) {
// Success - got the config
if (pollingIntervalRef.current) {
clearInterval(pollingIntervalRef.current);
pollingIntervalRef.current = null;
}
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
setConfigLoading(false);
setProgressPercent(100);
setConfigContent(data.config_content);
setConfigModalVisible(true);
message.success('Configuration retrieved successfully');
} else if (data.status === 'expired') {
// Request expired
if (pollingIntervalRef.current) {
clearInterval(pollingIntervalRef.current);
pollingIntervalRef.current = null;
}
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
setConfigLoading(false);
setProgressPercent(0);
message.error('Request expired. Agent did not respond in time.');
} else {
// Still pending - update progress
const elapsed = pollCountRef.current * 2; // 2 seconds per poll
const progress = Math.min((elapsed / 90) * 100, 95); // Cap at 95% until complete (90s timeout)
setProgressPercent(progress);
}
} catch (error) {
if (pollingIntervalRef.current) {
clearInterval(pollingIntervalRef.current);
pollingIntervalRef.current = null;
}
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
setConfigLoading(false);
setProgressPercent(0);
message.error('Failed to get configuration: ' + (extractApiError(error, error.message)));
}
}, []);
// View configuration
const viewConfig = async (agent) => {
if (agent.status !== 'online') {
message.warning(`Agent '${agent.name}' is not online. Cannot retrieve configuration.`);
return;
}
if (!selectedCluster) {
message.error('No cluster selected. Please select a cluster first.');
return;
}
setSelectedAgent(agent);
setConfigLoading(true);
setConfigContent('');
setProgressPercent(0);
setTimeRemaining(90);
pollCountRef.current = 0;
try {
// Create config request with cluster_id
const response = await axios.post('/api/configuration/request', null, {
params: {
agent_name: agent.name,
cluster_id: selectedCluster.id,
request_type: 'view'
}
});
const reqId = response.data.request_id;
setRequestId(reqId);
message.info('Configuration request sent. Waiting for agent response...');
// Start polling for response
pollingIntervalRef.current = setInterval(() => {
pollConfigResponse(reqId);
}, 2000); // Poll every 2 seconds
// Timeout after 90 seconds (agent checks every 30 seconds, worst case ~60s with restart)
timeoutRef.current = setTimeout(() => {
if (pollingIntervalRef.current) {
clearInterval(pollingIntervalRef.current);
pollingIntervalRef.current = null;
}
setConfigLoading(false);
setProgressPercent(0);
message.error('Request timeout. Agent did not respond in time. Please try again.');
}, 90000); // 90 seconds
} catch (error) {
setConfigLoading(false);
setProgressPercent(0);
message.error('Failed to create configuration request: ' + (extractApiError(error, error.message)));
}
};
// Download configuration
const downloadConfig = async (agent) => {
if (agent.status !== 'online') {
message.warning(`Agent '${agent.name}' is not online. Cannot retrieve configuration.`);
return;
}
if (!selectedCluster) {
message.error('No cluster selected. Please select a cluster first.');
return;
}
setSelectedAgent(agent);
setConfigLoading(true);
setProgressPercent(0);
pollCountRef.current = 0;
try {
// Create config request with cluster_id
const response = await axios.post('/api/configuration/request', null, {
params: {
agent_name: agent.name,
cluster_id: selectedCluster.id,
request_type: 'download'
}
});
const reqId = response.data.request_id;
message.info('Configuration request sent. Waiting for agent response...');
// Start polling for response
const pollForDownload = async () => {
try {
pollCountRef.current += 1;
const elapsed = pollCountRef.current * 2;
const progress = Math.min((elapsed / 90) * 100, 95); // 90s timeout
setProgressPercent(progress);
const pollResponse = await axios.get(`/api/configuration/response/${reqId}`);
const data = pollResponse.data;
if (data.status === 'completed' && data.config_content) {
// Success - download the config
setProgressPercent(100);
if (pollingIntervalRef.current) {
clearInterval(pollingIntervalRef.current);
pollingIntervalRef.current = null;
}
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
const element = document.createElement('a');
const file = new Blob([data.config_content], { type: 'text/plain' });
element.href = URL.createObjectURL(file);
element.download = `${agent.name}-haproxy.cfg`;
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
setConfigLoading(false);
setProgressPercent(0);
message.success('Configuration downloaded successfully');
return true;
} else if (data.status === 'expired') {
if (pollingIntervalRef.current) {
clearInterval(pollingIntervalRef.current);
pollingIntervalRef.current = null;
}
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
setConfigLoading(false);
setProgressPercent(0);
message.error('Request expired. Agent did not respond in time.');
return true;
}
return false;
} catch (error) {
if (pollingIntervalRef.current) {
clearInterval(pollingIntervalRef.current);
pollingIntervalRef.current = null;
}
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
setConfigLoading(false);
setProgressPercent(0);
message.error('Failed to download configuration: ' + (extractApiError(error, error.message)));
return true;
}
};
// Poll every 2 seconds
pollingIntervalRef.current = setInterval(async () => {
await pollForDownload();
}, 2000);
// Timeout after 90 seconds (agent checks every 30 seconds, worst case ~60s with restart)
timeoutRef.current = setTimeout(() => {
if (pollingIntervalRef.current) {
clearInterval(pollingIntervalRef.current);
pollingIntervalRef.current = null;
}
setConfigLoading(false);
setProgressPercent(0);
message.error('Request timeout. Agent did not respond in time. Please try again.');
}, 90000); // 90 seconds
} catch (error) {
setConfigLoading(false);
setProgressPercent(0);
message.error('Failed to create configuration request: ' + (extractApiError(error, error.message)));
}
};
// Cleanup polling on unmount
useEffect(() => {
return () => {
if (pollingIntervalRef.current) {
clearInterval(pollingIntervalRef.current);
pollingIntervalRef.current = null;
}
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
};
}, []);
// Table columns
const columns = [
{
title: 'Agent Info',
key: 'agent_info',
render: (text, record) => (
<Space direction="vertical" size="small">
<Space>
{getPlatformIcon(record.platform)}
<Text strong>{record.name}</Text>
{record.health === 'healthy' && (
<HeartTwoTone twoToneColor="#eb2f96" />
)}
</Space>
<Text type="secondary" style={{ fontSize: '12px' }}>
{record.hostname || 'Unknown hostname'}
</Text>
{record.ip_address && (
<Text type="secondary" style={{ fontSize: '11px' }}>
IP: {record.ip_address}
</Text>
)}
</Space>
),
width: 220,
},
{
title: 'Agent Pool',
dataIndex: 'pool_name',
key: 'pool_name',
render: (text, record) => (
<Space direction="vertical" size="small">
<Text>{text || 'Unknown'}</Text>
<Text type="secondary" style={{ fontSize: '12px' }}>
{record.pool_environment || 'Unknown environment'}
</Text>
</Space>
),
width: 180,
},
{
title: 'Platform',
key: 'platform',
render: (_, record) => (
<Space>
<Tag color="blue" style={{ textTransform: 'capitalize' }}>
{record.platform}
</Tag>
<Tag color="cyan" size="small">
{record.architecture}
</Tag>
</Space>
),
width: 150,
},
{
title: 'HAProxy Status',
key: 'haproxy_status',
render: (_, record) => (
<Tag
color={record.haproxy_status === 'running' ? 'green' :
record.haproxy_status === 'stopped' ? 'red' : 'orange'}
size="small"
>
{record.haproxy_status || 'unknown'}
</Tag>
),
width: 120,
},
{
title: 'Status',
key: 'status',
render: (_, record) => getStatusBadge(record.health, record.status, record.last_seen),
width: 120,
},
{
title: 'Actions',
key: 'actions',
render: (_, record) => {
const isLoading = configLoading && selectedAgent?.id === record.id;
if (isLoading) {
return (
<Space direction="vertical" style={{ width: '100%' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<SyncOutlined spin style={{ color: '#1890ff' }} />
<Text type="secondary" style={{ fontSize: '12px' }}>
Waiting for agent...
</Text>
</div>
<Progress
percent={progressPercent}
size="small"
status="active"
showInfo={false}
/>
<Button
size="small"
danger
onClick={cancelConfigRequest}
style={{ width: '100%' }}
>
Cancel
</Button>
</Space>
);
}
return (
<Space>
<Tooltip title={record.status !== 'online' ? 'Agent must be online' : 'View configuration'}>
<Button
type="primary"
size="small"
icon={<EyeOutlined />}
onClick={() => viewConfig(record)}
disabled={record.status !== 'online'}
>
View
</Button>
</Tooltip>
<Tooltip title={record.status !== 'online' ? 'Agent must be online' : 'Download configuration'}>
<Button
size="small"
icon={<DownloadOutlined />}
onClick={() => downloadConfig(record)}
disabled={record.status !== 'online'}
>
Download
</Button>
</Tooltip>
</Space>
);
},
width: 220,
fixed: 'right',
},
];
return (
<div style={{ padding: '24px' }}>
<div style={{ marginBottom: '24px' }}>
<Title level={2}>
<Space>
<FileTextOutlined />
Configuration Management
</Space>
</Title>
<Paragraph>
View and download active haproxy.cfg files from agents.
Configuration files are retrieved directly from agents in real-time.
</Paragraph>
{/* Info Alert */}
<Alert
message="How it works"
description={
<div>
<ul style={{ marginBottom: 0, paddingLeft: '20px' }}>
<li>Click "View" or "Download" to request the configuration file from an agent</li>
<li>The agent will retrieve its current haproxy.cfg file on the next heartbeat</li>
<li>The configuration will be displayed or downloaded once available</li>
<li>Agents must be online to process configuration requests</li>
</ul>
</div>
}
type="info"
showIcon
style={{ marginTop: '16px' }}
/>
</div>
<Card
title={<Space><DesktopOutlined /> Agents - {selectedCluster?.name || 'No cluster selected'}</Space>}
extra={
<Space>
<div style={{
position: 'relative',
display: 'inline-block',
width: 250
}}>
<input
type="text"
placeholder="Search agents..."
value={searchText}
onChange={(e) => handleSearch(e.target.value)}
style={{
width: '100%',
height: 32,
paddingLeft: 8,
paddingRight: searchText ? 32 : 8,
border: `1px solid ${token.colorBorder}`,
borderRadius: 6,
fontSize: 14,
outline: 'none',
boxShadow: 'none',
backgroundColor: token.colorBgContainer,
transition: 'border-color 0.3s ease'
}}
onFocus={(e) => {
e.target.style.borderColor = '#1890ff';
e.target.style.outline = 'none';
e.target.style.boxShadow = 'none';
}}
onBlur={(e) => {
e.target.style.borderColor = token.colorBorder;
}}
/>
{searchText && (
<CloseCircleOutlined
onClick={() => handleSearch('')}
style={{
position: 'absolute',
right: 8,
top: '50%',
transform: 'translateY(-50%)',
cursor: 'pointer',
color: '#bfbfbf',
fontSize: 14
}}
/>
)}
</div>
<Button
icon={<ReloadOutlined />}
onClick={fetchAgents}
loading={loading}
type="primary"
ghost
>
Refresh
</Button>
</Space>
}
>
{!selectedCluster ? (
// Phase J audit fix #6 — show a neutral "Loading…" state
// while the ClusterContext is still fetching, otherwise
// the operator sees "No Cluster Selected" during the
// legitimate post-deploy fetch window.
clustersLoading ? (
<Alert
message="Loading clusters…"
description="Fetching the cluster list. Agent inventory will appear automatically once a cluster is selected."
type="info"
showIcon
/>
) : (
<Alert
message="No Cluster Selected"
description="Please select a cluster from the cluster selector above to view its agents."
type="warning"
showIcon
/>
)
) : agents.length === 0 && !loading ? (
<div style={{
textAlign: 'center',
padding: '60px 20px',
background: token.colorFillQuaternary,
borderRadius: '6px'
}}>
<DesktopOutlined style={{ fontSize: '64px', color: token.colorTextQuaternary, marginBottom: '16px' }} />
<Title level={3} type="secondary">No Agents Found</Title>
<Paragraph type="secondary">
No agents are registered in this cluster yet.
</Paragraph>
</div>
) : (
<Spin spinning={loading} tip="Loading agents...">
<Table
columns={columns}
dataSource={filteredAgents}
rowKey="id"
pagination={{
pageSize: 10,
showSizeChanger: true,
showQuickJumper: true,
showTotal: (total, range) =>
`${range[0]}-${range[1]} of ${total} agents`,
}}
scroll={{ x: 1000 }}
size="middle"
/>
</Spin>
)}
</Card>
{/* Configuration Modal */}
<Modal
title={
<Space>
<FileTextOutlined />
<span>Configuration - {selectedAgent?.name}</span>
</Space>
}
open={configModalVisible}
onCancel={() => {
setConfigModalVisible(false);
setConfigContent('');
}}
width="90%"
footer={[
<Button
key="download"
icon={<DownloadOutlined />}
onClick={() => {
const element = document.createElement('a');
const file = new Blob([configContent], { type: 'text/plain' });
element.href = URL.createObjectURL(file);
element.download = `${selectedAgent?.name}-haproxy.cfg`;
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
message.success('Configuration downloaded');
}}
>
Download
</Button>,
<Button key="close" onClick={() => setConfigModalVisible(false)}>
Close
</Button>
]}
>
<Alert
message="Read-Only Configuration"
description="This is the current active configuration from the agent. Use the Download button to save it locally."
type="info"
showIcon
style={{ marginBottom: '16px' }}
/>
<div style={{ border: `1px solid ${token.colorBorder}`, borderRadius: '6px' }}>
<div style={{
background: '#001529',
color: 'white',
padding: '8px 12px',
fontSize: '12px',
borderBottom: '1px solid #434343'
}}>
{selectedAgent?.config_path || 'haproxy.cfg'}
</div>
<TextArea
value={configContent}
readOnly
rows={25}
style={{
fontFamily: 'Monaco, Menlo, "Ubuntu Mono", monospace',
fontSize: '12px',
border: 'none',
borderRadius: '0 0 6px 6px'
}}
/>
</div>
</Modal>
</div>
);
};
export default Configuration;