VM.pm 22.5 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 Hash::Util qw(lock_hash);
15
use IPC::Run3 qw(run3);
16
use JSON::XS;
17
18
19
use Socket qw( inet_aton inet_ntoa );
use Moose::Role;
use Net::DNS;
Francesc Guasch's avatar
Francesc Guasch committed
20
use Net::Ping;
21
use Net::SSH2;
22
23
24
25
use IO::Socket;
use IO::Interface;
use Net::Domain qw(hostfqdn);

Francesc Guasch's avatar
Francesc Guasch committed
26
27
28
no warnings "experimental::signatures";
use feature qw(signatures);

29
30
31
32
33
34
35
36
37
requires 'connect';

# global DB Connection

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

our $MIN_MEMORY_MB = 128 * 1024;

38
our %SSH;
39
40
41
42
43
44
45
46
# domain
requires 'create_domain';
requires 'search_domain';

requires 'list_domains';

# storage volume
requires 'create_volume';
Francesc Guasch's avatar
Francesc Guasch committed
47
requires 'list_storage_pools';
48
49
50

requires 'connect';
requires 'disconnect';
51
requires 'import_domain';
52

53
requires 'is_alive';
54
55

requires 'free_memory';
56
57
58
59
60
61
62
63
############################################################

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

64
65
has 'public_ip' => (
        isa => 'Str'
Francesc Guasch's avatar
Francesc Guasch committed
66
        , is => 'rw'
67
68
);

69
70
71
72
73
74
75
76
77
78
has 'default_dir_img' => (
      isa => 'String'
     , is => 'ro'
);

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

80
81
82
83
84
85
86
############################################################
#
# Method Modifiers definition
# 
#
around 'create_domain' => \&_around_create_domain;

87
88
before 'search_domain' => \&_pre_search_domain;
before 'list_domains' => \&_pre_list_domains;
89
90
91

before 'create_volume' => \&_connect;

92
around 'import_domain' => \&_around_import_domain;
Francesc Guasch's avatar
Francesc Guasch committed
93

Francesc Guasch's avatar
Francesc Guasch committed
94
95
around 'ping' => \&_around_ping;

96
97
98
99
#############################################################
#
# method modifiers
#
100

101
102
103
104
105
106
107
sub _init_connector {
    return if $CONNECTOR && $$CONNECTOR;
    $CONNECTOR = \$Ravada::CONNECTOR if $Ravada::CONNECTOR;
    $CONNECTOR = \$Ravada::Front::CONNECTOR if !defined $$CONNECTOR
                                                && defined $Ravada::Front::CONNECTOR;
}

108
109
110
111
112
113
114
115
116
117
118
119
=head1 Constructors

=head2 open

Opens a Virtual Machine Manager (VM)

Arguments: id of the VM

=cut

sub open {
    my $proto = shift;
120
121
122
123
124
125
126
127
128
    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;
    }
129
130
131
132
    my $class=ref($proto) || $proto;

    my $self = {};
    bless($self, $class);
133
    my $row = $self->_do_select_vm_db( id => $args{id});
134
    lock_hash(%$row);
135
    confess "ERROR: I can't find VM id=$args{id}" if !$row || !keys %$row;
136
137
138
139
140
141

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

142
    $args{host} = $row->{hostname};
143
    $args{security} = decode_json($row->{security}) if $row->{security};
144

145
    return $self->new(%args);
146
147
148

}

149
150
sub BUILD {
    my $self = shift;
151
152
153

    my $args = $_[0];

154
155
156
157
158
    my $id = delete $args->{id};
    my $host = delete $args->{host};
    my $name = delete $args->{name};
    delete $args->{readonly};
    delete $args->{security};
159
    delete $args->{public_ip};
160
161
162
163

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

Francesc Guasch's avatar
Francesc Guasch committed
164
165
    lock_hash(%$args);

166
167
168
169
    confess "ERROR: Unknown args ".join (",", keys (%$args)) if keys %$args;

    if ($id) {
        $self->_select_vm_db(id => $id)
170
171
    } else {
        my %query = (
Francesc Guasch's avatar
Francesc Guasch committed
172
            hostname => ($host or 'localhost')
173
174
            ,vm_type => $self->type
        );
Francesc Guasch's avatar
Francesc Guasch committed
175
        $query{name} = $name  if $name;
176
177
        $self->_select_vm_db(%query);
    }
178
    $self->id;
Francesc Guasch's avatar
Francesc Guasch committed
179
180
181
182
183
184
185

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

186
187
}

188
189
190
191
192
193
194
195
196
197
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;

198
    my $vm = $proto->new(%args);
199
200
201
202
203
    eval { $vm->vm };
    warn $@ if $@;
    return if $@;

    return $vm;
204
205
206

}

207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
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;
    $self->connect();
}

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

224
225
226
227
228
229
230
231
232
233
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();
}

234
235
sub _connect_ssh($self, $disconnect=0) {
    confess "Don't connect to local ssh"
Francesc Guasch's avatar
Francesc Guasch committed
236
237
        if $self->is_local;

238
    if ( $self->readonly ) {
239
        warn $self->name." readonly, don't do ssh";
240
241
        return;
    }
Francesc Guasch's avatar
Francesc Guasch committed
242
243
    return if !$self->ping();

244
245
246
    my @pwd = getpwuid($>);
    my $home = $pwd[7];

247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
    my $ssh= $self->{_ssh};
    $ssh = $SSH{$self->host}    if exists $SSH{$self->host};

    if (! $ssh || $disconnect ) {
        $ssh->disconnect if $ssh && $disconnect;
        $ssh = Net::SSH2->new();
        my $connect;
        for ( 1 .. 3 ) {
            $connect = $ssh->connect($self->host);
            last if $connect;
            warn "RETRYING ssh ".$self->host." ".join(" ",$ssh->error);
            sleep 1;
        }
        $connect = $ssh->connect($self->host)   if !$connect;
        confess $ssh->error()   if !$connect;
        $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
268
    }
269
    return $ssh;
270
271
}

272
sub _ssh_channel($self) {
273
    my $ssh = $self->_connect_ssh() or confess "ERROR: Cant connect to SSH in ".$self->host;
274
275
276
277
278
    my $ssh_channel;
    for ( 1 .. 5 ) {
        $ssh_channel = $ssh->channel();
        last if $ssh_channel;
        sleep 1;
279
    }
280
281
282
    if (!$ssh_channel) {
        $ssh = $self->_connect_ssh(1);
        $ssh_channel = $ssh->channel();
Francesc Guasch's avatar
Francesc Guasch committed
283
    }
284
285
286
    die $ssh->die_with_error    if !$ssh_channel;
    $ssh->blocking(1);
    return $ssh_channel;
Francesc Guasch's avatar
Francesc Guasch committed
287
288
}

289
290
291
292
293
sub _around_create_domain {
    my $orig = shift;
    my $self = shift;
    my %args = @_;

294
    my $id_owner = delete $args{id_owner} or confess "ERROR: Missing id_owner";
Francesc Guasch's avatar
Francesc Guasch committed
295
    my $owner = Ravada::Auth::SQL->search_by_id($id_owner) or confess "Unknown user id: $id_owner";
296
297
298
299
300

    my $base;
    my $id_base = delete $args{id_base};
    $base = Ravada::Domain->open($id_base)  if $id_base;

301
302
303
304
305
306
307
    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();
308

309
    $self->_pre_create_domain(@_);
310

311
    my $domain = $self->$orig(@_);
fv3rdugo's avatar
fv3rdugo committed
312

313
    $domain->add_volume_swap( size => $args{swap})  if $args{swap};
314

315
    if ($id_base) {
316
317
318
        $domain->run_timeout($base->run_timeout)
            if defined $base->run_timeout();
    }
319
    my $user = Ravada::Auth::SQL->search_by_id($id_owner);
320
    $domain->is_volatile(1)     if $user->is_temporary() ||($base && $base->volatile_clones());
Francesc Guasch's avatar
Francesc Guasch committed
321
322
323
324
325
326

    my @start_args = ( user => $owner );
    my $remote_ip = $args{remote_ip};
    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
327
    eval {
Francesc Guasch's avatar
Francesc Guasch committed
328
           $domain->start(@start_args)      if $domain->is_volatile && ! $domain->is_active;
Francesc Guasch's avatar
Francesc Guasch committed
329
330
    };
    die $@ if $@ && $@ !~ /code: 55,/;
331

Francesc Guasch's avatar
Francesc Guasch committed
332
    $domain->get_info();
333
    $domain->display($owner)    if $domain->is_active;
Francesc Guasch's avatar
Francesc Guasch committed
334

335
336
337
    return $domain;
}

338
339
340
sub _around_import_domain {
    my $orig = shift;
    my $self = shift;
341
    my ($name, $user, $spinoff) = @_;
342

343
    my $domain = $self->$orig($name, $user);
344
345
346

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

347
    if ($spinoff) {
348
349
        warn "Spinning volumes off their backing files ...\n"
            if $ENV{TERM} && $0 !~ /\.t$/;
350
351
        $domain->spinoff_volumes();
    }
352
    return $domain;
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
384
385
386
387
388
389
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;

390
    return $self->_data('name') if defined $self->{_data}->{name};
391

392
393
    my ($ref) = ref($self) =~ /.*::(.*)/;
    return ($ref or ref($self))."_".$self->host;
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
}

=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
417
418
419
420
421
422
423
424
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;
}

425
426
427
428
429
430
431
432
433
=head2 ip

Returns the external IP this for this VM

=cut

sub ip {
    my $self = shift;

434
435
    my $name = ($self->public_ip or $self->host())
        or confess "this vm has no host name";
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
    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
455
        ." This virtual machine won't be available from the network." if $0 !~ /\.t$/;
456
457
458
459

    return '127.0.0.1';
}

Francesc Guasch's avatar
Francesc Guasch committed
460
461
462
463
464
465
=head2 nat_ip

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

=cut

466
sub nat_ip($self) {
467
    return Ravada::nat_ip();
468
469
}

470
471
472
473
sub _interface_ip {
    my $s = IO::Socket::INET->new(Proto => 'tcp');

    for my $if ( $s->if_list) {
474
        next if $if =~ /^virbr/;
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
        my $addr = $s->if_addr($if);
        return $addr if $addr && $addr !~ /^127\./;
    }
    return;
}

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 = @_;

Francesc Guasch's avatar
Francesc Guasch committed
503
    confess "ERROR: Domains can only be created at localhost got ".$self->host
504
505
506
        unless     $self->host eq 'localhost'
                || $self->host eq '127.0.0.1';

507
508
509
510
511
512
513
514
515
516
517
518
    $self->_check_readonly(@_);

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

}

sub _check_require_base {
    my $self = shift;

    my %args = @_;
519
520
521
522
523
524

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

525
526
527
    delete $args{start};
    delete $args{remote_ip};

Francesc Guasch's avatar
Francesc Guasch committed
528
    delete @args{'_vm','name','vm', 'memory','description','id_iso'};
529
530
531
532
533

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

    my $base = Ravada::Domain->open($id_base);
534
    if (my @requests = grep { $_->command ne 'clone' } $base->list_requests) {
535
536
537
538
        confess "ERROR: Domain ".$base->name." has ".$base->list_requests
                            ." requests.\n"
            unless scalar @requests == 1 && $request
                && $requests[0]->id eq $request->id;
539
540
    }

541

542
543
544
    die "ERROR: Domain ".$self->name." is not base"
            if !$base->is_base();

545
546
547
548
    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;
549
550
}

551
552
553
554
555
556
557
558
559
560
561
=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
562
sub _data($self, $field, $value=undef) {
563
564
565
566
567
568
569
570
571
572
    if (defined $value) {
        $self->{_data}->{$field} = $value;
        my $sth = $$CONNECTOR->dbh->prepare(
            "UPDATE vms set $field=?"
            ." WHERE id=?"
        );
        $sth->execute($value, $self->id);
        $sth->finish;
        return $value;
    }
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588

#    _init_connector();

    return $self->{_data}->{$field} if exists $self->{_data}->{$field};
    $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 = @_;

589
590
    _init_connector();

591
592
593
594
595
596
597
598
599
    if (!keys %args) {
        my $id;
        eval { $id = $self->id  };
        if ($id) {
            %args =( id => $id );
        }
    }

    my $sth = $$CONNECTOR->dbh->prepare(
600
        "SELECT * FROM vms WHERE ".join(" AND ",map { "$_=?" } sort keys %args )
601
602
603
604
    );
    $sth->execute(map { $args{$_} } sort keys %args);
    my $row = $sth->fetchrow_hashref;
    $sth->finish;
Francesc Guasch's avatar
Francesc Guasch committed
605
606
607

    return if !$row;

608
609
610
611
612
613
    return $row;
}

sub _select_vm_db {
    my $self = shift;

614
    my ($row) = ($self->_do_select_vm_db(@_) or $self->_insert_vm_db(@_));
615
616
617
618
619
620
621
622

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

sub _insert_vm_db {
    my $self = shift;
    my $sth = $$CONNECTOR->dbh->prepare(
623
624
        "INSERT INTO vms (name, vm_type, hostname, public_ip)"
        ." VALUES(?, ?, ?, ?)"
625
    );
626
627
628
629
    my %args = @_;
    my $name = ( delete $args{name} or $self->name);
    my $host = ( delete $args{hostname} or $self->host );
    delete $args{vm_type};
630

631
632
    confess "Unknown args ".Dumper(\%args)  if keys %args;

633
    eval { $sth->execute($name,$self->type,$host, $self->public_ip)  };
634
    confess $@ if $@;
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
    $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;
    }
662
    $self->_select_vm_db();
663
664
665
    return $self->_data('default_storage');
}

Francesc Guasch's avatar
Francesc Guasch committed
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
=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;
    }
688
    $self->_select_vm_db();
Francesc Guasch's avatar
Francesc Guasch committed
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
    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;
    }
714
    $self->_select_vm_db();
Francesc Guasch's avatar
Francesc Guasch committed
715
716
717
    return $self->_data('clone_storage');
}

718
719
720
721
722
723
724
725
726
727
728
=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
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
=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');
}
750

Francesc Guasch's avatar
Francesc Guasch committed
751
752
753
754
755
756
757
758
759
760
761
762
763
=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
764
765
766
sub list_drivers($self, $name=undef) {
    return Ravada::Domain::drivers(undef,$name,$self->type);
}
767

Francesc Guasch's avatar
Francesc Guasch committed
768
769
770
771
772
773
=head2 is_local

Returns wether this virtual manager is in the local host

=cut

774
sub is_local($self) {
775
    return 1 if $self->host eq 'localhost'
776
777
        || $self->host eq '127.0.0,1'
        || !$self->host;
778
    return 0;
779
780
}

781
782
783
784
785
786
787
788
789

=head2 list_nodes

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

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

=cut

790
791
792
793
794
795
796
797
798
799
800
801
802
sub list_nodes($self) {
    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))
    }

    return @nodes;
}
803

804
805
806
807
808
809
=head2 ping

Returns if the virtual manager connection is available

=cut

810
811
812
813
814
815
sub ping($self, $option=undef) {
    confess "ERROR: option unknown" if defined $option && $option ne 'debug';
    
    my $debug = 0;
    $debug = 1 if defined $option && $option eq 'debug';

816
817
    return 1 if $self->is_local();

818
    warn "trying tcp"   if $debug;
Francesc Guasch's avatar
Francesc Guasch committed
819
820
821
822
    my $p = Net::Ping->new('tcp',2);
    return 1 if $p->ping($self->host);
    $p->close();

823
    return if $>; # icmp ping requires root privilege
824
    warn "trying icmp"   if $debug;
Francesc Guasch's avatar
Francesc Guasch committed
825
    $p= Net::Ping->new('icmp',2);
826
    return 1 if $p->ping($self->host);
Francesc Guasch's avatar
Francesc Guasch committed
827

828
    return 0;
Francesc Guasch's avatar
Francesc Guasch committed
829
830
}

Francesc Guasch's avatar
Francesc Guasch committed
831
832
833
834
835
836
837
838
839
sub _around_ping($orig, $self, $option=undef) {

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

    return $ping;
}

840
841
842
843
844
845
=head2 is_active

Returns if the domain is active.

=cut

846
sub is_active($self) {
847
    return $self->_do_is_active() if $self->is_local;
848

849
    return $self->_cached_active if time - $self->_cached_active_time < 5;
850
851
852
853
    return $self->_do_is_active();
}

sub _do_is_active($self) {
854
    my $ret = 0;
855
856
    if ( $self->is_local ) {
        $ret = 1 if $self->vm;
857
    } else {
858
859
860
861
862
863
864
865
866
867
        if ( !$self->ping() ) {
            $ret = 0;
        } else {
            if ( $self->is_alive ) {
                $ret = 1;
            }  else {
                $self->connect();
                $ret = 1 if $self->is_alive;
            }
        }
868
869
870
871
872
873
874
    }
    $self->_cached_active($ret);
    $self->_cached_active_time(time);
    return $ret;
}

sub _cached_active($self, $value=undef) {
875
    return $self->_data('is_active', $value);
876
}
Francesc Guasch's avatar
Francesc Guasch committed
877

878
879
sub _cached_active_time($self, $value=undef) {
    return $self->_data('cached_active_time', $value);
880
}
Francesc Guasch's avatar
Francesc Guasch committed
881

882
883
884
885
886
887
=head2 remove

Remove the virtual machine manager.

=cut

Francesc Guasch's avatar
Francesc Guasch committed
888
sub remove($self) {
889
890
    #TODO stop the active domains
    #
Francesc Guasch's avatar
Francesc Guasch committed
891
    $self->disconnect();
Francesc Guasch's avatar
Francesc Guasch committed
892
893
894
895
    my $sth = $$CONNECTOR->dbh->prepare("DELETE FROM vms WHERE id=?");
    $sth->execute($self->id);
}

896
897
898
899
900
901
902
903
=head2 run_command

Run a command on the node

    my @ls = $self->run_command("ls");

=cut

Francesc Guasch's avatar
Francesc Guasch committed
904
sub run_command($self, @command) {
Francesc Guasch's avatar
Francesc Guasch committed
905

Francesc Guasch's avatar
Francesc Guasch committed
906
    return $self->_run_command_local(@command) if $self->is_local();
907

Francesc Guasch's avatar
Francesc Guasch committed
908
    my $chan = $self->_ssh_channel() or die "ERROR: No SSH channel to host ".$self->host;
909

Francesc Guasch's avatar
Francesc Guasch committed
910
    my $command = join(" ",@command);
911
912
913
914
915
916
917
918
919
920
921
922
923
924
    $chan->exec($command);# or $self->{_ssh}->die_with_error;

    $chan->send_eof();

    my ($out, $err) = ('', '');
    while (!$chan->eof) {
        if (my ($o, $e) = $chan->read2) {
            $out .= $o;
            $err .= $e;
        }
    }
    return ($out, $err);
}

Francesc Guasch's avatar
Francesc Guasch committed
925
sub _run_command_local($self, @command) {
926
    my ( $in, $out, $err);
927
928
    my ($exec) = $command[0];
    confess "ERROR: Missing command $exec"  if ! -e $exec;
Francesc Guasch's avatar
Francesc Guasch committed
929
    run3(\@command, \$in, \$out, \$err);
930
    return ($out, $err);
931
932
}

933
934
935
936
937
938
939
940
=head2 write_file

Writes a file to the node

    $self->write_file("filename.extension", $contents);

=cut

941
sub write_file( $self, $file, $contents ) {
Francesc Guasch's avatar
Francesc Guasch committed
942
943
944
945
946
947
    return $self->_write_file_local($file, $contents )  if $self->is_local;

    my $chan = $self->_ssh_channel();
    $chan->exec("cat > $file");
    my $bytes = $chan->write($contents);
    $chan->send_eof();
948
}
Francesc Guasch's avatar
Francesc Guasch committed
949
950
951
952
953

sub _write_file_local( $self, $file, $contents ) {
    confess "TODO";
}

954
sub create_iptables_chain($self,$chain) {
955
    my ($out, $err) = $self->run_command("/sbin/iptables","-n","-L",$chain);
956

957
958
959
960
961
962
963
964
    $self->run_command("/sbin/iptables", '-N' => $chain)
        if $out !~ /^Chain $chain/;

    ($out, $err) = $self->run_command("/sbin/iptables","-n","-L",'INPUT');
    return if grep(/^RAVADA /, split(/\n/,$out));

    $self->run_command("/sbin/iptables", '-A','INPUT', '-j' => $chain);

965
966
967
}

sub iptables($self, @args) {
968
    my @cmd = ('/sbin/iptables');
969
970
971
972
973
974
975
976
    for ( ;; ) {
        my $key = shift @args or last;
        my $field = "-$key";
        $field = "-$field" if length($key)>1;
        push @cmd,($field);
        push @cmd,(shift @args);

    }
Francesc Guasch's avatar
Francesc Guasch committed
977
    my ($out, $err) = $self->run_command(@cmd);
978
979
980
981
982
983
    warn $err if $err;
}

sub iptables_list($self) {
#   Extracted from Rex::Commands::Iptables
#   (c) Jan Gehring <jan.gehring@gmail.com>
984
    my ($out,$err) = $self->run_command("/sbin/iptables-save");
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
    my ( %tables, $ret );

    my ($current_table);
    for my $line (split /\n/, $out) {
        chomp $line;

        next if ( $line eq "COMMIT" );
        next if ( $line =~ m/^#/ );
        next if ( $line =~ m/^:/ );

        if ( $line =~ m/^\*([a-z]+)$/ ) {
            $current_table = $1;
            $tables{$current_table} = [];
            next;
        }

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