VM.pm 19.1 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
56
57
58
59
60
61
############################################################

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

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

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

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

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

85
86
before 'search_domain' => \&_pre_search_domain;
before 'list_domains' => \&_pre_list_domains;
87
88
89

before 'create_volume' => \&_connect;

90
around 'import_domain' => \&_around_import_domain;
Francesc Guasch's avatar
Francesc Guasch committed
91

92
93
94
95
#############################################################
#
# method modifiers
#
96

97
98
99
100
101
102
103
sub _init_connector {
    return if $CONNECTOR && $$CONNECTOR;
    $CONNECTOR = \$Ravada::CONNECTOR if $Ravada::CONNECTOR;
    $CONNECTOR = \$Ravada::Front::CONNECTOR if !defined $$CONNECTOR
                                                && defined $Ravada::Front::CONNECTOR;
}

104
105
106
107
108
109
110
111
112
113
114
115
=head1 Constructors

=head2 open

Opens a Virtual Machine Manager (VM)

Arguments: id of the VM

=cut

sub open {
    my $proto = shift;
116
117
118
119
120
121
122
123
124
    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;
    }
125
126
127
128
    my $class=ref($proto) || $proto;

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

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

138
    $args{host} = $row->{hostname};
139
    $args{security} = decode_json($row->{security}) if $row->{security};
140

141
    return $self->new(%args);
142
143
144

}

145
146
sub BUILD {
    my $self = shift;
147
148
149

    my $args = $_[0];

150
151
152
153
154
    my $id = delete $args->{id};
    my $host = delete $args->{host};
    my $name = delete $args->{name};
    delete $args->{readonly};
    delete $args->{security};
155
    delete $args->{public_ip};
156
157
158
159

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

Francesc Guasch's avatar
Francesc Guasch committed
160
161
    lock_hash(%$args);

162
163
164
165
    confess "ERROR: Unknown args ".join (",", keys (%$args)) if keys %$args;

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

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

182
183
}

184
185
186
187
188
189
190
191
192
193
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;

194
    my $vm = $proto->new(%args);
195
196
197
198
199
    eval { $vm->vm };
    warn $@ if $@;
    return if $@;

    return $vm;
200
201
202

}

203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
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(@_);
}

220
221
222
223
224
225
226
227
228
229
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();
}

230
231
sub _connect_ssh($self, $disconnect=0) {
    confess "Don't connect to local ssh"
Francesc Guasch's avatar
Francesc Guasch committed
232
233
        if $self->is_local;

234
    if ( $self->readonly ) {
235
        warn $self->name." readonly, don't do ssh";
236
237
        return;
    }
Francesc Guasch's avatar
Francesc Guasch committed
238
239
    return if !$self->ping();

240
241
242
    my @pwd = getpwuid($>);
    my $home = $pwd[7];

243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
    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
264
    }
265
    return $ssh;
266
267
}

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

285
286
287
288
289
sub _around_create_domain {
    my $orig = shift;
    my $self = shift;
    my %args = @_;

290
291
    my $id_owner = delete $args{id_owner} or confess "ERROR: Missing id_owner";

292
    $self->_pre_create_domain(@_);
293

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

296
    $domain->add_volume_swap( size => $args{swap})  if $args{swap};
297

298
299
300
301
302
    if ($args{id_base}) {
        my $base = $self->search_domain_by_id($args{id_base});
        $domain->run_timeout($base->run_timeout)
            if defined $base->run_timeout();
    }
303
304
305
    my $user = Ravada::Auth::SQL->search_by_id($id_owner);
    $domain->is_volatile(1)    if $user->is_temporary();

Francesc Guasch's avatar
Francesc Guasch committed
306
307
    $domain->get_info();

308
309
310
    return $domain;
}

311
312
313
sub _around_import_domain {
    my $orig = shift;
    my $self = shift;
314
    my ($name, $user, $spinoff) = @_;
315

316
    my $domain = $self->$orig($name, $user);
317
318
319

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

320
    if ($spinoff) {
321
322
        warn "Spinning volumes off their backing files ...\n"
            if $ENV{TERM} && $0 !~ /\.t$/;
323
324
        $domain->spinoff_volumes();
    }
325
    return $domain;
326
327
}

328
329
############################################################
#
330

331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
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;

363
    return $self->_data('name') if defined $self->{_data}->{name};
364

365
366
    my ($ref) = ref($self) =~ /.*::(.*)/;
    return ($ref or ref($self))."_".$self->host;
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
}

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

=head2 ip

Returns the external IP this for this VM

=cut

sub ip {
    my $self = shift;

399
400
    my $name = ($self->public_ip or $self->host())
        or confess "this vm has no host name";
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
    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."
        ." This virtual machine won't be available from the network.";

    return '127.0.0.1';
}

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

    for my $if ( $s->if_list) {
429
        next if $if =~ /^virbr/;
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
        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
458
    confess "ERROR: Domains can only be created at localhost got ".$self->host
459
460
461
        unless     $self->host eq 'localhost'
                || $self->host eq '127.0.0.1';

462
463
464
465
466
467
468
469
470
471
472
473
    $self->_check_readonly(@_);

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

}

sub _check_require_base {
    my $self = shift;

    my %args = @_;
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490

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

    delete @args{'_vm','name','vm', 'memory','description'};

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

    my $base = Ravada::Domain->open($id_base);
    if (my @requests = $base->list_requests) {
        confess "ERROR: Domain ".$base->name." has ".$base->list_requests
                            ." requests.\n"
            unless scalar @requests == 1 && $request
                && $requests[0]->id eq $request->id;
491
492
    }

493

494
495
496
    die "ERROR: Domain ".$self->name." is not base"
            if !$base->is_base();

497
498
499
500
    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;
501
502
}

503
504
505
506
507
508
509
510
511
512
513
514
515
516
=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');
}

sub _data {
    my $self = shift;
    my $field = shift or confess "Missing field name";
517
518
519
520
521
522
523
524
525
526
527
    my $value = shift;
    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;
    }
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543

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

544
545
    _init_connector();

546
547
548
549
550
551
552
553
554
    if (!keys %args) {
        my $id;
        eval { $id = $self->id  };
        if ($id) {
            %args =( id => $id );
        }
    }

    my $sth = $$CONNECTOR->dbh->prepare(
555
        "SELECT * FROM vms WHERE ".join(" AND ",map { "$_=?" } sort keys %args )
556
557
558
559
    );
    $sth->execute(map { $args{$_} } sort keys %args);
    my $row = $sth->fetchrow_hashref;
    $sth->finish;
Francesc Guasch's avatar
Francesc Guasch committed
560
561
562

    return if !$row;

563
564
565
566
567
568
    return $row;
}

sub _select_vm_db {
    my $self = shift;

569
    my ($row) = ($self->_do_select_vm_db(@_) or $self->_insert_vm_db(@_));
570
571
572
573
574
575
576
577

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

sub _insert_vm_db {
    my $self = shift;
    my $sth = $$CONNECTOR->dbh->prepare(
578
579
        "INSERT INTO vms (name, vm_type, hostname, public_ip)"
        ." VALUES(?, ?, ?, ?)"
580
    );
581
582
583
584
    my %args = @_;
    my $name = ( delete $args{name} or $self->name);
    my $host = ( delete $args{hostname} or $self->host );
    delete $args{vm_type};
585

586
587
    confess "Unknown args ".Dumper(\%args)  if keys %args;

588
    eval { $sth->execute($name,$self->type,$host, $self->public_ip)  };
589
    confess $@ if $@;
590
591
592
593
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
    $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;
    }
    return $self->_data('default_storage');
}

Francesc Guasch's avatar
Francesc Guasch committed
620
621
622
623
624
625
626
627
628
629
630
631
632
=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
633
634
635
sub list_drivers($self, $name=undef) {
    return Ravada::Domain::drivers(undef,$name,$self->type);
}
636

Francesc Guasch's avatar
Francesc Guasch committed
637
638
639
640
641
642
=head2 is_local

Returns wether this virtual manager is in the local host

=cut

643
sub is_local($self) {
644
    return 1 if $self->host eq 'localhost'
645
646
        || $self->host eq '127.0.0,1'
        || !$self->host;
647
    return 0;
648
649
}

650
651
652
653
654
655
656
657
658

=head2 list_nodes

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

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

=cut

659
660
661
662
663
664
665
666
667
668
669
670
671
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;
}
672

673
674
675
676
677
678
=head2 ping

Returns if the virtual manager connection is available

=cut

679
680
681
682
683
684
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';

685
686
    return 1 if $self->is_local();

687
    warn "trying tcp"   if $debug;
Francesc Guasch's avatar
Francesc Guasch committed
688
689
690
691
    my $p = Net::Ping->new('tcp',2);
    return 1 if $p->ping($self->host);
    $p->close();

692
    return if $>; # icmp ping requires root privilege
693
    warn "trying icmp"   if $debug;
Francesc Guasch's avatar
Francesc Guasch committed
694
    $p= Net::Ping->new('icmp',2);
695
    return 1 if $p->ping($self->host);
Francesc Guasch's avatar
Francesc Guasch committed
696

697
    return 0;
Francesc Guasch's avatar
Francesc Guasch committed
698
699
}

700
701
702
703
704
705
=head2 is_active

Returns if the domain is active.

=cut

706
sub is_active($self) {
707
    return $self->_do_is_active() if $self->is_local;
708

709
    return $self->_cached_active if time - $self->_cached_active_time < 5;
710
711
712
713
    return $self->_do_is_active();
}

sub _do_is_active($self) {
714
    my $ret = 0;
715
716
    if ( $self->is_local ) {
        $ret = 1 if $self->vm;
717
    } else {
718
719
720
721
722
723
724
725
726
727
        if ( !$self->ping() ) {
            $ret = 0;
        } else {
            if ( $self->is_alive ) {
                $ret = 1;
            }  else {
                $self->connect();
                $ret = 1 if $self->is_alive;
            }
        }
728
729
730
731
732
733
734
    }
    $self->_cached_active($ret);
    $self->_cached_active_time(time);
    return $ret;
}

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

738
739
sub _cached_active_time($self, $value=undef) {
    return $self->_data('cached_active_time', $value);
740
}
Francesc Guasch's avatar
Francesc Guasch committed
741

742
743
744
745
746
747
=head2 remove

Remove the virtual machine manager.

=cut

Francesc Guasch's avatar
Francesc Guasch committed
748
sub remove($self) {
749
750
    #TODO stop the active domains
    #
Francesc Guasch's avatar
Francesc Guasch committed
751
    $self->disconnect();
Francesc Guasch's avatar
Francesc Guasch committed
752
753
754
755
    my $sth = $$CONNECTOR->dbh->prepare("DELETE FROM vms WHERE id=?");
    $sth->execute($self->id);
}

756
757
758
759
760
761
762
763
=head2 run_command

Run a command on the node

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

=cut

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

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

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

Francesc Guasch's avatar
Francesc Guasch committed
770
    my $command = join(" ",@command);
771
772
773
774
775
776
777
778
779
780
781
782
783
784
    $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
785
sub _run_command_local($self, @command) {
786
    my ( $in, $out, $err);
787
788
    my ($exec) = $command[0];
    confess "ERROR: Missing command $exec"  if ! -e $exec;
Francesc Guasch's avatar
Francesc Guasch committed
789
    run3(\@command, \$in, \$out, \$err);
790
    return ($out, $err);
791
792
}

793
794
795
796
797
798
799
800
=head2 write_file

Writes a file to the node

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

=cut

801
sub write_file( $self, $file, $contents ) {
Francesc Guasch's avatar
Francesc Guasch committed
802
803
804
805
806
807
    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();
808
}
Francesc Guasch's avatar
Francesc Guasch committed
809
810
811
812
813

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

814
sub create_iptables_chain($self,$chain) {
815
    my ($out, $err) = $self->run_command("/sbin/iptables","-n","-L",$chain);
816
817
    return if $out =~ /^Chain $chain/;

818
    $self->run_command("/sbin/iptables", '-N' => $chain);
819
820
821
}

sub iptables($self, @args) {
822
    my @cmd = ('/sbin/iptables');
823
824
825
826
827
828
829
830
    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
831
    my ($out, $err) = $self->run_command(@cmd);
832
833
834
835
836
837
    warn $err if $err;
}

sub iptables_list($self) {
#   Extracted from Rex::Commands::Iptables
#   (c) Jan Gehring <jan.gehring@gmail.com>
838
    my ($out,$err) = $self->run_command("/sbin/iptables-save");
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
    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;
        }

        #my @parts = grep { ! /^\s+$/ && ! /^$/ } split (/(\-\-?[^\s]+\s[^\s]+)/i, $line);
        my @parts = grep { !/^\s+$/ && !/^$/ } split( /^\-\-?|\s+\-\-?/i, $line );

        my @option = ();
        for my $part (@parts) {
            my ( $key, $value ) = split( /\s/, $part, 2 );
            push( @option, $key => $value );
        }

        push( @{ $ret->{$current_table} }, \@option );

    }

    return $ret;
}

871
1;
872