Domain.pm 19.1 KB
Newer Older
joansp's avatar
joansp committed
1
2
3
4
5
package Ravada::Domain;

use warnings;
use strict;

6
use Carp qw(carp confess croak cluck);
joansp's avatar
joansp committed
7
use Data::Dumper;
8
use Hash::Util qw(lock_hash);
joansp's avatar
joansp committed
9
10
11
12
use Image::Magick;
use JSON::XS;
use Moose::Role;
use Sys::Statistics::Linux;
fv3rdugo's avatar
fv3rdugo committed
13
use IPTables::ChainMgr;
joansp's avatar
joansp committed
14

15
16
use Ravada::Utils;

joansp's avatar
joansp committed
17
18
19
our $TIMEOUT_SHUTDOWN = 20;
our $CONNECTOR;

20
our $MIN_FREE_MEMORY = 1024*1024;
21
our $IPTABLES_CHAIN = 'RAVADA';
22

joansp's avatar
joansp committed
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
_init_connector();

requires 'name';
requires 'remove';
requires 'display';

requires 'is_active';
requires 'is_paused';
requires 'start';
requires 'shutdown';
requires 'shutdown_now';
requires 'pause';
requires 'resume';
requires 'prepare_base';

#storage
requires 'add_volume';
requires 'list_volumes';

requires 'disk_device';

44
45
46
47
48
49
50
#hardware info

requires 'get_info';
requires 'set_memory';
requires 'set_max_mem';
##########################################################

joansp's avatar
joansp committed
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
has 'domain' => (
    isa => 'Any'
    ,is => 'ro'
);

has 'timeout_shutdown' => (
    isa => 'Int'
    ,is => 'ro'
    ,default => $TIMEOUT_SHUTDOWN
);

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

has 'storage' => (
    is => 'ro',
    ,isa => 'Object'
    ,required => 0
);

has '_vm' => (
    is => 'ro',
    ,isa => 'Object'
    ,required => 1
);

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


##################################################################################3
#
# Method Modifiers
joansp's avatar
joansp committed
87
#
joansp's avatar
joansp committed
88
89
90
91
92
93
94

before 'display' => \&_allowed;

before 'remove' => \&_allow_remove;
 after 'remove' => \&_after_remove_domain;

before 'prepare_base' => \&_allow_prepare_base;
95
96
 after 'prepare_base' => \&_post_prepare_base;
 
97
before 'start' => \&_start_preconditions;
98
99
 after 'start' => \&_post_start;

joansp's avatar
joansp committed
100
before 'pause' => \&_allow_manage;
101
102
 after 'pause' => \&_post_pause;

joansp's avatar
joansp committed
103
before 'resume' => \&_allow_manage;
104
105
 after 'resume' => \&_post_resume;

joansp's avatar
joansp committed
106
before 'shutdown' => \&_allow_manage_args;
107
after 'shutdown' => \&_post_shutdown;
joansp's avatar
joansp committed
108
109
110
111

before 'remove_base' => \&_can_remove_base;
after 'remove_base' => \&_remove_base_db;

112
113
114
115
116
117
118
119
120
121
122
123
##################################################

sub _vm_connect {
    my $self = shift;
    $self->_vm->connect();
}

sub _vm_disconnect {
    my $self = shift;
    $self->_vm->disconnect();
}

124
sub _start_preconditions{
125
    
126
127
128
129
130
    if (scalar @_ %2 ) {
        _allow_manage_args(@_);
    } else {
        _allow_manage(@_);
    }
joansp's avatar
joansp committed
131
    _check_free_memory();
132
    _check_used_memory(@_);
133

joansp's avatar
joansp committed
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
}

sub _allow_manage_args {
    my $self = shift;

    confess "Disabled from read only connection"
        if $self->readonly;

    my %args = @_;

    confess "Missing user arg ".Dumper(\%args)
        if !$args{user} ;

    $self->_allowed($args{user});

}
sub _allow_manage {
    my $self = shift;

    confess "Disabled from read only connection"
        if $self->readonly;

    my ($user) = @_;

    $self->_allowed($user);

}

sub _allow_remove {
    my $self = shift;
    my ($user) = @_;

    $self->_allowed($user);
167
    $self->_check_has_clones() if $self->is_known();
joansp's avatar
joansp committed
168
169
170

}

joansp's avatar
joansp committed
171
172
sub _allow_prepare_base {
    my $self = shift;
joansp's avatar
joansp committed
173
174
175
176
177
178
179
180
181
182
183
184
185
    my ($user) = @_;

    $self->_allowed($user);
    $self->_check_disk_modified();
    $self->_check_has_clones();

    $self->is_base(0);
    if ($self->is_active) {
        $self->pause($user);
        $self->{_was_active} = 1;
    }
};

186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
sub _post_prepare_base {
    my $self = shift;

    my ($user) = @_;

    $self->is_base(1);
    if ($self->{_was_active} ) {
        $self->resume($user);
    }
    delete $self->{_was_active};

    $self->_remove_id_base();
};


joansp's avatar
joansp committed
201
202
sub _check_has_clones {
    my $self = shift;
203
    return if !$self->is_known();
joansp's avatar
joansp committed
204

205
    my @clones = $self->clones;
joansp's avatar
joansp committed
206
207
208
209
210
211
212
    die "Domain ".$self->name." has ".scalar @clones." clones : ".Dumper(\@clones)
        if $#clones>=0;
}

sub _check_free_memory{
    my $lxs  = Sys::Statistics::Linux->new( memstats => 1 );
    my $stat = $lxs->get;
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
    die "No free memory" if ( $stat->memstats->{realfree} < $MIN_FREE_MEMORY );
}

sub _check_used_memory {
    my $self = shift;
    my $used_memory = 0;

    my $lxs  = Sys::Statistics::Linux->new( memstats => 1 );
    my $stat = $lxs->get;

    # We get mem total less the used for the system
    my $mem_total = $stat->{memstats}->{memtotal} - 1*1024*1024;

    for my $domain ( $self->_vm->list_domains ) {
        my $alive;
        eval { $alive = 1 if $domain->is_active && !$domain->is_paused };
        next if !$alive;

        my $info = $domain->get_info;
        $used_memory += $info->{memory};
    }

235
    confess "ERROR: Out of free memory. Using $used_memory RAM of $mem_total available" if $used_memory>= $mem_total;
joansp's avatar
joansp committed
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
}

sub _check_disk_modified {
    my $self = shift;

    if ( !$self->is_base() ) {
        return;
    }

    my $last_stat_base = 0;
    for my $file_base ( $self->list_files_base ) {
        my @stat_base = stat($file_base);
        $last_stat_base = $stat_base[9] if$stat_base[9] > $last_stat_base;
#        warn $last_stat_base;
    }
joansp's avatar
joansp committed
251

joansp's avatar
joansp committed
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
    my $files_updated = 0;
    for my $file ( $self->disk_device ) {
        my @stat = stat($file) or next;
        $files_updated++ if $stat[9] > $last_stat_base;
#        warn "\ncheck\t$file ".$stat[9]."\n vs \tfile_base $last_stat_base $files_updated\n";
    }
    die "Base already created and no disk images updated"
        if !$files_updated;
}

sub _allowed {
    my $self = shift;

    my ($user) = @_;

    confess "Missing user"  if !defined $user;
    confess "ERROR: User '$user' not class user , it is ".(ref($user) or 'SCALAR')
        if !ref $user || ref($user) !~ /Ravada::Auth/;

    return if $user->is_admin;
    my $id_owner;
    eval { $id_owner = $self->id_owner };
    my $err = $@;

    die "User ".$user->name." [".$user->id."] not allowed to access ".$self->domain
        ." owned by ".($id_owner or '<UNDEF>')."\n".Dumper($self)
            if (defined $id_owner && $id_owner != $user->id );

    confess $err if $err;

}
##################################################################################3

sub _init_connector {
286
287
288
289
    return if $CONNECTOR && $$CONNECTOR;
    $CONNECTOR = \$Ravada::CONNECTOR if $Ravada::CONNECTOR;
    $CONNECTOR = \$Ravada::Front::CONNECTOR if !defined $$CONNECTOR
                                                && defined $Ravada::Front::CONNECTOR;
joansp's avatar
joansp committed
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
}

=head2 id
Returns the id of  the domain
    my $id = $domain->id();
=cut

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

}


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

sub _data {
    my $self = shift;
    my $field = shift or confess "Missing field name";

    _init_connector();

    return $self->{_data}->{$field} if exists $self->{_data}->{$field};
    $self->{_data} = $self->_select_domain_db( name => $self->name);

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

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

sub __open {
    my $self = shift;

    my %args = @_;

    my $id = $args{id} or confess "Missing required argument id";
    delete $args{id};

    my $row = $self->_select_domain_db ( );
    return $self->search_domain($row->{name});
#    confess $row;
}

333
334
335
336
337
338
339
340
341
342
343
=head2 is_known

Returns if the domain is known in Ravada.

=cut

sub is_known {
    my $self = shift;
    return $self->_select_domain_db(name => $self->name);
}

joansp's avatar
joansp committed
344
345
sub _select_domain_db {
    my $self = shift;
joansp's avatar
joansp committed
346
    my %args = @_;
joansp's avatar
joansp committed
347

348
349
    _init_connector();

joansp's avatar
joansp committed
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
    if (!keys %args) {
        my $id;
        eval { $id = $self->id  };
        if ($id) {
            %args =( id => $id );
        } else {
            %args = ( name => $self->name );
        }
    }

    my $sth = $$CONNECTOR->dbh->prepare(
        "SELECT * FROM domains WHERE ".join(",",map { "$_=?" } sort keys %args )
    );
    $sth->execute(map { $args{$_} } sort keys %args);
    my $row = $sth->fetchrow_hashref;
    $sth->finish;

    $self->{_data} = $row;
368
    return $row if $row->{id};
joansp's avatar
joansp committed
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
399
400
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
429
430
431
432
433
}

sub _prepare_base_db {
    my $self = shift;
    my $file_img = shift;

    if (!$self->_select_domain_db) {
        confess "CRITICAL: The data should be already inserted";
#        $self->_insert_db( name => $self->name, id_owner => $self->id_owner );
    }
    my $sth = $$CONNECTOR->dbh->prepare(
        "INSERT INTO file_base_images "
        ." (id_domain , file_base_img )"
        ." VALUES(?,?)"
    );
    $sth->execute($self->id, $file_img );
    $sth->finish;

    $sth = $$CONNECTOR->dbh->prepare(
        "UPDATE domains SET is_base=1 "
        ." WHERE id=?");
    $sth->execute($self->id);
    $sth->finish;

    $self->_select_domain_db();
}

sub _insert_db {
    my $self = shift;
    my %field = @_;

    _init_connector();

    for (qw(name id_owner)) {
        confess "Field $_ is mandatory ".Dumper(\%field)
            if !exists $field{$_};
    }

    my ($vm) = ref($self) =~ /.*\:\:(\w+)$/;
    confess "Unknown domain from ".ref($self)   if !$vm;
    $field{vm} = $vm;

    my $query = "INSERT INTO domains "
            ."(" . join(",",sort keys %field )." )"
            ." VALUES (". join(",", map { '?' } keys %field )." ) "
    ;
    my $sth = $$CONNECTOR->dbh->prepare($query);
    eval { $sth->execute( map { $field{$_} } sort keys %field ) };
    if ($@) {
        #warn "$query\n".Dumper(\%field);
        die $@;
    }
    $sth->finish;

}

sub _after_remove_domain {
    my $self = shift;
    $self->_remove_files_base();
    $self->_remove_domain_db();
}

sub _remove_domain_db {
    my $self = shift;

434
435
    return if !$self->is_known();

joansp's avatar
joansp committed
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
    $self->_select_domain_db or return;
    my $sth = $$CONNECTOR->dbh->prepare("DELETE FROM domains "
        ." WHERE id=?");
    $sth->execute($self->id);
    $sth->finish;
}

sub _remove_files_base {
    my $self = shift;

    for my $file ( $self->list_files_base ) {
        unlink $file or die "$! $file" if -e $file;
    }
}


452
453
454
455
456
457
458
459
460
461
462
463
sub _remove_id_base {

    my $self = shift;

    my $sth = $$CONNECTOR->dbh->prepare(
        "UPDATE domains set id_base=NULL "
        ." WHERE id=?"
    );
    $sth->execute($self->id);
    $sth->finish;
}

joansp's avatar
joansp committed
464
465
466
467
=head2 is_base
Returns true or  false if the domain is a prepared base
=cut

joansp's avatar
joansp committed
468
sub is_base {
joansp's avatar
joansp committed
469
470
    my $self = shift;
    my $value = shift;
joansp's avatar
joansp committed
471

joansp's avatar
joansp committed
472
473
474
475
476
477
478
479
480
481
482
483
484
    $self->_select_domain_db or return 0;

    if (defined $value ) {
        my $sth = $$CONNECTOR->dbh->prepare(
            "UPDATE domains SET is_base=? "
            ." WHERE id=?");
        $sth->execute($value, $self->id );
        $sth->finish;

        return $value;
    }
    my $ret = $self->_data('is_base');
    $ret = 0 if $self->_data('is_base') =~ /n/i;
joansp's avatar
joansp committed
485

joansp's avatar
joansp committed
486
487
488
489
490
491
492
493
494
495
496
    return $ret;
};

=head2 is_locked
Shows if the domain has running or pending requests. It could be considered
too as the domain is busy doing something like starting, shutdown or prepare base.
Returns true if locked.
=cut

sub is_locked {
    my $self = shift;
497
498
499

    $self->_init_connector() if !defined $$CONNECTOR;

joansp's avatar
joansp committed
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
    my $sth = $$CONNECTOR->dbh->prepare("SELECT count(*) FROM requests "
        ." WHERE id_domain=?");
    $sth->execute($self->id);
    my ($count) = $sth->fetchrow;
    $sth->finish;

    return $count;
}

=head2 id_owner
Returns the id of the user that created this domain
=cut

sub id_owner {
    my $self = shift;
    return $self->_data('id_owner',@_);
}

=head2 id_base
Returns the id from the base this domain is based on, if any.
=cut

sub id_base {
    my $self = shift;
    return $self->_data('id_base',@_);
}

=head2 vm
Returns a string with the name of the VM ( Virtual Machine ) this domain was created on
=cut


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

=head2 clones
Returns a list of clones from this virtual machine
    my @clones = $domain->clones
=cut

sub clones {
    my $self = shift;

    _init_connector();

    my $sth = $$CONNECTOR->dbh->prepare("SELECT id, name FROM domains "
            ." WHERE id_base = ?");
    $sth->execute($self->id);
    my @clones;
    while (my $row = $sth->fetchrow_hashref) {
        # TODO: open the domain, now it returns only the id
        push @clones , $row;
    }
    return @clones;
}

joansp's avatar
joansp committed
558
559
560
561
562
563
564
565
566
567
568
569
570
=head2 has_clones
Returns the number of clones from this virtual machine
    my $has_clones = $domain->has_clones
=cut

sub has_clones {
    my $self = shift;

    _init_connector();

    return scalar $self->clones;
}

joansp's avatar
joansp committed
571

joansp's avatar
joansp committed
572
573
574
575
576
577
578
=head2 list_files_base
Returns a list of the filenames of this base-type domain
=cut

sub list_files_base {
    my $self = shift;

579
580
    return if !$self->is_known();

joansp's avatar
joansp committed
581
582
583
584
585
586
587
588
589
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
    my $id;
    eval { $id = $self->id };
    return if $@ && $@ =~ /No DB info/i;
    die $@ if $@;

    my $sth = $$CONNECTOR->dbh->prepare("SELECT file_base_img "
        ." FROM file_base_images "
        ." WHERE id_domain=?");
    $sth->execute($self->id);

    my @files;
    while ( my $img = $sth->fetchrow) {
        push @files,($img);
    }
    $sth->finish;
    return @files;
}

=head2 json
Returns the domain information as json
=cut

sub json {
    my $self = shift;

    my $id = $self->_data('id');
    my $data = $self->{_data};
    $data->{is_active} = $self->is_active;

    return encode_json($data);
}

=head2 can_screenshot
Returns wether this domain can take an screenshot.
=cut

sub can_screenshot {
    return 0;
}

sub _convert_png {
    my $self = shift;
    my ($file_in ,$file_out) = @_;

    my $in = Image::Magick->new();
    my $err = $in->Read($file_in);
    confess $err if $err;

    $in->Write("png24:$file_out");

    chmod 0755,$file_out or die "$! chmod 0755 $file_out";
}

=head2 remove_base
Makes the domain a regular, non-base virtual machine and removes the base files.
=cut

sub remove_base {
    my $self = shift;
    $self->is_base(0);
    for my $file ($self->list_files_base) {
        unlink $file or die "$! unlinking $file";
    }
    $self->storage_refresh()    if $self->storage();
}

sub _can_remove_base {
    _allow_manage(@_);
    _check_has_clones(@_);
}

652
653
654
655
656
657
sub _post_remove_base {
    my $self = shift;
    $self->_vm->disconnect();
    $self->_remove_base_db(@_);
}

joansp's avatar
joansp committed
658
659
660
661
662
663
664
665
666
667
668
sub _remove_base_db {
    my $self = shift;

    my $sth = $$CONNECTOR->dbh->prepare("DELETE FROM file_base_images "
        ." WHERE id_domain=?");

    $sth->execute($self->id);
    $sth->finish;

}

669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
=head2 clone

Clones a domain

=head3 arguments

=over

=item user => $user : The user that owns the clone

=item name => $name : Name of the new clone

=back

=cut

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

    my $name = $args{name} or confess "ERROR: Missing domain cloned name";
    confess "ERROR: Missing request user" if !$args{user};

    my $uid = $args{user}->id;

    $self->prepare_base($args{user})  if !$self->is_base();

    my $id_base = $self->id;


    return $self->_vm->create_domain(
        name => $name
        ,id_base => $id_base
        ,id_owner => $uid
        ,vm => $self->vm
    );
}

707
708
709
710
711
712
713
sub _post_pause {
    my $self = shift;
    my $user = shift;

    $self->_remove_iptables(user => $user);
}

714
715
sub _post_shutdown {
    my $self = shift;
716
717
718
719
720
721
722
723
724

    $self->_remove_temporary_machine(@_);
    $self->_remove_iptables(@_);

}

sub _remove_iptables {
    my $self = shift;

725
726
    my $args = {@_};

727
728
    my $ipt_obj = _open_iptables();

729
730
731
732
733
734
735
736
737
    my $sth = $$CONNECTOR->dbh->prepare(
        "UPDATE iptables SET time_deleted=?"
        ." WHERE id=?"
    );
    for my $row ($self->_active_iptables($args->{user})) {
        my ($id, $iptables) = @$row;
        $ipt_obj->delete_ip_rule(@$iptables);
        $sth->execute(Ravada::Utils::now(), $id);
    }
738
739
740
741
742
}

sub _remove_temporary_machine {
    my $self = shift;

743
    my %args = @_;
744
745
    my $user;

746
    return if !$self->is_known();
747

748
749
750
    eval { $user = Ravada::Auth::SQL->search_by_id($self->id_owner) };
    return if !$user;

751
752
753
754
755
756
757
758
759
760
761
762
    if ($user->is_temporary) {
        $self->remove($user);
        my $req= $args{request};
        $req->status(
            "removing"
            ,"Removing domain ".$self->name." after shutdown"
            ." because user "
            .$user->name." is temporary")
                if $req;
    }
}

763
764
765
766
sub _post_resume {
    return _post_start(@_);
}

767
768
769
sub _post_start {
    my $self = shift;

770
771
772
773
774
    $self->_add_iptable(@_);
}

sub _add_iptable {
    my $self = shift;
775
776
777
778
779
780
781
782
783
    return if scalar @_ % 2;
    my %args = @_;

    my $remote_ip = $args{remote_ip} or return;

    my $owner = Ravada::Auth::SQL->search_by_id($self->id_owner);

    my $display = $self->display($owner);
    my ($local_ip, $local_port) = $display =~ m{\w+://(.*):(\d+)};
784

785
786
787
788
789
790
791
792
793
794

    my $ipt_obj = _open_iptables();
	# append rule at the end of the RAVADA chain in the filter table to
	# allow all traffic from $local_ip to $remote_ip via port $local_port
    #
    my @iptables_arg = ($remote_ip
                        ,$local_ip, 'filter', $IPTABLES_CHAIN, 'ACCEPT',
                        ,{'protocol' => 'tcp', 's_port' => 0, 'd_port' => $local_port});

	my ($rv, $out_ar, $errs_ar) = $ipt_obj->append_ip_rule(@iptables_arg);
795

796
797
798
799
800
801
802
803
804
805
    $self->_log_iptable(iptables => \@iptables_arg, @_);

    @iptables_arg = ( '0.0.0.0'
                        ,$local_ip, 'filter', $IPTABLES_CHAIN, 'DROP',
                        ,{'protocol' => 'tcp', 's_port' => 0, 'd_port' => $local_port});

    ($rv, $out_ar, $errs_ar) = $ipt_obj->append_ip_rule(@iptables_arg);

    $self->_log_iptable(iptables => \@iptables_arg, @_);

806
807
808
}

sub _open_iptables {
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834

	my %opts = (
    	'use_ipv6' => 0,         # can set to 1 to force ip6tables usage
	    'ipt_rules_file' => '',  # optional file path from
	                             # which to read iptables rules
	    'iptout'   => '/tmp/iptables.out',
	    'ipterr'   => '/tmp/iptables.err',
	    'debug'    => 0,
	    'verbose'  => 0,

	    ### advanced options
	    'ipt_alarm' => 5,  ### max seconds to wait for iptables execution.
	    'ipt_exec_style' => 'waitpid',  ### can be 'waitpid',
	                                    ### 'system', or 'popen'.
	    'ipt_exec_sleep' => 1, ### add in time delay between execution of
	                           ### iptables commands (default is 0).
	);

	my $ipt_obj = IPTables::ChainMgr->new(%opts)
    	or die "[*] Could not acquire IPTables::ChainMgr object";

	my $rv = 0;
	my $out_ar = [];
	my $errs_ar = [];

	#check_chain_exists
835
836
837
	($rv, $out_ar, $errs_ar) = $ipt_obj->chain_exists('filter', $IPTABLES_CHAIN);
    if (!$rv) {
		$ipt_obj->create_chain('filter', $IPTABLES_CHAIN);
838
839
840
841
	}
	# set the policy on the FORWARD table to DROP
    $ipt_obj->set_chain_policy('filter', 'FORWARD', 'DROP');

842
843
    return $ipt_obj;
}
844

845
sub _log_iptable {
846
847
848
849
850
851
852
853
854
855
856
857
    my $self = shift;
    if (scalar(@_) %2 ) {
        carp "Odd number ".Dumper(\@_);
        return;
    }
    my %args = @_;
    lock_hash(%args);
    my $remote_ip = $args{remote_ip};#~ or return;
    my $user = $args{user};
    my $iptables = $args{iptables};

    my $sth = $$CONNECTOR->dbh->prepare(
858
859
860
        "INSERT INTO iptables "
        ."(id_domain, id_user, remote_ip, time_req, iptables)"
        ."VALUES(?, ?, ?, ?, ?)"
861
    );
862
    $sth->execute($self->id, $user->id, $remote_ip, Ravada::Utils::now()
863
864
865
866
867
        ,encode_json($iptables));
    $sth->finish;

}

868
sub _active_iptables {
869
870
871
872
    my $self = shift;
    my $user = shift;

    my $sth = $$CONNECTOR->dbh->prepare(
873
874
875
        "SELECT id,iptables FROM iptables "
        ." WHERE "
        ."    id_domain=?"
876
        ."    AND id_user=? "
877
878
        ."    AND time_deleted IS NULL"
        ." ORDER BY time_req DESC "
879
880
    );
    $sth->execute($self->id, $user->id);
881
882
883
    my @iptables;
    while (my ($id, $iptables) = $sth->fetchrow) {
        push @iptables, [ $id, decode_json($iptables)];
884
    }
885
    return @iptables;
886
}
887
1;