326 lines
12 KiB
JavaScript
326 lines
12 KiB
JavaScript
// ============================
|
|
// DB Monitor — Settings Page
|
|
// ============================
|
|
|
|
(function () {
|
|
'use strict';
|
|
|
|
const $ = id => document.getElementById(id);
|
|
|
|
// ---- Tabs ----
|
|
document.querySelectorAll('.tab-btn').forEach(btn => {
|
|
btn.addEventListener('click', () => {
|
|
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
|
|
document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
|
|
btn.classList.add('active');
|
|
document.getElementById(btn.dataset.target).classList.add('active');
|
|
});
|
|
});
|
|
|
|
// ---- Status messages ----
|
|
function showMsg(text, type = 'success') {
|
|
const el = $('status-msg');
|
|
el.textContent = text;
|
|
el.className = type;
|
|
setTimeout(() => { el.className = ''; el.textContent = ''; }, 4000);
|
|
}
|
|
|
|
// ============================
|
|
// DATABASES
|
|
// ============================
|
|
|
|
async function loadDatabases() {
|
|
const list = $('list-dbs');
|
|
try {
|
|
const res = await fetch('/api/settings/databases');
|
|
const dbs = await res.json();
|
|
|
|
// Populate alert-db dropdown
|
|
const dbSelect = $('alert-db');
|
|
dbSelect.innerHTML = '<option value="">All Databases</option>';
|
|
if (dbs && dbs.length > 0) {
|
|
dbs.forEach(db => {
|
|
const opt = document.createElement('option');
|
|
opt.value = db.name;
|
|
opt.textContent = db.name;
|
|
dbSelect.appendChild(opt);
|
|
});
|
|
}
|
|
|
|
if (!dbs || dbs.length === 0) {
|
|
list.innerHTML = '<div class="empty-message">No databases tracked yet. Add one above.</div>';
|
|
return;
|
|
}
|
|
list.innerHTML = dbs.map(db => `
|
|
<div class="item-row" id="db-row-${db.id}">
|
|
<div class="item-info">
|
|
<div class="item-title">
|
|
<span class="rule-badge">#${db.id}</span>${db.name}
|
|
</div>
|
|
</div>
|
|
<button class="btn btn-danger" onclick="deleteDB(${db.id})">Remove</button>
|
|
</div>
|
|
`).join('');
|
|
} catch (e) {
|
|
list.innerHTML = '<div class="empty-message">Failed to load databases.</div>';
|
|
}
|
|
}
|
|
|
|
// Test connection
|
|
$('btn-test-db').addEventListener('click', async () => {
|
|
const dsn = $('db-dsn').value.trim();
|
|
if (!dsn) return showMsg('Please enter a DSN first.', 'error');
|
|
|
|
const btn = $('btn-test-db');
|
|
btn.textContent = 'Testing...';
|
|
btn.disabled = true;
|
|
|
|
try {
|
|
const res = await fetch('/api/settings/databases/test', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ dsn }),
|
|
});
|
|
const data = await res.json();
|
|
if (data.success) {
|
|
showMsg(`✅ Connected to "${data.name}" — ${data.version ? data.version.substring(0, 60) : ''} (${data.latency_ms}ms)`);
|
|
} else {
|
|
showMsg(`❌ Connection failed: ${data.error}`, 'error');
|
|
}
|
|
} catch (e) {
|
|
showMsg('❌ Could not reach server.', 'error');
|
|
} finally {
|
|
btn.textContent = 'Test Connection';
|
|
btn.disabled = false;
|
|
}
|
|
});
|
|
|
|
// Add database
|
|
$('form-add-db').addEventListener('submit', async (e) => {
|
|
e.preventDefault();
|
|
const dsn = $('db-dsn').value.trim();
|
|
if (!dsn) return;
|
|
|
|
try {
|
|
const res = await fetch('/api/settings/databases', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ dsn }),
|
|
});
|
|
if (!res.ok) {
|
|
const txt = await res.text();
|
|
return showMsg(`❌ Error: ${txt}`, 'error');
|
|
}
|
|
const data = await res.json();
|
|
showMsg(`✅ Added "${data.name}" — monitoring started!`);
|
|
$('db-dsn').value = '';
|
|
loadDatabases();
|
|
} catch (e) {
|
|
showMsg('❌ Failed to add database.', 'error');
|
|
}
|
|
});
|
|
|
|
// Delete database
|
|
window.deleteDB = async (id) => {
|
|
if (!confirm('Remove this database from monitoring?')) return;
|
|
try {
|
|
const res = await fetch(`/api/settings/databases/${id}`, { method: 'DELETE' });
|
|
if (!res.ok) return showMsg('❌ Failed to remove database.', 'error');
|
|
showMsg('🗑️ Database removed from monitoring.');
|
|
loadDatabases();
|
|
} catch (e) {
|
|
showMsg('❌ Failed to remove database.', 'error');
|
|
}
|
|
};
|
|
|
|
// ============================
|
|
// ALERT RULES
|
|
// ============================
|
|
|
|
const METRIC_LABELS = {
|
|
latency_ms: 'Latency (ms)',
|
|
connection_usage_pct: 'Connection Usage (%)',
|
|
cache_hit_ratio: 'Cache Hit Ratio (%)',
|
|
active_locks: 'Active Locks',
|
|
waiting_locks: 'Waiting Locks',
|
|
deadlocks: 'Deadlocks',
|
|
long_running_queries: 'Long Running Queries',
|
|
replication_lag_ms: 'Replication Lag (ms)',
|
|
};
|
|
|
|
async function loadAlerts() {
|
|
const list = $('list-alerts');
|
|
try {
|
|
const res = await fetch('/api/settings/alerts');
|
|
const rules = await res.json();
|
|
if (!rules || rules.length === 0) {
|
|
list.innerHTML = '<div class="empty-message">No alert rules defined. Add one above.</div>';
|
|
return;
|
|
}
|
|
list.innerHTML = rules.map(r => {
|
|
const dbLabel = r.db_name ? `<span class="rule-badge" style="background: rgba(16,185,129,0.15); color: var(--green)">${r.db_name}</span>` : '<span class="rule-badge">All DBs</span>';
|
|
return `
|
|
<div class="item-row" id="alert-row-${r.id}">
|
|
<div class="item-info">
|
|
<div class="item-title">
|
|
<span class="rule-badge">#${r.id}</span>
|
|
${dbLabel}
|
|
${METRIC_LABELS[r.metric] || r.metric} ${r.operator} ${r.threshold}
|
|
</div>
|
|
<div class="item-subtitle">Cooldown: ${r.cooldown_min}min</div>
|
|
</div>
|
|
<div style="display: flex; align-items: center; gap: 16px;">
|
|
<label class="switch" title="${r.enabled ? 'Enabled' : 'Disabled'}">
|
|
<input type="checkbox" ${r.enabled ? 'checked' : ''}
|
|
onchange="toggleAlert(${r.id}, '${r.db_name}', '${r.metric}', '${r.operator}', ${r.threshold}, this.checked, ${r.cooldown_min})">
|
|
<span class="slider"></span>
|
|
</label>
|
|
<button class="btn btn-danger" onclick="deleteAlert(${r.id})">Delete</button>
|
|
</div>
|
|
</div>`;
|
|
}).join('');
|
|
} catch (e) {
|
|
list.innerHTML = '<div class="empty-message">Failed to load rules.</div>';
|
|
}
|
|
}
|
|
|
|
$('form-add-alert').addEventListener('submit', async (e) => {
|
|
e.preventDefault();
|
|
const dbName = $('alert-db').value;
|
|
const metric = $('alert-metric').value;
|
|
const operator = $('alert-op').value;
|
|
const threshold = parseFloat($('alert-val').value);
|
|
|
|
try {
|
|
const res = await fetch('/api/settings/alerts', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ db_name: dbName, metric, operator, threshold, enabled: true, cooldown_min: 5 }),
|
|
});
|
|
if (!res.ok) {
|
|
const txt = await res.text();
|
|
return showMsg(`❌ Error: ${txt}`, 'error');
|
|
}
|
|
const dbLabel = dbName ? `for ${dbName}` : 'for all databases';
|
|
showMsg(`✅ Alert rule created: ${METRIC_LABELS[metric]} ${operator} ${threshold} ${dbLabel}`);
|
|
$('alert-val').value = '';
|
|
loadAlerts();
|
|
} catch (e) {
|
|
showMsg('❌ Failed to create alert rule.', 'error');
|
|
}
|
|
});
|
|
|
|
window.toggleAlert = async (id, dbName, metric, operator, threshold, enabled, cooldownMin) => {
|
|
try {
|
|
await fetch('/api/settings/alerts', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ id, db_name: dbName, metric, operator, threshold, enabled, cooldown_min: cooldownMin }),
|
|
});
|
|
} catch (e) {
|
|
showMsg('❌ Failed to toggle rule.', 'error');
|
|
}
|
|
};
|
|
|
|
window.deleteAlert = async (id) => {
|
|
if (!confirm('Delete this alert rule?')) return;
|
|
try {
|
|
const res = await fetch(`/api/settings/alerts/${id}`, { method: 'DELETE' });
|
|
if (!res.ok) return showMsg('❌ Failed to delete rule.', 'error');
|
|
showMsg('🗑️ Alert rule deleted.');
|
|
loadAlerts();
|
|
} catch (e) {
|
|
showMsg('❌ Failed to delete rule.', 'error');
|
|
}
|
|
};
|
|
|
|
// ============================
|
|
// NOTIFICATIONS (Telegram)
|
|
// ============================
|
|
|
|
async function loadNotifications() {
|
|
try {
|
|
const res = await fetch('/api/settings/notifications');
|
|
const channels = await res.json();
|
|
const tg = channels.find(c => c.channel_type === 'telegram');
|
|
if (tg) {
|
|
const cfg = typeof tg.config === 'string' ? JSON.parse(tg.config) : tg.config;
|
|
$('tg-token').value = cfg.bot_token || '';
|
|
$('tg-chat').value = cfg.chat_id || '';
|
|
$('tg-enabled').checked = tg.enabled;
|
|
}
|
|
} catch (e) { /* silent */ }
|
|
}
|
|
|
|
$('form-telegram').addEventListener('submit', async (e) => {
|
|
e.preventDefault();
|
|
const botToken = $('tg-token').value.trim();
|
|
const chatID = $('tg-chat').value.trim();
|
|
const enabled = $('tg-enabled').checked;
|
|
|
|
try {
|
|
const res = await fetch('/api/settings/notifications', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
channel_type: 'telegram',
|
|
config: { bot_token: botToken, chat_id: chatID },
|
|
enabled,
|
|
}),
|
|
});
|
|
if (!res.ok) return showMsg('❌ Failed to save.', 'error');
|
|
showMsg('✅ Telegram configuration saved!');
|
|
} catch (e) {
|
|
showMsg('❌ Failed to save.', 'error');
|
|
}
|
|
});
|
|
|
|
$('btn-test-tg').addEventListener('click', async () => {
|
|
const botToken = $('tg-token').value.trim();
|
|
const chatID = $('tg-chat').value.trim();
|
|
|
|
if (!botToken || !chatID) return showMsg('Please enter Bot Token and Chat ID first.', 'error');
|
|
|
|
const btn = $('btn-test-tg');
|
|
btn.textContent = 'Sending...';
|
|
btn.disabled = true;
|
|
|
|
try {
|
|
const res = await fetch('/api/settings/notifications/test', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
channel_type: 'telegram',
|
|
config: { bot_token: botToken, chat_id: chatID },
|
|
}),
|
|
});
|
|
const data = await res.json();
|
|
if (data.success) {
|
|
showMsg('✅ Test message sent! Check your Telegram.');
|
|
} else {
|
|
showMsg(`❌ Telegram error: ${data.error}`, 'error');
|
|
}
|
|
} catch (e) {
|
|
showMsg('❌ Failed to send test message.', 'error');
|
|
} finally {
|
|
btn.textContent = 'Send Test Message';
|
|
btn.disabled = false;
|
|
}
|
|
});
|
|
|
|
// ============================
|
|
// Helpers
|
|
// ============================
|
|
|
|
function maskDSN(dsn) {
|
|
// Hide password in displayed DSN
|
|
return dsn.replace(/:([^@]+)@/, ':****@');
|
|
}
|
|
|
|
// Initialize
|
|
loadDatabases();
|
|
loadAlerts();
|
|
loadNotifications();
|
|
|
|
})();
|