Domain.pm 38.6 KB
Newer Older
1
2
3
4
5
package Ravada::Domain;

use warnings;
use strict;

6
7
8
9
10
11
=head1 NAME

Ravada::Domain - Domains ( Virtual Machines ) library for Ravada

=cut

12
13
14
15
use Carp qw(carp confess croak cluck);
use Data::Dumper;
use Hash::Util qw(lock_hash);
use Image::Magick;
16
use IPC::Run3 qw(run3);
17
18
19
20
21
use JSON::XS;
use Moose::Role;
use Sys::Statistics::Linux;
use IPTables::ChainMgr;

22
23
24
no warnings "experimental::signatures";
use feature qw(signatures);

25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
use Ravada::Domain::Driver;
use Ravada::Utils;

our $TIMEOUT_SHUTDOWN = 20;
our $CONNECTOR;

our $MIN_FREE_MEMORY = 1024*1024;
our $IPTABLES_CHAIN = 'RAVADA';

_init_connector();

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

requires 'is_active';
41
requires 'is_hibernated';
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
requires 'is_paused';
requires 'start';
requires 'shutdown';
requires 'shutdown_now';
requires 'force_shutdown';
requires '_do_force_shutdown';

requires 'pause';
requires 'resume';
requires 'prepare_base';

requires 'rename';

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

requires 'disk_device';

requires 'disk_size';

requires 'spinoff_volumes';

requires 'clean_swap_volumes';
#hardware info

requires 'get_info';
requires 'set_memory';
requires 'set_max_mem';
71

72
73
requires 'hybernate';

74
75
76
77
# neworking

requires 'ip';

78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
##########################################################

has 'domain' => (
    isa => 'Any'
    ,is => 'rw'
);

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

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

has 'storage' => (
98
    is => 'ro'
99
100
101
102
103
104
105
106
107
108
    ,isa => 'Object'
    ,required => 0
);

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

109
110
111
112
113
114
has 'tls' => (
    is => 'rw'
    ,isa => 'Int'
    ,default => 0
);

115
116
117
118
119
120
121
has 'description' => (
    is => 'rw'
    ,isa => 'Str'
    ,required => 0
    ,trigger => \&_update_description
);

122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
##################################################################################3
#


##################################################################################3
#
# Method Modifiers
#

before 'display' => \&_allowed;

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

before 'prepare_base' => \&_pre_prepare_base;
 after 'prepare_base' => \&_post_prepare_base;

140
before 'start' => \&_pre_start;
141
142
143
144
145
 after 'start' => \&_post_start;

before 'pause' => \&_allow_manage;
 after 'pause' => \&_post_pause;

146
147
148
before 'hybernate' => \&_allow_manage;
 after 'hybernate' => \&_post_pause;

149
150
151
before 'resume' => \&_allow_manage;
 after 'resume' => \&_post_resume;

152
before 'shutdown' => \&_pre_shutdown;
153
154
after 'shutdown' => \&_post_shutdown;
after 'shutdown_now' => \&_post_shutdown_now;
155
156

before 'force_shutdown' => \&_pre_shutdown_now;
157
158
after 'force_shutdown' => \&_post_shutdown_now;

159
before 'remove_base' => \&_pre_remove_base;
160
161
162
163
164
165
166
after 'remove_base' => \&_post_remove_base;

before 'rename' => \&_pre_rename;
after 'rename' => \&_post_rename;

after 'screenshot' => \&_post_screenshot;
##################################################
167
168
169
170
171
172
#

sub BUILD {
    my $self = shift;
    $self->is_known();
}
173
174
175
176
177
178
179
180
181
182
183

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

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

184
sub _pre_start {
185
186
187
188
189
190
191
    my ($self) = @_;

    if (scalar @_ %2 ) {
        _allow_manage_args(@_);
    } else {
        _allow_manage(@_);
    }
192
    _clean_iptables();
193
194
195
196
197
    _check_free_memory();
    _check_used_memory(@_);

}

198
199
sub _update_description {
    my $self = shift;
200

201
202
203
204
    return if defined $self->description
        && defined $self->_data('description')
        && $self->description eq $self->_data('description');

205
206
    my $sth = $$CONNECTOR->dbh->prepare(
        "UPDATE domains SET description=? "
207
        ." WHERE id=? ");
fv3rdugo's avatar
fv3rdugo committed
208
    $sth->execute($self->description,$self->id);
209
    $sth->finish;
210
    $self->{_data}->{description} = $self->{description};
211
}
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258

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;

    return $self->_allow_manage_args(@_)
        if scalar(@_) % 2 == 0;

    my ($user) = @_;
    return $self->_allow_manage_args( user => $user);

}

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

    $self->_allowed($user);
    $self->_check_has_clones() if $self->is_known();

}

sub _pre_prepare_base {
    my $self = shift;
    my ($user, $request) = @_;

    $self->_allowed($user);

    # TODO: if disk is not base and disks have not been modified, do not generate them
    # again, just re-attach them 
    $self->_check_disk_modified() if $self->is_base();
    $self->_check_has_clones();

    $self->is_base(0);
259
    $self->_post_remove_base();
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
286
287
288
289
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
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
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
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
    if ($self->is_active) {
        $self->shutdown(user => $user);
        $self->{_was_active} = 1;
        for ( 1 .. $TIMEOUT_SHUTDOWN ) {
            last if !$self->is_active;
            sleep 1;
        }
        if ($self->is_active ) {
            $request->status('working'
                    ,"Domain ".$self->name." still active, forcing hard shutdown")
                if $request;
            $self->force_shutdown($user);
            sleep 1;
        }
    }
    if ($self->id_base ) {
        $self->spinoff_volumes();
    }
};

sub _post_prepare_base {
    my $self = shift;

    my ($user) = @_;

    $self->is_base(1);
    if ($self->{_was_active} ) {
        $self->start($user) if !$self->is_active;
    }
    delete $self->{_was_active};

    $self->_remove_id_base();
};

sub _check_has_clones {
    my $self = shift;
    return if !$self->is_known();

    my @clones = $self->clones;
    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;
    die "ERROR: No free memory. Only ".int($stat->memstats->{realfree}/1024)
            ." MB out of ".int($MIN_FREE_MEMORY/1024)." MB required." 
        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};
    }

    confess "ERROR: Out of free memory. Using $used_memory RAM of $mem_total available" if $used_memory>= $mem_total;
}

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

    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 {
    return if $CONNECTOR && $$CONNECTOR;
    $CONNECTOR = \$Ravada::CONNECTOR if $Ravada::CONNECTOR;
    $CONNECTOR = \$Ravada::Front::CONNECTOR if !defined $$CONNECTOR
                                                && defined $Ravada::Front::CONNECTOR;
}

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

Francesc Guasch's avatar
Francesc Guasch committed
415
=head2 open
416

Francesc Guasch's avatar
Francesc Guasch committed
417
418
419
420
421
422
423
424
425
426
427
428
429
Open a domain

Argument: id

Returns: Domain object read only

=cut

sub open($class, $id) {
    my $self = {};
    bless $self,$class;

    my $row = $self->_select_domain_db ( id => $id );
430

431
432
433
434
435
436
    die "Domain id = $id not found"
        if !keys %$row;

    die "Domain ".$row->{name}." has no VM "
        .Dumper($row)   if !$row->{vm};

Francesc Guasch's avatar
Francesc Guasch committed
437
    my $vm0 = {};
Francesc Guasch's avatar
Francesc Guasch committed
438
    my $vm_class = "Ravada::VM::".$row->{vm};
Francesc Guasch's avatar
Francesc Guasch committed
439
440
441
    bless $vm0, $vm_class;

    my $vm = $vm0->new( readonly => 1);
442

Francesc Guasch's avatar
Francesc Guasch committed
443
    return $vm->search_domain($row->{name});
444
445
446
447
448
449
450
451
452
453
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
}

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

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

    _init_connector();

    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;
481
    $self->description($row->{description}) if defined $row->{description};
482
483
484
485
486
487
488
489
490
491
492
493
494
    return $row if $row->{id};
}

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

    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 "
495
496
        ." (id_domain , file_base_img, target )"
        ." VALUES(?,?,?)"
497
498
    );
    for my $file_img (@file_img) {
499
500
501
        my $target;
        ($file_img, $target) = @$file_img if ref $file_img;
        $sth->execute($self->id, $file_img, $target );
502
503
504
505
506
507
508
509
510
511
512
513
    }
    $sth->finish;

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

    $self->_select_domain_db();
}

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
sub _set_spice_password {
    my $self = shift;
    my $password = shift;

    my $sth = $$CONNECTOR->dbh->prepare(
       "UPDATE domains set spice_password=?"
       ." WHERE id=?"
    );
    $sth->execute($password, $self->id);
    $sth->finish;

    $self->{_data}->{spice_password} = $password;
}

=head2 spice_password

Returns the password defined for the spice viewers

=cut

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

539
540
541
542
543
544
=head2 display_file

Returns a file with the display information. Defaults to spice.

=cut

545
546
sub display_file($self,$user) {
    return $self->_display_file_spice($user);
547
548
}

549
550
551
552
553
554
555
556
557
558
559
# taken from isard-vdi thanks to @tuxinthejungle Alberto Larraz
sub _display_file_spice($self,$user) {

    my ($ip,$port) = $self->display($user) =~ m{spice://(\d+\.\d+\.\d+\.\d+):(\d+)};

    die "I can't find ip port in ".$self->display   if !$ip ||!$port;

    my $ret =
        "[virt-viewer]\n"
        ."type=spice\n"
        ."host=$ip\n";
560
561
562
    if ($self->tls) {
        $ret .= "tls-port=%s\n";
    } else {
563
        $ret .= "port=$port\n";
564
    }
565
#    $ret .="password=%s\n"  if $self->spice_password();
566
567

    $ret .=
568
569
570
571
        "fullscreen=1\n"
        ."title=".$self->name." - Press SHIFT+F12 to exit\n"
        ."enable-smartcard=0\n"
        ."enable-usb-autoshare=1\n"
572
        ."delete-this-file=1\n"
573
        ."usb-filter=-1,-1,-1,-1,0\n";
574
575

    $ret .=";" if !$self->tls;
576
577
    $ret .= "tls-ciphers=DEFAULT\n"
        .";host-subject=O=".$ip.",CN=?\n";
578
579

    $ret .=";"  if !$self->tls;
580
581
582
583
    $ret .="ca=CA\n"
        ."toggle-fullscreen=shift+f11\n"
        ."release-cursor=shift+f12\n"
        ."secure-attention=ctrl+alt+end\n";
584
585
586
587
588
589
    $ret .=";" if !$self->tls;
    $ret .="secure-channels=main;inputs;cursor;playback;record;display;usbredir;smartcard\n";

    return $ret;
}

590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
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);
613
        confess $@;
614
615
616
617
618
    }
    $sth->finish;

}

619
=head2 pre_remove
620

621
622
623
624
625
Code to run before removing the domain. It can be implemented in each domain.
It is not expected to run by itself, the remove function calls it before proceeding.

    $domain->pre_remove();  # This isn't likely to be necessary
    $domain->remove();      # Automatically calls the domain pre_remove method
626
627
628

=cut

629
sub pre_remove { }
630

631
632
633
634
sub _pre_remove_domain {
    my $self = shift;
    eval { $self->id };
    $self->_allow_remove(@_);
635
    $self->shutdown_now(@_) if $self->is_active();
636
    $self->pre_remove();
637
638
639
640
641
642
643
644
645
}

sub _after_remove_domain {
    my $self = shift;
    if ($self->is_base) {
        $self->_do_remove_base(@_);
        $self->_remove_files_base();
    }
    return if !$self->{_data};
646
    $self->_remove_ports_db();
647
648
649
650
    $self->_remove_base_db();
    $self->_remove_domain_db();
}

651
652
653
654
655
656
657
658
sub _remove_ports_db {
    my $self = shift;

    my $sth = $$CONNECTOR->dbh->prepare("DELETE FROM domain_ports where id_domain=?");
    $sth->execute($self->id);
    $sth->finish;
}

659
660
661
662
663
664
665
666
667
668
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
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
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
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
sub _remove_domain_db {
    my $self = shift;

    return if !$self->is_known();

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


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

=head2 is_base
Returns true or  false if the domain is a prepared base
=cut

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

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

    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;

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

    my $sth = $$CONNECTOR->dbh->prepare("SELECT id FROM requests "
        ." WHERE id_domain=? AND status <> 'done'");
    $sth->execute($self->id);
    my ($id) = $sth->fetchrow;
    $sth->finish;

    return ($id or 0);
}

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

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


=head2 list_files_base
Returns a list of the filenames of this base-type domain
=cut

sub list_files_base {
    my $self = shift;
806
    my $with_target = shift;
807
808
809
810
811
812
813
814

    return if !$self->is_known();

    my $id;
    eval { $id = $self->id };
    return if $@ && $@ =~ /No DB info/i;
    die $@ if $@;

815
    my $sth = $$CONNECTOR->dbh->prepare("SELECT file_base_img, target "
816
817
818
819
820
        ." FROM file_base_images "
        ." WHERE id_domain=?");
    $sth->execute($self->id);

    my @files;
821
822
823
    while ( my ($img, $target) = $sth->fetchrow) {
        push @files,($img)          if !$with_target;
        push @files,[$img,$target]  if $with_target;
824
825
826
827
828
    }
    $sth->finish;
    return @files;
}

829
830
831
832
833
834
835
836
837
838
=head2 list_files_base_target

Returns a list of the filenames and targets of this base-type domain

=cut

sub list_files_base_target {
    return $_[0]->list_files_base("target");
}

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
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
=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;
    return $self->_do_remove_base();
}

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

893
sub _pre_remove_base {
894
895
    _allow_manage(@_);
    _check_has_clones(@_);
896
    $_[0]->spinoff_volumes();
897
898
899
900
901
}

sub _post_remove_base {
    my $self = shift;
    $self->_remove_base_db(@_);
Francesc Guasch's avatar
Francesc Guasch committed
902
    $self->_post_remove_base_domain();
903
904
}

Francesc Guasch's avatar
Francesc Guasch committed
905
sub _pre_shutdown_domain {}
906

Francesc Guasch's avatar
Francesc Guasch committed
907
sub _post_remove_base_domain {}
908

909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
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;

}

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

949
    my $clone = $self->_vm->create_domain(
950
951
952
953
954
955
        name => $name
        ,id_base => $id_base
        ,id_owner => $uid
        ,vm => $self->vm
        ,_vm => $self->_vm
    );
956
    $clone->description($self->description) if defined $self->description;
957
    return $clone;
958
959
960
961
962
}

sub _post_pause {
    my $self = shift;

963
    $self->_remove_iptables();
964
965
}

966
967
968
969
sub _pre_shutdown {
    my $self = shift;

    $self->_allow_manage_args(@_);
Francesc Guasch's avatar
Francesc Guasch committed
970
971
972

    $self->_pre_shutdown_domain();

973
974
975
976
977
978
    if ($self->is_paused) {
        my %args = @_;
        $self->resume(user => $args{user});
    }
}

979
980
981
982
sub _post_shutdown {
    my $self = shift;

    my %arg = @_;
983
984
    my $timeout = delete $arg{timeout};
    my $user = delete $arg{user};
985
986

    $self->_remove_temporary_machine(@_);
987
    $self->_remove_iptables() if $self->is_known();
988
    $self->clean_swap_volumes(user => $user)
989
        if $self->is_known && $self->id_base() && !$self->is_active;
990
991
992
993
994
995

    if (defined $timeout) {
        if ($timeout<2 && $self->is_active) {
            sleep $timeout;
            return $self->_do_force_shutdown() if $self->is_active;
        }
996
        confess "ERROR: Missing user "  if !$user;
997
998
        my $req = Ravada::Request->force_shutdown_domain(
                 name => $self->name
999
1000
                , uid => $user->id
                 , at => time+$timeout
1001
1002
1003
1004
        );
    }
}

1005
1006
1007
1008
1009
sub _pre_shutdown_now {
    my $self = shift;
    return if !$self->is_active;
}

1010
1011
1012
1013
1014
1015
1016
sub _post_shutdown_now {
    my $self = shift;
    my $user = shift;

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

1017
1018
1019
1020
1021
1022
1023
=head2 can_hybernate

Returns wether a domain supports hybernation

=cut

sub can_hybernate { 0 };
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043

=head2 add_volume_swap

Adds a swap volume to the virtual machine

Arguments:

    size => $kb
    name => $name (optional)

=cut

sub add_volume_swap {
    my $self = shift;
    my %arg = @_;

    $arg{name} = $self->name if !$arg{name};
    $self->add_volume(%arg, swap => 1);
}

1044
1045
1046
1047
=head2 expose

Expose a TCP port from the domain

Francesc Guasch's avatar
Francesc Guasch committed
1048
1049
1050
1051
Arguments: 
 - user
 - number of the port
 - optional name
1052
1053
1054
1055
1056

Returns: public ip and port

=cut

1057
sub expose($self, $user, $internal_port, $name=undef) {
1058

1059
    die "User ".$user->name." [".$user->id."] not allowed.\n"
1060
        if $self->id_owner != $user->id && !$user->is_admin;
1061

1062
1063
1064
1065
    my $sth = $$CONNECTOR->dbh->prepare(
        "INSERT INTO domain_ports (id_domain"
        ."  ,public_port, internal_port"
        ."  ,public_ip, internal_ip"
1066
        ."  ,name"
1067
        .")"
1068
        ." VALUES (?,?,?,?,?,?)"
1069
1070
    );

Francesc Guasch's avatar
Francesc Guasch committed
1071
    my $internal_ip;
1072
1073
1074
1075
    if ($self->is_active) {
        $internal_ip = $self->ip
            or warn "No internal IP for domain ".$self->name;
    }
1076
    my $public_ip = $self->_vm->ip;
1077
    my $public_port = $self->_new_free_port();
1078
1079

    # TODO
1080
1081
1082
1083
1084
1085
1086
    # if ($self->is_network_nat) {
    #   $public_ip = $self->_vm->ip;
    #   $public_port = $self->_new_free_port();
    # } else {
    #   $public_ip = $self->ip;
    #   $public_port = $internal_port
    # }
1087
1088
    $sth->execute($self->id
        , $public_port, $internal_port
1089
        , $public_ip, $internal_ip, ($name or undef));
1090
1091
    $sth->finish;

1092
    if ($internal_ip) {
1093
        my $remote_ip = $self->remote_ip();
Francesc Guasch's avatar
Francesc Guasch committed
1094
1095
        $self->_add_iptable($user, $remote_ip, $public_ip, $public_port);
        $self->_add_iptable_nat($user, $public_ip, $public_port, $internal_ip, $internal_port);
1096
    }
1097
1098
    return($public_ip, $public_port);
}
Francesc Guasch's avatar
Francesc Guasch committed
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109

=head2 remove_expose

Remove a exposed TCP port from the domain

Arguments:

 - number of the port
 - user

=cut
1110

1111
sub remove_expose($self, $user, $internal_port) {
1112

1113
    $self->_allow_manage($user);
1114
1115

    my ($public_ip, $public_port) = $self->public_address($internal_port);
1116
    $self->_remove_iptables(d_port => $public_port)
1117
1118
1119
1120
1121
1122
1123
1124
1125
        if $public_port;

    my $sth = $$CONNECTOR->dbh->prepare(
        "DELETE FROM domain_ports WHERE id_domain=? AND internal_port=?"
    );
    $sth->execute($self->id, $internal_port);

}

Francesc Guasch's avatar
Francesc Guasch committed
1126
1127
1128
1129
1130
1131
=head2 list_ports

List of exposed TCP ports

=cut

1132
sub list_ports($self) {
1133
1134
    $self->_init_connector();

1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
    my $sth = $$CONNECTOR->dbh->prepare("SELECT * FROM domain_ports "
        ." WHERE id_domain=?");
    $sth->execute($self->id);
    my @ports;
    while (my $row = $sth->fetchrow_hashref) {
        push @ports,($row);
    }
    return @ports;
}

1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
=head2 public_address

Returns the public IP address and port for a TCP service running in the domain.

Arguments: The internal port

=cut

sub public_address($self, $internal_port=undef) {
    return $self->_vm->ip if !$internal_port;

    my $sth = $$CONNECTOR->dbh->prepare(
        "SELECT public_ip,public_port "
        ." FROM domain_ports "
        ." WHERE id_domain=?"
        ."    AND internal_port=?"
    );

    $sth->execute($self->id, $internal_port);
    my ($public_ip, $public_port) = $sth->fetchrow();

    return ($public_ip, $public_port);
1167
1168
}

1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
=head2 client_ip

Returns the IP of the remote client that requested the start of the domain

=cut

sub client_ip($self) {
    my @active_iptables = $self->_active_iptables();
    die Dumper(\@active_iptables);
}

1180
1181
sub _remove_iptables {
    my $self = shift;
1182
    my %args = @_;
1183

1184
1185
    my $d_port = delete $args{d_port};
    croak "Unknown params:". join(", ", keys %args) if %args;
1186
1187
1188
1189
1190
1191
1192

    my $ipt_obj = _obj_iptables();

    my $sth = $$CONNECTOR->dbh->prepare(
        "UPDATE iptables SET time_deleted=?"
        ." WHERE id=?"
    );
1193
    for my $row ($self->_active_iptables()) {
1194
        my ($id, $iptables) = @$row;
1195
1196
1197
1198
1199
        if ($d_port) {
#            warn "$d_port\n".Dumper($iptables)."\n";
            next if !exists $iptables->[5]->{d_port}
                    || $iptables->[5]->{d_port} ne $d_port;
        }
1200
        my ($rv, $out, $err) = $ipt_obj->delete_ip_rule(@$iptables);
1201
1202
1203
1204
#        if (!$rv) {
#            warn Dumper($out,$err);
##            exit;
#        }
1205
1206
1207
1208
        $sth->execute(Ravada::Utils::now(), $id);
    }
}

1209
1210
1211
1212
1213
1214
# clean iptables left from down domains

sub _clean_iptables {

    my $sth = $$CONNECTOR->dbh->prepare(
        "SELECT id,id_domain,iptables FROM iptables "
1215
        ."    WHERE time_deleted IS NULL"
1216
    );
1217
1218
1219
1220
    my $sth_delete = $$CONNECTOR->dbh->prepare(
        "DELETE FROM iptables WHERE id=?"
    );

1221
    my ( $id, $id_domain, $iptables);
1222
    $sth->execute;
1223
    $sth->bind_columns(\( $id, $id_domain, $iptables));
1224
    while ($sth->fetch) {
1225
1226
1227
1228
1229
1230
1231
        my $domain;
        eval { $domain = Ravada::Domain->open($id_domain) };
        warn $@ if $@ && $@ !~ /Domain.*not found/i;
        if (!$domain) {
            $sth_delete->execute($id);
            next;
        }
1232
        next if $domain->is_active;
1233
        $domain->_remove_iptables();
1234
1235
1236
1237
    }
    $sth->finish;
}

1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
sub _remove_temporary_machine {
    my $self = shift;

    my %args = @_;
    my $user;

    return if !$self->is_known();

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

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

sub _post_resume {
    return _post_start(@_);
}

sub _post_start {
    my $self = shift;

1268
    $self->_add_iptable_display(@_);
1269
    $self->_open_iptables(@_);
1270
1271
}

1272
1273
sub _open_iptables {
    my $self = shift;
1274
1275
1276
1277

    # we need the remote_ip => ip , user => user
    return if scalar @_ % 2 ==1;

1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
    my %args = @_;
    my $user = $args{user};
    my $remote_ip = $args{remote_ip};

    my @ports = $self->list_ports();
    return if !@ports;

    # TODO check if no NAT, public ip is domain ip
    my $public_ip = $self->_vm->ip();

    my $internal_ip = $self->ip();
    for ( 0 .. 2 ) {
        $internal_ip = $self->ip();
        last if $internal_ip;
        sleep 1;
    }
    return if !$internal_ip;

    for my $row (@ports) {
        $self->_add_iptable($user, $remote_ip, $public_ip
                            , $row->{public_port});
        $self->_add_iptable_nat($user, $public_ip, $row->{public_port}
                                , $internal_ip, $row->{internal_port});
    }
1302
1303
}

1304
sub _add_iptable_display {
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
    my $self = shift;
    return if scalar @_ % 2;
    my %args = @_;

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

    my $user = $args{user};

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

1316
1317
1318
1319
1320
    $self->_add_iptable( $user, $remote_ip, $local_ip, $local_port);
}

sub _add_iptable($self, $user, $remote_ip, $local_ip, $local_port) {

1321
1322
1323
1324
    my $ipt_obj = _obj_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
    #
Francesc Guasch's avatar
Francesc Guasch committed
1325
1326
    my $filter = 'filter';
    my $chain = $IPTABLES_CHAIN;
1327
    my @iptables_arg = ($remote_ip
Francesc Guasch's avatar
Francesc Guasch committed
1328
                        ,$local_ip, $filter, $chain, 'ACCEPT',
1329
1330
1331
1332
                        ,{'protocol' => 'tcp', 's_port' => 0, 'd_port' => $local_port});

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

1333
    $self->_log_iptable(iptables => \@iptables_arg, remote_ip => $remote_ip, user => $user);
1334
1335

    @iptables_arg = ( '0.0.0.0'
Francesc Guasch's avatar
Francesc Guasch committed
1336
                        ,$local_ip, $filter, $chain, 'DROP',
1337
                        ,{'protocol' => 'tcp', 's_port' => 0, 'd_port' => $local_port});
1338

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

    $self->_log_iptable(iptables => \@iptables_arg, remote_ip => $remote_ip, user => $user);
1342
1343
1344

}

Francesc Guasch's avatar
Francesc Guasch committed
1345
sub _add_iptable_nat($self,$user, $public_ip, $public_port, $internal_ip, $internal_port) {
1346
1347
    confess "Undefined internal_ip (arg 4)"
        if !defined $internal_ip;
1348
1349
1350
1351
    my $filter = 'nat';
    my $chain = 'PREROUTING';
    my $ipt_obj = _obj_iptables();

1352
    my @iptables_arg = ( '0.0.0.0/0', $public_ip, $filter, $chain, 'DNAT'
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
        ,{    protocol => 'tcp',
                d_port => $public_port
            ,   to_port => $internal_port
            ,   to_ip => $internal_ip
        }
    );
    my ($rv, $out_ar, $errs_ar) = $ipt_obj->run_ipt_cmd(
        "/sbin/iptables -t nat -A PREROUTING"
        ." -d $public_ip"
        ." -m tcp -p tcp --dport $public_port"
        ." -j DNAT --to-destination $internal_ip:$internal_port"
    );

    $self->_log_iptable(iptables => \@iptables_arg
            , remote_ip => $public_ip     , user => $user);
Francesc Guasch's avatar
Francesc Guasch committed
1368
1369
}

1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
=head2 open_iptables

Open iptables for a remote client

=over

=item user

=item  remote_ip

=back

=cut

sub open_iptables {
    my $self = shift;

    my %args = @_;
    my $user = Ravada::Auth::SQL->search_by_id($args{uid});
    $args{user} = $user;
    delete $args{uid};
1391
    $self->_add_iptable_display(%args);
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
}

sub _obj_iptables {

	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' => 0, ### 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
	($rv, $out_ar, $errs_ar) = $ipt_obj->chain_exists('filter', $IPTABLES_CHAIN);
    if (!$rv) {
		$ipt_obj->create_chain('filter', $IPTABLES_CHAIN);
        $ipt_obj->add_jump_rule('filter','INPUT', 1, $IPTABLES_CHAIN);
	}
	# set the policy on the FORWARD table to DROP
#    $ipt_obj->set_chain_policy('filter', 'FORWARD', 'DROP');

    return $ipt_obj;
}

sub _log_iptable {
    my $self = shift;
    if (scalar(@_) %2 ) {
        carp "Odd number ".Dumper(\@_);
        return;
    }
    my %args = @_;
    my $remote_ip = $args{remote_ip};#~ or return;

    my $user = $args{user};
    my $uid = $args{uid};
Francesc Guasch's avatar
Francesc Guasch committed
1443
    confess "Chyoose wether uid or user "
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
        if $user && $uid;
    lock_hash(%args);

    $uid = $args{user}->id if !$uid;

    my $iptables = $args{iptables};

    my $sth = $$CONNECTOR->dbh->prepare(
        "INSERT INTO iptables "
        ."(id_domain, id_user, remote_ip, time_req, iptables)"
        ."VALUES(?, ?, ?, ?, ?)"
    );
    $sth->execute($self->id, $uid, $remote_ip, Ravada::Utils::now()
        ,encode_json($iptables));
    $sth->finish;

}

1462
sub _active_iptables($self) {
1463
1464
1465
1466
1467
1468
1469
1470

    my $sth = $$CONNECTOR->dbh->prepare(
        "SELECT id,iptables FROM iptables "
        ." WHERE "
        ."    id_domain=?"
        ."    AND time_deleted IS NULL"
        ." ORDER BY time_req DESC "
    );
1471
    $sth->execute($self->id);
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
    my @iptables;
    while (my ($id, $iptables) = $sth->fetchrow) {
        push @iptables, [ $id, decode_json($iptables)];
    }
    return @iptables;
}

sub _check_duplicate_domain_name {
    my $self = shift;
# TODO
#   check name not in current domain in db
#   check name not in other VM domain
    $self->id();
}

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

    my $new_name = $args{name} or confess "Missing new name";

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

=head2 is_public

Sets or get the domain public

    $domain->is_public(1);

    if ($domain->is_public()) {
        ...
    }

=cut

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

    _init_connector();
    if (defined $value) {
        my $sth = $$CONNECTOR->dbh->prepare("UPDATE domains set is_public=?"
                ." WHERE id=?");
        $sth->execute($value, $self->id);
        $sth->finish;
    }
    return $self->_data('is_public');
}

=head2 clean_swap_volumes

Check if the domain has swap volumes defined, and clean them

    $domain->clean_swap_volumes();

=cut

sub clean_swap_volumes {
    my $self = shift;
    for my $file ( $self->list_volumes) {
        $self->clean_disk($file)
            if $file =~ /\.SWAP\.\w+$/;
    }
}


sub _pre_rename {
    my $self = shift;

    my %args = @_;
    my $name = $args{name};
    my $user = $args{user};

    $self->_check_duplicate_domain_name(@_);

    $self->shutdown(user => $user)  if $self->is_active;
}

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

    $self->_rename_domain_db(@_);
}

 sub _post_screenshot {
     my $self = shift;
     my ($filename) = @_;

     return if !defined $filename;

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

=head2 drivers

List the drivers available for a domain. It may filter for a given type.

    my @drivers = $domain->drivers();
    my @video_drivers = $domain->drivers('video');

=cut

sub drivers {
    my $self = shift;
    my $name = shift;
    my $type = (shift or $self->_vm->type);

    _init_connector();

    $type = 'qemu' if $type =~ /^KVM$/;
    my $query = "SELECT id from domain_drivers_types "
        ." WHERE vm=?";
    $query .= " AND name=?" if $name;

    my $sth = $$CONNECTOR->dbh->prepare($query);

    my @sql_args = ($type);
    push @sql_args,($name)  if $name;

    $sth->execute(@sql_args);

    my @drivers;
    while ( my ($id) = $sth->fetchrow) {
        push @drivers,Ravada::Domain::Driver->new(id => $id, domain => $self);
    }
    return $drivers[0] if !wantarray && $name && scalar@drivers< 2;
    return @drivers;
}

=head2 set_driver_id

Sets the driver of a domain given it id. The id must be one from
the table domain_drivers_options

    $domain->set_driver_id($id_driver);

=cut

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

    my $sth = $$CONNECTOR->dbh->prepare(
        "SELECT d.name,o.value "
        ." FROM domain_drivers_types d, domain_drivers_options o"
        ." WHERE d.id=o.id_driver_type "
        ."    AND o.id=?"
    );
    $sth->execute($id);

    my ($type, $value) = $sth->fetchrow;
    confess "Unknown driver option $id" if !$type || !$value;

    $self->set_driver($type => $value);
    $sth->finish;
}

1639
sub _remote_data {
1640
1641
1642
    my $self = shift;

    my $sth = $$CONNECTOR->dbh->prepare(
1643
        "SELECT * FROM iptables "
1644
1645
1646
1647
1648
1649
        ." WHERE "
        ."    id_domain=?"
        ."    AND time_deleted IS NULL"
        ." ORDER BY time_req DESC "
    );
    $sth->execute($self->id);
1650
1651
1652
1653
1654
1655
1656
1657
1658
    my @rows;
    while (my $row = $sth->fetchrow_hashref) {
        my $iptables = decode_json($row->{iptables});
        next if $iptables->[3] ne 'RAVADA'
                || $iptables->[4] ne 'ACCEPT';

        next if scalar@rows
            && $row->{id_user} == $rows[0]->{id_user}
            && $row->{remote_ip} eq $rows[0]->{remote_ip};
1659

1660
1661
1662
1663
1664
1665
        push @rows,($row);
    }
    die "Too many active tables for this domain"
        .Dumper(\@rows)  if scalar @rows>1;
    return $rows[0]->{remote_ip}
            , $rows[0]->{id_user}
1666
}
1667

1668
1669
1670
1671
1672
1673
=head2 remote_ip

Returns the IP of the remote host that launched this virtual machine

=cut

1674
1675
sub remote_ip($self) {
    my ( $remote_ip ) = $self->_remote_data();
Francesc Guasch's avatar
Francesc Guasch committed
1676
    return $remote_ip;
1677
}
1678

1679
1680
1681
1682
1683
1684
=head2 remote_user

Returns the user that launched this virtual machine

=cut

1685
1686
sub remote_user($self) {
    my (undef, $remote_uid) = $self->_remote_data();
1687
1688
    return if !$remote_uid;
    return Ravada::Auth::SQL->search_by_id($remote_uid);
1689
1690
1691
1692
}



1693
1694
1695
1696
1697
1698
sub _new_free_port {
    my $self = shift;
    my $used_port = {};
    $self->_list_used_ports_sql($used_port);
    $self->_list_used_ports_netstat($used_port);

Francesc Guasch's avatar
Francesc Guasch committed
1699
    my $free_port = 5950;
1700
1701
1702
1703
1704
1705
1706
1707
    for (;;) {
        last if !$used_port->{$free_port};
        $free_port++ ;
    }
    return $free_port;

}

1708
1709
1710
1711
1712
1713
sub _dbh {
    my $self = shift;
    _init_connector() if !$CONNECTOR || !$$CONNECTOR;
    return $$CONNECTOR->dbh;
}

1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
sub _list_used_ports_sql {
    my $self = shift;
    my $used_port = shift;

    my $sth = $$CONNECTOR->dbh->prepare("SELECT public_port FROM domain_ports ");
    $sth->execute();
    my $port;
    $sth->bind_columns(\$port);

    while ($sth->fetch ) { $used_port->{$port}++ };

}

sub _list_used_ports_netstat {
    my $self = shift;
    my $used_port = shift;

    my @cmd = ('netstat', '-tln');
    my ($in, $out, $err);
    run3(\@cmd, \$in, \$err, \$out);

    for my $line (split /\n/, $out) {
        my ($port) = $line =~
                       /^tcp
                        \s+\d+
                        \s+\d+
                        \s+\d+\.\d+\.\d+\.\d+
                        \:(\d+)/;
        $used_port->{$port}++ if $port;
    }

}

1747
1;