KVM.pm 62.5 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
24
use File::Temp qw(tempfile);
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;
25
use Mojo::DOM;
26
use Mojo::UserAgent;
27
28
29
30
31
use Moose;
use Sys::Virt;
use URI;
use XML::LibXML;

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

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

with 'Ravada::VM';

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

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

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

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

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

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

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

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

our $CONNECTOR = \$Ravada::CONNECTOR;

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

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

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

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


sub _connect {
    my $self = shift;

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

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

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

129
130
131
132
133
134
135
136
137
138
139
140
141
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);
    }
}

142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
=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;
162
    return 1 if $self->vm;
163
    return 1 if $self->is_alive;
164

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

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

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

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

179
180
181
    my $vm_pool;
    my $available;

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

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

        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
201
    confess "I can't find /pool/target/path in the storage pools xml\n"
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
        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();
}

220
221
222
223
224
=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
225
226
Returns the volume as a Sys::Virt::StorageGol. If called in array context returns a
list of all the volumes.
227
228
229
230
231
232
233

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

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

=cut

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

    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
251
}
252

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

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

Francesc Guasch's avatar
Francesc Guasch committed
257
258
259
260
261
262
263
264
265
266
267
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
268

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

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

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

Francesc Guasch's avatar
Francesc Guasch committed
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
=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
297

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

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

Francesc Guasch's avatar
Francesc Guasch committed
307
308
            return $vol if !wantarray;
            push @volume,($vol);
Francesc Guasch's avatar
Francesc Guasch committed
309
310
        }
    }
Francesc Guasch's avatar
Francesc Guasch committed
311
312
313
314
315
316
317
    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
318
319
320
    return @volume;
}

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

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

336
337
338
339
340
341
342
343
=head2 refresh_storage

Refreshes all the storage pools

=cut

sub refresh_storage($self) {
    $self->_refresh_storage_pools();
Francesc Guasch's avatar
Francesc Guasch committed
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
    $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};
366
        $file = $row->{rename_file} if $row->{rename_file};
Francesc Guasch's avatar
Francesc Guasch committed
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
        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;
385
386
}

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

}

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

432
sub _storage_path($self, $storage) {
Francesc Guasch's avatar
Francesc Guasch committed
433
434
435
    if (!ref($storage)) {
        $storage = $self->vm->get_storage_pool_by_name($storage);
    }
436
437
438
439
440
441
442
443
444
445
    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;

}

446
447
sub _create_default_pool {
    my $self = shift;
448
449
    my $vm = shift;
    $vm = $self->vm if !$vm;
450
451
452

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

453
    my $dir = "/var/lib/libvirt/images";
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
    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
475
476
477
478
479
480
481
    my $pool;
    eval {
        $pool = $vm->define_storage_pool($xml);
        $pool->create();
        $pool->set_autostart(1);
    };
    warn $@ if $@;
482
483
484
485
486
487
488
489
490
491

}

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

492
493
494
495
496
497
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);

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

530
sub search_domain($self, $name, $force=undef) {
531

Francesc Guasch's avatar
Francesc Guasch committed
532
533
534
535
536
537
538
539
540
541
542
    eval {
        $self->connect();
    };
    if ($@ && $@ =~ /libvirt error code: 38,/) {
        warn $@;
        if (!$self->is_local) {
            warn "DISABLING NODE ".$self->name;
            $self->enabled(0);
        }
        return;
    }
543

544
545
    my $dom;
    eval { $dom = $self->vm->get_domain_by_name($name); };
Francesc Guasch's avatar
Francesc Guasch committed
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
    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
561
562
563
564
    if (!$dom) {
        return if !$force;
        return if !$self->_domain_in_db($name);
    }
565

566
    my $domain;
567

568
        my @domain = ( );
Francesc Guasch's avatar
Francesc Guasch committed
569
570
        push @domain, ( domain => $dom ) if $dom;
        push @domain, ( id_owner => $Ravada::USER_DAEMON->id)
Francesc Guasch's avatar
Francesc Guasch committed
571
            if $force && !$self->_domain_in_db($name);
572
573
        eval {
            $domain = Ravada::Domain::KVM->new(
574
575
                @domain
                ,name => $name
576
577
578
579
580
581
                ,readonly => $self->readonly
                ,_vm => $self
            );
        };
        warn $@ if $@;
        if ($domain) {
Francesc Guasch's avatar
Francesc Guasch committed
582
            $domain->xml_description()  if $dom && $domain->is_known();
583
584
            return $domain;
        }
585

586
587
588
589
590
591
592
593
594
595
596
597
598
    return;
}

=head2 list_domains

Returns a list of the created domains

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

=cut

sub list_domains {
    my $self = shift;
599
600
    my %args = @_;

601
602
    return if !$self->vm;

603
    my $active = (delete $args{active} or 0);
604
    my $read_only = delete $args{read_only};
605

606
    confess "Arguments unknown ".Dumper(\%args)  if keys %args;
607

608
609
610
611
612
613
    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 );
614
    my @list;
Francesc Guasch's avatar
Francesc Guasch committed
615
    while ( my ($id) = $sth->fetchrow) {
616
617
618
619
620
621
        my $domain;
        if ($read_only) {
            $domain = Ravada::Front::Domain->open( $id );
        } else {
            $domain = Ravada::Domain->open( id => $id, vm => $self);
        }
622
        push @list,($domain) if $domain;
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
    }
    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 = @_;

641
642
643
644
645
646
647
648
649
650
    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;
651
652

    confess "Invalid size"          if defined $size && ( $size == 0 || $size !~ /^\d+$/);
Francesc Guasch's avatar
Francesc Guasch committed
653
654
655
656

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

657
658
659
660
661
662
663
    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;

664
    open my $fh,'<', $file_xml or confess "$! $file_xml";
665
666
667
668
669

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

670
671
672
673
674
675
676
677
678
    my $storage_pool = $self->storage_pool();

    my $img_file = $self->_volume_path(
        target => $target
        , swap => $swap
        , name => $name
        , storage => $storage_pool
    );

679
680
681
682
683
684
685
    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
686
687
        confess "Size '$capacity' too small" if $capacity< 1024*10;
        $doc->findnodes('/volume/allocation/text()')->[0]->setData(int($allocation));
688
689
        $doc->findnodes('/volume/capacity/text()')->[0]->setData($capacity);
    }
690
691
692
    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();
693
694
695
696
697
698
699
700
701

    return $img_file;

}

sub _volume_path {
    my $self = shift;

    my %args = @_;
702
703
704
705
706
707
    my $swap     =(delete $args{swap} or 0);
    my $target   = delete $args{target};
    my $storage  = delete $args{storage} or confess "ERROR: Missing storage";
    my $filename = $args{name}  or confess "ERROR: Missing name";

    my $dir_img = $self->_storage_path($storage);
708
    my $suffix = ".img";
709
    $suffix = ".SWAP.img"   if $swap;
710
711
    $filename .= "-$target" if $target;
    my (undef, $img_file) = tempfile($filename."-XXXX"
712
713
714
715
716
717
718
719
720
721
        ,DIR => $dir_img
        ,OPEN => 0
        ,SUFFIX => $suffix
    );
    return $img_file;
}

sub _domain_create_from_iso {
    my $self = shift;
    my %args = @_;
722
    my %args2 = %args;
723
    for (qw(id_iso id_owner name)) {
724
        delete $args2{$_};
725
726
727
        croak "argument $_ required"
            if !$args{$_};
    }
728
    my $remove_cpu = delete $args2{remove_cpu};
729
730
    for (qw(disk swap active request vm memory iso_file id_template volatile spice_password
            listen_ip)) {
731
732
        delete $args2{$_};
    }
733
734

    my $iso_file = delete $args{iso_file};
735
736
    confess "Unknown parameters : ".join(" , ",sort keys %args2)
        if keys %args2;
737
738
739
740
741

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

    my $vm = $self->vm;
742
    my $iso = $self->_search_iso($args{id_iso} , $iso_file);
743
744
745

    die "ERROR: Empty field 'xml_volume' in iso_image ".Dumper($iso)
        if !$iso->{xml_volume};
746
747
        
    my $device_cdrom;
748
749

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

752
753
754
755
    if ($iso_file) {
        if ( $iso_file ne "<NONE>") {
            $device_cdrom = $iso_file;
        }
756
757
    }
    else {
joelalju's avatar
joelalju committed
758
      $device_cdrom = $self->_iso_name($iso, $args{request});
759
760
    }
    
joelalju's avatar
joelalju committed
761
762
763
764
765
766
767
    #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};
    #}
    
768
769
    my $disk_size;
    $disk_size = $args{disk} if $args{disk};
770
771
772

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

773
774
    my $device_disk = $self->create_volume(
          name => $args{name}
775
         , xml => $file_xml
776
        , size => $disk_size
777
        ,target => 'vda'
778
779
780
781
    );

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

782
783
784
785
786
    if ($device_cdrom) {
        _xml_modify_cdrom($xml, $device_cdrom);
    } else {
        _xml_remove_cdrom($xml);
    }
787
    _xml_remove_cpu($xml)                     if $remove_cpu;
788
789
790
791
    _xml_modify_disk($xml, [$device_disk])    if $device_disk;
    $self->_xml_modify_usb($xml);
    _xml_modify_video($xml);

792
793
    my ($domain, $spice_password)
        = $self->_domain_create_common($xml,%args);
Francesc Guasch's avatar
Francesc Guasch committed
794
795
796
    $domain->_insert_db(name=> $args{name}, id_owner => $args{id_owner}
        , id_vm => $self->id
    );
Francesc Guasch's avatar
Francesc Guasch committed
797

798
799
    $domain->_set_spice_password($spice_password)
        if $spice_password;
800
    $domain->xml_description();
801
802
803
804
805
806
807
808
809

    return $domain;
}

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

810
    my $id_owner = delete $args{id_owner} or confess "ERROR: The id_owner is mandatory";
811
    my $is_volatile = delete $args{is_volatile};
812
813
    my $listen_ip = delete $args{listen_ip};
    my $spice_password = delete $args{spice_password};
814
815
816
    my $user = Ravada::Auth::SQL->search_by_id($id_owner)
        or confess "ERROR: User id $id_owner doesn't exist";

817
818
819
    $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
820
    my $uuid = $self->_xml_modify_uuid($xml);
821
    $self->_xml_modify_spice_port($xml, $spice_password, $listen_ip);
822
    $self->_fix_pci_slots($xml);
JanFontanet's avatar
JanFontanet committed
823
    $self->_xml_add_guest_agent($xml);
824
    $self->_xml_clean_machine_type($xml) if !$self->is_local;
Francesc Guasch's avatar
Francesc Guasch committed
825
    $self->_xml_add_sysinfo_entry($xml, hostname => $args{name});
826
827
828

    my $dom;

Francesc Guasch's avatar
Francesc Guasch committed
829
830
831
832
833
834
835
836
837
838
839
840
    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
841
            $self->_xml_modify_uuid($xml);
Francesc Guasch's avatar
Francesc Guasch committed
842
843
        } elsif ($@ =~ /libvirt error code: 1, .* pool .* asynchronous/) {
            sleep 1;
844
        } else {
Francesc Guasch's avatar
Francesc Guasch committed
845
            last ;
846
        }
Francesc Guasch's avatar
Francesc Guasch committed
847
    }
848
849
    if ($@) {
        my $out;
850
		warn $self->name."\n".$@;
851
852
853
854
855
856
857
        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;
858
        confess $@ if !$dom;
859
860
861
862
863
864
    }

    my $domain = Ravada::Domain::KVM->new(
              _vm => $self
         , domain => $dom
        , storage => $self->storage_pool
Francesc Guasch's avatar
Francesc Guasch committed
865
       , id_owner => $id_owner
866
    );
867
    return ($domain, $spice_password);
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
}

sub _create_disk {
    return _create_disk_qcow2(@_);
}

sub _create_swap_disk {
    return _create_disk_raw(@_);
}

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

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

    my $dir_img  = $self->dir_img;
Francesc Guasch's avatar
Francesc Guasch committed
886
887
    my $clone_pool = $self->clone_storage_pool();
    $dir_img = $self->_storage_path($clone_pool) if $clone_pool;
888
889
890

    my @files_out;

891
892
    for my $file_data ( $base->list_files_base_target ) {
        my ($file_base,$target) = @$file_data;
893
894
        my $ext = ".qcow2";
        $ext = ".SWAP.qcow2" if $file_base =~ /\.SWAP\.ro\.\w+$/;
895
896
        my $file_out = "$dir_img/$name-".($target or _random_name(2))
            ."-"._random_name(2).$ext;
897

898
899
900
901
902
903
904
905
906
907
908
        $self->_clone_disk($file_base, $file_out);
        push @files_out,($file_out);
    }
    return @files_out;

}

# this may become official API eventually

sub _clone_disk($self, $file_base, $file_out) {

909
        my @cmd = ('/usr/bin/qemu-img','create'
910
911
912
913
914
                ,'-f','qcow2'
                ,"-b", $file_base
                ,$file_out
        );

915
916
        my ($out, $err) = $self->run_command(@cmd);
        die $err if $err;
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
}

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

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

    my $dir_img  = $self->dir_img;

    my @files_out;

    for my $file_base ( $base->list_files_base ) {
        next unless $file_base =~ /SWAP\.img$/;
        my $file_out = $file_base;
        $file_out =~ s/\.ro\.\w+$//;
        $file_out =~ s/-.*(img|qcow\d?)//;
        $file_out .= ".$name-".Ravada::Utils::random_name(4).".SWAP.img";

        push @files_out,($file_out);
    }
    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});

967
    my $base = $args{base};
968
969
970
971
972
973
974

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

975
    my $xml = XML::LibXML->load_xml(string => $base->get_xml_base());
976
977
978
979
980
981
982
983
984
985


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

986
    my ($domain, $spice_password)
987
        = $self->_domain_create_common($xml,%args, is_volatile => $base->volatile_clones);
Francesc Guasch's avatar
Francesc Guasch committed
988
989
990
    $domain->_insert_db(name=> $args{name}, id_base => $base->id, id_owner => $args{id_owner}
        , id_vm => $self->id
    );
991
    $domain->_set_spice_password($spice_password);
992
    $domain->xml_description();
993
994
995
996
997
998
999
1000
    return $domain;
}

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

    my %dupe = ("0x01/0x1" => 1); #reserved por IDE PCI
For faster browsing, not all history is shown. View entire blame