Improved the Server feature History Data
This commit is contained in:
@@ -2,7 +2,7 @@
|
||||
// This file handles realtime notifications in a client-side environment
|
||||
// In a production app, this would be a server-side endpoint
|
||||
|
||||
console.log("API Realtime endpoint loaded");
|
||||
//console.log("API Realtime endpoint loaded");
|
||||
|
||||
// Simple implementation that simulates sending notifications
|
||||
export default async function handler(req) {
|
||||
|
||||
@@ -78,7 +78,7 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
|
||||
// Initialize form data when server changes
|
||||
useEffect(() => {
|
||||
if (server) {
|
||||
console.log("Setting form data for server:", server);
|
||||
// console.log("Setting form data for server:", server);
|
||||
// Parse comma-separated notification_id into array
|
||||
const notificationChannels = server.notification_id
|
||||
? server.notification_id.split(',').map(id => id.trim()).filter(id => id)
|
||||
@@ -109,10 +109,10 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
|
||||
// Load existing threshold data when thresholds are loaded and we have a server with threshold_id
|
||||
useEffect(() => {
|
||||
if (server && server.threshold_id && thresholds.length > 0) {
|
||||
console.log("Loading existing threshold data for server:", server.threshold_id);
|
||||
// console.log("Loading existing threshold data for server:", server.threshold_id);
|
||||
const existingThreshold = thresholds.find(t => t.id === server.threshold_id);
|
||||
if (existingThreshold) {
|
||||
console.log("Found existing threshold:", existingThreshold);
|
||||
// console.log("Found existing threshold:", existingThreshold);
|
||||
setSelectedThreshold(existingThreshold);
|
||||
// Handle the API response format with proper field names and type conversion
|
||||
setThresholdFormData({
|
||||
@@ -166,7 +166,7 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
|
||||
const configs = await alertConfigService.getAlertConfigurations();
|
||||
setAlertConfigs(configs);
|
||||
} catch (error) {
|
||||
console.error('Error loading alert configurations:', error);
|
||||
// console.error('Error loading alert configurations:', error);
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
@@ -183,7 +183,7 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
|
||||
const templateList = await templateService.getTemplates();
|
||||
setTemplates(templateList);
|
||||
} catch (error) {
|
||||
console.error('Error loading templates:', error);
|
||||
// console.error('Error loading templates:', error);
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
@@ -200,7 +200,7 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
|
||||
const thresholdList = await serverThresholdService.getServerThresholds();
|
||||
setThresholds(thresholdList);
|
||||
} catch (error) {
|
||||
console.error('Error loading server thresholds:', error);
|
||||
// console.error('Error loading server thresholds:', error);
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
@@ -243,7 +243,7 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
|
||||
description: "Server threshold values have been updated successfully.",
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error updating threshold:', error);
|
||||
// console.error('Error updating threshold:', error);
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
@@ -301,7 +301,7 @@ export const EditServerDialog: React.FC<EditServerDialogProps> = ({
|
||||
onOpenChange(false);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error updating server:', error);
|
||||
// console.error('Error updating server:', error);
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
|
||||
@@ -24,7 +24,7 @@ export const ServerHistoryCharts = ({ serverId }: ServerHistoryChartsProps) => {
|
||||
isFetching
|
||||
} = useServerHistoryData(serverId);
|
||||
|
||||
console.log('ServerHistoryCharts: Rendering with serverId:', serverId, 'timeRange:', timeRange);
|
||||
// console.log('ServerHistoryCharts: Rendering with serverId:', serverId, 'timeRange:', timeRange);
|
||||
|
||||
// Memoize latest data calculation to prevent unnecessary recalculations
|
||||
const latestData = useMemo(() => {
|
||||
@@ -71,7 +71,7 @@ export const ServerHistoryCharts = ({ serverId }: ServerHistoryChartsProps) => {
|
||||
}
|
||||
|
||||
if (error) {
|
||||
console.error('ServerHistoryCharts: Error loading data:', error);
|
||||
// console.error('ServerHistoryCharts: Error loading data:', error);
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
@@ -122,7 +122,7 @@ export const ServerHistoryCharts = ({ serverId }: ServerHistoryChartsProps) => {
|
||||
);
|
||||
}
|
||||
|
||||
console.log('ServerHistoryCharts: Rendering charts with', chartData.length, 'data points for time range:', timeRange);
|
||||
// console.log('ServerHistoryCharts: Rendering charts with', chartData.length, 'data points for time range:', timeRange);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
|
||||
@@ -59,39 +59,26 @@ export const ServerTable = ({ servers, isLoading, onRefresh }: ServerTableProps)
|
||||
try {
|
||||
setPausingServers(prev => new Set(prev).add(serverId));
|
||||
|
||||
if (isPaused) {
|
||||
// Resume monitoring
|
||||
await pb.collection('servers').update(serverId, {
|
||||
status: "up",
|
||||
last_checked: new Date().toISOString()
|
||||
});
|
||||
|
||||
toast({
|
||||
title: "Server resumed",
|
||||
description: `Monitoring resumed for ${server.name}`,
|
||||
});
|
||||
|
||||
console.log(`Resume server monitoring: ${serverId}`);
|
||||
} else {
|
||||
// Pause monitoring
|
||||
await pb.collection('servers').update(serverId, {
|
||||
status: "paused",
|
||||
last_checked: new Date().toISOString()
|
||||
});
|
||||
|
||||
toast({
|
||||
title: "Server paused",
|
||||
description: `Monitoring paused for ${server.name}`,
|
||||
});
|
||||
|
||||
console.log(`Pause server monitoring: ${serverId}`);
|
||||
}
|
||||
// Only update the status field, preserving all other server configuration
|
||||
const updateData = {
|
||||
status: isPaused ? "up" : "paused",
|
||||
last_checked: new Date().toISOString()
|
||||
};
|
||||
|
||||
await pb.collection('servers').update(serverId, updateData);
|
||||
|
||||
toast({
|
||||
title: isPaused ? "Server resumed" : "Server paused",
|
||||
description: `Monitoring ${isPaused ? 'resumed' : 'paused'} for ${server.name}`,
|
||||
});
|
||||
|
||||
// console.log(`${isPaused ? 'Resume' : 'Pause'} server monitoring: ${serverId}`);
|
||||
|
||||
// Refresh the server list to show updated status
|
||||
onRefresh();
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error updating server status:', error);
|
||||
// console.error('Error updating server status:', error);
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
@@ -138,7 +125,7 @@ export const ServerTable = ({ servers, isLoading, onRefresh }: ServerTableProps)
|
||||
setSelectedServer(null);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error deleting server:', error);
|
||||
// console.error('Error deleting server:', error);
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
|
||||
@@ -50,21 +50,21 @@ export const timeRangeOptions = [
|
||||
|
||||
export const filterMetricsByTimeRange = (metrics: any[], timeRange: TimeRange): any[] => {
|
||||
if (!metrics?.length) {
|
||||
console.log('🔍 filterMetricsByTimeRange: No metrics provided');
|
||||
// console.log('🔍 filterMetricsByTimeRange: No metrics provided');
|
||||
return [];
|
||||
}
|
||||
|
||||
console.log('🔍 filterMetricsByTimeRange: Starting with', metrics.length, 'metrics for', timeRange);
|
||||
//console.log('🔍 filterMetricsByTimeRange: Starting with', metrics.length, 'metrics for', timeRange);
|
||||
|
||||
const now = new Date();
|
||||
|
||||
// For 60m, let's be very specific about what we're looking for
|
||||
if (timeRange === '60m') {
|
||||
console.log('⏰ 60m filter: Current time:', now.toISOString());
|
||||
// console.log('⏰ 60m filter: Current time:', now.toISOString());
|
||||
|
||||
// Try exact 60 minutes first
|
||||
const cutoffTime60m = new Date(now.getTime() - (60 * 60 * 1000));
|
||||
console.log('⏰ 60m filter: Cutoff time:', cutoffTime60m.toISOString());
|
||||
// console.log('⏰ 60m filter: Cutoff time:', cutoffTime60m.toISOString());
|
||||
|
||||
const filtered60m = metrics.filter(metric => {
|
||||
const metricTime = new Date(metric.created || metric.timestamp);
|
||||
@@ -72,17 +72,17 @@ export const filterMetricsByTimeRange = (metrics: any[], timeRange: TimeRange):
|
||||
|
||||
if (!isWithinRange) {
|
||||
const ageMinutes = Math.round((now.getTime() - metricTime.getTime()) / (1000 * 60));
|
||||
console.log('⏰ Excluding record:', {
|
||||
created: metric.created || metric.timestamp,
|
||||
ageMinutes: ageMinutes,
|
||||
reason: ageMinutes > 60 ? 'too old' : 'future date'
|
||||
});
|
||||
// console.log('⏰ Excluding record:', {
|
||||
// created: metric.created || metric.timestamp,
|
||||
// ageMinutes: ageMinutes,
|
||||
// reason: ageMinutes > 60 ? 'too old' : 'future date'
|
||||
// });
|
||||
}
|
||||
|
||||
return isWithinRange;
|
||||
});
|
||||
|
||||
console.log('✅ 60m strict filter result:', filtered60m.length, 'records');
|
||||
// console.log('✅ 60m strict filter result:', filtered60m.length, 'records');
|
||||
|
||||
if (filtered60m.length > 0) {
|
||||
return filtered60m.sort((a, b) =>
|
||||
@@ -91,18 +91,18 @@ export const filterMetricsByTimeRange = (metrics: any[], timeRange: TimeRange):
|
||||
}
|
||||
|
||||
// If no data in exactly 60m, show what we have and return it anyway for debugging
|
||||
console.log('⚠️ No data in 60m range, showing all available data ages:');
|
||||
// console.log('⚠️ No data in 60m range, showing all available data ages:');
|
||||
metrics.forEach((metric, index) => {
|
||||
const metricTime = new Date(metric.created || metric.timestamp);
|
||||
const ageMinutes = Math.round((now.getTime() - metricTime.getTime()) / (1000 * 60));
|
||||
console.log(`Record ${index}: ${metric.created || metric.timestamp} (${ageMinutes} minutes ago)`);
|
||||
// console.log(`Record ${index}: ${metric.created || metric.timestamp} (${ageMinutes} minutes ago)`);
|
||||
});
|
||||
|
||||
// Return the most recent data regardless of age
|
||||
const sorted = metrics.sort((a, b) =>
|
||||
new Date(b.created || b.timestamp).getTime() - new Date(a.created || a.timestamp).getTime()
|
||||
);
|
||||
console.log('🔄 Returning most recent available data for 60m view');
|
||||
// console.log('🔄 Returning most recent available data for 60m view');
|
||||
return sorted.slice(0, 20); // Show last 20 records
|
||||
}
|
||||
|
||||
@@ -117,7 +117,7 @@ export const filterMetricsByTimeRange = (metrics: any[], timeRange: TimeRange):
|
||||
return metricTime >= cutoffTime && metricTime <= now;
|
||||
});
|
||||
|
||||
console.log('✅ Filtered', metrics.length, 'to', filtered.length, 'metrics for', timeRange);
|
||||
// console.log('✅ Filtered', metrics.length, 'to', filtered.length, 'metrics for', timeRange);
|
||||
|
||||
return filtered.sort((a, b) =>
|
||||
new Date(a.created || a.timestamp).getTime() - new Date(b.created || b.timestamp).getTime()
|
||||
@@ -174,27 +174,27 @@ const formatTimestamp = (timestamp: string, timeRange: TimeRange): string => {
|
||||
};
|
||||
|
||||
export const formatChartData = (metrics: any[], timeRange: TimeRange) => {
|
||||
console.log('📊 formatChartData: Processing', {
|
||||
inputCount: metrics?.length || 0,
|
||||
timeRange,
|
||||
sampleMetric: metrics?.[0] ? {
|
||||
id: metrics[0].id,
|
||||
created: metrics[0].created,
|
||||
timestamp: metrics[0].timestamp,
|
||||
server_id: metrics[0].server_id
|
||||
} : null
|
||||
});
|
||||
// console.log('📊 formatChartData: Processing', {
|
||||
// inputCount: metrics?.length || 0,
|
||||
// timeRange,
|
||||
// sampleMetric: metrics?.[0] ? {
|
||||
// id: metrics[0].id,
|
||||
// created: metrics[0].created,
|
||||
// timestamp: metrics[0].timestamp,
|
||||
// server_id: metrics[0].server_id
|
||||
// } : null
|
||||
// });
|
||||
|
||||
if (!metrics?.length) {
|
||||
console.log('❌ formatChartData: No metrics provided');
|
||||
// console.log('❌ formatChartData: No metrics provided');
|
||||
return [];
|
||||
}
|
||||
|
||||
const filteredMetrics = filterMetricsByTimeRange(metrics, timeRange);
|
||||
console.log('📊 formatChartData: After time filtering:', filteredMetrics?.length || 0, 'metrics');
|
||||
// console.log('📊 formatChartData: After time filtering:', filteredMetrics?.length || 0, 'metrics');
|
||||
|
||||
if (!filteredMetrics.length) {
|
||||
console.log('❌ formatChartData: No metrics after time filtering');
|
||||
// console.log('❌ formatChartData: No metrics after time filtering');
|
||||
return [];
|
||||
}
|
||||
|
||||
@@ -213,7 +213,7 @@ export const formatChartData = (metrics: any[], timeRange: TimeRange) => {
|
||||
? filteredMetrics.filter((_, index) => index % Math.ceil(filteredMetrics.length / maxDataPoints) === 0)
|
||||
: filteredMetrics;
|
||||
|
||||
console.log('📊 formatChartData: After sampling:', sampledMetrics.length, 'metrics for display');
|
||||
// console.log('📊 formatChartData: After sampling:', sampledMetrics.length, 'metrics for display');
|
||||
|
||||
const formattedData = sampledMetrics.map((metric) => {
|
||||
const cpuUsage = typeof metric.cpu_usage === 'string' ?
|
||||
@@ -269,6 +269,6 @@ export const formatChartData = (metrics: any[], timeRange: TimeRange) => {
|
||||
};
|
||||
});
|
||||
|
||||
console.log('✅ formatChartData: Final formatted data count:', formattedData.length);
|
||||
// console.log('✅ formatChartData: Final formatted data count:', formattedData.length);
|
||||
return formattedData;
|
||||
};
|
||||
@@ -7,7 +7,7 @@ import { formatChartData } from "../dataUtils";
|
||||
type TimeRange = '60m' | '1d' | '7d' | '1m' | '3m';
|
||||
|
||||
export const useServerHistoryData = (serverId: string) => {
|
||||
const [timeRange, setTimeRange] = useState<TimeRange>("1d");
|
||||
const [timeRange, setTimeRange] = useState<TimeRange>("60m");
|
||||
|
||||
const {
|
||||
data: metrics = [],
|
||||
|
||||
@@ -29,7 +29,7 @@ const ContainerMonitoring = () => {
|
||||
});
|
||||
const [currentUser, setCurrentUser] = useState(authService.getCurrentUser());
|
||||
|
||||
console.log('ContainerMonitoring component loaded with serverId:', serverId);
|
||||
// console.log('ContainerMonitoring component loaded with serverId:', serverId);
|
||||
|
||||
const {
|
||||
data: containers = [],
|
||||
@@ -39,26 +39,26 @@ const ContainerMonitoring = () => {
|
||||
} = useQuery({
|
||||
queryKey: ['docker-containers', serverId],
|
||||
queryFn: () => {
|
||||
console.log('Query function called with serverId:', serverId);
|
||||
// console.log('Query function called with serverId:', serverId);
|
||||
return serverId ? dockerService.getContainersByServerId(serverId) : dockerService.getContainers();
|
||||
},
|
||||
refetchInterval: 30000 // Refetch every 30 seconds
|
||||
});
|
||||
|
||||
console.log('Query state:', { containers, isLoading, error });
|
||||
// console.log('Query state:', { containers, isLoading, error });
|
||||
|
||||
useEffect(() => {
|
||||
console.log('Containers changed:', containers);
|
||||
// console.log('Containers changed:', containers);
|
||||
if (containers.length > 0) {
|
||||
dockerService.getContainerStats(containers).then(newStats => {
|
||||
console.log('Stats calculated:', newStats);
|
||||
// console.log('Stats calculated:', newStats);
|
||||
setStats(newStats);
|
||||
});
|
||||
}
|
||||
}, [containers]);
|
||||
|
||||
const handleRefresh = () => {
|
||||
console.log('Manual refresh triggered');
|
||||
// console.log('Manual refresh triggered');
|
||||
refetch();
|
||||
};
|
||||
|
||||
@@ -72,7 +72,7 @@ const ContainerMonitoring = () => {
|
||||
};
|
||||
|
||||
if (error) {
|
||||
console.error('Container monitoring error:', error);
|
||||
// console.error('Container monitoring error:', error);
|
||||
return (
|
||||
<div className="flex h-screen overflow-hidden bg-background text-foreground">
|
||||
<Sidebar collapsed={sidebarCollapsed} />
|
||||
|
||||
@@ -22,7 +22,7 @@ const ServerDetail = () => {
|
||||
const { sidebarCollapsed, toggleSidebar } = useSidebar();
|
||||
const [currentUser, setCurrentUser] = useState(authService.getCurrentUser());
|
||||
|
||||
console.log('ServerDetail component loaded with serverId:', serverId);
|
||||
//console.log('ServerDetail component loaded with serverId:', serverId);
|
||||
|
||||
const {
|
||||
data: server,
|
||||
@@ -48,7 +48,7 @@ const ServerDetail = () => {
|
||||
systemInfo = JSON.parse(server.system_info);
|
||||
} catch (error) {
|
||||
// If JSON parsing fails, treat it as plain text
|
||||
console.log('system_info is plain text:', server.system_info);
|
||||
// console.log('system_info is plain text:', server.system_info);
|
||||
systemInfoText = server.system_info.toLowerCase();
|
||||
}
|
||||
} else {
|
||||
@@ -64,7 +64,7 @@ const ServerDetail = () => {
|
||||
// Combine all OS information for detection
|
||||
const combinedOSInfo = `${osFromJson} ${osFromText} ${osFromType}`.toLowerCase();
|
||||
|
||||
console.log('OS detection info:', { osFromJson, osFromText, osFromType, combinedOSInfo });
|
||||
// console.log('OS detection info:', { osFromJson, osFromText, osFromType, combinedOSInfo });
|
||||
|
||||
// Check for specific OS distributions first (most specific to least specific)
|
||||
if (combinedOSInfo.includes('ubuntu')) {
|
||||
|
||||
@@ -5,25 +5,25 @@ import { DockerContainer, DockerMetrics, DockerStats } from "@/types/docker.type
|
||||
class DockerService {
|
||||
async getContainers(): Promise<DockerContainer[]> {
|
||||
try {
|
||||
console.log('Fetching all Docker containers...');
|
||||
// console.log('Fetching all Docker containers...');
|
||||
const records = await pb.collection('dockers').getFullList({
|
||||
sort: '-created',
|
||||
});
|
||||
console.log('Docker containers fetched:', records);
|
||||
// console.log('Docker containers fetched:', records);
|
||||
return records as DockerContainer[];
|
||||
} catch (error) {
|
||||
console.error('Error fetching Docker containers:', error);
|
||||
// console.error('Error fetching Docker containers:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async getContainersByServerId(serverId: string): Promise<DockerContainer[]> {
|
||||
try {
|
||||
console.log('Fetching Docker containers for server ID:', serverId);
|
||||
// console.log('Fetching Docker containers for server ID:', serverId);
|
||||
|
||||
// First, try to get the server details to find the correct hostname
|
||||
const server = await pb.collection('servers').getOne(serverId);
|
||||
console.log('Server details:', server);
|
||||
// console.log('Server details:', server);
|
||||
|
||||
// Try multiple filter approaches to find containers
|
||||
const filters = [
|
||||
@@ -36,57 +36,57 @@ class DockerService {
|
||||
let containers: DockerContainer[] = [];
|
||||
|
||||
for (const filter of filters) {
|
||||
console.log('Trying filter:', filter);
|
||||
// console.log('Trying filter:', filter);
|
||||
try {
|
||||
const records = await pb.collection('dockers').getFullList({
|
||||
filter: filter,
|
||||
sort: '-created',
|
||||
});
|
||||
console.log(`Filter "${filter}" returned:`, records);
|
||||
// console.log(`Filter "${filter}" returned:`, records);
|
||||
|
||||
if (records.length > 0) {
|
||||
containers = records as DockerContainer[];
|
||||
break;
|
||||
}
|
||||
} catch (filterError) {
|
||||
console.warn(`Filter "${filter}" failed:`, filterError);
|
||||
// console.warn(`Filter "${filter}" failed:`, filterError);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// If no containers found with filters, get all and log for debugging
|
||||
if (containers.length === 0) {
|
||||
console.log('No containers found with filters, fetching all for debugging...');
|
||||
// console.log('No containers found with filters, fetching all for debugging...');
|
||||
const allContainers = await pb.collection('dockers').getFullList({
|
||||
sort: '-created',
|
||||
});
|
||||
console.log('All available Docker containers:', allContainers);
|
||||
console.log('Looking for containers that might match server:', {
|
||||
serverId,
|
||||
serverHostname: server.hostname,
|
||||
serverIp: server.ip_address
|
||||
});
|
||||
// console.log('All available Docker containers:', allContainers);
|
||||
// console.log('Looking for containers that might match server:', {
|
||||
//// serverId,
|
||||
// serverHostname: server.hostname,
|
||||
// serverIp: server.ip_address
|
||||
// });
|
||||
}
|
||||
|
||||
return containers;
|
||||
} catch (error) {
|
||||
console.error('Error fetching Docker containers by server ID:', error);
|
||||
// console.error('Error fetching Docker containers by server ID:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async getContainerMetrics(dockerId: string): Promise<DockerMetrics[]> {
|
||||
try {
|
||||
console.log('Fetching metrics for docker ID:', dockerId);
|
||||
// console.log('Fetching metrics for docker ID:', dockerId);
|
||||
const records = await pb.collection('docker_metrics').getFullList({
|
||||
filter: `docker_id = "${dockerId}"`,
|
||||
sort: '-timestamp',
|
||||
perPage: 100,
|
||||
});
|
||||
console.log('Docker metrics fetched:', records);
|
||||
// console.log('Docker metrics fetched:', records);
|
||||
return records as DockerMetrics[];
|
||||
} catch (error) {
|
||||
console.error('Error fetching Docker metrics:', error);
|
||||
// console.error('Error fetching Docker metrics:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ export const serverService = {
|
||||
const records = await pb.collection('servers').getFullList<Server>();
|
||||
return records;
|
||||
} catch (error) {
|
||||
console.error('Error fetching servers:', error);
|
||||
// console.error('Error fetching servers:', error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
@@ -17,48 +17,48 @@ export const serverService = {
|
||||
const record = await pb.collection('servers').getOne<Server>(serverId);
|
||||
return record;
|
||||
} catch (error) {
|
||||
console.error('Error fetching server:', error);
|
||||
// console.error('Error fetching server:', error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
async getServerMetrics(serverId: string, timeRange?: string): Promise<any[]> {
|
||||
try {
|
||||
console.log('🔍 serverService.getServerMetrics: Starting with serverId:', serverId, 'timeRange:', timeRange);
|
||||
// console.log('🔍 serverService.getServerMetrics: Starting with serverId:', serverId, 'timeRange:', timeRange);
|
||||
|
||||
// First, get the server to find the correct server_id for metrics
|
||||
let server;
|
||||
try {
|
||||
server = await this.getServer(serverId);
|
||||
console.log('✅ serverService.getServerMetrics: Found server:', {
|
||||
id: server.id,
|
||||
server_id: server.server_id,
|
||||
name: server.name
|
||||
});
|
||||
// console.log('✅ serverService.getServerMetrics: Found server:', {
|
||||
// id: server.id,
|
||||
// server_id: server.server_id,
|
||||
// name: server.name
|
||||
// });
|
||||
} catch (error) {
|
||||
console.log('❌ serverService.getServerMetrics: Could not fetch server details:', error);
|
||||
// console.log('❌ serverService.getServerMetrics: Could not fetch server details:', error);
|
||||
}
|
||||
|
||||
// Let's first check what data exists in the database for this server
|
||||
console.log('🔍 Checking all records for this server...');
|
||||
// console.log('🔍 Checking all records for this server...');
|
||||
const allServerRecords = await pb.collection('server_metrics').getFullList({
|
||||
filter: `server_id = "${serverId}" || server_id = "${server?.server_id}" || server_id = "${server?.id}"`,
|
||||
sort: '-created',
|
||||
requestKey: null
|
||||
});
|
||||
|
||||
console.log('📊 Found total records for server:', allServerRecords.length);
|
||||
// console.log('📊 Found total records for server:', allServerRecords.length);
|
||||
if (allServerRecords.length > 0) {
|
||||
console.log('📅 Date range of all records:', {
|
||||
newest: allServerRecords[0]?.created,
|
||||
oldest: allServerRecords[allServerRecords.length - 1]?.created
|
||||
});
|
||||
// console.log('📅 Date range of all records:', {
|
||||
// newest: allServerRecords[0]?.created,
|
||||
// oldest: allServerRecords[allServerRecords.length - 1]?.created
|
||||
// });
|
||||
|
||||
// Check last 5 records
|
||||
console.log('🔄 Last 5 records timestamps:', allServerRecords.slice(0, 5).map(r => ({
|
||||
created: r.created,
|
||||
age_minutes: Math.round((new Date().getTime() - new Date(r.created).getTime()) / (1000 * 60))
|
||||
})));
|
||||
// console.log('🔄 Last 5 records timestamps:', allServerRecords.slice(0, 5).map(r => ({
|
||||
// created: r.created,
|
||||
// age_minutes: Math.round((new Date().getTime() - new Date(r.created).getTime()) / (1000 * 60))
|
||||
// })));
|
||||
}
|
||||
|
||||
// Calculate time range for filtering
|
||||
@@ -67,9 +67,9 @@ export const serverService = {
|
||||
|
||||
if (timeRange === '60m') {
|
||||
cutoffTime = new Date(now.getTime() - (60 * 60 * 1000)); // Exactly 60 minutes
|
||||
console.log('⏰ 60m filter: Looking for records newer than:', cutoffTime.toISOString());
|
||||
console.log('⏰ Current time:', now.toISOString());
|
||||
console.log('⏰ Time difference in minutes:', Math.round((now.getTime() - cutoffTime.getTime()) / (1000 * 60)));
|
||||
// console.log('⏰ 60m filter: Looking for records newer than:', cutoffTime.toISOString());
|
||||
// console.log('⏰ Current time:', now.toISOString());
|
||||
// console.log('⏰ Time difference in minutes:', Math.round((now.getTime() - cutoffTime.getTime()) / (1000 * 60)));
|
||||
} else if (timeRange === '1d') {
|
||||
cutoffTime = new Date(now.getTime() - (24 * 60 * 60 * 1000));
|
||||
} else if (timeRange === '7d') {
|
||||
@@ -96,7 +96,7 @@ export const serverService = {
|
||||
const cutoffISO = cutoffTime.toISOString();
|
||||
const filter = `server_id = "${strategy}" && created >= "${cutoffISO}"`;
|
||||
|
||||
console.log(`🔍 Trying filter: ${filter}`);
|
||||
// console.log(`🔍 Trying filter: ${filter}`);
|
||||
|
||||
const records = await pb.collection('server_metrics').getFullList({
|
||||
filter: filter,
|
||||
@@ -104,22 +104,22 @@ export const serverService = {
|
||||
requestKey: null
|
||||
});
|
||||
|
||||
console.log(`📊 Strategy "${strategy}" found ${records.length} records within time range`);
|
||||
// console.log(`📊 Strategy "${strategy}" found ${records.length} records within time range`);
|
||||
|
||||
if (records.length > 0) {
|
||||
filteredRecords = records;
|
||||
console.log('✅ Using records from strategy:', strategy);
|
||||
// console.log('✅ Using records from strategy:', strategy);
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`❌ Error with strategy ${strategy}:`, error);
|
||||
// console.error(`❌ Error with strategy ${strategy}:`, error);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// If no filtered records found and it's 60m, let's see what we have in a larger window
|
||||
if (filteredRecords.length === 0 && timeRange === '60m') {
|
||||
console.log('⚠️ No records found in 60m window, checking last 24 hours...');
|
||||
// console.log('⚠️ No records found in 60m window, checking last 24 hours...');
|
||||
|
||||
const last24h = new Date(now.getTime() - (24 * 60 * 60 * 1000));
|
||||
|
||||
@@ -133,35 +133,35 @@ export const serverService = {
|
||||
requestKey: null
|
||||
});
|
||||
|
||||
console.log(`📊 Last 24h check for "${strategy}": ${records.length} records`);
|
||||
// console.log(`📊 Last 24h check for "${strategy}": ${records.length} records`);
|
||||
|
||||
if (records.length > 0) {
|
||||
console.log('📅 Sample record ages (minutes ago):', records.slice(0, 3).map(r =>
|
||||
Math.round((now.getTime() - new Date(r.created).getTime()) / (1000 * 60))
|
||||
));
|
||||
// console.log('📅 Sample record ages (minutes ago):', records.slice(0, 3).map(r =>
|
||||
// Math.round((now.getTime() - new Date(r.created).getTime()) / (1000 * 60))
|
||||
// ));
|
||||
|
||||
// Return all recent records for 60m if we have any
|
||||
filteredRecords = records;
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`❌ Error with 24h fallback for ${strategy}:`, error);
|
||||
// console.error(`❌ Error with 24h fallback for ${strategy}:`, error);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log('🎯 Final result:', filteredRecords.length, 'records found for', timeRange);
|
||||
// console.log('🎯 Final result:', filteredRecords.length, 'records found for', timeRange);
|
||||
if (filteredRecords.length > 0) {
|
||||
console.log('📅 Returned records age range (minutes ago):', {
|
||||
newest: Math.round((now.getTime() - new Date(filteredRecords[0].created).getTime()) / (1000 * 60)),
|
||||
oldest: Math.round((now.getTime() - new Date(filteredRecords[filteredRecords.length - 1].created).getTime()) / (1000 * 60))
|
||||
});
|
||||
// console.log('📅 Returned records age range (minutes ago):', {
|
||||
// newest: Math.round((now.getTime() - new Date(filteredRecords[0].created).getTime()) / (1000 * 60)),
|
||||
// oldest: Math.round((now.getTime() - new Date(filteredRecords[filteredRecords.length - 1].created).getTime()) / (1000 * 60))
|
||||
// });
|
||||
}
|
||||
|
||||
return filteredRecords;
|
||||
} catch (error) {
|
||||
console.error('❌ Error fetching server metrics:', error);
|
||||
// console.error('❌ Error fetching server metrics:', error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
@@ -23,62 +23,62 @@ export interface CreateUpdateServerThresholdData {
|
||||
export const serverThresholdService = {
|
||||
async getServerThresholds(): Promise<ServerThreshold[]> {
|
||||
try {
|
||||
console.log("Fetching server threshold templates");
|
||||
// console.log("Fetching server threshold templates");
|
||||
const response = await pb.collection('server_threshold_templates').getList(1, 50, {
|
||||
sort: '-created',
|
||||
});
|
||||
console.log("Server threshold templates response:", response);
|
||||
// console.log("Server threshold templates response:", response);
|
||||
return response.items as unknown as ServerThreshold[];
|
||||
} catch (error) {
|
||||
console.error("Error fetching server threshold templates:", error);
|
||||
// console.error("Error fetching server threshold templates:", error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
async getServerThreshold(id: string): Promise<ServerThreshold> {
|
||||
try {
|
||||
console.log(`Fetching server threshold template with id: ${id}`);
|
||||
// console.log(`Fetching server threshold template with id: ${id}`);
|
||||
const response = await pb.collection('server_threshold_templates').getOne(id);
|
||||
console.log("Server threshold template response:", response);
|
||||
// console.log("Server threshold template response:", response);
|
||||
return response as unknown as ServerThreshold;
|
||||
} catch (error) {
|
||||
console.error(`Error fetching server threshold template with id ${id}:`, error);
|
||||
// console.error(`Error fetching server threshold template with id ${id}:`, error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
async createServerThreshold(data: CreateUpdateServerThresholdData): Promise<ServerThreshold> {
|
||||
try {
|
||||
console.log("Creating new server threshold template with data:", data);
|
||||
// console.log("Creating new server threshold template with data:", data);
|
||||
const response = await pb.collection('server_threshold_templates').create(data);
|
||||
console.log("Create server threshold template response:", response);
|
||||
// console.log("Create server threshold template response:", response);
|
||||
return response as unknown as ServerThreshold;
|
||||
} catch (error) {
|
||||
console.error("Error creating server threshold template:", error);
|
||||
// console.error("Error creating server threshold template:", error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
async updateServerThreshold(id: string, data: Partial<CreateUpdateServerThresholdData>): Promise<ServerThreshold> {
|
||||
try {
|
||||
console.log(`Updating server threshold template with id: ${id}`, data);
|
||||
// console.log(`Updating server threshold template with id: ${id}`, data);
|
||||
const response = await pb.collection('server_threshold_templates').update(id, data);
|
||||
console.log("Update server threshold template response:", response);
|
||||
// console.log("Update server threshold template response:", response);
|
||||
return response as unknown as ServerThreshold;
|
||||
} catch (error) {
|
||||
console.error(`Error updating server threshold template with id ${id}:`, error);
|
||||
// console.error(`Error updating server threshold template with id ${id}:`, error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
async deleteServerThreshold(id: string): Promise<boolean> {
|
||||
try {
|
||||
console.log(`Deleting server threshold template with id: ${id}`);
|
||||
// console.log(`Deleting server threshold template with id: ${id}`);
|
||||
await pb.collection('server_threshold_templates').delete(id);
|
||||
console.log("Server threshold template deleted successfully");
|
||||
// console.log("Server threshold template deleted successfully");
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error(`Error deleting server threshold template with id ${id}:`, error);
|
||||
// console.error(`Error deleting server threshold template with id ${id}:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,62 +38,62 @@ export interface CreateUpdateTemplateData {
|
||||
export const templateService = {
|
||||
async getTemplates(): Promise<NotificationTemplate[]> {
|
||||
try {
|
||||
console.log("Fetching server notification templates");
|
||||
// console.log("Fetching server notification templates");
|
||||
const response = await pb.collection('server_notification_templates').getList(1, 50, {
|
||||
sort: '-created',
|
||||
});
|
||||
console.log("Server templates response:", response);
|
||||
// console.log("Server templates response:", response);
|
||||
return response.items as unknown as NotificationTemplate[];
|
||||
} catch (error) {
|
||||
console.error("Error fetching server templates:", error);
|
||||
// console.error("Error fetching server templates:", error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
async getTemplate(id: string): Promise<NotificationTemplate> {
|
||||
try {
|
||||
console.log(`Fetching server template with id: ${id}`);
|
||||
// console.log(`Fetching server template with id: ${id}`);
|
||||
const response = await pb.collection('server_notification_templates').getOne(id);
|
||||
console.log("Server template response:", response);
|
||||
// console.log("Server template response:", response);
|
||||
return response as unknown as NotificationTemplate;
|
||||
} catch (error) {
|
||||
console.error(`Error fetching server template with id ${id}:`, error);
|
||||
// console.error(`Error fetching server template with id ${id}:`, error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
async createTemplate(data: CreateUpdateTemplateData): Promise<NotificationTemplate> {
|
||||
try {
|
||||
console.log("Creating new server template with data:", data);
|
||||
// console.log("Creating new server template with data:", data);
|
||||
const response = await pb.collection('server_notification_templates').create(data);
|
||||
console.log("Create server template response:", response);
|
||||
// console.log("Create server template response:", response);
|
||||
return response as unknown as NotificationTemplate;
|
||||
} catch (error) {
|
||||
console.error("Error creating server template:", error);
|
||||
// console.error("Error creating server template:", error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
async updateTemplate(id: string, data: Partial<CreateUpdateTemplateData>): Promise<NotificationTemplate> {
|
||||
try {
|
||||
console.log(`Updating server template with id: ${id}`, data);
|
||||
// console.log(`Updating server template with id: ${id}`, data);
|
||||
const response = await pb.collection('server_notification_templates').update(id, data);
|
||||
console.log("Update server template response:", response);
|
||||
// console.log("Update server template response:", response);
|
||||
return response as unknown as NotificationTemplate;
|
||||
} catch (error) {
|
||||
console.error(`Error updating server template with id ${id}:`, error);
|
||||
// console.error(`Error updating server template with id ${id}:`, error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
async deleteTemplate(id: string): Promise<boolean> {
|
||||
try {
|
||||
console.log(`Deleting server template with id: ${id}`);
|
||||
// console.log(`Deleting server template with id: ${id}`);
|
||||
await pb.collection('server_notification_templates').delete(id);
|
||||
console.log("Server template deleted successfully");
|
||||
// console.log("Server template deleted successfully");
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error(`Error deleting server template with id ${id}:`, error);
|
||||
// console.error(`Error deleting server template with id ${id}:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user