KVM.pm 30.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
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
use Carp qw(cluck confess croak);
use Data::Dumper;
use File::Copy;
use File::Path qw(make_path);
use Hash::Util qw(lock_keys);
use IPC::Run3 qw(run3);
use Moose;
use Sys::Virt::Stream;
use XML::LibXML;

with 'Ravada::Domain';

has 'domain' => (
      is => 'rw'
    ,isa => 'Sys::Virt::Domain'
    ,required => 1
);

has '_vm' => (
    is => 'ro'
    ,isa => 'Ravada::VM::KVM'
    ,required => 0
);

##################################################
#
our $TIMEOUT_SHUTDOWN = 60;
our $OUT;

our %GET_DRIVER_SUB = (
    network => \&_get_driver_network
     ,sound => \&_get_driver_sound
     ,video => \&_get_driver_video
);
our %SET_DRIVER_SUB = (
    network => \&_set_driver_network
     ,sound => \&_set_driver_sound
     ,video => \&_set_driver_video
);

##################################################


=head2 name

Returns the name of the domain

=cut

sub name {
    my $self = shift;
    $self->{_name} = $self->domain->get_name if !$self->{_name};
    return $self->{_name};
}

=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 = ();

    my $doc = XML::LibXML->load_xml(string => $self->domain->get_xml_description);

    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');
                push @disks,($file);
            }
        }
    }
    return @disks;
}

=head2 remove_disks

Remove the volume files of the domain

=cut

sub remove_disks {
    my $self = shift;

    my $removed = 0;

    return if !$self->is_known();

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

    $self->_vm->connect();
    for my $file ($self->list_disks) {
        if (! -e $file ) {
            warn "WARNING: $file already removed for ".$self->domain->get_name."\n"
                if $0 !~ /.t$/;
            next;
        }
        $self->_vol_remove($file);
        if ( -e $file ) {
            unlink $file or die "$! $file";
        }
        $removed++;

    }

    warn "WARNING: No disk files removed for ".$self->domain->get_name."\n"
            .Dumper([$self->list_disks])
        if !$removed && $0 !~ /\.t$/;

}

sub _vol_remove {
    my $self = shift;
    my $file = shift;
    my $warning = shift;

138
139
    my $name;
    ($name) = $file =~ m{.*/(.*)}   if $file =~ m{/};
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200

    #TODO: do a remove_volume in the VM
    my @vols = $self->_vm->storage_pool->list_volumes();
    for my $vol ( @vols ) {
        $vol->delete() if$vol->get_name eq $name;
    }
    return 1;
}

=head2 remove

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

=cut

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

    if ($self->domain->is_active) {
        $self->_do_force_shutdown();
    }

    $self->remove_disks();
#    warn "WARNING: Problem removing disks for ".$self->name." : $@" if $@ && $0 !~ /\.t$/;

    $self->_remove_file_image();
#    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 $@;

    $self->domain->undefine();
}


sub _remove_file_image {
    my $self = shift;
    for my $file ( $self->list_files_base ) {

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

        chmod 0770, $file or die "$! chmodding $file";
        chown $<,$(,$file    or die "$! chowning $file";
        eval { $self->_vol_remove($file,1) };

        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 $@;
    }
}

sub _disk_device {
    my $self = shift;
201
202
203
    my $with_target = shift;


204
205
206
207
208
209
210
211
212
213
214
    my $doc = XML::LibXML->load_xml(string => $self->domain->get_xml_description)
        or die "ERROR: $!\n";

    my @img;
    my $list_disks = '';

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

        $list_disks .= $disk->toString();

215
        my ($file,$target);
216
217
        for my $child ($disk->childNodes) {
            if ($child->nodeName eq 'source') {
218
219
220
221
                $file = $child->getAttribute('file');
            }
            if ($child->nodeName eq 'target') {
                $target = $child->getAttribute('dev');
222
223
            }
        }
224
225
        push @img,[$file,$target]   if $with_target;
        push @img,($file)           if !$with_target;
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
    }
    if (!scalar @img) {
        my (@devices) = $doc->findnodes('/domain/devices/disk');
        die "I can't find disk device FROM "
            .join("\n",map { $_->toString() } @devices);
    }
    return @img;

}

sub _disk_devices_xml {
    my $self = shift;

    my $doc = XML::LibXML->load_xml(string => $self->domain
                                        ->get_xml_description)
        or die "ERROR: $!\n";

    my @devices;

    for my $disk ($doc->findnodes('/domain/devices/disk')) {
        next if $disk->getAttribute('device') ne '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;
268
    return $self->_disk_device(@_);
269
270
271
272
273
274
275
276
}

sub _create_qcow_base {
    my $self = shift;

    my @base_img;

    my $base_name = $self->name;
277
278
    for  my $vol_data ( $self->list_volumes_target()) {
        my ($file_img,$target) = @$vol_data;
279
280
281
282
283
284
285
286
287
288
289
290
        confess "ERROR: missing $file_img"
            if !-e $file_img;
        my $base_img = $file_img;

        my @cmd;
        $base_img =~ s{\.\w+$}{\.ro.qcow2};
        if ($file_img =~ /\.SWAP\.\w+$/) {
            @cmd = _cmd_copy($file_img, $base_img);
        } else {
            @cmd = _cmd_convert($file_img,$base_img);
        }

291
        push @base_img,([$base_img,$target]);
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385


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

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

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

}

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

    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

=head2 prepare_base

Prepares a base virtual machine with this domain disk

=cut


sub prepare_base {
    my $self = shift;

#    my @img = $self->_create_swap_base();
    my @img = $self->_create_qcow_base();
386
    $self->_store_xml();
387
388
389
    return @img;
}

390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
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);
414
415
    my $xml = $sth->fetchrow;
    return ($xml or $self->domain->get_xml_description);
416
417
}

418
sub _post_remove_base_domain {
419
420
421
422
423
424
425
    my $self = shift;
    my $sth = $self->_dbh->prepare(
        "DELETE FROM base_xml WHERE id_domain=?"
    );
    $sth->execute($self->id);
}

426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
=head2 display

Returns the display URI

=cut

sub display {
    my $self = shift;

    my $xml = XML::LibXML->load_xml(string => $self->domain->get_xml_description);
    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');
    my ($address) = $graph->getAttribute('listen');

    die "Unable to get port for domain ".$self->name
        if !$port;

    return "$type://$address:$port";
}

=head2 is_active

Returns whether the domain is running or not

=cut

sub is_active {
    my $self = shift;
    return ( $self->domain->is_active or 0);
}

=head2 start

Starts the domain

=cut

sub start {
    my $self = shift;
    $self->_set_spice_ip();
    $self->domain->create();
}

Francesc Guasch's avatar
Francesc Guasch committed
472
473
474
475
476
477
478
479
480
481
482
483
484
sub _pre_shutdown_domain {
    my $self = shift;
    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;
        }
    }
485
486
487

    $self->domain->managed_save_remove()
        if $self->domain->has_managed_save_image();
Francesc Guasch's avatar
Francesc Guasch committed
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
514
515
516
517
518
519
520
521
522
523
524
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
=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;
    $self->domain->shutdown();

}

=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;
    $self->_do_force_shutdown();
}

sub _do_force_shutdown {
    my $self = shift;
    return $self->domain->destroy;

}


=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;
    return $self->domain->resume();
}


571
572
573
574
575
576
577
578
579
580
581
=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;
}

582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
=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;
}

610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
=head2 can_hybernate

Returns true (1) for KVM domains

=cut

sub can_hybernate { 1 };

=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 {
    my $self = shift;
    $self->domain->managed_save();
}

633
634
635
636
637
638
639
640
641
642
643
644
645
=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');

=cut

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

646
    my %valid_arg = map { $_ => 1 } ( qw( name size vm xml swap target));
647
648
649
650
651
652
653
654
655

    for my $arg_name (keys %args) {
        confess "Unknown arg $arg_name"
            if !$valid_arg{$arg_name};
    }
#    confess "Missing vm"    if !$args{vm};
    $args{vm} = $self->_vm if !$args{vm};
    confess "Missing name " if !$args{name};
    if (!$args{xml}) {
656
657
        $args{xml} = $Ravada::VM::KVM::DIR_XML."/default-volume.xml";
        $args{xml} = $Ravada::VM::KVM::DIR_XML."/swap-volume.xml"      if $args{swap};
658
659
660
661
662
663
664
665
666
667
668
669
    }

    my $path = $args{vm}->create_volume(
        name => $args{name}
        ,xml =>  $args{xml}
        ,swap => ($args{swap} or 0)
        ,size => ($args{size} or undef)
    );

# TODO check if <target dev="/dev/vda" bus='virtio'/> widhout dev works it out
# change dev=vd*  , slot=*
#
670
    my ($target_dev) = ($args{target} or $self->_new_target_dev());
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
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
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
    my $pci_slot = $self->_new_pci_slot();
    my $driver_type = 'qcow2';
    my $cache = 'default';

    if ( $args{swap} ) {
        $cache = 'none';
        $driver_type = 'raw';
    }

    my $xml_device =<<EOT;
    <disk type='file' device='disk'>
      <driver name='qemu' type='$driver_type' cache='$cache'/>
      <source file='$path'/>
      <backingStore/>
      <target bus='virtio' dev='$target_dev'/>
      <alias name='virtio-disk1'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='$pci_slot' function='0x0'/>
    </disk>
EOT

    eval { $self->domain->attach_device($xml_device,Sys::Virt::Domain::DEVICE_MODIFY_CONFIG) };
    die $@."\n".$self->domain->get_xml_description if$@;
}



sub _new_target_dev {
    my $self = shift;

    my $doc = XML::LibXML->load_xml(string => $self->domain->get_xml_description)
        or die "ERROR: $!\n";

    my %target;

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


        for my $child ($disk->childNodes) {
            if ($child->nodeName eq 'target') {
#                die $child->toString();
                $target{ $child->getAttribute('dev') }++;
            }
        }
    }
    my ($dev) = keys %target;
    $dev =~ s/(.*).$/$1/;
    for ('b' .. 'z') {
        my $new = "$dev$_";
        return $new if !$target{$new};
    }
}

sub _new_pci_slot{
    my $self = shift;

    my $doc = XML::LibXML->load_xml(string => $self->domain->get_xml_description)
        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();
                    $target{ $child->getAttribute('slot') }++
                        if $child->getAttribute('slot');
                }
            }
        }
    }
    for ( 1 .. 99) {
        $_ = "0$_" if length $_ < 2;
        my $new = '0x'.$_;
        return $new if !$target{$new};
    }
}

=head2 BUILD

internal build method

=cut

sub BUILD {
    my $self = shift;
}

=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;
    return $self->disk_device();
}

776
777
778
779
780
781
782
783
784
785
786
787
788
789
=head2 list_volumes_target

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_target();

=cut

sub list_volumes_target {
    my $self = shift;
    return $self->disk_device("target");
}

790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
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
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
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
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
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
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
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
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
=head2 screenshot

Takes a screenshot, it stores it in file.

=cut

sub screenshot {
    my $self = shift;
    my $file = (shift or $self->_file_screenshot);

    my ($path) = $file =~ m{(.*)/};
    make_path($path) if ! -e $path;

    $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);

    my $file_tmp = "$file.tmp";
    my $data;
    my $bytes = 0;
    open my $out, '>', $file_tmp or die "$! $file_tmp";
    while ( my $rv =$stream->recv($data,1024)) {
        $bytes += $rv;
        last if $rv<=0;
        print $out $data;
    }
    close $out;

    $self->_convert_png($file_tmp,$file);
    unlink $file_tmp or warn "$! removing $file_tmp";

    $stream->finish;

    return $bytes;
}

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};
    }

    $info->{max_mem} = $info->{maxMem};
    $info->{memory} = $info->{memory};
    $info->{cpu_time} = $info->{cpuTime};
    $info->{n_virt_cpu} = $info->{nVirtCpu};

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

=head2 set_max_mem

Set the maximum memory for the domain

=cut

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

    confess "ERROR: Requested operation is not valid: domain is already running"
        if $self->domain->is_active();

    $self->domain->set_max_memory($value);

}

=head2 get_max_mem

Get the maximum memory for the domain

=cut

sub get_max_mem {
    return $_[0]->domain->get_max_memory();
}

=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;

    confess "ERROR: Requested operation is not valid: domain is not running"
        if !$self->domain->is_active();

    $self->domain->set_memory($value,Sys::Virt::Domain::MEM_CONFIG);
#    if (!$self->is_active) {
#        $self->domain->set_memory($value,Sys::Virt::Domain::MEM_MAXIMUM);
#        return;
#    }

    $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);
}

=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);
}

=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

sub rename_volumes {
    my $self = shift;
    my $new_dom_name = shift;

    for my $disk ($self->_disk_devices_xml) {

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

        my $volume = $source->getAttribute('file') or next;

        confess "ERROR: Domain ".$self->name
                ." volume '$volume' does not exists"
            if ! -e $volume;

        $self->domain->create if !$self->is_active;
        $self->domain->detach_device($disk);
        $self->domain->shutdown;

        my $cont = 0;
        my $new_volume;
        my $new_name = $new_dom_name;

        for (;;) {
            $new_volume=$volume;
            $new_volume =~ s{(.*)/.*\.(.*)}{$1/$new_name.$2};
            last if !-e $new_volume;
            $cont++;
            $new_name = "$new_dom_name.$cont";
        }
        warn "copy $volume -> $new_volume";
        copy($volume, $new_volume) or die "$! $volume -> $new_volume";
        $source->setAttribute(file => $new_volume);
        unlink $volume or warn "$! removing $volume";
        $self->storage->refresh();
        $self->domain->attach_device($disk);
    }
}

=cut

=head2 spinoff_volumes

Makes volumes indpendent from base

=cut

sub spinoff_volumes {
    my $self = shift;

    $self->_do_force_shutdown() if $self->is_active;

    for my $disk ($self->_disk_devices_xml) {

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

        my $volume = $source->getAttribute('file') or next;

        confess "ERROR: Domain ".$self->name
                ." volume '$volume' does not exists"
            if ! -e $volume;

        #TODO check mktemp or something
        my $volume_tmp  = "$volume.$$.tmp";

        unlink($volume_tmp) or die "ERROR $! removing $volume.tmp"
            if -e $volume_tmp;

        my @cmd = ('qemu-img'
              ,'convert'
              ,'-O','qcow2'
              ,$volume
              ,$volume_tmp
        );
        my ($in, $out, $err);
        run3(\@cmd,\$in,\$out,\$err);
        warn $out  if $out;
        warn $err   if $err;
        die "ERROR: Temporary output file $volume_tmp not created at "
                .join(" ",@cmd)."\n"
            if (! -e $volume_tmp );

        copy($volume_tmp,$volume) or die "$! $volume_tmp -> $volume";
        unlink($volume_tmp) or die "ERROR $! removing $volume_tmp";
    }
}


sub _set_spice_ip {
    my $self = shift;

    my $doc = XML::LibXML->load_xml(string
                            => $self->domain->get_xml_description) ;
    my @graphics = $doc->findnodes('/domain/devices/graphics');

    my $ip = $self->_vm->ip();

    for my $graphics ( $doc->findnodes('/domain/devices/graphics') ) {
        $graphics->setAttribute('listen' => $ip);
        my $listen;
        for my $child ( $graphics->childNodes()) {
            $listen = $child if $child->getName() eq 'listen';
        }
        # we should consider in the future add a new listen if it ain't one
        next if !$listen;
        $listen->setAttribute('address' => $ip);
        $self->domain->update_device($graphics);
    }
}

sub _hwaddr {
    my $self = shift;

    my $doc = XML::LibXML->load_xml(string => $self->domain->get_xml_description);

    my @hwaddr;
    for my $mac( $doc->findnodes("/domain/devices/interface/mac")) {
        push @hwaddr,($mac->getAttribute('address'));
    }
    return @hwaddr;
}

sub _find_base {
    my $self = shift;
    my $file = shift;
    my @cmd = ( 'qemu-img','info',$file);
    my ($in,$out, $err);
    run3(\@cmd,\$in, \$out, \$err);

    my ($base) = $out =~ m{^backing file: (.*)}mi;
    die "No base for $file in $out" if !$base;

    return $base;
}

=head2 clean_swap_volumes

Clean swap volumes. It actually just creates an empty qcow file from the base

=cut

sub clean_swap_volumes {
    my $self = shift;
    for my $file ($self->list_volumes) {
        next if $file !~ /\.SWAP\.\w+/;
        my $base = $self->_find_base($file) or next;

    	my @cmd = ('qemu-img','create'
                ,'-f','qcow2'
                ,'-b',$base
                ,$file
    	);
    	my ($in,$out, $err);
    	run3(\@cmd,\$in, \$out, \$err);
    	die $err if $err;
	}
}

=head2 get_driver

Gets the value of a driver

Argument: name

    my $driver = $domain->get_driver('video');

=cut

sub get_driver {
    my $self = shift;
    my $name = shift;

    my $sub = $GET_DRIVER_SUB{$name};

    die "I can't get driver $name for domain ".$self->name
        if !$sub;

    return $sub->($self);
}

=head2 set_driver

Sets the value of a driver

Argument: name , driver

    my $driver = $domain->set_driver('video','"type="qxl" ram="65536" vram="65536" vgamem="16384" heads="1" primary="yes"');

=cut

sub set_driver {
    my $self = shift;
    my $name = shift;

    my $sub = $SET_DRIVER_SUB{$name};

    die "I can't get driver $name for domain ".$self->name
        if !$sub;

    return $sub->($self,@_);
}

sub _get_driver_generic {
    my $self = shift;
    my $xml_path = shift;

    my @ret;
    my $doc = XML::LibXML->load_xml(string => $self->domain->get_xml_description);

    for my $driver ($doc->findnodes($xml_path)) {
        my $str = $driver->toString;
        $str =~ s{^<model (.*)/>}{$1};
        push @ret,($str);
    }

    return $ret[0] if !wantarray && scalar@ret <2;
    return @ret;
}

sub _get_driver_video {
    my $self = shift;
    return $self->_get_driver_generic('/domain/devices/video/model',@_);
}

sub _get_driver_network {
    my $self = shift;
    return $self->_get_driver_generic('/domain/devices/interface/model',@_);
}

sub _get_driver_sound {
    my $self = shift;
    my $xml_path ="/domain/devices/sound";

    my @ret;
    my $doc = XML::LibXML->load_xml(string => $self->domain->get_xml_description);

    for my $driver ($doc->findnodes($xml_path)) {
        push @ret,('model="'.$driver->getAttribute('model').'"');
    }

    return $ret[0] if !wantarray && scalar@ret <2;
    return @ret;

}

sub _text_to_hash {
    my $text = shift;

    my %ret;

    for my $item (split /\s+/,$text) {
        my ($name, $value) = $item =~ m{(.*?)=(.*)};
        if (!defined $name) {
            warn "I can't find name=value in '$item'";
            next;
        }
        $value =~ s/^"(.*)"$/$1/;
        $ret{$name} = ($value or '');
    }
    return %ret;
}

sub _set_driver_generic {
    my $self = shift;
    my $xml_path= shift;
    my $value_str = shift or confess "Missing value";

    my $doc = XML::LibXML->load_xml(string => $self->domain->get_xml_description);

    my %value = _text_to_hash($value_str);
    for my $video($doc->findnodes($xml_path)) {
        my $old_driver = $video->toString();
        for my $node ($video->findnodes('model')) {
            for my $attrib ( $node->attributes ) {
                my ( $name ) =$attrib =~ /\s*(.*)=/;
                next if !defined $name;
                my $new_value = ($value{$name} or '');
                if ($value{$name}) {
                    $node->setAttribute($name => $value{$name});
                } else {
                    $node->removeAttribute($name);
                }
            }
            for my $name ( keys %value ) {
                $node->setAttribute( $name => $value{$name} );
            }
        }
        return if $old_driver eq $video->toString();
    }
    $self->_vm->connect if !$self->_vm->vm;
    my $new_domain = $self->_vm->vm->define_domain($doc->toString);
    $self->domain($new_domain);

}

sub _set_driver_video {
    my $self = shift;
    return $self->_set_driver_generic('/domain/devices/video',@_);
}

sub _set_driver_network {
    my $self = shift;
    return $self->_set_driver_generic('/domain/devices/interface',@_);
}

sub _set_driver_sound {
    my $self = shift;
#    return $self->_set_driver_generic('/domain/devices/sound',@_);
    my $value_str = shift or confess "Missing value";

    my $doc = XML::LibXML->load_xml(string => $self->domain->get_xml_description);

    my %value = _text_to_hash($value_str);
    for my $node ($doc->findnodes("/domain/devices/sound")) {
        my $old_driver = $node->toString();
        for my $attrib ( $node->attributes ) {
            my ( $name ) =$attrib =~ /\s*(.*)=/;
            next if !defined $name;
            my $new_value = ($value{$name} or '');
            if ($value{$name}) {
                $node->setAttribute($name => $value{$name});
            } else {
                $node->removeAttribute($name);
            }
        }
        for my $name ( keys %value ) {
                $node->setAttribute( $name => $value{$name} );
        }
        return if $old_driver eq $node->toString();
    }
    $self->_vm->connect if !$self->_vm->vm;
    my $new_domain = $self->_vm->vm->define_domain($doc->toString);
    $self->domain($new_domain);

}

1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
=head2 pre_remove

Code to run before removing the domain. It can be implemented in each domain.
It is not expected to run by itself, the remove function calls it before proceeding.
In KVM it removes saved images.

    $domain->pre_remove();  # This isn't likely to be necessary
    $domain->remove();      # Automatically calls the domain pre_remove method

=cut

sub pre_remove {
    my $self = shift;
    $self->domain->managed_save_remove if $self->domain->has_managed_save_image;
}

1371
1;