KVM.pm 62.5 KB
Newer Older
1
2
3
4
5
package Ravada::Domain::KVM;

use warnings;
use strict;

6
7
8
9
10
11
=head2 NAME

Ravada::Domain::KVM - KVM Virtual Machines library for Ravada

=cut

12
13
14
15
use Carp qw(cluck confess croak);
use Data::Dumper;
use File::Copy;
use File::Path qw(make_path);
Francesc Guasch's avatar
Francesc Guasch committed
16
use Hash::Util qw(lock_keys lock_hash);
17
use IPC::Run3 qw(run3);
Francesc Guasch's avatar
Francesc Guasch committed
18
use MIME::Base64;
19
20
use Moose;
use Sys::Virt::Stream;
JanFontanet's avatar
JanFontanet committed
21
use Sys::Virt::Domain;
22
use Sys::Virt;
23
24
use XML::LibXML;

25
26
27
no warnings "experimental::signatures";
use feature qw(signatures);

Francesc Guasch's avatar
Francesc Guasch committed
28
extends 'Ravada::Front::Domain::KVM';
29
30
31
32
33
with 'Ravada::Domain';

has 'domain' => (
      is => 'rw'
    ,isa => 'Sys::Virt::Domain'
34
    ,required => 0
35
36
37
);

has '_vm' => (
38
    is => 'rw'
39
40
41
42
    ,isa => 'Ravada::VM::KVM'
    ,required => 0
);

Francesc Guasch's avatar
Francesc Guasch committed
43
44
45
46
47
48
has readonly => (
    isa => 'Int'
    ,is => 'rw'
    ,default => 0
);

49
50
51
52
53
54
55
56
57
##################################################
#
our $TIMEOUT_SHUTDOWN = 60;
our $OUT;

our %SET_DRIVER_SUB = (
    network => \&_set_driver_network
     ,sound => \&_set_driver_sound
     ,video => \&_set_driver_video
58
59
60
61
62
     ,image => \&_set_driver_image
     ,jpeg => \&_set_driver_jpeg
     ,zlib => \&_set_driver_zlib
     ,playback => \&_set_driver_playback
     ,streaming => \&_set_driver_streaming
Francesc Guasch's avatar
Francesc Guasch committed
63
     ,disk => \&_set_driver_disk
64
65
);

66
67
our %GET_CONTROLLER_SUB = (
    usb => \&_get_controller_usb
Francesc Guasch's avatar
Francesc Guasch committed
68
    ,disk => \&_get_controller_disk
Francesc Guasch's avatar
Francesc Guasch committed
69
    ,network => \&_get_controller_network
70
71
72
    );
our %SET_CONTROLLER_SUB = (
    usb => \&_set_controller_usb
Francesc Guasch's avatar
Francesc Guasch committed
73
    ,disk => \&_set_controller_disk
Francesc Guasch's avatar
Francesc Guasch committed
74
    ,network => \&_set_controller_network
75
76
77
    );
our %REMOVE_CONTROLLER_SUB = (
    usb => \&_remove_controller_usb
Francesc Guasch's avatar
Francesc Guasch committed
78
    ,disk => \&_remove_controller_disk
Francesc Guasch's avatar
Francesc Guasch committed
79
    ,network => \&_remove_controller_network
80
    );
Francesc Guasch's avatar
Francesc Guasch committed
81
82
83

our %CHANGE_HARDWARE_SUB = (
    disk => \&_change_hardware_disk
Francesc Guasch's avatar
Francesc Guasch committed
84
85
    ,vcpus => \&_change_hardware_vcpus
    ,memory => \&_change_hardware_memory
Francesc Guasch's avatar
Francesc Guasch committed
86
    ,network => \&_change_hardware_network
Francesc Guasch's avatar
Francesc Guasch committed
87
);
88
89
##################################################

Francesc Guasch's avatar
Francesc Guasch committed
90
91
92
93
94
sub BUILD {
    my ($self, $arg) = @_;
    $self->readonly( $arg->{readonly} or 0);
}

95
96
97
98
99
100
101
102
103

=head2 name

Returns the name of the domain

=cut

sub name {
    my $self = shift;
104

105
    return $self->domain->get_name if $self->domain;
106
107

    confess "ERROR: Unknown domain name";
108
109
110
111
112
113
114
115
116
117
118
119
120
121
}

=head2 list_disks

Returns a list of the disks used by the virtual machine. CDRoms are not included

  my@ disks = $domain->list_disks();

=cut

sub list_disks {
    my $self = shift;
    my @disks = ();

122
    my $doc = XML::LibXML->load_xml(string => $self->xml_description);
123
124
125
126
127
128
129

    for my $disk ($doc->findnodes('/domain/devices/disk')) {
        next if $disk->getAttribute('device') ne 'disk';

        for my $child ($disk->childNodes) {
            if ($child->nodeName eq 'source') {
                my $file = $child->getAttribute('file');
Francesc Guasch's avatar
Francesc Guasch committed
130
                next if $file =~ /\.iso$/;
131
132
133
134
135
136
137
                push @disks,($file);
            }
        }
    }
    return @disks;
}

Francesc Guasch's avatar
Francesc Guasch committed
138
sub xml_description($self, $inactive=0) {
139
140
141
    return $self->_data_extra('xml')
        if ($self->is_removed || !$self->domain )
            && $self->is_known;
142

143
    confess "ERROR: KVM domain not available ".$self->is_known   if !$self->domain;
144
145
    my $xml;
    eval {
Francesc Guasch's avatar
Francesc Guasch committed
146
147
148
149
150
151
152
153
154
        my @flags;
        @flags = ( Sys::Virt::Domain::XML_INACTIVE ) if $inactive;

        $xml = $self->domain->get_xml_description(@flags);
        $self->_data_extra('xml', $xml) if $self->is_known
                                        && ( $inactive
                                                || !$self->_data_extra('xml')
                                                || !$self->is_active
                                        );
155
156
157
158
159
160
161
162
    };
    confess $@ if $@ && $@ !~ /libvirt error code: 42/;
    if ( $@ ) {
        return $self->_data_extra('xml');
    }
    return $xml;
}

Francesc Guasch's avatar
Francesc Guasch committed
163
164
165
166
sub xml_description_inactive($self) {
    return $self->xml_description(1);
}

167
168
169
170
171
172
173
174
175
176
177
178
179
180
=head2 remove_disks

Remove the volume files of the domain

=cut

sub remove_disks {
    my $self = shift;

    my $removed = 0;

    my $id;
    eval { $id = $self->id };
    return if $@ && $@ =~ /No DB info/i;
181
    confess $@ if $@;
182
183

    $self->_vm->connect();
Francesc Guasch's avatar
Francesc Guasch committed
184
    for my $file ($self->list_disks( device => 'disk')) {
185
186
187
188
        if (! -e $file ) {
            next;
        }
        $self->_vol_remove($file);
Francesc Guasch's avatar
Francesc Guasch committed
189
        $self->_vol_remove($file);
190
191
192
#        if ( -e $file ) {
#            unlink $file or die "$! $file";
#        }
193
194
195
        $removed++;

    }
196
    return if $self->is_removed;
197
198
199
200
201
202
    warn "WARNING: No disk files removed for ".$self->domain->get_name."\n"
            .Dumper([$self->list_disks])
        if !$removed && $0 !~ /\.t$/;

}

203
204
205
206
207
208
209
210
211
212
=head2 pre_remove_domain

Cleanup operations executed before removing this domain

    $self->pre_remove_domain

=cut

sub pre_remove_domain {
    my $self = shift;
Francesc Guasch's avatar
Francesc Guasch committed
213
    return if $self->is_removed;
214
    $self->xml_description();
215
216
217
    $self->domain->managed_save_remove()    if $self->domain->has_managed_save_image;
}

218
219
220
221
222
sub _vol_remove {
    my $self = shift;
    my $file = shift;
    my $warning = shift;

223
224
    confess "Error: I won't remove an iso file " if $file =~ /\.iso$/i;

225
226
    my $name;
    ($name) = $file =~ m{.*/(.*)}   if $file =~ m{/};
227

228
229
230
    my $removed = 0;
    for my $pool ( $self->_vm->vm->list_storage_pools ) {
        $pool->refresh;
231
232
        my $vol;
        eval { $vol = $pool->get_volume_by_name($name) };
233
        if (! $vol ) {
234
            warn "VOLUME $name not found in $pool \n".($@ or '')
235
                if $@ !~ /libvirt error code: 50,/i;
236
237
238
239
            next;
        }
        $vol->delete();
        $pool->refresh;
240
241
242
243
    }
    return 1;
}

Francesc Guasch's avatar
Francesc Guasch committed
244
245
246
247
sub remove_volume {
    return _vol_remove(@_);
}

248
249
250
251
252
253
254
255
256
257
=head2 remove

Removes this domain. It removes also the disk drives and base images.

=cut

sub remove {
    my $self = shift;
    my $user = shift;

258
    my @volumes;
259
    if (!$self->is_removed ) {
Francesc Guasch's avatar
Francesc Guasch committed
260
        for my $vol ( $self->list_volumes_info ) {
Francesc Guasch's avatar
Francesc Guasch committed
261
262
263
264
            push @volumes,($vol->{file})
                if exists $vol->{file}
                   && exists $vol->{device}
                   && $vol->{device} eq 'file';
Francesc Guasch's avatar
Francesc Guasch committed
265
        }
266
267
    }

Francesc Guasch's avatar
Francesc Guasch committed
268
    if (!$self->is_removed && $self->domain && $self->domain->is_active) {
269
270
271
        $self->_do_force_shutdown();
    }

Francesc Guasch's avatar
Francesc Guasch committed
272
    eval { $self->domain->undefine()    if $self->domain && !$self->is_removed };
273
    confess $@ if $@ && $@ !~ /libvirt error code: 42/;
274

Francesc Guasch's avatar
Francesc Guasch committed
275
    eval { $self->remove_disks() if $self->is_known };
276
    confess $@ if $@ && $@ !~ /libvirt error code: 42/;
277

278
    for my $file ( @volumes ) {
279
280
        eval { $self->remove_volume($file) };
        warn $@ if $@;
281
282
    }

283
    eval { $self->_remove_file_image() };
284
        warn $@ if $@;
285
    confess $@ if $@ && $@ !~ /libvirt error code: 42/;
286
287
288
289
290
#    warn "WARNING: Problem removing file image for ".$self->name." : $@" if $@ && $0 !~ /\.t$/;

#    warn "WARNING: Problem removing ".$self->file_base_img." for ".$self->name
#            ." , I will try again later : $@" if $@;

291
    $self->_post_remove_base_domain() if $self->is_base();
292
293
294
295
296
297
298

}


sub _remove_file_image {
    my $self = shift;
    for my $file ( $self->list_files_base ) {
299
        next if $file && $file =~ /\.iso$/i;
300
301
302
303
304
305

        next if !$file || ! -e $file;

        chmod 0770, $file or die "$! chmodding $file";
        chown $<,$(,$file    or die "$! chowning $file";
        eval { $self->_vol_remove($file,1) };
306
        warn $@ if $@;
307
308
309
310
311
312
313
314
315
316
317
318
319
320

        if ( -e $file ) {
            eval {
                unlink $file or die "$! $file" ;
                #TODO: do a refresh of all the storage pools in the VM if anything removed
                $self->_vm->storage_pool->refresh();
            };
            warn $@ if $@;
        }
        next if ! -e $file;
        warn $@ if $@;
    }
}

Francesc Guasch's avatar
Francesc Guasch committed
321
sub _disk_device($self, $with_info=undef, $attribute=undef, $value=undef) {
322

Francesc Guasch's avatar
Francesc Guasch committed
323
324
    my $doc = XML::LibXML->load_xml(string
            => $self->xml_description(Sys::Virt::Domain::XML_INACTIVE))
325
326
327
328
        or die "ERROR: $!\n";

    my @img;

Francesc Guasch's avatar
Francesc Guasch committed
329
    my $n_order = 0;
330
    for my $disk ($doc->findnodes('/domain/devices/disk')) {
Francesc Guasch's avatar
Francesc Guasch committed
331
332
333
334
335
336
337
338
339
340
341
        my ($source_node) = $disk->findnodes('source');
        my $file;
        $file = $source_node->getAttribute('file')  if $source_node;

        my ($target_node) = $disk->findnodes('target');
        my $device = $disk->getAttribute('device');
        my $target = $target_node->getAttribute('dev');
        my $bus = $target_node->getAttribute('bus');

        my ($boot_node) = $disk->findnodes('boot');
        my $info = {};
Francesc Guasch's avatar
Francesc Guasch committed
342
343
        eval { $info = $self->_volume_info($file) if $file && $device eq 'disk' };
        die $@ if $@ && $@ !~ /not found/i;
Francesc Guasch's avatar
Francesc Guasch committed
344
345
346
347
348
349
        $info->{device} = $device;
        if (!$info->{name} ) {
            if ($file) {
                ($info->{name}) = $file =~ m{.*/(.*)};
            } else {
                $info->{name} = $target."-".$info->{device};
350
351
            }
        }
Francesc Guasch's avatar
Francesc Guasch committed
352
353
354
355
        $info->{target} = $target;
        $info->{driver} = $bus;
        $info->{n_order} = $n_order++;
        $info->{boot} = $boot_node->getAttribute('order') if $boot_node;
Francesc Guasch's avatar
Francesc Guasch committed
356
        $info->{file} = $file if defined $file;
Francesc Guasch's avatar
Francesc Guasch committed
357
358
359
360
361

        next if defined $attribute
           && (!exists $info->{$attribute}
                || $info->{$attribute} ne $value);

Francesc Guasch's avatar
Francesc Guasch committed
362
        if (!$with_info) {
Francesc Guasch's avatar
Francesc Guasch committed
363
            push @img,($file) if $file;
Francesc Guasch's avatar
Francesc Guasch committed
364
365
            next;
        }
366
        push @img,Ravada::Volume->new(file => $file, info => $info, domain => $self);
367
368
369
370
371
    }
    return @img;

}

Francesc Guasch's avatar
Francesc Guasch committed
372
sub _volume_info($self, $file, $refresh=0) {
Francesc Guasch's avatar
Francesc Guasch committed
373
374
    confess "Error: No vm connected" if !$self->_vm->vm;

Francesc Guasch's avatar
Francesc Guasch committed
375
376
377
378
379
380
381
382
383
384
385
386
387
    my ($name) = $file =~ m{.*/(.*)};

    my $vol;
    for my $pool ( $self->_vm->vm->list_storage_pools ) {
        $pool->refresh() if $refresh;
        eval { $vol = $pool->get_volume_by_name($name) };
        warn $@ if $@ && $@ !~ /^libvirt error code: 50,/;
        last if $vol;
    }
    if (!$vol && !$refresh) {
        return $self->_volume_info($file, ++$refresh);
    }

Francesc Guasch's avatar
Francesc Guasch committed
388
    if (!$vol) {
Francesc Guasch's avatar
Francesc Guasch committed
389
        confess "Error: Volume $file not found ".$self->name;
Francesc Guasch's avatar
Francesc Guasch committed
390
391
        return;
    }
Francesc Guasch's avatar
Francesc Guasch committed
392

Francesc Guasch's avatar
Francesc Guasch committed
393
394
395
    my $info;
    eval { $info = $vol->get_info };
    warn "WARNING: $@" if $@ && $@ !~ /^libvirt error code: 50,/;
Francesc Guasch's avatar
Francesc Guasch committed
396
397
    $info->{file} = $file;
    $info->{name} = $name;
Francesc Guasch's avatar
Francesc Guasch committed
398
    $info->{driver} = delete $info->{bus} if exists $info->{bus};
Francesc Guasch's avatar
Francesc Guasch committed
399
400
401
402

    return $info;
}

403
404
405
sub _disk_devices_xml {
    my $self = shift;

406
    my $doc = XML::LibXML->load_xml(string => $self->xml_description)
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
        or die "ERROR: $!\n";

    my @devices;

    for my $disk ($doc->findnodes('/domain/devices/disk')) {
        my $is_disk = 0;
        for my $child ($disk->childNodes) {
            $is_disk++ if $child->nodeName eq 'source';
        }
        push @devices,($disk) if $is_disk;
    }
    return @devices;

}

=head2 disk_device

Returns the file name of the disk of the domain.

  my $file_name = $domain->disk_device();

=cut

sub disk_device {
    my $self = shift;
432
    return $self->_disk_device(@_);
433
434
}

435

436
sub _create_qcow_base {
437
    confess "Deprecated";
438
439
440
441
    my $self = shift;

    my @base_img;

Francesc Guasch's avatar
Francesc Guasch committed
442
    for  my $vol_data ( $self->list_volumes_info( device => 'disk')) {
443
444
        my $base_img = $vol_data->prepare_base();
        push @base_img,([$base_img,$vol_data->info->{target}]);
445
446
447
448
449
450
451
452
453

    }
    return @base_img;

}

sub _cmd_convert {
    my ($base_img, $qcow_img) = @_;

454

455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
    return    ('qemu-img','convert',
                '-O','qcow2', $base_img
                ,$qcow_img
        );

}

sub _cmd_copy {
    my ($base_img, $qcow_img) = @_;

    return ('cp'
            ,$base_img, $qcow_img
    );
}

=pod

sub _create_swap_base {
    my $self = shift;

    my @swap_img;

    my $base_name = $self->name;
    for  my $base_img ( $self->list_volumes()) {

      next unless $base_img =~ 'SWAP';

        confess "ERROR: missing $base_img"
            if !-e $base_img;
        my $swap_img = $base_img;

        $swap_img =~ s{\.\w+$}{\.ro.img};

        push @swap_img,($swap_img);

        my @cmd = ('qemu-img','convert',
                '-O','raw', $base_img
                ,$swap_img
        );

        my ($in, $out, $err);
        run3(\@cmd,\$in,\$out,\$err);
        warn $out if $out;
        warn $err if $err;

        if (! -e $swap_img) {
            warn "ERROR: Output file $swap_img not created at ".join(" ",@cmd)."\n";
            exit;
        }

        chmod 0555,$swap_img;
        $self->_prepare_base_db($swap_img);
    }
    return @swap_img;

}

=cut

514
=head2 post_prepare_base
515

516
Task to run after preparing a base virtual machine
517
518
519
520

=cut


521
sub post_prepare_base {
522
523
    my $self = shift;

524
    $self->_store_xml();
525
526
}

527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
sub _store_xml {
    my $self = shift;
    my $xml = $self->domain->get_xml_description(Sys::Virt::Domain::XML_INACTIVE);
    my $sth = $self->_dbh->prepare(
        "INSERT INTO base_xml (id_domain, xml) "
        ." VALUES ( ?,? ) "
    );
    $sth->execute($self->id , $xml);
    $sth->finish;
}

=head2 get_xml_base

Returns the XML definition for the base, only if prepare_base has been run befor

=cut

sub get_xml_base{

    my $self = shift;
    my $sth = $self->_dbh->prepare(
        "SELECT xml FROM base_xml WHERE id_domain=?"
    );
    $sth->execute($self->id);
551
552
    my $xml = $sth->fetchrow;
    return ($xml or $self->domain->get_xml_description);
553
554
}

555
sub _post_remove_base_domain {
556
557
558
559
560
561
562
    my $self = shift;
    my $sth = $self->_dbh->prepare(
        "DELETE FROM base_xml WHERE id_domain=?"
    );
    $sth->execute($self->id);
}

JanFontanet's avatar
JanFontanet committed
563
564
565
566
567
568
569
570
571
572
573
574

sub post_resume_aux($self) {
    my $time = time();
    eval {
        $self->domain->set_time($time, 0, 0);
    };
    if ($@) {
        $@='' if $@ !~ /libvirt error code: 86 /;
        die $@ if $@;
    }
}

Francesc Guasch's avatar
Francesc Guasch committed
575
=head2 display_info
576

Francesc Guasch's avatar
Francesc Guasch committed
577
Returns the display information as a hashref. The display URI is in the display entry
578
579
580

=cut

Francesc Guasch's avatar
Francesc Guasch committed
581
sub display_info($self, $user) {
582

583
    my $xml = XML::LibXML->load_xml(string => $self->xml_description);
584
585
586
587
588
    my ($graph) = $xml->findnodes('/domain/devices/graphics')
        or die "ERROR: I can't find graphic";

    my ($type) = $graph->getAttribute('type');
    my ($port) = $graph->getAttribute('port');
Francesc Guasch's avatar
Francesc Guasch committed
589
    my ($tls_port) = $graph->getAttribute('tlsPort');
590
591
    my ($address) = $graph->getAttribute('listen');

592
    warn "ERROR: Machine ".$self->name." is not active in node ".$self->_vm->name."\n"
593
        if !$port && !$self->is_active;
594

Francesc Guasch's avatar
Francesc Guasch committed
595
596
597
598

    my %display = (
                type => $type
               ,port => $port
599
                 ,ip => $address
Francesc Guasch's avatar
Francesc Guasch committed
600
601
          ,tls_port => $tls_port
    );
602
603
604
    $port = '' if !defined $port;
    my $display = $type."://$address:$port";
    $display{display} = $display;
Francesc Guasch's avatar
Francesc Guasch committed
605
606
    lock_hash(%display);
    return \%display;
607
608
609
610
611
612
613
614
615
616
}

=head2 is_active

Returns whether the domain is running or not

=cut

sub is_active {
    my $self = shift;
617
    return 0 if $self->is_removed;
Francesc Guasch's avatar
Francesc Guasch committed
618
619
620
621
    my $is_active = 0;
    eval { $is_active = $self->domain->is_active };
    die $@ if $@ && $@ !~ /code: 42,/;
    return $is_active;
622
623
}

Francesc Guasch's avatar
Francesc Guasch committed
624
625
626
627
628
629
630
631
=head2 is_persistent

Returns wether the domain has a persistent configuration file

=cut

sub is_persistent($self) {
    return $self->domain->is_persistent;
632
633
634
635
636
637
638
639
640
641
}

=head2 start

Starts the domain

=cut

sub start {
    my $self = shift;
642
643
    my %arg;

644
    if (!(scalar(@_) % 2))  {
645
646
        %arg = @_;
    }
647

648
649
    my $remote_ip = delete $arg{remote_ip};
    my $request = delete $arg{request};
650
651
    my $listen_ip = ( delete $arg{listen_ip} or $self->_listen_ip);
    my $set_password = delete $arg{set_password};
652

653
    $self->_set_spice_ip($set_password, $listen_ip);
654
    $self->status('starting');
Francesc Guasch's avatar
Francesc Guasch committed
655
656
657
658
659
660
661
662
663
664
665
666
667

    my $error;
    for ( ;; ) {
        eval { $self->domain->create() };
        $error = $@;
        next if $error && $error =~ /libvirt error code: 1, .* pool .* asynchronous/;
        last;
    }
    return if !$error || $error =~ /already running/i;
    if ($error =~ /libvirt error code: 38,/) {
        if (!$self->_vm->is_local) {
            warn "Disabling node ".$self->_vm->name();
            $self->_vm->enabled(0);
668
        }
Francesc Guasch's avatar
Francesc Guasch committed
669
670
671
        die $error;
    } elsif ( $error =~ /libvirt error code: 9, .*already defined with uuid/) {
        die "TODO";
672
673
674
    } elsif ( $error =~ /libvirt error code: 1,.*smbios/) {
        $self->_remove_smbios();
        $self->domain->create();
Francesc Guasch's avatar
Francesc Guasch committed
675
676
677
678
679
680
    } elsif ( $self->domain->has_managed_save_image ) {
        $request->status("removing saved image") if $request;
        $self->domain->managed_save_remove();
        $self->domain->create();
    } else {
        die $error;
681
    }
682
683
}

684
685
686
687
688
689
690
691
692
693
694
sub _remove_smbios($self) {
    my $doc = XML::LibXML->load_xml(string => $self->domain->get_xml_description(Sys::Virt::Domain::XML_INACTIVE));

    my ($os) = $doc->findnodes('/domain/os');
    my ($smbios) = $os->findnodes('smbios');
    $os->removeChild($smbios) if $smbios;

    my $new_domain = $self->_vm->vm->define_domain($doc->toString);
    $self->domain($new_domain);
}

Francesc Guasch's avatar
Francesc Guasch committed
695
696
sub _pre_shutdown_domain {
    my $self = shift;
Francesc Guasch's avatar
Francesc Guasch committed
697

Francesc Guasch's avatar
Francesc Guasch committed
698
699
700
701
702
703
704
705
706
707
708
    my ($state, $reason) = $self->domain->get_state();

    if ($state == Sys::Virt::Domain::STATE_PMSUSPENDED_UNKNOWN 
         || $state == Sys::Virt::Domain::STATE_PMSUSPENDED_DISK_UNKNOWN 
         || $state == Sys::Virt::Domain::STATE_PMSUSPENDED) {
        $self->domain->pm_wakeup();
        for ( 1 .. 10 ) {
            last if $self->is_active;
            sleep 1;
        }
    }
709
710
711

    $self->domain->managed_save_remove()
        if $self->domain->has_managed_save_image();
Francesc Guasch's avatar
Francesc Guasch committed
712

Francesc Guasch's avatar
Francesc Guasch committed
713
714
}

715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
=head2 shutdown

Stops the domain

=cut

sub shutdown {
    my $self = shift;

    my %args = @_;
    my $req = $args{req};

    if (!$self->is_active && !$args{force}) {
        $req->status("done")                if $req;
        $req->error("Domain already down")  if $req;
        return;
    }

    return $self->_do_force_shutdown() if $args{force};
    return $self->_do_shutdown();

}

sub _do_shutdown {
    my $self = shift;
Francesc Guasch's avatar
Francesc Guasch committed
740
741
742
    return if !$self->domain->is_active;
    eval { $self->domain->shutdown() };
    die $@ if $@ && $@ !~ /libvirt error code: 55,/;
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764

}

=head2 shutdown_now

Shuts down uncleanly the domain

=cut

sub shutdown_now {
    my $self = shift;
    return $self->_do_force_shutdown()  if $self->is_active;
}

=head2 force_shutdown

Shuts down uncleanly the domain

=cut

sub force_shutdown{
    my $self = shift;
765
    return $self->_do_force_shutdown() if $self->is_active;
766
767
768
769
}

sub _do_force_shutdown {
    my $self = shift;
770
771
772
773
    return if !$self->domain->is_active;

    eval { $self->domain->destroy   };
    warn $@ if $@;
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
}


=head2 pause

Pauses the domain

=cut

sub pause {
    my $self = shift;
    return $self->domain->suspend();
}

=head2 resume

Resumes a paused the domain

=cut

sub resume {
    my $self = shift;
Francesc Guasch's avatar
Francesc Guasch committed
796
797
    eval { $self->domain->resume() };
    die $@ if $@ && $@ !~ /libvirt error code: 55/;
798
799
800
}


801
802
803
804
805
806
807
808
809
810
811
=head2 is_hibernated

Returns if the domain has a managed saved state.

=cut

sub is_hibernated {
    my $self = shift;
    return $self->domain->has_managed_save_image;
}

812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
=head2 is_paused

Returns if the domain is paused

=cut

sub is_paused {
    my $self = shift;
    my ($state, $reason) = $self->domain->get_state();



    return 0 if $state == 1;
    #TODO, find out which one of those id "1" and remove it from this list
    #
    return $state &&
        ($state == Sys::Virt::Domain::STATE_PAUSED_UNKNOWN
        || $state == Sys::Virt::Domain::STATE_PAUSED_USER
        || $state == Sys::Virt::Domain::STATE_PAUSED_DUMP
        || $state == Sys::Virt::Domain::STATE_PAUSED_FROM_SNAPSHOT
        || $state == Sys::Virt::Domain::STATE_PAUSED_IOERROR
        || $state == Sys::Virt::Domain::STATE_PAUSED_MIGRATION
        || $state == Sys::Virt::Domain::STATE_PAUSED_SAVE
        || $state == Sys::Virt::Domain::STATE_PAUSED_SHUTTING_DOWN
    );
    return 0;
}

840
841
842
843
844
845
846
847
=head2 can_hybernate

Returns true (1) for KVM domains

=cut

sub can_hybernate { 1 };

Francesc Guasch's avatar
Francesc Guasch committed
848
849
850
851
852
853
854
855
=head2 can_hybernate

Returns true (1) for KVM domains

=cut

sub can_hibernate { 1 };

856
857
858
859
860
861
862
863
864
865
866
=head2 hybernate

Take a snapshot of the domain's state and save the information to a
managed save location. The domain will be automatically restored with
this state when it is next started.

    $domain->hybernate();

=cut

sub hybernate {
Francesc Guasch's avatar
Francesc Guasch committed
867
    my $self = shift;
868
    $self->hibernate(@_);
Francesc Guasch's avatar
Francesc Guasch committed
869
870
871
872
873
874
875
876
877
878
879
880
881
}

=head2 hybernate

Take a snapshot of the domain's state and save the information to a
managed save location. The domain will be automatically restored with
this state when it is next started.

    $domain->hybernate();

=cut

sub hibernate {
882
883
884
885
    my $self = shift;
    $self->domain->managed_save();
}

Francesc Guasch's avatar
Francesc Guasch committed
886

887
888
889
890
891
892
893
=head2 add_volume

Adds a new volume to the domain

    $domain->add_volume(name => $name, size => $size);
    $domain->add_volume(name => $name, size => $size, xml => 'definition.xml');

894
895
    $domain->add_volume(path => "/var/lib/libvirt/images/path.img");

896
897
898
899
900
901
=cut

sub add_volume {
    my $self = shift;
    my %args = @_;

902
    my $bus = delete $args{driver};# or 'virtio');
Francesc Guasch's avatar
Francesc Guasch committed
903
904
    my $boot = (delete $args{boot} or undef);
    my $device = (delete $args{device} or 'disk');
Francesc Guasch's avatar
Francesc Guasch committed
905
    my $type = delete $args{type};
Francesc Guasch's avatar
Francesc Guasch committed
906
    my %valid_arg = map { $_ => 1 } ( qw( driver name size vm xml swap target file allocation));
907
908
909
910
911

    for my $arg_name (keys %args) {
        confess "Unknown arg $arg_name"
            if !$valid_arg{$arg_name};
    }
Francesc Guasch's avatar
Francesc Guasch committed
912
913
914
915
916

    $type = 'swap'  if !defined $type && $args{swap};
    $type = ''   if !defined $type || $type eq 'sys';
    confess "Error: type $type can't have swap flag" if $args{swap} && $type ne 'swap';

917
918
#    confess "Missing vm"    if !$args{vm};
    $args{vm} = $self->_vm if !$args{vm};
Francesc Guasch's avatar
Francesc Guasch committed
919
920
    my ($target_dev) = ($args{target} or $self->_new_target_dev());
    my $name = delete $args{name};
921
    if (!$args{xml}) {
922
923
        $args{xml} = $Ravada::VM::KVM::DIR_XML."/default-volume.xml";
        $args{xml} = $Ravada::VM::KVM::DIR_XML."/swap-volume.xml"      if $args{swap};
924
925
    }

Francesc Guasch's avatar
Francesc Guasch committed
926
927
    my $path = delete $args{file};
    ($name) = $path =~ m{.*/(.*)} if !$name && $path;
928
929

    $path = $args{vm}->create_volume(
930
        name => $name
931
932
933
        ,xml =>  $args{xml}
        ,swap => ($args{swap} or 0)
        ,size => ($args{size} or undef)
Francesc Guasch's avatar
Francesc Guasch committed
934
        ,type => $type
Francesc Guasch's avatar
Francesc Guasch committed
935
936
        ,allocation => ($args{allocation} or undef)
        ,target => $target_dev
937
    )   if !$path;
Francesc Guasch's avatar
Francesc Guasch committed
938
    ($name) = $path =~ m{.*/(.*)} if !$name;
939
940
941
942
943
944
945

# TODO check if <target dev="/dev/vda" bus='virtio'/> widhout dev works it out
# change dev=vd*  , slot=*
#
    my $driver_type = 'qcow2';
    my $cache = 'default';

Francesc Guasch's avatar
Francesc Guasch committed
946
    if ( $args{swap} || $device eq 'cdrom' ) {
947
948
949
950
        $cache = 'none';
        $driver_type = 'raw';
    }

951
952
953
954
955
956
957
    if ( !defined $bus ) {
        if  ($device eq 'cdrom') {
            $bus = 'ide';
        } else {
            $bus = 'virtio'
        }
    }
Francesc Guasch's avatar
Francesc Guasch committed
958
959
960
961
962
    my $xml_device = $self->_xml_new_device(
            bus => $bus
          ,file => $path
          ,type => $driver_type
         ,cache => $cache
Francesc Guasch's avatar
Francesc Guasch committed
963
        ,device => $device
Francesc Guasch's avatar
Francesc Guasch committed
964
965
966
967
        ,target => $target_dev
    );

    eval { $self->domain->attach_device($xml_device,Sys::Virt::Domain::DEVICE_MODIFY_CONFIG) };
Francesc Guasch's avatar
Francesc Guasch committed
968
    die $@ if $@;
Francesc Guasch's avatar
Francesc Guasch committed
969

Francesc Guasch's avatar
Francesc Guasch committed
970
    $self->_set_boot_order($path, $boot) if $boot;
Francesc Guasch's avatar
Francesc Guasch committed
971
972
973
    return $path;
}

Francesc Guasch's avatar
Francesc Guasch committed
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
sub _set_boot_hd($self, $value) {
    my $doc;
    if ($value ) {
        $doc = $self->_remove_boot_order() if $value;
    } else {
        $doc = XML::LibXML->load_xml(string => $self->domain->get_xml_description(Sys::Virt::Domain::XML_INACTIVE));
    }
    my ($os) = $doc->findnodes('/domain/os');
    my ($boot) = $os->findnodes('boot');
    if (!$value) {
        $os->removeChild($boot) or die "Error removing ".$boot->toString();
    } else {
        if (!$boot) {
            $boot = $os->addNewChild(undef,'boot');
        }
        $boot->setAttribute(dev => 'hd');
    }
    my $new_domain = $self->_vm->vm->define_domain($doc->toString);
    $self->domain($new_domain);
};

sub _remove_boot_order($self, $index=undef) {
    return $self->_cmd_boot_order(0,$index,0);
}

sub _set_boot_order($self, $index, $order) {
    my $doc = $self->_cmd_boot_order(1,$index, $order);

    my ($os) = $doc->findnodes('/domain/os');
    my ($boot) = $os->findnodes('boot');

    $os->removeChild($boot) if $boot;

    my $new_domain = $self->_vm->vm->define_domain($doc->toString);
    $self->domain($new_domain);
}

sub _cmd_boot_order($self, $set, $index=undef, $order=1) {
    my $doc = XML::LibXML->load_xml(string => $self->domain->get_xml_description(Sys::Virt::Domain::XML_INACTIVE));
    my $count = 0;

    # if index is not numeric is the file, search the real index
    $index = $self->_search_volume_index($index) if defined $index && $index !~ /^\d+$/;

    for my $device ($doc->findnodes('/domain/devices/disk')) {
        my ($boot) = $device->findnodes('boot');
        if ( defined $index && $count++ != $index) {
            next if !$set || !$boot;
            my $this_order = $boot->getAttribute('order');
            next if $this_order < $order;
            $boot->setAttribute( order => $this_order+1);
            next;
        }
        if (!$set) {
            next if !$boot;
            $device->removeChild($boot);
        } else {
            $boot = $device->addNewChild(undef,'boot')  if !$boot;
            $boot->setAttribute( order => $order );
        }
    }
    return $doc;
}

sub _search_volume_index($self, $file) {
    my $doc = XML::LibXML->load_xml(string => $self->domain->get_xml_description(Sys::Virt::Domain::XML_INACTIVE));
    my $index = 0;
    for my $device ($doc->findnodes('/domain/devices/disk')) {
        my ($source) = $device->findnodes('source');
        return $index if $source->getAttribute('file') eq $file;
        $index++;
    }
    confess "I can't find file $file in ".$self->name;
}

Francesc Guasch's avatar
Francesc Guasch committed
1049
1050
1051
sub _xml_new_device($self , %arg) {
    my $bus = delete $arg{bus} or confess "Missing bus.";
    my $file = delete $arg{file} or confess "Missing target.";
Francesc Guasch's avatar
Francesc Guasch committed
1052
1053
    my $boot = delete $arg{boot};
    my $device = delete $arg{device};
Francesc Guasch's avatar
Francesc Guasch committed
1054
1055

    my $xml = <<EOT;
Francesc Guasch's avatar
Francesc Guasch committed
1056
    <disk type='file' device='$device'>
Francesc Guasch's avatar
Francesc Guasch committed
1057
1058
      <driver name='qemu' type='$arg{type}' cache='$arg{cache}'/>
      <source file='$file'/>
1059
      <backingStore/>
Francesc Guasch's avatar
Francesc Guasch committed
1060
1061
      <target bus='$bus' dev='$arg{target}'/>
      <address type=''/>
Francesc Guasch's avatar
Francesc Guasch committed
1062
      <boot/>
1063
1064
1065
    </disk>
EOT

Francesc Guasch's avatar
Francesc Guasch committed
1066
1067
    my $xml_device=XML::LibXML->load_xml(string => $xml);
    my ($address) = $xml_device->findnodes('/disk/address') or die "No address in ".$xml_device->toString();
1068

Francesc Guasch's avatar
Francesc Guasch committed
1069
1070
    my $doc = XML::LibXML->load_xml(string => $self->xml_description);
    $self->_change_xml_address($doc, $address, $bus);
1071

Francesc Guasch's avatar
Francesc Guasch committed
1072
1073
1074
1075
1076
1077
1078
1079
    my ($boot_xml) = $xml_device->findnodes('/disk/boot');
    if ($boot) {
        $boot_xml->setAttribute( order => $boot );
    } else {
        my ($disk) = $xml_device->findnodes('/disk');
        $disk->removeChild($boot_xml) or die "I can't remove boot node from disk";
    }
    return $xml_device->toString();
Francesc Guasch's avatar
Francesc Guasch committed
1080
}
1081
1082
1083
1084

sub _new_target_dev {
    my $self = shift;

Francesc Guasch's avatar
Francesc Guasch committed
1085
    my $doc = XML::LibXML->load_xml(string => $self->domain->get_xml_description(Sys::Virt::Domain::XML_INACTIVE))
1086
1087
1088
1089
        or die "ERROR: $!\n";

    my %target;

Francesc Guasch's avatar
Francesc Guasch committed
1090
    my $dev='vd';
1091

1092
1093
1094
1095
    for my $disk ($doc->findnodes('/domain/devices/disk')) {
        for my $child ($disk->childNodes) {
            if ($child->nodeName eq 'target') {
#                die $child->toString();
1096
1097
1098
1099
1100
                my $cur_dev = $child->getAttribute('dev');
                $target{$cur_dev}++;
                if (!$dev && $disk->getAttribute('device') eq 'disk') {
                    ($dev) = $cur_dev =~ /(.*).$/;
                }
1101
1102
1103
            }
        }
    }
Francesc Guasch's avatar
Francesc Guasch committed
1104
    for ('a' .. 'z') {
1105
1106
1107
1108
1109
        my $new = "$dev$_";
        return $new if !$target{$new};
    }
}

Francesc Guasch's avatar
Francesc Guasch committed
1110
1111
# TODO try refactor this replacing by a call to
# return $self->_new_address_xml('slot','0x',2);
1112
1113
1114
sub _new_pci_slot{
    my $self = shift;

Francesc Guasch's avatar
Francesc Guasch committed
1115
    my $doc = XML::LibXML->load_xml(string => $self->domain->get_xml_description(Sys::Virt::Domain::XML_INACTIVE))
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
        or die "ERROR: $!\n";

    my %target;

    for my $name (qw(disk controller interface graphics sound video memballoon)) {
        for my $disk ($doc->findnodes("/domain/devices/$name")) {


            for my $child ($disk->childNodes) {
                if ($child->nodeName eq 'address') {
#                    die $child->toString();
Francesc Guasch's avatar
Francesc Guasch committed
1127
1128
1129
1130
                    my $hex = $child->getAttribute('slot');
                    next if !defined $hex;
                    my $dec = hex($hex);
                    $target{$dec}++;
1131
1132
1133
1134
                }
            }
        }
    }
Francesc Guasch's avatar
Francesc Guasch committed
1135
1136
1137
    for my $dec ( 1 .. 99) {
        next if $target{$dec};
        return sprintf("0x%X", $dec);
1138
1139
1140
    }
}

Francesc Guasch's avatar
Francesc Guasch committed
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
sub _new_address_xml($self, %arg) {

    my $doc = (delete $arg{xml} or XML::LibXML->load_xml(string => $self->domain->get_xml_description(Sys::Virt::Domain::XML_INACTIVE)));
    my $match = delete $arg{match}            or confess "Error: Missing argument match";
    my $prefix = ( delete $arg{prefix} or '');
    my $length = ( delete $arg{length} or 1);
    my $attribute = delete $arg{attribute}    or confess "Error: Missing argument attribute";

    die "Error: Unknown arguments ".Dumper(\%arg) if keys %arg;

    my %used;

    if (!ref($match)) {
        $match = {type => $match }
    }
    for my $device ($doc->findnodes('/domain/devices/*')) {
        for my $child ($device->childNodes) {
            if ($child->nodeName eq 'address') {
                my $found = 1;
                for my $field (keys %$match) {
                    $found = 0 if !defined $child->getAttribute($field)
                    || $child->getAttribute($field) ne $match->{$field}
                }
                if ( $found ) {
                    $used{ $child->getAttribute($attribute) }++
                }
            }
        }
    }
    for my $new ( 0 .. 99) {
        $new = "0$new" while length($new) < $length;
        my $new = $prefix.$new;
        return $new if !$used{$new};
    }
}

1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
=head2 list_volumes

Returns a list of the disk volumes. Each element of the list is a string with the filename.
For KVM it reads from the XML definition of the domain.

    my @volumes = $domain->list_volumes();

=cut

sub list_volumes {
    my $self = shift;
Francesc Guasch's avatar
Francesc Guasch committed
1188
    return $self->disk_device(0,@_);
1189
1190
}

Francesc Guasch's avatar
Francesc Guasch committed
1191
=head2 list_volumes_info
1192
1193
1194
1195

Returns a list of the disk volumes. Each element of the list is a string with the filename.
For KVM it reads from the XML definition of the domain.

Francesc Guasch's avatar
Francesc Guasch committed
1196
    my @volumes = $domain->list_volumes_info();
1197
1198
1199

=cut

Francesc Guasch's avatar
Francesc Guasch committed
1200
sub list_volumes_info {
1201
    my $self = shift;
Francesc Guasch's avatar
Francesc Guasch committed
1202
    return $self->disk_device("info",@_);
1203
1204
}

1205
1206
1207
1208
1209
1210
=head2 screenshot

Takes a screenshot, it stores it in file.

=cut

fv3rdugo's avatar
fv3rdugo committed
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
sub handler {
    my ($stream, $data, $n) = @_;
    my $file_tmp = "/var/tmp/$$.tmp";

    open my $out ,'>>',$file_tmp;
    print $out $data;
    close $out;

    return $n;
}

Francesc Guasch's avatar
Francesc Guasch committed
1222
sub screenshot($self) {
1223
1224
1225
1226
    $self->domain($self->_vm->vm->get_domain_by_name($self->name));
    my $stream = $self->{_vm}->vm->new_stream();

    my $mimetype = $self->domain->screenshot($stream,0);
fv3rdugo's avatar
fv3rdugo committed
1227
    $stream->recv_all(\&handler);
1228

fv3rdugo's avatar
fv3rdugo committed
1229
1230
    my $file_tmp = "/var/tmp/$$.tmp";
    $stream->finish;
1231

Francesc Guasch's avatar
Francesc Guasch committed
1232
1233
1234
    my $file = "$file_tmp.png";
    my $blob_file = $self->_convert_png($file_tmp,$file);
    $self->_data(screenshot => encode_base64($blob_file));
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
    unlink $file_tmp or warn "$! removing $file_tmp";
}

sub _file_screenshot {
    my $self = shift;
    my $doc = XML::LibXML->load_xml(string => $self->_vm->storage_pool->get_xml_description);
    my ($path) = $doc->findnodes('/pool/target/path/text()');
    return "$path/".$self->name.".png";
}

=head2 can_screenshot

Returns if a screenshot of this domain can be taken.

=cut

sub can_screenshot {
    my $self = shift;
    return 1 if $self->_vm();
}

=head2 storage_refresh

Refreshes the internal storage. Used after removing files such as base images.

=cut

sub storage_refresh {
    my $self = shift;
    $self->storage->refresh();
}


=head2 get_info

This is taken directly from Sys::Virt::Domain.

Returns a hash reference summarising the execution state of the
domain. The elements of the hash are as follows:

=over

=item maxMem

The maximum memory allowed for this domain, in kilobytes

=item memory

The current memory allocated to the domain in kilobytes

=item cpu_time

The amount of CPU time used by the domain

=item n_virt_cpu

The current number of virtual CPUs enabled in the domain

=item state

The execution state of the machine, which will be one of the
constants &Sys::Virt::Domain::STATE_*.

=back

=cut

sub get_info {
    my $self = shift;
    my $info = $self->domain->get_info;

    if ($self->is_active) {
        my $mem_stats = $self->domain->memory_stats();
        $info->{actual_ballon} = $mem_stats->{actual_balloon};
    }

Francesc Guasch's avatar
Francesc Guasch committed
1311
1312
1313
1314
1315
1316
1317
    my $doc = XML::LibXML->load_xml(
        string => $self->domain->get_xml_description(Sys::Virt::Domain::XML_INACTIVE));

    my ($mem_node) = $doc->findnodes('/domain/currentMemory/text()');
    my $mem_xml = $mem_node->getData();
    $info->{memory} = $mem_xml if $mem_xml ne $info->{memory};

1318
    $info->{max_mem} = $info->{maxMem};
Francesc Guasch's avatar
Francesc Guasch committed
1319
1320
1321
1322
    ($mem_node) = $doc->findnodes('/domain/memory/text()');
    $mem_xml = $mem_node->getData();
    $info->{max_mem} = $mem_xml if $mem_xml ne $info->{max_mem};

1323
    $info->{cpu_time} = $info->{cpuTime};
Francesc Guasch's avatar
Francesc Guasch committed
1324
1325
    $info->{n_virt_cpu} = $info->{nrVirtCpu};
    confess Dumper($info) if !$info->{n_virt_cpu};
1326
    $info->{ip} = $self->ip()   if $self->is_active();
1327
1328
1329
1330
1331

    lock_keys(%$info);
    return $info;
}

1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
sub _ip_agent($self) {
    my @ip;
    eval { @ip = $self->domain->get_interface_addresses(Sys::Virt::Domain::INTERFACE_ADDRESSES_SRC_AGENT) };
    return if $@ && $@ =~ /^libvirt error code: (74|86),/;
    warn $@ if $@;

    for my $if (@ip) {
        next if $if->{name} =~ /^lo/;
        for my $addr ( @{$if->{addrs}} ) {
            return $addr->{addr}
            if $addr->{type} == 0 && $addr->{addr} !~ /^127\./;
        }
    }
}

1347
1348
1349
1350
1351
sub ip($self) {
    my @ip;
    eval { @ip = $self->domain->get_interface_addresses(Sys::Virt::Domain::INTERFACE_ADDRESSES_SRC_LEASE) };
    warn $@ if $@;
    return $ip[0]->{addrs}->[0]->{addr} if $ip[0];
1352
1353
1354

    return $self->_ip_agent();

1355
1356
}

1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
=head2 set_max_mem

Set the maximum memory for the domain

=cut

sub set_max_mem {
    my $self = shift;
    my $value = shift;

Francesc Guasch's avatar
Francesc Guasch committed
1367
1368
1369
1370
    $self->_set_max_memory_xml($value);
    if ( $self->is_active ) {
        $self->needs_restart(1);
    }
1371

Francesc Guasch's avatar
Francesc Guasch committed
1372
    $self->domain->set_max_memory($value) if !$self->is_active;
1373
1374
1375
1376
1377
1378
1379
1380
1381

}

=head2 get_max_mem

Get the maximum memory for the domain

=cut

Francesc Guasch's avatar
Francesc Guasch committed
1382
1383
sub get_max_mem($self) {
    return $self->get_info->{max_mem};
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
}

=head2 set_memory

Sets the current available memory for the domain

=cut

sub set_memory {
    my $self = shift;
    my $value = shift;

    my $max_mem = $self->get_max_mem();
    confess "ERROR: invalid argument '$value': cannot set memory higher than max memory"
            ." ($max_mem)"
        if $value > $max_mem;

Francesc Guasch's avatar
Francesc Guasch committed
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
    $self->_set_memory_xml($value);

    if ($self->is_active) {

        $self->domain->set_memory($value,Sys::Virt::Domain::MEM_CONFIG);

        $self->domain->set_memory($value,Sys::Virt::Domain::MEM_LIVE);
        $self->domain->set_memory($value,Sys::Virt::Domain::MEM_CURRENT);
        #    $self->domain->set_memory($value,Sys::Virt::Domain::MEMORY_HARD_LIMIT);
        #    $self->domain->set_memory($value,Sys::Virt::Domain::MEMORY_SOFT_LIMIT);
    }
}

sub _set_memory_xml($self, $value) {
    my $doc = XML::LibXML->load_xml(string => $self->domain->get_xml_description);

    my ($mem) = $doc->findnodes('/domain/currentMemory/text()');
    $mem->setData($value);

    my $new_domain = $self->_vm->vm->define_domain($doc->toString);
    $self->domain($new_domain);

}

sub _set_max_memory_xml($self, $value) {
    my $doc = XML::LibXML->load_xml(string => $self->domain->get_xml_description);

    my ($mem) = $doc->findnodes('/domain/memory/text()');
    $mem->setData($value);
1430

Francesc Guasch's avatar
Francesc Guasch committed
1431
1432
    my $new_domain = $self->_vm->vm->define_domain($doc->toString);
    $self->domain($new_domain);
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449

}

=head2 rename

Renames the domain

    $domain->rename("new name");

=cut

sub rename {
    my $self = shift;
    my %args = @_;
    my $new_name = $args{name};

    $self->domain->rename($new_name);
1450
1451
1452
1453
1454
    my $doc = XML::LibXML->load_xml(string => $self->domain->get_xml_description);
    $self->_vm->_xml_add_sysinfo_entry($doc, hostname => $new_name);

    my $new_domain = $self->_vm->vm->define_domain($doc->toString);
    $self->domain($new_domain);
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
}

=head2 disk_size

Returns the size of the domains disk or disks
If an array is expected, it returns the list of disks sizes, if it
expects an scalar returns the first disk as it is asumed to be the main one.


    my $size = $domain->disk_size();

=cut


sub disk_size {
    my $self = shift;
    my @size;
    for my $disk ($self->_disk_devices_xml) {

        my ($source) = $disk->findnodes('source');
        next if !$source;

        my $file = $source->getAttribute('file');
        $file =~ s{.*/}{};

        my $vol;
        eval { $vol = $self->_vm->search_volume($file) };

        warn "I can't find volume in storage. source: $source , file: ".($file or '<UNDEF>')
            if !$vol;
        push @size, ($vol->get_info->{capacity})    if $vol;
    }
    return @size if wantarray;
    return ($size[0] or undef);
}

=pod

Francesc Guasch's avatar
Francesc Guasch committed
1493
1494
=cut

1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515