Implement Distributed Regional Monitoring Agent with add form, API details, one-click install, and bash script generation. Refactor: Rename API Documentation to Regional Monitoring

This commit is contained in:
Tola Leng
2025-06-20 22:46:12 +07:00
parent 918a248b8f
commit ea95490f13
13 changed files with 977 additions and 38 deletions
+77 -25
View File
@@ -1,11 +1,11 @@
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { Toaster } from '@/components/ui/sonner';
import { ThemeProvider } from '@/contexts/ThemeContext';
import { LanguageProvider } from '@/contexts/LanguageContext';
import { SidebarProvider } from '@/contexts/SidebarContext';
import { Toaster } from '@/components/ui/toaster';
import { ErrorBoundary } from '@/components/ErrorBoundary';
// Pages
@@ -13,51 +13,103 @@ import Index from '@/pages/Index';
import Login from '@/pages/Login';
import Dashboard from '@/pages/Dashboard';
import ServiceDetail from '@/pages/ServiceDetail';
import Profile from '@/pages/Profile';
import Settings from '@/pages/Settings';
import OperationalPage from '@/pages/OperationalPage';
import ScheduleIncident from '@/pages/ScheduleIncident';
import Profile from '@/pages/Profile';
import SslDomain from '@/pages/SslDomain';
import ScheduleIncident from '@/pages/ScheduleIncident';
import OperationalPage from '@/pages/OperationalPage';
import PublicStatusPage from '@/pages/PublicStatusPage';
import RegionalMonitoring from '@/pages/RegionalMonitoring';
import NotFound from '@/pages/NotFound';
import { authService } from '@/services/authService';
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: 1,
refetchOnWindowFocus: false,
retry: 2,
staleTime: 5 * 60 * 1000, // 5 minutes
},
},
});
// Protected Route wrapper
const ProtectedRoute = ({ children }: { children: React.ReactNode }) => {
const isAuthenticated = authService.isAuthenticated();
return isAuthenticated ? <>{children}</> : <Navigate to="/login" replace />;
};
function App() {
return (
<QueryClientProvider client={queryClient}>
<ThemeProvider>
<LanguageProvider>
<SidebarProvider>
<ErrorBoundary>
<ErrorBoundary>
<QueryClientProvider client={queryClient}>
<ThemeProvider>
<LanguageProvider>
<SidebarProvider>
<Router>
<Routes>
<Route path="/" element={<Index />} />
<Route path="/login" element={<Login />} />
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/service/:id" element={<ServiceDetail />} />
<Route path="/profile" element={<Profile />} />
<Route path="/settings" element={<Settings />} />
<Route path="/operational-page" element={<OperationalPage />} />
<Route path="/schedule-incident" element={<ScheduleIncident />} />
<Route path="/ssl-domain" element={<SslDomain />} />
<Route path="/status/:slug" element={<PublicStatusPage />} />
<Route path="/public/:pageId" element={<PublicStatusPage />} />
{/* Protected Routes */}
<Route path="/dashboard" element={
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
} />
<Route path="/service/:id" element={
<ProtectedRoute>
<ServiceDetail />
</ProtectedRoute>
} />
<Route path="/settings" element={
<ProtectedRoute>
<Settings />
</ProtectedRoute>
} />
<Route path="/profile" element={
<ProtectedRoute>
<Profile />
</ProtectedRoute>
} />
<Route path="/ssl-domain" element={
<ProtectedRoute>
<SslDomain />
</ProtectedRoute>
} />
<Route path="/schedule-incident" element={
<ProtectedRoute>
<ScheduleIncident />
</ProtectedRoute>
} />
<Route path="/operational-page" element={
<ProtectedRoute>
<OperationalPage />
</ProtectedRoute>
} />
<Route path="/regional-monitoring" element={
<ProtectedRoute>
<RegionalMonitoring />
</ProtectedRoute>
} />
<Route path="*" element={<NotFound />} />
</Routes>
</Router>
<Toaster />
</ErrorBoundary>
</SidebarProvider>
</LanguageProvider>
</ThemeProvider>
</QueryClientProvider>
</SidebarProvider>
</LanguageProvider>
</ThemeProvider>
</QueryClientProvider>
</ErrorBoundary>
);
}
@@ -1,5 +1,4 @@
import { Globe, Boxes, Radar, Calendar, BarChart2, LineChart, FileText, Settings, User, Bell, Database, Info, BookOpen } from "lucide-react";
import { Globe, Boxes, Radar, Calendar, BarChart2, LineChart, MapPin, Settings, User, Bell, Database, Info, BookOpen } from "lucide-react";
export const mainMenuItems = [
{
@@ -51,12 +50,12 @@ export const mainMenuItems = [
hasNavigation: false
},
{
id: 'api-documentation',
path: null,
icon: FileText,
translationKey: 'apiDocumentation',
id: 'regional-monitoring',
path: '/regional-monitoring',
icon: MapPin,
translationKey: 'regionalMonitoring',
color: 'text-indigo-400',
hasNavigation: false
hasNavigation: true
}
];
@@ -0,0 +1,321 @@
import React, { useState } from "react";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Copy, Download, Terminal, CheckCircle } from "lucide-react";
import { regionalService } from "@/services/regionalService";
import { InstallCommand } from "@/types/regional.types";
import { useToast } from "@/hooks/use-toast";
interface AddRegionalAgentDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
onAgentAdded: () => void;
}
export const AddRegionalAgentDialog: React.FC<AddRegionalAgentDialogProps> = ({
open,
onOpenChange,
onAgentAdded
}) => {
const [step, setStep] = useState(1);
const [regionName, setRegionName] = useState("");
const [agentIp, setAgentIp] = useState("");
const [installCommand, setInstallCommand] = useState<InstallCommand | null>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
const { toast } = useToast();
const handleCreateAgent = async (e: React.FormEvent) => {
e.preventDefault();
if (!regionName.trim() || !agentIp.trim()) return;
setIsSubmitting(true);
try {
const result = await regionalService.createRegionalService({
region_name: regionName,
agent_ip_address: agentIp,
});
setInstallCommand(result.installCommand);
setStep(2);
} catch (error) {
toast({
title: "Error",
description: "Failed to create regional agent configuration.",
variant: "destructive",
});
} finally {
setIsSubmitting(false);
}
};
const copyToClipboard = async (text: string) => {
try {
await navigator.clipboard.writeText(text);
toast({
title: "Copied!",
description: "Installation command copied to clipboard.",
});
} catch (error) {
toast({
title: "Copy failed",
description: "Failed to copy to clipboard.",
variant: "destructive",
});
}
};
const downloadScript = () => {
if (!installCommand) return;
const blob = new Blob([installCommand.bash_script], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `install-regional-agent-${installCommand.agent_id}.sh`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
toast({
title: "Downloaded!",
description: "Installation script downloaded successfully.",
});
};
const handleComplete = () => {
onAgentAdded();
setStep(1);
setRegionName("");
setAgentIp("");
setInstallCommand(null);
onOpenChange(false);
};
const resetDialog = () => {
setStep(1);
setRegionName("");
setAgentIp("");
setInstallCommand(null);
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[800px] max-h-[90vh] overflow-auto">
<DialogHeader>
<DialogTitle>Add Regional Monitoring Agent</DialogTitle>
<DialogDescription>
Configure a new regional monitoring agent to extend your monitoring coverage.
</DialogDescription>
</DialogHeader>
{step === 1 && (
<form onSubmit={handleCreateAgent} className="space-y-6">
<div className="space-y-4">
<div>
<Label htmlFor="regionName">Region Name</Label>
<Input
id="regionName"
placeholder="e.g., US East, Europe West, Asia Pacific"
value={regionName}
onChange={(e) => setRegionName(e.target.value)}
required
/>
</div>
<div>
<Label htmlFor="agentIp">Agent Server IP Address</Label>
<Input
id="agentIp"
placeholder="e.g., 192.168.1.100 or your-server.com"
value={agentIp}
onChange={(e) => setAgentIp(e.target.value)}
required
/>
</div>
</div>
<div className="flex justify-end space-x-2">
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
Cancel
</Button>
<Button type="submit" disabled={isSubmitting}>
{isSubmitting ? "Creating..." : "Generate Installation"}
</Button>
</div>
</form>
)}
{step === 2 && installCommand && (
<div className="space-y-6">
<div className="text-center space-y-2">
<CheckCircle className="h-12 w-12 text-green-600 mx-auto" />
<h3 className="text-lg font-semibold">Agent Configuration Created!</h3>
<p className="text-muted-foreground">
Use the installation script below to set up your regional monitoring agent.
</p>
</div>
<Tabs defaultValue="details" className="w-full">
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="details">Agent Details</TabsTrigger>
<TabsTrigger value="install">Installation</TabsTrigger>
</TabsList>
<TabsContent value="details" className="space-y-4">
<Card>
<CardHeader>
<CardTitle>Agent Information</CardTitle>
<CardDescription>
Configuration details for your regional monitoring agent
</CardDescription>
</CardHeader>
<CardContent className="space-y-3">
<div className="grid grid-cols-2 gap-4">
<div>
<Label className="text-sm font-medium text-foreground">Agent ID</Label>
<div className="relative">
<Input
value={installCommand.agent_id}
readOnly
className="font-mono text-sm bg-muted/50 border-muted-foreground/20 text-foreground pr-10"
/>
<Button
size="sm"
variant="ghost"
className="absolute right-1 top-1/2 -translate-y-1/2 h-8 w-8 p-0 hover:bg-muted"
onClick={() => copyToClipboard(installCommand.agent_id)}
>
<Copy className="h-3 w-3" />
</Button>
</div>
</div>
<div>
<Label className="text-sm font-medium text-foreground">Region</Label>
<Input
value={regionName}
readOnly
className="font-mono text-sm bg-muted/50 border-muted-foreground/20 text-foreground"
/>
</div>
<div>
<Label className="text-sm font-medium text-foreground">Server IP</Label>
<Input
value={agentIp}
readOnly
className="font-mono text-sm bg-muted/50 border-muted-foreground/20 text-foreground"
/>
</div>
<div>
<Label className="text-sm font-medium text-foreground">API Endpoint</Label>
<Input
value={installCommand.api_endpoint}
readOnly
className="font-mono text-sm bg-muted/50 border-muted-foreground/20 text-foreground"
/>
</div>
</div>
<div>
<Label className="text-sm font-medium text-foreground">Authentication Token</Label>
<div className="relative">
<Input
value={installCommand.token}
readOnly
className="font-mono text-sm bg-muted/50 border-muted-foreground/20 text-foreground pr-10"
/>
<Button
size="sm"
variant="ghost"
className="absolute right-1 top-1/2 -translate-y-1/2 h-8 w-8 p-0 hover:bg-muted"
onClick={() => copyToClipboard(installCommand.token)}
>
<Copy className="h-3 w-3" />
</Button>
</div>
</div>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="install" className="space-y-4">
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Terminal className="h-5 w-5" />
One-Click Installation
</CardTitle>
<CardDescription>
Run this command on your target server to automatically install and configure the agent
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label>Installation Command</Label>
<div className="relative">
<Textarea
readOnly
value={`curl -fsSL | sudo bash -s -- <<'EOF'\n${installCommand.bash_script}\nEOF`}
className="font-mono text-sm min-h-[100px]"
/>
<Button
size="sm"
variant="outline"
className="absolute top-2 right-2"
onClick={() => copyToClipboard(`curl -fsSL | sudo bash -s -- <<'EOF'\n${installCommand.bash_script}\nEOF`)}
>
<Copy className="h-3 w-3" />
</Button>
</div>
</div>
<div className="flex gap-2">
<Button onClick={downloadScript} variant="outline" className="flex-1">
<Download className="mr-2 h-4 w-4" />
Download Script
</Button>
<Button
onClick={() => copyToClipboard(installCommand.bash_script)}
variant="outline"
className="flex-1"
>
<Copy className="mr-2 h-4 w-4" />
Copy Script
</Button>
</div>
<div className="text-sm text-muted-foreground space-y-2">
<p className="font-medium">Installation Steps:</p>
<ol className="list-decimal list-inside space-y-1">
<li>Copy the installation command above</li>
<li>SSH into your target server</li>
<li>Run the command as root (with sudo)</li>
<li>The agent will be automatically installed and started</li>
<li>Check the agent status in the Regional Monitoring dashboard</li>
</ol>
</div>
</CardContent>
</Card>
</TabsContent>
</Tabs>
<div className="flex justify-end space-x-2">
<Button variant="outline" onClick={resetDialog}>
Add Another
</Button>
<Button onClick={handleComplete}>
Complete Setup
</Button>
</div>
</div>
)}
</DialogContent>
</Dialog>
);
};
@@ -0,0 +1,139 @@
import React from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { MapPin, Wifi, WifiOff, MoreVertical, Trash2, Terminal, Copy } from "lucide-react";
import { RegionalService } from "@/types/regional.types";
import { formatDistanceToNow } from "date-fns";
import { useToast } from "@/hooks/use-toast";
interface RegionalAgentCardProps {
agent: RegionalService;
onDelete: () => void;
}
export const RegionalAgentCard: React.FC<RegionalAgentCardProps> = ({ agent, onDelete }) => {
const { toast } = useToast();
const copyAgentId = async () => {
try {
await navigator.clipboard.writeText(agent.agent_id);
toast({
title: "Copied!",
description: "Agent ID copied to clipboard.",
});
} catch (error) {
toast({
title: "Copy failed",
description: "Failed to copy agent ID.",
variant: "destructive",
});
}
};
const getConnectionStatus = () => {
if (agent.connection === 'online') {
return {
icon: <Wifi className="h-4 w-4" />,
label: 'Online',
variant: 'default' as const,
className: 'bg-green-100 text-green-800 hover:bg-green-100'
};
} else {
return {
icon: <WifiOff className="h-4 w-4" />,
label: 'Offline',
variant: 'secondary' as const,
className: 'bg-red-100 text-red-800 hover:bg-red-100'
};
}
};
const connectionStatus = getConnectionStatus();
return (
<Card className="relative">
<CardHeader className="pb-3">
<div className="flex items-start justify-between">
<div className="flex items-center space-x-2">
<MapPin className="h-5 w-5 text-blue-600" />
<div>
<CardTitle className="text-lg">{agent.region_name}</CardTitle>
<CardDescription className="flex items-center gap-1 text-sm">
{agent.agent_ip_address}
</CardDescription>
</div>
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="sm">
<MoreVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={copyAgentId}>
<Copy className="mr-2 h-4 w-4" />
Copy Agent ID
</DropdownMenuItem>
<DropdownMenuItem onClick={onDelete} className="text-red-600">
<Trash2 className="mr-2 h-4 w-4" />
Remove Agent
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center justify-between">
<Badge
variant={connectionStatus.variant}
className={connectionStatus.className}
>
{connectionStatus.icon}
<span className="ml-1">{connectionStatus.label}</span>
</Badge>
<Badge variant="outline" className="text-xs">
{agent.status}
</Badge>
</div>
<div className="space-y-2">
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Agent ID:</span>
<span className="font-mono text-xs">{agent.agent_id.substring(0, 12)}...</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Last Updated:</span>
<span className="text-xs">
{formatDistanceToNow(new Date(agent.updated), { addSuffix: true })}
</span>
</div>
</div>
{agent.connection === 'online' && (
<div className="pt-2 border-t">
<div className="flex items-center text-xs text-green-600">
<div className="w-2 h-2 bg-green-600 rounded-full mr-2 animate-pulse"></div>
Active monitoring
</div>
</div>
)}
{agent.connection === 'offline' && (
<div className="pt-2 border-t">
<div className="flex items-center text-xs text-red-600">
<div className="w-2 h-2 bg-red-600 rounded-full mr-2"></div>
Connection lost
</div>
</div>
)}
</CardContent>
</Card>
);
};
@@ -0,0 +1,164 @@
import React, { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Plus, MapPin, Activity, Wifi, WifiOff } from "lucide-react";
import { regionalService } from "@/services/regionalService";
import { RegionalService } from "@/types/regional.types";
import { AddRegionalAgentDialog } from "./AddRegionalAgentDialog";
import { RegionalAgentCard } from "./RegionalAgentCard";
import { useToast } from "@/hooks/use-toast";
export const RegionalMonitoringContent = () => {
const [addDialogOpen, setAddDialogOpen] = useState(false);
const { toast } = useToast();
const queryClient = useQueryClient();
const { data: regionalServices = [], isLoading, error } = useQuery({
queryKey: ['regional-services'],
queryFn: regionalService.getRegionalServices,
refetchInterval: 30000, // Refetch every 30 seconds
});
const handleAgentAdded = () => {
queryClient.invalidateQueries({ queryKey: ['regional-services'] });
toast({
title: "Regional Agent Added",
description: "The regional monitoring agent has been successfully configured.",
});
};
const handleDeleteAgent = async (id: string) => {
try {
await regionalService.deleteRegionalService(id);
queryClient.invalidateQueries({ queryKey: ['regional-services'] });
toast({
title: "Agent Removed",
description: "The regional monitoring agent has been removed.",
});
} catch (error) {
toast({
title: "Error",
description: "Failed to remove the regional monitoring agent.",
variant: "destructive",
});
}
};
const onlineAgents = regionalServices.filter(agent => agent.connection === 'online').length;
const totalAgents = regionalServices.length;
return (
<div className="p-6 space-y-6">
<div className="flex justify-between items-center">
<div>
<h1 className="text-3xl font-bold tracking-tight">Regional Monitoring</h1>
<p className="text-muted-foreground">
Manage distributed monitoring agents across different regions
</p>
</div>
<Button onClick={() => setAddDialogOpen(true)}>
<Plus className="mr-2 h-4 w-4" />
Add Regional Agent
</Button>
</div>
{/* Stats Cards */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Total Agents</CardTitle>
<MapPin className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{totalAgents}</div>
<p className="text-xs text-muted-foreground">
Regional monitoring agents
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Online Agents</CardTitle>
<Wifi className="h-4 w-4 text-green-600" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-green-600">{onlineAgents}</div>
<p className="text-xs text-muted-foreground">
Currently connected
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">Offline Agents</CardTitle>
<WifiOff className="h-4 w-4 text-red-600" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-red-600">{totalAgents - onlineAgents}</div>
<p className="text-xs text-muted-foreground">
Disconnected agents
</p>
</CardContent>
</Card>
</div>
{/* Agents List */}
<div className="space-y-4">
<h2 className="text-xl font-semibold">Regional Agents</h2>
{isLoading ? (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{[...Array(3)].map((_, i) => (
<Card key={i} className="animate-pulse">
<CardHeader>
<div className="h-4 bg-gray-200 rounded w-3/4"></div>
<div className="h-3 bg-gray-200 rounded w-1/2"></div>
</CardHeader>
<CardContent>
<div className="space-y-2">
<div className="h-3 bg-gray-200 rounded"></div>
<div className="h-3 bg-gray-200 rounded w-5/6"></div>
</div>
</CardContent>
</Card>
))}
</div>
) : regionalServices.length === 0 ? (
<Card>
<CardContent className="flex flex-col items-center justify-center py-12">
<MapPin className="h-12 w-12 text-muted-foreground mb-4" />
<h3 className="text-lg font-semibold mb-2">No Regional Agents</h3>
<p className="text-muted-foreground text-center mb-4">
Get started by adding your first regional monitoring agent to extend your monitoring coverage.
</p>
<Button onClick={() => setAddDialogOpen(true)}>
<Plus className="mr-2 h-4 w-4" />
Add First Agent
</Button>
</CardContent>
</Card>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{regionalServices.map((agent) => (
<RegionalAgentCard
key={agent.id}
agent={agent}
onDelete={() => handleDeleteAgent(agent.id)}
/>
))}
</div>
)}
</div>
<AddRegionalAgentDialog
open={addDialogOpen}
onOpenChange={setAddDialogOpen}
onAgentAdded={handleAgentAdded}
/>
</div>
);
};
@@ -0,0 +1,4 @@
export { RegionalMonitoringContent } from './RegionalMonitoringContent';
export { AddRegionalAgentDialog } from './AddRegionalAgentDialog';
export { RegionalAgentCard } from './RegionalAgentCard';
@@ -0,0 +1,38 @@
import React, { useState } from "react";
import { Header } from "@/components/dashboard/Header";
import { Sidebar } from "@/components/dashboard/Sidebar";
import { authService } from "@/services/authService";
import { useNavigate } from "react-router-dom";
import { useSidebar } from "@/contexts/SidebarContext";
import { RegionalMonitoringContent } from "@/components/regional-monitoring/RegionalMonitoringContent";
const RegionalMonitoring = () => {
const { sidebarCollapsed, toggleSidebar } = useSidebar();
const currentUser = authService.getCurrentUser();
const navigate = useNavigate();
const handleLogout = () => {
authService.logout();
navigate("/login");
};
return (
<div className="flex h-screen bg-background text-foreground">
<Sidebar collapsed={sidebarCollapsed} />
<div className="flex flex-col flex-1 overflow-hidden">
<Header
currentUser={currentUser}
onLogout={handleLogout}
sidebarCollapsed={sidebarCollapsed}
toggleSidebar={toggleSidebar}
/>
<div className="flex-1 overflow-auto">
<RegionalMonitoringContent />
</div>
</div>
</div>
);
};
export default RegionalMonitoring;
+198
View File
@@ -0,0 +1,198 @@
import { pb } from '@/lib/pocketbase';
import { RegionalService, CreateRegionalServiceParams, InstallCommand } from '@/types/regional.types';
// Generate a random token
const generateToken = (): string => {
return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
};
// Generate a random agent ID
const generateAgentId = (): string => {
return 'agent_' + Math.random().toString(36).substring(2, 10);
};
export const regionalService = {
async getRegionalServices(): Promise<RegionalService[]> {
try {
const response = await pb.collection('regional_service').getFullList({
sort: '-created',
});
return response.map(record => ({
id: record.id,
region_name: record.region_name,
status: record.status,
agent_id: record.agent_id,
agent_ip_address: record.agent_ip_address,
token: record.token,
connection: record.connection,
created: record.created,
updated: record.updated,
}));
} catch (error) {
console.error('Error fetching regional services:', error);
throw new Error('Failed to fetch regional services');
}
},
async createRegionalService(params: CreateRegionalServiceParams): Promise<{ service: RegionalService; installCommand: InstallCommand }> {
try {
const token = generateToken();
const agentId = generateAgentId();
const data = {
region_name: params.region_name,
status: 'pending',
agent_id: agentId,
agent_ip_address: params.agent_ip_address,
token: token,
connection: 'offline',
};
const record = await pb.collection('regional_service').create(data);
const service: RegionalService = {
id: record.id,
region_name: record.region_name,
status: record.status,
agent_id: record.agent_id,
agent_ip_address: record.agent_ip_address,
token: record.token,
connection: record.connection,
created: record.created,
updated: record.updated,
};
const installCommand: InstallCommand = {
token: token,
agent_id: agentId,
api_endpoint: pb.baseUrl,
bash_script: this.generateBashScript(token, agentId, pb.baseUrl, params.agent_ip_address)
};
return { service, installCommand };
} catch (error) {
console.error('Error creating regional service:', error);
throw new Error('Failed to create regional service');
}
},
async deleteRegionalService(id: string): Promise<void> {
try {
await pb.collection('regional_service').delete(id);
} catch (error) {
console.error('Error deleting regional service:', error);
throw new Error('Failed to delete regional service');
}
},
generateBashScript(token: string, agentId: string, apiEndpoint: string, agentIp: string): string {
return `#!/bin/bash
# CheckCle - Regional Monitoring Agent Installation Script
# Generated on: $(date)
echo "🚀 Installing CheckCle Regional Monitoring Agent..."
echo "======================================================"
# Configuration
AGENT_ID="${agentId}"
TOKEN="${token}"
API_ENDPOINT="${apiEndpoint}"
AGENT_IP="${agentIp}"
INSTALL_DIR="/opt/checkcle-regional-agent"
SERVICE_NAME="checkcle-regional-agent"
# Check if running as root
if [[ $EUID -ne 0 ]]; then
echo "❌ This script must be run as root (use sudo)"
exit 1
fi
# Create installation directory
echo "📁 Creating installation directory..."
mkdir -p $INSTALL_DIR
cd $INSTALL_DIR
# Download the agent binary
echo "📥 Downloading Regional Monitoring Agent..."
wget -O regional-check-agent https://github.com/operacle/distributed-regional-monitoring/releases/latest/download/distributed-regional-check-agent-linux-amd64
# Make it executable
chmod +x regional-check-agent
# Create configuration file
echo "⚙️ Creating configuration file..."
cat > config.yaml << EOF
# CheckCle Regional Monitoring Agent Configuration
agent:
id: "$AGENT_ID"
region: "$(curl -s ipinfo.io/region 2>/dev/null || echo 'Unknown')"
ip_address: "$AGENT_IP"
api:
endpoint: "$API_ENDPOINT"
token: "$TOKEN"
collection: "regional_service"
monitoring:
interval: 30s
timeout: 10s
max_retries: 3
logging:
level: "info"
file: "/var/log/checkcle-regional-agent.log"
EOF
# Create systemd service
echo "🔧 Creating systemd service..."
cat > /etc/systemd/system/$SERVICE_NAME.service << EOF
[Unit]
Description=CheckCle Regional Monitoring Agent
After=network.target
Wants=network.target
[Service]
Type=simple
User=root
WorkingDirectory=$INSTALL_DIR
ExecStart=$INSTALL_DIR/regional-check-agent --config=$INSTALL_DIR/config.yaml
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
EOF
# Enable and start the service
echo "🎯 Enabling and starting the service..."
systemctl daemon-reload
systemctl enable $SERVICE_NAME
systemctl start $SERVICE_NAME
# Check status
echo "✅ Installation completed!"
echo ""
echo "📊 Service Status:"
systemctl status $SERVICE_NAME --no-pager -l
echo ""
echo "🔍 Quick Status Check:"
echo " Agent ID: $AGENT_ID"
echo " API Endpoint: $API_ENDPOINT"
echo " Log file: /var/log/checkcle-regional-agent.log"
echo ""
echo "📝 Useful commands:"
echo " - Check status: systemctl status $SERVICE_NAME"
echo " - View logs: journalctl -u $SERVICE_NAME -f"
echo " - Restart: systemctl restart $SERVICE_NAME"
echo " - Stop: systemctl stop $SERVICE_NAME"
echo ""
echo "🎉 Regional Monitoring Agent is now running!"
`;
}
};
+1 -1
View File
@@ -9,7 +9,7 @@ export const menuTranslations: MenuTranslations = {
scheduleIncident: "Zeitplan & Vorfall",
operationalPage: "Betriebsstatus-Seite",
reports: "Berichte",
apiDocumentation: "API-Dokumentation",
regionalMonitoring: "Regional Monitoring",
// Einstellungen-Panel
settingPanel: "Einstellungsbereich",
generalSettings: "Allgemeine Einstellungen",
+1 -1
View File
@@ -8,7 +8,7 @@ export const menuTranslations: MenuTranslations = {
scheduleIncident: "Schedule & Incident",
operationalPage: "Operational Page",
reports: "Reports",
apiDocumentation: "API Documentation",
regionalMonitoring: "Regional Monitoring",
settingPanel: "Setting Panel",
generalSettings: "General Settings",
userManagement: "User Management",
+2 -2
View File
@@ -8,7 +8,7 @@ export const menuTranslations: MenuTranslations = {
scheduleIncident: "កាលវិភាគនិងឧបទ្ទវហេតុ",
operationalPage: "ទំព័រប្រតិបត្តិការ",
reports: "របាយការណ៍",
apiDocumentation: "ឯកសារ API",
regionalMonitoring: "ការត្រួតពិនិត្យតំបន់",
settingPanel: "ផ្ទាំងការកំណត់",
generalSettings: "ការកំណត់ទូទៅ",
userManagement: "ការគ្រប់គ្រងអ្នកប្រើប្រាស់",
@@ -18,4 +18,4 @@ export const menuTranslations: MenuTranslations = {
dataRetention: "ការរក្សាទុកទិន្នន័យ",
backupSettings: "ការកំណត់បម្រុងទុក",
aboutSystem: "អំពីប្រព័ន្ធ",
};
};
+2 -2
View File
@@ -6,7 +6,7 @@ export interface MenuTranslations {
scheduleIncident: string;
operationalPage: string;
reports: string;
apiDocumentation: string;
regionalMonitoring: string;
settingPanel: string;
generalSettings: string;
userManagement: string;
@@ -16,4 +16,4 @@ export interface MenuTranslations {
dataRetention: string;
backupSettings: string;
aboutSystem: string;
}
}
+24
View File
@@ -0,0 +1,24 @@
export interface RegionalService {
id: string;
region_name: string;
status: string;
agent_id: string;
agent_ip_address: string;
token: string;
connection: "online" | "offline";
created: string;
updated: string;
}
export interface CreateRegionalServiceParams {
region_name: string;
agent_ip_address: string;
}
export interface InstallCommand {
token: string;
agent_id: string;
bash_script: string;
api_endpoint: string;
}