Compare commits

...

63 Commits

Author SHA1 Message Date
47b4e6e182 Fix bug with VM name showing as filter 2025-03-02 18:38:31 -05:00
acfd2554b0 Fix bug with selected VM 2025-03-02 17:55:42 -05:00
8d1028ab47 Add way to clear localstorage of last VM 2025-03-02 17:52:23 -05:00
e26c5defa4 URL-less VM view and persistence 2025-03-02 17:46:37 -05:00
61dbe8eed1 Make Node selection persistent 2025-03-02 17:37:20 -05:00
779dbe1632 Add health messages for nodes 2025-03-02 17:31:08 -05:00
e6da8ec2c0 Fix up colour of collapsed section title 2025-03-02 17:11:51 -05:00
e11217e28a Unify and clean up position styling 2025-03-02 17:06:47 -05:00
4ca93fcc9a Further adjust spacing to be perfect 2025-03-02 16:52:52 -05:00
0200df7b16 Fix up Node page styling 2025-03-02 16:38:09 -05:00
d581d17273 Clean up styling and organize components 2025-03-02 15:56:52 -05:00
5b691d0e5b Add more search bar features 2025-03-02 15:07:35 -05:00
745d554768 Fix search bar behaviour (step 9) 2025-03-02 14:56:51 -05:00
804f049111 Fix search bar behaviour (step 8) 2025-03-02 14:46:05 -05:00
4a97f365b0 Fix search bar behaviour (step 7) 2025-03-02 14:43:55 -05:00
cb27e81b7c Fix search bar behaviour (step 6) 2025-03-02 14:42:25 -05:00
1d26e0338f Fix search bar behaviour (step 5) 2025-03-02 14:38:43 -05:00
c1ddbd1f3f Fix search bar behaviour (step 4) 2025-03-02 14:35:18 -05:00
99372fdfe8 Fix search bar behaviour (step 3) 2025-03-02 14:32:44 -05:00
a8e3488354 Fix search bar behaviour (step 2) 2025-03-02 14:29:21 -05:00
e588df9fca Fix search bar behaviour (step 1) 2025-03-02 14:27:28 -05:00
4e5274c6f0 Broken but retrying 2025-03-02 14:24:02 -05:00
adfc1d8269 . 2025-03-02 14:14:23 -05:00
bcf0e98b54 Fix search filtering bug 2025-03-02 14:03:48 -05:00
493dd94f21 Fix list highlighting 2025-03-02 14:01:34 -05:00
f879fddd95 Fix VM search displaying 2025-03-02 13:54:25 -05:00
0107197b2b Move remaining search components 2025-03-02 12:06:06 -05:00
645eec5d0d Adjust some padding between components 2025-03-02 11:30:36 -05:00
e450c5dca3 Move selector into dedicated component 2025-03-02 11:25:36 -05:00
c467b92384 Move search bar into dedicated component 2025-03-02 11:20:31 -05:00
037ea7fe8e First attempt at style fix 2025-03-02 11:12:54 -05:00
4e0cd95b75 Improve loading on VM page 2025-03-02 11:09:20 -05:00
ef3e013f2d Fix seconds handling in sidebar 2025-03-02 11:06:14 -05:00
94d0ed544f Reuse data to avoid dupe API calls 2025-03-02 10:50:49 -05:00
8f5dac1ca4 Consolidate back to VMOverview.vue and disable 2025-03-02 10:41:34 -05:00
8158f84eb7 Disable unused NodeStatus.vue 2025-03-02 10:40:29 -05:00
26a2d23798 Refactor component layouts 2025-03-02 01:33:51 -05:00
526e6f4a36 First attempt at fixing broken VM page 2025-03-02 01:20:39 -05:00
ac9428a41b Refactor collapsable section into reusable component 2025-03-02 01:11:42 -05:00
14e11a4772 Add basic but broken VM page 2025-03-02 01:09:10 -05:00
78608da00a Adjust padding and selector elements 2025-03-01 23:43:44 -05:00
f29f18eb26 Include maintenance mode in node health graphs 2025-03-01 23:02:16 -05:00
77adaea793 Fix maintenance mode displays 2025-03-01 22:55:30 -05:00
6a2729c33b Fix maintenance mode message 2025-03-01 22:15:42 -05:00
264eecdf7c Adjust sidebar layout and sizing 2025-03-01 21:51:41 -05:00
52057fa9e4 Show update interval in seconds 2025-03-01 17:21:21 -05:00
65fbbeed0c Fetch VM data properly 2025-03-01 17:09:32 -05:00
6d2f3fd7a8 Split VMs into dedicated component 2025-03-01 17:07:06 -05:00
94f32735a7 Refactor Nodes into a component 2025-03-01 16:53:24 -05:00
41d9ef4057 Jump to current VM in full VM list 2025-03-01 14:34:50 -05:00
dbb1dae0d9 Improve search and list behaviour 2025-03-01 14:31:01 -05:00
1dd1387624 Enhance search bar and hide filters when unneeded 2025-03-01 14:26:59 -05:00
21d98f1a98 Remove X from search bar when not opened 2025-03-01 14:21:42 -05:00
4a9b48caa0 Reorder state filters so start is first 2025-03-01 14:19:26 -05:00
70639194ea Add basic VMs page to start 2025-03-01 11:17:50 -05:00
af00d1fe61 Add VM list to nodes page and remove whitespace 2025-02-28 23:02:07 -05:00
187e46ee6d Add node state colours 2025-02-28 21:56:09 -05:00
b367d4086e Refactor cards in Nodes 2025-02-28 21:41:17 -05:00
3d13a05c0f Refactor cards to be generic and reusable 2025-02-28 21:20:24 -05:00
08f00d9c62 Add editorconfig to fix issues 2025-02-28 20:38:53 -05:00
97de6bda82 Split overview charts into discrete components 2025-02-28 20:36:12 -05:00
9e14502bc2 Refactor nodes page, update health chart 2025-02-28 20:20:10 -05:00
11e1e8eec4 Initial implementation of nice Nodes page 2025-02-28 19:53:44 -05:00
31 changed files with 4635 additions and 596 deletions

16
pvc-vue/.editorconfig Normal file
View File

@ -0,0 +1,16 @@
# EditorConfig helps maintain consistent coding styles across different editors
# https://editorconfig.org/
root = true
[*]
charset = utf-8
end_of_line = lf
indent_style = space
indent_size = 2
trim_trailing_whitespace = true
insert_final_newline = true
# Markdown files allow trailing whitespace for line breaks
[*.md]
trim_trailing_whitespace = false

View File

@ -3,10 +3,9 @@
<!-- Sidebar --> <!-- Sidebar -->
<div class="sidebar bg-dark" :class="{ 'collapsed': sidebarCollapsed }"> <div class="sidebar bg-dark" :class="{ 'collapsed': sidebarCollapsed }">
<div class="sidebar-header"> <div class="sidebar-header">
<h5 class="text-white mb-0">PVC Dashboard</h5> <h5 class="text-white mb-0 text-center">
<button class="btn btn-link text-white p-0 collapse-btn" @click="toggleSidebar"> {{ clusterData.cluster_name || 'Cluster' }}
<i class="fas" :class="sidebarCollapsed ? 'fa-chevron-right' : 'fa-chevron-left'"></i> </h5>
</button>
</div> </div>
<div class="sidebar-content"> <div class="sidebar-content">
<nav class="nav-menu"> <nav class="nav-menu">
@ -18,10 +17,31 @@
<i class="fas fa-server"></i> <i class="fas fa-server"></i>
<span class="nav-text">Nodes</span> <span class="nav-text">Nodes</span>
</router-link> </router-link>
<router-link to="/vms" class="nav-item" active-class="active" data-title="VMs">
<i class="fas fa-desktop"></i>
<span class="nav-text">VMs</span>
</router-link>
</nav> </nav>
</div> </div>
<div class="sidebar-footer"> <div class="sidebar-footer">
<button class="btn btn-outline-light w-100" @click="toggleConfig"> <!-- Refresh interval display with tooltip -->
<div class="refresh-display text-white-50 mb-3 text-center" data-title="Refresh Time">
<i class="fas fa-sync-alt"></i>
<span class="refresh-text ms-2">{{ api.config.updateInterval }}s</span>
</div>
<!-- Collapse/Expand button with tooltip -->
<button class="btn btn-outline-light w-100 mb-2"
@click="toggleSidebar"
data-title="Expand">
<i class="fas" :class="sidebarCollapsed ? 'fa-caret-right' : 'fa-caret-left'"></i>
<span class="action-text ms-2">{{ sidebarCollapsed ? 'Expand' : 'Collapse' }}</span>
</button>
<!-- Configure button with tooltip -->
<button class="btn btn-outline-light w-100"
@click="toggleConfig"
data-title="Configure">
<i class="fas fa-cog"></i> <i class="fas fa-cog"></i>
<span class="config-text ms-2">Configure</span> <span class="config-text ms-2">Configure</span>
</button> </button>
@ -35,8 +55,9 @@
</div> </div>
<router-view <router-view
:clusterData="clusterData" :clusterData="clusterData"
:metricsData="metricsHistory"
:nodeData="nodeData" :nodeData="nodeData"
:vmData="vmData"
:metricsData="metricsHistory"
/> />
</div> </div>
</div> </div>
@ -50,13 +71,14 @@
<script setup> <script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'; import { ref, computed, onMounted, onUnmounted } from 'vue';
import ConfigPanel from './components/ConfigPanel.vue'; import ConfigPanel from './components/general/ConfigPanel.vue';
import { useApiStore } from './stores/api'; import { useApiStore } from './stores/api';
const api = useApiStore(); const api = useApiStore();
const configPanelOpen = ref(false); const configPanelOpen = ref(false);
const clusterData = ref({}); const clusterData = ref({});
const nodeData = ref([]); const nodeData = ref([]);
const vmData = ref([]);
const metricsHistory = ref({ const metricsHistory = ref({
cpu: { labels: [], data: [] }, cpu: { labels: [], data: [] },
memory: { labels: [], data: [] }, memory: { labels: [], data: [] },
@ -93,26 +115,98 @@ const updateMetricsHistory = (timestamp, status) => {
memory: status.resources?.memory?.utilization || 0, memory: status.resources?.memory?.utilization || 0,
health: status.cluster_health?.health || 0, health: status.cluster_health?.health || 0,
storage: status.resources?.disk?.utilization || 0, storage: status.resources?.disk?.utilization || 0,
maintenance: status.maintenance === "true" ? true : false
}; };
// Create maintenance array if it doesn't exist
if (!metricsHistory.value.maintenance) {
metricsHistory.value.maintenance = { labels: [], data: [] };
}
// Track maintenance status as a boolean for each data point
const isInMaintenance = status.maintenance === "true";
Object.keys(metrics).forEach(metric => { Object.keys(metrics).forEach(metric => {
const labels = [...metricsHistory.value[metric].labels, timestamp]; const labels = [...metricsHistory.value[metric].labels, timestamp];
const data = [...metricsHistory.value[metric].data, const data = [...metricsHistory.value[metric].data,
typeof metrics[metric] === 'boolean' ? metrics[metric] : Math.round(metrics[metric]) Math.round(metrics[metric])
]; ];
// Keep only last 180 points // Keep only last 180 points
if (labels.length > 180) { if (labels.length > 180) {
labels.shift(); labels.shift();
data.shift(); data.shift();
} }
metricsHistory.value[metric] = { metricsHistory.value[metric] = {
labels, labels,
data data
}; };
}); });
// Update maintenance history
const maintenanceLabels = [...metricsHistory.value.maintenance.labels, timestamp];
const maintenanceData = [...metricsHistory.value.maintenance.data, isInMaintenance];
// Keep only last 180 points for maintenance too
if (maintenanceLabels.length > 180) {
maintenanceLabels.shift();
maintenanceData.shift();
}
metricsHistory.value.maintenance = {
labels: maintenanceLabels,
data: maintenanceData
};
// Track node-specific metrics
if (!metricsHistory.value.nodes) {
metricsHistory.value.nodes = {};
}
// Update metrics for each node
nodeData.value.forEach(node => {
const nodeName = node.name;
if (!metricsHistory.value.nodes[nodeName]) {
metricsHistory.value.nodes[nodeName] = {
health: { labels: [], data: [], maintenance: [] },
cpu: { labels: [], data: [] },
memory: { labels: [], data: [] },
allocated: { labels: [], data: [] }
};
}
// Calculate node metrics
const nodeMetrics = {
health: node.health || 0,
cpu: node.load && node.cpu_count ? Math.round((node.load / node.cpu_count) * 100) : 0,
memory: node.memory?.used && node.memory?.total ? Math.round((node.memory.used / node.memory.total) * 100) : 0,
allocated: node.memory?.allocated && node.memory?.total ? Math.round((node.memory.allocated / node.memory.total) * 100) : 0
};
// Update each metric for this node
Object.keys(nodeMetrics).forEach(metric => {
const nodeLabels = [...metricsHistory.value.nodes[nodeName][metric].labels, timestamp];
const nodeData = [...metricsHistory.value.nodes[nodeName][metric].data, nodeMetrics[metric]];
// Keep only last 180 points
if (nodeLabels.length > 180) {
nodeLabels.shift();
nodeData.shift();
}
metricsHistory.value.nodes[nodeName][metric] = {
labels: nodeLabels,
data: nodeData,
...(metric === 'health' ? { maintenance: [...(metricsHistory.value.nodes[nodeName][metric].maintenance || []), isInMaintenance] } : {})
};
// Trim maintenance array if needed
if (metric === 'health' && metricsHistory.value.nodes[nodeName][metric].maintenance.length > 180) {
metricsHistory.value.nodes[nodeName][metric].maintenance.shift();
}
});
});
}; };
const updateDashboard = async () => { const updateDashboard = async () => {
@ -124,15 +218,32 @@ const updateDashboard = async () => {
} }
try { try {
const status = await api.fetchStatus(); console.log(`${new Date().toISOString()} Starting API calls`);
const nodes = await api.fetchNodes();
// Ensure all endpoints are called together in a single Promise.all
const [status, nodes, vms] = await Promise.all([
api.fetchStatus().then(res => {
console.log(`${new Date().toISOString()} Status API call complete`);
return res;
}),
api.fetchNodes().then(res => {
console.log(`${new Date().toISOString()} Nodes API call complete`);
return res;
}),
api.fetchVMs().then(res => {
console.log(`${new Date().toISOString()} VMs API call complete`);
return res;
})
]);
console.log('[API] Status Response:', status); console.log('[API] Status Response:', status);
console.log('[API] Nodes Response:', nodes); console.log('[API] Nodes Response:', nodes);
console.log('[API] VMs Response:', vms);
// Update state with new objects instead of mutating
// Update state with new objects
clusterData.value = { ...status }; clusterData.value = { ...status };
nodeData.value = [...nodes]; nodeData.value = [...nodes];
vmData.value = [...vms];
const timestamp = new Date().toLocaleTimeString(); const timestamp = new Date().toLocaleTimeString();
updateMetricsHistory(timestamp, status); updateMetricsHistory(timestamp, status);
@ -151,7 +262,8 @@ const restartDashboard = () => {
clearInterval(updateTimer); clearInterval(updateTimer);
} }
updateDashboard(); updateDashboard();
updateTimer = setInterval(updateDashboard, api.config.updateInterval); const intervalMs = api.config.updateInterval * 1000;
updateTimer = setInterval(updateDashboard, intervalMs);
}; };
onMounted(() => { onMounted(() => {
@ -267,16 +379,16 @@ onUnmounted(() => {
.sidebar-footer { .sidebar-footer {
margin-top: auto; margin-top: auto;
padding-left: 0.25rem; padding: 0.75rem 0.25rem;
padding-right: 0.25rem;
padding-top: 0.75rem;
border-top: 1px solid rgba(255,255,255,0.1); border-top: 1px solid rgba(255,255,255,0.1);
display: flex;
flex-direction: column;
gap: 0.5rem;
} }
.sidebar.collapsed .sidebar-footer .btn { .sidebar.collapsed .sidebar-footer .btn {
padding: 0.375rem 0.5rem; padding: 0.375rem;
display: flex; height: 38px;
justify-content: center;
} }
.content-grid { .content-grid {
@ -372,8 +484,100 @@ onUnmounted(() => {
} }
.sidebar.collapsed .sidebar-footer .btn { .sidebar.collapsed .sidebar-footer .btn {
padding: 0.375rem 0.5rem; padding: 0.375rem;
height: 38px;
}
/* Add these styles for the sidebar header */
.sidebar-header h5 {
width: 100%;
text-align: center;
}
/* Style for collapsed sidebar header */
.sidebar.collapsed .sidebar-header h5 {
display: block;
font-size: 0.95rem;
writing-mode: normal;
transform: none;
height: auto;
margin: 0.5rem 0;
white-space: normal;
text-align: center;
}
/* Style for refresh interval display */
.refresh-display {
position: relative;
font-size: 0.9rem;
height: 24px;
display: flex; display: flex;
align-items: center;
justify-content: center; justify-content: center;
margin-bottom: 0.75rem !important;
}
.sidebar.collapsed .refresh-display {
height: 24px;
}
.sidebar.collapsed .refresh-text {
display: inline;
font-size: 0.75rem;
}
/* Style for action text in collapsed view */
.sidebar.collapsed .action-text {
display: none;
}
/* Standardize button heights and padding */
.sidebar-footer .btn {
position: relative;
height: 38px;
display: flex;
align-items: center;
justify-content: center;
padding: 0.375rem 0.75rem;
margin-bottom: 0.5rem;
}
/* Last button shouldn't have margin */
.sidebar-footer .btn:last-child {
margin-bottom: 0;
}
/* Add tooltip styles for footer elements in collapsed view */
.sidebar.collapsed .sidebar-footer .refresh-display:hover::after,
.sidebar.collapsed .sidebar-footer .btn:hover::after {
content: attr(data-title);
position: absolute;
left: 100%;
top: 50%;
transform: translateY(-50%);
background: #343a40;
color: white;
padding: 0.5rem 0.75rem;
border-radius: 0.25rem;
white-space: nowrap;
z-index: 1010;
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
margin-left: 0.5rem;
font-size: 0.875rem;
}
/* Add arrow for the tooltips */
.sidebar.collapsed .sidebar-footer .refresh-display:hover::before,
.sidebar.collapsed .sidebar-footer .btn:hover::before {
content: "";
position: absolute;
left: 100%;
top: 50%;
transform: translateY(-50%);
border-width: 5px;
border-style: solid;
border-color: transparent #343a40 transparent transparent;
margin-left: 0.25rem;
z-index: 1011;
} }
</style> </style>

View File

View File

@ -0,0 +1,202 @@
<template>
<div class="metric-card">
<div class="card-header">
<h6 class="card-title mb-0">
<span class="metric-label">{{ title }}</span>
</h6>
</div>
<div class="card-body">
<div class="metric-percentage">
<h4 class="metric-value">{{ value }}%</h4>
</div>
<div class="chart-wrapper">
<Line
:data="formattedChartData"
:options="chartOptions"
class="chart-cpu"
/>
</div>
</div>
</div>
</template>
<script setup>
import { computed } from 'vue';
import { Line } from 'vue-chartjs';
import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend, Filler } from 'chart.js';
// Register Chart.js components
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
Filler
);
const props = defineProps({
title: {
type: String,
default: 'CPU Utilization'
},
value: {
type: Number,
default: 0
},
chartData: {
type: Object,
default: () => ({ labels: [], data: [] })
}
});
const chartOptions = {
responsive: true,
maintainAspectRatio: false,
clip: false,
resizeDelay: 0,
responsiveAnimationDuration: 0,
plugins: {
legend: {
display: false
},
tooltip: {
callbacks: {
label: (context) => `${context.parsed.y}%`
}
}
},
scales: {
x: {
display: false,
grid: {
display: false
}
},
y: {
display: false,
grid: {
display: false
},
min: 0,
max: 100
}
},
animation: false,
interaction: {
enabled: true,
mode: 'nearest',
intersect: false
},
onResize: (chart, size) => {
chart.resize();
}
};
const formattedChartData = computed(() => ({
labels: props.chartData.labels || [],
datasets: [{
label: 'CPU',
data: props.chartData.data || [],
borderColor: 'rgb(75, 192, 192)',
fill: true,
backgroundColor: 'rgba(75, 192, 192, 0.1)',
borderWidth: 1.5,
tension: 0.4,
pointRadius: 0,
pointHoverRadius: 4,
pointBackgroundColor: 'rgba(255, 255, 255, 0.8)',
pointBorderColor: 'rgba(75, 192, 192, 0.5)',
pointBorderWidth: 1.5
}]
}));
</script>
<style scoped>
.chart-wrapper {
position: relative;
width: 100%;
height: 160px;
min-height: 160px;
overflow: hidden;
border: none;
border-radius: 0;
background-color: white;
margin: 0;
}
.metric-percentage {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: rgba(255, 255, 255, 0.8);
padding: 0.25rem 0.75rem;
border-radius: 0.5rem;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
z-index: 2;
}
.metric-percentage .metric-value {
font-size: 2.5rem;
font-weight: 500;
color: #333;
line-height: 1;
margin: 0;
text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
}
.chart-cpu {
background: white;
border: none;
}
.metric-card {
min-width: 180px;
background: white;
border: 1px solid rgba(0,0,0,0.125);
border-radius: 0.25rem;
height: 100%;
display: flex;
flex-direction: column;
min-width: 0;
width: 100%;
overflow: hidden;
}
.metric-card .card-header {
background-color: rgba(0, 0, 0, 0.03);
padding: 0.5rem;
border-bottom: 1px solid rgba(0, 0, 0, 0.125);
height: 38px;
display: flex;
justify-content: space-between;
align-items: center;
}
.card-header h6 {
font-size: 0.95rem;
font-weight: 600;
display: flex;
justify-content: space-between;
align-items: center;
margin: 0;
}
.metric-card .card-body {
flex: 1;
padding: 0.5rem;
display: flex;
flex-direction: column;
position: relative;
width: 100%;
overflow: visible;
}
.metric-label {
color: #495057;
font-weight: 600;
}
</style>

View File

@ -0,0 +1,320 @@
<template>
<div class="metric-card">
<div class="card-header">
<h6 class="card-title mb-0">
<span class="metric-label">{{ title }}</span>
</h6>
</div>
<div class="card-body">
<div class="metric-percentage">
<h4 class="metric-value">{{ value }}%</h4>
</div>
<div class="chart-wrapper">
<Line
:data="formattedChartData"
:options="chartOptions"
class="chart-health"
/>
</div>
</div>
</div>
</template>
<script setup>
import { computed } from 'vue';
import { Line } from 'vue-chartjs';
import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend, Filler } from 'chart.js';
import annotationPlugin from 'chartjs-plugin-annotation';
import ValueCard from '../general/ValueCard.vue';
// Register Chart.js components
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
Filler,
annotationPlugin
);
const props = defineProps({
title: {
type: String,
default: 'Health'
},
value: {
type: Number,
default: 0
},
chartData: {
type: Object,
default: () => ({ labels: [], data: [], maintenance: [] })
},
maintenance: {
type: Boolean,
default: false
}
});
const chartOptions = {
responsive: true,
maintainAspectRatio: false,
clip: false,
resizeDelay: 0,
responsiveAnimationDuration: 0,
plugins: {
legend: {
display: false
},
tooltip: {
callbacks: {
label: (context) => {
const dataPoint = context.dataIndex;
const maintenanceData = props.chartData.maintenance || [];
const isInMaintenance = maintenanceData[dataPoint];
return isInMaintenance
? `${context.parsed.y}% (Maintenance)`
: `${context.parsed.y}%`;
}
}
},
annotation: {
annotations: {
criticalLine: {
type: 'line',
yMin: 50,
yMax: 50,
borderColor: 'rgba(220, 53, 69, 0.5)',
borderWidth: 1,
borderDash: [5, 5]
},
warningLine: {
type: 'line',
yMin: 90,
yMax: 90,
borderColor: 'rgba(255, 193, 7, 0.5)',
borderWidth: 1,
borderDash: [5, 5]
}
}
}
},
scales: {
x: {
display: false,
grid: {
display: false
}
},
y: {
display: false,
grid: {
display: false
},
min: 0,
max: 100
}
},
animation: false,
interaction: {
enabled: true,
mode: 'nearest',
intersect: false
},
onResize: (chart, size) => {
chart.resize();
}
};
// Helper function to get health color based on value and maintenance status
const getHealthColor = (value, isInMaintenance) => {
if (isInMaintenance) {
return {
border: 'rgba(13, 110, 253, 0.8)', // Blue for maintenance
background: 'rgba(13, 110, 253, 0.1)'
};
} else if (value > 90) {
return {
border: 'rgba(40, 167, 69, 0.8)', // Green
background: 'rgba(40, 167, 69, 0.1)'
};
} else if (value > 50) {
return {
border: 'rgba(255, 193, 7, 0.8)', // Yellow
background: 'rgba(255, 193, 7, 0.1)'
};
} else {
return {
border: 'rgba(220, 53, 69, 0.8)', // Red
background: 'rgba(220, 53, 69, 0.1)'
};
}
};
const formattedChartData = computed(() => {
const labels = props.chartData.labels || [];
const data = props.chartData.data || [];
const maintenanceData = props.chartData.maintenance || [];
// For single value or empty data
if (data.length <= 1) {
const value = data.length === 1 ? data[0] : props.value;
const isInMaintenance = props.maintenance;
const color = getHealthColor(value, isInMaintenance);
return {
labels: labels.length ? labels : ['Health'],
datasets: [{
label: 'Health',
data: data.length ? data : [value],
borderColor: color.border,
backgroundColor: color.background,
fill: true,
borderWidth: 1.5,
tension: 0.4,
pointRadius: 0,
pointHoverRadius: 4,
pointBackgroundColor: 'rgba(255, 255, 255, 0.8)',
pointBorderColor: color.border,
pointBorderWidth: 1.5
}]
};
}
// For historical data with multiple values
return {
labels,
datasets: [{
label: 'Health',
data,
segment: {
borderColor: ctx => {
const index = ctx.p1DataIndex;
const value = ctx.p1.parsed.y;
const isInMaintenance = maintenanceData[index];
if (isInMaintenance) return 'rgba(13, 110, 253, 0.8)'; // Blue for maintenance
if (value > 90) return 'rgba(40, 167, 69, 0.8)'; // Green
if (value > 50) return 'rgba(255, 193, 7, 0.8)'; // Yellow
return 'rgba(220, 53, 69, 0.8)'; // Red
},
backgroundColor: ctx => {
const index = ctx.p1DataIndex;
const value = ctx.p1.parsed.y;
const isInMaintenance = maintenanceData[index];
if (isInMaintenance) return 'rgba(13, 110, 253, 0.1)'; // Blue for maintenance
if (value > 90) return 'rgba(40, 167, 69, 0.1)'; // Green
if (value > 50) return 'rgba(255, 193, 7, 0.1)'; // Yellow
return 'rgba(220, 53, 69, 0.1)'; // Red
}
},
fill: true,
borderWidth: 1.5,
tension: 0.4,
pointRadius: 0,
pointHoverRadius: 4,
pointBackgroundColor: 'rgba(255, 255, 255, 0.8)',
pointBorderColor: function(context) {
const index = context.dataIndex;
const value = context.dataset.data[index];
const isInMaintenance = maintenanceData[index];
return getHealthColor(value, isInMaintenance).border;
},
pointBorderWidth: 1.5
}]
};
});
</script>
<style scoped>
.chart-wrapper {
position: relative;
width: 100%;
height: 160px;
min-height: 160px;
overflow: hidden;
border: none;
border-radius: 0;
background-color: white;
margin: 0;
}
.metric-percentage {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: rgba(255, 255, 255, 0.8);
padding: 0.25rem 0.75rem;
border-radius: 0.5rem;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
z-index: 2;
}
.metric-percentage .metric-value {
font-size: 2.5rem;
font-weight: 500;
color: #333;
line-height: 1;
margin: 0;
text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
}
.chart-health {
background: white;
border: none;
}
/* Add these styles to match the original design */
.metric-card {
min-width: 180px;
background: white;
border: 1px solid rgba(0,0,0,0.125);
border-radius: 0.25rem;
height: 100%;
display: flex;
flex-direction: column;
min-width: 0;
width: 100%;
overflow: hidden;
}
.metric-card .card-header {
background-color: rgba(0, 0, 0, 0.03);
padding: 0.5rem;
border-bottom: 1px solid rgba(0, 0, 0, 0.125);
height: 38px;
display: flex;
justify-content: space-between;
align-items: center;
}
.card-header h6 {
font-size: 0.95rem;
font-weight: 600;
display: flex;
justify-content: space-between;
align-items: center;
margin: 0;
}
.metric-card .card-body {
flex: 1;
padding: 0.5rem;
display: flex;
flex-direction: column;
position: relative;
width: 100%;
overflow: visible;
}
.metric-label {
color: #495057;
font-weight: 600;
}
</style>

View File

@ -0,0 +1,202 @@
<template>
<div class="metric-card">
<div class="card-header">
<h6 class="card-title mb-0">
<span class="metric-label">{{ title }}</span>
</h6>
</div>
<div class="card-body">
<div class="metric-percentage">
<h4 class="metric-value">{{ value }}%</h4>
</div>
<div class="chart-wrapper">
<Line
:data="formattedChartData"
:options="chartOptions"
class="chart-memory"
/>
</div>
</div>
</div>
</template>
<script setup>
import { computed } from 'vue';
import { Line } from 'vue-chartjs';
import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend, Filler } from 'chart.js';
// Register Chart.js components
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
Filler
);
const props = defineProps({
title: {
type: String,
default: 'Memory Utilization'
},
value: {
type: Number,
default: 0
},
chartData: {
type: Object,
default: () => ({ labels: [], data: [] })
}
});
const chartOptions = {
responsive: true,
maintainAspectRatio: false,
clip: false,
resizeDelay: 0,
responsiveAnimationDuration: 0,
plugins: {
legend: {
display: false
},
tooltip: {
callbacks: {
label: (context) => `${context.parsed.y}%`
}
}
},
scales: {
x: {
display: false,
grid: {
display: false
}
},
y: {
display: false,
grid: {
display: false
},
min: 0,
max: 100
}
},
animation: false,
interaction: {
enabled: true,
mode: 'nearest',
intersect: false
},
onResize: (chart, size) => {
chart.resize();
}
};
const formattedChartData = computed(() => ({
labels: props.chartData.labels || [],
datasets: [{
label: 'Memory',
data: props.chartData.data || [],
borderColor: 'rgb(153, 102, 255)',
fill: true,
backgroundColor: 'rgba(153, 102, 255, 0.1)',
borderWidth: 1.5,
tension: 0.4,
pointRadius: 0,
pointHoverRadius: 4,
pointBackgroundColor: 'rgba(255, 255, 255, 0.8)',
pointBorderColor: 'rgba(153, 102, 255, 0.5)',
pointBorderWidth: 1.5
}]
}));
</script>
<style scoped>
.chart-wrapper {
position: relative;
width: 100%;
height: 160px;
min-height: 160px;
overflow: hidden;
border: none;
border-radius: 0;
background-color: white;
margin: 0;
}
.metric-percentage {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: rgba(255, 255, 255, 0.8);
padding: 0.25rem 0.75rem;
border-radius: 0.5rem;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
z-index: 2;
}
.metric-percentage .metric-value {
font-size: 2.5rem;
font-weight: 500;
color: #333;
line-height: 1;
margin: 0;
text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
}
.chart-memory {
background: white;
border: none;
}
.metric-card {
min-width: 180px;
background: white;
border: 1px solid rgba(0,0,0,0.125);
border-radius: 0.25rem;
height: 100%;
display: flex;
flex-direction: column;
min-width: 0;
width: 100%;
overflow: hidden;
}
.metric-card .card-header {
background-color: rgba(0, 0, 0, 0.03);
padding: 0.5rem;
border-bottom: 1px solid rgba(0, 0, 0, 0.125);
height: 38px;
display: flex;
justify-content: space-between;
align-items: center;
}
.card-header h6 {
font-size: 0.95rem;
font-weight: 600;
display: flex;
justify-content: space-between;
align-items: center;
margin: 0;
}
.metric-card .card-body {
flex: 1;
padding: 0.5rem;
display: flex;
flex-direction: column;
position: relative;
width: 100%;
overflow: visible;
}
.metric-label {
color: #495057;
font-weight: 600;
}
</style>

View File

@ -82,6 +82,7 @@ import {
Tooltip, Tooltip,
Legend Legend
} from 'chart.js'; } from 'chart.js';
import ValueCard from '../general/ValueCard.vue';
// Register Chart.js components // Register Chart.js components
ChartJS.register( ChartJS.register(

View File

@ -0,0 +1,202 @@
<template>
<div class="metric-card">
<div class="card-header">
<h6 class="card-title mb-0">
<span class="metric-label">{{ title }}</span>
</h6>
</div>
<div class="card-body">
<div class="metric-percentage">
<h4 class="metric-value">{{ value }}%</h4>
</div>
<div class="chart-wrapper">
<Line
:data="formattedChartData"
:options="chartOptions"
class="chart-storage"
/>
</div>
</div>
</div>
</template>
<script setup>
import { computed } from 'vue';
import { Line } from 'vue-chartjs';
import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend, Filler } from 'chart.js';
// Register Chart.js components
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
Filler
);
const props = defineProps({
title: {
type: String,
default: 'Storage Utilization'
},
value: {
type: Number,
default: 0
},
chartData: {
type: Object,
default: () => ({ labels: [], data: [] })
}
});
const chartOptions = {
responsive: true,
maintainAspectRatio: false,
clip: false,
resizeDelay: 0,
responsiveAnimationDuration: 0,
plugins: {
legend: {
display: false
},
tooltip: {
callbacks: {
label: (context) => `${context.parsed.y}%`
}
}
},
scales: {
x: {
display: false,
grid: {
display: false
}
},
y: {
display: false,
grid: {
display: false
},
min: 0,
max: 100
}
},
animation: false,
interaction: {
enabled: true,
mode: 'nearest',
intersect: false
},
onResize: (chart, size) => {
chart.resize();
}
};
const formattedChartData = computed(() => ({
labels: props.chartData.labels || [],
datasets: [{
label: 'Storage',
data: props.chartData.data || [],
borderColor: 'rgb(255, 159, 64)',
fill: true,
backgroundColor: 'rgba(255, 159, 64, 0.1)',
borderWidth: 1.5,
tension: 0.4,
pointRadius: 0,
pointHoverRadius: 4,
pointBackgroundColor: 'rgba(255, 255, 255, 0.8)',
pointBorderColor: 'rgba(255, 159, 64, 0.5)',
pointBorderWidth: 1.5
}]
}));
</script>
<style scoped>
.chart-wrapper {
position: relative;
width: 100%;
height: 160px;
min-height: 160px;
overflow: hidden;
border: none;
border-radius: 0;
background-color: white;
margin: 0;
}
.metric-percentage {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: rgba(255, 255, 255, 0.8);
padding: 0.25rem 0.75rem;
border-radius: 0.5rem;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
z-index: 2;
}
.metric-percentage .metric-value {
font-size: 2.5rem;
font-weight: 500;
color: #333;
line-height: 1;
margin: 0;
text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
}
.chart-storage {
background: white;
border: none;
}
.metric-card {
min-width: 180px;
background: white;
border: 1px solid rgba(0,0,0,0.125);
border-radius: 0.25rem;
height: 100%;
display: flex;
flex-direction: column;
min-width: 0;
width: 100%;
overflow: hidden;
}
.metric-card .card-header {
background-color: rgba(0, 0, 0, 0.03);
padding: 0.5rem;
border-bottom: 1px solid rgba(0, 0, 0, 0.125);
height: 38px;
display: flex;
justify-content: space-between;
align-items: center;
}
.card-header h6 {
font-size: 0.95rem;
font-weight: 600;
display: flex;
justify-content: space-between;
align-items: center;
margin: 0;
}
.metric-card .card-body {
flex: 1;
padding: 0.5rem;
display: flex;
flex-direction: column;
position: relative;
width: 100%;
overflow: visible;
}
.metric-label {
color: #495057;
font-weight: 600;
}
</style>

View File

@ -0,0 +1,155 @@
<template>
<div class="section-container" :class="{ 'collapsed': !isExpanded }">
<!-- Collapsed section indicator -->
<div v-if="!isExpanded" class="section-content-wrapper">
<div class="section-content">
<div class="collapsed-section-header">
<h5 class="section-title" v-if="title">{{ title }}</h5>
</div>
</div>
<div class="toggle-column">
<button class="section-toggle" @click="toggleSection">
<i class="fas fa-chevron-down"></i>
</button>
</div>
</div>
<!-- Toggle button for expanded section -->
<div v-show="isExpanded" class="section-content-wrapper">
<div class="section-content">
<slot></slot>
</div>
<div class="toggle-column expanded">
<button class="section-toggle" @click="toggleSection">
<i class="fas fa-chevron-up"></i>
</button>
</div>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue';
const props = defineProps({
title: {
type: String,
required: true
},
initiallyExpanded: {
type: Boolean,
default: true
}
});
const isExpanded = ref(props.initiallyExpanded);
const toggleSection = () => {
isExpanded.value = !isExpanded.value;
};
</script>
<style scoped>
.section-container {
position: relative;
margin-bottom: 0.5rem;
}
.section-content-wrapper {
display: flex;
position: relative;
}
.section-content {
flex: 1;
min-width: 0;
padding-right: 40px;
}
.toggle-column {
position: absolute;
top: 4px;
right: 0;
width: 40px;
height: 30px;
z-index: 10;
padding-left: 6px;
}
.section-toggle {
background: none;
border: none;
color: #666;
cursor: pointer;
padding: 0.25rem;
border-radius: 0.25rem;
transition: all 0.2s;
width: 30px;
height: 30px;
display: flex;
align-items: center;
justify-content: center;
background-color: rgba(255, 255, 255, 0.8);
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.section-toggle:hover {
background-color: rgba(0, 0, 0, 0.05);
color: #333;
}
.section-toggle:focus {
outline: none;
box-shadow: none;
}
.collapsed-section-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.5rem;
background-color: rgba(0, 0, 0, 0.03);
border: 1px solid rgba(0, 0, 0, 0.125);
border-radius: 0.25rem;
height: 38px;
width: 100%;
}
.collapsed-section-header .card-title {
margin: 0;
color: #495057;
font-size: 0.95rem;
font-weight: 600;
}
.toggle-column.expanded {
top: 0;
right: 0;
height: 100%;
display: flex;
align-items: flex-start;
padding-top: 4px;
}
.section-container.collapsed {
margin-bottom: 0.5rem;
}
.section-container.collapsed .section-content-wrapper {
margin-bottom: 0;
}
.section-header h6 {
font-size: 0.95rem;
font-weight: 600;
display: flex;
justify-content: space-between;
align-items: center;
}
.section-title {
margin: 0;
font-size: 0.95rem;
font-weight: 600;
color: #495057;
}
</style>

View File

@ -1,12 +1,12 @@
<template> <template>
<div> <div>
<!-- Overlay that captures clicks outside the panel --> <!-- Overlay that captures clicks outside the panel -->
<div <div
v-if="modelValue" v-if="modelValue"
class="config-overlay" class="config-overlay"
@click="closePanel" @click="closePanel"
></div> ></div>
<div class="config-panel" :class="{ 'open': modelValue }"> <div class="config-panel" :class="{ 'open': modelValue }">
<div class="config-content" @click.stop> <div class="config-content" @click.stop>
<h3>Configuration</h3> <h3>Configuration</h3>
@ -36,16 +36,19 @@
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label for="updateInterval" class="form-label">Update Interval (ms)</label> <label for="updateInterval" class="form-label">Update Interval (seconds)</label>
<input <input
type="number" type="number"
class="form-control" class="form-control"
id="updateInterval" id="updateInterval"
v-model="formData.updateInterval" v-model.number="formData.updateInterval"
min="1000" min="5"
step="1000" max="300"
required required
> >
<div class="form-text">
Enter value in seconds (5-300, default: 15)
</div>
</div> </div>
<div class="d-grid gap-2"> <div class="d-grid gap-2">
@ -74,14 +77,20 @@ const props = defineProps({
const emit = defineEmits(['update:modelValue', 'save']); const emit = defineEmits(['update:modelValue', 'save']);
// Initialize form data with raw values from config
const formData = ref({ const formData = ref({
apiUri: props.config.apiUri || '', apiUri: props.config.apiUri || '',
apiKey: props.config.apiKey || '', apiKey: props.config.apiKey || '',
updateInterval: props.config.updateInterval || 5000 updateInterval: props.config.updateInterval || 15 // Default to 15 seconds
}); });
const saveConfig = () => { const saveConfig = () => {
emit('save', { ...formData.value }); // Pass the raw values to parent
emit('save', {
apiUri: formData.value.apiUri,
apiKey: formData.value.apiKey,
updateInterval: formData.value.updateInterval // Pass seconds directly
});
}; };
const closePanel = () => { const closePanel = () => {

View File

@ -0,0 +1,113 @@
<template>
<div class="node-select-bar">
<div class="node-select-row">
<button
v-for="node in nodes"
:key="node"
class="node-tab"
:class="{ 'active': modelValue === node }"
@click="selectNode(node)"
>
{{ node }}
</button>
</div>
</div>
</template>
<script setup>
import { ref, onMounted, watch } from 'vue';
const props = defineProps({
modelValue: {
type: String,
required: true
},
nodes: {
type: Array,
required: true,
default: () => []
},
value: {
type: String,
default: null
}
});
const emit = defineEmits(['update:modelValue', 'select']);
const selectedNode = ref(props.value || props.modelValue);
const selectNode = (node) => {
selectedNode.value = node;
emit('update:modelValue', node);
emit('select', node);
// Save to localStorage
localStorage.setItem('selectedNodeId', node);
};
onMounted(() => {
// Restore selected node from localStorage if available
const savedNodeId = localStorage.getItem('selectedNodeId');
if (savedNodeId && props.nodes.includes(savedNodeId)) {
// Only select if the node exists in the available nodes
selectedNode.value = savedNodeId;
emit('update:modelValue', savedNodeId);
emit('select', savedNodeId);
}
});
watch(() => props.value, (newValue) => {
if (newValue) {
selectedNode.value = newValue;
}
});
watch(() => props.modelValue, (newValue) => {
if (newValue) {
selectedNode.value = newValue;
}
});
</script>
<style scoped>
.node-select-bar {
display: flex;
flex-direction: column;
gap: 0.5rem;
background-color: white;
border-radius: 0.25rem;
padding-top: 0.25rem;
border-bottom: 1px solid rgba(0, 0, 0, 0.125);
}
.node-select-row {
display: flex;
align-items: center;
gap: 0.5rem;
padding-bottom: 0.75rem !important;
}
.node-tab {
padding: 0.45rem 0.75rem;
border: none;
background: none;
color: #495057;
font-weight: 500;
cursor: pointer;
border-radius: 0.25rem;
white-space: nowrap;
transition: all 0.2s;
}
.node-tab:hover {
background-color: rgba(0, 0, 0, 0.03);
}
.node-tab.active {
color: #0d6efd;
background-color: rgba(13, 110, 253, 0.1);
border-bottom: 4px solid rgba(13, 110, 253, 0.25);
margin-bottom: -4px;
}
</style>

View File

@ -21,7 +21,6 @@ defineProps({
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
align-items: center; align-items: center;
margin-bottom: 1rem;
padding-bottom: 0.5rem; padding-bottom: 0.5rem;
border-bottom: 1px solid rgba(0, 0, 0, 0.1); border-bottom: 1px solid rgba(0, 0, 0, 0.1);
} }
@ -37,4 +36,4 @@ defineProps({
display: flex; display: flex;
gap: 0.5rem; gap: 0.5rem;
} }
</style> </style>

View File

@ -0,0 +1,979 @@
<template>
<div class="vm-selector-bar" ref="controlsBar">
<div class="vm-selector-row">
<button
class="btn btn-outline-secondary list-toggle-btn"
@click="toggleList"
:class="{
'active': showList && !isFilterActive,
'filtering': showList && isFilterActive
}"
:title="showList ? (isFilterActive ? 'Show all VMs' : 'Filter VMs') : 'Show VM list'"
>
<i class="fas fa-list"></i> List VMs
</button>
<div class="search-box">
<i class="fas fa-search search-icon"></i>
<input
type="text"
placeholder="Search VMs..."
:value="inputValue"
@input="handleSearch"
@focus="handleFocus"
@blur="handleBlur"
@click="handleSearchClick"
:class="{ 'search-active': showList && isFilterActive }"
class="form-control search-input"
>
<button
v-if="shouldShowClearButton"
class="btn-clear"
@click.stop="handleClearButton"
:title="showList ? 'Clear search' : 'Clear selected VM'"
>
<i class="fas fa-times"></i>
</button>
</div>
<div class="filter-dropdown" ref="filterDropdown">
<button
class="btn btn-outline-secondary dropdown-toggle"
:disabled="!showList"
@click="toggleFilterMenu"
>
<i class="fas fa-filter"></i> Filters
<span v-if="activeFiltersCount > 0" class="filter-badge">{{ activeFiltersCount }}</span>
</button>
<div class="filter-menu" v-show="showFilterMenu" ref="filterMenu">
<div class="filter-section">
<h6>State</h6>
<div class="filter-options-dropdown">
<div class="filter-pills">
<button
v-for="state in availableStates"
:key="state"
class="filter-pill"
:class="{ 'active': appliedFilters.states[state] }"
@click="handleFilterToggle('states', state)"
>
{{ state }}
</button>
</div>
</div>
</div>
<div class="filter-section">
<h6>Node</h6>
<div class="filter-options-dropdown">
<div class="filter-pills">
<button
v-for="node in availableNodes"
:key="node"
class="filter-pill"
:class="{ 'active': appliedFilters.nodes[node] }"
@click="handleFilterToggle('nodes', node)"
>
{{ node }}
</button>
</div>
</div>
</div>
<div class="filter-actions">
<button class="btn btn-sm btn-outline-secondary" @click="handleResetFilters">Reset All</button>
<button class="btn btn-sm btn-primary" @click="showFilterMenu = false">Close</button>
</div>
</div>
</div>
</div>
<!-- VM List -->
<div v-if="showList" class="vm-list-container">
<div v-if="filteredVMs.length === 0" class="no-vms-message">
<p>No VMs match your search criteria</p>
</div>
<div v-else class="vm-list" ref="vmListContainer">
<button
v-for="vm in filteredVMs"
:key="vm.name"
:data-vm-name="vm.name"
class="vm-list-item"
:class="{ 'active': isVMSelected(vm.name) }"
@click="handleVMSelect(vm)"
>
<div v-if="isVMSelected(vm.name)" class="active-indicator"></div>
<div class="vm-item-content">
<div class="vm-name">{{ vm.name }}</div>
<div class="vm-state" :class="getStateClass(vm.state)">
<i class="fas fa-circle state-indicator"></i>
<span>{{ vm.state }}</span>
</div>
<div v-if="vm.node" class="vm-node">
<i class="fas fa-server node-icon"></i>
<span>{{ vm.node }}</span>
</div>
</div>
</button>
</div>
</div>
</div>
</template>
<script setup>
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue';
const props = defineProps({
modelValue: {
type: String,
required: true
},
showList: {
type: Boolean,
required: true
},
showClearButton: {
type: Boolean,
default: true
},
vmList: {
type: Array,
required: true
},
selectedVM: {
type: String,
default: ''
},
vmFromUrl: {
type: String,
default: ''
}
});
const emit = defineEmits([
'update:modelValue',
'search',
'focus',
'blur',
'clear',
'toggle-list',
'select-vm',
'toggle-filter',
'reset-filters',
'clear-vm'
]);
// UI state refs
const showFilterMenu = ref(false);
const filterDropdown = ref(null);
const filterMenu = ref(null);
const controlsBar = ref(null);
const vmListContainer = ref(null);
// Search state refs
const inputValue = ref('');
const searchText = ref('');
const isFilterActive = ref(false);
// Filter state
const appliedFilters = ref({
states: {},
nodes: {}
});
// Add a computed property to determine if the clear button should be shown
const shouldShowClearButton = computed(() => {
// Show when:
// 1. List is open and there's a search query
// 2. List is closed and there's a selected VM
return (props.showList && props.modelValue && props.showClearButton) ||
(!props.showList && (props.selectedVM || localStorage.getItem('selectedVMId')));
});
// Add a computed property to check if a VM is selected
const isVMSelected = (vmName) => {
return props.selectedVM === vmName ||
props.vmFromUrl === vmName ||
localStorage.getItem('selectedVMId') === vmName;
};
// Initialize the component
onMounted(() => {
// Set up click outside handler
document.addEventListener('click', handleClickOutside);
// Get the selected VM from localStorage
const savedVMId = localStorage.getItem('selectedVMId');
// Restore search text from localStorage if available
const savedSearchText = localStorage.getItem('vmSearchText');
// Initialize input value based on context
if (!props.showList) {
// If list is closed, show the selected VM name in the input
const effectiveVM = props.selectedVM || props.vmFromUrl || savedVMId;
if (effectiveVM) {
// Find the VM in the list to get its full name
const vm = props.vmList.find(v => v.name === effectiveVM);
if (vm) {
inputValue.value = vm.name;
} else {
inputValue.value = effectiveVM;
}
}
} else if (props.showList) {
// If list is open
if (props.modelValue) {
// If there's a model value, use it
inputValue.value = props.modelValue;
searchText.value = props.modelValue;
} else if (savedSearchText) {
// If there's saved search text, restore it
inputValue.value = savedSearchText;
searchText.value = savedSearchText;
emit('update:modelValue', savedSearchText);
}
}
// Always restore the search text ref from localStorage
if (savedSearchText) {
searchText.value = savedSearchText;
}
// Load saved filters
loadFiltersFromLocalStorage();
// If the list is visible on mount, scroll to selected VM
if (props.showList) {
nextTick(() => {
scrollToSelectedVM();
});
}
});
onUnmounted(() => {
document.removeEventListener('click', handleClickOutside);
});
// Handle search input
const handleSearch = (event) => {
const value = event.target.value;
inputValue.value = value;
// Update search text ref
searchText.value = value;
// Update the model
emit('update:modelValue', value);
emit('search', value);
// Save to localStorage for search history
if (value) {
localStorage.setItem('vmSearchText', value);
} else {
localStorage.removeItem('vmSearchText');
}
// Update filter state
isFilterActive.value = !!value;
};
// Handle focus on search input
const handleFocus = (event) => {
// If the list is not shown, show it
if (!props.showList) {
emit('toggle-list');
} else {
// If the list is already shown, activate filtering
isFilterActive.value = true;
// Restore search text if available
if (searchText.value) {
inputValue.value = searchText.value;
emit('update:modelValue', searchText.value);
}
}
emit('focus', event);
};
// Handle blur on search input
const handleBlur = (event) => {
emit('blur', event);
};
// Handle click on search input
const handleSearchClick = () => {
if (props.showList) {
// When clicking the search input while list is open, activate filtering
isFilterActive.value = true;
// Restore search text if available
if (searchText.value && searchText.value !== inputValue.value) {
inputValue.value = searchText.value;
emit('update:modelValue', searchText.value);
}
}
};
// Toggle the VM list
const toggleList = () => {
emit('toggle-list');
// When toggling the list, ensure search text is preserved
const savedSearchText = localStorage.getItem('vmSearchText');
if (!props.showList) {
// When opening the list, restore search text if available
if (savedSearchText && !inputValue.value) {
nextTick(() => {
inputValue.value = savedSearchText;
searchText.value = savedSearchText;
emit('update:modelValue', savedSearchText);
});
}
}
};
// Handle clear button click
const handleClearButton = () => {
if (props.showList) {
// If the list is open, clear the search
clearSearch();
} else {
// If the list is closed, clear the selected VM
clearSelectedVM();
}
};
// Clear search
const clearSearch = () => {
inputValue.value = '';
searchText.value = '';
isFilterActive.value = false;
// Clear search text from localStorage
localStorage.removeItem('vmSearchText');
emit('update:modelValue', '');
emit('clear');
// Scroll to selected VM after clearing search
nextTick(() => {
scrollToSelectedVM();
// Focus the search input after clearing
const searchInput = document.querySelector('.search-input');
if (searchInput) {
searchInput.focus();
}
});
};
// Clear selected VM
const clearSelectedVM = () => {
// Clear the input value
inputValue.value = '';
// Clear from localStorage
localStorage.removeItem('selectedVMId');
// Don't clear vmSearchText - that's for search history
// Only clear if the input value matches the selected VM
const savedVMId = localStorage.getItem('selectedVMId');
const savedSearchText = localStorage.getItem('vmSearchText');
if (savedSearchText === savedVMId) {
localStorage.removeItem('vmSearchText');
}
// Show the VM list
emit('toggle-list');
// Emit event to parent component
emit('clear-vm');
};
// Select a VM
const handleVMSelect = (vm) => {
console.log('Selecting VM:', vm);
// Update the input value to show the selected VM
inputValue.value = vm.name;
// Save the current search text before selecting a VM
if (props.modelValue) {
searchText.value = props.modelValue;
// Save to localStorage
localStorage.setItem('vmSearchText', props.modelValue);
}
// Save selected VM to localStorage
localStorage.setItem('selectedVMId', vm.name);
emit('select-vm', vm);
};
// Handle click outside
const handleClickOutside = (event) => {
// Handle filter menu clicks
if (showFilterMenu.value &&
filterMenu.value &&
!filterMenu.value.contains(event.target) &&
!filterDropdown.value.contains(event.target)) {
showFilterMenu.value = false;
}
// Handle closing the VM list when clicking outside
if (props.showList &&
controlsBar.value &&
!controlsBar.value.contains(event.target)) {
emit('toggle-list');
}
};
// Toggle filter menu
const toggleFilterMenu = () => {
showFilterMenu.value = !showFilterMenu.value;
};
// Filter toggle
const handleFilterToggle = (type, value) => {
appliedFilters.value[type][value] = !appliedFilters.value[type][value];
saveFiltersToLocalStorage();
};
// Reset filters
const handleResetFilters = () => {
Object.keys(appliedFilters.value.states).forEach(state => {
appliedFilters.value.states[state] = false;
});
Object.keys(appliedFilters.value.nodes).forEach(node => {
appliedFilters.value.nodes[node] = false;
});
saveFiltersToLocalStorage();
showFilterMenu.value = false;
};
// Computed properties
const filteredVMs = computed(() => {
let filtered = [...props.vmList];
// Apply text filter only if filtering is active
if (isFilterActive.value && props.modelValue) {
const query = props.modelValue.toLowerCase();
filtered = filtered.filter(vm =>
vm.name.toLowerCase().includes(query)
);
}
// Apply state filters
const activeStates = Object.entries(appliedFilters.value.states)
.filter(([_, isActive]) => isActive)
.map(([state]) => state);
if (activeStates.length > 0) {
filtered = filtered.filter(vm => activeStates.includes(vm.state));
}
// Apply node filters
const activeNodes = Object.entries(appliedFilters.value.nodes)
.filter(([_, isActive]) => isActive)
.map(([node]) => node);
if (activeNodes.length > 0) {
filtered = filtered.filter(vm => activeNodes.includes(vm.node));
}
return filtered;
});
// Calculate available states from vmList
const availableStates = computed(() => {
const states = new Set();
props.vmList.forEach(vm => {
if (vm.state) states.add(vm.state);
});
// Convert to array and ensure all important states are included
const statesArray = Array.from(states);
const importantStates = ['start', 'disable', 'migrate', 'unmigrate', 'provision', 'mirror', 'stop', 'fail', 'shutdown', 'restart'];
// Add any missing important states
importantStates.forEach(state => {
if (!statesArray.includes(state)) {
statesArray.push(state);
}
});
// Sort with 'start' first, then alphabetically
return statesArray.sort((a, b) => {
if (a.toLowerCase() === 'start') return -1;
if (b.toLowerCase() === 'start') return 1;
return a.localeCompare(b);
});
});
// Calculate available nodes from vmList
const availableNodes = computed(() => {
const nodes = new Set();
props.vmList.forEach(vm => {
if (vm.node) nodes.add(vm.node);
});
return Array.from(nodes).sort();
});
// Initialize filters when states/nodes change
watch([availableStates, availableNodes], ([states, nodes]) => {
// Initialize any new states
states.forEach(state => {
if (!(state in appliedFilters.value.states)) {
appliedFilters.value.states[state] = false;
}
});
// Initialize any new nodes
nodes.forEach(node => {
if (!(node in appliedFilters.value.nodes)) {
appliedFilters.value.nodes[node] = false;
}
});
// Save updated filters
saveFiltersToLocalStorage();
});
// Count active filters
const activeFiltersCount = computed(() => {
let count = 0;
Object.values(appliedFilters.value.states).forEach(isActive => {
if (isActive) count++;
});
Object.values(appliedFilters.value.nodes).forEach(isActive => {
if (isActive) count++;
});
return count;
});
// Update function name from getStatusClass to getStateClass
const getStateClass = (state) => {
if (!state) return 'status-unknown';
const lowerState = state.toLowerCase();
// Green for running VMs
if (lowerState === 'start') {
return 'status-running';
}
// Blue for provisioning, migration, etc.
if (['disable', 'migrate', 'unmigrate', 'provision'].includes(lowerState)) {
return 'status-provisioning';
}
// Purple for mirror
if (lowerState === 'mirror') {
return 'status-mirror';
}
// Red for stopped or failed VMs
if (['stop', 'fail'].includes(lowerState)) {
return 'status-stopped';
}
// Yellow for shutdown or restart
if (['shutdown', 'restart'].includes(lowerState)) {
return 'status-restarting';
}
// Default to unknown (black) for any other states
return 'status-unknown';
};
// Watch for changes in showList
watch(() => props.showList, (isVisible) => {
if (!isVisible) {
// When list is closed, show selected VM
const effectiveVM = props.selectedVM || props.vmFromUrl || localStorage.getItem('selectedVMId');
if (effectiveVM) {
inputValue.value = effectiveVM;
// Don't clear the model value when closing the list
// This ensures the search text is preserved
if (!props.modelValue && searchText.value) {
emit('update:modelValue', searchText.value);
}
}
} else {
// When list is opened, show search text if available
if (searchText.value) {
inputValue.value = searchText.value;
// Ensure the model value is updated to match the search text
if (props.modelValue !== searchText.value) {
emit('update:modelValue', searchText.value);
}
} else {
inputValue.value = '';
}
// Scroll to selected VM when list opens
scrollToSelectedVM();
}
});
// Watch for changes in selectedVM or vmFromUrl
watch([() => props.selectedVM, () => props.vmFromUrl], ([selectedVM, vmFromUrl]) => {
if (!props.showList) {
const effectiveVM = selectedVM || vmFromUrl || localStorage.getItem('selectedVMId');
if (effectiveVM) {
inputValue.value = effectiveVM;
}
}
});
// Add a function to scroll to the selected VM
const scrollToSelectedVM = () => {
nextTick(() => {
// Find the first selected VM
const selectedVMName = props.selectedVM || props.vmFromUrl || localStorage.getItem('selectedVMId');
if (selectedVMName && vmListContainer.value) {
const activeElement = vmListContainer.value.querySelector(`[data-vm-name="${selectedVMName}"]`);
if (activeElement) {
// Scroll the element into view
activeElement.scrollIntoView({ block: 'center', behavior: 'smooth' });
}
}
});
};
// Add localStorage persistence for filters
const saveFiltersToLocalStorage = () => {
localStorage.setItem('vmFilters', JSON.stringify(appliedFilters.value));
};
const loadFiltersFromLocalStorage = () => {
const savedFilters = localStorage.getItem('vmFilters');
if (savedFilters) {
try {
const parsedFilters = JSON.parse(savedFilters);
// Merge saved filters with current filters to handle new states/nodes
appliedFilters.value = {
states: { ...appliedFilters.value.states, ...parsedFilters.states },
nodes: { ...appliedFilters.value.nodes, ...parsedFilters.nodes }
};
} catch (e) {
console.error('Error parsing saved filters:', e);
}
}
};
</script>
<style scoped>
.vm-selector-bar {
display: flex;
flex-direction: column;
gap: 0.5rem;
background-color: white;
border-radius: 0.25rem;
padding-top: 0.25rem;
border-bottom: 1px solid rgba(0, 0, 0, 0.125);
}
.vm-selector-row {
display: flex;
align-items: center;
gap: 0.5rem;
padding-bottom: 0.75rem !important;
}
.search-box {
position: relative;
flex: 1;
min-width: 200px;
}
.search-icon {
position: absolute;
left: 10px;
top: 50%;
transform: translateY(-50%);
color: #6c757d;
}
.search-input {
padding-left: 30px;
padding-right: 30px;
}
.btn-clear {
position: absolute;
right: 10px;
top: 50%;
transform: translateY(-50%);
background: none;
border: none;
color: #6c757d;
cursor: pointer;
padding: 0;
font-size: 0.875rem;
transition: color 0.2s;
z-index: 5; /* Ensure it's above other elements */
}
.btn-clear:hover {
color: #dc3545; /* Red color on hover */
}
.list-toggle-btn {
display: flex;
align-items: center;
gap: 0.5rem;
}
.list-toggle-btn.active {
background-color: #0d6efd;
color: white;
border-color: #0d6efd;
}
.list-toggle-btn.filtering {
background-color: white;
color: #212529;
border-color: #6c757d;
}
.filter-dropdown {
position: relative;
}
.filter-badge {
display: inline-flex;
align-items: center;
justify-content: center;
width: 18px;
height: 18px;
background-color: #0d6efd;
color: white;
border-radius: 50%;
font-size: 0.7rem;
margin-left: 0.5rem;
}
/* VM List styles */
.vm-list-container {
background-color: white;
border-radius: 0.25rem;
overflow: hidden;
margin-top: -0.5rem;
padding-bottom: 0.25rem;
}
.vm-list {
display: flex;
flex-direction: column;
width: 100%;
max-height: calc(100vh - 200px);
overflow-y: auto;
padding-bottom: 0.25rem;
}
.vm-list-item {
display: flex;
align-items: center;
padding: 0.75rem 1rem;
border: none !important;
background-color: white;
text-align: left;
cursor: pointer;
transition: background-color 0.2s;
width: 100%;
}
.vm-list-item:last-child {
border-bottom: none !important;
margin-bottom: 0.25rem;
}
.vm-list-item:hover {
background-color: rgba(0, 0, 0, 0.03) !important;
}
.vm-list-item.active {
background-color: rgba(13, 110, 253, 0.15) !important;
position: relative !important;
z-index: 1 !important;
}
.vm-list-item.active::before {
content: '';
position: absolute !important;
left: 0 !important;
top: 0 !important;
bottom: 0 !important;
width: 4px !important;
background-color: #0d6efd !important;
z-index: 2 !important;
}
.vm-selector-bar .vm-list-container .vm-list .vm-list-item.active {
background-color: rgba(13, 110, 253, 0.15) !important;
position: relative !important;
}
.vm-selector-bar .vm-list-container .vm-list .vm-list-item.active::before {
content: '';
position: absolute !important;
left: 0 !important;
top: 0 !important;
bottom: 0 !important;
width: 4px !important;
background-color: #0d6efd !important;
}
.vm-item-content {
display: flex;
align-items: center;
width: 100%;
gap: 1rem;
}
.vm-name {
font-weight: 500;
flex: 1;
}
.vm-state {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.875rem;
width: 100px;
}
.vm-node {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.875rem;
color: #6c757d;
width: 100px;
}
.node-icon {
font-size: 0.75rem;
}
.state-indicator {
font-size: 0.625rem;
}
/* Status colors - updated */
.status-running {
color: #28a745; /* Green */
}
.status-stopped {
color: #dc3545; /* Red */
}
.status-provisioning {
color: #0d6efd; /* Blue */
}
.status-mirror {
color: #6f42c1; /* Purple */
}
.status-restarting {
color: #ffc107; /* Yellow */
}
.no-vms-message {
padding: 2rem;
text-align: center;
color: #6c757d;
}
/* Filter menu styles */
.filter-menu {
position: absolute;
top: 100%;
right: 0;
z-index: 1000;
min-width: 350px;
padding: 1rem;
margin-top: 0.5rem;
background-color: white;
border-radius: 0.25rem;
box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
}
.filter-section {
margin-bottom: 1rem;
}
.filter-section h6 {
margin-bottom: 0.5rem;
font-weight: 600;
color: #495057;
padding-bottom: 0.25rem;
}
.filter-options-dropdown {
max-height: 200px;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 0.25rem;
padding-left: 0.25rem;
}
.filter-pills {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
padding: 0.25rem;
}
.filter-pill {
display: inline-flex;
align-items: center;
padding: 0.25rem 0.75rem;
background-color: #f8f9fa;
border: 1px solid #dee2e6;
border-radius: 1rem;
font-size: 0.875rem;
cursor: pointer;
transition: all 0.2s;
}
.filter-pill:hover {
background-color: #e9ecef;
}
.filter-pill.active {
background-color: #0d6efd;
color: white;
border-color: #0d6efd;
}
.filter-actions {
display: flex;
justify-content: space-between;
border-top: 1px solid rgba(0, 0, 0, 0.1);
padding-top: 0.5rem;
margin-top: 0.5rem;
}
.active-indicator {
position: absolute !important;
left: 0 !important;
top: 0 !important;
bottom: 0 !important;
width: 4px !important;
background-color: #0d6efd !important;
z-index: 2 !important;
}
.search-input.search-active {
border-color: #0d6efd;
box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
}
</style>

View File

@ -0,0 +1,124 @@
<template>
<div class="metric-card">
<div class="card-header">
<h6 class="card-title mb-0">
<span class="metric-label">{{ title }}</span>
</h6>
</div>
<div class="card-body" :class="bgColorClass">
<h4 class="metric-value" :class="valueClass">{{ value }}</h4>
</div>
</div>
</template>
<script setup>
import { computed } from 'vue';
const props = defineProps({
title: {
type: String,
required: true
},
value: {
type: [String, Number],
required: true
},
valueClass: {
type: String,
default: ''
},
bgColor: {
type: String,
default: ''
}
});
// Compute the background color class based on the bgColor prop
const bgColorClass = computed(() => {
if (!props.bgColor) return '';
return `bg-${props.bgColor}`;
});
</script>
<style scoped>
.metric-card {
min-width: 180px;
background: white;
border: 1px solid rgba(0,0,0,0.125);
border-radius: 0.25rem;
height: 100%;
display: flex;
flex-direction: column;
min-width: 0;
width: 100%;
overflow: hidden;
}
/* Background color classes */
.bg-green {
background-color: rgba(40, 167, 69, 0.1);
}
.bg-yellow {
background-color: rgba(255, 193, 7, 0.1);
}
.bg-red {
background-color: rgba(220, 53, 69, 0.1);
}
.bg-blue {
background-color: rgba(13, 110, 253, 0.1);
}
.bg-gray {
background-color: rgba(108, 117, 125, 0.1);
}
.metric-card .card-header {
background-color: rgba(0, 0, 0, 0.03);
padding: 0.5rem;
border-bottom: 1px solid rgba(0, 0, 0, 0.125);
height: 38px;
display: flex;
justify-content: space-between;
align-items: center;
}
.card-header h6 {
font-size: 0.95rem;
font-weight: 600;
display: flex;
justify-content: space-between;
align-items: center;
margin: 0;
}
.metric-card .card-body {
flex: 1;
padding: 0.5rem;
display: flex;
flex-direction: column;
position: relative;
width: 100%;
overflow: visible;
justify-content: center;
align-items: center;
}
.metric-value {
font-size: 1.25rem;
font-weight: bold;
color: #333;
line-height: 1;
margin: 0;
text-align: center;
white-space: nowrap;
min-width: fit-content;
}
.metric-label {
color: #495057;
font-weight: 600;
}
</style>

View File

@ -0,0 +1,760 @@
<template>
<NodeSelectBar
v-model="selectedNode"
:nodes="availableNodes"
@select="handleNodeSelect"
/>
<!-- Node Details -->
<div v-if="selectedNodeData" class="content-container">
<!-- Information Cards Section -->
<CollapsibleSection title="Node Information" :initially-expanded="sections.info">
<div class="info-row">
<!-- Card 1: Daemon State -->
<ValueCard
title="Daemon State"
:value="selectedNodeData.daemon_state || 'Unknown'"
:bg-color="getDaemonStateColor(selectedNodeData.daemon_state)"
/>
<!-- Card 2: Coordinator State -->
<ValueCard
title="Coordinator State"
:value="selectedNodeData.coordinator_state || 'Unknown'"
:bg-color="getCoordinatorStateColor(selectedNodeData.coordinator_state)"
/>
<!-- Card 3: Domain State -->
<ValueCard
title="Domain State"
:value="selectedNodeData.domain_state || 'Unknown'"
:bg-color="getDomainStateColor(selectedNodeData.domain_state)"
/>
<!-- Card 4: PVC Version -->
<ValueCard
title="PVC Version"
:value="selectedNodeData.pvc_version || 'Unknown'"
/>
<!-- Card 5: Kernel Version -->
<ValueCard
title="Kernel Version"
:value="selectedNodeData.kernel || 'Unknown'"
/>
<!-- Card 6: VM Count -->
<ValueCard
title="VM Count"
:value="selectedNodeData.domains_count || 0"
/>
</div>
</CollapsibleSection>
<!-- Utilization Graphs Section -->
<CollapsibleSection title="Health & Utilization Graphs" :initially-expanded="sections.graphs">
<div class="graphs-row">
<!-- Health Chart -->
<HealthChart
title="Node Health"
:value="selectedNodeData.health || 0"
:chart-data="nodeHealthChartData"
:maintenance="isMaintenanceMode"
/>
<!-- CPU Utilization Chart -->
<CPUChart
title="CPU Utilization"
:value="calculateCpuUtilization(selectedNodeData)"
:chart-data="nodeCpuChartData"
/>
<!-- Memory Utilization Chart -->
<MemoryChart
title="Memory Utilization"
:value="calculateMemoryUtilization(selectedNodeData)"
:chart-data="nodeMemoryChartData"
/>
<!-- Allocated Memory Chart -->
<StorageChart
title="Allocated Memory"
:value="calculateAllocatedMemory(selectedNodeData)"
:chart-data="nodeAllocatedMemoryChartData"
/>
</div>
</CollapsibleSection>
<!-- CPU Resources Section -->
<CollapsibleSection title="CPU Resources" :initially-expanded="sections.cpu">
<div class="resources-row-cpu">
<!-- Card 1: Host CPUs -->
<ValueCard
title="Host CPUs"
:value="selectedNodeData.cpu_count || 0"
/>
<!-- Card 2: Guest CPUs -->
<ValueCard
title="Guest CPUs"
:value="selectedNodeData.vcpu?.allocated || 0"
/>
<!-- Card 3: Load -->
<ValueCard
title="Load"
:value="selectedNodeData.load || 0"
/>
</div>
</CollapsibleSection>
<!-- Memory Resources Section -->
<CollapsibleSection title="Memory Resources" :initially-expanded="sections.resources">
<div class="resources-row-memory">
<!-- Total Memory -->
<ValueCard
title="Total Memory"
:value="formatMemory(selectedNodeData.memory?.total)"
/>
<!-- Used Memory -->
<ValueCard
title="Used Memory"
:value="formatMemory(selectedNodeData.memory?.used)"
/>
<!-- Free Memory -->
<ValueCard
title="Free Memory"
:value="formatMemory(selectedNodeData.memory?.free)"
/>
<!-- Allocated Memory -->
<ValueCard
title="Allocated Memory"
:value="formatMemory(selectedNodeData.memory?.allocated)"
/>
<!-- Provisioned Memory -->
<ValueCard
title="Provisioned Memory"
:value="formatMemory(selectedNodeData.memory?.provisioned)"
/>
</div>
</CollapsibleSection>
<!-- Running VMs Section -->
<CollapsibleSection title="Running VMs" :initially-expanded="sections.vms">
<div class="vm-list-row">
<NodeVMList
:vmData="props.vmData"
:nodeData="props.nodeData"
:nodeName="selectedNode"
/>
</div>
</CollapsibleSection>
<!-- Health Details Section -->
<CollapsibleSection title="Health Details" :initially-expanded="sections.health">
<div class="health-details-row">
<!-- Health messages card -->
<div class="metric-card">
<div class="card-header">
<h6 class="card-title mb-0 metric-label">Health Messages</h6>
</div>
<div class="card-body">
<div class="messages-list">
<template v-if="nodeHealthMessages.length">
<div
v-for="(msg, idx) in nodeHealthMessages"
:key="idx"
:class="[
'health-message',
getHealthMessageClass(msg),
]"
>
<div class="message-header">
<i class="fas" :class="getMessageIcon(msg)"></i>
<span class="message-id">{{ msg.name }}</span>
<span v-if="msg.health_delta > 0" class="health-delta">
(-{{ msg.health_delta }}%)
</span>
</div>
<div class="message-content">
{{ getMessageContent(msg) }}
</div>
</div>
</template>
<div v-else class="health-message healthy">
<div class="message-header">
<i class="fas fa-circle-check me-1"></i>
<span class="message-id">Node healthy</span>
</div>
<div class="message-content">
Node is at full health with no faults
</div>
</div>
</div>
</div>
</div>
</div>
</CollapsibleSection>
</div>
<!-- No node selected message -->
<div v-else class="no-node-selected">
<p>Select a node to view details</p>
</div>
</template>
<script setup>
// Import all the same components and functions from the original Nodes.vue
import { ref, computed, onMounted, watch, nextTick, onUnmounted } from 'vue';
import CPUChart from '../../charts/CPUChart.vue';
import MemoryChart from '../../charts/MemoryChart.vue';
import StorageChart from '../../charts/StorageChart.vue';
import HealthChart from '../../charts/HealthChart.vue';
import ValueCard from '../../general/ValueCard.vue';
import CollapsibleSection from '../../general/CollapsibleSection.vue';
import NodeSelectBar from '../../general/NodeSelectBar.vue';
import NodeVMList from './NodeVMList.vue';
import { useRouter, useRoute } from 'vue-router';
// Move all the props, refs, computed properties, and functions from Nodes.vue
const props = defineProps({
nodeData: {
type: Array,
required: true,
default: () => []
},
metricsData: {
type: Object,
required: true,
default: () => ({})
},
clusterData: {
type: Object,
required: true,
default: () => ({})
},
vmData: {
type: Array,
required: true,
default: () => []
}
});
// State for sections (expanded/collapsed)
const sections = ref({
info: true,
graphs: true,
cpu: true,
resources: true,
vms: true,
health: true
});
// State for selected node and tab scrolling
const selectedNode = ref('');
const tabsContainer = ref(null);
const showLeftScroll = ref(false);
const showRightScroll = ref(false);
// Get the selected node data
const selectedNodeData = computed(() => {
if (!selectedNode.value || !props.nodeData) return null;
return props.nodeData.find(node => node.name === selectedNode.value) || null;
});
// Select a node
const selectNode = (nodeName) => {
selectedNode.value = nodeName;
// Scroll the selected tab into view
nextTick(() => {
const activeTab = tabsContainer.value?.querySelector('.node-tab.active');
if (activeTab) {
activeTab.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
}
// Check if scroll buttons should be shown
checkScrollButtons();
});
};
// Check if scroll buttons should be shown
const checkScrollButtons = () => {
if (!tabsContainer.value) return;
const { scrollLeft, scrollWidth, clientWidth } = tabsContainer.value;
// Show left scroll button if not at the beginning
showLeftScroll.value = scrollLeft > 0;
// Show right scroll button if not at the end
showRightScroll.value = scrollLeft + clientWidth < scrollWidth - 1; // -1 for rounding errors
};
// Scroll tabs left or right
const scrollTabs = (direction) => {
if (!tabsContainer.value) return;
const scrollAmount = tabsContainer.value.clientWidth / 2;
const currentScroll = tabsContainer.value.scrollLeft;
if (direction === 'left') {
tabsContainer.value.scrollTo({
left: Math.max(0, currentScroll - scrollAmount),
behavior: 'smooth'
});
} else {
tabsContainer.value.scrollTo({
left: currentScroll + scrollAmount,
behavior: 'smooth'
});
}
// Check scroll buttons after scrolling
setTimeout(checkScrollButtons, 300);
};
// Calculate CPU utilization (load / cpu_count * 100)
const calculateCpuUtilization = (nodeData) => {
if (!nodeData || !nodeData.load || !nodeData.cpu_count) return 0;
const utilization = (nodeData.load / nodeData.cpu_count) * 100;
return Math.round(utilization);
};
// Calculate memory utilization
const calculateMemoryUtilization = (node) => {
if (!node || !node.memory) return 0;
const used = node.memory.used || 0;
const total = node.memory.total || 1; // Avoid division by zero
if (total === 0) return 0;
return Math.round((used / total) * 100);
};
// Calculate allocated memory
const calculateAllocatedMemory = (node) => {
if (!node || !node.memory) return 0;
const allocated = node.memory.allocated || 0;
const total = node.memory.total || 1; // Avoid division by zero
if (total === 0) return 0;
return Math.round((allocated / total) * 100);
};
// Format memory values
const formatMemory = (memoryMB) => {
if (!memoryMB) return '0 GB';
// The values are already in MB, so we just need to convert to GB
return Math.round(memoryMB / 1024) + ' GB';
};
// Check if the cluster is in maintenance mode
const isMaintenanceMode = computed(() => {
return props.clusterData.maintenance === "true";
});
// Update the nodeHealthChartData computed property to include maintenance data
const nodeHealthChartData = computed(() => {
// Get node metrics history if available
const nodeMetrics = props.metricsData.nodes?.[selectedNodeData.value?.name];
if (nodeMetrics && nodeMetrics.health && nodeMetrics.health.data.length > 0) {
return {
labels: nodeMetrics.health.labels,
data: nodeMetrics.health.data,
maintenance: nodeMetrics.health.maintenance || []
};
}
// Fallback to current value only
return {
labels: ['Health'],
data: [selectedNodeData.value?.health || 0],
maintenance: [isMaintenanceMode.value]
};
});
const nodeCpuChartData = computed(() => {
// Get node metrics history if available
const nodeMetrics = props.metricsData.nodes?.[selectedNodeData.value?.name];
if (nodeMetrics && nodeMetrics.cpu && nodeMetrics.cpu.data.length > 0) {
return {
labels: nodeMetrics.cpu.labels,
data: nodeMetrics.cpu.data
};
}
// Fallback to current value only
return {
labels: ['CPU'],
data: [calculateCpuUtilization(selectedNodeData.value)]
};
});
const nodeMemoryChartData = computed(() => {
if (!selectedNodeData.value) return { labels: [], data: [] };
// Get node metrics history if available
const nodeMetrics = props.metricsData.nodes?.[selectedNodeData.value.name];
if (nodeMetrics && nodeMetrics.memory && nodeMetrics.memory.data.length > 0) {
return {
labels: nodeMetrics.memory.labels,
data: nodeMetrics.memory.data
};
}
// Fallback to current value only
return {
labels: ['Memory'],
data: [calculateMemoryUtilization(selectedNodeData.value)]
};
});
const nodeAllocatedMemoryChartData = computed(() => {
if (!selectedNodeData.value) return { labels: [], data: [] };
// Get node metrics history if available
const nodeMetrics = props.metricsData.nodes?.[selectedNodeData.value.name];
if (nodeMetrics && nodeMetrics.allocated && nodeMetrics.allocated.data.length > 0) {
return {
labels: nodeMetrics.allocated.labels,
data: nodeMetrics.allocated.data
};
}
// Fallback to current value only
return {
labels: ['Allocated'],
data: [calculateAllocatedMemory(selectedNodeData.value)]
};
});
// Helper functions for state colors
const getDaemonStateColor = (state) => {
if (!state) return '';
if (state === 'run') return 'green';
if (['init', 'shutdown'].includes(state)) return 'yellow';
if (['stop', 'dead', 'fenced'].includes(state)) return 'red';
return 'blue';
};
const getCoordinatorStateColor = (state) => {
if (!state) return '';
if (state === 'primary') return 'green';
if (state === 'secondary') return 'blue';
if (state === 'hypervisor') return 'gray';
return '';
};
const getDomainStateColor = (state) => {
if (!state) return '';
if (state === 'ready') return 'green';
if (['flushing', 'flushed', 'unflushing'].includes(state)) return 'blue';
return 'gray';
};
// Initialize the component
onMounted(() => {
// Check if there's a saved node selection
const savedNodeId = localStorage.getItem('selectedNodeId');
if (savedNodeId && props.nodeData.some(node => node.name === savedNodeId)) {
selectNode(savedNodeId);
} else if (props.nodeData && props.nodeData.length > 0) {
// Fall back to selecting the first node
selectNode(props.nodeData[0].name);
}
// Check if scroll buttons should be shown
window.addEventListener('resize', checkScrollButtons);
nextTick(checkScrollButtons);
});
// Watch for changes in the nodes data
watch(() => props.nodeData, () => {
// If the currently selected node no longer exists, select the first available node
if (props.nodeData && props.nodeData.length > 0 && !props.nodeData.find(node => node.name === selectedNode.value)) {
selectNode(props.nodeData[0].name);
}
// Check if scroll buttons should be shown
nextTick(checkScrollButtons);
}, { deep: true });
// Clean up event listeners
onUnmounted(() => {
window.removeEventListener('resize', checkScrollButtons);
});
const availableNodes = computed(() => {
return props.nodeData.map(node => node.name).sort();
});
const handleNodeSelect = (node) => {
selectedNode.value = node;
// Save to localStorage
localStorage.setItem('selectedNodeId', node);
};
// Process node health messages
const nodeHealthMessages = computed(() => {
if (!selectedNodeData.value || !selectedNodeData.value.health_details) {
return [];
}
const healthDetails = selectedNodeData.value.health_details;
// Make sure we're getting an array of health details
if (Array.isArray(healthDetails)) {
return healthDetails;
} else if (typeof healthDetails === 'object') {
// If it's an object, convert to array
return Object.values(healthDetails);
}
return [];
});
// Helper function to determine message class based on health status
const getHealthMessageClass = (msg) => {
if (msg.health_delta >= 25) {
return 'delta-high'; // Red for critical issues (>=25%)
}
if (msg.health_delta > 0) {
return 'delta-medium';
}
return 'delta-low'; // Green for healthy items
};
// Helper function to get appropriate icon for health message
const getMessageIcon = (msg) => {
if (msg.health_delta >= 25) {
return 'fa-circle-exclamation me-1'; // Warning icon for significant issues
}
if (msg.health_delta > 0) {
return 'fa-info-circle me-1'; // Info icon for minor issues
}
return 'fa-circle-check me-1'; // Checkmark for healthy items
};
// Helper function to format message content
const getMessageContent = (msg) => {
return msg.message || 'No details available';
};
const selectVM = (vmId) => {
// Store the VM ID in localStorage so it will be selected when the VMs page loads
localStorage.setItem('selectedVMId', vmId);
};
</script>
<style scoped>
/* Add these missing styles from the original Nodes.vue */
.content-container {
background-color: white;
border-radius: 0.25rem;
width: 100%;
padding-top: 0.25rem;
}
.loading-container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 2rem;
}
.info-row, .graphs-row, .resources-row-cpu, .resources-row-memory, .vm-list-row {
display: grid;
gap: 0.5rem;
width: 100%;
}
.health-details-row {
display: grid;
gap: 0.5rem;
width: 100%;
}
/* Responsive grid layouts */
@media (min-width: 1201px) {
.info-row {
grid-template-columns: repeat(3, 1fr);
}
.graphs-row {
grid-template-columns: repeat(4, 1fr);
}
.resources-row-cpu {
grid-template-columns: repeat(3, 1fr);
}
.resources-row-memory {
grid-template-columns: repeat(5, 1fr);
}
.health-details-row {
grid-template-columns: 1fr;
}
}
@media (min-width: 801px) and (max-width: 1200px) {
.info-row {
grid-template-columns: repeat(2, 1fr);
}
.graphs-row {
grid-template-columns: repeat(2, 1fr);
}
.resources-row-cpu {
grid-template-columns: repeat(3, 1fr);
}
.resources-row-memory {
grid-template-columns: repeat(3, 1fr);
}
.health-details-row {
grid-template-columns: 1fr;
}
}
@media (max-width: 800px) {
.info-row,
.graphs-row,
.resources-row-cpu,
.resources-row-memory {
grid-template-columns: 1fr;
}
.health-details-row {
grid-template-columns: 1fr;
}
}
.messages-list {
display: flex;
flex-direction: column;
gap: 0.5rem;
width: 100%;
align-self: flex-start;
}
.health-message {
font-size: 0.875rem;
text-align: left;
padding: 0.5rem;
border-radius: 0.25rem;
position: relative;
height: auto;
display: flex;
flex-direction: column;
min-width: 0;
flex: 1;
/* Default styling - will be overridden by delta classes */
background: rgba(108, 117, 125, 0.15);
color: #495057;
}
.message-header {
display: flex;
align-items: center;
font-weight: 500;
margin-bottom: 0.25rem;
}
.message-id {
font-weight: 600;
}
.message-content {
font-size: 0.8rem;
line-height: 1.4;
white-space: pre-line; /* Allow line breaks in content */
color: inherit;
opacity: 0.9;
}
.health-message.healthy {
background: rgba(40, 167, 69, 0.1);
color: #0d5524;
}
.delta-low {
background: rgba(40, 167, 69, 0.15); /* Green background */
color: #0d5524;
}
.delta-medium {
background: rgba(255, 193, 7, 0.15); /* Yellow background */
color: #856404;
}
.delta-high {
background: rgba(220, 53, 69, 0.15); /* Red background */
color: #721c24;
}
.delta-info {
background: rgba(13, 110, 253, 0.15); /* Blue background */
color: #0d6efd;
}
.health-delta {
margin-left: 0.5rem;
font-size: 0.8em;
}
.metric-card {
min-width: 180px;
background: white;
border: 1px solid rgba(0,0,0,0.125);
border-radius: 0.25rem;
height: 100%;
display: flex;
flex-direction: column;
min-width: 0;
width: 100%;
overflow: hidden;
}
.metric-card .card-header {
background-color: rgba(0, 0, 0, 0.03);
padding: 0.5rem;
border-bottom: 1px solid rgba(0, 0, 0, 0.125);
height: 38px;
display: flex;
align-items: center;
}
.card-header h6 {
font-size: 0.95rem;
font-weight: 600;
display: flex;
justify-content: space-between;
align-items: center;
margin: 0;
line-height: 1.2;
}
.metric-card .card-body {
flex: 1;
padding: 0.5rem;
display: flex;
flex-direction: column;
position: relative;
width: 100%;
overflow: visible;
justify-content: flex-start;
align-items: center;
}
</style>

View File

@ -38,6 +38,7 @@
<script setup> <script setup>
import { ref } from 'vue'; import { ref } from 'vue';
import ValueCard from '../../general/ValueCard.vue';
const props = defineProps({ const props = defineProps({
nodeData: { nodeData: {
@ -60,7 +61,7 @@ const formatMemory = (node) => {
if (!node.memory || typeof node.memory !== 'object') { if (!node.memory || typeof node.memory !== 'object') {
return { used: 'N/A', total: 'N/A', percent: 'N/A' }; return { used: 'N/A', total: 'N/A', percent: 'N/A' };
} }
// Convert MB to GB with 2 decimal places // Convert MB to GB with 2 decimal places
const toGB = (mb) => { const toGB = (mb) => {
if (typeof mb !== 'number' || isNaN(mb)) { if (typeof mb !== 'number' || isNaN(mb)) {
@ -68,17 +69,17 @@ const formatMemory = (node) => {
} }
return (mb / 1024).toFixed(2); return (mb / 1024).toFixed(2);
}; };
// Extract values from the Proxy object // Extract values from the Proxy object
const memoryData = Object.assign({}, node.memory); const memoryData = Object.assign({}, node.memory);
const used = toGB(memoryData.used); const used = toGB(memoryData.used);
const total = toGB(memoryData.total); const total = toGB(memoryData.total);
let percent = 'N/A'; let percent = 'N/A';
if (used !== 'N/A' && total !== 'N/A' && parseFloat(total) > 0) { if (used !== 'N/A' && total !== 'N/A' && parseFloat(total) > 0) {
percent = Math.round((parseFloat(used) / parseFloat(total)) * 100); percent = Math.round((parseFloat(used) / parseFloat(total)) * 100);
} }
return { used, total, percent }; return { used, total, percent };
}; };
</script> </script>

View File

@ -0,0 +1,156 @@
<template>
<div class="vms-container">
<div class="card-header">
<h6 class="card-title mb-0">
<span class="metric-label">Running VMs</span>
</h6>
</div>
<div v-if="!runningDomains || runningDomains.length === 0" class="no-vms">
No VMs running on this node
</div>
<div v-else class="vm-list" :style="{
'grid-template-columns': `repeat(auto-fill, minmax(150px, 1fr))`
}">
<div
v-for="vmName in runningDomains"
:key="vmName"
class="vm-item"
@click="selectVMAndNavigate(vmName)"
>
{{ vmName }}
</div>
</div>
</div>
</template>
<script setup>
import { computed } from 'vue';
import { useRouter } from 'vue-router';
import { navigateToVM } from '../../../services/navigation';
const props = defineProps({
vmData: {
type: Array,
required: true,
default: () => []
},
nodeData: {
type: Array,
required: true,
default: () => []
},
nodeName: {
type: String,
required: true
}
});
const router = useRouter();
// Get the selected node data
const nodeData = computed(() => {
if (!props.nodeName || !props.nodeData || props.nodeData.length === 0) {
console.log('No node selected or no node data available');
return null;
}
const node = props.nodeData.find(node => node.name === props.nodeName);
console.log(`Node data for ${props.nodeName}:`, node);
return node;
});
// Get running domains from the node data
const runningDomains = computed(() => {
if (!nodeData.value || !nodeData.value.running_domains) {
console.log('No running domains found for node:', props.nodeName);
return [];
}
console.log(`Found ${nodeData.value.running_domains.length} running domains on node ${props.nodeName}:`, nodeData.value.running_domains);
return nodeData.value.running_domains;
});
// Navigate to VM details using the navigation service
const selectVMAndNavigate = (vmName) => {
navigateToVM(vmName, router);
};
</script>
<style scoped>
.vms-container {
min-width: 180px;
background: white;
border: 1px solid rgba(0,0,0,0.125);
border-radius: 0.25rem;
height: 100%;
display: flex;
flex-direction: column;
min-width: 0;
width: 100%;
overflow: hidden;
}
.card-header {
background-color: rgba(0, 0, 0, 0.03);
padding: 0.5rem;
border-bottom: 1px solid rgba(0, 0, 0, 0.125);
height: 38px;
display: flex;
justify-content: space-between;
align-items: center;
}
.card-header h6 {
font-size: 0.95rem;
font-weight: 600;
display: flex;
justify-content: space-between;
align-items: center;
margin: 0;
}
.no-vms {
display: flex;
justify-content: center;
align-items: center;
height: 100px;
color: #6c757d;
font-style: italic;
}
.vm-list {
display: grid;
gap: 0.5rem;
width: 100%;
padding: 0.5rem;
border-radius: 0.25rem;
}
.vm-item {
padding: 0.5rem;
background-color: rgba(0, 0, 0, 0.015);
border: 1px solid rgba(0, 0, 0, 0.05);
border-radius: 0.25rem;
cursor: pointer;
text-align: center;
font-weight: 500;
color: #333;
transition: all 0.2s;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
position: relative;
display: block;
}
.vm-item:hover {
background-color: rgba(0, 0, 0, 0.04);
border-color: rgba(0, 0, 0, 0.1);
}
.vm-node {
font-size: 0.7rem;
color: #6c757d;
margin-top: 0.25rem;
}
</style>

View File

@ -0,0 +1,157 @@
<template>
<div class="vm-detail">
<!-- Basic Info Section -->
<CollapsibleSection title="VM Information" :initially-expanded="sections.info">
<div class="info-row">
<ValueCard
title="State"
:value="vm.state || 'Unknown'"
:status="getStateColor(vm.state)"
/>
<ValueCard
title="Node"
:value="vm.node || 'N/A'"
/>
<ValueCard
title="CPUs"
:value="vm.vcpus || 0"
/>
<ValueCard
title="Memory"
:value="formatMemory(vm.memory)"
/>
</div>
</CollapsibleSection>
<!-- Resources Section -->
<CollapsibleSection title="Resources" :initially-expanded="sections.resources">
<div class="resources-row">
<ValueCard
title="Disk Size"
:value="formatStorage(vm.disk_size)"
/>
<ValueCard
title="Network IPs"
:value="vm.ips?.join(', ') || 'None'"
/>
</div>
</CollapsibleSection>
<!-- Networks Section -->
<CollapsibleSection
v-if="vm.networks?.length"
title="Network Interfaces"
:initially-expanded="sections.networks"
>
<div class="networks-row">
<div v-for="network in vm.networks" :key="network.vni" class="network-card">
<ValueCard title="Interface" :value="network.vni" />
<ValueCard title="Type" :value="network.type" />
<ValueCard title="MAC" :value="network.mac" />
<ValueCard title="Source" :value="network.source" />
</div>
</div>
</CollapsibleSection>
<!-- Storage Section -->
<CollapsibleSection
v-if="vm.disks?.length"
title="Storage"
:initially-expanded="sections.storage"
>
<div class="storage-row">
<div v-for="disk in vm.disks" :key="disk.dev" class="storage-card">
<ValueCard title="Device" :value="disk.dev" />
<ValueCard title="Type" :value="disk.type" />
<ValueCard title="Bus" :value="disk.bus" />
<ValueCard title="Source" :value="disk.name" />
</div>
</div>
</CollapsibleSection>
</div>
</template>
<script setup>
import { ref } from 'vue';
import CollapsibleSection from '../../general/CollapsibleSection.vue';
import ValueCard from '../../general/ValueCard.vue';
const props = defineProps({
vm: {
type: Object,
required: true
}
});
// Section visibility state
const sections = ref({
info: true,
resources: true,
networks: true,
storage: true
});
// Helper functions
const getStateColor = (state) => {
if (!state) return '';
switch(state.toLowerCase()) {
case 'start': return 'success';
case 'stop': return 'danger';
case 'disable': return 'warning';
default: return '';
}
};
const formatMemory = (memoryMB) => {
if (!memoryMB) return '0 GB';
return Math.round(memoryMB / 1024) + ' GB';
};
const formatStorage = (sizeGB) => {
if (!sizeGB) return '0 GB';
if (sizeGB < 1024) return sizeGB + ' GB';
return (sizeGB / 1024).toFixed(1) + ' TB';
};
</script>
<style scoped>
.vm-detail {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.info-row,
.resources-row {
display: grid;
gap: 0.5rem;
width: 100%;
}
.networks-row,
.storage-row {
display: flex;
flex-direction: column;
gap: 1rem;
}
.network-card,
.storage-card {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 0.5rem;
padding: 0.5rem;
background-color: rgba(0, 0, 0, 0.02);
border-radius: 0.25rem;
}
@media (min-width: 1201px) {
.info-row { grid-template-columns: repeat(4, 1fr); }
.resources-row { grid-template-columns: repeat(2, 1fr); }
}
@media (max-width: 1200px) {
.info-row { grid-template-columns: repeat(2, 1fr); }
.resources-row { grid-template-columns: 1fr; }
}
</style>

View File

@ -0,0 +1,440 @@
<template>
<VMSearchBar
:key="`vm-search-${selectedVM}`"
v-model="searchQuery"
:selected-vm="selectedVM"
:vm-from-url="route.query.vm"
:show-list="showVMList"
:show-clear-button="true"
:vm-list="props.vmData"
@search="handleSearch"
@focus="handleSearchFocus"
@blur="handleSearchBlur"
@clear="clearSearch"
@toggle-list="toggleVMList"
@select-vm="selectVM"
@clear-vm="clearSelectedVM"
/>
<!-- VM Details -->
<div v-if="selectedVMData && !showVMList" class="content-container">
<CollapsibleSection title="VM Information" :initially-expanded="sections.info">
<div class="info-grid-general">
<ValueCard
title="State"
:value="selectedVMData.state || 'Unknown'"
:status="getStateColor(selectedVMData.state)"
/>
<ValueCard
title="Node"
:value="selectedVMData.node || 'N/A'"
/>
<ValueCard
title="CPUs"
:value="selectedVMData.vcpus || 0"
/>
<ValueCard
title="Memory"
:value="formatMemory(selectedVMData.memory)"
/>
</div>
</CollapsibleSection>
<!-- Resources Section -->
<CollapsibleSection title="Resources" :initially-expanded="sections.resources">
<div class="info-grid-resources">
<ValueCard
title="Disk Size"
:value="formatStorage(selectedVMData.disk_size)"
/>
<ValueCard
title="Network IPs"
:value="selectedVMData.ips?.join(', ') || 'None'"
/>
</div>
</CollapsibleSection>
<!-- Networks Section -->
<CollapsibleSection
v-if="selectedVMData.networks?.length"
title="Network Interfaces"
:initially-expanded="sections.networks"
>
<div class="cards-stack">
<div v-for="network in selectedVMData.networks"
:key="network.vni"
class="detail-card"
>
<ValueCard title="Interface" :value="network.vni" />
<ValueCard title="Type" :value="network.type" />
<ValueCard title="MAC" :value="network.mac" />
<ValueCard title="Source" :value="network.source" />
</div>
</div>
</CollapsibleSection>
<!-- Storage Section -->
<CollapsibleSection
v-if="selectedVMData.disks?.length"
title="Storage"
:initially-expanded="sections.storage"
>
<div class="cards-stack">
<div v-for="disk in selectedVMData.disks"
:key="disk.dev"
class="detail-card"
>
<ValueCard title="Device" :value="disk.dev" />
<ValueCard title="Type" :value="disk.type" />
<ValueCard title="Bus" :value="disk.bus" />
<ValueCard title="Source" :value="disk.name" />
</div>
</div>
</CollapsibleSection>
</div>
<!-- Loading and no-selection states -->
<div v-if="!selectedVMData && !showVMList" class="content-container">
<div v-if="isLoading" class="loading-container">
<div class="spinner-border text-primary" role="status">
<span class="visually-hidden">Loading...</span>
</div>
<p class="mt-2 text-muted">Loading VM details...</p>
</div>
<div v-else class="no-content-message">
<div class="alert alert-info">
<i class="fas fa-info-circle me-2"></i>
<span v-if="invalidVMSelected">
Selected VM does not exist
</span>
<span v-else>
Please select a VM from the list to view its details
</span>
</div>
</div>
</div>
</template>
<script setup>
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import CollapsibleSection from '../../general/CollapsibleSection.vue';
import ValueCard from '../../general/ValueCard.vue';
import VMSearchBar from '../../general/VMSearchBar.vue';
const router = useRouter();
const route = useRoute();
const props = defineProps({
vmData: {
type: Array,
required: true,
default: () => []
},
metricsData: {
type: Object,
required: true,
default: () => ({})
},
clusterData: {
type: Object,
required: true,
default: () => ({})
},
loading: {
type: Boolean,
default: false
}
});
// Use ref and sync with route
const selectedVM = ref('');
const searchQuery = ref('');
const showVMList = ref(true);
const searchActive = ref(false);
const invalidVMSelected = ref(false);
const isLoading = ref(false);
const sections = ref({
info: true,
graphs: true,
resources: true,
network: true,
storage: true
});
// Get the selected VM data
const selectedVMData = computed(() => {
if (!selectedVM.value || !props.vmData) return null;
return props.vmData.find(vm => vm.name === selectedVM.value) || null;
});
// Handle search input
const handleSearch = (value) => {
searchQuery.value = value;
searchActive.value = true;
// Store the search query in localStorage for persistence
if (value) {
localStorage.setItem('vmSearchQuery', value);
// Also save to vmSearchText for consistency
localStorage.setItem('vmSearchText', value);
} else {
localStorage.removeItem('vmSearchQuery');
// Don't remove vmSearchText here - it's used for search history
}
};
// Handle search focus
const handleSearchFocus = () => {
if (!showVMList.value) {
showVMList.value = true;
}
searchActive.value = true;
};
// Handle search blur
const handleSearchBlur = (event) => {
// Keep blur logic for handling clicks outside
// ... existing blur logic ...
};
// Toggle VM list visibility
const toggleVMList = () => {
showVMList.value = !showVMList.value;
if (showVMList.value) {
// When opening the list
searchActive.value = false;
invalidVMSelected.value = false;
// Restore search text if available
const savedSearchText = localStorage.getItem('vmSearchText');
if (savedSearchText && !searchQuery.value) {
searchQuery.value = savedSearchText;
}
}
};
// Select a VM
const selectVM = (vm) => {
console.log('VMOverview selectVM called with:', vm);
// Update the ref
selectedVM.value = vm.name;
invalidVMSelected.value = false;
// Close the VM list
showVMList.value = false;
// Save to localStorage
localStorage.setItem('selectedVMId', vm.name);
// No URL parameter update
};
// Clear search
const clearSearch = () => {
searchQuery.value = '';
searchActive.value = false;
localStorage.removeItem('vmSearchQuery');
};
// Add a method to clear the selected VM
const clearSelectedVM = () => {
// Clear the selected VM
selectedVM.value = '';
invalidVMSelected.value = false;
// Clear the search query in this component
searchQuery.value = '';
// Show the VM list
showVMList.value = true;
// Clear VM selection from localStorage
localStorage.removeItem('selectedVMId');
// Don't clear vmSearchText unless it matches the VM name
const savedVMId = localStorage.getItem('selectedVMId');
const savedSearchText = localStorage.getItem('vmSearchText');
if (savedSearchText === savedVMId) {
localStorage.removeItem('vmSearchText');
}
// Clear URL parameter if it exists
if (route.query.vm) {
router.replace({ path: '/vms' }, { replace: true });
}
};
// Lifecycle hooks
onMounted(() => {
console.log('VMOverview mounted');
isLoading.value = true;
// Check sources in priority order:
// 1. localStorage (for returning to the page or navigating from other pages)
// 2. URL query parameter (for backward compatibility)
const savedVMId = localStorage.getItem('selectedVMId');
const vmFromQuery = route.query.vm;
// Restore previous search query from localStorage
const savedSearch = localStorage.getItem('vmSearchQuery');
const savedSearchText = localStorage.getItem('vmSearchText');
// If we have a VM to select
let vmToSelect = savedVMId || vmFromQuery;
if (vmToSelect && props.vmData.length > 0) {
// Check if the VM exists
const vmExists = props.vmData.some(v => v.name === vmToSelect);
if (vmExists) {
selectedVM.value = vmToSelect;
showVMList.value = false;
// Set the search query to the VM name for display in the search bar
searchQuery.value = vmToSelect;
// If from URL, save to localStorage for persistence
if (vmFromQuery && !savedVMId) {
localStorage.setItem('selectedVMId', vmFromQuery);
// Remove the VM ID from the URL without reloading the page
router.replace({ path: '/vms' }, { replace: true });
}
} else {
console.log('Selected VM does not exist:', vmToSelect);
invalidVMSelected.value = true;
localStorage.removeItem('selectedVMId');
// Only clear search text if it matches the VM name
if (savedSearchText === vmToSelect) {
localStorage.removeItem('vmSearchText');
}
// Show the VM list with any saved search
showVMList.value = true;
if (savedSearch) {
searchQuery.value = savedSearch;
} else if (savedSearchText) {
searchQuery.value = savedSearchText;
}
}
} else {
// No VM selected, show the list with any saved search
showVMList.value = true;
if (savedSearch) {
searchQuery.value = savedSearch;
} else if (savedSearchText) {
searchQuery.value = savedSearchText;
}
}
isLoading.value = false;
});
// Watch for changes in the selected VM
watch(selectedVM, (newValue) => {
if (newValue) {
// Save to localStorage whenever it changes
localStorage.setItem('selectedVMId', newValue);
} else {
localStorage.removeItem('selectedVMId');
}
});
// Watch for changes in the VM data
watch(() => props.vmData, (newData) => {
if (selectedVM.value && newData.length > 0) {
// Verify the VM still exists
const vmExists = newData.some(vm => vm.name === selectedVM.value);
invalidVMSelected.value = !vmExists;
if (!vmExists) {
// If VM no longer exists, clear localStorage
localStorage.removeItem('selectedVMId');
}
}
}, { deep: true });
// Helper functions
const getStateColor = (state) => {
if (!state) return '';
switch(state.toLowerCase()) {
case 'start': return 'success';
case 'stop': return 'danger';
case 'disable': return 'warning';
default: return '';
}
};
const formatMemory = (memoryMB) => {
if (!memoryMB) return '0 GB';
return Math.round(memoryMB / 1024) + ' GB';
};
const formatStorage = (sizeGB) => {
if (!sizeGB) return '0 GB';
if (sizeGB < 1024) return sizeGB + ' GB';
return (sizeGB / 1024).toFixed(1) + ' TB';
};
</script>
<style scoped>
.content-container {
background-color: white;
border-radius: 0.25rem;
padding: 1rem;
width: 100%;
padding-top: 0.25rem;
}
.loading-container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 2rem;
}
.no-content-message {
text-align: center;
padding: 2rem;
}
.info-grid-general {
display: grid;
gap: 0.5rem;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}
.info-grid-resources {
display: grid;
gap: 0.5rem;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
}
.cards-stack {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.detail-card {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 0.5rem;
}
@media (max-width: 768px) {
.info-grid-general,
.info-grid-resources {
grid-template-columns: 1fr;
}
.detail-card {
grid-template-columns: 1fr;
}
}
</style>

View File

@ -3,6 +3,9 @@ import { createPinia } from 'pinia';
import App from './App.vue'; import App from './App.vue';
import router from './router'; import router from './router';
// Add global styles
import './assets/styles.css';
// Create the app // Create the app
const app = createApp(App); const app = createApp(App);

View File

@ -1,6 +1,7 @@
import { createRouter, createWebHistory } from 'vue-router'; import { createRouter, createWebHistory } from 'vue-router';
import Overview from '../views/Overview.vue'; import Overview from '../views/Overview.vue';
import Nodes from '../views/Nodes.vue'; import Nodes from '../views/Nodes.vue';
import VMs from '../views/VMs.vue';
const routes = [ const routes = [
{ {
@ -12,6 +13,11 @@ const routes = [
path: '/nodes', path: '/nodes',
name: 'Nodes', name: 'Nodes',
component: Nodes component: Nodes
},
{
path: '/vms',
name: 'VMs',
component: VMs
} }
]; ];

View File

@ -0,0 +1,39 @@
import { useRouter } from 'vue-router';
/**
* Navigate to a VM without using URL parameters
* @param {string} vmId - The ID of the VM to navigate to
* @param {import('vue-router').Router} router - Vue Router instance
*/
export function navigateToVM(vmId, router) {
// Save the VM ID to localStorage
localStorage.setItem('selectedVMId', vmId);
// Navigate to the VMs page
router.push('/vms');
}
/**
* Navigate to a node without using URL parameters
* @param {string} nodeId - The ID of the node to navigate to
* @param {import('vue-router').Router} router - Vue Router instance
*/
export function navigateToNode(nodeId, router) {
// Save the node ID to localStorage
localStorage.setItem('selectedNodeId', nodeId);
// Navigate to the Nodes page
router.push('/nodes');
}
/**
* Clear the selected VM and return to the default VM page view
* @param {import('vue-router').Router} router - Vue Router instance
*/
export function clearSelectedVM(router) {
// Clear from localStorage
localStorage.removeItem('selectedVMId');
// Navigate to the VMs page without query parameters
router.push('/vms');
}

View File

@ -6,7 +6,7 @@ export const useApiStore = defineStore('api', () => {
const config = ref({ const config = ref({
apiUri: localStorage.getItem('pvc_api_uri') || '', apiUri: localStorage.getItem('pvc_api_uri') || '',
apiKey: localStorage.getItem('pvc_api_key') || '', apiKey: localStorage.getItem('pvc_api_key') || '',
updateInterval: parseInt(localStorage.getItem('pvc_update_interval')) || 5000 updateInterval: parseInt(localStorage.getItem('pvc_update_interval')) || 15 // Default to 15s
}); });
// Computed // Computed
@ -16,12 +16,18 @@ export const useApiStore = defineStore('api', () => {
// Actions // Actions
const updateConfig = (newConfig) => { const updateConfig = (newConfig) => {
config.value = { ...newConfig }; // Ensure interval is between 5 and 300 seconds
const interval = Math.min(300, Math.max(5, parseInt(newConfig.updateInterval) || 15));
config.value = {
...newConfig,
updateInterval: interval
};
// Save to localStorage // Save to localStorage
localStorage.setItem('pvc_api_uri', newConfig.apiUri); localStorage.setItem('pvc_api_uri', newConfig.apiUri);
localStorage.setItem('pvc_api_key', newConfig.apiKey); localStorage.setItem('pvc_api_key', newConfig.apiKey);
localStorage.setItem('pvc_update_interval', newConfig.updateInterval.toString()); localStorage.setItem('pvc_update_interval', interval.toString());
}; };
const fetchStatus = async () => { const fetchStatus = async () => {
@ -70,11 +76,36 @@ export const useApiStore = defineStore('api', () => {
} }
}; };
const fetchVMs = async () => {
try {
const response = await fetch('/api/vm', {
headers: {
'X-API-URI': config.value.apiUri,
'X-API-Key': config.value.apiKey
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return Object.entries(data).map(([name, details]) => ({
name,
...details
}));
} catch (error) {
console.error('Error fetching VM data:', error);
throw error;
}
};
return { return {
config, config,
isConfigured, isConfigured,
updateConfig, updateConfig,
fetchStatus, fetchStatus,
fetchNodes fetchNodes,
fetchVMs
}; };
}); });

View File

@ -0,0 +1,13 @@
import { defineStore } from 'pinia';
export const useClusterStore = defineStore('cluster', {
state: () => ({
clusterData: {}
}),
actions: {
setClusterData(data) {
this.clusterData = data;
}
}
});

17
pvc-vue/src/stores/vm.js Normal file
View File

@ -0,0 +1,17 @@
import { defineStore } from 'pinia';
export const useVMStore = defineStore('vm', {
state: () => ({
vmList: [],
metrics: {}
}),
actions: {
setVMList(vms) {
this.vmList = vms;
},
setMetrics(metrics) {
this.metrics = metrics;
}
}
});

View File

@ -0,0 +1,32 @@
/**
* Selects a VM and saves the selection to localStorage
* @param {string} vmId - The ID of the VM to select
* @param {import('vue-router').Router} router - Vue Router instance (optional)
*/
export function selectVM(vmId, router = null) {
// Save to localStorage
localStorage.setItem('selectedVMId', vmId);
// Optionally update URL if router is provided
if (router) {
router.push({
path: '/vms',
query: { vm: vmId }
});
}
}
/**
* Gets the currently selected VM from localStorage
* @returns {string|null} The selected VM ID or null if none is selected
*/
export function getSelectedVM() {
return localStorage.getItem('selectedVMId');
}
/**
* Clears the selected VM from localStorage
*/
export function clearSelectedVM() {
localStorage.removeItem('selectedVMId');
}

View File

@ -1,19 +1,62 @@
<template> <template>
<div class="content-grid"> <div class="content-grid">
<PageTitle title="Nodes" /> <PageTitle title="Nodes" />
<NodeStatus :nodeData="nodeData" /> <NodeOverview
:nodeData="nodeData"
:metricsData="metricsData"
:clusterData="clusterData"
/>
</div> </div>
</template> </template>
<script setup> <script setup>
import NodeStatus from '../components/NodeStatus.vue'; import { ref, onMounted, watch } from 'vue';
import PageTitle from '../components/PageTitle.vue'; import PageTitle from '../components/general/PageTitle.vue';
import NodeOverview from '../components/pages/nodes/NodeOverview.vue';
defineProps({ const props = defineProps({
nodeData: { nodeData: {
type: Array, type: Array,
required: true, required: true,
default: () => [] default: () => []
},
metricsData: {
type: Object,
required: true,
default: () => ({})
},
clusterData: {
type: Object,
required: true,
default: () => ({})
} }
}); });
</script>
const selectedNode = ref(null);
onMounted(() => {
// Restore selected node from localStorage if available
const savedNodeId = localStorage.getItem('selectedNodeId');
if (savedNodeId) {
selectedNode.value = savedNodeId;
}
});
watch(selectedNode, (newValue) => {
// Save selected node to localStorage whenever it changes
if (newValue) {
localStorage.setItem('selectedNodeId', newValue);
} else {
localStorage.removeItem('selectedNodeId');
}
});
</script>
<style scoped>
.content-grid {
display: flex;
flex-direction: column;
gap: 0.5rem;
width: 100%;
}
</style>

View File

@ -1,7 +1,7 @@
<template> <template>
<div class="content-grid"> <div class="content-grid">
<PageTitle title="Cluster Overview" /> <PageTitle title="Cluster Overview" />
<ClusterOverview <ClusterOverview
:clusterData="clusterData" :clusterData="clusterData"
:metricsData="metricsData" :metricsData="metricsData"
/> />
@ -9,8 +9,8 @@
</template> </template>
<script setup> <script setup>
import ClusterOverview from '../components/ClusterOverview.vue'; import ClusterOverview from '../components/pages/overview/ClusterOverview.vue';
import PageTitle from '../components/PageTitle.vue'; import PageTitle from '../components/general/PageTitle.vue';
defineProps({ defineProps({
clusterData: { clusterData: {
@ -24,4 +24,4 @@ defineProps({
default: () => ({}) default: () => ({})
} }
}); });
</script> </script>

55
pvc-vue/src/views/VMs.vue Normal file
View File

@ -0,0 +1,55 @@
<template>
<div class="content-grid">
<PageTitle title="Virtual Machines" />
<VMOverview
:vmData="vmData"
:metricsData="metricsData"
:clusterData="clusterData"
:loading="isLoading"
/>
</div>
</template>
<script setup>
import { ref, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import PageTitle from '../components/general/PageTitle.vue';
import VMOverview from '../components/pages/vms/VMOverview.vue';
const router = useRouter();
const route = useRoute();
const props = defineProps({
vmData: {
type: Array,
required: true,
default: () => []
},
metricsData: {
type: Object,
required: true,
default: () => ({})
},
clusterData: {
type: Object,
required: true,
default: () => ({})
},
isLoading: {
type: Boolean,
default: false
}
});
// We'll handle the VM selection in the VMOverview component
// This parent component just needs to pass the data
</script>
<style scoped>
.content-grid {
display: flex;
flex-direction: column;
gap: 0.5rem;
width: 100%;
}
</style>

View File

@ -1,6 +1,11 @@
import { defineConfig } from 'vite'; import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue'; import vue from '@vitejs/plugin-vue';
function getTimestamp() {
const now = new Date();
return now.toISOString().replace('T', ' ').replace('Z', '');
}
export default defineConfig({ export default defineConfig({
plugins: [vue()], plugins: [vue()],
server: { server: {
@ -21,7 +26,7 @@ export default defineConfig({
const requestPath = req.url.replace('/api', ''); const requestPath = req.url.replace('/api', '');
proxyReq.path = `${apiPath}${requestPath}`; proxyReq.path = `${apiPath}${requestPath}`;
console.log(`Proxying to: ${options.target}${proxyReq.path}`); console.log(`${getTimestamp()} Proxying to: ${options.target}${proxyReq.path}`);
} }
if (req.headers['x-api-key']) { if (req.headers['x-api-key']) {