KVM.pm 62.1 KB
Newer Older
joelalju's avatar
joelalju committed
1

2
3
package Ravada::VM::KVM;

4
5
6
7
8
9
10
11
12
use warnings;
use strict;

=head1 NAME

Ravada::VM::KVM - KVM Virtual Managers library for Ravada

=cut

13
14
15
16
17
use Carp qw(croak carp cluck);
use Data::Dumper;
use Digest::MD5;
use Encode;
use Encode::Locale;
18
use File::Path qw(make_path);
19
20
21
22
23
use Fcntl qw(:flock O_WRONLY O_EXCL O_CREAT);
use Hash::Util qw(lock_hash);
use IPC::Run3 qw(run3);
use IO::Interface::Simple;
use JSON::XS;
24
use Mojo::DOM;
25
use Mojo::UserAgent;
26
27
28
29
30
use Moose;
use Sys::Virt;
use URI;
use XML::LibXML;

Francesc Guasch's avatar
Francesc Guasch committed
31
32
33
use feature qw(signatures);
no warnings "experimental::signatures";

34
35
36
use Ravada::Domain::KVM;
use Ravada::NetInterface::KVM;
use Ravada::NetInterface::MacVTap;
37
use Ravada::Utils;
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53

with 'Ravada::VM';

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

has vm => (
#    isa => 'Sys::Virt'
    is => 'rw'
    ,builder => '_connect'
    ,lazy => 1
);

has type => (
    isa => 'Str'
    ,is => 'ro'
54
    ,default => 'KVM'
55
56
57
58
59
);

#########################################################################3
#

60
#TODO use config file for DIR_XML
61
our $DIR_XML = "etc/xml";
62
$DIR_XML = "/var/lib/ravada/xml/" if $0 =~ m{^/usr/sbin};
63

Francesc Guasch's avatar
Francesc Guasch committed
64
65
our $FILE_CONFIG_QEMU = "/etc/libvirt/qemu.conf";

66
67
68
69
70
71
72
73
74
75
our $XML = XML::LibXML->new();

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

our $CONNECTOR = \$Ravada::CONNECTOR;

Francesc Guasch's avatar
Francesc Guasch committed
76
77
78
our $WGET = `which wget`;
chomp $WGET;

79
80
81
our $BRCTL = `which brctl`;
chomp $BRCTL;

82
our $CACHE_DOWNLOAD = 1;
Francesc Guasch's avatar
Francesc Guasch committed
83
our $VERIFY_ISO = 1;
Francesc Guasch's avatar
Francesc Guasch committed
84

Francesc Guasch's avatar
Francesc Guasch committed
85
our %_CREATED_DEFAULT_STORAGE = ();
86
87
88
89
90
91
92
93
94
##########################################################################


sub _connect {
    my $self = shift;

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

95
96
97
    my $con_type = $self->type;
    $con_type = 'qemu' if $self->type eq 'KVM';

98
    if ($self->host eq 'localhost') {
99
        $vm = Sys::Virt->new( address => $con_type.":///system" , readonly => $self->readonly);
100
    } else {
101
102
        confess "Error: You can't connect to remote VMs in readonly mode"
            if $self->readonly;
103
        my $transport = 'ssh';
104
105
106
        my $address = $con_type."+".$transport
                                            ."://".'root@'.$self->host
                                            ."/system";
107
        eval {
108
109
            $vm = Sys::Virt->new(
                                address => $address
110
111
112
113
114
                              ,auth => 1
                              ,credlist => [
                                  Sys::Virt::CRED_AUTHNAME,
                                  Sys::Virt::CRED_PASSPHRASE,
                              ]
115
                          );
116
         };
117
         confess $@ if $@;
118
    }
Francesc Guasch's avatar
Francesc Guasch committed
119
120
    if ( ! $vm->list_storage_pools && !$_CREATED_DEFAULT_STORAGE{$self->host}) {
	    warn "WARNING: No storage pools creating default\n";
121
    	$self->_create_default_pool($vm);
Francesc Guasch's avatar
Francesc Guasch committed
122
        $_CREATED_DEFAULT_STORAGE{$self->host}++;
123
    }
124
    $self->_check_networks($vm);
125
126
127
    return $vm;
}

128
129
130
131
132
133
134
135
136
137
138
139
140
sub _check_networks {
    my $self = shift;
    my $vm = shift;

    for my $net ($vm->list_all_networks) {
        next if $net->is_active;

        warn "INFO: Activating KVM network ".$net->get_name."\n";
        $net->create;
        $net->set_autostart(1);
    }
}

141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
=head2 disconnect

Disconnect from the Virtual Machine Manager

=cut

sub disconnect {
    my $self = shift;

    $self->vm(undef);
}

=head2 connect

Connect to the Virtual Machine Manager

=cut

sub connect {
    my $self = shift;
161
    return 1 if $self->vm;
162
    return 1 if $self->is_alive;
163

164
    return $self->vm($self->_connect);
165
166
167
#    $self->storage_pool($self->_load_storage_pool);
}

168
169
170
171
172
sub _reconnect($self) {
    $self->vm(undef);
    return $self->connect();
}

173
174
175
sub _load_storage_pool {
    my $self = shift;

176
177
    confess "no hi ha vm" if !$self->vm;

178
179
180
    my $vm_pool;
    my $available;

Francesc Guasch's avatar
Francesc Guasch committed
181
    if ($self->default_storage_pool_name) {
182
183
184
185
        return( $self->vm->get_storage_pool_by_name($self->default_storage_pool_name)
            or confess "ERROR: Unknown storage pool: ".$self->default_storage_pool_name);
    }

186
187
188
    for my $pool ($self->vm->list_storage_pools) {
        my $info = $pool->get_info();
        next if defined $available
189
                && $info->{available} <= $available;
190
191
192
193
194
195
196
197
198
199

        my $doc = $XML->load_xml(string => $pool->get_xml_description);

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

        $vm_pool = $pool;
        $available = $info->{available};

    }
Francesc Guasch's avatar
Francesc Guasch committed
200
    confess "I can't find /pool/target/path in the storage pools xml\n"
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
        if !$vm_pool;

    return $vm_pool;

}

=head2 storage_pool

Returns a storage pool usable by the domain to store new volumes.

=cut

sub storage_pool {
    my $self = shift;

    return $self->_load_storage_pool();
}

219
220
221
222
223
=head2 search_volume

Searches for a volume in all the storage pools known to the Virtual Manager

Argument: the filenaname;
Francesc Guasch's avatar
Francesc Guasch committed
224
225
Returns the volume as a Sys::Virt::StorageGol. If called in array context returns a
list of all the volumes.
226
227
228
229
230
231
232

    my $iso = $vm->search_volume("debian-8.iso");

    my @disk = $vm->search_volume("windows10-clone.img");

=cut

Francesc Guasch's avatar
Francesc Guasch committed
233
sub search_volume($self,$file,$refresh=0) {
234
    confess "ERROR: undefined file" if !defined $file;
Francesc Guasch's avatar
Francesc Guasch committed
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249

    my ($name) = $file =~ m{.*/(.*)};
    $name = $file if !defined $name;

    my $vol;
    for my $pool ($self->vm->list_storage_pools) {
        if ($refresh) {
            $pool->refresh();
            sleep 1;
        }
        eval { $vol = $pool->get_volume_by_name($name) };
        die $@ if $@ && $@ !~ /^libvirt error code: 50,/;
    }

    return $self->search_volume_re(qr(^$name$),$refresh);
Francesc Guasch's avatar
Francesc Guasch committed
250
}
251

Francesc Guasch's avatar
Francesc Guasch committed
252
=head2 search_volume_path
253

Francesc Guasch's avatar
Francesc Guasch committed
254
Searches for a volume in all the storage pools known to the Virtual Manager
255

Francesc Guasch's avatar
Francesc Guasch committed
256
257
258
259
260
261
262
263
264
265
266
Argument: the filenaname;
Returns the path of the volume. If called in array context returns a
list of all the paths to all the matching volumes.

    my $iso = $vm->search_volume("debian-8.iso");

    my @disk = $vm->search_volume("windows10-clone.img");



=cut
267

Francesc Guasch's avatar
Francesc Guasch committed
268
269
270
sub search_volume_path {
    my $self = shift;
    my @volume = $self->search_volume(@_);
Francesc Guasch's avatar
Francesc Guasch committed
271

Francesc Guasch's avatar
Francesc Guasch committed
272
273
274
275
276
277
    my @vol2 = map { $_->get_path() if ref($_) } @volume;

    return $vol2[0] if !wantarray;
    return @vol2;
}

Francesc Guasch's avatar
Francesc Guasch committed
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
=head2 search_volume_re

Searches for a volume in all the storage pools known to the Virtual Manager

Argument: a regular expression;
Returns the volume. If called in array context returns a
list of all the matching volumes.

    my $iso = $vm->search_volume(qr(debian-\d+\.iso));

    my @disk = $vm->search_volume(qr(windows10-clone.*\.img));

=cut

sub search_volume_re($self,$pattern,$refresh=0) {

    confess "'$pattern' doesn't look like a regexp to me ".ref($pattern)
        if !ref($pattern) || ref($pattern) ne 'Regexp';
Francesc Guasch's avatar
Francesc Guasch committed
296

Francesc Guasch's avatar
Francesc Guasch committed
297
    $self->_connect();
298
299
    $self->_refresh_storage_pools()    if $refresh;

Francesc Guasch's avatar
Francesc Guasch committed
300
301
302
    my @volume;
    for my $pool ($self->vm->list_storage_pools) {
        for my $vol ( $pool->list_all_volumes()) {
Francesc Guasch's avatar
Francesc Guasch committed
303
304
            my ($file) = $vol->get_path =~ m{.*/(.*)};
            next if $file !~ $pattern;
Francesc Guasch's avatar
Francesc Guasch committed
305

Francesc Guasch's avatar
Francesc Guasch committed
306
307
            return $vol if !wantarray;
            push @volume,($vol);
Francesc Guasch's avatar
Francesc Guasch committed
308
309
        }
    }
Francesc Guasch's avatar
Francesc Guasch committed
310
311
312
313
314
315
316
    if (!scalar @volume && !$refresh && !$self->readonly
            && time - ($self->{_time_refreshed} or 0) > 60) {
        $self->{_time_refreshed} = time;
        @volume = $self->search_volume_re($pattern,"refresh");
        return $volume[0] if !wantarray && scalar @volume;
    }
    return if !wantarray && !scalar@volume;
Francesc Guasch's avatar
Francesc Guasch committed
317
318
319
    return @volume;
}

320
321
322
323
sub refresh_storage_pools($self) {
    $self->_refresh_storage_pools();
}

324
325
sub _refresh_storage_pools($self) {
    for my $pool ($self->vm->list_storage_pools) {
326
327
328
329
330
331
        for ( 1 .. 10 ) {
            eval { $pool->refresh() };
            last if !$@;
            warn $@ if $@ !~ /pool .* has asynchronous jobs running/;
            sleep 1;
        }
332
333
334
    }
}

335
336
337
338
339
340
341
342
=head2 refresh_storage

Refreshes all the storage pools

=cut

sub refresh_storage($self) {
    $self->_refresh_storage_pools();
Francesc Guasch's avatar
Francesc Guasch committed
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
    $self->_refresh_isos();
}

sub _refresh_isos($self) {
    $self->_init_connector();
    my $sth = $$CONNECTOR->dbh->prepare(
        "SELECT * FROM iso_images ORDER BY name"
    );
    my $sth_update = $$CONNECTOR->dbh->prepare("UPDATE iso_images set device=? WHERE id=?");

    $sth->execute;
    while (my $row = $sth->fetchrow_hashref) {

        if ( $row->{device} && !-e $row->{device} ) {
            delete $row->{device};
            $sth_update->execute($row->{device}, $row->{id});
            next;
        }
        next if $row->{device};

        my ($file);
        ($file) = $row->{url} =~ m{.*/(.*)}   if $row->{url};
365
        $file = $row->{rename_file} if $row->{rename_file};
Francesc Guasch's avatar
Francesc Guasch committed
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
        my $file_re = $row->{file_re};

        next if $row->{device};
        if ($file) {
            my $iso_file = $self->search_volume_path($file);
            if ($iso_file) {
                $row->{device} = $iso_file;
            }
        }
        if (!$row->{device} && $file_re) {
            my $iso_file = $self->search_volume_path_re(qr($file_re));
            if ($iso_file) {
                $row->{device} = $iso_file;
            }
        }
        $sth_update->execute($row->{device}, $row->{id}) if $row->{device};
    }
    $sth->finish;
384
385
}

Francesc Guasch's avatar
Francesc Guasch committed
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
=head2 search_volume_path_re

Searches for a volume in all the storage pools known to the Virtual Manager

Argument: a regular expression;
Returns the volume path. If called in array context returns a
list of all the paths of all the matching volumes.

    my $iso = $vm->search_volume(qr(debian-\d+\.iso));

    my @disk = $vm->search_volume(qr(windows10-clone.*\.img));

=cut


sub search_volume_path_re($self, $pattern) {
    my @vol = $self->search_volume_re($pattern);

    return if !wantarray && !scalar @vol;
    return $vol[0]->get_path if !wantarray;

    return map { $_->get_path() if ref($_) } @vol;

}

411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
=head2 dir_img

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

=cut

sub dir_img {
    my $self = shift;

    my $pool = $self->_load_storage_pool();
    $pool = $self->_create_default_pool() if !$pool;
    my $xml = XML::LibXML->load_xml(string => $pool->get_xml_description());

    my $dir = $xml->findnodes('/pool/target/path/text()');
    die "I can't find /pool/target/path in ".$xml->toString
        if !$dir;

    return $dir;
}

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
=head2 dir_base

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

=cut


sub dir_base($self, $volume_size) {
    my $pool_base = $self->default_storage_pool_name;
    $pool_base = $self->base_storage_pool()    if $self->base_storage_pool();
    $pool_base = $self->storage_pool()         if !$pool_base;

    $self->_check_free_disk($volume_size * 2, $pool_base);
    return $self->_storage_path($pool_base);

}

=head2 dir_clone

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

=cut


sub dir_clone($self) {

    my $dir_img  = $self->dir_img;
    my $clone_pool = $self->clone_storage_pool();
    $dir_img = $self->_storage_path($clone_pool) if $clone_pool;

    return $dir_img;
}

464
sub _storage_path($self, $storage) {
Francesc Guasch's avatar
Francesc Guasch committed
465
466
467
    if (!ref($storage)) {
        $storage = $self->vm->get_storage_pool_by_name($storage);
    }
468
469
470
471
472
473
474
475
476
477
    my $xml = XML::LibXML->load_xml(string => $storage->get_xml_description());

    my $dir = $xml->findnodes('/pool/target/path/text()');
    die "I can't find /pool/target/path in ".$xml->toString
        if !$dir;

    return $dir;

}

478
479
sub _create_default_pool {
    my $self = shift;
480
481
    my $vm = shift;
    $vm = $self->vm if !$vm;
482
483
484

    my $uuid = Ravada::VM::KVM::_new_uuid('68663afc-aaf4-4f1f-9fff-93684c260942');

485
    my $dir = "/var/lib/libvirt/images";
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
    mkdir $dir if ! -e $dir;

    my $xml =
"<pool type='dir'>
  <name>default</name>
  <uuid>$uuid</uuid>
  <capacity unit='bytes'></capacity>
  <allocation unit='bytes'></allocation>
  <available unit='bytes'></available>
  <source>
  </source>
  <target>
    <path>$dir</path>
    <permissions>
      <mode>0711</mode>
      <owner>0</owner>
      <group>0</group>
    </permissions>
  </target>
</pool>"
;
Francesc Guasch's avatar
Francesc Guasch committed
507
508
509
510
511
512
513
    my $pool;
    eval {
        $pool = $vm->define_storage_pool($xml);
        $pool->create();
        $pool->set_autostart(1);
    };
    warn $@ if $@;
514
515
516
517
518
519
520
521
522
523

}

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

524
525
526
527
528
529
Creates a domain and removes the CPU defined in the XML template:

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

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

sub create_domain {
    my $self = shift;
    my %args = @_;
    $args{active} = 1 if !defined $args{active};

    croak "argument name required"       if !$args{name};
    croak "argument id_owner required"   if !$args{id_owner};
    croak "argument id_iso or id_base required ".Dumper(\%args)
        if !$args{id_iso} && !$args{id_base};

    my $domain;
    if ($args{id_iso}) {
        $domain = $self->_domain_create_from_iso(@_);
    } elsif($args{id_base}) {
        $domain = $self->_domain_create_from_base(@_);
    } else {
        confess "TODO";
    }

    return $domain;
}

=head2 search_domain

Returns true or false if domain exists.

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

=cut

562
sub search_domain($self, $name, $force=undef) {
563

Francesc Guasch's avatar
Francesc Guasch committed
564
565
566
567
568
569
570
571
572
573
574
    eval {
        $self->connect();
    };
    if ($@ && $@ =~ /libvirt error code: 38,/) {
        warn $@;
        if (!$self->is_local) {
            warn "DISABLING NODE ".$self->name;
            $self->enabled(0);
        }
        return;
    }
575

576
577
    my $dom;
    eval { $dom = $self->vm->get_domain_by_name($name); };
Francesc Guasch's avatar
Francesc Guasch committed
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
    my $error = $@;
    return if $error =~  /error code: 42,/ && !$force;

    if ($error && $error =~ /libvirt error code: 38,/ ) {
        eval {
            $self->disconnect;
            $self->connect;
        };
        confess "Error connecting to ".$self->name." $@" if $@;
        eval { $dom = $self->vm->get_domain_by_name($name); };
        confess $@ if $@ && $@ !~  /error code: 42,/;
    } elsif ($error && $error !~ /error code: 42,/) {
        confess $error;
    }

Francesc Guasch's avatar
Francesc Guasch committed
593
594
595
596
    if (!$dom) {
        return if !$force;
        return if !$self->_domain_in_db($name);
    }
597

598
    my $domain;
599

600
        my @domain = ( );
Francesc Guasch's avatar
Francesc Guasch committed
601
602
        push @domain, ( domain => $dom ) if $dom;
        push @domain, ( id_owner => $Ravada::USER_DAEMON->id)
Francesc Guasch's avatar
Francesc Guasch committed
603
            if $force && !$self->_domain_in_db($name);
604
605
        eval {
            $domain = Ravada::Domain::KVM->new(
606
607
                @domain
                ,name => $name
608
609
610
611
612
613
                ,readonly => $self->readonly
                ,_vm => $self
            );
        };
        warn $@ if $@;
        if ($domain) {
Francesc Guasch's avatar
Francesc Guasch committed
614
            $domain->xml_description()  if $dom && $domain->is_known();
615
616
            return $domain;
        }
617

618
619
620
621
622
623
624
625
626
627
628
629
630
    return;
}

=head2 list_domains

Returns a list of the created domains

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

=cut

sub list_domains {
    my $self = shift;
631
632
    my %args = @_;

633
634
    return if !$self->vm;

635
    my $active = (delete $args{active} or 0);
636
    my $read_only = delete $args{read_only};
637

638
    confess "Arguments unknown ".Dumper(\%args)  if keys %args;
639

640
641
642
643
644
645
    my $query = "SELECT id, name FROM domains WHERE id_vm = ? ";
    $query .= " AND status = 'active' " if $active;

    my $sth = $$CONNECTOR->dbh->prepare($query);

    $sth->execute( $self->id );
646
    my @list;
Francesc Guasch's avatar
Francesc Guasch committed
647
    while ( my ($id) = $sth->fetchrow) {
648
649
650
651
652
653
        my $domain;
        if ($read_only) {
            $domain = Ravada::Front::Domain->open( $id );
        } else {
            $domain = Ravada::Domain->open( id => $id, vm => $self);
        }
654
        push @list,($domain) if $domain;
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
    }
    return @list;
}

=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 => $name, name => $file_xml);

=cut

sub create_volume {
    my $self = shift;

    confess "Wrong arrs " if scalar @_ % 2;
    my %args = @_;

673
674
675
676
677
678
679
680
681
682
    my $name = delete $args{name}       or confess "ERROR: Missing volume name";
    my $file_xml = delete $args{xml}   or confess "ERROR: Missing XML template";

    my $size        = delete $args{size};
    my $swap        =(delete $args{swap} or 0);
    my $target      = delete $args{target};
    my $capacity    = delete $args{capacity};
    my $allocation  = delete $args{allocation};

    confess "ERROR: Unknown args ".Dumper(\%args)   if keys %args;
683
684

    confess "Invalid size"          if defined $size && ( $size == 0 || $size !~ /^\d+$/);
Francesc Guasch's avatar
Francesc Guasch committed
685
686
687
688

    confess "Invalid capacity"
        if defined $capacity && ( $capacity == 0 || $capacity !~ /^\d+$/);

689
690
691
692
693
694
695
    confess "Capacity and size are the same, give only one of them"
        if defined $capacity && defined $size;

    $capacity = $size if defined $size;
    $allocation = int($capacity * 0.1)+1
        if !defined $allocation && $capacity;

696
    open my $fh,'<', $file_xml or confess "$! $file_xml";
697
698
699
700
701

    my $doc;
    eval { $doc = $XML->load_xml(IO => $fh) };
    die "ERROR reading $file_xml $@"    if $@;

702
703
    my $storage_pool = $self->storage_pool();

704
705
706
    confess $name if $name =~ /-\w{4}-vd[a-z]-\w{4}\./
        || $name =~ /\d-vd[a-z]\./;

707
708
709
710
711
712
713
    my $img_file = $self->_volume_path(
        target => $target
        , swap => $swap
        , name => $name
        , storage => $storage_pool
    );

714
    confess if $img_file =~ /\d-vd[a-z]\./;
715
716
717
718
719
720
721
    my ($volume_name) = $img_file =~m{.*/(.*)};
    $doc->findnodes('/volume/name/text()')->[0]->setData($volume_name);
    $doc->findnodes('/volume/key/text()')->[0]->setData($img_file);
    $doc->findnodes('/volume/target/path/text()')->[0]->setData(
                        $img_file);

    if ($capacity) {
Francesc Guasch's avatar
Francesc Guasch committed
722
723
        confess "Size '$capacity' too small" if $capacity< 1024*10;
        $doc->findnodes('/volume/allocation/text()')->[0]->setData(int($allocation));
724
725
        $doc->findnodes('/volume/capacity/text()')->[0]->setData($capacity);
    }
726
727
728
    my $vol = $self->storage_pool->create_volume($doc->toString)
        or die "volume $img_file does not exists after creating volume on ".$self->name." "
            .$doc->toString();
729
730
731
732
733
734
735
736
737

    return $img_file;

}

sub _volume_path {
    my $self = shift;

    my %args = @_;
738
739
740
    my $swap     =(delete $args{swap} or 0);
    my $storage  = delete $args{storage} or confess "ERROR: Missing storage";
    my $filename = $args{name}  or confess "ERROR: Missing name";
741
    my $target = delete $args{target};
742
743

    my $dir_img = $self->_storage_path($storage);
744
745
746
    my $suffix = "qcow2";
    $suffix = ".SWAP.qcow2"   if $swap;
    return "$dir_img/$filename.$suffix";
747
748
749
750
751
}

sub _domain_create_from_iso {
    my $self = shift;
    my %args = @_;
752
    my %args2 = %args;
753
    for (qw(id_iso id_owner name)) {
754
        delete $args2{$_};
755
756
757
        croak "argument $_ required"
            if !$args{$_};
    }
758
    my $remove_cpu = delete $args2{remove_cpu};
759
760
    for (qw(disk swap active request vm memory iso_file id_template volatile spice_password
            listen_ip)) {
761
762
        delete $args2{$_};
    }
763
764

    my $iso_file = delete $args{iso_file};
765
766
    confess "Unknown parameters : ".join(" , ",sort keys %args2)
        if keys %args2;
767
768
769
770
771

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

    my $vm = $self->vm;
772
    my $iso = $self->_search_iso($args{id_iso} , $iso_file);
773
774
775

    die "ERROR: Empty field 'xml_volume' in iso_image ".Dumper($iso)
        if !$iso->{xml_volume};
776
777
        
    my $device_cdrom;
778
779

    confess "Template ".$iso->{name}." has no URL, iso_file argument required."
Francesc Guasch's avatar
Francesc Guasch committed
780
        if !$iso->{url} && !$iso_file && !$iso->{device};
781

782
783
784
785
    if ($iso_file) {
        if ( $iso_file ne "<NONE>") {
            $device_cdrom = $iso_file;
        }
786
787
    }
    else {
joelalju's avatar
joelalju committed
788
      $device_cdrom = $self->_iso_name($iso, $args{request});
789
790
    }
    
joelalju's avatar
joelalju committed
791
792
793
794
795
796
797
    #if ((not exists $args{iso_file}) || ((exists $args{iso_file}) && ($args{iso_file} eq "<NONE>"))) {
    #    $device_cdrom = $self->_iso_name($iso, $args{request});
    #}
    #else {
    #    $device_cdrom = $args{iso_file};
    #}
    
798
799
    my $disk_size;
    $disk_size = $args{disk} if $args{disk};
800
801
802

    my $file_xml =  $DIR_XML."/".$iso->{xml_volume};

803
    my $device_disk = $self->create_volume(
804
          name => "$args{name}-vda-".Ravada::Utils::random_name(4)
805
         , xml => $file_xml
806
        , size => $disk_size
807
        ,target => 'vda'
808
809
810
811
    );

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

812
813
814
815
816
    if ($device_cdrom) {
        _xml_modify_cdrom($xml, $device_cdrom);
    } else {
        _xml_remove_cdrom($xml);
    }
817
    _xml_remove_cpu($xml)                     if $remove_cpu;
818
819
820
821
    _xml_modify_disk($xml, [$device_disk])    if $device_disk;
    $self->_xml_modify_usb($xml);
    _xml_modify_video($xml);

822
823
    my ($domain, $spice_password)
        = $self->_domain_create_common($xml,%args);
Francesc Guasch's avatar
Francesc Guasch committed
824
825
826
    $domain->_insert_db(name=> $args{name}, id_owner => $args{id_owner}
        , id_vm => $self->id
    );
Francesc Guasch's avatar
Francesc Guasch committed
827

828
829
    $domain->_set_spice_password($spice_password)
        if $spice_password;
830
    $domain->xml_description();
831
832
833
834
835
836
837
838
839

    return $domain;
}

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

840
    my $id_owner = delete $args{id_owner} or confess "ERROR: The id_owner is mandatory";
841
    my $is_volatile = delete $args{is_volatile};
842
843
    my $listen_ip = delete $args{listen_ip};
    my $spice_password = delete $args{spice_password};
844
845
846
    my $user = Ravada::Auth::SQL->search_by_id($id_owner)
        or confess "ERROR: User id $id_owner doesn't exist";

847
848
849
    $self->_xml_modify_memory($xml,$args{memory})   if $args{memory};
    $self->_xml_modify_network($xml , $args{network})   if $args{network};
    $self->_xml_modify_mac($xml);
Francesc Guasch's avatar
Francesc Guasch committed
850
    my $uuid = $self->_xml_modify_uuid($xml);
851
    $self->_xml_modify_spice_port($xml, $spice_password, $listen_ip);
852
    $self->_fix_pci_slots($xml);
JanFontanet's avatar
JanFontanet committed
853
    $self->_xml_add_guest_agent($xml);
854
    $self->_xml_clean_machine_type($xml) if !$self->is_local;
Francesc Guasch's avatar
Francesc Guasch committed
855
    $self->_xml_add_sysinfo_entry($xml, hostname => $args{name});
856
857
858

    my $dom;

Francesc Guasch's avatar
Francesc Guasch committed
859
860
861
862
863
864
865
866
867
868
869
870
    for ( 1 .. 10 ) {
        eval {
            if ($user->is_temporary || $is_volatile ) {
                $dom = $self->vm->create_domain($xml->toString());
            } else {
                $dom = $self->vm->define_domain($xml->toString());
                $dom->create if $args{active};
            }
        };

        last if !$@;
        if ($@ =~ /libvirt error code: 9, .*already defined with uuid/) {
Francesc Guasch's avatar
Francesc Guasch committed
871
            $self->_xml_modify_uuid($xml);
Francesc Guasch's avatar
Francesc Guasch committed
872
873
        } elsif ($@ =~ /libvirt error code: 1, .* pool .* asynchronous/) {
            sleep 1;
874
        } else {
Francesc Guasch's avatar
Francesc Guasch committed
875
            last ;
876
        }
Francesc Guasch's avatar
Francesc Guasch committed
877
    }
878
879
    if ($@) {
        my $out;
880
		warn $self->name."\n".$@;
881
882
883
884
885
886
887
        my $name_out = "/var/tmp/$args{name}.xml";
        warn "Dumping $name_out";
        open $out,">",$name_out and do {
            print $out $xml->toString();
        };
        close $out;
        warn "$! $name_out" if !$out;
888
        confess $@ if !$dom;
889
890
891
892
893
894
    }

    my $domain = Ravada::Domain::KVM->new(
              _vm => $self
         , domain => $dom
        , storage => $self->storage_pool
Francesc Guasch's avatar
Francesc Guasch committed
895
       , id_owner => $id_owner
896
    );
897
    return ($domain, $spice_password);
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
}

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 @files_out;

913
914
    for my $file_data ( $base->list_files_base_target ) {
        my ($file_base,$target) = @$file_data;
915
916
917
918
        my $vol_base = Ravada::Volume->new(
            file => $file_base
            ,is_base => 1
            ,vm => $self
919
        );
920
921
        my $clone = $vol_base->clone(name => "$name-$target");
        push @files_out,($clone->file);
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
    }
    return @files_out;

}

sub _random_name { return Ravada::Utils::random_name(@_); };

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

    my $sth = $$CONNECTOR->dbh->prepare("SELECT * FROM domains WHERE id=?");
    $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});

951
    my $base = $args{base};
952
953
954
955
956
957
958

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

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

959
    my $xml = XML::LibXML->load_xml(string => $base->get_xml_base());
960
961
962
963
964
965
966
967
968
969


    my @device_disk = $self->_create_disk($base, $args{name});
#    _xml_modify_cdrom($xml);
    _xml_remove_cdrom($xml);
    my ($node_name) = $xml->findnodes('/domain/name/text()');
    $node_name->setData($args{name});

    _xml_modify_disk($xml, \@device_disk);#, \@swap_disk);

970
    my ($domain, $spice_password)
971
        = $self->_domain_create_common($xml,%args, is_volatile => $base->volatile_clones);
Francesc Guasch's avatar
Francesc Guasch committed
972
973
974
    $domain->_insert_db(name=> $args{name}, id_base => $base->id, id_owner => $args{id_owner}
        , id_vm => $self->id
    );
975
    $domain->_set_spice_password($spice_password);
976
    $domain->xml_description();
977
978
979
980
981
982
983
984
985
986
987
988
989
990
    return $domain;
}

sub _fix_pci_slots {
    my $self = shift;
    my $doc = shift;

    my %dupe = ("0x01/0x1" => 1); #reserved por IDE PCI
    my ($all_devices) = $doc->findnodes('/domain/devices');

    for my $dev ($all_devices->findnodes('*')) {

        # skip IDE PCI, reserved before
        next if $dev->getAttribute('type')
991
            && $dev->getAttribute('type') =~ /^(ide)$/i;
992
993
994
995
996

#        warn "finding address of type ".$dev->getAttribute('type')."\n";

        for my $child ($dev->findnodes('address')) {
            my $bus = $child->getAttribute('bus');
997
998
999
1000
            my $slot = ($child->getAttribute('slot') or '');
            my $function = ($child->getAttribute('function') or '');
            my $multifunction = $child->getAttribute('multifunction');

For faster browsing, not all history is shown. View entire blame