aboutsummaryrefslogtreecommitdiffstats
path: root/static/modules/vm.js
blob: fdffd09158d493e4c28e212cbb84cf4d197a262c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
// deck-it - the VMs tab: libvirt power, snapshots and an ssh session
// Copyright (C) 2026 Danilo M. <danix@danix.xyz>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

import { offline } from "../offline.js";

// Destructive actions fire only after a hold this long, so a stray touch on
// an always-on tablet cannot force a VM off.
const HOLD_MS = 800;
const HOLD = new Set(["reset", "destroy", "discardsave", "revert", "snapdelete"]);
const PILL = { running: "good", paused: "warn", suspended: "warn", "shutting down": "warn", crashed: "bad" };

// The buttons per state, as keystone's drawer offers them.
function actionsFor(st, saved) {
  if (st === "running")
    return [["ssh", "SSH"], ["shutdown", "Shutdown"], ["reboot", "Reboot"], ["suspend", "Suspend"],
            ["reset", "Reset"], ["destroy", "Force stop"]];
  if (st === "paused" || st === "suspended")
    return [["resume", "Resume"], ["shutdown", "Shutdown"], ["destroy", "Force stop"]];
  return saved ? [["start", "Start"], ["discardsave", "Discard saved state"]] : [["start", "Start"]];
}

const gib = (b) => (b == null ? "—" : `${(b / 2 ** 30).toFixed(1)} GiB`);

async function post(action, body, card) {
  const err = card.querySelector(".vm-err");
  card.classList.add("busy");
  try {
    const r = await fetch(`/api/vm/${action}`, {
      method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body),
    });
    err.textContent = r.ok ? "" : (await r.text()) || r.statusText;
  } catch (e) {
    err.textContent = String(e);
  }
  err.hidden = !err.textContent;
  card.classList.remove("busy");
}

function button(label, action, body, card) {
  const b = document.createElement("button");
  b.textContent = label;
  const fire = () => post(action, body, card);
  if (!HOLD.has(action)) {
    b.onclick = fire;
    return b;
  }
  // Press and hold: the fill grows over HOLD_MS, releasing early cancels.
  b.className = "hold";
  b.title = "Press and hold";
  b.style.setProperty("--hold", `${HOLD_MS}ms`);
  let timer = null;
  const cancel = () => { clearTimeout(timer); b.classList.remove("holding"); };
  b.addEventListener("pointerdown", (e) => {
    e.preventDefault();
    b.setPointerCapture(e.pointerId);
    b.classList.add("holding");
    timer = setTimeout(() => { cancel(); fire(); }, HOLD_MS);
  });
  b.addEventListener("pointerup", cancel);
  b.addEventListener("pointercancel", cancel);
  return b;
}

function card() {
  const c = document.createElement("div");
  c.className = "vm-card";
  c.innerHTML = `<div class="vm-head"><span class="vm-name"></span><span class="vm-state"></span>
      <span class="vm-ip num"></span></div>
    <div class="vm-use"><span class="mlabel">CPU</span><div class="gbar"><i></i></div><span class="vm-cpu num"></span>
      <span class="mlabel">RAM</span><span class="vm-mem num"></span></div>
    <div class="row vm-acts"></div>
    <div class="vm-err" hidden></div>
    <div class="vm-snaps"></div>`;
  return c;
}

// Text every poll; buttons only when what they depend on changed, so a
// hold in progress is not torn down under the finger.
function fill(c, vm) {
  c.querySelector(".vm-name").textContent = vm.name;
  const pill = c.querySelector(".vm-state");
  pill.textContent = vm.saved && vm.state === "shut off" ? "saved" : vm.state;
  pill.className = `vm-state ${PILL[vm.state] ?? ""}`;
  c.querySelector(".vm-ip").textContent = vm.ip;
  const on = vm.state === "running";
  c.querySelector(".vm-use").hidden = !on;
  c.querySelector(".gbar > i").style.width = `${vm.cpu ?? 0}%`;
  c.querySelector(".vm-cpu").textContent = vm.cpu == null ? "—" : `${Math.round(vm.cpu)}% of ${vm.vcpus}`;
  c.querySelector(".vm-mem").textContent = gib(vm.mem);

  const key = JSON.stringify([vm.state, vm.saved, vm.snapshots]);
  if (c.dataset.key === key) return;
  c.dataset.key = key;
  const acts = c.querySelector(".vm-acts");
  acts.replaceChildren(...actionsFor(vm.state, vm.saved).map(([a, l]) => button(l, a, { vm: vm.name }, c)),
    button("Snapshot", "snapshot", { vm: vm.name }, c));
  c.querySelector(".vm-snaps").replaceChildren(...vm.snapshots.map((s) => {
    const row = document.createElement("div");
    row.className = "vm-snap";
    const name = document.createElement("span");
    name.textContent = s;
    row.append(name, button("Revert", "revert", { vm: vm.name, snap: s }, c),
      button("Delete", "snapdelete", { vm: vm.name, snap: s }, c));
    return row;
  }));
}

export default {
  title: "VMs",
  tab: "VMs",
  interval: 2,

  mount(el) {
    el.innerHTML = `<div class="vm"><div class="vm-off"></div><div class="vm-list"></div></div>`;
  },

  update(st, el) {
    const off = el.querySelector(".vm-off");
    const list = el.querySelector(".vm-list");
    off.hidden = !st.offline;
    list.hidden = Boolean(st.offline);
    if (st.offline) {
      offline(off, { icon: "/icons/virt-manager.svg", title: "libvirt is not answering",
        detail: "Start libvirtd and the VMs appear here.", reason: st.reason });
      return;
    }
    const cards = new Map([...list.children].map((c) => [c.dataset.vm, c]));
    list.replaceChildren(...st.vms.map((vm) => {
      const c = cards.get(vm.name) ?? card();
      c.dataset.vm = vm.name;
      fill(c, vm);
      return c;
    }));
    if (!st.vms.length) list.textContent = "No VMs defined.";
  },
};