Domain.pm 35.2 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
use Carp qw(carp confess croak cluck);
use Data::Dumper;
Francesc Guasch's avatar
Francesc Guasch committed
14
use File::Copy;
15
16
17
18
19
20
21
use Hash::Util qw(lock_hash);
use Image::Magick;
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
##########################################################

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' => (
94
    is => 'ro'
95
96
97
98
99
100
101
102
103
104
    ,isa => 'Object'
    ,required => 0
);

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

105
106
107
108
109
110
has 'tls' => (
    is => 'rw'
    ,isa => 'Int'
    ,default => 0
);

111
112
113
114
115
116
117
has 'description' => (
    is => 'rw'
    ,isa => 'Str'
    ,required => 0
    ,trigger => \&_update_description
);

118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
##################################################################################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;

before 'start' => \&_start_preconditions;
 after 'start' => \&_post_start;

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

142
143
144
before 'hybernate' => \&_allow_manage;
 after 'hybernate' => \&_post_pause;

145
146
147
before 'resume' => \&_allow_manage;
 after 'resume' => \&_post_resume;

148
before 'shutdown' => \&_pre_shutdown;
149
150
after 'shutdown' => \&_post_shutdown;
after 'shutdown_now' => \&_post_shutdown_now;
151
152

before 'force_shutdown' => \&_pre_shutdown_now;
153
154
after 'force_shutdown' => \&_post_shutdown_now;

155
before 'remove_base' => \&_pre_remove_base;
156
157
158
159
160
after 'remove_base' => \&_post_remove_base;

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

161
162
before 'clone' => \&_pre_clone;

163
after 'screenshot' => \&_post_screenshot;
Francesc Guasch's avatar
Francesc Guasch committed
164
165
166

after '_select_domain_db' => \&_post_select_domain_db;

167
##################################################
168
169
170
171
172
173
#

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

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

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

sub _start_preconditions{
    my ($self) = @_;

188
    confess "Domain ".$self->name." is a base. Bases can't get started."
189
190
        if $self->is_base();

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

}

201
202
sub _update_description {
    my $self = shift;
fv3rdugo's avatar
fv3rdugo committed
203

204
205
206
207
    return if defined $self->description
        && defined $self->_data('description')
        && $self->description eq $self->_data('description');

208
209
    my $sth = $$CONNECTOR->dbh->prepare(
        "UPDATE domains SET description=? "
210
211
        ." WHERE id=? ");
    $sth->execute($self->description,$self->id);
212
    $sth->finish;
213
    $self->{_data}->{description} = $self->{description};
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

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();

}

250
251
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
sub _allow_shutdown {
    my $self = shift;
    my %args = @_;

    my $user = $args{user} || confess "ERROR: Missing user arg";

    if ( $self->id_base() && $user->can_shutdown_clone()) {
        my $base = $self->open($self->id_base);
        return if $base->id_owner == $user->id;
    } elsif($user->can_shutdown_all) {
        return;
    } else {
        $self->_allow_manage_args(user => $user);
    }
}

sub _around_add_volume {
    my $orig = shift;
    my $self = shift;
    confess "ERROR in args ".Dumper(\@_)
        if scalar @_ % 2;
    my %args = @_;

    my $path = $args{path};
    if ( $path ) {
        my $name = $args{name};
        if (!$name) {
            ($args{name}) = $path =~ m{.*/(.*)};
        }
    }
    return $self->$orig(%args);
}

283
284
285
286
287
288
289
290
291
292
293
294
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);
295
    $self->_post_remove_base();
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
    if ($self->is_active) {
        $self->shutdown(user => $user);
        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);

Francesc Guasch's avatar
Francesc Guasch committed
322
323
324
325
326
    if ($self->id_base && !$self->description()) {
        my $base = Ravada::Domain->open($self->id_base);
        $self->description($base->description)  if $base->description();
    }

327
    $self->_remove_id_base();
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
};

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
451
=head2 open
452

Francesc Guasch's avatar
Francesc Guasch committed
453
454
455
456
457
458
459
460
461
Open a domain

Argument: id

Returns: Domain object read only

=cut

sub open($class, $id) {
462
463
    confess "Missing id"    if !defined $id;

Francesc Guasch's avatar
Francesc Guasch committed
464
465
466
467
    my $self = {};
    bless $self,$class;

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

Francesc Guasch's avatar
Francesc Guasch committed
469
    my $vm0 = {};
Francesc Guasch's avatar
Francesc Guasch committed
470
    my $vm_class = "Ravada::VM::".$row->{vm};
Francesc Guasch's avatar
Francesc Guasch committed
471
472
473
    bless $vm0, $vm_class;

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

Francesc Guasch's avatar
Francesc Guasch committed
475
    return $vm->search_domain($row->{name});
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
}

=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;
Francesc Guasch's avatar
Francesc Guasch committed
513

514
515
516
    return $row if $row->{id};
}

Francesc Guasch's avatar
Francesc Guasch committed
517
518
519
520
521
522
sub _post_select_domain_db {
    my $self = shift;
    $self->description($self->{_data}->{description})
        if defined $self->{_data}->{description}
};

523
524
525
526
527
528
529
530
531
532
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 "
533
534
        ." (id_domain , file_base_img, target )"
        ." VALUES(?,?,?)"
535
536
    );
    for my $file_img (@file_img) {
537
538
539
        my $target;
        ($file_img, $target) = @$file_img if ref $file_img;
        $sth->execute($self->id, $file_img, $target );
540
541
542
543
544
545
546
547
548
549
550
551
    }
    $sth->finish;

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

    $self->_select_domain_db();
}

552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
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');
}

577
578
579
580
581
582
=head2 display_file

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

=cut

583
584
sub display_file($self,$user) {
    return $self->_display_file_spice($user);
585
586
}

587
588
589
590
591
592
593
594
595
596
597
# 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";
598
599
600
    if ($self->tls) {
        $ret .= "tls-port=%s\n";
    } else {
601
        $ret .= "port=$port\n";
602
603
604
605
    }
    $ret .="password=%s\n"  if $self->spice_password();

    $ret .=
606
607
608
609
        "fullscreen=1\n"
        ."title=".$self->name." - Press SHIFT+F12 to exit\n"
        ."enable-smartcard=0\n"
        ."enable-usb-autoshare=1\n"
610
        ."delete-this-file=1\n"
611
        ."usb-filter=-1,-1,-1,-1,0\n";
612
613

    $ret .=";" if !$self->tls;
614
615
    $ret .= "tls-ciphers=DEFAULT\n"
        .";host-subject=O=".$ip.",CN=?\n";
616
617

    $ret .=";"  if !$self->tls;
618
619
620
621
    $ret .="ca=CA\n"
        ."toggle-fullscreen=shift+f11\n"
        ."release-cursor=shift+f12\n"
        ."secure-attention=ctrl+alt+end\n";
622
623
624
625
626
627
    $ret .=";" if !$self->tls;
    $ret .="secure-channels=main;inputs;cursor;playback;record;display;usbredir;smartcard\n";

    return $ret;
}

628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
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);
651
        confess $@;
652
653
654
655
656
    }
    $sth->finish;

}

657
=head2 pre_remove
658

659
660
661
662
663
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
664
665
666

=cut

667
sub pre_remove { }
668

669
670
671
sub _pre_remove_domain {
    my $self = shift;
    eval { $self->id };
672
    $self->pre_remove();
673
    $self->_allow_remove(@_);
674
    $self->pre_remove();
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
}

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

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 "
805
            ." WHERE id_base = ? AND (is_base=NULL OR is_base=0)");
806
807
808
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
    $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;
835
    my $with_target = shift;
836
837
838
839
840
841
842
843

    return if !$self->is_known();

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

844
    my $sth = $$CONNECTOR->dbh->prepare("SELECT file_base_img, target "
845
846
847
848
849
        ." FROM file_base_images "
        ." WHERE id_domain=?");
    $sth->execute($self->id);

    my @files;
850
851
852
    while ( my ($img, $target) = $sth->fetchrow) {
        push @files,($img)          if !$with_target;
        push @files,[$img,$target]  if $with_target;
853
854
855
856
857
    }
    $sth->finish;
    return @files;
}

858
859
860
861
862
863
864
865
866
867
=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");
}

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

Francesc Guasch's avatar
Francesc Guasch committed
894
    my $in = Image::Magick->new();
895
896
897
    my $err = $in->Read($file_in);
    confess $err if $err;

Francesc Guasch's avatar
Francesc Guasch committed
898
    $in->Scale(width => 250, height => 188);
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
    $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();
}

923
sub _pre_remove_base {
924
925
    _allow_manage(@_);
    _check_has_clones(@_);
926
    $_[0]->spinoff_volumes();
927
928
929
930
931
}

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

Francesc Guasch's avatar
Francesc Guasch committed
935
sub _pre_shutdown_domain {}
936

Francesc Guasch's avatar
Francesc Guasch committed
937
sub _post_remove_base_domain {}
938

939
940
941
942
943
944
sub _remove_base_db {
    my $self = shift;

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

Francesc Guasch's avatar
Francesc Guasch committed
945
    $sth->execute($self->{_data}->{id});
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
    $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 = @_;

970
971
972
973
974
    my $name = delete $args{name}
        or confess "ERROR: Missing domain cloned name";

    my $user = delete $args{user}
        or confess "ERROR: Missing request user";
975

Francesc Guasch's avatar
Francesc Guasch committed
976
977
    return $self->_copy_clone(@_)   if $self->id_base();

978
979
980
981
982
    my $request = delete $args{request};
    my $memory = delete $args{memory};

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

984
985
986
987
988
989
    my $uid = $user->id;

    if ( !$self->is_base() ) {
        $request->status("working","Preparing base")    if $request;
        $self->prepare_base($user)
    }
990
991
992

    my $id_base = $self->id;

993
    my @args_copy = ();
994
995
    push @args_copy, ( memory => $memory )      if $memory;
    push @args_copy, ( request => $request )    if $request;
996

997
    my $clone = $self->_vm->create_domain(
998
999
1000
1001
1002
        name => $name
        ,id_base => $id_base
        ,id_owner => $uid
        ,vm => $self->vm
        ,_vm => $self->_vm
1003
        ,@args_copy
1004
    );
1005
    return $clone;
1006
1007
}

Francesc Guasch's avatar
Francesc Guasch committed
1008
1009
1010
sub _copy_clone($self, %args) {
    my $name = delete $args{name} or confess "ERROR: Missing name";
    my $user = delete $args{user} or confess "ERROR: Missing user";
1011
    my $memory = delete $args{memory};
1012
    my $request = delete $args{request};
1013
1014
1015

    confess "ERROR: Unknown arguments ".join(",",sort keys %args)
        if keys %args;
Francesc Guasch's avatar
Francesc Guasch committed
1016
1017
1018

    my $base = Ravada::Domain->open($self->id_base);

1019
1020
1021
1022
    my @copy_arg;
    push @copy_arg, ( memory => $memory ) if $memory;

    $request->status("working","Copying domain ".$self->name
1023
1024
        ." to $name")   if $request;

Francesc Guasch's avatar
Francesc Guasch committed
1025
1026
1027
1028
1029
    my $copy = $self->_vm->create_domain(
        name => $name
        ,id_base => $base->id
        ,id_owner => $user->id
        ,_vm => $self->_vm
1030
        ,@copy_arg
Francesc Guasch's avatar
Francesc Guasch committed
1031
    );
1032
1033
1034
1035
1036
1037
1038
1039
    my @volumes = $self->list_volumes_target;
    my @copy_volumes = $copy->list_volumes_target;

    my %volumes = map { $_->[1] => $_->[0] } @volumes;
    my %copy_volumes = map { $_->[1] => $_->[0] } @copy_volumes;
    for my $target (keys %volumes) {
        copy($volumes{$target}, $copy_volumes{$target})
            or die "$! $volumes{$target}, $copy_volumes{$target}"
Francesc Guasch's avatar
Francesc Guasch committed
1040
1041
1042
1043
    }
    return $copy;
}

1044
1045
1046
1047
1048
1049
1050
sub _post_pause {
    my $self = shift;
    my $user = shift;

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

1051
1052
1053
sub _pre_shutdown {
    my $self = shift;

1054
    $self->_allow_shutdown(@_);
Francesc Guasch's avatar
Francesc Guasch committed
1055
1056
1057

    $self->_pre_shutdown_domain();

1058
1059
1060
1061
1062
1063
    if ($self->is_paused) {
        my %args = @_;
        $self->resume(user => $args{user});
    }
}

1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
sub _post_shutdown {
    my $self = shift;

    my %arg = @_;
    my $timeout = $arg{timeout};

    $self->_remove_temporary_machine(@_);
    $self->_remove_iptables(@_);
    $self->clean_swap_volumes(@_) if $self->id_base() && !$self->is_active;

    if (defined $timeout) {
        if ($timeout<2 && $self->is_active) {
            sleep $timeout;
            return $self->_do_force_shutdown() if $self->is_active;
        }

        my $req = Ravada::Request->force_shutdown_domain(
                 name => $self->name
                , uid => $arg{user}->id
                 , at => time+$timeout 
        );
    }
}

1088
1089
1090
1091
1092
sub _pre_shutdown_now {
    my $self = shift;
    return if !$self->is_active;
}

1093
1094
1095
1096
1097
1098
1099
sub _post_shutdown_now {
    my $self = shift;
    my $user = shift;

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

1100
1101
1102
1103
1104
1105
1106
=head2 can_hybernate

Returns wether a domain supports hybernation

=cut

sub can_hybernate { 0 };
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
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
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287

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

sub _remove_iptables {
    my $self = shift;

    my $args = {@_};

    confess "Missing user=>\$user" if !$args->{user};

    my $ipt_obj = _obj_iptables();

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

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;

    $self->_add_iptable(@_);
}

sub _add_iptable {
    my $self = shift;
    return if scalar @_ % 2;
    my %args = @_;

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

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

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

    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
    #
    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);

    $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, %args);

}

=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};
    $self->_add_iptable(%args);
}

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
1288
    confess "Chyoose wether uid or user "
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
        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;

}

sub _active_iptables {
    my $self = shift;
    my $user = shift;

    confess "Missing \$user" if !$user;

    my $sth = $$CONNECTOR->dbh->prepare(
        "SELECT id,iptables FROM iptables "
        ." WHERE "
        ."    id_domain=?"
        ."    AND id_user=? "
        ."    AND time_deleted IS NULL"
        ." ORDER BY time_req DESC "
    );
    $sth->execute($self->id, $user->id);
    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;
1371
        $self->{_data}->{is_public} = $value;
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
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
    }
    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();

1442
1443
1444
    my $type2 = $type;
    $type2 = 'KVM' if $type =~ /qemu/;
    $type2 = 'qemu' if $type =~ /KVM;/;
1445
    my $query = "SELECT id from domain_drivers_types "
1446
        ." WHERE (vm=? or vm=?)";
1447
1448
1449
1450
    $query .= " AND name=?" if $name;

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

1451
    my @sql_args = ($type,$type2);
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
    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;
}

1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
sub remote_ip {
    my $self = shift;

    my $sth = $$CONNECTOR->dbh->prepare(
        "SELECT remote_ip FROM iptables "
        ." WHERE "
        ."    id_domain=?"
        ."    AND time_deleted IS NULL"
        ." ORDER BY time_req DESC "
    );
    $sth->execute($self->id);
    my ($remote_ip) = $sth->fetchrow();
    $sth->finish;
    return ($remote_ip or undef);

}
1508

1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
=head2 get_driver

Returns the driver from a domain

Argument: name of the device [ optional ]
Returns all the drivers if not passwed

    my $driver = $domain->get_driver('video');

=cut

sub get_driver {}

1522
1523
=head2 list_requests

1524
1525
Returns a list of pending requests from the domain. It won't show those requests
scheduled for later.
1526
1527
1528
1529
1530

=cut

sub list_requests {
    my $self = shift;
1531
1532
    my $all = shift;

1533
    my $sth = $$CONNECTOR->dbh->prepare(
1534
        "SELECT * FROM requests WHERE id_domain = ? AND status ne 'done'"
1535
1536
1537
1538
    );
    $sth->execute($self->id);
    my @list;
    while ( my $req_data =  $sth->fetchrow_hashref ) {
1539
        next if !$all && $req_data->{at_time} && $req_data->{at_time} - time > 1;
1540
1541
1542
1543
1544
1545
1546
        push @list,($req_data);
    }
    $sth->finish;
    return scalar @list if !wantarray;
    return map { Ravada::Request->open($_->{id}) } @list;
}

1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
=head2 list_all_requests

Returns a list of pending requests from the domain including those scheduled for later

=cut

sub list_all_requests {
    return list_requests(@_,'all');
}

1557
1558
1559
1560
1561
1562
sub _dbh {
    my $self = shift;
    _init_connector() if !$CONNECTOR || !$$CONNECTOR;
    return $$CONNECTOR->dbh;
}

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
=head2 set_option

Sets a domain option:

=over

=item * description

=item * run_timeout

=back


    $domain->set_option(description => 'Virtual Machine for ...');

=cut

sub set_option($self, $option, $value) {
    if ($option eq 'description') {
        warn "$option -> $value\n";
        $self->description($value);
    } elsif ($option eq 'run_timeout') {
        $self->run_timeout($value);
    } else {
        confess "ERROR: Unknown option '$option'";
    }
}

=head2 type

Returns the virtual machine type as a string.

=cut

sub type {
    my $self = shift;
    my ($type) = $self =~ m{.*::(.*)};
    return $type;
}

sub _pre_clone($self,%args) {
    my $name = delete $args{name};
    my $user = delete $args{user};
    my $memory = delete $args{memory};
1607
    delete $args{request};
1608
1609

    confess "ERROR: Missing clone name "    if !$name;
1610
    confess "ERROR: Invalid name '$name'"   if $name !~ /^[a-z0-9_-]+$/i;
1611
1612
1613
1614
1615
1616

    confess "ERROR: Missing user owner of new domain"   if !$user;

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

1617
1;