VM.pm 33.7 KB
Newer Older
1
2
3
4
use warnings;
use strict;

package Ravada::VM;
5

6
7
8
9
10
=head1 NAME

Ravada::VM - Virtual Managers library for Ravada

=cut
11

Francesc Guasch's avatar
Francesc Guasch committed
12
use Carp qw( carp croak cluck);
13
use Data::Dumper;
14
use File::Path qw(make_path);
15
use Hash::Util qw(lock_hash);
16
use IPC::Run3 qw(run3);
17
use JSON::XS;
18
19
20
use Socket qw( inet_aton inet_ntoa );
use Moose::Role;
use Net::DNS;
Francesc Guasch's avatar
Francesc Guasch committed
21
use Net::Ping;
Francesc Guasch's avatar
Francesc Guasch committed
22
use Net::SSH2 qw(LIBSSH2_FLAG_SIGPIPE);
23
24
25
26
use IO::Socket;
use IO::Interface;
use Net::Domain qw(hostfqdn);

27
28
use Ravada::Utils;

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

32
33
34
35
36
37
38
39
40
requires 'connect';

# global DB Connection

our $CONNECTOR = \$Ravada::CONNECTOR;
our $CONFIG = \$Ravada::CONFIG;

our $MIN_MEMORY_MB = 128 * 1024;

Francesc Guasch's avatar
Francesc Guasch committed
41
42
our $SSH_TIMEOUT = 20 * 1000;

Francesc Guasch's avatar
Francesc Guasch committed
43
our %VM; # cache Virtual Manager Connection
44
our %SSH;
Francesc Guasch's avatar
Francesc Guasch committed
45
46
47
48

our $ARP = `which arp`;
chomp $ARP;

49
50
51
52
53
54
55
56
# domain
requires 'create_domain';
requires 'search_domain';

requires 'list_domains';

# storage volume
requires 'create_volume';
Francesc Guasch's avatar
Francesc Guasch committed
57
requires 'list_storage_pools';
58
59
60

requires 'connect';
requires 'disconnect';
61
requires 'import_domain';
62

63
requires 'is_alive';
64
65

requires 'free_memory';
Francesc Guasch's avatar
Francesc Guasch committed
66
requires 'free_disk';
Francesc Guasch's avatar
Francesc Guasch committed
67
68
69

requires '_fetch_dir_cert';

70
71
72
73
74
75
76
77
############################################################

has 'host' => (
          isa => 'Str'
         , is => 'ro',
    , default => 'localhost'
);

78
79
has 'public_ip' => (
        isa => 'Str'
Francesc Guasch's avatar
Francesc Guasch committed
80
        , is => 'rw'
81
82
);

83
84
85
86
87
88
89
90
91
92
has 'default_dir_img' => (
      isa => 'String'
     , is => 'ro'
);

has 'readonly' => (
    isa => 'Str'
    , is => 'ro'
    ,default => 0
);
93

Francesc Guasch's avatar
Francesc Guasch committed
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
has 'tls_host_subject' => (
    isa => 'Str'
    , is => 'ro'
    , builder => '_fetch_tls_host_subject'
    , lazy => 1
);

has 'tls_ca' => (
    isa => 'Str'
    , is => 'ro'
    , builder => '_fetch_tls_ca'
    , lazy => 1
);

has dir_cert => (
    isa => 'Str'
    ,is => 'ro'
    ,lazy => 1
    ,builder => '_fetch_dir_cert'
);

Francesc Guasch's avatar
Francesc Guasch committed
115
116
117
118
119
has 'store' => (
    isa => 'Bool'
    , is => 'rw'
    , default => 1
);
120
121
122
123
124
125
126
############################################################
#
# Method Modifiers definition
# 
#
around 'create_domain' => \&_around_create_domain;

127
128
before 'search_domain' => \&_pre_search_domain;
before 'list_domains' => \&_pre_list_domains;
129
130
131

before 'create_volume' => \&_connect;

132
around 'import_domain' => \&_around_import_domain;
Francesc Guasch's avatar
Francesc Guasch committed
133

Francesc Guasch's avatar
Francesc Guasch committed
134
around 'ping' => \&_around_ping;
Francesc Guasch's avatar
Francesc Guasch committed
135
around 'connect' => \&_around_connect;
Francesc Guasch's avatar
Francesc Guasch committed
136

137
138
139
140
#############################################################
#
# method modifiers
#
141

142
143
144
145
146
147
148
sub _init_connector {
    return if $CONNECTOR && $$CONNECTOR;
    $CONNECTOR = \$Ravada::CONNECTOR if $Ravada::CONNECTOR;
    $CONNECTOR = \$Ravada::Front::CONNECTOR if !defined $$CONNECTOR
                                                && defined $Ravada::Front::CONNECTOR;
}

149
150
151
152
153
154
155
156
157
158
159
160
=head1 Constructors

=head2 open

Opens a Virtual Machine Manager (VM)

Arguments: id of the VM

=cut

sub open {
    my $proto = shift;
161
162
163
164
165
166
167
168
169
    my %args;
    if (!scalar @_ % 2) {
        %args = @_;
        confess "ERROR: Don't set the id and the type "
            if $args{id} && $args{type};
        return _open_type($proto,@_) if $args{type};
    } else {
        $args{id} = shift;
    }
170
171
172
173
    my $class=ref($proto) || $proto;

    my $self = {};
    bless($self, $class);
174
    my $row = $self->_do_select_vm_db( id => $args{id});
175
    lock_hash(%$row);
176
    confess "ERROR: I can't find VM id=$args{id}" if !$row || !keys %$row;
177

Francesc Guasch's avatar
Francesc Guasch committed
178
179
    return $VM{$args{id}} if $VM{$args{id}} && $VM{$args{id}}->name eq $row->{name};

180
181
182
183
184
    my $type = $row->{vm_type};
    $type = 'KVM'   if $type eq 'qemu';
    $class .= "::$type";
    bless ($self,$class);

185
    $args{host} = $row->{hostname};
186
    $args{security} = decode_json($row->{security}) if $row->{security};
187

Francesc Guasch's avatar
Francesc Guasch committed
188
189
190
    my $vm = $self->new(%args);
    $VM{$args{id}} = $vm;
    return $vm;
191
192
193

}

Francesc Guasch's avatar
Francesc Guasch committed
194
195
196
197
sub _clean_cache {
    %VM = ();
}

198
199
sub BUILD {
    my $self = shift;
200
201
202

    my $args = $_[0];

203
204
205
    my $id = delete $args->{id};
    my $host = delete $args->{host};
    my $name = delete $args->{name};
Francesc Guasch's avatar
Francesc Guasch committed
206
207
208
    my $store = delete $args->{store};
    $store = 1 if !defined $store;

209
210
    delete $args->{readonly};
    delete $args->{security};
211
    delete $args->{public_ip};
212
213
214
215

    # TODO check if this is needed
    delete $args->{connector};

Francesc Guasch's avatar
Francesc Guasch committed
216
217
    lock_hash(%$args);

218
    confess "ERROR: Unknown args ".join (",", keys (%$args)) if keys %$args;
Francesc Guasch's avatar
Francesc Guasch committed
219
    return if !$store;
220
221
    if ($id) {
        $self->_select_vm_db(id => $id)
222
223
    } else {
        my %query = (
Francesc Guasch's avatar
Francesc Guasch committed
224
            hostname => ($host or 'localhost')
225
226
            ,vm_type => $self->type
        );
Francesc Guasch's avatar
Francesc Guasch committed
227
        $query{name} = $name  if $name;
228
229
        $self->_select_vm_db(%query);
    }
230
    $self->id;
Francesc Guasch's avatar
Francesc Guasch committed
231
232
233
234
235
236
237

    $self->public_ip($self->_data('public_ip'))
        if defined $self->_data('public_ip')
            && (!defined $self->public_ip
                || $self->public_ip ne $self->_data('public_ip')
            );

238
239
}

240
241
242
243
244
245
246
247
248
249
sub _open_type {
    my $self = shift;
    my %args = @_;

    my $type = delete $args{type} or confess "ERROR: Missing VM type";
    my $class = "Ravada::VM::$type";

    my $proto = {};
    bless $proto,$class;

250
    my $vm = $proto->new(%args);
251
252
253
254
    eval { $vm->vm };
    warn $@ if $@;

    return $vm;
255
256
257

}

258
259
260
261
262
263
264
265
266
sub _check_readonly {
    my $self = shift;
    confess "ERROR: You can't create domains in read-only mode "
        if $self->readonly 

}

sub _connect {
    my $self = shift;
Francesc Guasch's avatar
Francesc Guasch committed
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
    my $result = $self->connect();
    if ($result) {
        $self->is_active(1);
    } else {
        $self->is_active(0);
    }
    return $result;
}

sub _around_connect($orig, $self) {
    my $result = $self->$orig();
    if ($result) {
        $self->is_active(1);
    } else {
        $self->is_active(0);
    }
    return $result;
284
285
286
287
288
289
290
}

sub _pre_create_domain {
    _check_create_domain(@_);
    _connect(@_);
}

291
292
293
294
295
296
297
298
299
300
sub _pre_search_domain($self,@) {
    $self->_connect();
    die "ERROR: VM ".$self->name." unavailable" if !$self->ping();
}

sub _pre_list_domains($self,@) {
    $self->_connect();
    die "ERROR: VM ".$self->name." unavailable" if !$self->ping();
}

301
302
sub _connect_ssh($self, $disconnect=0) {
    confess "Don't connect to local ssh"
Francesc Guasch's avatar
Francesc Guasch committed
303
304
        if $self->is_local;

305
    if ( $self->readonly ) {
306
        warn $self->name." readonly, don't do ssh";
307
308
        return;
    }
Francesc Guasch's avatar
Francesc Guasch committed
309
310
    return if !$self->ping();

311
312
313
    my @pwd = getpwuid($>);
    my $home = $pwd[7];

314
315
316
317
318
    my $ssh= $self->{_ssh};
    $ssh = $SSH{$self->host}    if exists $SSH{$self->host};

    if (! $ssh || $disconnect ) {
        $ssh->disconnect if $ssh && $disconnect;
Francesc Guasch's avatar
Francesc Guasch committed
319
        $ssh = Net::SSH2->new( timeout => $SSH_TIMEOUT );
320
321
        my $connect;
        for ( 1 .. 3 ) {
322
            eval { $connect = $ssh->connect($self->host) };
323
324
325
326
            last if $connect;
            warn "RETRYING ssh ".$self->host." ".join(" ",$ssh->error);
            sleep 1;
        }
327
328
329
330
331
332
333
        if ( !$connect) {
            eval { $connect = $ssh->connect($self->host) };
            if (!$connect) {
                $self->_cached_active(0);
                confess $ssh->error();
            }
        }
334
335
336
337
338
339
        $ssh->auth_publickey( 'root'
            , "$home/.ssh/id_rsa.pub"
            , "$home/.ssh/id_rsa"
        ) or $ssh->die_with_error();
        $self->{_ssh} = $ssh;
        $SSH{$self->host} = $ssh;
Francesc Guasch's avatar
Francesc Guasch committed
340
    }
341
    return $ssh;
342
343
}

344
sub _ssh_channel($self) {
345
    my $ssh = $self->_connect_ssh() or confess "ERROR: I can't connect to SSH in ".$self->host;
346
347
348
349
350
    my $ssh_channel;
    for ( 1 .. 5 ) {
        $ssh_channel = $ssh->channel();
        last if $ssh_channel;
        sleep 1;
351
    }
352
353
354
    if (!$ssh_channel) {
        $ssh = $self->_connect_ssh(1);
        $ssh_channel = $ssh->channel();
Francesc Guasch's avatar
Francesc Guasch committed
355
    }
356
357
358
    die $ssh->die_with_error    if !$ssh_channel;
    $ssh->blocking(1);
    return $ssh_channel;
Francesc Guasch's avatar
Francesc Guasch committed
359
360
}

361
362
363
364
365
sub _around_create_domain {
    my $orig = shift;
    my $self = shift;
    my %args = @_;

366
    my $id_owner = delete $args{id_owner} or confess "ERROR: Missing id_owner";
Francesc Guasch's avatar
Francesc Guasch committed
367
    my $owner = Ravada::Auth::SQL->search_by_id($id_owner) or confess "Unknown user id: $id_owner";
368
369

    my $base;
Francesc Guasch's avatar
Francesc Guasch committed
370
    my $remote_ip = delete $args{remote_ip};
Francesc Guasch's avatar
Francesc Guasch committed
371
    my $volatile = delete $args{volatile};
372
    my $id_base = delete $args{id_base};
Francesc Guasch's avatar
Francesc Guasch committed
373
374
375
376
377
378
379
380
381
382
     my $id_iso = delete $args{id_iso};
     my $active = delete $args{active};
       my $name = delete $args{name};
       my $swap = delete $args{swap};

     # args get deleted but kept on @_ so when we call $self->$orig below are passed
     delete $args{disk};
     delete $args{memory};
     delete $args{request};
     delete $args{iso_file};
383
     delete $args{id_template};
384
     delete @args{'description','remove_cpu','vm','start'};
Francesc Guasch's avatar
Francesc Guasch committed
385
386
387

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

Francesc Guasch's avatar
Francesc Guasch committed
388
    $self->_check_duplicate_name($name);
389
390
391
    if ($id_base) {
        $base = $self->search_domain_by_id($id_base)
            or confess "Error: I can't find domain $id_base on ".$self->name;
Francesc Guasch's avatar
Francesc Guasch committed
392
        $volatile = 1 if $base->volatile_clones;
393
    }
Francesc Guasch's avatar
Francesc Guasch committed
394

395
396
397
398
399
400
401
    confess "ERROR: User ".$owner->name." is not allowed to create machines"
        unless $owner->is_admin
            || $owner->can_create_machine()
            || ($base && $owner->can_clone);

    confess "ERROR: Base ".$base->name." is private"
        if !$owner->is_admin && $base && !$base->is_public();
402

403
    $self->_pre_create_domain(@_);
404

Francesc Guasch's avatar
Francesc Guasch committed
405
    my $domain = $self->$orig(@_, volatile => $volatile);
Francesc Guasch's avatar
Francesc Guasch committed
406
    $domain->add_volume_swap( size => $swap )   if $swap;
407

408
    if ($id_base) {
409
410
411
        $domain->run_timeout($base->run_timeout)
            if defined $base->run_timeout();
    }
412
    my $user = Ravada::Auth::SQL->search_by_id($id_owner);
413
    $domain->is_volatile(1)     if $user->is_temporary() ||($base && $base->volatile_clones());
Francesc Guasch's avatar
Francesc Guasch committed
414
415
416
417
418

    my @start_args = ( user => $owner );
    push @start_args, (remote_ip => $remote_ip) if $remote_ip;

    $domain->_post_start(@start_args) if $domain->is_active;
Francesc Guasch's avatar
Francesc Guasch committed
419
    eval {
Francesc Guasch's avatar
Francesc Guasch committed
420
           $domain->start(@start_args)      if $active || ($domain->is_volatile && ! $domain->is_active);
Francesc Guasch's avatar
Francesc Guasch committed
421
422
    };
    die $@ if $@ && $@ !~ /code: 55,/;
423

Francesc Guasch's avatar
Francesc Guasch committed
424
    $domain->info($owner);
425
    $domain->display($owner)    if $domain->is_active;
Francesc Guasch's avatar
Francesc Guasch committed
426

427
428
429
    return $domain;
}

Francesc Guasch's avatar
Francesc Guasch committed
430
431
432
433
434
435
436
437
438
sub _check_duplicate_name($self, $name) {
    my $sth = $$CONNECTOR->dbh->prepare("SELECT id,name,vm FROM domains where name=?");
    $sth->execute($name);
    my $row = $sth->fetchrow_hashref;
    confess "Error: machine with name '$name' already exists ".Dumper($row)
        if $row->{id};
    return 1;
}

439
440
441
sub _around_import_domain {
    my $orig = shift;
    my $self = shift;
442
    my ($name, $user, $spinoff) = @_;
443

444
    my $domain = $self->$orig($name, $user);
445
446
447

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

448
    if ($spinoff) {
449
450
        warn "Spinning volumes off their backing files ...\n"
            if $ENV{TERM} && $0 !~ /\.t$/;
451
452
        $domain->spinoff_volumes();
    }
453
    return $domain;
454
455
}

456
457
############################################################
#
458

459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
sub _domain_remove_db {
    my $self = shift;
    my $name = shift;
    my $sth = $$CONNECTOR->dbh->prepare("DELETE FROM domains WHERE name=?");
    $sth->execute($name);
    $sth->finish;
}

=head2 domain_remove

Remove the domain. Returns nothing.

=cut


sub domain_remove {
    my $self = shift;
    $self->domain_remove_vm();
    $self->_domain_remove_bd();
}

=head2 name

Returns the name of this Virtual Machine Manager

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

=cut

sub name {
    my $self = shift;

491
    return $self->_data('name') if defined $self->{_data}->{name};
492

493
494
    my ($ref) = ref($self) =~ /.*::(.*)/;
    return ($ref or ref($self))."_".$self->host;
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
}

=head2 search_domain_by_id

Returns a domain searching by its id

    $domain = $vm->search_domain_by_id($id);

=cut

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

    my $sth = $$CONNECTOR->dbh->prepare("SELECT name FROM domains "
        ." WHERE id=?");
    $sth->execute($id);
    my ($name) = $sth->fetchrow;
    return if !$name;

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

Francesc Guasch's avatar
Francesc Guasch committed
518
519
520
521
522
523
524
525
sub _domain_in_db($self, $name) {

    my $sth = $$CONNECTOR->dbh->prepare("SELECT id FROM domains WHERE name=?");
    $sth->execute($name);
    my ($id) =$sth->fetchrow;
    return $id;
}

526
527
528
529
530
531
532
533
534
=head2 ip

Returns the external IP this for this VM

=cut

sub ip {
    my $self = shift;

535
536
    my $name = ($self->public_ip or $self->host())
        or confess "this vm has no host name";
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
    my $ip = inet_ntoa(inet_aton($name)) ;

    return $ip if $ip && $ip !~ /^127\./;

    $name = Ravada::display_ip();

    if ($name) {
        if ($name =~ /^\d+\.\d+\.\d+\.\d+$/) {
            $ip = $name;
        } else {
            $ip = inet_ntoa(inet_aton($name));
        }
    }
    return $ip if $ip && $ip !~ /^127\./;

    $ip = $self->_interface_ip();
    return $ip if $ip && $ip !~ /^127/ && $ip =~ /^\d+\.\d+\.\d+\.\d+$/;

    warn "WARNING: I can't find the IP of host ".$self->host.", using localhost."
Francesc Guasch's avatar
Francesc Guasch committed
556
        ." This virtual machine won't be available from the network." if $0 !~ /\.t$/;
557
558
559
560

    return '127.0.0.1';
}

Francesc Guasch's avatar
Francesc Guasch committed
561
562
563
564
565
566
=head2 nat_ip

Returns the IP of the VM when it is in a NAT environment

=cut

567
sub nat_ip($self) {
568
    return Ravada::nat_ip();
569
570
}

571
572
573
574
575
sub _interface_ip($self, $remote_ip=undef) {
    return '127.0.0.1' if $remote_ip && $remote_ip =~ /^127\./;
    my ($out, $err) = $self->run_command("/sbin/ip","route");
    my %route;
    my ($default_gw , $default_ip);
576

577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
    my $remote_ip_addr = NetAddr::IP->new($remote_ip);

    for my $line ( split( /\n/, $out ) ) {
        if ( $line =~ m{^default via ([\d\.]+)} ) {
            $default_gw = NetAddr::IP->new($1);
        }
        if ( $line =~ m{^([\d\.\/]+).*src ([\d\.\/]+)} ) {
            my ($network, $ip) = ($1, $2);
            $route{$network} = $ip;

            my $netaddr = NetAddr::IP->new($network);
            return $ip if $remote_ip_addr->within($netaddr);

            $default_ip = $ip if defined $default_gw && $default_gw->within($netaddr);
        }
592
    }
593
    return $default_ip;
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
}

sub _check_memory {
    my $self = shift;
    my %args = @_;
    return if !exists $args{memory};

    die "ERROR: Low memory '$args{memory}' required ".int($MIN_MEMORY_MB/1024)." MB " if $args{memory} < $MIN_MEMORY_MB;
}

sub _check_disk {
    my $self = shift;
    my %args = @_;
    return if !exists $args{disk};

    die "ERROR: Low Disk '$args{disk}' required 1 Gb " if $args{disk} < 1024*1024;
}


sub _check_create_domain {
    my $self = shift;

    my %args = @_;

    $self->_check_readonly(@_);

    $self->_check_require_base(@_);
    $self->_check_memory(@_);
    $self->_check_disk(@_);

}

sub _check_require_base {
    my $self = shift;

    my %args = @_;
630
631
632
633
634
635

    my $id_base = delete $args{id_base} or return;
    my $request = delete $args{request};
    my $id_owner = delete $args{id_owner}
        or confess "ERROR: id_owner required ";

636
637
638
    delete $args{start};
    delete $args{remote_ip};

Francesc Guasch's avatar
Francesc Guasch committed
639
    delete @args{'_vm','name','vm', 'memory','description','id_iso'};
640
641
642
643
644

    confess "ERROR: Unknown arguments ".join(",",keys %args)
        if keys %args;

    my $base = Ravada::Domain->open($id_base);
645
646
647
648
649
650
    my %ignore_requests = map { $_ => 1 } qw(clone refresh_machine set_base_vm start_clones);
    my @requests;
    for my $req ( $base->list_requests ) {
        push @requests,($req) if !$ignore_requests{$req->command};
    }
    if (@requests) {
651
652
        confess "ERROR: Domain ".$base->name." has ".$base->list_requests
                            ." requests.\n"
Francesc Guasch's avatar
Francesc Guasch committed
653
                            .Dumper([$base->list_requests])
654
655
            unless scalar @requests == 1 && $request
                && $requests[0]->id eq $request->id;
656
657
    }

658

659
660
661
    die "ERROR: Domain ".$self->name." is not base"
            if !$base->is_base();

662
663
664
665
    my $user = Ravada::Auth::SQL->search_by_id($id_owner);

    die "ERROR: Base ".$base->name." is not public\n"
        unless $user->is_admin || $base->is_public;
666
667
}

668
669
670
671
672
673
674
675
676
677
678
=head2 id

Returns the id value of the domain. This id is used in the database
tables and is not related to the virtual machine engine.

=cut

sub id {
    return $_[0]->_data('id');
}

Francesc Guasch's avatar
Francesc Guasch committed
679
sub _data($self, $field, $value=undef) {
Francesc Guasch's avatar
Francesc Guasch committed
680
    if (defined $value && $self->store ) {
681
682
683
684
685
686
687
688
689
        $self->{_data}->{$field} = $value;
        my $sth = $$CONNECTOR->dbh->prepare(
            "UPDATE vms set $field=?"
            ." WHERE id=?"
        );
        $sth->execute($value, $self->id);
        $sth->finish;
        return $value;
    }
690
691
692
693

#    _init_connector();

    return $self->{_data}->{$field} if exists $self->{_data}->{$field};
Francesc Guasch's avatar
Francesc Guasch committed
694
695
    return if !$self->store();

696
697
698
699
700
701
702
703
704
705
706
707
    $self->{_data} = $self->_select_vm_db( name => $self->name);

    confess "No DB info for VM ".$self->name    if !$self->{_data};
    confess "No field $field in vms"            if !exists$self->{_data}->{$field};

    return $self->{_data}->{$field};
}

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

708
709
    _init_connector();

710
711
712
713
714
715
716
717
    if (!keys %args) {
        my $id;
        eval { $id = $self->id  };
        if ($id) {
            %args =( id => $id );
        }
    }

Francesc Guasch's avatar
Francesc Guasch committed
718
    confess Dumper(\%args) if !keys %args;
719
    my $sth = $$CONNECTOR->dbh->prepare(
720
        "SELECT * FROM vms WHERE ".join(" AND ",map { "$_=?" } sort keys %args )
721
722
723
724
    );
    $sth->execute(map { $args{$_} } sort keys %args);
    my $row = $sth->fetchrow_hashref;
    $sth->finish;
Francesc Guasch's avatar
Francesc Guasch committed
725
726
727

    return if !$row;

728
729
730
731
732
733
    return $row;
}

sub _select_vm_db {
    my $self = shift;

734
    my ($row) = ($self->_do_select_vm_db(@_) or $self->_insert_vm_db(@_));
735
736
737
738
739
740
741

    $self->{_data} = $row;
    return $row if $row->{id};
}

sub _insert_vm_db {
    my $self = shift;
Francesc Guasch's avatar
Francesc Guasch committed
742
743
    return if !$self->store();

744
    my $sth = $$CONNECTOR->dbh->prepare(
745
746
        "INSERT INTO vms (name, vm_type, hostname, public_ip)"
        ." VALUES(?, ?, ?, ?)"
747
    );
748
749
750
751
    my %args = @_;
    my $name = ( delete $args{name} or $self->name);
    my $host = ( delete $args{hostname} or $self->host );
    delete $args{vm_type};
752

753
754
    confess "Unknown args ".Dumper(\%args)  if keys %args;

755
    eval { $sth->execute($name,$self->type,$host, $self->public_ip)  };
756
    confess $@ if $@;
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
    $sth->finish;

    return $self->_do_select_vm_db( name => $name);
}

=head2 default_storage_pool_name

Set the default storage pool name for this Virtual Machine Manager

    $vm->default_storage_pool_name('default');

=cut

sub default_storage_pool_name {
    my $self = shift;
    my $value = shift;

    #TODO check pool exists
    if (defined $value) {
        my $id = $self->id();
        my $sth = $$CONNECTOR->dbh->prepare(
            "UPDATE vms SET default_storage=?"
            ." WHERE id=?"
        );
        $sth->execute($value,$id);
        $self->{_data}->{default_storage} = $value;
    }
Francesc Guasch's avatar
Francesc Guasch committed
784
    $self->_select_vm_db() if $self->store();
785
786
787
    return $self->_data('default_storage');
}

Francesc Guasch's avatar
Francesc Guasch committed
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
=head2 base_storage_pool

Set the storage pool for bases in this Virtual Machine Manager

    $vm->base_storage_pool('pool2');

=cut

sub base_storage_pool {
    my $self = shift;
    my $value = shift;

    #TODO check pool exists
    if (defined $value) {
        my $id = $self->id();
        my $sth = $$CONNECTOR->dbh->prepare(
            "UPDATE vms SET base_storage=?"
            ." WHERE id=?"
        );
        $sth->execute($value,$id);
        $self->{_data}->{base_storage} = $value;
    }
810
    $self->_select_vm_db();
Francesc Guasch's avatar
Francesc Guasch committed
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
    return $self->_data('base_storage');
}

=head2 clone_storage_pool

Set the storage pool for clones in this Virtual Machine Manager

    $vm->clone_storage_pool('pool3');

=cut

sub clone_storage_pool {
    my $self = shift;
    my $value = shift;

    #TODO check pool exists
    if (defined $value) {
        my $id = $self->id();
        my $sth = $$CONNECTOR->dbh->prepare(
            "UPDATE vms SET clone_storage=?"
            ." WHERE id=?"
        );
        $sth->execute($value,$id);
        $self->{_data}->{clone_storage} = $value;
    }
836
    $self->_select_vm_db();
Francesc Guasch's avatar
Francesc Guasch committed
837
838
839
    return $self->_data('clone_storage');
}

840
841
842
843
844
845
846
847
848
849
850
=head2 min_free_memory

Returns the minimun free memory necessary to start a new virtual machine

=cut

sub min_free_memory {
    my $self = shift;
    return $self->_data('min_free_memory');
}

Francesc Guasch's avatar
Francesc Guasch committed
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
=head2 max_load 

Returns the maximum cpu load that the host can handle.

=cut

sub max_load {
    my $self = shift;
    return $self->_data('max_load');
}

=head2 active_limit

Returns the value of 'active_limit' in the BBDD

=cut

sub active_limit {
    my $self = shift;
    return $self->_data('active_limit');
}
872

Francesc Guasch's avatar
Francesc Guasch committed
873
874
875
876
877
878
879
880
881
882
883
884
885
=head2 list_drivers

Lists the drivers available for this Virtual Machine Manager

Arguments: Optional driver type

Returns a list of strings with the nams of the drivers.

    my @drivers = $vm->list_drivers();
    my @drivers = $vm->list_drivers('image');

=cut

Francesc Guasch's avatar
Francesc Guasch committed
886
887
888
sub list_drivers($self, $name=undef) {
    return Ravada::Domain::drivers(undef,$name,$self->type);
}
889

Francesc Guasch's avatar
Francesc Guasch committed
890
891
892
893
894
895
=head2 is_local

Returns wether this virtual manager is in the local host

=cut

896
sub is_local($self) {
897
    return 1 if $self->host eq 'localhost'
898
899
        || $self->host eq '127.0.0,1'
        || !$self->host;
900
    return 0;
901
902
}

903
904
905
906
907
908
909
910
911

=head2 list_nodes

Returns a list of virtual machine manager nodes of the same type as this.

    my @nodes = $self->list_nodes();

=cut

912
sub list_nodes($self) {
913
914
    return @{$self->{_nodes}} if $self->{_nodes};

915
916
917
918
919
920
921
922
923
924
    my $sth = $$CONNECTOR->dbh->prepare(
        "SELECT id FROM vms WHERE vm_type=?"
    );
    my @nodes;
    $sth->execute($self->type);

    while (my ($id) = $sth->fetchrow) {
        push @nodes,(Ravada::VM->open($id))
    }

925
    $self->{_nodes} = \@nodes;
926
927
    return @nodes;
}
928

929
930
931
932
933
934
=head2 ping

Returns if the virtual manager connection is available

=cut

935
936
sub ping($self, $option=undef) {
    confess "ERROR: option unknown" if defined $option && $option ne 'debug';
Francesc Guasch's avatar
Francesc Guasch committed
937
938

    return 1 if $self->is_local();
939
940
941
    my $debug = 0;
    $debug = 1 if defined $option && $option eq 'debug';

Francesc Guasch's avatar
Francesc Guasch committed
942
943
944
945
    return $self->_do_ping($self->host, $debug);
}

sub _do_ping($self, $host, $debug=0) {
946

Francesc Guasch's avatar
Francesc Guasch committed
947
    my $p = Net::Ping->new('tcp',2);
948
    my $ping_ok;
Francesc Guasch's avatar
Francesc Guasch committed
949
950
951
952
953
    eval { $ping_ok = $p->ping($host) };
    confess $@ if $@;
    warn "$@ pinging host $host" if $@;

    $self->_store_mac_address() if $ping_ok && $self;
954
    return 1 if $ping_ok;
Francesc Guasch's avatar
Francesc Guasch committed
955
956
    $p->close();

957
    return if $>; # icmp ping requires root privilege
958
    warn "trying icmp"   if $debug;
Francesc Guasch's avatar
Francesc Guasch committed
959
    $p= Net::Ping->new('icmp',2);
Francesc Guasch's avatar
Francesc Guasch committed
960
    eval { $ping_ok = $p->ping($host) };
961
    warn $@ if $@;
Francesc Guasch's avatar
Francesc Guasch committed
962
    $self->_store_mac_address() if $ping_ok && $self;
963
    return 1 if $ping_ok;
Francesc Guasch's avatar
Francesc Guasch committed
964

965
    return 0;
Francesc Guasch's avatar
Francesc Guasch committed
966
967
}

Francesc Guasch's avatar
Francesc Guasch committed
968
969
970
971
972
973
974
975
976
sub _around_ping($orig, $self, $option=undef) {

    my $ping = $self->$orig($option);
    $self->_cached_active($ping);
    $self->_cached_active_time(time);

    return $ping;
}

977
978
=head2 is_active

979
980
981
982
983
984
985
986
987
988
989
Returns if the domain is active. The active state is cached for some seconds.
Pass an optional true value to perform a real check.

Arguments: optional force mode

    if ($node->is_active) {
    }


    if ($node->is_active(1)) {
    }
990
991
992

=cut

993
994
sub is_active($self, $force=0) {
    return $self->_do_is_active() if $self->is_local || $force;
995

996
    return $self->_cached_active if time - $self->_cached_active_time < 60;
997
998
999
1000
    return $self->_do_is_active();
}

sub _do_is_active($self) {
For faster browsing, not all history is shown. View entire blame