KVM.pm 62.2 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
    $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};
Francesc Guasch's avatar
Francesc Guasch committed
362
        next if !$row->{url};
Francesc Guasch's avatar
Francesc Guasch committed
363

Francesc Guasch's avatar
Francesc Guasch committed
364
        my $file_re = $row->{file_re};
Francesc Guasch's avatar
Francesc Guasch committed
365
366
        my ($file);
        ($file) = $row->{url} =~ m{.*/(.*)}   if $row->{url};
367
        $file = $row->{rename_file} if $row->{rename_file};
Francesc Guasch's avatar
Francesc Guasch committed
368

Francesc Guasch's avatar
Francesc Guasch committed
369
370
371
372
373
        $file_re = "^$file\$" if $file;

        if (!$file_re) {
            warn "Error: ISO mismatch ".Dumper($row);
            next;
Francesc Guasch's avatar
Francesc Guasch committed
374
        }
Francesc Guasch's avatar
Francesc Guasch committed
375
376
377
378

        my $iso_file = $self->search_volume_path_re(qr($file_re));
        if ($iso_file) {
            $row->{device} = $iso_file;
Francesc Guasch's avatar
Francesc Guasch committed
379
380
381
382
        }
        $sth_update->execute($row->{device}, $row->{id}) if $row->{device};
    }
    $sth->finish;
383
384
}

Francesc Guasch's avatar
Francesc Guasch committed
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
=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;

}

410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
=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;
}

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

463
sub _storage_path($self, $storage) {
Francesc Guasch's avatar
Francesc Guasch committed
464
465
466
    if (!ref($storage)) {
        $storage = $self->vm->get_storage_pool_by_name($storage);
    }
467
468
469
470
471
472
473
474
475
476
    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;

}

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

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

484
    my $dir = "/var/lib/libvirt/images";
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
    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
506
507
508
509
510
511
512
    my $pool;
    eval {
        $pool = $vm->define_storage_pool($xml);
        $pool->create();
        $pool->set_autostart(1);
    };
    warn $@ if $@;
513
514
515
516
517
518
519
520
521
522

}

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

523
524
525
526
527
528
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);

529
530
531
532
533
534
535
536
537
=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};
Francesc Guasch's avatar
Francesc Guasch committed
538
    confess "argument id_iso or id_base required ".Dumper(\%args)
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
        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

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

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

575
576
    my $dom;
    eval { $dom = $self->vm->get_domain_by_name($name); };
Francesc Guasch's avatar
Francesc Guasch committed
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
    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
592
593
594
595
    if (!$dom) {
        return if !$force;
        return if !$self->_domain_in_db($name);
    }
596

597
    my $domain;
598

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

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

=head2 list_domains

Returns a list of the created domains

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

=cut

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

632
633
    return if !$self->vm;

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

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

639
640
641
642
643
644
    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 );
645
    my @list;
Francesc Guasch's avatar
Francesc Guasch committed
646
    while ( my ($id) = $sth->fetchrow) {
647
648
649
650
651
652
        my $domain;
        if ($read_only) {
            $domain = Ravada::Front::Domain->open( $id );
        } else {
            $domain = Ravada::Domain->open( id => $id, vm => $self);
        }
653
        push @list,($domain) if $domain;
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
    }
    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 = @_;

672
673
674
675
676
677
678
679
680
681
    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;
682
683

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

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

688
689
690
691
692
693
694
    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;

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

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

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

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

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

713
    confess if $img_file =~ /\d-vd[a-z]\./;
714
715
716
717
718
719
720
    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
721
722
        confess "Size '$capacity' too small" if $capacity< 1024*10;
        $doc->findnodes('/volume/allocation/text()')->[0]->setData(int($allocation));
723
724
        $doc->findnodes('/volume/capacity/text()')->[0]->setData($capacity);
    }
725
726
727
    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();
728
729
730
731
732
733
734
735
736

    return $img_file;

}

sub _volume_path {
    my $self = shift;

    my %args = @_;
737
738
739
    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";
740
    my $target = delete $args{target};
741
742

    my $dir_img = $self->_storage_path($storage);
743
    my $suffix = "qcow2";
Francesc Guasch's avatar
Francesc Guasch committed
744
    $suffix = "SWAP.qcow2"   if $swap;
745
    return "$dir_img/$filename.$suffix";
746
747
748
749
750
}

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

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

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

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

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

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

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

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

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

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

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

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

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

    return $domain;
}

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

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

846
847
848
    $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
849
    my $uuid = $self->_xml_modify_uuid($xml);
850
    $self->_xml_modify_spice_port($xml, $spice_password, $listen_ip);
851
    $self->_fix_pci_slots($xml);
JanFontanet's avatar
JanFontanet committed
852
    $self->_xml_add_guest_agent($xml);
853
    $self->_xml_clean_machine_type($xml) if !$self->is_local;
Francesc Guasch's avatar
Francesc Guasch committed
854
    $self->_xml_add_sysinfo_entry($xml, hostname => $args{name});
855
856
857

    my $dom;

Francesc Guasch's avatar
Francesc Guasch committed
858
859
860
861
862
863
864
865
866
867
868
869
    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
870
            $self->_xml_modify_uuid($xml);
Francesc Guasch's avatar
Francesc Guasch committed
871
872
        } elsif ($@ =~ /libvirt error code: 1, .* pool .* asynchronous/) {
            sleep 1;
873
        } else {
Francesc Guasch's avatar
Francesc Guasch committed
874
            last ;
875
        }
Francesc Guasch's avatar
Francesc Guasch committed
876
    }
877
878
    if ($@) {
        my $out;
879
		warn $self->name."\n".$@;
880
881
882
883
884
885
886
        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;
887
        confess $@ if !$dom;
888
889
890
891
892
893
    }

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

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;

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

950
    my $base = $args{base};
951
    my $with_cd = delete $args{with_cd};
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


    my @device_disk = $self->_create_disk($base, $args{name});
#    _xml_modify_cdrom($xml);
964
965
966
967
    if ( !defined $with_cd ) {
        $with_cd = grep (/\.iso$/ ,@device_disk);
    }
    _xml_remove_cdrom($xml) if !$with_cd;
968
969
970
971
972
    my ($node_name) = $xml->findnodes('/domain/name/text()');
    $node_name->setData($args{name});

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

973
    my ($domain, $spice_password)
974
        = $self->_domain_create_common($xml,%args, is_volatile => $base->volatile_clones);
Francesc Guasch's avatar
Francesc Guasch committed
975
976
977
    $domain->_insert_db(name=> $args{name}, id_base => $base->id, id_owner => $args{id_owner}
        , id_vm => $self->id
    );
978
    $domain->_set_spice_password($spice_password);
979
    $domain->xml_description();
980
981
982
983
984
985
986
987
988
989
990
991
992
993
    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')
994
            && $dev->getAttribute('type') =~ /^(ide)$/i;
995
996
997
998
999

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

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