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
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
    $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};
        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
sub _storage_path($self, $storage) {
Francesc Guasch's avatar
Francesc Guasch committed
432
433
434
    if (!ref($storage)) {
        $storage = $self->vm->get_storage_pool_by_name($storage);
    }
435
436
437
438
439
440
441
442
443
444
    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;

}

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

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

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

}

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

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

497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
=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

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

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

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

565
    my $domain;
566

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

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

=head2 list_domains

Returns a list of the created domains

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

=cut

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

600
601
    return if !$self->vm;

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

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

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

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

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

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

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

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

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

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

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

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

    return $img_file;

}

sub _volume_path {
    my $self = shift;

    my %args = @_;
701
702
703
704
705
706
    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);
707
    my $suffix = ".img";
708
    $suffix = ".SWAP.img"   if $swap;
709
710
    $filename .= "-$target" if $target;
    my (undef, $img_file) = tempfile($filename."-XXXX"
711
712
713
714
715
716
717
718
719
720
        ,DIR => $dir_img
        ,OPEN => 0
        ,SUFFIX => $suffix
    );
    return $img_file;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

    return $domain;
}

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

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

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

    my $dom;

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

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

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
885
886
    my $clone_pool = $self->clone_storage_pool();
    $dir_img = $self->_storage_path($clone_pool) if $clone_pool;
887
888
889

    my @files_out;

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

897
898
899
900
901
902
903
904
905
906
907
        $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) {

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

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

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

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

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

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


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

985
    my ($domain, $spice_password)
986
        = $self->_domain_create_common($xml,%args, is_volatile => $base->volatile_clones);
Francesc Guasch's avatar
Francesc Guasch committed
987
988
989
    $domain->_insert_db(name=> $args{name}, id_base => $base->id, id_owner => $args{id_owner}
        , id_vm => $self->id
    );
990
    $domain->_set_spice_password($spice_password);
991
    $domain->xml_description();
992
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
    my ($all_devices) = $doc->findnodes('/domain/devices');
For faster browsing, not all history is shown. View entire blame