Debian Codegraph @

pkg/storaged/utils.js

raw
1 /*
2 * Copyright (C) 2015 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 import cockpit from "cockpit";
7
8 import * as service from "service";
9 import * as timeformat from "timeformat";
10
11 const _ = cockpit.gettext;
12 const C_ = cockpit.gettext;
13
14 export const BTRFS_TOOL_MOUNT_PATH = "/run/cockpit/btrfs/";
15
16 /* UTILITIES
17 */
18
19 export function compare_versions(a, b) {
20 function to_ints(str) {
21 return str.split(".").map(function (s) { return s ? parseInt(s, 10) : 0 });
22 }
23
24 const a_ints = to_ints(a);
25 const b_ints = to_ints(b);
26 const len = Math.min(a_ints.length, b_ints.length);
27 let i;
28
29 for (i = 0; i < len; i++) {
30 if (a_ints[i] == b_ints[i])
31 continue;
32 return a_ints[i] - b_ints[i];
33 }
34
35 return a_ints.length - b_ints.length;
36 }
37
38 export function parse_options(options) {
39 if (options)
40 return (options.split(",")
41 .map(function (s) { return s.trim() })
42 .filter(function (s) { return s != "" }));
43 else
44 return [];
45 }
46
47 export function unparse_options(split) {
48 return split.join(",");
49 }
50
51 export function extract_option(split, opt) {
52 const index = split.indexOf(opt);
53 if (index >= 0) {
54 split.splice(index, 1);
55 return true;
56 } else {
57 return false;
58 }
59 }
60
61 export function edit_crypto_config(block, modify) {
62 let old_config;
63 let new_config;
64
65 function commit() {
66 new_config[1]["track-parents"] = { t: 'b', v: true };
67 if (old_config)
68 return block.UpdateConfigurationItem(old_config, new_config, { });
69 else
70 return block.AddConfigurationItem(new_config, { });
71 }
72
73 return block.GetSecretConfiguration({}).then(
74 function (items) {
75 old_config = items.find(c => c[0] == "crypttab");
76 new_config = ["crypttab", old_config ? Object.assign({ }, old_config[1]) : { }];
77
78 // UDisks insists on always having a "passphrase-contents" field when
79 // adding a crypttab entry, but doesn't include one itself when returning
80 // an entry without a stored passphrase.
81 //
82 if (!new_config[1]['passphrase-contents'])
83 new_config[1]['passphrase-contents'] = { t: 'ay', v: encode_filename("") };
84
85 return modify(new_config[1], commit);
86 });
87 }
88
89 export function set_crypto_options(block, readonly, auto, nofail, netdev) {
90 return edit_crypto_config(block, (config, commit) => {
91 const opts = config.options ? parse_options(decode_filename(config.options.v)) : [];
92 if (readonly !== null) {
93 extract_option(opts, "readonly");
94 extract_option(opts, "read-only");
95 if (readonly)
96 opts.push("readonly");
97 }
98 if (auto !== null) {
99 extract_option(opts, "noauto");
100 if (!auto)
101 opts.push("noauto");
102 }
103 if (nofail !== null) {
104 extract_option(opts, "nofail");
105 if (nofail)
106 opts.push("nofail");
107 }
108 if (netdev !== null) {
109 extract_option(opts, "_netdev");
110 if (netdev)
111 opts.push("_netdev");
112 }
113 config.options = { t: 'ay', v: encode_filename(unparse_options(opts)) };
114 return commit();
115 });
116 }
117
118 export function set_crypto_auto_option(block, flag) {
119 return set_crypto_options(block, null, flag, null, null);
120 }
121
122 export let hostnamed = cockpit.dbus("org.freedesktop.hostname1").proxy();
123
124 // for unit tests
125 let orig_hostnamed;
126
127 export function mock_hostnamed(value) {
128 if (value) {
129 orig_hostnamed = hostnamed;
130 hostnamed = value;
131 } else {
132 hostnamed = orig_hostnamed;
133 }
134 }
135
136 export function flatten(array_of_arrays) {
137 if (array_of_arrays.length > 0)
138 return Array.prototype.concat.apply([], array_of_arrays);
139 else
140 return [];
141 }
142
143 export const decode_filename = encoded => window.atob(encoded).replace('\u0000', '');
144 export const encode_filename = decoded => window.btoa(decoded + '\u0000');
145
146 export function get_block_mntopts(config) {
147 // treat an absent field as "default", like util-linux
148 return (config.opts ? decode_filename(config.opts.v) : "defaults");
149 }
150
151 export function fmt_size(bytes) {
152 return cockpit.format_bytes(bytes);
153 }
154
155 export function fmt_size_long(bytes) {
156 const with_decimal_unit = cockpit.format_bytes(bytes);
157 const with_binary_unit = cockpit.format_bytes(bytes, { base2: true });
158 /* Translators: Used in "..." */
159 return with_decimal_unit + ", " + with_binary_unit + ", " + bytes + " " + C_("format-bytes", "bytes");
160 }
161
162 export function fmt_rate(bytes_per_sec) {
163 return cockpit.format_bytes_per_sec(bytes_per_sec);
164 }
165
166 export function format_temperature(kelvin) {
167 const celsius = kelvin - 273.15;
168 const fahrenheit = 9.0 * celsius / 5.0 + 32.0;
169 return celsius.toFixed(1) + "° C / " + fahrenheit.toFixed(1) + "° F";
170 }
171
172 export function format_fsys_usage(used, total) {
173 let text = "";
174 let parts = cockpit.format_bytes(total, { separate: true, precision: 2 });
175 text = " / " + parts.join(" ");
176 const unit = parts[1];
177
178 // FIXME: passing explicit unit is deprecated, redesign this
179 parts = cockpit.format_bytes(used, unit, { separate: true, precision: 2 });
180 return parts[0] + text;
181 }
182
183 export function format_delay(d) {
184 return timeformat.distanceToNow(new Date().valueOf() + d);
185 }
186
187 export function format_size_and_text(size, text) {
188 return fmt_size(size) + " " + text;
189 }
190
191 export function validate_mdraid_name(name) {
192 return validate_lvm2_name(name);
193 }
194
195 export function validate_lvm2_name(name) {
196 if (name === "")
197 return _("Name cannot be empty.");
198 if (name.length > 127)
199 return _("Name cannot be longer than 127 characters.");
200 const m = name.match(/[^a-zA-Z0-9+._-]/);
201 if (m) {
202 if (m[0].search(/\s+/) === -1)
203 return cockpit.format(_("Name cannot contain the character '$0'."), m[0]);
204 else
205 return cockpit.format(_("Name cannot contain whitespace."), m[0]);
206 }
207 }
208
209 export function validate_fsys_label(label, type) {
210 const fs_label_max = {
211 xfs: 12,
212 ext4: 16,
213 vfat: 11,
214 ntfs: 128,
215 btrfs: 256,
216 };
217
218 const limit = fs_label_max[type.replace("luks+", "")];
219 const bytes = new TextEncoder().encode(label);
220 if (limit && bytes.length > limit) {
221 // Let's not confuse people with encoding issues unless
222 // they use funny characters.
223 if (bytes.length == label.length)
224 return cockpit.format(_("Name cannot be longer than $0 characters"), limit);
225 else
226 return cockpit.format(_("Name cannot be longer than $0 bytes"), limit);
227 }
228 }
229
230 export function block_name(block) {
231 return decode_filename(block.PreferredDevice);
232 }
233
234 export function block_short_name(block) {
235 return block_name(block).replace(/^\/dev\//, "");
236 }
237
238 export function mdraid_name(mdraid) {
239 if (!mdraid.Name)
240 return "";
241
242 const parts = mdraid.Name.split(":");
243
244 if (parts.length != 2)
245 return mdraid.Name;
246
247 /* Check the static (from /etc/hostname) and transient (acquired from DHCP server via
248 * NetworkManager → hostnamed, may not exist) host name -- if either one matches, we
249 * consider the RAID a local one and just show the device name.
250 * Otherwise it's a remote one, and include the host in the name.
251 *
252 * However: if we call hostnamed too early, before the dbus.proxy() promise is
253 * fulfilled, it will not be valid yet (hostnamed properties are undefined);
254 * it's too inconvenient to make this function asynchronous, so just don't
255 * show the host name in this case. */
256 if (hostnamed.StaticHostname === undefined || parts[0] == hostnamed.StaticHostname || parts[0] == hostnamed.Hostname)
257 return parts[1];
258 else
259 return cockpit.format(_("$name (from $host)"),
260 {
261 name: parts[1],
262 host: parts[0]
263 });
264 }
265
266 export function lvol_name(lvol) {
267 let type;
268 if (lvol.Type == "pool")
269 type = _("Pool for thin logical volumes");
270 else if (lvol.ThinPool != "/")
271 type = _("Thin logical volume");
272 else if (lvol.Origin != "/")
273 type = _("Logical volume (snapshot)");
274 else
275 type = _("Logical volume");
276 return cockpit.format('$0 "$1"', type, lvol.Name);
277 }
278
279 export function drive_name(drive) {
280 const name_parts = [];
281 if (drive.Vendor)
282 name_parts.push(drive.Vendor);
283 if (drive.Model)
284 name_parts.push(drive.Model);
285
286 let name = name_parts.join(" ");
287 if (drive.Serial)
288 name += " (" + drive.Serial + ")";
289 else if (drive.WWN)
290 name += " (" + drive.WWN + ")";
291
292 return name;
293 }
294
295 export function get_block_link_parts(client, path) {
296 let is_part;
297 let is_crypt;
298 let is_lvol;
299
300 while (true) {
301 if (client.blocks_part[path] && client.blocks_ptable[client.blocks_part[path].Table]) {
302 is_part = true;
303 path = client.blocks_part[path].Table;
304 } else if (client.blocks[path] && client.blocks[client.blocks[path].CryptoBackingDevice]) {
305 is_crypt = true;
306 path = client.blocks[path].CryptoBackingDevice;
307 } else
308 break;
309 }
310
311 if (client.blocks_lvm2[path] && client.lvols[client.blocks_lvm2[path].LogicalVolume])
312 is_lvol = true;
313
314 const block = client.blocks[path];
315 if (!block)
316 return;
317
318 let location;
319 let link;
320 if (client.mdraids[block.MDRaid]) {
321 location = ["mdraid", client.mdraids[block.MDRaid].UUID];
322 link = cockpit.format(_("MDRAID device $0"), mdraid_name(client.mdraids[block.MDRaid]));
323 } else if (client.blocks_lvm2[path] &&
324 client.lvols[client.blocks_lvm2[path].LogicalVolume] &&
325 client.vgroups[client.lvols[client.blocks_lvm2[path].LogicalVolume].VolumeGroup]) {
326 const target = client.vgroups[client.lvols[client.blocks_lvm2[path].LogicalVolume].VolumeGroup].Name;
327 location = ["vg", target];
328 link = cockpit.format(_("LVM2 volume group $0"), target);
329 } else {
330 const vdo = client.legacy_vdo_overlay.find_by_block(block);
331 if (vdo) {
332 location = ["vdo", vdo.name];
333 link = cockpit.format(_("VDO device $0"), vdo.name);
334 } else {
335 location = [block_short_name(block)];
336 if (client.drives[block.Drive])
337 link = drive_name(client.drives[block.Drive]);
338 else
339 link = block_name(block);
340 }
341 }
342
343 // Partitions of logical volumes are shown as just logical volumes.
344 let format;
345 if (is_lvol && is_crypt)
346 format = _("Encrypted logical volume of $0");
347 else if (is_part && is_crypt)
348 format = _("Encrypted partition of $0");
349 else if (is_lvol)
350 format = _("Logical volume of $0");
351 else if (is_part)
352 format = _("Partition of $0");
353 else if (is_crypt)
354 format = _("Encrypted $0");
355 else
356 format = "$0";
357
358 return {
359 location,
360 format,
361 link
362 };
363 }
364
365 export function go_to_block(client, path) {
366 const parts = get_block_link_parts(client, path);
367 cockpit.location.go(parts.location);
368 }
369
370 export function get_partitions(client, block) {
371 const partitions = client.blocks_partitions[block.path];
372
373 function process_level(level, container_start, container_size) {
374 let n;
375 let last_end = container_start;
376 const total_end = container_start + container_size;
377 let block;
378 let start;
379 let size;
380 let is_container;
381 let is_contained;
382
383 const result = [];
384
385 function append_free_space(start, size) {
386 // There is a lot of rounding and aligning going on in
387 // the storage stack. All of udisks2, libblockdev,
388 // and libparted seem to contribute their own ideas of
389 // where a partition really should start.
390 //
391 // The start of partitions are aggressively rounded
392 // up, sometimes twice, but the end is not aligned in
393 // the same way. This means that a few megabytes of
394 // free space will show up between partitions.
395 //
396 // We hide these small free spaces because they are
397 // unexpected and can't be used for anything anyway.
398 //
399 // "Small" is anything less than 3 MiB, which seems to
400 // work okay. (The worst case is probably creating
401 // the first logical partition inside a extended
402 // partition with udisks+libblockdev. It leads to a 2
403 // MiB gap.)
404
405 if (size >= 3 * 1024 * 1024) {
406 result.push({ type: 'free', start, size });
407 }
408 }
409
410 for (n = 0; n < partitions.length; n++) {
411 block = client.blocks[partitions[n].path];
412 start = partitions[n].Offset;
413 size = partitions[n].Size;
414 is_container = partitions[n].IsContainer;
415 is_contained = partitions[n].IsContained;
416
417 if (block === null)
418 continue;
419
420 if (level === 0 && is_contained)
421 continue;
422
423 if (level == 1 && !is_contained)
424 continue;
425
426 if (start < container_start || start + size > container_start + container_size)
427 continue;
428
429 append_free_space(last_end, start - last_end);
430 if (is_container) {
431 result.push({
432 type: 'container',
433 block,
434 size,
435 partitions: process_level(level + 1, start, size)
436 });
437 } else {
438 result.push({ type: 'block', block });
439 }
440 last_end = start + size;
441 }
442
443 append_free_space(last_end, total_end - last_end);
444
445 return result;
446 }
447
448 return process_level(0, 0, block.Size);
449 }
450
451 let available_spaces = [];
452
453 export function get_available_spaces() {
454 return available_spaces.sort((a, b) => block_cmp(a.block, b.block));
455 }
456
457 export function reset_available_spaces() {
458 available_spaces = [];
459 }
460
461 export function register_available_block_space(client, block) {
462 const parts = get_block_link_parts(client, block.path);
463 const text = cockpit.format(parts.format, parts.link);
464 available_spaces.push({ type: 'block', block, size: block.Size, desc: text });
465 }
466
467 export function register_available_free_space(client, block, partition) {
468 const link_parts = get_block_link_parts(client, block.path);
469 const text = cockpit.format(link_parts.format, link_parts.link);
470 available_spaces.push({
471 type: 'free',
472 block,
473 start: partition.start,
474 size: partition.size,
475 desc: cockpit.format(_("unpartitioned space on $0"), text)
476 });
477 }
478
479 export function prepare_available_spaces(client, spcs) {
480 function prepare(spc) {
481 if (spc.type == 'block')
482 return Promise.resolve(spc.block.path);
483 else if (spc.type == 'free') {
484 const block_ptable = client.blocks_ptable[spc.block.path];
485 return block_ptable.CreatePartition(spc.start, spc.size, "", "", { });
486 }
487 }
488
489 return Promise.all(spcs.map(prepare));
490 }
491
492 export function is_snap(client, block) {
493 const block_fsys = client.blocks_fsys[block.path];
494 return block_fsys && block_fsys.MountPoints.map(decode_filename).some(mp => mp.indexOf("/snap/") == 0 || mp.indexOf("/var/lib/snapd/snap/") == 0);
495 }
496
497 export function get_other_devices(client) {
498 return Object.keys(client.blocks).filter(path => {
499 const block = client.blocks[path];
500 const block_part = client.blocks_part[path];
501 const block_lvm2 = client.blocks_lvm2[path];
502
503 return ((!block_part || block_part.Table == "/") &&
504 block.Drive == "/" &&
505 block.CryptoBackingDevice == "/" &&
506 block.MDRaid == "/" &&
507 (!block_lvm2 || block_lvm2.LogicalVolume == "/") &&
508 !block.HintIgnore &&
509 block.Size > 0 &&
510 !client.legacy_vdo_overlay.find_by_block(block) &&
511 !client.blocks_stratis_fsys[block.path] &&
512 !is_snap(client, block) &&
513 !should_ignore(client, block.path));
514 });
515 }
516
517 /* Comparison function for sorting lists of block devices.
518
519 We sort by major:minor numbers to get the expected order when
520 there are more than 10 devices of a kind. For example, if you
521 have 20 loopback devices named loop0 to loop19, sorting them
522 alphabetically would put them in the wrong order
523
524 loop0, loop1, loop10, loop11, ..., loop2, ...
525
526 Sorting by major:minor is an easy way to do the right thing.
527 */
528
529 export function block_cmp(a, b) {
530 return a.DeviceNumber - b.DeviceNumber;
531 }
532
533 export function make_block_path_cmp(client) {
534 return function(path_a, path_b) {
535 return block_cmp(client.blocks[path_a], client.blocks[path_b]);
536 };
537 }
538
539 let multipathd_service;
540
541 export function get_multipathd_service () {
542 if (!multipathd_service)
543 multipathd_service = service.proxy("multipathd");
544 return multipathd_service;
545 }
546
547 function get_parent(client, path) {
548 if (client.blocks_part[path] && client.blocks[client.blocks_part[path].Table])
549 return client.blocks_part[path].Table;
550 if (client.blocks[path] && client.blocks[client.blocks[path].CryptoBackingDevice])
551 return client.blocks[path].CryptoBackingDevice;
552 if (client.blocks[path] && client.drives[client.blocks[path].Drive])
553 return client.blocks[path].Drive;
554 if (client.blocks[path] && client.mdraids[client.blocks[path].MDRaid])
555 return client.blocks[path].MDRaid;
556 if (client.blocks_lvm2[path] && client.lvols[client.blocks_lvm2[path].LogicalVolume])
557 return client.blocks_lvm2[path].LogicalVolume;
558 if (client.lvols[path] && client.vgroups[client.lvols[path].VolumeGroup])
559 return client.lvols[path].VolumeGroup;
560 if (client.blocks_stratis_fsys[path])
561 return client.blocks_stratis_fsys[path].Pool;
562 if (client.vgroups[path])
563 return path;
564 if (client.stratis_pools[path])
565 return path;
566 }
567
568 function get_direct_parent_blocks(client, path) {
569 if (client.blocks[path])
570 path = get_parent(client, path);
571 if (!path)
572 return [];
573 if (client.blocks[path])
574 return [path];
575 if (client.mdraids[path])
576 return client.mdraids_members[path].map(function (m) { return m.path });
577 if (client.lvols[path])
578 path = client.lvols[path].VolumeGroup;
579 if (client.vgroups[path])
580 return client.vgroups_pvols[path].map(function (pv) { return pv.path });
581 if (client.stratis_pools[path])
582 return client.stratis_pool_blockdevs[path].map(bd => client.slashdevs_block[bd.Devnode].path);
583 return [];
584 }
585
586 export function get_parent_blocks(client, path) {
587 const direct_parents = get_direct_parent_blocks(client, path);
588 const direct_and_indirect_parents = flatten(direct_parents.map(function (p) {
589 return get_parent_blocks(client, p);
590 }));
591 return [path].concat(direct_and_indirect_parents);
592 }
593
594 export function is_netdev(client, path) {
595 const block = client.blocks[path];
596 const drive = block && client.drives[block.Drive];
597 if (drive && drive.Vendor == "LIO-ORG")
598 return true;
599 if (block && block.Major == 43) // NBD
600 return true;
601 return false;
602 }
603
604 export function should_ignore(client, path) {
605 const block = client.blocks[path];
606
607 // HACK - https://github.com/stratis-storage/stratisd/issues/3801
608 //
609 // Filter out Stratis private device mapper devices. This normally
610 // happens by setting the DM_UDEV_DISABLE_OTHER_RULES_FLAG in the
611 // udev database (which causes UDisks2 to ignore the block
612 // device), but since Stratis 3.8 the "*-crypt" devices don't have
613 // them.
614
615 if (block && decode_filename(block.PreferredDevice).startsWith("/dev/mapper/stratis-1-private"))
616 return true;
617
618 // Check what Anaconda tells us.
619
620 if (!client.in_anaconda_mode())
621 return false;
622
623 const parents = get_direct_parent_blocks(client, path);
624 if (parents.length == 0) {
625 return block && client.should_ignore_block(block);
626 } else {
627 return parents.some(p => should_ignore(client, p));
628 }
629 }
630
631 /* GET_CHILDREN gets the direct children of the storage object at
632 PATH, like the partitions of a partitioned block device, or the
633 volume group of a physical volume. By calling GET_CHILDREN
634 recursively, you can traverse the whole storage hierarchy from
635 hardware drives at the bottom to filesystems at the top.
636
637 GET_CHILDREN_FOR_TEARDOWN is similar but doesn't consider things
638 like volume groups to be children of their physical volumes. This
639 is appropriate for teardown processing, where tearing down a
640 physical volume does not imply tearing down the whole volume group
641 with everything that it contains.
642 */
643
644 function get_children_for_teardown(client, path) {
645 const children = [];
646
647 if (client.blocks_cleartext[path]) {
648 children.push(client.blocks_cleartext[path].path);
649 }
650
651 if (client.blocks_ptable[path]) {
652 client.blocks_partitions[path].forEach(function (part) {
653 if (!part.IsContainer)
654 children.push(part.path);
655 });
656 }
657
658 if (client.blocks_part[path] && client.blocks_part[path].IsContainer) {
659 const ptable_path = client.blocks_part[path].Table;
660 client.blocks_partitions[ptable_path].forEach(function (part) {
661 if (part.IsContained)
662 children.push(part.path);
663 });
664 }
665
666 if (client.vgroups[path]) {
667 client.vgroups_lvols[path].forEach(function (lvol) {
668 if (client.lvols_block[lvol.path])
669 children.push(client.lvols_block[lvol.path].path);
670 });
671 }
672
673 if (client.lvols_pool_members[path]) {
674 for (const lvol of client.lvols_pool_members[path]) {
675 const block = client.lvols_block[lvol.path];
676 if (block)
677 children.push(block.path);
678 }
679 }
680
681 if (client.stratis_pools[path]) {
682 client.stratis_pool_filesystems[path].forEach(function (fsys) {
683 const block = client.slashdevs_block[fsys.Devnode];
684 if (block)
685 children.push(block.path);
686 });
687 }
688
689 return children;
690 }
691
692 export function get_children(client, path) {
693 const children = get_children_for_teardown(client, path);
694
695 if (client.blocks[path]) {
696 const mdraid = client.blocks[path].MDRaidMember;
697 if (mdraid != "/")
698 children.push(mdraid);
699 }
700
701 if (client.blocks_pvol[path]) {
702 const vgroup = client.blocks_pvol[path].VolumeGroup;
703 if (vgroup != "/")
704 children.push(vgroup);
705 }
706
707 if (client.blocks_stratis_blockdev[path]) {
708 const pool = client.blocks_stratis_blockdev[path].Pool;
709 if (pool != "/")
710 children.push(pool);
711 }
712
713 return children;
714 }
715
716 /**
717 * True if `active_mount` refers to a path strictly below `parent_mount`.
718 *
719 * Examples: `/home` is below `/`; `/srv/jail` is below `/srv`. `/etc` is not below `/srv`.
720 *
721 * Root is special: the only character shared by `/` and `/home` is the leading slash, so we
722 * cannot require a "/" immediately after the parent string (that would look at `h` in `/home`).
723 */
724 function is_strict_descendant_mount_path(parent_mount, active_mount) {
725 if (active_mount.length <= parent_mount.length)
726 return false;
727 if (!active_mount.startsWith(parent_mount))
728 return false;
729 if (parent_mount === "/")
730 return true;
731 return active_mount[parent_mount.length] === "/";
732 }
733
734 export function find_children_for_mount_point(client, mount_point, self, self_subvol) {
735 const children = {};
736
737 function is_self(b) {
738 return self && (b == self || client.blocks[b.CryptoBackingDevice] == self);
739 }
740
741 for (const p in client.blocks) {
742 const b = client.blocks[p];
743 const fs = client.blocks_fsys[p];
744
745 if (!fs)
746 continue;
747
748 // Skip self block except btrfs (subvolumes share one block); then ignore only this subvol's mounts.
749 if (is_self(b) && !client.blocks_fsys_btrfs[self.path])
750 continue;
751
752 const skip = is_self(b) && self_subvol ? get_mount_points(client, fs, self_subvol) : [];
753
754 for (const mp of fs.MountPoints) {
755 const active = decode_filename(mp);
756 if (skip.includes(active))
757 continue;
758 if (is_strict_descendant_mount_path(mount_point, active))
759 children[active] = b;
760 }
761 }
762
763 return children;
764 }
765
766 export function get_fstab_config_with_client(client, block, also_child_config, subvol) {
767 function match(c) {
768 if (c[0] != "fstab")
769 return false;
770 if (subvol !== undefined) {
771 if (!c[1].opts)
772 return false;
773
774 const opts = decode_filename(c[1].opts.v).split(",");
775 if (opts.indexOf("subvolid=" + subvol.id) >= 0)
776 return true;
777 if (opts.indexOf("subvol=" + subvol.pathname) >= 0 || opts.indexOf("subvol=/" + subvol.pathname) >= 0)
778 return true;
779
780 // btrfs mounted without subvol argument.
781 const btrfs_volume = client.blocks_fsys_btrfs[block.path];
782 const default_subvolid = client.uuids_btrfs_default_subvol[btrfs_volume.data.uuid];
783 if (default_subvolid === subvol.id && !opts.find(o => o.indexOf("subvol=") >= 0 || o.indexOf("subvolid=") >= 0))
784 return true;
785
786 return false;
787 }
788 return true;
789 }
790
791 let config = block.Configuration.find(match);
792
793 if (!config && also_child_config && client.blocks_crypto[block.path])
794 config = client.blocks_crypto[block.path]?.ChildConfiguration.find(c => c[0] == "fstab");
795
796 if (config && decode_filename(config[1].type.v) != "swap") {
797 const mnt_opts = get_block_mntopts(config[1]).split(",");
798 let dir = decode_filename(config[1].dir.v);
799 let opts = mnt_opts
800 .filter(function (s) { return s.indexOf("x-parent") !== 0 })
801 .join(",");
802 const parents = mnt_opts
803 .filter(function (s) { return s.indexOf("x-parent") === 0 })
804 .join(",");
805 if (dir[0] != "/")
806 dir = "/" + dir;
807 if (opts == "defaults")
808 opts = "";
809 return [config, dir, opts, parents];
810 } else
811 return [];
812 }
813
814 export function get_active_usage(client, path, top_action, child_action, is_temporary, subvol, allow_multi_device_delete) {
815 function get_usage(usage, path, level) {
816 const block = client.blocks[path];
817 const fsys = client.blocks_fsys[path];
818 const swap = client.blocks_swap[path];
819 const mdraid = block && client.mdraids[block.MDRaidMember];
820 const pvol = client.blocks_pvol[path];
821 const vgroup = pvol && client.vgroups[pvol.VolumeGroup];
822 const vdo = block && client.legacy_vdo_overlay.find_by_backing_block(block);
823 const stratis_blockdev = block && client.blocks_stratis_blockdev[path];
824 const stratis_pool = stratis_blockdev && client.stratis_pools[stratis_blockdev.Pool];
825 const btrfs_volume = client.blocks_fsys_btrfs[path];
826
827 get_children_for_teardown(client, path).map(p => get_usage(usage, p, level + 1));
828
829 function get_actions(teardown_action) {
830 const actions = [];
831 if (teardown_action)
832 actions.push(teardown_action);
833 const global_action = (level == 0 || (block && client.blocks[block.CryptoBackingDevice] && level == 1)) ? top_action : child_action || top_action;
834 if (global_action)
835 actions.push(global_action);
836 return actions;
837 }
838
839 function enter_unmount(block, location, is_top) {
840 const [, mount_point] = get_fstab_config_with_client(client, block);
841 const has_fstab_entry = is_temporary && location == mount_point;
842
843 // Ignore the secret btrfs mount point unless we are
844 // formatting (in which case subvol is false).
845 if (btrfs_volume && subvol && location.startsWith(BTRFS_TOOL_MOUNT_PATH))
846 return;
847
848 for (const u of usage) {
849 if (u.usage == 'mounted' && u.location == location) {
850 if (is_top) {
851 u.actions = get_actions(_("unmount"));
852 u.set_noauto = false;
853 }
854 return;
855 }
856 }
857 usage.push({
858 level,
859 block,
860 usage: 'mounted',
861 location,
862 has_fstab_entry,
863 set_noauto: !is_top && !is_temporary,
864 actions: (is_top ? get_actions(_("unmount")) : [_("unmount")]).concat(has_fstab_entry ? [_("mount")] : []),
865 blocking: client.strip_mount_point_prefix(location) === false && !location.startsWith(BTRFS_TOOL_MOUNT_PATH),
866 });
867 }
868
869 // HACK: get_active_usage is used for mounting and formatting so we use the absence of the subvol argument
870 // to figure out that we want to format this device.
871 // This is separate from the if's below as we also always have to umount the filesystem.
872
873 // We allow a btrfs volume with one device to be formatted as this
874 // looks the most like a normal filesystem use case.
875 if (btrfs_volume && btrfs_volume.data.num_devices !== 1 && !subvol && !allow_multi_device_delete) {
876 usage.push({
877 level,
878 usage: 'btrfs-device',
879 block,
880 btrfs_volume,
881 location: btrfs_volume.data.label || btrfs_volume.data.uuid,
882 actions: get_actions(_("remove from btrfs volume")),
883 blocking: true,
884 });
885 }
886
887 const mount_points = get_mount_points(client, fsys, subvol);
888 if (mount_points.length > 0) {
889 mount_points.forEach(mp => {
890 const children = find_children_for_mount_point(client, mp, null);
891 for (const c in children)
892 enter_unmount(children[c], c, false);
893 enter_unmount(block, mp, true);
894 });
895 } else if (swap) {
896 if (swap.Active) {
897 usage.push({
898 level,
899 usage: 'swap',
900 block,
901 actions: get_actions(_("stop")),
902 });
903 }
904 } else if (mdraid) {
905 const active_state = mdraid.ActiveDevices.find(as => as[0] == block.path);
906 usage.push({
907 level,
908 usage: 'mdraid-member',
909 block,
910 mdraid,
911 location: mdraid_name(mdraid),
912 actions: get_actions(_("remove from MDRAID")),
913 blocking: !(active_state && active_state[1] < 0)
914 });
915 } else if (vgroup) {
916 usage.push({
917 level,
918 usage: 'pvol',
919 block,
920 vgroup,
921 pvol,
922 location: vgroup.Name,
923 actions: get_actions(_("remove from LVM2")),
924 blocking: pvol.FreeSize != pvol.Size
925 });
926 } else if (vdo) {
927 usage.push({
928 level,
929 usage: 'vdo-backing',
930 block,
931 vdo,
932 location: vdo.name,
933 blocking: true
934 });
935 } else if (stratis_pool) {
936 usage.push({
937 level,
938 usage: 'stratis-pool-member',
939 block,
940 stratis_pool,
941 location: stratis_pool.Name,
942 blocking: true
943 });
944 } else if (block && !client.blocks_cleartext[block.path]) {
945 usage.push({
946 level,
947 usage: 'none',
948 block,
949 actions: get_actions(null),
950 blocking: false
951 });
952 }
953
954 return usage;
955 }
956
957 const usage = [];
958 get_usage(usage, path, 0);
959
960 usage.Blocking = usage.some(u => u.blocking);
961 usage.Teardown = usage.some(u => !u.blocking);
962
963 if (usage.length == 1 && usage[0].level == 0 && usage[0].usage == "none")
964 usage.Teardown = false;
965
966 return usage;
967 }
968
969 async function set_fsys_noauto(client, block, mount_point) {
970 for (const conf of block.Configuration) {
971 if (conf[0] == "fstab" &&
972 decode_filename(conf[1].dir.v) == mount_point) {
973 const options = parse_options(get_block_mntopts(conf[1]));
974 if (options.indexOf("noauto") >= 0)
975 continue;
976 options.push("noauto");
977 const new_conf = [
978 "fstab",
979 Object.assign({ }, conf[1],
980 {
981 opts: {
982 t: 'ay',
983 v: encode_filename(unparse_options(options))
984 }
985 })
986 ];
987 await block.UpdateConfigurationItem(conf, new_conf, { });
988 }
989 }
990
991 const crypto_backing = client.blocks[block.CryptoBackingDevice];
992 if (crypto_backing) {
993 const crypto_backing_crypto = client.blocks_crypto[crypto_backing.path];
994 await set_crypto_auto_option(crypto_backing, false);
995 if (crypto_backing_crypto)
996 await crypto_backing_crypto.Lock({});
997 }
998 }
999
1000 export function teardown_active_usage(client, usage) {
1001 // The code below is complicated by the fact that the last
1002 // physical volume of a volume group can not be removed
1003 // directly (even if it is completely empty). We want to
1004 // remove the whole volume group instead in this case.
1005 //
1006 // However, we might be removing the last two (or more)
1007 // physical volumes here, and it is easiest to catch this
1008 // condition upfront by reshuffling the data structures.
1009
1010 async function unmount(mounteds) {
1011 for (const m of mounteds) {
1012 await client.unmount_at(m.location, m.users);
1013 if (m.set_noauto)
1014 await set_fsys_noauto(client, m.block, m.location);
1015 }
1016 }
1017
1018 async function stop_swap(swaps) {
1019 for (const s of swaps) {
1020 await client.blocks_swap[s.block.path].Stop({});
1021 }
1022 }
1023
1024 function mdraid_remove(members) {
1025 return Promise.all(members.map(m => m.mdraid.RemoveDevice(m.block.path, { wipe: { t: 'b', v: true } })));
1026 }
1027
1028 function pvol_remove(pvols) {
1029 const by_vgroup = { };
1030 pvols.forEach(function (p) {
1031 if (!by_vgroup[p.vgroup.path])
1032 by_vgroup[p.vgroup.path] = [];
1033 by_vgroup[p.vgroup.path].push(p.block);
1034 });
1035
1036 function handle_vg(p) {
1037 const vg = client.vgroups[p];
1038 const pvs = by_vgroup[p];
1039 // If we would remove all physical volumes of a volume
1040 // group, remove the whole volume group instead.
1041 if (pvs.length == client.vgroups_pvols[p].length) {
1042 return vg.Delete(true, { 'tear-down': { t: 'b', v: true } }).then(reload_systemd);
1043 } else {
1044 return Promise.all(pvs.map(pv => vg.RemoveDevice(pv.path, true, {})));
1045 }
1046 }
1047
1048 return Promise.all(Object.keys(by_vgroup).map(handle_vg));
1049 }
1050
1051 return Promise.all(Array.prototype.concat(
1052 unmount(usage.filter(function(use) { return use.usage == "mounted" })),
1053 stop_swap(usage.filter(function(use) { return use.usage == "swap" })),
1054 mdraid_remove(usage.filter(function(use) { return use.usage == "mdraid-member" })),
1055 pvol_remove(usage.filter(function(use) { return use.usage == "pvol" }))
1056 ));
1057 }
1058
1059 export async function undo_temporary_teardown(client, usage) {
1060 for (let i = usage.length - 1; i >= 0; i--) {
1061 const u = usage[i];
1062 if (u.usage == "mounted" && u.has_fstab_entry) {
1063 await client.mount_at(u.block, u.location);
1064 }
1065 }
1066 }
1067
1068 // TODO - generalize this to arbitrary number of arguments (when needed)
1069 export function fmt_to_array(fmt, arg) {
1070 const index = fmt.indexOf("$0");
1071 if (index >= 0)
1072 return [fmt.slice(0, index), arg, fmt.slice(index + 2)];
1073 else
1074 return [fmt];
1075 }
1076
1077 export function reload_systemd() {
1078 return cockpit.spawn(["systemctl", "daemon-reload"], { superuser: "require", err: "message" });
1079 }
1080
1081 export function is_mounted_synch(block) {
1082 return (cockpit.spawn(["findmnt", "-n", "-o", "TARGET", "-S", decode_filename(block.Device)],
1083 { superuser: "require", err: "message" })
1084 .then(data => data.trim())
1085 .catch(() => false));
1086 }
1087
1088 export function for_each_async(arr, func) {
1089 return arr.reduce((promise, elt) => promise.then(() => func(elt)), Promise.resolve());
1090 }
1091
1092 /*
1093 * Get mount points for a given org.freedesktop.UDisks2.Filesystem object
1094 *
1095 * This generalises getting the given MountPoints of a Filesystem for btrfs and
1096 * other filesystems, for btrfs we want to know if a subvolume is mounted
1097 * anywhere. UDisks is currently not aware of subvolumes and it's Filesystem
1098 * object gives us the MountPoints for all subvolumes while we want it per
1099 * subvolume.
1100 *
1101 * @param {Object} block_fsys
1102 * @param {Object|null} subvol
1103 * @returns {Array} an array of MountPoints
1104 */
1105 export function get_mount_points(client, block_fsys, subvol) {
1106 let mounted_at = [];
1107
1108 if (subvol && block_fsys) {
1109 const btrfs_volume = client.blocks_fsys_btrfs[block_fsys.path];
1110 const volume_mounts = client.btrfs_mounts[btrfs_volume.data.uuid];
1111 if (volume_mounts)
1112 mounted_at = subvol.id in volume_mounts ? volume_mounts[subvol.id].mount_points : [];
1113 } else {
1114 mounted_at = block_fsys ? block_fsys.MountPoints.map(decode_filename) : [];
1115 }
1116
1117 return mounted_at;
1118 }
1119
1120 export function get_byte_units(guide_value) {
1121 const units = [
1122 { factor: 1000 ** 2, name: "MB" },
1123 { factor: 1000 ** 3, name: "GB" },
1124 { factor: 1000 ** 4, name: "TB" },
1125 ];
1126 // Find the biggest unit which gives two digits left of the decimal point (>= 10)
1127 let unit;
1128 for (unit = units.length - 1; unit >= 0; unit--)
1129 if (guide_value / units[unit].factor >= 10)
1130 break;
1131 // Mark it selected. If we couldn't find one (-1), then use MB.
1132 units[Math.max(0, unit)].selected = true;
1133 return units;
1134 }
1135
1136 /** @type (client: any, path: string) => boolean */
1137 export function contains_rootfs(client, path) {
1138 const block = client.blocks[path];
1139 const crypto = client.blocks_crypto[path];
1140 let fsys_config = null;
1141
1142 if (block)
1143 fsys_config = block.Configuration.find(c => c[0] == "fstab");
1144 if (!fsys_config && crypto)
1145 fsys_config = crypto.ChildConfiguration.find(c => c[0] == "fstab");
1146
1147 if (fsys_config) {
1148 const dir = decode_filename(fsys_config[1].dir.v);
1149 return dir == "/";
1150 }
1151
1152 return get_children(client, path).some(p => contains_rootfs(client, p));
1153 }