mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-16 20:11:08 +00:00
* feat(system-manager): add container runtime switcher and kubectl pods Keep the existing Docker tab and select docker, podman, nerdctl, or Kubernetes from runtimes detected on the host. Kubernetes replaces the switcher with context and namespace selectors in the same panel. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(system-manager): address container runtime review findings Move the runtime adapter into the domain layer, keep a context namespace when namespace listing is forbidden, and emit PowerShell or cmd startup commands for Kubernetes shell, logs, and describe. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(system-manager): cover Windows container popups and stale namespaces Run container shell and logs through the host shell's inspect wrapper on PowerShell and cmd, and reset the namespace when a remembered Kubernetes context is no longer present. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(system-manager): parse kubectl JSON after banners and scope inspect cache Skip bracketed banners before kubectl JSON, and include the container runtime in image and container inspect cache keys. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(system-manager): parse Podman image lists emitted as JSON arrays Podman applies {{json .}} to the whole image slice. Accept that array, including Names and byte sizes, and keep Docker's JSON lines. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(system-manager): parse Podman stats arrays Accept Podman's stats JSON array and its id/cpu_percent fields, and keep Docker's one-stat-per-line output. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(system-manager): list every Podman image tag Expand each name in a Podman image's Names array into its own row so extra tags stay visible and searchable. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(system-manager): quote kubectl list and delete for the session shell Namespace, pod, and delete commands follow PowerShell or cmd quoting when the session shell is not POSIX, so apostrophes in a context name survive local PowerShell. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(system-manager): drop renamed runtime launch commands from shell history Container popups now probe with _nc_rt_err and also cover podman, nerdctl, and kubectl. History sanitizers still required _nc_docker_err, so those launches stayed in persisted history. Confirm-dialog resets also follow the selected runtime. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(system-manager): sum Podman interface stats and quote kubectl for the executor Podman {{json .}} stats keep per-interface counters on Network, so the details panel now sums RxBytes and TxBytes. Background kubectl runs in powershell.exe on local Windows even when the terminal is cmd, so those commands are quoted for that executor instead of the interactive shell. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(system-manager): remove a selected image tag instead of the shared id Podman rows that share one image id were all deleted with rmi <id>, which either fails while other tags remain or drops every name. Tagged rows now run rmi repository:tag; dangling images still use the id. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(system-manager): reject cmd kubectl arguments that contain percent signs Interactive cmd.exe expands %VAR% inside double quotes, so a context such as prod-%USERNAME% would be rewritten before kubectl sees it. Cmd popups now refuse that argument. PowerShell quoting still preserves the percent. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * refactor(system-manager): move runtime selection into an application hook Persisted source, context, and namespace state plus the kubectl discovery effects now live in useContainerRuntimeSelection. DockerManagerTab only renders the switcher and panels. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(system-manager): offer kubectl shell only for running containers Succeeded and failed pods have no running container, and a completed init container cannot accept exec. Shell targets now come from container statuses that are running; logs still include init containers. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(system-manager): keep Windows popup commands out of shell history PowerShell and cmd container popups inspect then run, and kubectl popups are typed directly. History filtering only matched the POSIX sh -c wrapper, so those launches were stored as user commands. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(system-manager): mark Windows popups instead of matching kubectl syntax Filtering kubectl --context logs and describe also dropped commands the user typed. Windows popups now carry __NC_POPUP__, and ordinary kubectl lines stay in history. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(system-manager): reject cmd arguments that contain delayed-expansion marks cmd.exe with /V:ON expands !VAR! inside double quotes. Contexts such as prod!USER! are refused for cmd popups, same as percent signs. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(system-manager): hide raw nerdctl and unreachable cluster errors Only offer nerdctl after a short info probe succeeds, or when the failure is a socket permission error that sudo can still recover. Map dead containerd and unreachable kube API errors to short localized messages and keep the CLI text in the log. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(system-manager): show terminating pods and ephemeral containers A deletion timestamp is Terminating even while the phase is still Running. Ephemeral containers are included in the logs list, and a running one is a shell target. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(system-manager): keep the runtime select on Kubernetes and avoid covering it Kubernetes uses the same compact source menu as Docker, with context and namespace beside it. Shell popups open in the free part of the window so they no longer sit on top of the pod badges. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(system-manager): restore the saved engine when Kubernetes disappears A host that was on Podman before Kubernetes keeps Podman if kubectl is gone, instead of falling back to Docker and overwriting that choice. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(system-manager): avoid the visible system panel when others are parked A hidden parking-host panel can be the first system-manager match and has a zero-size rect. Scan every match and pass the first panel that actually has size so the shell popup still sits beside the open panel. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(system-manager): keep a runtime choice across probe gaps and show podman ports A failed nerdctl or kubectl probe was saved as the fallback engine, so the previous choice never returned. Reconciliation now restores the stored source when it is detected again, and automatic fallbacks are not written back. Podman ps port mappings and exposed ports are formatted into the same display string the container detail strip already shows. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(system-manager): show a pod's Evicted reason Pod status.reason is the eviction signal, while the phase stays Failed and the container often reports Error. Use that reason after a container waiting state and before the generic phase so the badge stays Evicted. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(system-manager): keep an avoided shell popup inside the work area When the source window sits partly off-screen, clamping a slot back onto the display could cover the system panel, and the fallback then used the raw slot origin. Place the popup in the on-screen part of the slot instead. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(system-manager): left-align the runtime selector row The Kubernetes context, namespace, and runtime selects sat on the right of the header, so they did not line up with the search field. Keep the same padding, let the context select fill the remaining width, and leave the runtime and namespace selects at their natural width. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>
551 lines
20 KiB
JavaScript
551 lines
20 KiB
JavaScript
"use strict";
|
|
|
|
const CONTAINER_RUNTIMES = ["docker", "podman", "nerdctl"];
|
|
const SOURCE_ORDER = ["docker", "podman", "nerdctl", "kubernetes"];
|
|
|
|
const CLEAR_STARTUP_OUTPUT = "printf '\\033[H\\033[2J\\033[3J';";
|
|
const NETCATTY_POPUP_HISTORY_MARKER = "__NC_POPUP__";
|
|
|
|
function popupHistoryPrefix(shell) {
|
|
if (shell === "powershell") return `$__nc_popup='${NETCATTY_POPUP_HISTORY_MARKER}'; `;
|
|
if (shell === "cmd") return `set "${NETCATTY_POPUP_HISTORY_MARKER}=1"& `;
|
|
return "";
|
|
}
|
|
|
|
function shQuote(str) {
|
|
return `'${String(str).replace(/'/g, "'\"'\"'")}'`;
|
|
}
|
|
|
|
function normalizeContainerRuntime(runtime) {
|
|
return CONTAINER_RUNTIMES.includes(runtime) ? runtime : "docker";
|
|
}
|
|
|
|
function isContainerSource(value) {
|
|
return SOURCE_ORDER.includes(value);
|
|
}
|
|
|
|
function runtimeBinary(runtime) {
|
|
return normalizeContainerRuntime(runtime);
|
|
}
|
|
|
|
function buildRuntimeCommand(runtime, args) {
|
|
return `${runtimeBinary(runtime)} ${String(args || "")}`.trim();
|
|
}
|
|
|
|
function parseRuntimeProbe(stdout) {
|
|
const text = stdout || "";
|
|
const hasFlag = (name) => new RegExp(`(?:^|\\r?\\n)${name}=1(?:\\r?\\n|$)`).test(text);
|
|
return {
|
|
docker: hasFlag("__NC_DOCKER__"),
|
|
podman: hasFlag("__NC_PODMAN__"),
|
|
nerdctl: hasFlag("__NC_NERDCTL__"),
|
|
kubernetes: hasFlag("__NC_KUBECTL__"),
|
|
};
|
|
}
|
|
|
|
function sourcesFromCapabilities(capabilities) {
|
|
if (!capabilities) return [];
|
|
const present = {
|
|
docker: capabilities.hasDocker === true || capabilities.docker === true,
|
|
podman: capabilities.hasPodman === true || capabilities.podman === true,
|
|
nerdctl: capabilities.hasNerdctl === true || capabilities.nerdctl === true,
|
|
kubernetes: capabilities.hasKubectl === true || capabilities.kubernetes === true,
|
|
};
|
|
return SOURCE_ORDER.filter((id) => present[id]);
|
|
}
|
|
|
|
function pickContainerSource(detected, current, remembered) {
|
|
const available = SOURCE_ORDER.filter((id) => Array.isArray(detected) && detected.includes(id));
|
|
if (current && available.includes(current)) return current;
|
|
if (remembered && available.includes(remembered)) return remembered;
|
|
return available[0] || null;
|
|
}
|
|
|
|
function rememberedContainerSource(preference, detected) {
|
|
const source = preference?.source;
|
|
if (!isContainerSource(source)) return null;
|
|
const available = Array.isArray(detected) ? detected : [];
|
|
if (source === "kubernetes" && !available.includes("kubernetes") && CONTAINER_RUNTIMES.includes(preference?.engine)) {
|
|
return preference.engine;
|
|
}
|
|
return source;
|
|
}
|
|
|
|
function reconcileContainerSource(detected, current, preference) {
|
|
const available = SOURCE_ORDER.filter((id) => Array.isArray(detected) && detected.includes(id));
|
|
const preferred = rememberedContainerSource(preference, available);
|
|
if (preferred && available.includes(preferred)) return preferred;
|
|
return pickContainerSource(available, current, preferred);
|
|
}
|
|
|
|
function isAutomaticRuntimeFallback(preference, source, detected) {
|
|
if (!preference?.source || !isContainerSource(source) || preference.source === source) return false;
|
|
const available = Array.isArray(detected) ? detected : [];
|
|
if (available.includes(preference.source)) return false;
|
|
const automatic = pickContainerSource(
|
|
available,
|
|
null,
|
|
rememberedContainerSource(preference, available),
|
|
);
|
|
return source === automatic;
|
|
}
|
|
|
|
function firstContainerRuntime(detected) {
|
|
return CONTAINER_RUNTIMES.find((id) => Array.isArray(detected) && detected.includes(id)) || null;
|
|
}
|
|
|
|
function socketNeedles(runtime) {
|
|
if (runtime === "podman") {
|
|
return ["podman.sock", "/run/podman", "podman daemon"];
|
|
}
|
|
if (runtime === "nerdctl") {
|
|
return ["containerd.sock", "/run/containerd"];
|
|
}
|
|
return ["docker daemon", "docker.sock", "/var/run/docker.sock", "connect to the docker daemon"];
|
|
}
|
|
|
|
function isRuntimeSocketPermissionError(runtime, result) {
|
|
const text = `${result?.stderr || ""}\n${result?.stdout || ""}\n${result?.error || ""}`.toLowerCase();
|
|
if (!text.includes("permission denied")) return false;
|
|
return socketNeedles(normalizeContainerRuntime(runtime)).some((needle) => text.includes(needle));
|
|
}
|
|
|
|
function socketCasePatterns(runtime) {
|
|
if (runtime === "podman") {
|
|
return [
|
|
"*permission\\ denied*podman.sock*",
|
|
"*podman.sock*permission\\ denied*",
|
|
"*permission\\ denied*/run/podman*",
|
|
"*/run/podman*permission\\ denied*",
|
|
"*permission\\ denied*podman\\ daemon*",
|
|
"*podman\\ daemon*permission\\ denied*",
|
|
];
|
|
}
|
|
if (runtime === "nerdctl") {
|
|
return [
|
|
"*permission\\ denied*containerd.sock*",
|
|
"*containerd.sock*permission\\ denied*",
|
|
"*permission\\ denied*/run/containerd*",
|
|
"*/run/containerd*permission\\ denied*",
|
|
];
|
|
}
|
|
return [
|
|
"*permission\\ denied*docker\\ daemon*",
|
|
"*docker\\ daemon*permission\\ denied*",
|
|
"*permission\\ denied*docker.sock*",
|
|
"*docker.sock*permission\\ denied*",
|
|
"*permission\\ denied*/var/run/docker.sock*",
|
|
"*/var/run/docker.sock*permission\\ denied*",
|
|
"*permission\\ denied*connect\\ to\\ the\\ docker\\ daemon*",
|
|
"*connect\\ to\\ the\\ docker\\ daemon*permission\\ denied*",
|
|
];
|
|
}
|
|
|
|
function sanitizeContainerId(id) {
|
|
return String(id || "").replace(/[^a-zA-Z0-9]/g, "").slice(0, 64);
|
|
}
|
|
|
|
function containerInteractiveArgs(containerId, shell) {
|
|
if (shell === "cmd") {
|
|
return `exec -it ${containerId} sh -c "command -v bash >/dev/null 2>&1 && exec bash || exec sh"`;
|
|
}
|
|
return `exec -it ${containerId} sh -c 'command -v bash >/dev/null 2>&1 && exec bash || exec sh'`;
|
|
}
|
|
|
|
function buildContainerCommandWithSudoFallback(runtime, containerId, cliArgs, shell) {
|
|
const popupShell = normalizePopupShell(shell);
|
|
const bin = runtimeBinary(runtime);
|
|
const plainCommand = `${bin} ${cliArgs}`;
|
|
if (popupShell === "powershell") {
|
|
return `${popupHistoryPrefix(popupShell)}${bin} inspect ${containerId} >$null; if ($LASTEXITCODE -eq 0) { ${plainCommand} } else { exit $LASTEXITCODE }`;
|
|
}
|
|
if (popupShell === "cmd") {
|
|
return `${popupHistoryPrefix(popupShell)}${bin} inspect ${containerId} >nul && ${plainCommand}`;
|
|
}
|
|
const sudoCommand = `sudo ${plainCommand}`;
|
|
const script = [
|
|
CLEAR_STARTUP_OUTPUT,
|
|
`_nc_rt_err=$(${bin} inspect ${containerId} 2>&1 >/dev/null);`,
|
|
"_nc_rt_status=$?;",
|
|
`if [ "$_nc_rt_status" -eq 0 ]; then exec ${plainCommand}; fi;`,
|
|
"_nc_rt_lc=$(printf '%s' \"$_nc_rt_err\" | tr '[:upper:]' '[:lower:]');",
|
|
"case \"$_nc_rt_lc\" in",
|
|
`${socketCasePatterns(normalizeContainerRuntime(runtime)).join("|")}) exec ${sudoCommand} ;;`,
|
|
"*) printf '%s\\n' \"$_nc_rt_err\" >&2; exit \"$_nc_rt_status\" ;;",
|
|
"esac",
|
|
].join(" ");
|
|
return `sh -c ${shQuote(script)}`;
|
|
}
|
|
|
|
function buildContainerExecShellCommand(runtime, containerId, shell) {
|
|
const safeId = sanitizeContainerId(containerId);
|
|
if (!safeId) return 'echo "Invalid container id"';
|
|
return buildContainerCommandWithSudoFallback(
|
|
runtime,
|
|
safeId,
|
|
containerInteractiveArgs(safeId, normalizePopupShell(shell)),
|
|
shell,
|
|
);
|
|
}
|
|
|
|
function buildContainerLogsCommand(runtime, containerId, shell) {
|
|
const safeId = sanitizeContainerId(containerId);
|
|
if (!safeId) return 'echo "Invalid container id"';
|
|
return buildContainerCommandWithSudoFallback(runtime, safeId, `logs -f --tail 200 ${safeId}`, shell);
|
|
}
|
|
|
|
function hasControlChar(text) {
|
|
for (let i = 0; i < text.length; i += 1) {
|
|
const code = text.charCodeAt(i);
|
|
if (code <= 31 || code === 127) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
function isSafeShellArg(value, shell) {
|
|
const text = String(value ?? "");
|
|
if (!text || text.length > 512) return false;
|
|
if (hasControlChar(text)) return false;
|
|
// Interactive cmd.exe expands %VAR% inside double quotes, and %% is not a
|
|
// reliable escape there. With /V:ON it also expands !VAR! inside quotes.
|
|
// Reject those arguments instead of targeting a substituted context.
|
|
if (shell === "cmd" && (text.includes("%") || text.includes("!"))) return false;
|
|
return true;
|
|
}
|
|
|
|
function normalizePopupShell(shell) {
|
|
return shell === "powershell" || shell === "cmd" ? shell : "posix";
|
|
}
|
|
|
|
function quoteShellArg(shell, value) {
|
|
const text = String(value);
|
|
if (shell === "cmd") return `"${text.replace(/"/g, '""')}"`;
|
|
if (shell === "powershell") return `'${text.replace(/'/g, "''")}'`;
|
|
return shQuote(text);
|
|
}
|
|
|
|
function kubectlPrefix(context, namespace, shell = "posix") {
|
|
const popupShell = normalizePopupShell(shell);
|
|
if (!isSafeShellArg(context, popupShell)) return null;
|
|
const parts = ["kubectl", "--context", quoteShellArg(popupShell, context)];
|
|
if (namespace != null && namespace !== "") {
|
|
if (!isSafeShellArg(namespace, popupShell)) return null;
|
|
parts.push("-n", quoteShellArg(popupShell, namespace));
|
|
}
|
|
return parts.join(" ");
|
|
}
|
|
|
|
function optionalContainerArg(container, shell = "posix") {
|
|
if (container == null || container === "") return "";
|
|
if (!isSafeShellArg(container, normalizePopupShell(shell))) return null;
|
|
return ` -c ${quoteShellArg(normalizePopupShell(shell), container)}`;
|
|
}
|
|
|
|
function isKubectlForbiddenError(message) {
|
|
return /\bforbidden\b/i.test(String(message || ""));
|
|
}
|
|
|
|
function isKubectlUnreachableError(message) {
|
|
const text = String(message || "");
|
|
if (!text.trim() || isKubectlForbiddenError(text)) return false;
|
|
return /couldn'?t get current server api group list|could not get current server api group list|unable to connect to the server|connection refused|dial tcp|i\/o timeout|no such host|network is unreachable|context deadline exceeded|tls handshake timeout/i.test(text);
|
|
}
|
|
|
|
function isNerdctlUnreachableError(message) {
|
|
const text = String(message || "").toLowerCase();
|
|
if (!text.trim()) return false;
|
|
if (text.includes("rootless containerd") || text.includes("xdg_runtime_dir")) return true;
|
|
if (text.includes("cannot connect to the docker daemon")) return true;
|
|
if (!text.includes("containerd")) return false;
|
|
return /not running|connection refused|no such file|cannot connect|failed to connect|unavailable/.test(text);
|
|
}
|
|
|
|
const POD_STATUS_MESSAGE_KEYS = {
|
|
Running: "systemManager.k8s.status.Running",
|
|
Pending: "systemManager.k8s.status.Pending",
|
|
Completed: "systemManager.k8s.status.Completed",
|
|
Succeeded: "systemManager.k8s.status.Succeeded",
|
|
Failed: "systemManager.k8s.status.Failed",
|
|
Unknown: "systemManager.k8s.status.Unknown",
|
|
CrashLoopBackOff: "systemManager.k8s.status.CrashLoopBackOff",
|
|
ContainerCreating: "systemManager.k8s.status.ContainerCreating",
|
|
Evicted: "systemManager.k8s.status.Evicted",
|
|
Terminating: "systemManager.k8s.status.Terminating",
|
|
ImagePullBackOff: "systemManager.k8s.status.ImagePullBackOff",
|
|
ErrImagePull: "systemManager.k8s.status.ErrImagePull",
|
|
Error: "systemManager.k8s.status.Error",
|
|
OOMKilled: "systemManager.k8s.status.OOMKilled",
|
|
};
|
|
|
|
function podStatusMessageKey(status) {
|
|
return POD_STATUS_MESSAGE_KEYS[String(status || "")] || null;
|
|
}
|
|
|
|
function runtimeFailureMessage(errorCode, context) {
|
|
if (errorCode === "nerdctlUnreachable") {
|
|
return { key: "systemManager.errors.nerdctlUnreachable" };
|
|
}
|
|
if (errorCode === "clusterUnreachable") {
|
|
const name = typeof context === "string" ? context.trim() : "";
|
|
if (name) {
|
|
return {
|
|
key: "systemManager.errors.clusterUnreachable",
|
|
values: { context: name },
|
|
};
|
|
}
|
|
return { key: "systemManager.errors.clusterUnreachableGeneric" };
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function wrapClearAndExec(command) {
|
|
return `sh -c ${shQuote(`${CLEAR_STARTUP_OUTPUT} exec ${command}`)}`;
|
|
}
|
|
|
|
function buildKubectlContextsCommand() {
|
|
return "kubectl config view -o json";
|
|
}
|
|
|
|
function buildKubectlNamespacesCommand(context, shell) {
|
|
const popupShell = normalizePopupShell(shell);
|
|
if (!isSafeShellArg(context, popupShell)) return null;
|
|
return `kubectl --context ${quoteShellArg(popupShell, context)} get namespaces -o json`;
|
|
}
|
|
|
|
function buildKubectlPodsCommand(context, namespace, shell) {
|
|
const prefix = kubectlPrefix(context, namespace, shell);
|
|
if (!prefix) return null;
|
|
return `${prefix} get pods -o json`;
|
|
}
|
|
|
|
function buildKubectlDeletePodCommand(context, namespace, pod, shell) {
|
|
const popupShell = normalizePopupShell(shell);
|
|
const prefix = kubectlPrefix(context, namespace, popupShell);
|
|
if (!prefix || !isSafeShellArg(pod, popupShell)) return null;
|
|
return `${prefix} delete pod ${quoteShellArg(popupShell, pod)} --wait=false`;
|
|
}
|
|
|
|
function containerShellArg(shell) {
|
|
if (shell === "cmd") {
|
|
return 'sh -c "command -v bash >/dev/null 2>&1 && exec bash || exec sh"';
|
|
}
|
|
return "sh -c 'command -v bash >/dev/null 2>&1 && exec bash || exec sh'";
|
|
}
|
|
|
|
function finishKubectlPopup(shell, command) {
|
|
return shell === "posix" ? wrapClearAndExec(command) : `${popupHistoryPrefix(shell)}${command}`;
|
|
}
|
|
|
|
function buildKubectlExecShellCommand(context, namespace, pod, container, shell) {
|
|
const popupShell = normalizePopupShell(shell);
|
|
const prefix = kubectlPrefix(context, namespace, popupShell);
|
|
if (!prefix) return 'echo "Invalid context"';
|
|
if (!isSafeShellArg(pod, popupShell)) return 'echo "Invalid pod name"';
|
|
const containerArg = optionalContainerArg(container, popupShell);
|
|
if (containerArg == null) return 'echo "Invalid container name"';
|
|
const command = `${prefix} exec -it ${quoteShellArg(popupShell, pod)}${containerArg} -- ${containerShellArg(popupShell)}`;
|
|
return finishKubectlPopup(popupShell, command);
|
|
}
|
|
|
|
function buildKubectlLogsCommand(context, namespace, pod, container, shell) {
|
|
const popupShell = normalizePopupShell(shell);
|
|
const prefix = kubectlPrefix(context, namespace, popupShell);
|
|
if (!prefix) return 'echo "Invalid context"';
|
|
if (!isSafeShellArg(pod, popupShell)) return 'echo "Invalid pod name"';
|
|
const containerArg = optionalContainerArg(container, popupShell);
|
|
if (containerArg == null) return 'echo "Invalid container name"';
|
|
const command = `${prefix} logs -f --tail 200 ${quoteShellArg(popupShell, pod)}${containerArg}`;
|
|
return finishKubectlPopup(popupShell, command);
|
|
}
|
|
|
|
function buildKubectlDescribeCommand(context, namespace, pod, shell) {
|
|
const popupShell = normalizePopupShell(shell);
|
|
const prefix = kubectlPrefix(context, namespace, popupShell);
|
|
if (!prefix) return 'echo "Invalid context"';
|
|
if (!isSafeShellArg(pod, popupShell)) return 'echo "Invalid pod name"';
|
|
const command = `${prefix} describe pod ${quoteShellArg(popupShell, pod)}`;
|
|
return finishKubectlPopup(popupShell, command);
|
|
}
|
|
|
|
function parseJsonValue(text) {
|
|
const raw = String(text || "");
|
|
for (let i = 0; i < raw.length; i += 1) {
|
|
const ch = raw[i];
|
|
if (ch !== "{" && ch !== "[") continue;
|
|
try {
|
|
return JSON.parse(raw.slice(i));
|
|
} catch {
|
|
// A bracketed banner such as [WARN] is not the JSON document.
|
|
}
|
|
}
|
|
throw new Error("Invalid JSON");
|
|
}
|
|
|
|
function parseKubeconfigContexts(jsonText) {
|
|
const parsed = parseJsonValue(jsonText);
|
|
const current = typeof parsed["current-context"] === "string" ? parsed["current-context"] : "";
|
|
const contexts = [];
|
|
const list = Array.isArray(parsed.contexts) ? parsed.contexts : [];
|
|
for (const entry of list) {
|
|
const name = typeof entry?.name === "string" ? entry.name : "";
|
|
if (!name) continue;
|
|
const rawNamespace = entry?.context?.namespace;
|
|
const namespace = typeof rawNamespace === "string" && rawNamespace ? rawNamespace : "default";
|
|
contexts.push({
|
|
name,
|
|
namespace,
|
|
current: name === current,
|
|
});
|
|
}
|
|
return { contexts, current };
|
|
}
|
|
|
|
function parseNamespaceList(jsonText) {
|
|
const parsed = parseJsonValue(jsonText);
|
|
const items = Array.isArray(parsed.items) ? parsed.items : [];
|
|
const names = [];
|
|
for (const item of items) {
|
|
const name = item?.metadata?.name;
|
|
if (typeof name === "string" && name) names.push(name);
|
|
}
|
|
return names;
|
|
}
|
|
|
|
function formatPodAge(iso, now = Date.now()) {
|
|
const timestamp = Date.parse(String(iso || ""));
|
|
if (!Number.isFinite(timestamp)) return "";
|
|
const seconds = Math.max(0, Math.floor((now - timestamp) / 1000));
|
|
if (seconds < 60) return `${seconds}s`;
|
|
const minutes = Math.floor(seconds / 60);
|
|
if (minutes < 60) return `${minutes}m`;
|
|
const hours = Math.floor(minutes / 60);
|
|
if (hours < 24) return `${hours}h`;
|
|
return `${Math.floor(hours / 24)}d`;
|
|
}
|
|
|
|
function podDisplayStatus(pod) {
|
|
if (typeof pod?.metadata?.deletionTimestamp === "string" && pod.metadata.deletionTimestamp) {
|
|
return "Terminating";
|
|
}
|
|
const statuses = [
|
|
...(Array.isArray(pod?.status?.initContainerStatuses) ? pod.status.initContainerStatuses : []),
|
|
...(Array.isArray(pod?.status?.containerStatuses) ? pod.status.containerStatuses : []),
|
|
];
|
|
for (const status of statuses) {
|
|
const reason = status?.state?.waiting?.reason;
|
|
if (reason) return String(reason);
|
|
}
|
|
const podReason = typeof pod?.status?.reason === "string" ? pod.status.reason.trim() : "";
|
|
if (podReason) return podReason;
|
|
for (const status of statuses) {
|
|
const reason = status?.state?.terminated?.reason;
|
|
if (reason && reason !== "Completed") return String(reason);
|
|
}
|
|
const phase = String(pod?.status?.phase || "Unknown");
|
|
if (phase === "Succeeded") return "Completed";
|
|
return phase;
|
|
}
|
|
|
|
function podContainerNames(pod) {
|
|
const names = [];
|
|
const specs = [
|
|
...(Array.isArray(pod?.spec?.containers) ? pod.spec.containers : []),
|
|
...(Array.isArray(pod?.spec?.initContainers) ? pod.spec.initContainers : []),
|
|
...(Array.isArray(pod?.spec?.ephemeralContainers) ? pod.spec.ephemeralContainers : []),
|
|
];
|
|
for (const container of specs) {
|
|
const name = container?.name;
|
|
if (typeof name === "string" && name && !names.includes(name)) names.push(name);
|
|
}
|
|
return names;
|
|
}
|
|
|
|
function podShellContainerNames(pod) {
|
|
const running = new Set();
|
|
const statuses = [
|
|
...(Array.isArray(pod?.status?.containerStatuses) ? pod.status.containerStatuses : []),
|
|
...(Array.isArray(pod?.status?.initContainerStatuses) ? pod.status.initContainerStatuses : []),
|
|
...(Array.isArray(pod?.status?.ephemeralContainerStatuses) ? pod.status.ephemeralContainerStatuses : []),
|
|
];
|
|
for (const status of statuses) {
|
|
if (status?.state?.running && typeof status.name === "string" && status.name) {
|
|
running.add(status.name);
|
|
}
|
|
}
|
|
const ordered = podContainerNames(pod).filter((name) => running.has(name));
|
|
for (const name of running) {
|
|
if (!ordered.includes(name)) ordered.push(name);
|
|
}
|
|
return ordered;
|
|
}
|
|
|
|
function podRestartCount(pod) {
|
|
const statuses = [
|
|
...(Array.isArray(pod?.status?.containerStatuses) ? pod.status.containerStatuses : []),
|
|
...(Array.isArray(pod?.status?.initContainerStatuses) ? pod.status.initContainerStatuses : []),
|
|
];
|
|
let restarts = 0;
|
|
for (const status of statuses) {
|
|
const count = Number(status?.restartCount || 0);
|
|
if (Number.isFinite(count)) restarts += count;
|
|
}
|
|
return restarts;
|
|
}
|
|
|
|
function parseKubectlPodList(jsonText, now = Date.now()) {
|
|
const parsed = parseJsonValue(jsonText);
|
|
const items = Array.isArray(parsed.items) ? parsed.items : [];
|
|
const pods = [];
|
|
for (const pod of items) {
|
|
const name = typeof pod?.metadata?.name === "string" ? pod.metadata.name : "";
|
|
if (!name) continue;
|
|
pods.push({
|
|
name,
|
|
namespace: typeof pod?.metadata?.namespace === "string" ? pod.metadata.namespace : "",
|
|
status: podDisplayStatus(pod),
|
|
restarts: podRestartCount(pod),
|
|
age: formatPodAge(pod?.metadata?.creationTimestamp, now),
|
|
containers: podContainerNames(pod),
|
|
shellContainers: podShellContainerNames(pod),
|
|
});
|
|
}
|
|
return pods;
|
|
}
|
|
|
|
module.exports = {
|
|
NETCATTY_POPUP_HISTORY_MARKER,
|
|
CONTAINER_RUNTIMES,
|
|
SOURCE_ORDER,
|
|
normalizeContainerRuntime,
|
|
isContainerSource,
|
|
runtimeBinary,
|
|
buildRuntimeCommand,
|
|
parseRuntimeProbe,
|
|
sourcesFromCapabilities,
|
|
pickContainerSource,
|
|
rememberedContainerSource,
|
|
reconcileContainerSource,
|
|
isAutomaticRuntimeFallback,
|
|
firstContainerRuntime,
|
|
isRuntimeSocketPermissionError,
|
|
sanitizeContainerId,
|
|
buildContainerExecShellCommand,
|
|
buildContainerLogsCommand,
|
|
buildKubectlContextsCommand,
|
|
buildKubectlNamespacesCommand,
|
|
buildKubectlPodsCommand,
|
|
buildKubectlDeletePodCommand,
|
|
buildKubectlExecShellCommand,
|
|
buildKubectlLogsCommand,
|
|
buildKubectlDescribeCommand,
|
|
isKubectlForbiddenError,
|
|
isKubectlUnreachableError,
|
|
isNerdctlUnreachableError,
|
|
podStatusMessageKey,
|
|
runtimeFailureMessage,
|
|
parseKubeconfigContexts,
|
|
parseNamespaceList,
|
|
parseKubectlPodList,
|
|
formatPodAge,
|
|
};
|