blib/lib/App/FuguVM/CLI.pm untested

filter: Statementstmt 0.0% 0 / 562 Branchbran 0.0% 0 / 270 Conditioncond 0.0% 0 / 159 MC/DCmcdc 0.0% 0 / 89 Subroutinesub 0.0% 0 / 54 Podpod 0.0% 0 / 38 totaltotal 0.0% 0 / 1172 CC 136 SCAR 37.6
CC
136
Cov
0%
_image_export
132.0
cmd_disk
110.0
cmd_mirror
90.0
CRAP 42.7
1 # ex:ts=8 sw=4:
2 # $OpenBSD$
3 #
4 # Copyright (c) 2024 Dick Olsson <hi@senzilla.io>
5 #
6 # Permission to use, copy, modify, and distribute this software for any
7 # purpose with or without fee is hereby granted, provided that the above
8 # copyright notice and this permission notice appear in all copies.
9 #
10 # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  
18 use v5.36;
19  
20 package App::FuguVM::CLI;
21 our $VERSION = '0.3.1';
22  
23 use File::Basename;
24 use File::Spec ();
25 use Fugu::CLI;
26 use Fugu::File;
27 use Fugu::Log;
28 use App::FuguVM::Config;
29 use App::FuguVM::Disk;
30 use App::FuguVM::Console;
31 use App::FuguVM::DiskCache;
32 use App::FuguVM::Mirror;
33 use App::FuguVM::Proxy;
34 use App::FuguVM::Remote;
35 use App::FuguVM::State;
36 use App::FuguVM::Guest;
37  
38 # The generic exit codes come from Fugu::CLI. Only the codes that
39 # mean something to a VM are defined here. App::FuguVM::Guest defines
40 # the codes that it returns itself: this module loads it, and the
41 # reverse import would be a cycle.
42 use constant {
43 EXIT_SUCCESS => Fugu::CLI::EXIT_SUCCESS,
44 EXIT_ERROR => Fugu::CLI::EXIT_ERROR,
45 EXIT_INVALID_ARGS => Fugu::CLI::EXIT_INVALID_ARGS,
46 EXIT_CONFIG_ERROR => Fugu::CLI::EXIT_CONFIG_ERROR,
47 EXIT_TIMEOUT => Fugu::CLI::EXIT_TIMEOUT,
48  
49 EXIT_VM_NOT_FOUND => 4,
50 EXIT_VM_RUNNING => 5,
51 EXIT_EXPECT_FAILED => 9,
52  
53 # Scriptable: a script that runs
54 # 'snapshot restore || provision-from-scratch' can tell a
55 # missing layer from a real failure.
56 EXIT_SNAPSHOT_NOT_FOUND => 11,
57 };
58  
59 # The subcommands. Each entry names the method that runs it, whether
60 # it needs a loaded project, and its own options. Fugu::CLI parses
61 # and dispatches; nothing here repeats a Getopt::Long block. A method
62 # without the cmd_ prefix is an App::FuguVM::Guest lifecycle verb, and
63 # run() loads the VM and calls it directly.
64 my %COMMANDS = (
65 up => {
66 summary => 'Ensure VM is running (download, create, start)',
67 usage => '[--no-cache]',
68 options => { 'no-cache' => 'ignore the installed-image cache' },
69 method => 'up',
70 },
71 down => {
72 summary => 'Stop VM gracefully',
73 method => 'down',
74 },
75 destroy => {
76 summary => 'Stop VM and delete disk image',
77 method => 'destroy',
78 },
79 status => {
80 summary => 'Show VM status',
81 usage => '[key]',
82 method => 'cmd_status',
83 },
84 start => {
85 summary => 'Start VM in background',
86 method => 'start',
87 },
88 stop => {
89 summary => 'Stop VM',
90 usage => '[--force]',
91 options => { 'force|f' => 'kill the VM instead of asking it' },
92 method => 'stop',
93 },
94 ssh => {
95 summary => 'Open SSH session or run command',
96 usage => '[--] [command [argument ...]]',
97 method => 'cmd_ssh',
98 },
99 put => {
100 summary => 'Copy a local file or directory into the VM',
101 usage => '[--mode=<octal>] <local> <remote>',
102 options => { 'mode=s' => 'the mode of each written file' },
103 method => 'cmd_put',
104 },
105 get => {
106 summary => 'Copy one guest file to the host',
107 usage => '<remote> <local>',
108 method => 'cmd_get',
109 },
110 console => {
111 summary => 'Attach to the VM serial console',
112 method => 'cmd_console',
113 },
114 expect => {
115 summary => 'Run expect script against console',
116 usage => '<script> [args...]',
117 method => 'cmd_expect',
118 },
119 wait => {
120 summary => 'Wait for VM to be ready (SSH available)',
121 usage => '[--timeout=N]',
122 options => { 'timeout=s' => 'seconds to wait' },
123 method => 'cmd_wait',
124 },
125 cache => {
126 summary => 'Manage installed images (list, clear [--stale])',
127 usage => '<list|clear> [--stale]',
128 options => { 'stale' => 'keep the entry the current VM uses' },
129 method => 'cmd_cache',
130 },
131 mirror => {
132 summary => 'Fetch and verify OpenBSD mirror files',
133 usage => '<fetch <file>|verify>',
134 method => 'cmd_mirror',
135 },
136 snapshot => {
137 summary => 'Manage snapshots (save, restore, rm, list)',
138 usage => '<save|restore|rm|list> [name] [--names]',
139 options => { 'names' => 'print names only' },
140 method => 'cmd_snapshot',
141 },
142 image => {
143 summary => 'Export the installed base image',
144 usage => 'export <path> [--format=qcow2|raw]',
145 options => { 'format=s' => 'the output format: qcow2 or raw' },
146 method => 'cmd_image',
147 },
148 disk => {
149 summary => 'Manage disk (check, repair, info)',
150 usage => '<check|repair|info>',
151 method => 'cmd_disk',
152 },
153 init => {
154 summary => 'Initialize .fuguvm/ directory',
155 usage => '[dir]',
156 method => 'cmd_init',
157 offline => 1,
158 },
159 );
160  
161 sub new ( $class, %opts )
162 {
163 my $mode =
164 $opts{quiet} ? Fugu::Log::MODE_QUIET : Fugu::Log::MODE_STDERR;
165 my $log = Fugu::Log->new(
166 mode => $mode,
167 level => 'info',
168 ident => 'fuguvm',
169 );
170  
171 my $self = bless {
172 vm_name => $opts{vm} // 'default',
173 project => $opts{project},
174 quiet => $opts{quiet} // 0,
175 emulate => $opts{emulate} // 0,
176 log => $log,
177 }, $class;
178  
179 return $self;
180 }
181  
182 sub run ( $class, @argv )
183 {
184 # The object exists before the parse, because each command body
185 # is a method on it. _prepare fills in what the global options
186 # decided, once Fugu::CLI has read them.
187 my $self = $class->new;
188  
189 my %commands;
190 for my $name ( keys %COMMANDS ) {
191 my $entry = $COMMANDS{$name};
192 $commands{$name} = {
193 %$entry,
194 run => sub ( $cli, @args ) {
195 my $failure = $self->_prepare( $cli, $entry );
196 return $failure if defined $failure;
197  
198 my $method = $entry->{method};
199 return $self->$method( $cli, @args )
200 if $self->can($method);
201  
202 # The entry names an App::FuguVM::Guest
203 # lifecycle verb. Load the VM and call it;
204 # 'up' and 'stop' each read one option.
205 my $vm = $self->_load_vm(
206 no_cache => $cli->option('no-cache')
207 // 0 )
208 or return $self->{load_exit};
209 my @verb_args =
210 $method eq 'stop'
211 ? ( $cli->option('force') // 0 )
212 : ();
213  
214 return $vm->$method(@verb_args);
215 },
216 };
217 }
218  
219 my $cli = Fugu::CLI->new(
220 name => 'fuguvm',
221 usage => '[--vm <name>] <command> [options]',
222 log => $self->{log},
223 commands => \%commands,
224 options => {
225 'vm=s' =>
226 'the VM to operate on (default: the default_vm '
227 . 'directive, or "default")',
228 'project=s' =>
229 'the project root (default: auto-discover)',
230 'quiet|q' => 'suppress informational output',
231 'verbose|v' => 'increase verbosity',
232 'emulate' => 'force TCG emulation',
233 },
234 epilogue => <<'EOF',
235 Examples:
236 fuguvm init
237 fuguvm up
238 fuguvm ssh -- uname -a
239 fuguvm wait --timeout=300
240 fuguvm --vm minimal up
241 EOF
242 );
243  
244 return $cli->run(@argv);
245 }
246  
247 # $self->_prepare($cli, $entry):
248 # Apply the global options and load the project. The method
249 # returns undef when the command may run, and an exit code when
250 # it may not.
251 sub _prepare ( $self, $cli, $entry )
252 {
253 $self->{vm_name} = $cli->option('vm') // 'default';
254 $self->{project} = $cli->option('project');
255 $self->{emulate} = $cli->option('emulate') // 0;
256  
257 if ( $cli->option('quiet') ) {
258 $self->{quiet} = 1;
259 $self->{log} = Fugu::Log->new(
260 mode => Fugu::Log::MODE_QUIET,
261 ident => 'fuguvm',
262 );
263 }
264 elsif ( $cli->option('verbose') ) {
265 $self->{log}->set_level('debug');
266 }
267  
268 return if $entry->{offline};
269  
270 my $project_root = $self->{project}
271 // App::FuguVM::Config->find_project_root;
272 if ( !defined $project_root ) {
273 $self->{log}->error(
274 "Not in a FuguVM project. Run 'fuguvm init' first.");
275 return EXIT_CONFIG_ERROR;
276 }
277 if ( !-d $project_root ) {
278 $self->{log}
279 ->error("Project path does not exist: $project_root");
280 return EXIT_CONFIG_ERROR;
281 }
282  
283 $self->{config} = App::FuguVM::Config->new($project_root);
284  
285 # The configuration names the default VM. The option wins; the
286 # offline commands, which return before the configuration
287 # exists, keep the literal 'default' from above.
288 $self->{vm_name} = $cli->option('vm') // $self->{config}->default_vm;
289  
290 # State->new diagnoses its own failure
291 $self->{state} = App::FuguVM::State->new( $self->{config}->state_dir,
292 $self->{vm_name} );
293 return EXIT_ERROR if !defined $self->{state};
294  
295 return;
296 }
297  
298 # $self->_load_vm(%opts):
299 # Load the invoked VM, or return undef with the exit code in
300 # $self->{load_exit}. An unknown configuration value gives
301 # EXIT_CONFIG_ERROR. A VM that no file declares gives
302 # EXIT_VM_NOT_FOUND.
303 sub _load_vm ( $self, %opts )
304 {
305 my $vm_config = $self->{config}->load_vm( $self->{vm_name} );
306 if ( !defined $vm_config ) {
307 my $reason = $self->{config}->error;
308 $self->{load_exit} =
309 defined $reason ? EXIT_CONFIG_ERROR : EXIT_VM_NOT_FOUND;
310 $self->{log}
311 ->error( $reason // "VM '$self->{vm_name}' not found" );
312 return;
313 }
314  
315 return App::FuguVM::Guest->new(
316 config => $vm_config,
317 state => $self->{state},
318 log => $self->{log},
319 emulate => $self->{emulate},
320 no_cache => $opts{no_cache} // 0,
321 );
322 }
323  
324 # Show the VM status. The report is data, so it goes to standard
325 # output whatever --quiet says. An optional key argument selects one
326 # bare value, so a make target reads one port without a text filter.
327 sub cmd_status ( $self, $cli, @args )
328 {
329 my ( $key, @extra ) = @args;
330 if (@extra) {
331 $self->{log}->error('Usage: fuguvm status [key]');
332 return EXIT_INVALID_ARGS;
333 }
334  
335 my $vm = $self->_load_vm or return $self->{load_exit};
336 my $status = $vm->status;
337  
338 if ( defined $key ) {
339 if ( !exists $status->{$key} ) {
340 $self->{log}->error(
341 sprintf(
342 "Unknown status key '%s' (valid keys:"
343 . ' %s)',
344 $key, join( ', ', sort keys %$status ) )
345 );
346 return EXIT_INVALID_ARGS;
347 }
348  
349 say $status->{$key} // '';
350 return EXIT_SUCCESS;
351 }
352  
353 $self->_dump_sorted($status);
354 return EXIT_SUCCESS;
355 }
356  
357 # $self->_dump_sorted($hash):
358 # Write the hash as sorted "key: value" lines to standard
359 # output, where a shell can read them. A line with an empty
360 # value ends with the colon and one space, so every line has one
361 # shape.
362 sub _dump_sorted ( $self, $hash )
363 {
364 for my $key ( sort keys %$hash ) {
365 my $value = $hash->{$key} // '';
366 say "$key: $value";
367 }
368  
369 return;
370 }
371  
372 # $self->_require_port($vm, $directive):
373 # Return the resolved port of the guest, or undef with a
374 # diagnostic. A stopped guest with a directive of 'auto' has no
375 # port, and a connection with an undef port would reach the
376 # default port of the protocol on the host itself.
377 sub _require_port ( $self, $vm, $directive )
378 {
379 my $port = $directive eq 'ssh_port' ? $vm->ssh_port : $vm->console_port;
380 return $port if defined $port;
381  
382 $self->{log}->error( "VM '$self->{vm_name}' has no $directive now."
383 . " Run 'fuguvm up' first." );
384 return;
385 }
386  
387 # $self->_require_running($vm):
388 # Return 1 while the guest runs. Log one line and return 0
389 # otherwise, because a clear message beats a "Failed to connect"
390 # from libssh2.
391 sub _require_running ( $self, $vm )
392 {
393 return 1 if $vm->is_running;
394  
395 $self->{log}->error( "VM '$self->{vm_name}' does not run."
396 . " Run 'fuguvm up' first." );
397 return 0;
398 }
399  
400 # $self->_require_remote($vm, $directive):
401 # Return the App::FuguVM::Remote object of the guest, or undef.
402 # The guest must run, and the port of $directive must resolve.
403 # _require_running and _require_port each log the reason.
404 sub _require_remote ( $self, $vm, $directive )
405 {
406 return if !$self->_require_running($vm);
407  
408 my $port = $self->_require_port( $vm, $directive );
409 return if !defined $port;
410  
411 # The connection uses the SSH agent for authentication. Connect
412 # to the IPv4 address that the forwarded port binds to. A name
413 # such as 'localhost' resolves to ::1 first on a dual-stack
414 # host, and QEMU does not listen there.
415 return App::FuguVM::Remote->new(
416 host => $vm->connect_address,
417 port => $port,
418 );
419 }
420  
421 # Open an SSH session into the VM, or run one argument vector on it
422 sub cmd_ssh ( $self, $cli, @args )
423 {
424 my $vm = $self->_load_vm or return $self->{load_exit};
425  
426 my $remote = $self->_require_remote( $vm, 'ssh_port' );
427 return EXIT_ERROR if !defined $remote;
428  
429 if (@args) {
430 my $result = $remote->run(@args);
431 print $result->{stdout} if $result->{stdout};
432 print STDERR $result->{stderr} if $result->{stderr};
433 return $result->{exit_code};
434 }
435 else {
436 return $remote->interactive;
437 }
438 }
439  
440 # Copy a local file or a local directory into the guest
441 sub cmd_put ( $self, $cli, @args )
442 {
443 my ( $local, $remote_path, @extra ) = @args;
444 if ( !defined $local || !defined $remote_path || @extra ) {
445 $self->{log}->error(
446 'Usage: fuguvm put [--mode=<octal>] <local> <remote>');
447 return EXIT_INVALID_ARGS;
448 }
449 if ( index( $remote_path, '/' ) != 0 ) {
450 $self->{log}
451 ->error("The remote path is not absolute: $remote_path");
452 return EXIT_INVALID_ARGS;
453 }
454  
455 my $mode = $cli->option('mode');
456 if ( defined $mode && $mode !~ /^[0-7]{3,4}$/ ) {
457 $self->{log}->error(
458 "Invalid --mode value: $mode (3 or 4 octal digits)");
459 return EXIT_INVALID_ARGS;
460 }
461 if ( -l $local || ( !-f $local && !-d $local ) ) {
462 $self->{log}
463 ->error("Not a regular file or a directory: $local");
464 return EXIT_INVALID_ARGS;
465 }
466  
467 my $vm = $self->_load_vm or return $self->{load_exit};
468  
469 my $remote = $self->_require_remote( $vm, 'ssh_port' );
470 return EXIT_ERROR if !defined $remote;
471  
472 return EXIT_ERROR
473 if !$remote->put( $local, $remote_path,
474 defined $mode ? ( mode => oct($mode) ) : () );
475  
476 return EXIT_SUCCESS;
477 }
478  
479 # Copy one guest file to the host
480 sub cmd_get ( $self, $cli, @args )
481 {
482 my ( $remote_path, $local, @extra ) = @args;
483 if ( !defined $remote_path || !defined $local || @extra ) {
484 $self->{log}->error('Usage: fuguvm get <remote> <local>');
485 return EXIT_INVALID_ARGS;
486 }
487 if ( index( $remote_path, '/' ) != 0 ) {
488 $self->{log}
489 ->error("The remote path is not absolute: $remote_path");
490 return EXIT_INVALID_ARGS;
491 }
492 if ( -d $local ) {
493 $self->{log}
494 ->error("The local destination is a directory: $local");
495 return EXIT_INVALID_ARGS;
496 }
497  
498 my $vm = $self->_load_vm or return $self->{load_exit};
499  
500 my $remote = $self->_require_remote( $vm, 'ssh_port' );
501 return EXIT_ERROR if !defined $remote;
502  
503 # The installed Fugu can come from a release that has no
504 # read_file yet: the manifests fetch the unversioned latest
505 # asset. A missing method must read as a diagnosis, not as a
506 # stack trace.
507 if ( !Fugu::SSH->can('read_file') ) {
508 $self->{log}->error(
509 'The installed Fugu has no Fugu::SSH->read_file.'
510 . ' Install Fugu 0.2.0 or later.' );
511 return EXIT_ERROR;
512 }
513  
514 return EXIT_ERROR if !$remote->get( $remote_path, $local );
515  
516 return EXIT_SUCCESS;
517 }
518  
519 # Attach the terminal of the operator to the serial console
520 sub cmd_console ( $self, $cli, @args )
521 {
522 my $vm = $self->_load_vm or return $self->{load_exit};
523  
524 return EXIT_ERROR if !$self->_require_running($vm);
525  
526 my $port = $self->_require_port( $vm, 'console_port' );
527 return EXIT_ERROR if !defined $port;
528  
529 my $host = $vm->connect_address;
530  
531 # The line goes through the logger, so --quiet drops it and
532 # the attachment still happens.
533 $self->{log}
534 ->info("Attaching to $host:$port. Leave with Ctrl-], then 'quit'.");
535  
536 my $console = App::FuguVM::Console->new(
537 host => $host,
538 port => $port,
539 );
540  
541 return $console->attach;
542 }
543  
544 # Run an expect script
545 sub cmd_expect ( $self, $cli, @args )
546 {
547 my $script = shift @args;
548 if ( !defined $script ) {
549 $self->{log}->error("Usage: fuguvm expect <script> [args...]");
550 return EXIT_INVALID_ARGS;
551 }
552  
553 my $vm = $self->_load_vm or return $self->{load_exit};
554  
555 my $port = $self->_require_port( $vm, 'console_port' );
556 return EXIT_ERROR if !defined $port;
557  
558 my $expect = App::FuguVM::Console->new(
559 host => $vm->connect_address,
560 port => $port,
561 );
562  
563 my $result = $expect->run_script( $script, @args );
564 return $result ? EXIT_SUCCESS : EXIT_EXPECT_FAILED;
565 }
566  
567 # Wait for SSH to become available
568 sub cmd_wait ( $self, $cli, @args )
569 {
570 my $timeout = $cli->option('timeout') // 120;
571  
572 # Make sure that the timeout is a positive integer
573 if ( $timeout !~ /^[1-9][0-9]*$/ ) {
574 $self->{log}->error("Invalid timeout value: $timeout");
575 return EXIT_INVALID_ARGS;
576 }
577  
578 my $vm = $self->_load_vm or return $self->{load_exit};
579  
580 my $port = $self->_require_port( $vm, 'ssh_port' );
581 return EXIT_ERROR if !defined $port;
582  
583 if ( !$vm->wait_ssh($timeout) ) {
584 $self->{log}->error("Timeout waiting for SSH");
585 return EXIT_TIMEOUT;
586 }
587  
588 $self->{log}->info("VM ready");
589 return EXIT_SUCCESS;
590 }
591  
592 # Installed-image cache management
593 sub cmd_cache ( $self, $cli, @args )
594 {
595 my $action = shift @args;
596 if ( !defined $action || $action !~ /^(list|clear)$/ ) {
597 $self->{log}
598 ->error("Usage: fuguvm cache <list|clear [--stale]>");
599 return EXIT_INVALID_ARGS;
600 }
601  
602 my $cache = App::FuguVM::DiskCache->new( $self->{config}->cache_dir );
603  
604 return $self->_cache_list($cache) if $action eq 'list';
605 return $self->_cache_clear( $cli, $cache, @args );
606 }
607  
608 # $self->_cache_list($cache):
609 # Show one line for each cached entry. Mark the entry that the
610 # configuration of the invoked VM currently derives. Then show
611 # what the proxy holds.
612 sub _cache_list ( $self, $cache )
613 {
614 my $entries = $cache->list;
615 if ( !@$entries ) {
616 $self->{log}->info("No cached images");
617 return $self->_proxy_list;
618 }
619  
620 my $current = $self->_current_cache_key($cache);
621  
622 for my $entry (@$entries) {
623 my $created =
624 defined $entry->{created_at}
625 ? scalar localtime $entry->{created_at}
626 : 'unknown';
627 my $marker = defined $current
628 && $entry->{key} eq $current ? ' (current)' : '';
629  
630 $self->{log}->info(
631 sprintf(
632 ' - %s %s %s snapshots: %d%s',
633 $entry->{key},
634 _format_size( $entry->{size} ),
635 $created,
636 scalar @{ $entry->{snapshots} },
637 $marker
638 ) );
639 }
640  
641 return $self->_proxy_list;
642 }
643  
644 # $self->_proxy_list:
645 # Show what the download cache of the proxy holds, one line for
646 # each OpenBSD version, and one line for the distfile tree.
647 # 'cache list' reports it because it shares cache_dir with the
648 # images, and the same 'cache clear' prunes it. A half of the
649 # directory that nothing printed was a half nobody knew to bound.
650 sub _proxy_list ($self)
651 {
652 my $cache = $self->_proxy_cache;
653 my $files = $cache->list;
654  
655 if ( !@$files ) {
656 $self->{log}->info('No proxy downloads');
657 return EXIT_SUCCESS;
658 }
659  
660 # Group the sizes per version, because 'clear --stale' prunes
661 # at that granularity. The code counts a URL that names no
662 # version under '-' and does not drop it. Thus an entry that
663 # cannot be pruned is still visible as one. A distfile carries
664 # no version, so the grouping excludes the distfile tree: its
665 # own line below reports it against the cap.
666 my %bytes;
667 for my $file (@$files) {
668 next if $file->{url} =~ m{/pub/OpenBSD/distfiles/};
669 my ($version) =
670 $file->{url} =~ m{/pub/OpenBSD/(?:syspatch/)?([0-9.]+)/};
671 $bytes{ $version // '-' } += $file->{size};
672 }
673  
674 $self->{log}->info(
675 sprintf 'Proxy downloads (%s):',
676 _format_size( $cache->size ) );
677  
678 for my $version ( sort keys %bytes ) {
679 $self->{log}->info( sprintf ' - OpenBSD %s %s',
680 $version, _format_size( $bytes{$version} ) );
681 }
682  
683 # The distfile line: the size against the cap, or the size with
684 # a note that nothing bounds new content. The line stays absent
685 # while the tree is empty.
686 my $distfiles = $cache->distfile_size;
687 my $limit = $cache->distfile_limit;
688 if ( $distfiles > 0 ) {
689 $self->{log}->info(
690 $limit > 0
691 ? sprintf(
692 'Distfiles: %s of %s',
693 _format_size($distfiles),
694 _format_size($limit) )
695 : sprintf( 'Distfiles: %s, caching off',
696 _format_size($distfiles) ) );
697 }
698  
699 return EXIT_SUCCESS;
700 }
701  
702 # $self->_proxy_cache:
703 # Build the proxy cache of the project, with the distfile cap of
704 # the configuration.
705 sub _proxy_cache ($self)
706 {
707 return App::FuguVM::Proxy::Cache->new( $self->{config}->cache_dir,
708 $self->{config}->distfile_cache );
709 }
710  
711 # $self->_cache_clear($cli, $cache, @args):
712 # Remove cached entries. Bare 'clear' removes them all. --stale
713 # keeps the entry that the VM named by --vm derives. The key
714 # inputs 'version' and 'disk_size' are per-VM. Thus --stale run
715 # for one VM does prune bases that another VM would have hit.
716 sub _cache_clear ( $self, $cli, $cache, @args )
717 {
718 my $stale = $cli->option('stale') // 0;
719  
720 # An interrupted store leaves partial trees behind. Both forms
721 # of 'clear' sweep them.
722 my $swept = $cache->sweep_temp;
723 $self->{log}->info("Removed $swept incomplete cache entries")
724 if $swept;
725  
726 # _current_cache_key diagnoses the failure; refuse to prune on it
727 my $keep = $stale ? $self->_current_cache_key($cache) : undef;
728 return EXIT_ERROR if $stale && !defined $keep;
729  
730 my $removed = 0;
731 for my $entry ( @{ $cache->list } ) {
732 next if defined $keep && $entry->{key} eq $keep;
733  
734 my $users = $self->_disks_backed_by( $entry->{dir} );
735 my @running = grep { $_->{running} } @$users;
736 if (@running) {
737 $self->{log}->error(
738 sprintf(
739 "Cannot remove %s: VM '%s' is running on it",
740 $entry->{key}, $running[0]{vm} ) );
741 return EXIT_VM_RUNNING;
742 }
743  
744 # The user can rebuild a stopped disk with
745 # 'fuguvm destroy'. Thus this is a warning. The check
746 # cannot cover checkouts other than this one. Those
747 # checkouts share cache_dir but not state_dir.
748 for my $user (@$users) {
749 $self->{log}->warning(
750 sprintf(
751 "Removing %s orphans the disk of VM '%s'; run 'fuguvm destroy' for it",
752 $entry->{key}, $user->{vm} ) );
753 }
754  
755 if ( !$cache->remove( $entry->{key} ) ) {
756 return EXIT_ERROR;
757 }
758 $self->{log}->info("Removed $entry->{key}");
759 $removed++;
760 }
761  
762 $self->{log}->info(
763 $removed
764 ? "Removed $removed cached images"
765 : "No cached images removed"
766 );
767  
768 return $self->_proxy_clear($stale);
769 }
770  
771 # $self->_proxy_clear($stale):
772 # Clear the other half of cache_dir: the download cache of the
773 # proxy. Bare 'clear' empties it. --stale keeps the OpenBSD
774 # version that the invoked VM installs. That is the same one-VM
775 # scope that the image prune above has.
776 #
777 # The image loop cannot reach this cache. That is why this is a
778 # second pass, not a branch inside the loop. The two caches share
779 # nothing but cache_dir. Also, the images have running-VM and
780 # orphaned-disk checks that a re-downloadable file set does not
781 # need.
782 sub _proxy_clear ( $self, $stale )
783 {
784 my $cache = $self->_proxy_cache;
785  
786 if ( !$stale ) {
787 my $size = $cache->size;
788 if ( !$cache->clear ) {
789 $self->{log}->error("Cannot clear proxy downloads");
790 return EXIT_ERROR;
791 }
792 $self->{log}->info( sprintf 'Removed %s of proxy downloads',
793 _format_size($size) );
794  
795 return EXIT_SUCCESS;
796 }
797  
798 # The --stale path got this far. Thus the VM resolves. To keep
799 # its version is the point of the flag.
800 my $vm = $self->{config}->load_vm( $self->{vm_name} );
801 my $removed = $cache->prune( $vm->{version} );
802  
803 for my $entry (@$removed) {
804 $self->{log}->info(
805 sprintf 'Removed %s of downloads for OpenBSD %s',
806 _format_size( $entry->{size} ),
807 $entry->{version} );
808 }
809 $self->{log}->info('No proxy downloads removed') if !@$removed;
810  
811 # A distfile carries no version, so the version rule above
812 # cannot decide about the distfile tree. --stale keeps the
813 # tree, because a refill is expensive, and re-applies the cap.
814 # With a cap of 0 no cap applies here, and the flag keeps the
815 # whole tree.
816 if ( $cache->distfile_limit > 0 ) {
817 my $trimmed = $cache->trim_distfiles;
818 if (@$trimmed) {
819 my $bytes = 0;
820 $bytes += $_->{size} for @$trimmed;
821 $self->{log}->info( sprintf 'Removed %s of distfiles',
822 _format_size($bytes) );
823 }
824 }
825  
826 return EXIT_SUCCESS;
827 }
828  
829 # The mirror subcommand: fetch one verified file of the release, or
830 # verify the cached files of the version and the architecture of the
831 # invoked guest.
832 sub cmd_mirror ( $self, $cli, @args )
833 {
834 my $action = shift @args;
835 if ( !defined $action || $action !~ /^(fetch|verify)$/ ) {
836 $self->{log}
837 ->error('Usage: fuguvm mirror <fetch <file>|verify>');
838 return EXIT_INVALID_ARGS;
839 }
840  
841 my $vm_config = $self->{config}->load_vm( $self->{vm_name} );
842 if ( !defined $vm_config ) {
843 my $reason = $self->{config}->error;
844 $self->{log}
845 ->error( $reason // "VM '$self->{vm_name}' not found" );
846 return defined $reason ? EXIT_CONFIG_ERROR : EXIT_VM_NOT_FOUND;
847 }
848  
849 # The verify verb proves; a 'verify no' directive must not turn
850 # it into a walk that proves nothing.
851 my $verifies = $action eq 'verify' ? 1 : $vm_config->{verify} // 1;
852 my $mirror = App::FuguVM::Mirror->new(
853 cache => $self->_proxy_cache,
854 version => $vm_config->{version},
855 arch => $vm_config->{arch},
856 verify => $verifies,
857 log => $self->{log},
858 (
859 defined $vm_config->{signify_dir}
860 ? ( keys_dir => $vm_config->{signify_dir} )
861 : ()
862 ),
863 );
864  
865 # An absent public key for the version is a configuration
866 # error, apart from a failed download or a failed signature.
867 if ( $verifies && !defined $mirror->key_path ) {
868 $self->{log}->error( $mirror->error );
869 return EXIT_CONFIG_ERROR;
870 }
871  
872 if ( $action eq 'verify' ) {
873 if (@args) {
874 $self->{log}->error('Usage: fuguvm mirror verify');
875 return EXIT_INVALID_ARGS;
876 }
877 return $self->_mirror_verify($mirror);
878 }
879 return $self->_mirror_fetch( $mirror, @args );
880 }
881  
882 # $self->_mirror_fetch($mirror, @args):
883 # Fetch, verify and cache one file of the release, and write the
884 # cached path to standard output, where a script can read it.
885 # The scope comes from the manifests: the release scope when the
886 # manifest of the architecture directory names the file, and the
887 # source scope otherwise. Both manifests are authoritative
888 # lists, so the tool guesses nothing.
889 sub _mirror_fetch ( $self, $mirror, @args )
890 {
891 my ( $file, @extra ) = @args;
892 if ( !defined $file || @extra ) {
893 $self->{log}->error('Usage: fuguvm mirror fetch <file>');
894 return EXIT_INVALID_ARGS;
895 }
896  
897 my $scope;
898 for my $candidate (qw(release source)) {
899 my $names = $mirror->manifest_names($candidate);
900 if ( !defined $names ) {
901 $self->{log}->error( $mirror->error );
902 return EXIT_ERROR;
903 }
904 if ( grep { $_ eq $file } @$names ) {
905 $scope = $candidate;
906 last;
907 }
908 }
909 if ( !defined $scope ) {
910 $self->{log}->error("No manifest of the release names '$file'");
911 return EXIT_ERROR;
912 }
913  
914 my $path = $mirror->ensure( $scope, $file );
915 if ( !defined $path ) {
916 $self->{log}->error( $mirror->error );
917 return EXIT_ERROR;
918 }
919  
920 say $path;
921 return EXIT_SUCCESS;
922 }
923  
924 # $self->_mirror_verify($mirror):
925 # Verify every cached file of the two scopes. The verb removes
926 # each file that failed, in its own scope only, because a file
927 # that fails a digest must not stay in a cache that a later run
928 # reads and a same-named file of the other scope failed nothing.
929 # It must not remove an unknown file: a name that no manifest
930 # holds is not a failure, and index.txt is such a name on every
931 # mirror. The verb is idempotent: a second run over a clean
932 # cache removes nothing and exits 0.
933 sub _mirror_verify ( $self, $mirror )
934 {
935 my $report = $mirror->verify_cache;
936 if ( !defined $report ) {
937 $self->{log}->error( $mirror->error );
938 return EXIT_ERROR;
939 }
940  
941 for my $entry ( @{ $report->{failed} } ) {
942 $self->{log}->error( sprintf 'Verification failed: %s/%s',
943 $entry->{scope}, $entry->{name} );
944 my $path =
945 $mirror->cached_path( $entry->{scope}, $entry->{name} );
946 unlink $path if defined $path && -f $path;
947 }
948  
949 $self->{log}->info(
950 sprintf 'Verified: %d ok, %d failed, %d unknown',
951 scalar @{ $report->{ok} },
952 scalar @{ $report->{failed} },
953 scalar @{ $report->{unknown} } );
954  
955 return @{ $report->{failed} } ? EXIT_ERROR : EXIT_SUCCESS;
956 }
957  
958 # $self->_current_cache_key($cache):
959 # Return the key that the configuration of the invoked VM
960 # derives. Return undef, with the diagnostic already logged, when
961 # the VM or one of the key inputs cannot be resolved.
962 sub _current_cache_key ( $self, $cache )
963 {
964 my $vm_config = $self->{config}->load_vm( $self->{vm_name} );
965 my $key = defined $vm_config ? $cache->key($vm_config) : undef;
966  
967 $self->{log}->error("Cannot determine the current cache key")
968 if !defined $key;
969  
970 return $key;
971 }
972  
973 # $self->_disks_backed_by($entry_dir):
974 # Return every VM in this checkout whose working disk hangs off
975 # an image in $entry_dir, as [ { vm => name, running => bool } ].
976 # The method enumerates the state directory, not the
977 # configuration. Thus a disk counts whether a 'vm' block still
978 # declares it or not.
979 sub _disks_backed_by ( $self, $entry_dir )
980 {
981 my $state_dir = $self->{config}->state_dir;
982 return [] if !-d $state_dir;
983  
984 opendir my $dh, $state_dir or return [];
985 my @names =
986 sort grep { !/^\./ && -f "$state_dir/$_/disk.qcow2" } readdir $dh;
987 closedir $dh;
988  
989 my $disk = App::FuguVM::Disk->new($state_dir);
990 my @users;
991  
992 for my $name (@names) {
993 my $backing = $disk->backing_file($name);
994 next if !defined $backing;
995 next if index( $backing, "$entry_dir/" ) != 0;
996  
997 my $state = App::FuguVM::State->new( $state_dir, $name );
998 push @users,
999 {
1000 vm => $name,
1001 running => $state && $state->is_vm_running ? 1 : 0,
1002 };
1003 }
1004  
1005 return \@users;
1006 }
1007  
1008 # Named snapshot layers over a cached base image
1009 sub cmd_snapshot ( $self, $cli, @args )
1010 {
1011 my $action = shift @args;
1012 if ( !defined $action || $action !~ /^(save|restore|list|rm)$/ ) {
1013 $self->{log}->error(
1014 "Usage: fuguvm snapshot <save|restore|rm> <name> | list [--names]"
1015 );
1016 return EXIT_INVALID_ARGS;
1017 }
1018  
1019 my $cache = App::FuguVM::DiskCache->new( $self->{config}->cache_dir );
1020  
1021 return $self->_snapshot_list( $cli, $cache, @args )
1022 if $action eq 'list';
1023  
1024 my $name = shift @args;
1025 if ( !$cache->valid_snapshot_name($name) ) {
1026 $self->{log}->error(
1027 "Invalid snapshot name: " . ( $name // '(missing)' ) );
1028 return EXIT_INVALID_ARGS;
1029 }
1030  
1031 return $self->_snapshot_save( $cache, $name ) if $action eq 'save';
1032 return $self->_snapshot_restore( $cache, $name )
1033 if $action eq 'restore';
1034 return $self->_snapshot_remove( $cache, $name );
1035 }
1036  
1037 # $self->_snapshot_save($cache, $name):
1038 # Flatten the stopped working disk into the cache, under the base
1039 # it was built on. A live overlay is not consistent. Thus the
1040 # command refuses a running VM and does not copy it.
1041 sub _snapshot_save ( $self, $cache, $name )
1042 {
1043 my $vm = $self->_load_vm or return $self->{load_exit};
1044  
1045 if ( $vm->is_running ) {
1046 $self->{log}->error("Stop the VM before saving a snapshot");
1047 return EXIT_VM_RUNNING;
1048 }
1049  
1050 if ( !$self->{state}->disk_exists ) {
1051 $self->{log}->error("No disk image. Run 'fuguvm up' first.");
1052 return EXIT_ERROR;
1053 }
1054  
1055 if ( !$self->{state}->is_installed ) {
1056 $self->{log}->error("VM is not installed yet");
1057 return EXIT_ERROR;
1058 }
1059  
1060 # The snapshot belongs under the base that the disk hangs off,
1061 # directly or through another snapshot. To save again after a
1062 # restore is normal.
1063 my $key = $self->_disk_cache_key($cache);
1064 if ( !defined $key ) {
1065 $self->{log}->error(
1066 "This disk is not built on a cached image, so it cannot be snapshotted."
1067 );
1068 $self->{log}->error(
1069 "It was created with --no-cache or 'image_cache no'; recreate it with 'fuguvm destroy' and 'fuguvm up'."
1070 );
1071 return EXIT_ERROR;
1072 }
1073  
1074 $self->{log}->info("Saving snapshot '$name' of $key...");
1075  
1076 my $state = $self->{state};
1077 my $path = $cache->snapshot_store(
1078 $key, $name,
1079 $state->disk_path,
1080 {
1081 installed => 1,
1082 installed_ssh_pubkey =>
1083 $state->get_installed_ssh_pubkey,
1084 } );
1085 if ( !defined $path ) {
1086 $self->{log}->error("Failed to save snapshot '$name'");
1087 return EXIT_ERROR;
1088 }
1089  
1090 $self->{log}->info("Saved snapshot '$name': $path");
1091 return EXIT_SUCCESS;
1092 }
1093  
1094 # $self->_snapshot_restore($cache, $name):
1095 # Replace the working disk with a fresh overlay on a snapshot.
1096 # Reseed the state that the disk embodies. The command works from
1097 # nothing: no disk, no state. Thus a fresh checkout can restore
1098 # before its first 'up'.
1099 sub _snapshot_restore ( $self, $cache, $name )
1100 {
1101 my $vm = $self->_load_vm or return $self->{load_exit};
1102 my $state = $self->{state};
1103  
1104 if ( $vm->is_running ) {
1105 $self->{log}->error("Stop the VM before restoring a snapshot");
1106 return EXIT_VM_RUNNING;
1107 }
1108  
1109 my $key = $self->_current_cache_key($cache)
1110 or return EXIT_ERROR;
1111  
1112 my $found = $self->_snapshot_found( $cache, $key, $name )
1113 or return EXIT_SNAPSHOT_NOT_FOUND;
1114  
1115 # Disk::create returns early on an existing path. Without this
1116 # removal, a restore would report success and change nothing.
1117 my $disk_path = $state->disk_path;
1118 if ( -f $disk_path ) {
1119 unlink $disk_path or do {
1120 $self->{log}->error("Cannot remove $disk_path: $!");
1121 return EXIT_ERROR;
1122 };
1123 }
1124  
1125 my $vm_config = $self->{config}->load_vm( $self->{vm_name} );
1126 my $disk = App::FuguVM::Disk->new( $self->{config}->state_dir );
1127 my $created =
1128 $disk->create( $vm_config->{name}, undef, $found->{path} );
1129 if ( !defined $created ) {
1130 $self->{log}->error("Failed to overlay snapshot '$name'");
1131 return EXIT_ERROR;
1132 }
1133  
1134 # Reseed what the disk embodies. The next 'fuguvm up' reconciles
1135 # a checkout whose SSH key differs from the saved one.
1136 my $meta = $found->{meta};
1137 $state->mark_installed( $vm_config->{arch} );
1138 $state->set_root_password( $meta->{root_password} )
1139 if defined $meta->{root_password};
1140 $state->mark_ssh_key_installed( $meta->{installed_ssh_pubkey} )
1141 if defined $meta->{installed_ssh_pubkey};
1142 $state->data->{cached_from} = "$key/$name";
1143 $state->save;
1144  
1145 $self->{log}->info("Restored snapshot '$name' of $key");
1146 return EXIT_SUCCESS;
1147 }
1148  
1149 sub _snapshot_list ( $self, $cli, $cache, @args )
1150 {
1151 my $names = $cli->option('names') // 0;
1152  
1153 my $key = $self->_current_cache_key($cache)
1154 or return EXIT_ERROR;
1155  
1156 my $snapshots = $cache->snapshot_list($key);
1157  
1158 # --names writes bare names to stdout, where a shell can read
1159 # them. The human listing goes through the logger, which writes
1160 # to stderr and prefixes every line.
1161 if ($names) {
1162 say $_->{name} for @$snapshots;
1163 return EXIT_SUCCESS;
1164 }
1165  
1166 if ( !@$snapshots ) {
1167 $self->{log}->info("No snapshots for $key");
1168 return EXIT_SUCCESS;
1169 }
1170  
1171 for my $snapshot (@$snapshots) {
1172 my $created =
1173 defined $snapshot->{created_at}
1174 ? scalar localtime $snapshot->{created_at}
1175 : 'unknown';
1176 $self->{log}->info(
1177 sprintf( ' - %s %s %s',
1178 $snapshot->{name},
1179 _format_size( $snapshot->{size} ),
1180 $created ) );
1181 }
1182  
1183 return EXIT_SUCCESS;
1184 }
1185  
1186 sub _snapshot_remove ( $self, $cache, $name )
1187 {
1188 my $key = $self->_current_cache_key($cache)
1189 or return EXIT_ERROR;
1190  
1191 $self->_snapshot_found( $cache, $key, $name )
1192 or return EXIT_SNAPSHOT_NOT_FOUND;
1193  
1194 if ( !$cache->snapshot_remove( $key, $name ) ) {
1195 return EXIT_ERROR;
1196 }
1197  
1198 $self->{log}->info("Removed snapshot '$name'");
1199 return EXIT_SUCCESS;
1200 }
1201  
1202 # $self->_snapshot_found($cache, $key, $name):
1203 # Look a snapshot up. Diagnose a miss, once for every caller.
1204 sub _snapshot_found ( $self, $cache, $key, $name )
1205 {
1206 my $found = $cache->snapshot_lookup( $key, $name );
1207  
1208 $self->{log}->error("No snapshot '$name' for $key")
1209 if !defined $found;
1210  
1211 return $found;
1212 }
1213  
1214 # $self->_disk_cache_key($cache):
1215 # Return the cache entry that backs the working disk, directly
1216 # with its base image or through a snapshot of it.
1217 sub _disk_cache_key ( $self, $cache )
1218 {
1219 my $vm_config = $self->{config}->load_vm( $self->{vm_name} );
1220 return if !defined $vm_config;
1221  
1222 # Scalar context: backing_file returns an empty list for a
1223 # standalone disk. Without scalar context, the empty list would
1224 # reach key_for_path as no argument at all, not as undef.
1225 my $disk = App::FuguVM::Disk->new( $self->{config}->state_dir );
1226 my $backing = $disk->backing_file( $vm_config->{name} );
1227  
1228 return $cache->key_for_path($backing);
1229 }
1230  
1231 # The image export, beside the snapshot verbs. Those verbs already
1232 # resolve a cache key from a working disk, and the export needs the
1233 # same resolution.
1234 sub cmd_image ( $self, $cli, @args )
1235 {
1236 my $action = shift @args;
1237 if ( !defined $action || $action ne 'export' ) {
1238 $self->{log}->error( 'Usage: fuguvm image export <path>'
1239 . ' [--format=qcow2|raw]' );
1240 return EXIT_INVALID_ARGS;
1241 }
1242  
1243 return $self->_image_export( $cli, @args );
1244 }
1245  
1246 # $self->_image_export($cli, @args):
1247 # Write the base image of the invoked VM as a full-disk image.
1248 # The source is the base image of the cache entry that backs the
1249 # working disk, or the working disk itself when the disk is
1250 # standalone. The write goes through one temporary sibling and
1251 # one rename, so a failure leaves no partial file behind.
1252 sub _image_export ( $self, $cli, @args )
1253 {
1254 my ( $target, @extra ) = @args;
1255 if ( !defined $target || @extra ) {
1256 $self->{log}->error( 'Usage: fuguvm image export <path>'
1257 . ' [--format=qcow2|raw]' );
1258 return EXIT_INVALID_ARGS;
1259 }
1260  
1261 my $format = $cli->option('format') // 'qcow2';
1262 if ( $format ne 'qcow2' && $format ne 'raw' ) {
1263 $self->{log}->error(
1264 "Unknown format '$format' (accepted values: qcow2, raw)"
1265 );
1266 return EXIT_INVALID_ARGS;
1267 }
1268  
1269 my $vm = $self->_load_vm or return $self->{load_exit};
1270  
1271 # A live overlay is not consistent, and a running QEMU holds
1272 # an exclusive lock on the working disk. snapshot save refuses
1273 # a running guest for the same reason.
1274 if ( $vm->is_running ) {
1275 $self->{log}->error("Stop the VM before exporting its image");
1276 return EXIT_VM_RUNNING;
1277 }
1278  
1279 if ( !$self->{state}->disk_exists ) {
1280 $self->{log}->error("No disk image. Run 'fuguvm up' first.");
1281 return EXIT_ERROR;
1282 }
1283  
1284 if ( !$self->{state}->is_installed ) {
1285 $self->{log}->error("VM is not installed yet");
1286 return EXIT_ERROR;
1287 }
1288  
1289 # The tool must not overwrite an image that an operator
1290 # published.
1291 if ( -e $target ) {
1292 $self->{log}->error("The target exists: $target");
1293 return EXIT_ERROR;
1294 }
1295  
1296 # The tool creates no directory for the operator
1297 my $parent = dirname($target);
1298 if ( !-d $parent ) {
1299 $self->{log}->error("The parent directory is absent: $parent");
1300 return EXIT_ERROR;
1301 }
1302  
1303 # The source. A standalone disk comes from --no-cache or from
1304 # 'image_cache no', and the export then reads the disk itself.
1305 my $cache = App::FuguVM::DiskCache->new( $self->{config}->cache_dir );
1306 my $key = $self->_disk_cache_key($cache);
1307 my $source =
1308 defined $key ? $cache->base_path($key) : $self->{state}->disk_path;
1309  
1310 my $tmp = "$target.tmp.$$";
1311 if ( !App::FuguVM::Disk->convert( $source, $tmp, format => $format ) ) {
1312 unlink $tmp;
1313 $self->{log}->error("Export failed");
1314 return EXIT_ERROR;
1315 }
1316 if ( !rename $tmp, $target ) {
1317 $self->{log}->error("Cannot publish $target: $!");
1318 unlink $tmp;
1319 return EXIT_ERROR;
1320 }
1321  
1322 my $path = File::Spec->rel2abs($target);
1323 $self->_dump_sorted( {
1324 bytes => -s $path,
1325 format => $format,
1326 key => $key // '',
1327 path => $path,
1328 source => File::Spec->rel2abs($source),
1329 } );
1330  
1331 return EXIT_SUCCESS;
1332 }
1333  
1334 # Disk management
1335 sub cmd_disk ( $self, $cli, @args )
1336 {
1337 my $action = shift @args;
1338 if ( !defined $action || $action !~ /^(check|repair|info)$/ ) {
1339 $self->{log}->error("Usage: fuguvm disk <check|repair|info>");
1340 return EXIT_INVALID_ARGS;
1341 }
1342  
1343 my $disk = App::FuguVM::Disk->new( $self->{state}{state_dir} );
1344  
1345 if ( $action eq 'info' ) {
1346 my $info = $disk->info( $self->{vm_name} );
1347 if ( !defined $info ) {
1348 $self->{log}->error("Disk not found");
1349 return EXIT_ERROR;
1350 }
1351  
1352 $self->_dump_sorted($info);
1353 return EXIT_SUCCESS;
1354 }
1355  
1356 if ( $action eq 'check' ) {
1357 $self->{log}->info("Checking disk image...");
1358 my $result = $disk->check( $self->{vm_name} );
1359 if ( !defined $result ) {
1360 $self->{log}->error("Disk not found");
1361 return EXIT_ERROR;
1362 }
1363  
1364 if ( $result->{status} eq 'ok' ) {
1365 $self->{log}->info("Disk image OK");
1366 return EXIT_SUCCESS;
1367 }
1368  
1369 $self->{log}->error("Disk image has errors");
1370 print $result->{output} if $result->{output};
1371 return EXIT_ERROR;
1372 }
1373  
1374 # The action regex above admits 'repair' alone from here
1375 $self->{log}->info("Repairing disk image...");
1376  
1377 # First, check if the VM runs
1378 my $vm = $self->_load_vm;
1379 if ( defined $vm && $vm->is_running ) {
1380 $self->{log}->error("Cannot repair disk while VM is running");
1381 return EXIT_ERROR;
1382 }
1383  
1384 my $ok = $disk->repair( $self->{vm_name} );
1385 if ($ok) {
1386  
1387 # Clear the unclean shutdown state after a successful
1388 # repair
1389 $self->{state}->clear_shutdown_state;
1390 $self->{log}->info("Disk repaired");
1391 return EXIT_SUCCESS;
1392 }
1393  
1394 $self->{log}->error("Disk repair failed");
1395 return EXIT_ERROR;
1396 }
1397  
1398 # Initialize the project
1399 sub cmd_init ( $self, $cli, @args )
1400 {
1401 my $dir = shift @args // '.';
1402 my $data_dir = App::FuguVM::Config::DATA_DIR();
1403 my $fuguvm_dir = "$dir/$data_dir";
1404 my $config_file = "$dir/" . App::FuguVM::Config::PROJECT_CONFIG();
1405  
1406 if ( -f $config_file ) {
1407 $self->{log}->info("FuguVM already initialized in $dir");
1408 return EXIT_SUCCESS;
1409 }
1410  
1411 # Fugu::File diagnoses a directory it cannot create or write
1412 for my $dir ( "$fuguvm_dir/vms", "$fuguvm_dir/state" ) {
1413 Fugu::File->ensure_dir($dir) or return EXIT_ERROR;
1414 }
1415  
1416 # Create the project configuration. state_dir must agree with
1417 # the directory created above. Thus it derives from the same
1418 # constant.
1419 my $wrote_config = Fugu::File->write( $config_file, <<"EOF" );
1420 # FuguVM project configuration
1421  
1422 cache_dir = ~/.cache/fuguvm
1423 state_dir = $data_dir/state
1424 default_vm = default
1425 EOF
1426 return EXIT_ERROR if !$wrote_config;
1427  
1428 # Create the default VM config
1429 my $wrote_vm =
1430 Fugu::File->write( "$fuguvm_dir/vms/default.conf", <<"EOF" );
1431 # Default OpenBSD VM
1432  
1433 name = openbsd-default
1434 arch = arm64
1435 version = 7.8
1436 memory = 2048
1437 disk_size = 8G
1438  
1439 ssh_port = 2222
1440 console_port = 4444
1441 EOF
1442 return EXIT_ERROR if !$wrote_vm;
1443  
1444 # Create the .gitignore file
1445 my $wrote_ignore =
1446 Fugu::File->write( "$fuguvm_dir/.gitignore", <<'EOF' );
1447 state/
1448 *.log
1449 EOF
1450 return EXIT_ERROR if !$wrote_ignore;
1451  
1452 $self->{log}->info("Initialized FuguVM in $dir");
1453 return EXIT_SUCCESS;
1454 }
1455  
1456 # _format_size($bytes):
1457 # Return a byte count in the shortest unit that keeps it under
1458 # 1024. A count of undef reads as a question mark: a size that
1459 # nobody could measure is not a size of zero.
1460 #
1461 # The command-line interface is the only caller. A byte count for
1462 # a person to read is presentation, so it belongs here.
1463 sub _format_size ( $bytes = undef )
1464 {
1465 return '?' if !defined $bytes;
1466  
1467 my @units = ( 'B', 'K', 'M', 'G', 'T' );
1468 my $size = $bytes;
1469 my $unit = 0;
1470  
1471 while ( $size >= 1024 && $unit < $#units ) {
1472 $size /= 1024;
1473 $unit++;
1474 }
1475  
1476 return $unit == 0
1477 ? sprintf( '%d%s', $size, $units[$unit] )
1478 : sprintf( '%.1f%s', $size, $units[$unit] );
1479 }
1480  
1481 1;