Debian Codegraph @

pkg/shell/machines/machines.js

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2 import cockpit from "cockpit";
3 import { import_Manifests } from "../manifests";
4 import { validate } from "import-json";
5 import { host_superuser_storage_key } from "superuser-dialogs";
6
7 import ssh_add_key_sh from "../../lib/ssh-add-key.sh";
8
9 const mod = { };
10
11 /*
12 * We share the Machines state between multiple frames. Only
13 * one frame has the job of loading the state, usually index.js
14 * The Loader code below does all the loading.
15 *
16 * The data is stored in sessionStorage in a JSON object, like this
17 * {
18 * content: name → info dict from bridge's /machines Machines property
19 * overlay: extra data to augment and override on top of content
20 * }
21 *
22 * This uses sessionStorage rather than cockpit.sessionStorage
23 * because we don't ever want to write unprefixed keys.
24 */
25
26 const key = cockpit.sessionStorage.prefixedKey("v2-machines.json");
27 const session_prefix = cockpit.sessionStorage.prefixedKey("v1-session-machine");
28
29 function generate_session_key(host) {
30 return session_prefix + "/" + host;
31 }
32
33 export function get_init_superuser_for_options(options) {
34 let value = null;
35 const key = host_superuser_storage_key(options.host);
36 if (key)
37 value = window.localStorage.getItem(key);
38
39 /* When connecting, we can optionally try to start a privileged
40 * bridge immediately. However, it is quite likely that that
41 * needs a password and if we don't have one, it will likely fail.
42 * That would be okay, but sudo is very noisy about failures and
43 * might send nasty emails to your parents. For that reason we
44 * pass "init-superuser": "none" here when there is no password.
45 *
46 * The downside is that if sudo is configured to not require a
47 * password, we could start it successfully immediately as part
48 * of the connection process, which would be convenient. However,
49 * if sudo works without password, gaining admin privs is just a
50 * single click, and the convenience loss is not that of a big deal,
51 * hopefully.
52 */
53
54 if (value == "sudo" && !options.password)
55 value = "none";
56
57 return value;
58 }
59
60 export function generate_connection_string(user, port, addr) {
61 let address = addr;
62 if (user)
63 address = user + "@" + address;
64
65 if (port)
66 address = address + ":" + port;
67
68 return address;
69 }
70
71 export function split_connection_string (conn_to) {
72 const parts = { address: "" };
73 let user_spot = -1;
74 let port_spot = -1;
75
76 if (conn_to) {
77 if (conn_to.substring(0, 6) === "ssh://")
78 conn_to = conn_to.substring(6);
79 user_spot = conn_to.lastIndexOf('@');
80 port_spot = conn_to.lastIndexOf(':');
81 }
82
83 if (user_spot > 0) {
84 parts.user = conn_to.substring(0, user_spot);
85 conn_to = conn_to.substring(user_spot + 1);
86 port_spot = conn_to.lastIndexOf(':');
87 }
88
89 if (port_spot > -1) {
90 const port = parseInt(conn_to.substring(port_spot + 1), 10);
91 if (!isNaN(port)) {
92 parts.port = port;
93 conn_to = conn_to.substring(0, port_spot);
94 }
95 }
96
97 parts.address = conn_to;
98 return parts;
99 }
100
101 function import_manifests(val) {
102 return validate("manifests", val, import_Manifests, {});
103 }
104
105 function Machines() {
106 const self = this;
107
108 cockpit.event_target(self);
109
110 let flat = null;
111 self.ready = false;
112
113 /* parsed machine data */
114 const machines = { };
115
116 /* Data shared between Machines() instances */
117 let last = {
118 content: null,
119 overlay: {
120 localhost: {
121 visible: true,
122 manifests: import_manifests(cockpit.manifests)
123 }
124 }
125 };
126
127 function storage(ev) {
128 if (ev.key === key && ev.storageArea === window.sessionStorage)
129 refresh(JSON.parse(ev.newValue || "null"));
130 }
131
132 window.addEventListener("storage", storage);
133
134 window.setTimeout(function() {
135 const value = window.sessionStorage.getItem(key);
136 if (!self.ready && value)
137 refresh(JSON.parse(value));
138 });
139
140 let timeout = null;
141
142 function sync(machine, values, overlay) {
143 const desired = { ...values, ...overlay };
144 for (const prop in desired) {
145 if (machine[prop] !== desired[prop])
146 machine[prop] = desired[prop];
147 }
148 for (const prop in machine) {
149 if (machine[prop] !== desired[prop])
150 delete machine[prop];
151 }
152 return machine;
153 }
154
155 function refresh(shared, push) {
156 if (!shared)
157 return;
158
159 last = shared;
160 flat = null;
161
162 if (push && !timeout) {
163 timeout = window.setTimeout(function() {
164 timeout = null;
165 window.sessionStorage.setItem(key, JSON.stringify(last));
166 }, 10);
167 }
168
169 const hosts = { };
170 const content = shared.content || { };
171 const overlay = shared.overlay || { };
172 for (const host in content)
173 hosts[host] = true;
174 for (const host in overlay)
175 hosts[host] = true;
176
177 const events = [];
178
179 for (const host in hosts) {
180 const old_machine = machines[host] || { };
181 const old_conns = old_machine.connection_string;
182
183 /* Invert logic for color, always respect what's on disk */
184 if (content[host] && content[host].color && overlay[host])
185 delete overlay[host].color;
186
187 const machine = sync(old_machine, content[host], overlay[host]);
188
189 /* Fill in defaults */
190 machine.key = host;
191 if (!machine.address)
192 machine.address = host;
193
194 machine.connection_string = generate_connection_string(machine.user,
195 machine.port,
196 machine.address);
197
198 if (!machine.label) {
199 if (host == "localhost" || host == "localhost.localdomain") {
200 const application = cockpit.transport.application();
201 if (application.indexOf('cockpit+=') === 0)
202 machine.label = application.replace('cockpit+=', '');
203 else
204 machine.label = window.location.hostname;
205 } else {
206 machine.label = host;
207 }
208 }
209 if (!machine.avatar)
210 machine.avatar = "../shell/images/server-small.png";
211
212 events.push([host in machines ? "updated" : "added",
213 [machine, host, old_conns]]);
214 machines[host] = machine;
215 }
216
217 /* Remove any lost hosts */
218 for (const host in machines) {
219 if (!(host in hosts)) {
220 const machine = machines[host];
221 delete machines[host];
222 delete overlay[host];
223 events.push(["removed", [machine, host]]);
224 }
225 }
226
227 /* Fire off all events */
228 const len = events.length;
229 for (let i = 0; i < len; i++) {
230 self.dispatchEvent(events[i][0], ...events[i][1]);
231 }
232 }
233
234 function update_session_machine(machine, host, values) {
235 /* We don't save the whole machine object */
236 const skey = generate_session_key(host);
237 const data = { ...machine, ...values };
238 window.sessionStorage.setItem(skey, JSON.stringify(data));
239 self.overlay(host, values);
240 return Promise.resolve([]);
241 }
242
243 function update_saved_machine(host, values) {
244 // wrap values in variants for D-Bus call; at least values.port can
245 // be int or string, so stringify everything but the "visible" boolean
246 const values_variant = {};
247 for (const prop in values) {
248 if (values[prop] !== null) {
249 if (prop == "visible")
250 values_variant[prop] = cockpit.variant('b', values[prop]);
251 else
252 values_variant[prop] = cockpit.variant('s', values[prop].toString());
253 }
254 }
255
256 // FIXME: investigate reusing the proxy from Loader (runs in different frame/scope)
257 const bridge = cockpit.dbus(null, { bus: "internal", superuser: "require" });
258 const mod =
259 bridge.call("/machines", "cockpit.Machines", "Update", ["99-webui.json", host, values_variant])
260 .catch(error => {
261 // avoid make noise when we are not superuser
262 if (error.problem !== "access-denied")
263 console.error("failed to call cockpit.Machines.Update(): ", JSON.stringify(error));
264 })
265 .then(() => self.overlay(host, values));
266
267 return mod;
268 }
269
270 self.set_ready = function ready() {
271 if (!self.ready) {
272 self.ready = true;
273 self.dispatchEvent("ready");
274 }
275 };
276
277 self.add_key = function(host_key) {
278 return cockpit.script(ssh_add_key_sh, [host_key.trim(), "known_hosts"], { err: "message" });
279 };
280
281 self.add = function add(connection_string, color) {
282 let values = split_connection_string(connection_string);
283 const host = values.address;
284
285 values = {
286 visible: true,
287 color: color || self.unused_color(),
288 ...values
289 };
290
291 const machine = self.lookup(host);
292 if (machine)
293 machine.on_disk = true;
294
295 return self.change(values.address, values);
296 };
297
298 self.unused_color = function unused_color() {
299 const len = mod.colors.length;
300 for (let i = 0; i < len; i++) {
301 if (!color_in_use(mod.colors[i]))
302 return mod.colors[i];
303 }
304 return "gray";
305 };
306
307 function color_in_use(color) {
308 const norm = mod.colors.parse(color);
309 for (const key in machines) {
310 const machine = machines[key];
311 if (machine.color && mod.colors.parse(machine.color) == norm)
312 return true;
313 }
314 return false;
315 }
316
317 function merge(item, values) {
318 for (const prop in values) {
319 if (values[prop] === null)
320 delete item[prop];
321 else
322 item[prop] = values[prop];
323 }
324 }
325
326 self.change = function change(host, values) {
327 const machine = self.lookup(host);
328
329 if (machine && !machine.on_disk)
330 return update_session_machine(machine, host, values);
331 else
332 return update_saved_machine(host, values);
333 };
334
335 self.data = function data(content) {
336 const changes = {};
337
338 for (const host in content) {
339 changes[host] = { ...last.overlay[host] };
340 merge(changes[host], { on_disk: true });
341 }
342
343 /* It's a full reload, so data not
344 * present is no longer from disk
345 */
346 for (const host in machines) {
347 if (content && !content[host]) {
348 changes[host] = { ...last.overlay[host] };
349 merge(changes[host], { on_disk: null });
350 }
351 }
352
353 refresh({
354 content,
355 overlay: { ...last.overlay, ...changes },
356 }, true);
357 };
358
359 self.overlay = function overlay(host, values) {
360 const address = split_connection_string(host).address;
361 const changes = { };
362 changes[address] = { ...last.overlay[address] };
363 merge(changes[address], values);
364 refresh({
365 content: last.content,
366 overlay: { ...last.overlay, ...changes }
367 }, true);
368 };
369
370 Object.defineProperty(self, "list", {
371 enumerable: true,
372 get: function get() {
373 if (!flat) {
374 flat = [];
375 for (const key in machines) {
376 if (machines[key].visible)
377 flat.push(machines[key]);
378 }
379 flat.sort(function(m1, m2) {
380 return m1.label.localeCompare(m2.label);
381 });
382 }
383 return flat;
384 }
385 });
386
387 Object.defineProperty(self, "addresses", {
388 enumerable: true,
389 get: function get() {
390 return Object.keys(machines);
391 }
392 });
393
394 self.lookup = function lookup(address) {
395 const parts = split_connection_string(address);
396 return machines[parts.address || "localhost"] || null;
397 };
398
399 self.close = function close() {
400 window.removeEventListener("storage", storage);
401 };
402 }
403
404 function Loader(machines, session_only) {
405 const self = this;
406
407 /* Have we loaded from cockpit session */
408 let session_loaded = false;
409
410 /* echo channels to each machine */
411 const channels = { };
412 const channels_listeners_message = { };
413 const channels_listeners_close = { };
414
415 /* hostnamed proxies to each machine, if hostnamed available */
416 const proxies = { };
417 const proxies_listeners_changed = { };
418
419 /* clients for the bridge D-Bus API */
420 const bridge_dbus = { };
421
422 function process_session_key(key, value) {
423 const parts = key.split("/");
424 if (parts[0] == session_prefix &&
425 parts.length === 2) {
426 const host = parts[1];
427 if (value) {
428 const values = JSON.parse(value);
429 const machine = machines.lookup(host);
430 if (!machine || !machine.on_disk)
431 machines.overlay(host, values);
432 else if (!machine.visible)
433 machines.change(host, { visible: true });
434 self.connect(host);
435 }
436 }
437 }
438
439 function load_from_session_storage() {
440 session_loaded = true;
441 for (let i = 0; i < window.sessionStorage.length; i++) {
442 const k = window.sessionStorage.key(i);
443 process_session_key(k, window.sessionStorage.getItem(k));
444 }
445 }
446
447 function process_session_machines(ev) {
448 if (ev.storageArea === window.sessionStorage)
449 process_session_key(ev.key || "", ev.newValue);
450 }
451 window.addEventListener("storage", process_session_machines);
452
453 function state(host, value, problem) {
454 const values = { state: value, problem };
455 if (value == "connected") {
456 values.restarting = false;
457 } else if (problem) {
458 values.manifests = null;
459 values.checksum = null;
460 if (problem == "authentication-failed" || problem == "authentication-not-supported")
461 values.restarting = false;
462 }
463 machines.overlay(host, values);
464 }
465
466 machines.addEventListener("added", updated);
467 machines.addEventListener("updated", updated);
468 machines.addEventListener("removed", removed);
469
470 function updated(ev, machine, host, old_conns) {
471 if (!machine) {
472 machine = machines.lookup(host);
473 if (!machine)
474 return;
475 }
476
477 let props = proxies[host];
478 if (!props || !props.valid)
479 props = { };
480
481 const overlay = { };
482
483 if (!machine.color)
484 overlay.color = machines.unused_color();
485
486 const label = props.PrettyHostname || props.StaticHostname || props.Hostname;
487 if (label && label !== machine.label)
488 overlay.label = label;
489
490 const os = props.OperatingSystemPrettyName;
491 if (os && os != machine.os)
492 overlay.os = props.OperatingSystemPrettyName;
493
494 if (Object.keys(overlay).length > 0)
495 machines.overlay(host, overlay);
496
497 /* Don't automatically reconnect failed machines, and don't
498 * automatically connect to new machines. The navigation will
499 * explicitly connect as necessary.
500 */
501 if (machine.visible) {
502 if (old_conns && machine.connection_string != old_conns) {
503 cockpit.kill(old_conns);
504 self.disconnect(host);
505 self.connect(host);
506 }
507 } else {
508 self.disconnect(host);
509 }
510 }
511
512 function removed(ev, machine, host) {
513 self.disconnect(host);
514 }
515
516 self.connect = function connect(host) {
517 const machine = machines.lookup(host);
518 if (!machine)
519 return;
520
521 let channel = channels[host];
522 if (channel)
523 return;
524
525 const options = {
526 host: machine.connection_string,
527 payload: "echo",
528 };
529
530 options["init-superuser"] = get_init_superuser_for_options(options);
531
532 if (!machine.on_disk && machine.host_key) {
533 options['temp-session'] = false; /* Compatibility option */
534 options.session = 'shared';
535 options['host-key'] = machine.host_key;
536 }
537
538 channel = cockpit.channel(options);
539 channels[host] = channel;
540
541 const local = host === "localhost";
542
543 /* Request is null, and message is true when connected */
544 let request = null;
545 let open = local;
546
547 let url;
548 if (!machine.manifests) {
549 if (machine.checksum)
550 url = "../../" + machine.checksum + "/manifests.json";
551 else
552 url = "../../@" + encodeURI(machine.connection_string) + "/manifests.json";
553 }
554
555 function whirl() {
556 if (!request && open)
557 state(host, "connected", null);
558 else
559 state(host, "connecting", null);
560 }
561
562 /* Here we load the machine manifests, and expect them before going to "connected" */
563 function request_manifest() {
564 request = new XMLHttpRequest();
565 request.responseType = "json";
566 request.open("GET", url, true);
567 request.addEventListener("load", () => {
568 const overlay = { manifests: import_manifests(request.response) };
569 const etag = request.getResponseHeader("ETag");
570 if (etag) /* and remove quotes */
571 overlay.checksum = etag.replace(/^"(.+)"$/, '$1');
572 machines.overlay(host, overlay);
573
574 request = null;
575 whirl();
576 });
577 request.addEventListener("error", () => {
578 console.warn("failed to load manifests from " + machine.connection_string);
579 request = null;
580 whirl();
581 });
582 request.send();
583 }
584
585 /* Try to get change notifications via the internal
586 /packages D-Bus interface of the bridge. Not all
587 bridges support this API, so we still get the first
588 version of the manifests via HTTP in request_manifest.
589 */
590
591 function watch_manifests() {
592 const dbus = cockpit.dbus(null, {
593 bus: "internal",
594 host: machine.connection_string
595 });
596 bridge_dbus[host] = dbus;
597 dbus.subscribe({
598 path: "/packages",
599 interface: "org.freedesktop.DBus.Properties",
600 member: "PropertiesChanged"
601 },
602 function (path, iface, member, args) {
603 if (args[0] == "cockpit.Packages") {
604 if (args[1].Manifests) {
605 const manifests = JSON.parse(args[1].Manifests.v);
606 machines.overlay(host, { manifests: import_manifests(manifests) });
607 }
608 }
609 });
610
611 /* Tell the bridge to reload the packages, but only if
612 it hasn't just started. Thus, nothing happens on
613 the first login, but if you reload the shell, we
614 will also reload the packages.
615 */
616 dbus.call("/packages", "cockpit.Packages", "ReloadHint", []);
617 }
618
619 function request_hostname() {
620 if (!machine.static_hostname) {
621 const proxy = cockpit.dbus("org.freedesktop.hostname1",
622 { host: machine.connection_string }).proxy();
623 proxies[host] = proxy;
624 proxy.wait(function() {
625 proxies_listeners_changed[host] = () => updated(null, null, host);
626 proxy.addEventListener("changed", proxies_listeners_changed[host]);
627 updated(null, null, host);
628 });
629 }
630 }
631
632 /* Send a message to the server and get back a message once connected */
633 if (!local) {
634 channel.send("x");
635
636 channels_listeners_message[host] = () => {
637 open = true;
638 if (url)
639 request_manifest();
640 watch_manifests();
641 request_hostname();
642 whirl();
643 };
644 channel.addEventListener("message", channels_listeners_message[host]);
645
646 channels_listeners_close[host] = (ev, options) => {
647 const m = machines.lookup(host);
648 open = false;
649 // reset to clean state when removing machine (orderly disconnect), otherwise mark as failed
650 if (!options.problem && m && !m.visible)
651 state(host, null, null);
652 else
653 state(host, "failed", options.problem || "disconnected");
654 if (m && m.restarting) {
655 window.setTimeout(function() {
656 self.connect(host);
657 }, 10000);
658 }
659 self.disconnect(host);
660 };
661 channel.addEventListener("close", channels_listeners_close[host]);
662 } else {
663 if (url)
664 request_manifest();
665 watch_manifests();
666 request_hostname();
667 }
668
669 /* In case already ready, for example when local */
670 whirl();
671 };
672
673 self.disconnect = function disconnect(host) {
674 if (host === "localhost")
675 return;
676
677 const channel = channels[host];
678 delete channels[host];
679 if (channel) {
680 channel.close();
681 channel.removeEventListener("message", channels_listeners_message[host]);
682 channel.removeEventListener("close", channels_listeners_close[host]);
683 }
684
685 const proxy = proxies[host];
686 delete proxies[host];
687 if (proxy) {
688 proxy.client.close();
689 proxy.removeEventListener("changed", proxies_listeners_changed[host]);
690 }
691
692 const dbus = bridge_dbus[host];
693 delete bridge_dbus[host];
694 if (dbus) {
695 dbus.close();
696 }
697 };
698
699 self.expect_restart = function expect_restart(host) {
700 const parts = split_connection_string(host);
701 machines.overlay(parts.address, {
702 restarting: true,
703 problem: null
704 });
705 };
706
707 self.close = function close() {
708 machines.removeEventListener("added", updated);
709 machines.removeEventListener("changed", updated);
710 machines.removeEventListener("removed", removed);
711 machines = null;
712
713 window.removeEventListener("storage", process_session_machines);
714 const hosts = Object.keys(channels);
715 hosts.forEach(self.disconnect);
716 };
717
718 if (!session_only) {
719 const proxy = cockpit.dbus(null, { bus: "internal" }).proxy("cockpit.Machines", "/machines");
720 proxy.addEventListener("changed", data => {
721 // unwrap variants from D-Bus call
722 const wrapped = proxy.Machines;
723 cockpit.assert(typeof wrapped === "object" && wrapped !== null, "unexpected type of Machines property");
724 const data_unwrap = {};
725 for (const host in wrapped) {
726 const host_props = {};
727 for (const prop in wrapped[host])
728 host_props[prop] = wrapped[host][prop].v;
729 data_unwrap[host] = host_props;
730 }
731
732 machines.data(data_unwrap);
733 if (!session_loaded)
734 load_from_session_storage();
735 machines.set_ready();
736 });
737 } else {
738 load_from_session_storage();
739 machines.data({});
740 machines.set_ready();
741 }
742 }
743
744 mod.instance = function instance(loader) {
745 return new Machines();
746 };
747
748 mod.loader = function loader(machines, session_only) {
749 return new Loader(machines, session_only);
750 };
751
752 mod.colors = [
753 "#0099d3",
754 "#67d300",
755 "#d39e00",
756 "#d3007c",
757 "#00d39f",
758 "#00d1d3",
759 "#00618a",
760 "#4c8a00",
761 "#8a6600",
762 "#9b005b",
763 "#008a55",
764 "#008a8a",
765 "#00b9ff",
766 "#7dff00",
767 "#ffbe00",
768 "#ff0096",
769 "#00ffc0",
770 "#00fdff",
771 "#023448",
772 "#264802",
773 "#483602",
774 "#590034",
775 "#024830",
776 "#024848"
777 ];
778
779 mod.colors.parse = function parse_color(input) {
780 const div = document.createElement('div');
781 div.style.color = input;
782 const style = window.getComputedStyle(div, null);
783 return style.getPropertyValue("color") || div.style.color;
784 };
785
786 export const machines = mod;