KVM.pm 24.9 KB
Newer Older
1
2
package Ravada::VM::KVM;

3
use Carp qw(croak carp cluck);
4
use Data::Dumper;
Francesc Guasch's avatar
Francesc Guasch committed
5
use Digest::MD5;
6
7
8
9
10
use Encode;
use Encode::Locale;
use Fcntl qw(:flock O_WRONLY O_EXCL O_CREAT);
use Hash::Util qw(lock_hash);
use IPC::Run3 qw(run3);
11
12
use IO::Interface::Simple;
use JSON::XS;
13
14
15
16
17
18
use LWP::UserAgent;
use Moose;
use Sys::Virt;
use URI;
use XML::LibXML;

19
use Ravada::Domain::KVM;
20
21
use Ravada::NetInterface::KVM;
use Ravada::NetInterface::MacVTap;
22

23
24
25
with 'Ravada::VM';

##########################################################################
26
#
27
28

has vm => (
29
30
#    isa => 'Sys::Virt'
    is => 'rw'
31
    ,builder => '_connect'
32
33
34
35
    ,lazy => 1
);

has storage_pool => (
36
37
#    isa => 'Sys::Virt::StoragePool'
    is => 'rw'
38
39
40
41
    ,builder => '_load_storage_pool'
    ,lazy => 1
);

Francesc Guasch's avatar
Francesc Guasch committed
42
43
44
45
46
47
has type => (
    isa => 'Str'
    ,is => 'ro'
    ,default => 'qemu'
);

48
49
50
51
52
53
54
55
56
57
58
59
60
61
#########################################################################3
#

our $DIR_XML = "etc/xml";

our $DEFAULT_DIR_IMG;
our $XML = XML::LibXML->new();

#-----------
#
# global download vars
#
our ($DOWNLOAD_FH, $DOWNLOAD_TOTAL);

62
63
our $CONNECTOR = \$Ravada::CONNECTOR;

64
##########################################################################
65
 
66

67
sub _connect {
68
69
70
71
72
73
    my $self = shift;

    my $vm;
    confess "undefined host" if !defined $self->host;

    if ($self->host eq 'localhost') {
74
        $vm = Sys::Virt->new( address => $self->type.":///system" , readonly => $self->readonly);
75
    } else {
76
77
78
        $vm = Sys::Virt->new( address => $self->type."+ssh"."://".$self->host."/system"
                              ,readonly => $self->mode
                          );
79
    }
80
#    $vm->register_close_callback(\&_reconnect);
81
82
83
    return $vm;
}

84
85
86
87
88
89
90
91
92
93
=head2 disconnect

Disconnect from the Virtual Machine Manager

=cut

sub disconnect {
    my $self = shift;

    $self->storage_pool(undef);
94
    $self->vm(undef);
95
96
}

97
=head2 connect
98

99
Connect to the Virtual Machine Manager
100
101
102

=cut

103
sub connect {
104
    my $self = shift;
105
106
    return if $self->vm;

107
    $self->vm($self->_connect);
108
    $self->storage_pool($self->_load_storage_pool);
109
110
}

111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
sub _load_storage_pool {
    my $self = shift;

    my $vm_pool;

    for my $pool ($self->vm->list_storage_pools) {
        my $doc = $XML->load_xml(string => $pool->get_xml_description);

        my ($path) =$doc->findnodes('/pool/target/path/text()');
        next if !$path;

        $DEFAULT_DIR_IMG = $path;
        $vm_pool = $pool;
    }
    die "I can't find /pool/target/path in the storage pools xml\n"
        if !$vm_pool;

    return $vm_pool;

}

132
133
134
135
136
137
=head2 dir_img

Returns the directory where disk images are stored in this Virtual Manager

=cut

138
sub dir_img {
139
140
141
142
    my $self = shift;
    return $DEFAULT_DIR_IMG if $DEFAULT_DIR_IMG;
    
    $self->_load_storage_pool();
143
144
145
    return $DEFAULT_DIR_IMG;
}

146
147
148
149
150
151
152
153
154
155
=head2 create_domain

Creates a domain.

    $dom = $vm->create_domain(name => $name , id_iso => $id_iso);
    $dom = $vm->create_domain(name => $name , id_base => $id_base);

=cut

sub create_domain {
156
157
    my $self = shift;
    my %args = @_;
Francesc Guasch's avatar
Francesc Guasch committed
158
159

    $args{active} = 1 if !defined $args{active};
160
161
    
    croak "argument name required"       if !$args{name};
162
    croak "argument id_owner required"   if !$args{id_owner};
163
    croak "argument id_iso or id_base required ".Dumper(\%args)
164
165
        if !$args{id_iso} && !$args{id_base};

166
    my $domain;
167
    if ($args{id_iso}) {
168
169
170
        $domain = $self->_domain_create_from_iso(@_);
    } elsif($args{id_base}) {
        $domain = $self->_domain_create_from_base(@_);
171
172
173
    } else {
        confess "TODO";
    }
174
175
176
177
178
179
180
181
182
183
184
185
186
187

    return $domain;
}

=head2 search_domain

Returns true or false if domain exists.

    $domain = $vm->search_domain($domain_name);

=cut

sub search_domain {
    my $self = shift;
fv3rdugo's avatar
fv3rdugo committed
188
    my $name = shift or confess "Missing name";
189

190
    $self->connect();
191
192
    my @all_domains;
    eval { @all_domains = $self->vm->list_all_domains() };
193
    confess $@ if $@;
194
195
196

    for my $dom (@all_domains) {
        next if $dom->get_name ne $name;
197
198

        my $domain;
199
200
201
202
203
204

        my @args_create = ();
        @args_create = ( storage => $self->storage_pool
                    ,_vm => $self)
        if !$self->readonly;

205
206
        eval {
            $domain = Ravada::Domain::KVM->new(
207
                domain => $dom
Francesc Guasch's avatar
Francesc Guasch committed
208
                ,readonly => $self->readonly
209
                ,@args_create
210
211
212
            );
        };
        warn $@ if $@;
213
214
215
        if ($domain) {
            return $domain;
        }
216
    }
217
    return;
218
219
}

Francesc Guasch's avatar
Francesc Guasch committed
220

221
222
223
224
225
226
227
228
229
230
231
232
=head2 list_domains

Returns a list of the created domains

  my @list = $vm->list_domains();

=cut

sub list_domains {
    my $self = shift;

    my @list;
233
234
    my @domains = $self->vm->list_all_domains();
    for my $name (@domains) {
235
        my $domain ;
236
        my $id;
237
        $domain = Ravada::Domain::KVM->new(
238
239
                          domain => $name
                        ,storage => $self->storage_pool
240
                        ,_vm => $self
241
242
243
        );
        next if !$domain->is_known();
        $id = $domain->id();
244
        warn $@ if $@ && $@ !~ /No DB info/i;
245
        push @list,($domain) if $domain && $id;
246
247
248
249
    }
    return @list;
}

250
251
252
253
254
255
256
257
258
259
=head2 create_volume

Creates a new storage volume. It requires a name and a xml template file defining the volume

   my $vol = $vm->create_volume($name, $file_xml);

=cut

sub create_volume {
    my $self = shift;
260
261
    my ($name, $file_xml, $size) = @_;

262
263
    confess "Missing volume name"   if !$name;
    confess "Missing xml template"  if !$file_xml;
264
    confess "Invalid size"          if defined $size && ( $size == 0 || $size !~ /^\d+$/);
265
266
267
268

    open my $fh,'<', $file_xml or die "$! $file_xml";
    my $dir_img = $DEFAULT_DIR_IMG;

269
270
271
    my $doc;
    eval { $doc = $XML->load_xml(IO => $fh) };
    die "ERROR reading $file_xml $@"    if $@;
272
273
274
275
276
277

    $doc->findnodes('/volume/name/text()')->[0]->setData("$name.img");
    $doc->findnodes('/volume/key/text()')->[0]->setData("$dir_img/$name.img");
    $doc->findnodes('/volume/target/path/text()')->[0]->setData(
                "$dir_img/$name.img");

278
    if ($size) {
279
        my ($prev_size) = $doc->findnodes('/volume/capacity/text()')->[0]->getData();
280
        confess "Size '$size' too small" if $size < 1024*512;
281
        $doc->findnodes('/volume/allocation/text()')->[0]->setData(int($size*0.9));
282
283
        $doc->findnodes('/volume/capacity/text()')->[0]->setData($size);
    }
284
285
286
287
    my $vol = $self->storage_pool->create_volume($doc->toString);
    warn "volume $dir_img/$name.img does not exists after creating volume"
            if ! -e "$dir_img/$name.img";
    return "$dir_img/$name.img";
288
289
290

}

291
292
293
294
295
296
297
298
299
300
301
302
303
304
=head2 search_volume

Searches a volume

    my $vol =$vm->search_volume($name);

=cut

sub search_volume {
    my $self = shift;
    my $name = shift or confess "Missing volume name";

    my $vol;
    eval { $vol = $self->storage_pool->get_volume_by_name($name) };
305
    die $@ if $@;
306

307
308
309
    return $vol;
}

310
311
312
313
sub _domain_create_from_iso {
    my $self = shift;
    my %args = @_;

314
    for (qw(id_iso id_owner name)) {
315
316
317
        croak "argument $_ required" 
            if !$args{$_};
    }
318

319
320
321
    die "Domain $args{name} already exists"
        if $self->search_domain($args{name});

322
323
324
325
326
    my $vm = $self->vm;
    my $storage = $self->storage_pool;

    my $iso = $self->_search_iso($args{id_iso});

327
328
329
    die "ERROR: Empty field 'xml_volume' in iso_image ".Dumper($iso)
        if !$iso->{xml_volume};

330
    my $device_cdrom = _iso_name($iso);
331

332
333
334
    my $disk_size = $args{disk} if $args{disk};
    my $device_disk = $self->create_volume($args{name}, $DIR_XML."/".$iso->{xml_volume}
                                            , $disk_size);
335
336
337

    my $xml = $self->_define_xml($args{name} , "$DIR_XML/$iso->{xml}");

338
339
    $self->_xml_modify_memory($xml,$args{memory})   if $args{memory};

340
    _xml_modify_cdrom($xml, $device_cdrom);
341
    _xml_modify_disk($xml, [$device_disk])    if $device_disk;
342
#    $self->_xml_modify_usb($xml);
343

344
345
    $self->_xml_modify_network($xml , $args{network})   if $args{network};

346
    my $dom = $self->vm->define_domain($xml->toString());
Francesc Guasch's avatar
Francesc Guasch committed
347
    $dom->create if $args{active};
348

349
    my $domain = Ravada::Domain::KVM->new(domain => $dom , storage => $self->storage_pool
350
                , _vm => $self
351
    );
352

353
    $domain->_insert_db(name => $args{name}, id_owner => $args{id_owner});
354
    return $domain;
355
}
356
357
358
359
360
361
362
363
364
365
366
367
368
sub _create_disk {
    return _create_disk_qcow2(@_);
}

sub _create_disk_qcow2 {
    my $self = shift;
    my ($base, $name) = @_;

    confess "Missing base" if !$base;
    confess "Missing name" if !$name;

    my $dir_img  = $DEFAULT_DIR_IMG;

369
    my @files_out;
370

371
    for my $file_base ( $base->list_files_base ) {
372
        my $file_out = $file_base;
373
        $file_out =~ s/\.ro\.\w+$//;
374
        $file_out .= ".$name.qcow2";
375

376
        my @cmd = ('qemu-img','create'
377
                ,'-f','qcow2'
378
                ,"-b", $file_base
379
                ,$file_out
380
        );
381
#    warn join(" ",@cmd)."\n";
382

383
384
385
386
        my ($in, $out, $err);
        run3(\@cmd,\$in,\$out,\$err);
        print $out  if $out;
        warn $err   if $err;
387

388
389
390
391
392
        if (! -e $file_out) {
            warn "ERROR: Output file $file_out not created at ".join(" ",@cmd)."\n";
            exit;
        }
        push @files_out,($file_out);
393
    }
394
    return @files_out;
395
396
397
398
399
400
401
    
}

sub _search_domain_by_id {
    my $self = shift;
    my $id = shift;

402
    my $sth = $$CONNECTOR->dbh->prepare("SELECT * FROM domains WHERE id=?");
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
    $sth->execute($id);
    my $row = $sth->fetchrow_hashref;
    $sth->finish;

    return $self->search_domain($row->{name});
}

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

    confess "argument id_base or base required ".Dumper(\%args) 
        if !$args{id_base} && !$args{base};

    die "Domain $args{name} already exists"
        if $self->search_domain($args{name});

    my $base = $args{base}  if $args{base};

    $base = $self->_search_domain_by_id($args{id_base}) if $args{id_base};
423
    confess "Unknown base id: $args{id_base}" if !$base;
424
425
426

    my $vm = $self->vm;
    my $storage = $self->storage_pool;
427

428
    my $xml = XML::LibXML->load_xml(string => $base->domain->get_xml_description());
429

430
    my @device_disk = $self->_create_disk($base, $args{name});
Francesc Guasch's avatar
Francesc Guasch committed
431
432
#    _xml_modify_cdrom($xml);
    _xml_remove_cdrom($xml);
433
434
435
    my ($node_name) = $xml->findnodes('/domain/name/text()');
    $node_name->setData($args{name});

436
    _xml_modify_disk($xml, \@device_disk);
437
438
    $self->_xml_modify_mac($xml);
    $self->_xml_modify_uuid($xml);
439
    $self->_xml_modify_spice_port($xml);
440
    _xml_modify_video($xml);
441
    $self->_xml_modify_usb($xml);
442

443
    $self->_fix_slots($xml);
444
445
446
447
448

    open my $out,'>',"/var/tmp/$args{name}.xml" or die $!;
    print $out $xml->toString();
    close $out;

449
    my $dom = $self->vm->define_domain($xml->toString());
450
    $dom->create();
451

452
453
    my $domain = Ravada::Domain::KVM->new(domain => $dom , storage => $self->storage_pool
        , _vm => $self);
454

455
    $domain->_insert_db(name => $args{name}, id_base => $base->id, id_owner => $args{id_owner});
456
    return $domain;
457
}
458
459
460

sub _iso_name {
    my $iso = shift;
461

462
    my ($iso_name) = $iso->{url} =~ m{.*/(.*)};
463
464
    $iso_name = $iso->{url} if !$iso_name;

465
466
    my $device = "$DEFAULT_DIR_IMG/$iso_name";

Francesc Guasch's avatar
Francesc Guasch committed
467
468
469
    confess "Missing MD5 field on table iso_images FOR $iso->{url}"
        if !$iso->{md5};

470
471
472
    if (! -e $device || ! -s $device) {
        _download_file_external($iso->{url}, $device);
    }
Francesc Guasch's avatar
Francesc Guasch committed
473
474
    confess "Download failed, MD5 missmatched"
            if (! _check_md5($device, $iso->{md5}));
475
476
477
    return $device;
}

Francesc Guasch's avatar
Francesc Guasch committed
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
sub _check_md5 {
    my ($file, $md5 ) =@_;

    my  $ctx = Digest::MD5->new;
    open my $in,'<',$file or die "$! $file";
    $ctx->addfile($in);

    my $digest = $ctx->hexdigest;

    return 1 if $digest eq $md5;

    warn "$file MD5 fails\n"
        ." got  : $digest\n"
        ."expecting: $md5\n"
        ;
    return 0;
}

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
sub _download_file_lwp_progress {
    my( $data, $response, $proto ) = @_;
    print $DOWNLOAD_FH $data; # write data to file
    $DOWNLOAD_TOTAL += length($data);
    my $size = $response->header('Content-Length');
    warn floor(($DOWNLOAD_TOTAL/$size)*100),"% downloaded\n"; # print percent downloaded
}

sub _download_file_lwp {
    my ($url_req, $device) = @_;

    unlink $device or die "$! $device" if -e $device;

    $DOWNLOAD_FH = undef;
    $DOWNLOAD_TOTAL = 0;
    sysopen($DOWNLOAD_FH, $device, O_WRONLY|O_EXCL|O_CREAT) ||
		      die "Can't open $device $!";

    my $ua = LWP::UserAgent->new(keep_alive => 1);

    my $url = URI->new(decode(locale => $url_req)) or die "Error decoding $url_req";
    warn $url;

    my $res = $ua->request(HTTP::Request->new(GET => $url)
        ,sub {
            my ($data, $response) = @_;

            unless (fileno $DOWNLOAD_FH) {
                open $DOWNLOAD_FH,">",$device || die "Can't open $device $!\n";
            }
            binmode($DOWNLOAD_FH);
            print $DOWNLOAD_FH $data or die "Can't write to $device: $!\n";
            $DOWNLOAD_TOTAL += length($data);
            my $size = $response->header('Content-Length');
            warn floor(($DOWNLOAD_TOTAL/$size)*100),"% downloaded\n"; # print percent downloaded
        }
    );
    close $DOWNLOAD_FH or die "$! $device";

    close $DOWNLOAD_FH if fileno($DOWNLOAD_FH);
    $DOWNLOAD_FH = undef;

    warn $res->status_line;
}

sub _download_file_external {
    my ($url,$device) = @_;
543
    my @cmd = ("/usr/bin/wget",,'--quiet',$url,'-O',$device);
544
545
546
547
    my ($in,$out,$err) = @_;
    warn join(" ",@cmd)."\n";
    run3(\@cmd,\$in,\$out,\$err);
    print $out if $out;
548
549
    chmod 0755,$device or die "$! chmod 0755 $device"
        if -e $device;
550
551
552
553
554
555
556
    die $err if $err;
}

sub _search_iso {
    my $self = shift;
    my $id_iso = shift or croak "Missing id_iso";

557
    my $sth = $$CONNECTOR->dbh->prepare("SELECT * FROM iso_images WHERE id = ?");
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
    $sth->execute($id_iso);
    my $row = $sth->fetchrow_hashref;
    die "Missing iso_image id=$id_iso" if !keys %$row;
    return $row;
}

###################################################################################
#
# XML methods
#

sub _define_xml {
    my $self = shift;
    my ($name, $xml_source) = @_;
    my $doc = $XML->parse_file($xml_source) or die "ERROR: $! $xml_source\n";

        my ($node_name) = $doc->findnodes('/domain/name/text()');
    $node_name->setData($name);

    $self->_xml_modify_mac($doc);
    $self->_xml_modify_uuid($doc);
579
    $self->_xml_modify_spice_port($doc);
580
581
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
    _xml_modify_video($doc);

    return $doc;

}

sub _xml_modify_video {
    my $doc = shift;

    my ( $video , $video2 ) = $doc->findnodes('/domain/devices/video/model');
    ( $video , $video2 ) = $doc->findnodes('/domain/devices/video')
        if !$video;

    die "I can't find video in "
                .join("\n"
                     ,map { $_->toString() } $doc->findnodes('/domain/devices/video'))
        if !$video;
    $video->setAttribute(type => 'qxl');
    $video->setAttribute( ram => 65536 );
    $video->setAttribute( vram => 65536 );
    $video->setAttribute( vgamem => 16384 );
    $video->setAttribute( heads => 1 );
    
    warn "WARNING: more than one video card found\n".
        $video->toString().$video2->toString()  if $video2;

}

sub _xml_modify_spice_port {
609
610
    my $self = shift;
    my $doc = shift or confess "Missing XML doc";
611
612
613
614
615

    my ($graph) = $doc->findnodes('/domain/devices/graphics') 
        or die "ERROR: I can't find graphic";
    $graph->setAttribute(type => 'spice');
    $graph->setAttribute(autoport => 'yes');
616
    $graph->setAttribute(listen=> $self->ip() );
617
618
619
620
621
622
623
624

    my ($listen) = $doc->findnodes('/domain/devices/graphics/listen');

    if (!$listen) {
        $listen = $graph->addNewChild(undef,"listen");
    }

    $listen->setAttribute(type => 'address');
625
    $listen->setAttribute(address => $self->ip());
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661

}

sub _xml_modify_uuid {
    my $self = shift;
    my $doc = shift;
    my ($uuid) = $doc->findnodes('/domain/uuid/text()');

    random:while (1) {
        my $new_uuid = _new_uuid($uuid);
        next if $new_uuid eq $uuid;
        for my $dom ($self->vm->list_all_domains) {
            next random if $dom->get_uuid_string eq $new_uuid;
        }
        $uuid->setData($new_uuid);
        last;
    }
}

sub _xml_modify_cdrom {
    my ($doc, $iso) = @_;

    my @nodes = $doc->findnodes('/domain/devices/disk');
    for my $disk (@nodes) {
        next if $disk->getAttribute('device') ne 'cdrom';
        for my $child ($disk->childNodes) {
            if ($child->nodeName eq 'source') {
                $child->setAttribute(file => $iso);
                return;
            }
        }

    }
    die "I can't find CDROM on ". join("\n",map { $_->toString() } @nodes);
}

662
663
664
665
666
667
668
sub _xml_modify_memory {
    my $self = shift;
     my $doc = shift;
  my $memory = shift;

    my $found++;
    my ($mem) = $doc->findnodes('/domain/currentMemory/text()');
669
    $mem->setData($memory);
670
671
672
673
674
675

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

}

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
sub _xml_modify_network {
    my $self = shift;
     my $doc = shift;
    my $network = shift;

    my ($type, $source );
    if (ref($network) =~ /^Ravada/) {
        ($type, $source) = ($network->type , $network->source);
    } else {
        $network = decode_json($network);
        ($type, $source) = ($network->{type} , $network->{source});
    }

    confess "Unknown network type " if !defined $type;
    confess "Unknown network xml_source" if !defined $source;

    my @interfaces = $doc->findnodes('/domain/devices/interface');
    if (scalar @interfaces>1) {
        warn "WARNING: ".scalar @interfaces." found, changing the first one";
    }
    my $if = $interfaces[0];
    $if->setAttribute(type => $type);

    my ($node_source) = $if->findnodes('./source');
    $node_source->removeAttribute('network');
    for my $field (keys %$source) {
        $node_source->setAttribute($field => $source->{$field});
    }
}

706
707
708
709
710
711
712
713
714
715
sub _fix_slots {
    my $self = shift;
    my $doc = shift;

    my %slot;
    for my $item ($doc->findnodes('/domain/devices/*')) {
        for my $node ($item->childNodes()) {
            next if $node->nodeName ne 'address';
            my $slot = $node->getAttribute('slot');
            my $function = $node->getAttribute('slot');
716
            next if !defined $slot || !defined $function;
717
            if ($slot{$slot}->{$function}) {
718
                warn "Conflict of slot $slot , function $function";
719
720
721
722
723
724
            }
        }
    }
    return %slot;
}

725
726
727
728
sub _xml_modify_usb {
    my $self = shift;
     my $doc = shift;

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
    for my $ctrl ($doc->findnodes('/domain/devices/controller')) {
        next if $ctrl->getAttribute('type') ne 'usb';
        $ctrl->setAttribute(model => 'ich9-ehci1');

        for my $child ($ctrl->childNodes) {
            if ($child->nodeName eq 'address') {
                $child->setAttribute(slot => '0x08');
                $child->setAttribute(function => '0x7');
            }
        }
    }
    my ($devices) = $doc->findnodes('/domain/devices');

    $self->_xml_add_usb_uhci1($devices);
    $self->_xml_add_usb_uhci2($devices);
    $self->_xml_add_usb_uhci3($devices);

    $self->_xml_add_usb_redirect($devices);

}

sub _xml_add_usb_redirect {
    my $self = shift;
    my $devices = shift;

    my $dev = $devices->addNewChild(undef,'redirdev');
    $dev->setAttribute( bus => 'usb');
    $dev->setAttribute(type => 'spicevmc');

}

sub _xml_add_usb_uhci1 {
    my $self = shift;
    my $devices = shift;
764

765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
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
    # USB uhci1
    my $controller = $devices->addNewChild(undef,"controller");
    $controller->setAttribute(type => 'usb');
    $controller->setAttribute(index => '0');
    $controller->setAttribute(model => 'ich9-uhci1');

    my $master = $controller->addNewChild(undef,'master');
    $master->setAttribute(startport => 0);

    my $address = $controller->addNewChild(undef,'address');
    $address->setAttribute(type => 'pci');
    $address->setAttribute(domain => '0x0000');
    $address->setAttribute(bus => '0x00');
    $address->setAttribute(slot => '0x08');
    $address->setAttribute(function => '0x0');
    $address->setAttribute(multifunction => 'on');
}

sub _xml_add_usb_uhci2 {
    my $self = shift;
    my $devices = shift;

    # USB uhci2
    my $controller = $devices->addNewChild(undef,"controller");
    $controller->setAttribute(type => 'usb');
    $controller->setAttribute(index => '0');
    $controller->setAttribute(model => 'ich9-uhci2');

    my $master = $controller->addNewChild(undef,'master');
    $master->setAttribute(startport => 2);

    my $address = $controller->addNewChild(undef,'address');
    $address->setAttribute(type => 'pci');
    $address->setAttribute(domain => '0x0000');
    $address->setAttribute(bus => '0x00');
    $address->setAttribute(slot => '0x08');
    $address->setAttribute(function => '0x1');
}

sub _xml_add_usb_uhci3 {
    my $self = shift;
    my $devices = shift;

    # USB uhci2
    my $controller = $devices->addNewChild(undef,"controller");
    $controller->setAttribute(type => 'usb');
    $controller->setAttribute(index => '0');
    $controller->setAttribute(model => 'ich9-uhci3');

    my $master = $controller->addNewChild(undef,'master');
    $master->setAttribute(startport => 4);

    my $address = $controller->addNewChild(undef,'address');
    $address->setAttribute(type => 'pci');
    $address->setAttribute(domain => '0x0000');
    $address->setAttribute(bus => '0x00');
    $address->setAttribute(slot => '0x08');
    $address->setAttribute(function => '0x2');

}

826
827


Francesc Guasch's avatar
Francesc Guasch committed
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
sub _xml_remove_cdrom {
    my $doc = shift;

    my ($node_devices )= $doc->findnodes('/domain/devices');
    my $devices = $doc->findnodes('/domain/devices');
    for my $context ($devices->get_nodelist) {
        for my $disk ($context->findnodes('./disk')) {
#            warn $node->toString();
            if ( $disk->nodeName eq 'disk'
                && $disk->getAttribute('device') eq 'cdrom') {

                my ($source) = $disk->findnodes('./source');
                if ($source) {
#                    warn "\n\t->removing ".$source->nodeName." ".$source->getAttribute('file')
#                        ."\n";
                    $disk->removeChild($source);
                }
            }
        }
    }
}

850
851
852
853
854
855
856
857
858
859
860
861
862
863
sub _xml_modify_disk {
    my $doc = shift;
    my $device = shift          or confess "Missing device";

#  <source file="/var/export/vmimgs/ubuntu-mate.img" dev="/var/export/vmimgs/clone01.qcow2"/>

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

        for my $child ($disk->childNodes) {
            if ($child->nodeName eq 'driver') {
                $child->setAttribute(type => 'qcow2');
            } elsif ($child->nodeName eq 'source') {
864
865
866
                my $new_device = $device->[$cont++] or confess "Missing device $cont "
                    .Dumper($device);
                $child->setAttribute(file => $new_device);
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
            }
        }
    }

}

sub _unique_mac {
    my $self = shift;

    my $mac = shift;

    $mac = lc($mac);

    for my $dom ($self->vm->list_all_domains) {
        my $doc = $XML->load_xml(string => $dom->get_xml_description()) or die "ERROR: $!\n";

        for my $nic ( $doc->findnodes('/domain/devices/interface/mac')) {
            my $nic_mac = $nic->getAttribute('address');
            return 0 if $mac eq lc($nic_mac);
        }
    }
    return 1;
}

sub _new_uuid {
    my $uuid = shift;
    
    my ($principi, $f1,$f2) = $uuid =~ /(.*)(.)(.)/;

    return $principi.int(rand(10)).int(rand(10));
    
}

sub _xml_modify_mac {
    my $self = shift;
902
    my $doc = shift or confess "Missing XML doc";
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921

    my ($if_mac) = $doc->findnodes('/domain/devices/interface/mac')
        or exit;
    my $mac = $if_mac->getAttribute('address');

    my @macparts = split/:/,$mac;

    my $new_mac;
    for my $last ( 0 .. 99 ) {
        $last = "0$last" if length($last)<2;
        $macparts[-1] = $last;
        $new_mac = join(":",@macparts);
        last if $self->_unique_mac($new_mac);
        $new_mac = undef;
    }
    die "I can't find a new unique mac" if !$new_mac;
    $if_mac->setAttribute(address => $new_mac);
}

922
923
924
925
926
927
928
929
930
=head2 list_networks

Returns a list of networks known to this VM. Each element is a Ravada::NetInterface object

=cut

sub list_networks {
    my $self = shift;
    
931
    $self->connect() if !$self->vm;
932
933
934
935
    my @nets = $self->vm->list_all_networks();
    my @ret_nets;

    for my $net (@nets) {
936
        push @ret_nets ,( Ravada::NetInterface::KVM->new( name => $net->get_name ) );
937
938
939
940
    }

    for my $if (IO::Interface::Simple->interfaces) {
        next if $if->is_loopback();
941
942
        next if !$if->address();
        next if $if =~ /virbr/i;
943
944
945
946
947
948

        # that should catch bridges
        next if $if->hwaddr =~ /^[00:]+00$/;

        push @ret_nets, ( Ravada::NetInterface::MacVTap->new(interface => $if));
    }
949
950

    $self->vm(undef);
951
952
953
    return @ret_nets;
}

954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
=head2 import_domain

Imports a KVM domain in Ravada

    my $domain = $vm->import_domain($name, $user);

=cut

sub import_domain {
    my $self = shift;
    my ($name, $user) = @_;

    my $domain_kvm = $self->vm->get_domain_by_name($name);
    confess "ERROR: unknown domain $name in KVM" if !$domain_kvm;

    my $domain = Ravada::Domain::KVM->new(
                      _vm => $self
                  ,domain => $domain_kvm 
                , storage => $self->storage_pool
    );

    $domain->_insert_db(name => $name, id_owner => $user->id);
976

977
978
979
    return $domain;
}

980
1;