Веб-UI: логи kind create, старт/стоп кластеров, документация README
- Потоковые логи в job_store и UI; kind create через Popen с построчным выводом
- POST /clusters/{name}/start|stop; create по сохранённому kind-config.yaml
- Страница /documentation: GET /api/v1/docs/readme, marked+DOMPurify из static/vendor
- Иконки действий, плавающие подсказки, модалка подтверждения вместо confirm
- Makefile: make docker|podman rebuild; compose: монтирование README.md
- Dockerfile: COPY README.md; readme_doc: несколько путей к README
Автор: Сергей Антропов — https://devops.org.ru
This commit is contained in:
+428
-67
@@ -1,6 +1,7 @@
|
||||
/**
|
||||
* Панель управления кластерами kind (REST /api/v1).
|
||||
* Автообновление списков и health; прогресс и отмена создания кластера.
|
||||
* Полная перезагрузка страницы (location.reload) не используется: только fetch и точечная
|
||||
* замена содержимого блоков (статистика, таблицы, плашка среды) — SPA-поведение.
|
||||
*
|
||||
* Автор: Сергей Антропов
|
||||
* Сайт: https://devops.org.ru
|
||||
@@ -23,6 +24,8 @@
|
||||
var createInProgress = false;
|
||||
/** @type {string | null} */
|
||||
var currentPollJobId = null;
|
||||
/** Имя кластера в открытой модалке «Состояние» (для скачивания kubeconfig). */
|
||||
var currentModalClusterName = null;
|
||||
|
||||
function formatApiError(data, fallback) {
|
||||
if (!data) return fallback;
|
||||
@@ -66,6 +69,137 @@
|
||||
return d.innerHTML;
|
||||
}
|
||||
|
||||
/**
|
||||
* Скачать kubeconfig кластера (GET /clusters/{name}/kubeconfig).
|
||||
* @param {string} clusterName
|
||||
*/
|
||||
function downloadKubeconfig(clusterName) {
|
||||
const url = API + "/clusters/" + encodeURIComponent(clusterName) + "/kubeconfig";
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = "kubeconfig-" + clusterName + ".yaml";
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
}
|
||||
|
||||
/** SVG-иконки действий (stroke, currentColor). */
|
||||
var ICONS = {
|
||||
state:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8"/><path d="M12 17v4"/></svg>',
|
||||
play:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polygon points="7 3 21 12 7 21 7 3"/></svg>',
|
||||
stop:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="5" y="5" width="14" height="14" rx="2"/></svg>',
|
||||
download:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>',
|
||||
trash:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><line x1="10" y1="11" x2="10" y2="17"/><line x1="14" y1="11" x2="14" y2="17"/></svg>',
|
||||
};
|
||||
|
||||
/** @type {ReturnType<typeof setTimeout> | null} */
|
||||
var actionTooltipHideTimer = null;
|
||||
|
||||
function getActionTooltipEl() {
|
||||
return document.getElementById("action-tooltip");
|
||||
}
|
||||
|
||||
/** Скрыть плавающую подсказку (#action-tooltip, position: fixed). */
|
||||
function hideActionTooltip() {
|
||||
if (actionTooltipHideTimer) {
|
||||
clearTimeout(actionTooltipHideTimer);
|
||||
actionTooltipHideTimer = null;
|
||||
}
|
||||
const el = getActionTooltipEl();
|
||||
if (!el) return;
|
||||
el.classList.add("hidden");
|
||||
el.textContent = "";
|
||||
el.style.visibility = "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Показать подсказку у иконки (полный текст, без обрезки overflow таблицы).
|
||||
* @param {HTMLElement} host элемент .icon-tooltip-host
|
||||
*/
|
||||
function showActionTooltip(host) {
|
||||
const el = getActionTooltipEl();
|
||||
const text = host.getAttribute("data-tooltip");
|
||||
if (!el || !text) return;
|
||||
if (actionTooltipHideTimer) {
|
||||
clearTimeout(actionTooltipHideTimer);
|
||||
actionTooltipHideTimer = null;
|
||||
}
|
||||
el.textContent = text;
|
||||
const margin = 10;
|
||||
const maxW = Math.min(352, window.innerWidth - margin * 2);
|
||||
el.style.maxWidth = maxW + "px";
|
||||
el.classList.remove("hidden");
|
||||
var w = el.offsetWidth;
|
||||
var h = el.offsetHeight;
|
||||
var r = host.getBoundingClientRect();
|
||||
var left = r.left + r.width / 2 - w / 2;
|
||||
if (left < margin) left = margin;
|
||||
if (left + w > window.innerWidth - margin) left = Math.max(margin, window.innerWidth - w - margin);
|
||||
var top = r.top - h - margin;
|
||||
if (top < margin) top = r.bottom + margin;
|
||||
if (top + h > window.innerHeight - margin) {
|
||||
top = Math.max(margin, window.innerHeight - h - margin);
|
||||
}
|
||||
el.style.left = left + "px";
|
||||
el.style.top = top + "px";
|
||||
}
|
||||
|
||||
/**
|
||||
* Подписать .icon-tooltip-host внутри root на hover/focus (повторно безопасно).
|
||||
* @param {ParentNode | null} root
|
||||
*/
|
||||
function bindActionTooltipHosts(root) {
|
||||
if (!root) return;
|
||||
root.querySelectorAll(".icon-tooltip-host").forEach(function (host) {
|
||||
if (host.dataset.actionTooltipBound === "1") return;
|
||||
host.dataset.actionTooltipBound = "1";
|
||||
host.addEventListener("mouseenter", function () {
|
||||
showActionTooltip(host);
|
||||
});
|
||||
host.addEventListener("mouseleave", function () {
|
||||
actionTooltipHideTimer = setTimeout(hideActionTooltip, 120);
|
||||
});
|
||||
host.addEventListener("focusin", function () {
|
||||
showActionTooltip(host);
|
||||
});
|
||||
host.addEventListener("focusout", function (ev) {
|
||||
var rel = ev.relatedTarget;
|
||||
if (!rel || !host.contains(rel)) hideActionTooltip();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Кнопка-иконка в обёртке; подсказка — data-tooltip (см. #action-tooltip в base.html).
|
||||
* @param {string} svgHtml
|
||||
* @param {string} tooltip
|
||||
* @param {string} [classExtra] например icon-btn--danger
|
||||
* @param {((ev: Event) => void) | null} onClick
|
||||
* @param {boolean} [isDisabled]
|
||||
*/
|
||||
function iconActionButton(svgHtml, tooltip, classExtra, onClick, isDisabled) {
|
||||
const btn = document.createElement("button");
|
||||
btn.type = "button";
|
||||
btn.className = "icon-btn" + (classExtra ? " " + classExtra : "");
|
||||
btn.innerHTML = svgHtml;
|
||||
btn.setAttribute("aria-label", tooltip);
|
||||
if (isDisabled) {
|
||||
btn.disabled = true;
|
||||
} else if (onClick) {
|
||||
btn.addEventListener("click", onClick);
|
||||
}
|
||||
const host = document.createElement("span");
|
||||
host.className = "icon-tooltip-host";
|
||||
host.setAttribute("data-tooltip", tooltip);
|
||||
host.appendChild(btn);
|
||||
return host;
|
||||
}
|
||||
|
||||
function showToast(message, isError) {
|
||||
const el = document.getElementById("toast");
|
||||
if (!el) return;
|
||||
@@ -78,17 +212,6 @@
|
||||
}, 4500);
|
||||
}
|
||||
|
||||
function setBusy(section, busy) {
|
||||
const el = document.querySelector("[data-busy='" + section + "']");
|
||||
if (!el) return;
|
||||
if (busy) {
|
||||
el.setAttribute("aria-busy", "true");
|
||||
} else {
|
||||
el.removeAttribute("aria-busy");
|
||||
}
|
||||
el.classList.toggle("is-loading", busy);
|
||||
}
|
||||
|
||||
function setStatusBannerClass(ok, degraded) {
|
||||
const el = document.getElementById("status-banner");
|
||||
if (!el) return;
|
||||
@@ -129,10 +252,9 @@
|
||||
const dl = document.getElementById("stats-dl");
|
||||
const errEl = document.getElementById("stats-err");
|
||||
if (!dl) return;
|
||||
errEl.classList.add("hidden");
|
||||
dl.innerHTML = "";
|
||||
try {
|
||||
const s = await api("/stats");
|
||||
errEl.classList.add("hidden");
|
||||
const rows = [
|
||||
["Кластеров в kind", s.kind_clusters_count],
|
||||
["Локальных каталогов", s.local_cluster_dirs_count],
|
||||
@@ -140,14 +262,16 @@
|
||||
["Заданий в памяти", s.jobs_total],
|
||||
["Заданий с ошибкой", s.jobs_recent_failed],
|
||||
];
|
||||
const frag = document.createDocumentFragment();
|
||||
rows.forEach(function (kv) {
|
||||
const dt = document.createElement("dt");
|
||||
dt.textContent = kv[0];
|
||||
const dd = document.createElement("dd");
|
||||
dd.textContent = String(kv[1]);
|
||||
dl.appendChild(dt);
|
||||
dl.appendChild(dd);
|
||||
frag.appendChild(dt);
|
||||
frag.appendChild(dd);
|
||||
});
|
||||
dl.replaceChildren(frag);
|
||||
} catch (e) {
|
||||
errEl.textContent = "Статистика: " + e.message;
|
||||
errEl.classList.remove("hidden");
|
||||
@@ -196,17 +320,14 @@
|
||||
const tbody = document.querySelector("#tbl-clusters tbody");
|
||||
const msg = document.getElementById("list-msg");
|
||||
if (!tbody) return;
|
||||
setBusy("clusters", true);
|
||||
tbody.innerHTML = "";
|
||||
if (msg) msg.textContent = "";
|
||||
try {
|
||||
const rows = await api("/clusters");
|
||||
const frag = document.createDocumentFragment();
|
||||
rows.forEach(function (c) {
|
||||
const tr = document.createElement("tr");
|
||||
const ver = (c.meta && (c.meta.kubernetes_version_tag || c.meta.node_image)) || "—";
|
||||
const wn = c.meta && c.meta.worker_nodes != null ? c.meta.worker_nodes : "—";
|
||||
const nameEsc = escapeHtml(c.name);
|
||||
const dlHref = API + "/clusters/" + encodeURIComponent(c.name) + "/kubeconfig";
|
||||
tr.innerHTML =
|
||||
"<td><code class=\"cluster-name\">" +
|
||||
nameEsc +
|
||||
@@ -223,40 +344,78 @@
|
||||
"<td>" +
|
||||
escapeHtml(String(wn)) +
|
||||
"</td>" +
|
||||
"<td class=\"actions\"></td>";
|
||||
const td = tr.querySelector(".actions");
|
||||
const b1 = document.createElement("button");
|
||||
b1.type = "button";
|
||||
b1.className = "btn-small";
|
||||
b1.textContent = "Состояние";
|
||||
b1.addEventListener("click", function () {
|
||||
openWorkloadsModal(c.name);
|
||||
});
|
||||
td.appendChild(b1);
|
||||
if (c.has_local_kubeconfig) {
|
||||
const a = document.createElement("a");
|
||||
a.href = dlHref;
|
||||
a.className = "btn-secondary btn-small";
|
||||
a.download = "kubeconfig-" + c.name + ".yaml";
|
||||
a.textContent = "kubeconfig";
|
||||
a.title = "Скачать kubeconfig";
|
||||
td.appendChild(a);
|
||||
"<td class=\"actions\"><span class=\"actions-toolbar\"></span></td>";
|
||||
const td = tr.querySelector(".actions-toolbar");
|
||||
td.appendChild(
|
||||
iconActionButton(
|
||||
ICONS.state,
|
||||
"Состояние: узлы и поды (kubectl get nodes / pods)",
|
||||
"",
|
||||
function () {
|
||||
openWorkloadsModal(c.name);
|
||||
},
|
||||
false,
|
||||
),
|
||||
);
|
||||
td.appendChild(
|
||||
iconActionButton(
|
||||
ICONS.play,
|
||||
"Старт: если кластер в kind — запуск контейнеров; иначе при наличии kind-config.yaml — kind create в фоне",
|
||||
"",
|
||||
function () {
|
||||
startCluster(c.name);
|
||||
},
|
||||
false,
|
||||
),
|
||||
);
|
||||
if (c.registered_in_kind) {
|
||||
td.appendChild(
|
||||
iconActionButton(
|
||||
ICONS.stop,
|
||||
"Стоп: остановить узлы (docker/podman stop), запись кластера в kind сохраняется",
|
||||
"icon-btn--secondary",
|
||||
function () {
|
||||
stopCluster(c.name);
|
||||
},
|
||||
false,
|
||||
),
|
||||
);
|
||||
}
|
||||
const b2 = document.createElement("button");
|
||||
b2.type = "button";
|
||||
b2.className = "btn-small btn-danger";
|
||||
b2.textContent = "Удалить";
|
||||
b2.addEventListener("click", function () {
|
||||
deleteCluster(c.name);
|
||||
});
|
||||
td.appendChild(b2);
|
||||
tbody.appendChild(tr);
|
||||
td.appendChild(
|
||||
iconActionButton(
|
||||
ICONS.download,
|
||||
c.has_local_kubeconfig
|
||||
? "Скачать kubeconfig для kubectl на хосте"
|
||||
: "Kubeconfig ещё нет — появится после создания или подъёма кластера",
|
||||
"icon-btn--secondary",
|
||||
c.has_local_kubeconfig
|
||||
? function () {
|
||||
downloadKubeconfig(c.name);
|
||||
}
|
||||
: null,
|
||||
!c.has_local_kubeconfig,
|
||||
),
|
||||
);
|
||||
td.appendChild(
|
||||
iconActionButton(
|
||||
ICONS.trash,
|
||||
"Удалить кластер (kind delete) и каталог clusters/<имя>/",
|
||||
"icon-btn--danger",
|
||||
function () {
|
||||
deleteCluster(c.name);
|
||||
},
|
||||
false,
|
||||
),
|
||||
);
|
||||
frag.appendChild(tr);
|
||||
});
|
||||
if (!rows.length && msg) msg.textContent = "Кластеров пока нет.";
|
||||
tbody.replaceChildren(frag);
|
||||
bindActionTooltipHosts(document.getElementById("tbl-clusters"));
|
||||
if (msg) {
|
||||
msg.textContent = rows.length ? "" : "Кластеров пока нет.";
|
||||
}
|
||||
} catch (e) {
|
||||
if (msg) msg.textContent = "Ошибка списка: " + e.message;
|
||||
} finally {
|
||||
setBusy("clusters", false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -264,17 +423,19 @@
|
||||
const tbody = document.querySelector("#tbl-jobs tbody");
|
||||
const msg = document.getElementById("jobs-msg");
|
||||
if (!tbody) return;
|
||||
setBusy("jobs", true);
|
||||
tbody.innerHTML = "";
|
||||
if (msg) msg.textContent = "";
|
||||
try {
|
||||
const rows = await api("/jobs?limit=30");
|
||||
const frag = document.createDocumentFragment();
|
||||
rows.forEach(function (j) {
|
||||
const tr = document.createElement("tr");
|
||||
const st = escapeHtml(j.status || "");
|
||||
var cellMsg = (j.message || "").slice(0, 160);
|
||||
var kindTag = j.kind === "start_cluster" ? "[старт] " : "";
|
||||
var cellMsg = kindTag + (j.message || "").slice(0, 140);
|
||||
if ((j.status === "running" || j.status === "queued") && j.progress_stage) {
|
||||
cellMsg = j.progress_stage + (j.progress_percent != null ? " (" + j.progress_percent + "%)" : "");
|
||||
cellMsg =
|
||||
kindTag +
|
||||
j.progress_stage +
|
||||
(j.progress_percent != null ? " (" + j.progress_percent + "%)" : "");
|
||||
}
|
||||
tr.innerHTML =
|
||||
"<td><time datetime=\"" +
|
||||
@@ -293,15 +454,16 @@
|
||||
"<td class=\"jobs-msg-cell\">" +
|
||||
escapeHtml(cellMsg) +
|
||||
"</td>";
|
||||
tbody.appendChild(tr);
|
||||
frag.appendChild(tr);
|
||||
});
|
||||
if (!rows.length && msg) {
|
||||
msg.textContent = "Заданий ещё не было (или контейнер перезапускали).";
|
||||
tbody.replaceChildren(frag);
|
||||
if (msg) {
|
||||
msg.textContent = rows.length
|
||||
? ""
|
||||
: "Заданий ещё не было (или контейнер перезапускали).";
|
||||
}
|
||||
} catch (e) {
|
||||
if (msg) msg.textContent = "Задания: " + e.message;
|
||||
} finally {
|
||||
setBusy("jobs", false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -311,11 +473,15 @@
|
||||
const nodes = document.getElementById("modal-nodes");
|
||||
const pods = document.getElementById("modal-pods");
|
||||
const spin = document.getElementById("modal-spinner");
|
||||
const modalDlWrap = document.getElementById("modal-dl-wrap");
|
||||
if (!overlay) return;
|
||||
hideActionTooltip();
|
||||
currentModalClusterName = name;
|
||||
document.getElementById("modal-title").textContent = "Кластер «" + name + "»";
|
||||
sub.textContent = "";
|
||||
nodes.textContent = "";
|
||||
pods.textContent = "";
|
||||
if (modalDlWrap) modalDlWrap.classList.add("hidden");
|
||||
if (spin) spin.classList.remove("hidden");
|
||||
overlay.classList.remove("hidden");
|
||||
document.body.classList.add("modal-open");
|
||||
@@ -328,6 +494,7 @@
|
||||
sub.textContent = "kubectl: узлы rc=" + w.nodes_rc + ", поды rc=" + w.pods_rc;
|
||||
nodes.textContent = w.nodes_output || "(пусто)";
|
||||
pods.textContent = w.pods_output || "(пусто)";
|
||||
if (modalDlWrap) modalDlWrap.classList.remove("hidden");
|
||||
} catch (e) {
|
||||
sub.textContent = "Ошибка: " + e.message;
|
||||
} finally {
|
||||
@@ -335,14 +502,131 @@
|
||||
}
|
||||
}
|
||||
|
||||
/** Колбэк ожидающего Promise от openConfirmModal (одно окно за раз). */
|
||||
var confirmModalResolver = null;
|
||||
|
||||
function isConfirmModalOpen() {
|
||||
const el = document.getElementById("confirm-modal-overlay");
|
||||
return !!(el && !el.classList.contains("hidden"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Закрыть модалку подтверждения и вернуть результат в Promise.
|
||||
* @param {boolean} confirmed
|
||||
*/
|
||||
function closeConfirmModal(confirmed) {
|
||||
const ov = document.getElementById("confirm-modal-overlay");
|
||||
if (ov) ov.classList.add("hidden");
|
||||
document.body.classList.remove("modal-open");
|
||||
if (confirmModalResolver) {
|
||||
var fn = confirmModalResolver;
|
||||
confirmModalResolver = null;
|
||||
fn(!!confirmed);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Показать модальное подтверждение (вместо window.confirm).
|
||||
* @param {{ title?: string, message: string, confirmLabel?: string, danger?: boolean }} opts
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
function openConfirmModal(opts) {
|
||||
return new Promise(function (resolve) {
|
||||
const ov = document.getElementById("confirm-modal-overlay");
|
||||
const titleEl = document.getElementById("confirm-modal-title");
|
||||
const msgEl = document.getElementById("confirm-modal-message");
|
||||
const okBtn = document.getElementById("confirm-modal-ok");
|
||||
if (!ov || !titleEl || !msgEl || !okBtn) {
|
||||
resolve(false);
|
||||
return;
|
||||
}
|
||||
if (confirmModalResolver) {
|
||||
closeConfirmModal(false);
|
||||
}
|
||||
confirmModalResolver = resolve;
|
||||
titleEl.textContent = opts.title || "Подтвердите действие";
|
||||
msgEl.textContent = opts.message || "";
|
||||
okBtn.textContent = opts.confirmLabel || "Подтвердить";
|
||||
okBtn.className = opts.danger ? "btn-danger" : "";
|
||||
ov.classList.remove("hidden");
|
||||
document.body.classList.add("modal-open");
|
||||
okBtn.focus();
|
||||
});
|
||||
}
|
||||
|
||||
function closeModal() {
|
||||
hideActionTooltip();
|
||||
const overlay = document.getElementById("modal-overlay");
|
||||
const modalDlWrap = document.getElementById("modal-dl-wrap");
|
||||
if (modalDlWrap) modalDlWrap.classList.add("hidden");
|
||||
currentModalClusterName = null;
|
||||
if (overlay) overlay.classList.add("hidden");
|
||||
document.body.classList.remove("modal-open");
|
||||
}
|
||||
|
||||
async function stopCluster(name) {
|
||||
const ok = await openConfirmModal({
|
||||
title: "Остановить узлы кластера?",
|
||||
message:
|
||||
"Кластер «" +
|
||||
name +
|
||||
"»: контейнеры будут остановлены (docker/podman stop). Запись в kind сохранится — позже можно снова нажать «Старт».",
|
||||
confirmLabel: "Остановить",
|
||||
danger: false,
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
const res = await api("/clusters/" + encodeURIComponent(name) + "/stop", { method: "POST" });
|
||||
showToast(String(res.summary || "Узлы остановлены"), false);
|
||||
await loadClusters();
|
||||
await loadStats();
|
||||
await loadHealth();
|
||||
} catch (e) {
|
||||
showToast(e.message, true);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Старт: либо docker start узлов (кластер уже в kind), либо фоновый kind create по kind-config.yaml.
|
||||
*/
|
||||
async function startCluster(name) {
|
||||
const url = API + "/clusters/" + encodeURIComponent(name) + "/start";
|
||||
const r = await fetch(url, { method: "POST", headers: { Accept: "application/json" } });
|
||||
const text = await r.text();
|
||||
var data = {};
|
||||
try {
|
||||
data = text ? JSON.parse(text) : {};
|
||||
} catch (e) {
|
||||
data = {};
|
||||
}
|
||||
if (r.status === 202 && data.job_id) {
|
||||
setProgressHint(name);
|
||||
pollJob(data.job_id);
|
||||
return;
|
||||
}
|
||||
if (!r.ok) {
|
||||
showToast(formatApiError(data, text || r.statusText), true);
|
||||
return;
|
||||
}
|
||||
showToast(String(data.summary || "Готово"), false);
|
||||
await loadClusters();
|
||||
await loadStats();
|
||||
await loadHealth();
|
||||
}
|
||||
|
||||
async function deleteCluster(name) {
|
||||
if (!confirm("Удалить кластер «" + name + "» и папку clusters/" + name + "?")) return;
|
||||
const ok = await openConfirmModal({
|
||||
title: "Удалить кластер?",
|
||||
message:
|
||||
"Кластер «" +
|
||||
name +
|
||||
"»: будут выполнены kind delete и удаление каталога clusters/" +
|
||||
name +
|
||||
"/ на томе данных. Действие необратимо.",
|
||||
confirmLabel: "Удалить",
|
||||
danger: true,
|
||||
});
|
||||
if (!ok) return;
|
||||
const msg = document.getElementById("list-msg");
|
||||
if (msg) msg.textContent = "Удаление…";
|
||||
try {
|
||||
@@ -376,6 +660,29 @@
|
||||
if (!wrap) return;
|
||||
wrap.classList.toggle("hidden", !show);
|
||||
wrap.setAttribute("aria-hidden", show ? "false" : "true");
|
||||
if (!show) {
|
||||
const logEl = document.getElementById("job-log-panel");
|
||||
if (logEl) logEl.textContent = "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Обновить текст подсказки над прогрессом (создание с нуля или старт по конфигу).
|
||||
* @param {string | null} clusterName
|
||||
*/
|
||||
function setProgressHint(clusterName) {
|
||||
const hint = document.getElementById("create-progress-hint");
|
||||
if (!hint) return;
|
||||
if (clusterName) {
|
||||
hint.innerHTML =
|
||||
"Кластер <code>" +
|
||||
escapeHtml(clusterName) +
|
||||
"</code>: подъём по конфигу или длительный <code>kind create</code> — ниже журнал (pull образов и ноды).";
|
||||
} else {
|
||||
hint.innerHTML =
|
||||
"Создание кластера: шаг <code>kind create</code> может занять несколько минут при первом pull образов. " +
|
||||
"Ниже — журнал в реальном времени.";
|
||||
}
|
||||
}
|
||||
|
||||
function updateCreateProgressFromJob(j) {
|
||||
@@ -417,6 +724,8 @@
|
||||
function pollJob(jobId) {
|
||||
const details = document.getElementById("job-details");
|
||||
const msg = document.getElementById("create-msg");
|
||||
const logEl = document.getElementById("job-log-panel");
|
||||
if (logEl) logEl.textContent = "";
|
||||
if (details) {
|
||||
details.classList.remove("hidden");
|
||||
details.open = false;
|
||||
@@ -434,20 +743,29 @@
|
||||
const preEl = document.getElementById("job-json");
|
||||
if (preEl) preEl.textContent = JSON.stringify(j, null, 2);
|
||||
updateCreateProgressFromJob(j);
|
||||
if (logEl && j.progress_log && j.progress_log.length) {
|
||||
logEl.textContent = j.progress_log.join("\n");
|
||||
logEl.scrollTop = logEl.scrollHeight;
|
||||
}
|
||||
|
||||
if (j.status === "success" || j.status === "failed" || j.status === "cancelled") {
|
||||
stopPollJob();
|
||||
setProgressHint(null);
|
||||
if (msg) {
|
||||
if (j.status === "success") msg.textContent = "Кластер создан.";
|
||||
else if (j.status === "cancelled") msg.textContent = j.message || "Создание отменено.";
|
||||
if (j.status === "success") {
|
||||
msg.textContent =
|
||||
j.kind === "start_cluster" ? "Кластер поднят по сохранённому конфигу." : "Кластер создан.";
|
||||
} else if (j.status === "cancelled") msg.textContent = j.message || "Операция отменена.";
|
||||
else msg.textContent = "Ошибка: " + (j.message || "");
|
||||
}
|
||||
if (j.status === "success") showToast("Кластер создан", false);
|
||||
else if (j.status === "cancelled") showToast(j.message || "Отменено", false);
|
||||
else showToast(j.message || "Ошибка создания", true);
|
||||
if (j.status === "success") {
|
||||
showToast(j.kind === "start_cluster" ? "Кластер запущен" : "Кластер создан", false);
|
||||
} else if (j.status === "cancelled") showToast(j.message || "Отменено", false);
|
||||
else showToast(j.message || "Ошибка", true);
|
||||
await loadClusters();
|
||||
await loadStats();
|
||||
await loadJobs();
|
||||
await loadHealth();
|
||||
}
|
||||
} catch (e) {
|
||||
if (msg) msg.textContent = "Ошибка опроса задания: " + e.message;
|
||||
@@ -474,6 +792,7 @@
|
||||
const details = document.getElementById("job-details");
|
||||
if (msg) msg.textContent = "";
|
||||
if (details) details.classList.add("hidden");
|
||||
setProgressHint(null);
|
||||
const fd = new FormData(form);
|
||||
const body = {
|
||||
name: String(fd.get("name") || "").trim(),
|
||||
@@ -505,6 +824,13 @@
|
||||
const mClose = document.getElementById("modal-close");
|
||||
if (mClose) mClose.addEventListener("click", closeModal);
|
||||
|
||||
const modalBtnKube = document.getElementById("modal-btn-kubeconfig");
|
||||
if (modalBtnKube) {
|
||||
modalBtnKube.addEventListener("click", function () {
|
||||
if (currentModalClusterName) downloadKubeconfig(currentModalClusterName);
|
||||
});
|
||||
}
|
||||
|
||||
const overlay = document.getElementById("modal-overlay");
|
||||
if (overlay) {
|
||||
overlay.addEventListener("click", function (ev) {
|
||||
@@ -513,9 +839,43 @@
|
||||
}
|
||||
|
||||
document.addEventListener("keydown", function (ev) {
|
||||
if (ev.key === "Escape") closeModal();
|
||||
if (ev.key !== "Escape") return;
|
||||
if (isConfirmModalOpen()) {
|
||||
closeConfirmModal(false);
|
||||
return;
|
||||
}
|
||||
hideActionTooltip();
|
||||
closeModal();
|
||||
});
|
||||
|
||||
const confirmOv = document.getElementById("confirm-modal-overlay");
|
||||
const confirmCancel = document.getElementById("confirm-modal-cancel");
|
||||
const confirmOk = document.getElementById("confirm-modal-ok");
|
||||
if (confirmCancel) {
|
||||
confirmCancel.addEventListener("click", function () {
|
||||
closeConfirmModal(false);
|
||||
});
|
||||
}
|
||||
if (confirmOk) {
|
||||
confirmOk.addEventListener("click", function () {
|
||||
closeConfirmModal(true);
|
||||
});
|
||||
}
|
||||
if (confirmOv) {
|
||||
confirmOv.addEventListener("click", function (ev) {
|
||||
if (ev.target === confirmOv) closeConfirmModal(false);
|
||||
});
|
||||
}
|
||||
|
||||
window.addEventListener(
|
||||
"scroll",
|
||||
function () {
|
||||
hideActionTooltip();
|
||||
},
|
||||
true,
|
||||
);
|
||||
window.addEventListener("resize", hideActionTooltip);
|
||||
|
||||
autoTimer = setInterval(refreshLists, AUTO_REFRESH_MS);
|
||||
|
||||
loadHealth();
|
||||
@@ -523,6 +883,7 @@
|
||||
loadVersions();
|
||||
loadClusters();
|
||||
loadJobs();
|
||||
bindActionTooltipHosts(document.getElementById("modal-overlay"));
|
||||
}
|
||||
|
||||
if (document.readyState === "loading") {
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* Страница /documentation: загрузка README через API и рендер Markdown.
|
||||
* Зависимости из репозитория: /static/js/vendor/marked.min.js, purify.min.js
|
||||
*
|
||||
* Автор: Сергей Антропов
|
||||
* Сайт: https://devops.org.ru
|
||||
*/
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
const body = document.body;
|
||||
const API = (body.dataset.apiBase || "/api/v1").replace(/\/$/, "");
|
||||
|
||||
function showErr(el, msg) {
|
||||
if (!el) return;
|
||||
el.textContent = msg;
|
||||
el.classList.remove("hidden");
|
||||
}
|
||||
|
||||
async function run() {
|
||||
const article = document.getElementById("readme-doc-article");
|
||||
const errEl = document.getElementById("readme-error");
|
||||
const loadEl = document.getElementById("readme-loading");
|
||||
if (!article || !loadEl) return;
|
||||
|
||||
if (typeof marked === "undefined" || typeof DOMPurify === "undefined") {
|
||||
showErr(errEl, "Не загружены скрипты marked или DOMPurify из /static/js/vendor/.");
|
||||
loadEl.classList.add("hidden");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const r = await fetch(API + "/docs/readme", {
|
||||
headers: { Accept: "text/markdown, text/plain, */*" },
|
||||
});
|
||||
const text = await r.text();
|
||||
if (!r.ok) {
|
||||
var detail = text;
|
||||
try {
|
||||
var j = JSON.parse(text);
|
||||
if (j.detail) detail = typeof j.detail === "string" ? j.detail : JSON.stringify(j.detail);
|
||||
} catch (e) {
|
||||
/* сырой текст */
|
||||
}
|
||||
showErr(errEl, "Не удалось загрузить README: " + (detail || r.statusText));
|
||||
loadEl.classList.add("hidden");
|
||||
return;
|
||||
}
|
||||
|
||||
/* marked v15: переносы строк в параграфах (breaks). */
|
||||
try {
|
||||
if (marked.defaults && typeof marked.defaults === "object") {
|
||||
marked.defaults.breaks = true;
|
||||
marked.defaults.gfm = true;
|
||||
}
|
||||
} catch (e) {
|
||||
/* игнорируем, если defaults защищены от записи */
|
||||
}
|
||||
var rawHtml =
|
||||
typeof marked.parse === "function" ? marked.parse(text, { async: false }) : marked(text);
|
||||
article.innerHTML = DOMPurify.sanitize(rawHtml);
|
||||
article.removeAttribute("hidden");
|
||||
loadEl.classList.add("hidden");
|
||||
} catch (e) {
|
||||
showErr(errEl, "Ошибка: " + (e.message || String(e)));
|
||||
loadEl.classList.add("hidden");
|
||||
}
|
||||
}
|
||||
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", run);
|
||||
} else {
|
||||
run();
|
||||
}
|
||||
})();
|
||||
Vendored
+8
@@ -0,0 +1,8 @@
|
||||
Вендорные скрипты для страницы /documentation (Markdown в браузере):
|
||||
|
||||
- marked v15.0.7 — https://github.com/markedjs/marked (лицензия MIT)
|
||||
- DOMPurify v3.2.4 — https://github.com/cure53/DOMPurify (Apache-2.0 / MPL-2.0)
|
||||
|
||||
Файлы: marked.min.js, purify.min.js (без CDN, в репозитории).
|
||||
|
||||
Автор сводки: Сергей Антропов — https://devops.org.ru
|
||||
Vendored
+6
File diff suppressed because one or more lines are too long
Vendored
+3
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user