Ravada.pm 31.2 KB
Newer Older
1
2
3
4
5
package Ravada;

use warnings;
use strict;

Francesc Guasch's avatar
Francesc Guasch committed
6
our $VERSION = '0.2.4';
Francesc Guasch's avatar
Francesc Guasch committed
7

8
use Carp qw(carp croak);
9
use Data::Dumper;
10
use DBIx::Connector;
11
use Hash::Util qw(lock_hash);
12
use Moose;
Francesc Guasch's avatar
Francesc Guasch committed
13
use POSIX qw(WNOHANG);
14
15
use YAML;

16
17
use Socket qw( inet_aton inet_ntoa );

Francesc Guasch's avatar
Francesc Guasch committed
18
use Ravada::Auth;
19
use Ravada::Request;
20
use Ravada::VM::KVM;
21
use Ravada::VM::Void;
22

Francesc Guasch's avatar
Francesc Guasch committed
23
24
25
26
27
28
29
30
31
32
33
34
=head1 NAME

Ravada - Remove Virtual Desktop Manager

=head1 SYNOPSIS

  use Ravada;

  my $ravada = Ravada->new()

=cut

35
36
37
38
39
40
41

our $FILE_CONFIG = "/etc/ravada.conf";

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

our $CONNECTOR;
our $CONFIG = {};
42
our $DEBUG;
43
our $CAN_FORK = 1;
44
our $CAN_LXC = 0;
45
46
47
48

# Seconds to wait for other long process
our $SECONDS_WAIT_CHILDREN = 2;
# Limit for long processes
49
our $LIMIT_PROCESS = 2;
50
51
our $LIMIT_HUGE_PROCESS = 1;

52
53
our $DIR_SQL = "sql/mysql";
$DIR_SQL = "/usr/share/doc/ravada/sql/mysql" if ! -e $DIR_SQL;
54

55
# LONG commands take long
56
57
our %HUGE_COMMAND = map { $_ => 1 } qw(download);
our %LONG_COMMAND =  map { $_ => 1 } (qw(prepare_base remove_base screenshot ), keys %HUGE_COMMAND);
58
59
60
61
62
63
64
65
66

has 'vm' => (
          is => 'ro'
        ,isa => 'ArrayRef'
       ,lazy => 1
     , builder => '_create_vm'
);

has 'connector' => (
67
68
69
70
71
72
        is => 'rw'
);

has 'config' => (
    is => 'ro'
    ,isa => 'Str'
73
74
);

75
76
77
78
79
80
has 'warn_error' => (
    is => 'rw'
    ,isa => 'Bool'
    ,default => sub { 1 }
);

Francesc Guasch's avatar
Francesc Guasch committed
81
82
83
84
85
86
87
=head2 BUILD

Internal constructor

=cut


88
89
sub BUILD {
    my $self = shift;
90
    if ($self->config()) {
91
        _init_config($self->config);
92
    } else {
Francesc Guasch's avatar
Francesc Guasch committed
93
        _init_config($FILE_CONFIG) if -e $FILE_CONFIG;
94
    }
95

Francesc Guasch's avatar
Francesc Guasch committed
96
    if ( $self->connector ) {
joansp's avatar
joansp committed
97
        $CONNECTOR = $self->connector
Francesc Guasch's avatar
Francesc Guasch committed
98
99
    } else {
        $CONNECTOR = $self->_connect_dbh();
100
        $self->connector($CONNECTOR);
Francesc Guasch's avatar
Francesc Guasch committed
101
    }
Francesc Guasch's avatar
Francesc Guasch committed
102
    Ravada::Auth::init($CONFIG);
103
    $self->_create_tables();
104
    $self->_upgrade_tables();
105
106
}

107
108
109
110
111
112
113
114
115
116
117
118
119
120
sub _upgrade_table {
    my $self = shift;
    my ($table, $field, $definition) = @_;
    my $dbh = $CONNECTOR->dbh;

    my $sth = $dbh->column_info(undef,undef,$table,$field);
    my $row = $sth->fetchrow_hashref;
    $sth->finish;
    return if $row;

    warn "INFO: adding $field $definition to $table\n";
    $dbh->do("alter table $table add $field $definition");
}

121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
sub _create_table {
    my $self = shift;
    my $table = shift;

    my $sth = $CONNECTOR->dbh->table_info('%',undef,$table,'TABLE');
    my $info = $sth->fetchrow_hashref();
    $sth->finish;
    return if keys %$info;

    warn "INFO: creating table $table\n";
    my $file_sql = "$DIR_SQL/$table.sql";
    open my $in,'<',$file_sql or die "$! $file_sql";
    my $sql = join " ",<$in>;
    close $in;

    $CONNECTOR->dbh->do($sql);
    return 1;
}

sub _insert_data {
    my $self = shift;
    my $table = shift;

    my $file_sql =  "$DIR_SQL/../data/insert_$table.sql";
    return if ! -e $file_sql;

    warn "INFO: inserting data for $table\n";
    open my $in,'<',$file_sql or die "$! $file_sql";
    my $sql = '';
    while (my $line = <$in>) {
        $sql .= $line;
        next if $sql !~ /\w/ || $sql !~ /;\s*$/;
        $CONNECTOR->dbh->do($sql);
        $sql = '';
    }
    close $in;

}

sub _create_tables {
    my $self = shift;
162
163
    return if $CONNECTOR->dbh->{Driver}{Name} !~ /mysql/i;

164
165
166
167
168
169
170
171
172
    opendir my $ls,$DIR_SQL or die "$! $DIR_SQL";
    while (my $file = readdir $ls) {
        my ($table) = $file =~ m{(.*)\.sql$};
        next if !$table;
        $self->_insert_data($table)     if $self->_create_table($table);
    }
    closedir $ls;
}

173
174
sub _upgrade_tables {
    my $self = shift;
175
176
    return if $CONNECTOR->dbh->{Driver}{Name} !~ /mysql/i;

177
    $self->_upgrade_table('file_base_images','target','varchar(64) DEFAULT NULL');
178
179
    $self->_upgrade_table('vms','vm_type',"char(20) NOT NULL DEFAULT 'KVM'");
    $self->_upgrade_table('requests','at_time','int(11) DEFAULT NULL');
180
181
    $self->_upgrade_table('iso_images','md5_url','varchar(255)');
    $self->_upgrade_table('iso_images','file_re','char(64)');
182
    $self->_upgrade_table('iso_images','device','varchar(255)');
183
184
185
}


186
187
188
189
sub _connect_dbh {
    my $driver= ($CONFIG->{db}->{driver} or 'mysql');;
    my $db_user = ($CONFIG->{db}->{user} or getpwnam($>));;
    my $db_pass = ($CONFIG->{db}->{password} or undef);
Francesc Guasch's avatar
Francesc Guasch committed
190
191
    my $db = ( $CONFIG->{db}->{db} or 'ravada' );
    return DBIx::Connector->new("DBI:$driver:$db"
192
193
194
195
196
                        ,$db_user,$db_pass,{RaiseError => 1
                        , PrintError=> 0 });

}

197
=head2 display_ip
198

199
Returns the default display IP read from the config file
200

201
=cut
202

203
sub display_ip {
204

205
    my $ip = $CONFIG->{display_ip};
joansp's avatar
joansp committed
206

207
    return $ip if $ip;
208
209
}

210
211
sub _init_config {
    my $file = shift;
212
213

    my $connector = shift;
214
    confess "Deprecated connector" if $connector;
215

216
    $CONFIG = YAML::LoadFile($file);
217
218
219

    $LIMIT_PROCESS = $CONFIG->{limit_process} 
        if $CONFIG->{limit_process} && $CONFIG->{limit_process}>1;
220
#    $CONNECTOR = ( $connector or _connect_dbh());
221
222
}

223
sub _create_vm_kvm {
224
    my $self = shift;
225

226
227
228
229
    my $cmd_qemu_img = `which qemu-img`;
    chomp $cmd_qemu_img;

    return(undef,"ERROR: Missing qemu-img") if !$cmd_qemu_img;
230
231

    my $vm_kvm;
232

233
234
    eval { $vm_kvm = Ravada::VM::KVM->new( connector => ( $self->connector or $CONNECTOR )) };
    my $err_kvm = $@;
235
236
237
238

    my ($internal_vm , $storage);
    eval {
        $storage = $vm_kvm->dir_img();
239
        $internal_vm = $vm_kvm->vm;
240
241
    };
    $vm_kvm = undef if $@ || !$internal_vm || !$storage;
Francesc Guasch's avatar
Francesc Guasch committed
242
243
    $err_kvm .= ($@ or '');
    return ($vm_kvm,$err_kvm);
244
245
}

246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
=head2 disconnect_vm

Disconnect all the Virtual Managers connections.

=cut


sub disconnect_vm {
    my $self = shift;
    $self->_disconnect_vm();
}

sub _disconnect_vm{
    my $self = shift;
    return $self->_connect_vm(0);
}

sub _connect_vm {
264
    my $self = shift;
265
266
267
268

    my $connect = shift;
    $connect = 1 if !defined $connect;

269
270
    my @vms;
    eval { @vms = $self->vm };
271
    warn $@ if $@ && $self->warn_error;
272
273
274
275
    return if $@ && $@ =~ /No VMs found/i;
    die $@ if $@;

    return if !scalar @vms;
276
277
    for my $n ( 0 .. $#{$self->vm}) {
        my $vm = $self->vm->[$n];
278
279
280

        if (!$connect) {
            $vm->disconnect();
281
282
        } else {
            $vm->connect();
283
        }
284
285
286
    }
}

287
288
289
290
291
292
sub _create_vm {
    my $self = shift;

    my @vms = ();

    my ($vm_kvm, $err_kvm) = $self->_create_vm_kvm();
293
    warn $err_kvm if $err_kvm && $0 !~ /\.t$/;
294

295
296
    my $err = $err_kvm;

297
298
299
    push @vms,($vm_kvm) if $vm_kvm;

    my $vm_lxc;
300
301
302
303
304
305
    if ($CAN_LXC) {
        eval { $vm_lxc = Ravada::VM::LXC->new( connector => ( $self->connector or $CONNECTOR )) };
        push @vms,($vm_lxc) if $vm_lxc;
        my $err_lxc = $@;
        $err .= "\n$err_lxc" if $err_lxc;
    }
306
    if (!@vms) {
307
        warn "No VMs found: $err\n" if $self->warn_error;
308
309
310
    }
    return \@vms;

311
312
}

313
sub _check_vms {
314
315
    my $self = shift;

316
317
    my @vm;
    eval { @vm = @{$self->vm} };
318
319
320
321
322
323
324
325
326
327
    for my $n ( 0 .. $#vm ) {
        if ($vm[$n] && ref $vm[$n] =~ /KVM/i) {
            if (!$vm[$n]->is_alive) {
                warn "$vm[$n] dead" if $DEBUG;
                $vm[$n] = $self->_create_vm_kvm();
            }
        }
    }
}

Francesc Guasch's avatar
Francesc Guasch committed
328
329
330
331
=head2 create_domain

Creates a new domain based on an ISO image or another domain.

joansp's avatar
joansp committed
332
  my $domain = $ravada->create_domain(
Francesc Guasch's avatar
Francesc Guasch committed
333
334
335
336
337
         name => $name
    , id_iso => 1
  );


joansp's avatar
joansp committed
338
  my $domain = $ravada->create_domain(
Francesc Guasch's avatar
Francesc Guasch committed
339
340
341
342
343
344
345
346
         name => $name
    , id_base => 3
  );


=cut


347
sub create_domain {
348
349
    my $self = shift;

350
351
    my %args = @_;

352
353
354
    croak "Argument id_owner required "
        if !$args{id_owner};

355
356
    my $vm_name = $args{vm};
    delete $args{vm};
357

358
    my $request = ( $args{request} or undef);
Francesc Guasch's avatar
Francesc Guasch committed
359

360
    my $vm;
361
362
363
364
    if ($vm_name) {
        $vm = $self->search_vm($vm_name);
        confess "ERROR: vm $vm_name not found"  if !$vm;
    }
365
    $vm = $self->vm->[0]               if !$vm;
366

367
368
    confess "No vm found"   if !$vm;

369
370
    carp "WARNING: no VM defined, we will use ".$vm->name
        if !$vm_name;
Francesc Guasch's avatar
Francesc Guasch committed
371

372
    confess "I can't find any vm ".Dumper($self->vm) if !$vm;
Francesc Guasch's avatar
Francesc Guasch committed
373

374
    return $vm->create_domain(@_);
375
376
}

Francesc Guasch's avatar
Francesc Guasch committed
377
378
379
380
381
382
383
384
=head2 remove_domain

Removes a domain

  $ravada->remove_domain($name);

=cut

385
386
sub remove_domain {
    my $self = shift;
387
388
    my %arg = @_;

389
    confess "Argument name required "
390
391
        if !$arg{name};

392
393
    confess "Argument uid required "
        if !$arg{uid};
394
395
396
397

    lock_hash(%arg);

    my $domain = $self->search_domain($arg{name}, 1)
398
        or die "ERROR: I can't find domain '$arg{name}', maybe already removed.";
399

400
401
    my $user = Ravada::Auth::SQL->search_by_id( $arg{uid});
    $domain->remove( $user);
402
403
}

Francesc Guasch's avatar
Francesc Guasch committed
404
405
406
407
408
409
=head2 search_domain

  my $domain = $ravada->search_domain($name);

=cut

410
411
412
sub search_domain {
    my $self = shift;
    my $name = shift;
413
    my $import = shift;
414

415
416
417
418
419
420
421
422
423
424
425
426
    my $vm = $self->search_vm('Void');
    warn "No Void VM" if !$vm;
    return if !$vm;

    my $domain = $vm->search_domain($name, $import);
    return $domain if $domain;

    my @vms;
    eval { @vms = $self->vm };
    return if $@ && $@ =~ /No VMs found/i;
    die $@ if $@;

427
    for my $vm (@{$self->vm}) {
Francesc Guasch's avatar
Francesc Guasch committed
428
        my $domain = $vm->search_domain($name, $import);
429
        next if !$domain;
430
        next if !$domain->_select_domain_db && !$import;
431
432
433
        my $id;
        eval { $id = $domain->id };
        # TODO import the domain in the database with an _insert_db or something
Francesc Guasch's avatar
Francesc Guasch committed
434
        warn $@ if $@   && $DEBUG;
435
        return $domain if $id || $import;
436
    }
437
438


439
    return;
440
}
441

Francesc Guasch's avatar
Francesc Guasch committed
442
=head2 search_domain_by_id
Francesc Guasch's avatar
Francesc Guasch committed
443

Francesc Guasch's avatar
Francesc Guasch committed
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
  my $domain = $ravada->search_domain_by_id($id);

=cut

sub search_domain_by_id {
    my $self = shift;
    my $id = shift  or confess "ERROR: missing argument id";

    my $sth = $CONNECTOR->dbh->prepare("SELECT name FROM domains WHERE id=?");
    $sth->execute($id);
    my ($name) = $sth->fetchrow;
    confess "Unknown domain id=$id" if !$name;

    return $self->search_domain($name);
}
Francesc Guasch's avatar
Francesc Guasch committed
459

460
461
=head2 list_domains

Francesc Guasch's avatar
Francesc Guasch committed
462
List all created domains
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478

  my @list = $ravada->list_domains();

=cut

sub list_domains {
    my $self = shift;
    my @domains;
    for my $vm (@{$self->vm}) {
        for my $domain ($vm->list_domains) {
            push @domains,($domain);
        }
    }
    return @domains;
}

479
480
481
482
483
484
485
486
487
488
489
490
491
=head2 list_domains_data

List all domains in raw format. Return a list of id => { name , id , is_active , is_base }

   my $list = $ravada->list_domains_data();

   $c->render(json => $list);

=cut

sub list_domains_data {
    my $self = shift;
    my @domains;
492
493
494
495
496
497
    my $sth = $CONNECTOR->dbh->prepare(
        "SELECT * FROM domains ORDER BY name"
    );
    $sth->execute;
    while (my $row = $sth->fetchrow_hashref) {
        push @domains,($row);
498
    }
499
    $sth->finish;
500
    return \@domains;
501
502
}

503
504
505
506
507
508
509
# sub list_domains_data {
#     my $self = shift;
#     my @domains;
#     for my $domain ($self->list_domains()) {
#         eval { $domain->id };
#         warn $@ if $@;
#         next if $@;
joansp's avatar
joansp committed
510
#         push @domains, {                id => $domain->id
511
512
513
#                                     , name => $domain->name
#                                   ,is_base => $domain->is_base
#                                 ,is_active => $domain->is_active
joansp's avatar
joansp committed
514

515
516
517
518
519
#                            }
#     }
#     return \@domains;
# }

520

Francesc Guasch's avatar
Francesc Guasch committed
521
522
523
524
525
526
527
528
529
530
531
532
533
534
=head2 list_bases

List all base domains

  my @list = $ravada->list_domains();


=cut

sub list_bases {
    my $self = shift;
    my @domains;
    for my $vm (@{$self->vm}) {
        for my $domain ($vm->list_domains) {
535
536
537
            eval { $domain->id };
            warn $@ if $@;
            next    if $@;
Francesc Guasch's avatar
Francesc Guasch committed
538
539
540
541
542
543
            push @domains,($domain) if $domain->is_base;
        }
    }
    return @domains;
}

544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
=head2 list_bases_data

List information about the bases

=cut

sub list_bases_data {
    my $self = shift;
    my @data;
    for ($self->list_bases ) {
        push @data,{ id => $_->id , name => $_->name };
    }
    return \@data;
}

Francesc Guasch's avatar
Francesc Guasch committed
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
=head2 list_images

List all ISO images

=cut

sub list_images {
    my $self = shift;
    my @domains;
    my $sth = $CONNECTOR->dbh->prepare(
        "SELECT * FROM iso_images ORDER BY name"
    );
    $sth->execute;
    while (my $row = $sth->fetchrow_hashref) {
        push @domains,($row);
    }
    $sth->finish;
    return @domains;
}

579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
=head2 list_images_data

List information about the images

=cut

sub list_images_data {
    my $self = shift;
    my @data;
    for ($self->list_images ) {
        push @data,{ id => $_->{id} , name => $_->{name} };
    }
    return \@data;
}

Francesc Guasch's avatar
Francesc Guasch committed
594

595
596
597
=pod

sub _list_images_lxc {
fv3rdugo's avatar
fv3rdugo committed
598
599
600
    my $self = shift;
    my @domains;
    my $sth = $CONNECTOR->dbh->prepare(
601
        "SELECT * FROM lxc_templates ORDER BY name"
fv3rdugo's avatar
fv3rdugo committed
602
603
604
605
606
607
608
609
610
    );
    $sth->execute;
    while (my $row = $sth->fetchrow_hashref) {
        push @domains,($row);
    }
    $sth->finish;
    return @domains;
}

611
sub _list_images_data_lxc {
fv3rdugo's avatar
fv3rdugo committed
612
613
614
615
616
617
618
619
    my $self = shift;
    my @data;
    for ($self->list_images_lxc ) {
        push @data,{ id => $_->{id} , name => $_->{name} };
    }
    return \@data;
}

620
=cut
fv3rdugo's avatar
fv3rdugo committed
621

Francesc Guasch's avatar
Francesc Guasch committed
622
623
624
625
=head2 remove_volume

  $ravada->remove_volume($file);

Francesc Guasch's avatar
Francesc Guasch committed
626

Francesc Guasch's avatar
Francesc Guasch committed
627
628
=cut

629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
sub remove_volume {
    my $self = shift;

    my $file = shift;
    my ($name) = $file =~ m{.*/(.*)};

    my $removed = 0;
    for my $vm (@{$self->vm}) {
        my $vol = $vm->search_volume($name);
        next if !$vol;

        $vol->delete();
        $removed++;
    }
    if (!$removed && -e $file ) {
        warn "volume $file not found. removing file $file.\n";
        unlink $file or die "$! $file";
    }

}
649

650
651
652
653
654
655
656
657
658
=head2 clean_killed_requests

Before processing requests, old killed requests must be cleaned.

=cut

sub clean_killed_requests {
    my $self = shift;
    my $sth = $CONNECTOR->dbh->prepare("SELECT id FROM requests "
659
        ." WHERE status <> 'done' "
660
661
662
663
664
665
666
667
668
    );
    $sth->execute;
    while (my ($id) = $sth->fetchrow) {
        my $req = Ravada::Request->open($id);
        $req->status("done","Killed before completion");
    }

}

Francesc Guasch's avatar
Francesc Guasch committed
669
670
671
672
673
674
675
676
=head2 process_requests

This is run in the ravada backend. It processes the commands requested by the fronted

  $ravada->process_requests();

=cut

677
678
sub process_requests {
    my $self = shift;
679
    my $debug = shift;
680
    my $dont_fork = shift;
681
682
    my $long_commands = (shift or 0);
    my $short_commands = (shift or 0);
683

684
685
    $self->_wait_pids_nohang();

686
    my $sth = $CONNECTOR->dbh->prepare("SELECT id,id_domain FROM requests "
687
688
689
        ." WHERE "
        ."    ( status='requested' OR status like 'retry %' OR status='waiting')"
        ."   AND ( at_time IS NULL  OR at_time = 0 OR at_time<=?) "
690
691
        ." ORDER BY date_req"
    );
692
693
694
695
696
697
698
    $sth->execute(time);

    my $debug_type = '';
    $debug_type = 'long' if $long_commands;
    $debug_type = 'short' if $short_commands || !$long_commands;
    $debug_type = 'all' if $long_commands && $short_commands;

699
700
    while (my ($id_request,$id_domain)= $sth->fetchrow) {
        my $req = Ravada::Request->open($id_request);
701
702
703
704
705
706
707
708
709

        if ( ($long_commands && 
                (!$short_commands && !$LONG_COMMAND{$req->command}))
            ||(!$long_commands && $LONG_COMMAND{$req->command})
        ) {
            warn "[$debug_type,$long_commands,$short_commands] $$ skipping request "
                .$req->command  if $DEBUG;
            next;
        }
710
711
        next if $req->command !~ /shutdown/i
            && $self->_domain_working($id_domain, $id_request);
712

713
714
        warn "[$debug_type] $$ executing request ".$req->id." ".$req->status()." "
            .$req->command
715
            ." ".Dumper($req->args) if $DEBUG || $debug;
Francesc Guasch's avatar
Francesc Guasch committed
716
717
718

        my ($n_retry) = $req->status() =~ /retry (\d+)/;
        $n_retry = 0 if !$n_retry;
719
720
721
        my $err = $self->_execute($req, $dont_fork);
        $req->error($err)   if $err;
        if ($err && $err =~ /libvirt error code: 38/) {
Francesc Guasch's avatar
Francesc Guasch committed
722
            if ( $n_retry < 3) {
723
                warn $req->id." ".$req->command." to retry" if $DEBUG;
joansp's avatar
joansp committed
724
                $req->status("retry ".++$n_retry)
725
            }
726
        }
727
728
729
        next if !$DEBUG && !$debug;

        sleep 1;
730
        warn "req ".$req->id." , command: ".$req->command." , status: ".$req->status()
731
            ." , error: '".($req->error or 'NONE')."'\n"  if $DEBUG;
Francesc Guasch's avatar
Francesc Guasch committed
732

733
734
    }
    $sth->finish;
735
736
737

}

Francesc Guasch's avatar
Francesc Guasch committed
738
=head2 process_long_requests
739
740
741
742
743
744
745
746
747
748
749

Process requests that take log time. It will fork on each one

=cut

sub process_long_requests {
    my $self = shift;
    my ($debug,$dont_fork) = @_;

    $self->_disconnect_vm();
    return $self->process_requests($debug, $dont_fork, 1);
750
751
}

752
753
754
755
756
757
758
759
760
761
762
763
764
=head2 process_all_requests

Process all the requests, long and short

=cut

sub process_all_requests {

    my $self = shift;
    my ($debug,$dont_fork) = @_;

    $self->process_requests($debug, $dont_fork,1,1);

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
sub _domain_working {
    my $self = shift;
    my ($id_domain, $id_request) = @_;

    confess "Missing id_request" if !defined$id_request;

    if (!$id_domain) {
        my $req = Ravada::Request->open($id_request);
        $id_domain = $req->defined_arg('id_base');
        if (!$id_domain) {
            my $domain_name = $req->defined_arg('name');
            return if !$domain_name;
            my $domain = $self->search_domain($domain_name) or return;
            $id_domain = $domain->id;
            if (!$id_domain) {
                warn Dumper($req);
                return;
            }
        }
    }
    my $sth = $CONNECTOR->dbh->prepare("SELECT id, status FROM requests "
        ." WHERE id <> ? AND id_domain=? AND (status <> 'requested' AND status <> 'done')");
    $sth->execute($id_request, $id_domain);
    my ($id, $status) = $sth->fetchrow;
#    warn "CHECKING DOMAIN WORKING "
#        ."[$id_request] id_domain $id_domain working in request ".($id or '<NULL>')
#            ." status: ".($status or '<UNDEF>');
    return $id;
}

797
798
799
800
801
802
803
sub _process_all_requests_dont_fork {
    my $self = shift;
    my $debug = shift;

    return $self->process_requests($debug,1, 1, 1);
}

804
805
sub _process_requests_dont_fork {
    my $self = shift;
806
    my $debug = shift;
807
    return $self->process_requests($debug, 1);
808
}
Francesc Guasch's avatar
Francesc Guasch committed
809

810
811
812
813
814
815
816
817
=head2 list_vm_types

Returnsa list ofthe types of Virtual Machines available on this system

=cut

sub list_vm_types {
    my $self = shift;
joansp's avatar
joansp committed
818

819
820
821
822
823
    my %type;
    for my $vm (@{$self->vm}) {
            my ($name) = ref($vm) =~ /.*::(.*)/;
            $type{$name}++;
    }
824
    return keys %type;
825
826
}

827
828
829
sub _execute {
    my $self = shift;
    my $request = shift;
830
    my $dont_fork = shift;
831

Francesc Guasch's avatar
Francesc Guasch committed
832
833
    my $sub = $self->_req_method($request->command);

834
835
    confess "Unknown command ".$request->command
            if !$sub;
Francesc Guasch's avatar
Francesc Guasch committed
836

837
    if ($dont_fork || !$CAN_FORK || !$LONG_COMMAND{$request->command}) {
Francesc Guasch's avatar
Francesc Guasch committed
838

839
840
841
        eval { $sub->($self,$request) };
        my $err = ($@ or '');
        $request->error($err);
842
        $request->status('done') if $request->status() ne 'done';
843
844
        return $err;
    }
Francesc Guasch's avatar
Francesc Guasch committed
845

846
847
848
    $self->_wait_pids_nohang();
    return if $self->_wait_children($request);

849
    $request->status('working');
850
851
    my $pid = fork();
    die "I can't fork" if !defined $pid;
852
853
854
855
856
    if ( $pid == 0 ) {
        $self->_do_execute_command($sub, $request) 
    } else {
        $self->_add_pid($pid, $request->id);
    }
857
#    $self->_connect_vm_kvm();
858
    return '';
Francesc Guasch's avatar
Francesc Guasch committed
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
sub _do_execute_command {
    my $self = shift;
    my ($sub, $request) = @_;

#    if ($DEBUG ) {
#        mkdir 'log' if ! -e 'log';
#        open my $f_out ,'>', "log/fork_$$.out";
#        open my $f_err ,'>', "log/fork_$$.err";
#        $| = 1;
#        local *STDOUT = $f_out;
#        local *STDERR = $f_err;
#    }

    eval {
        $self->_connect_vm();
        $sub->($self,$request);
        $self->_disconnect_vm();
    };
    my $err = ( $@ or '');
    $request->error($err);
    $request->status('done') if $request->status() ne 'done';
    exit;

}

886
887
888
889
890
891
892
sub _cmd_domdisplay {
    my $self = shift;
    my $request = shift;

    my $name = $request->args('name');
    confess "Unknown name for request ".Dumper($request)  if!$name;
    my $domain = $self->search_domain($request->args->{name});
893
    my $user = Ravada::Auth::SQL->search_by_id( $request->args->{uid});
894
    $request->error('');
895
    my $display = $domain->display($user);
896
897
    $request->result({display => $display});

898
899
}

900
901
902
903
904
905
sub _cmd_screenshot {
    my $self = shift;
    my $request = shift;

    my $id_domain = $request->args('id_domain');
    my $domain = $self->search_domain_by_id($id_domain);
906
    my $bytes = 0;
907
    if (!$domain->can_screenshot) {
908
        die "I can't take a screenshot of the domain ".$domain->name;
909
    } else {
910
911
        $bytes = $domain->screenshot($request->args('filename'));
        $bytes = $domain->screenshot($request->args('filename'))    if !$bytes;
912
    }
913
    $request->error("No data received") if !$bytes;
914
915
916
}


917
sub _cmd_create{
Francesc Guasch's avatar
Francesc Guasch committed
918
919
920
    my $self = shift;
    my $request = shift;

921
    $request->status('creating domain');
922
    warn "$$ creating domain"   if $DEBUG;
923
    my $domain;
924

925
    $domain = $self->create_domain(%{$request->args},request => $request);
926

927
    my $msg = '';
928

929
    if ($domain) {
930
       $msg = 'Domain '
931
932
            ."<a href=\"/machine/view/".$domain->id.".html\">"
            .$request->args('name')."</a>"
Francesc Guasch's avatar
Francesc Guasch committed
933
            ." created."
934
935
936
937
        ;
    }

    $request->status('done',$msg);
Francesc Guasch's avatar
Francesc Guasch committed
938
939
940

}

941
942
943
944
945
sub _wait_children {
    my $self = shift;
    my $req = shift or confess "Missing request";

    my $try = 0;
946
    for ( 1 .. $SECONDS_WAIT_CHILDREN ) {
947
948
        my $n_pids = scalar keys %{$self->{pids}};

949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
        my $msg;
        if ($HUGE_COMMAND{$req->command}) {
            if ( $n_pids < $LIMIT_HUGE_PROCESS) {
                $msg = $req->id." ".$req->command
                ." waiting for processes to finish $n_pids"
                ." of $LIMIT_HUGE_PROCESS ";
                warn $msg if $DEBUG;
                return;
            }
        } elsif ( $n_pids < $LIMIT_PROCESS) {
            $msg = $req->id." ".$req->command
                ." waiting for processes to finish $n_pids"
                ." of $LIMIT_PROCESS ";
            warn $msg if $DEBUG;
            return;
        }
965
966
967
        $self->_wait_pids_nohang();
        sleep 1;

968
969
970
        next if $try++;

        $req->error($msg);
971
        $req->status('waiting') if $req->status() !~ 'waiting';
972
    }
973
    return scalar keys %{$self->{pids}};
974
975
}

976
977
978
979
sub _wait_pids_nohang {
    my $self = shift;
    return if !keys %{$self->{pids}};

Francesc Guasch's avatar
Francesc Guasch committed
980
981
982
983
    for my $pid ( keys %{$self->{pids}}) {
        my $kid = waitpid($pid , WNOHANG);
        next if !$kid || $kid == -1;
        $self->_set_req_done($kid);
984
        $self->_delete_pid($kid);
Francesc Guasch's avatar
Francesc Guasch committed
985
    }
986
987
988
989
990
991
992
993
994
995
996
997

}

sub _set_req_done {
    my $self = shift;
    my $pid = shift;

    my $id_request = $self->{pids}->{$pid};
    return if !$id_request;

    my $req = Ravada::Request->open($id_request);
    $req->status('done')    if $req->status =~ /working/i;
998
999
}

Francesc Guasch's avatar
Francesc Guasch committed
1000
1001
1002
1003
sub _wait_pids {
    my $self = shift;
    my $request = shift;

1004
1005
    $request->status('waiting for other tasks')
        if $request && $request->status !~ /waiting/i;
Francesc Guasch's avatar
Francesc Guasch committed
1006

Francesc Guasch's avatar
Francesc Guasch committed
1007
    for my $pid ( keys %{$self->{pids}}) {
1008
1009
        $request->status("waiting for pid $pid")
            if $request && $request->status !~ /waiting/i;
1010
1011

#        warn "Checking for pid '$pid' created at ".localtime($self->{pids}->{$pid});
Francesc Guasch's avatar
Francesc Guasch committed
1012
        my $kid = waitpid($pid,0);
1013
#        warn "Found $kid";
1014
1015
        $self->_set_req_done($pid);

1016
        $self->_delete_pid($kid);
Francesc Guasch's avatar
Francesc Guasch committed
1017
1018
1019
1020
1021
1022
1023
        return if $kid  == $pid;
    }
}

sub _add_pid {
    my $self = shift;
    my $pid = shift;
1024
    my $id_req = shift;
Francesc Guasch's avatar
Francesc Guasch committed
1025

1026
    $self->{pids}->{$pid} = $id_req;
1027
1028
1029
1030
1031
1032
1033
1034

}

sub _delete_pid {
    my $self = shift;
    my $pid = shift;

    delete $self->{pids}->{$pid};
Francesc Guasch's avatar
Francesc Guasch committed
1035
1036
}

1037
sub _cmd_remove {
Francesc Guasch's avatar
Francesc Guasch committed
1038
1039
1040
    my $self = shift;
    my $request = shift;

1041
1042
1043
1044
    confess "Unknown user id ".$request->args->{uid}
        if !defined $request->args->{uid};

    $self->remove_domain(name => $request->args('name'), uid => $request->args('uid'));
Francesc Guasch's avatar
Francesc Guasch committed
1045

1046
}
Francesc Guasch's avatar
Francesc Guasch committed
1047

1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
sub _cmd_pause {
    my $self = shift;
    my $request = shift;

    my $name = $request->args('name');
    my $domain = $self->search_domain($name);
    die "Unknown domain '$name'" if !$domain;

    my $uid = $request->args('uid');
    my $user = Ravada::Auth::SQL->search_by_id($uid);

    $domain->pause($user);

    $request->status('done');

}

sub _cmd_resume {
    my $self = shift;
    my $request = shift;

    my $name = $request->args('name');
    my $domain = $self->search_domain($name);
    die "Unknown domain '$name'" if !$domain;

    my $uid = $request->args('uid');
    my $user = Ravada::Auth::SQL->search_by_id($uid);

1076
1077
    $domain->resume(
        remote_ip => $request->args('remote_ip')
1078
        ,user => $user
1079
    );
1080
1081
1082
1083
1084
1085

    $request->status('done');

}


1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
sub _cmd_open_iptables {
    my $self = shift;
    my $request = shift;

    my $uid = $request->args('uid');
    my $user = Ravada::Auth::SQL->search_by_id($uid);

    my $domain = $self->search_domain_by_id($request->args('id_domain'));
    die "Unknown domain" if !$domain;

    $domain->open_iptables(
        remote_ip => $request->args('remote_ip')
        ,uid => $user->id
    );
}

Francesc Guasch's avatar
Francesc Guasch committed
1102
1103
1104
1105
1106
sub _cmd_start {
    my $self = shift;
    my $request = shift;

    my $name = $request->args('name');
1107

1108
1109
    my $domain = $self->search_domain($name);
    die "Unknown domain '$name'" if !$domain;
1110
1111
1112
1113

    my $uid = $request->args('uid');
    my $user = Ravada::Auth::SQL->search_by_id($uid);

1114
    $domain->start(user => $user, remote_ip => $request->args('remote_ip'));
1115
1116
1117
    my $msg = 'Domain '
            ."<a href=\"/machine/view/".$domain->id.".html\">"
            .$request->args('name')."</a>"
Francesc Guasch's avatar
Francesc Guasch committed
1118
            ." started"
1119
1120
        ;
    $request->status('done', $msg);
Francesc Guasch's avatar
Francesc Guasch committed
1121
1122
1123

}

Francesc Guasch's avatar
Francesc Guasch committed
1124
1125
1126
1127
sub _cmd_prepare_base {
    my $self = shift;
    my $request = shift;

Francesc Guasch's avatar
Francesc Guasch committed
1128
    my $id_domain = $request->id_domain   or confess "Missing request id_domain";
1129
1130
1131
1132
    my $uid = $request->args('uid')     or confess "Missing argument uid";

    my $user = Ravada::Auth::SQL->search_by_id( $uid);

Francesc Guasch's avatar
Francesc Guasch committed
1133
    my $domain = $self->search_domain_by_id($id_domain);
1134

Francesc Guasch's avatar
Francesc Guasch committed
1135
    die "Unknown domain id '$id_domain'\n" if !$domain;
1136
1137

    $domain->prepare_base($user);
Francesc Guasch's avatar
Francesc Guasch committed
1138
1139
1140

}

1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
sub _cmd_remove_base {
    my $self = shift;
    my $request = shift;

    my $id_domain = $request->id_domain or confess "Missing request id_domain";
    my $uid = $request->args('uid')     or confess "Missing argument uid";

    my $user = Ravada::Auth::SQL->search_by_id( $uid);

    my $domain = $self->search_domain_by_id($id_domain);

    die "Unknown domain id '$id_domain'\n" if !$domain;

1154
1155
    $domain->_vm->disconnect();
    $self->_disconnect_vm();
1156
1157
1158
1159
1160
    $domain->remove_base($user);

}


1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
sub _cmd_hybernate {
    my $self = shift;
    my $request = shift;

    my $uid = $request->args('uid') or confess "Missing argument uid";
    my $id_domain = $request->id_domain or confess "Missing request id_domain";

    my $user = Ravada::Auth::SQL->search_by_id( $uid);
    my $domain = $self->search_domain_by_id($id_domain);

    die "Unknown domain id '$id_domain'\n" if !$domain;

    $domain->hybernate($user);

}

1177
1178
1179
1180
sub _cmd_download {
    my $self = shift;
    my $request = shift;

1181
1182
1183
    my $id_iso = $request->args('id_iso')
        or confess "Missing argument id_iso";

Francesc Guasch's avatar
Francesc Guasch committed
1184
1185
    my $vm = Ravada::VM->open($request->args('id_vm'));

1186
1187
    my $delay = $request->defined_arg('delay');
    sleep $delay if $delay;
1188

Francesc Guasch's avatar
Francesc Guasch committed
1189
    my $iso = $vm->_search_iso($id_iso);
Francesc Guasch's avatar
Francesc Guasch committed
1190
1191
1192
1193
    if ($iso->{device} && -e $iso->{device}) {
        $request->status('done',"$iso->{device} already downloaded");
        return;
    }
Francesc Guasch's avatar
Francesc Guasch committed
1194
    my $device_cdrom = $vm->_iso_name($iso, $request);
1195
1196
}

Francesc Guasch's avatar
Francesc Guasch committed
1197
1198
1199
1200
sub _cmd_shutdown {
    my $self = shift;
    my $request = shift;

1201
    my $uid = $request->args('uid');
Francesc Guasch's avatar
Francesc Guasch committed
1202
    my $name = $request->args('name');
1203
    my $timeout = ($request->args('timeout') or 60);
1204

1205
    my $domain;
1206
1207
1208
    $domain = $self->search_domain($name);
    die "Unknown domain '$name'\n" if !$domain;

1209
1210
    my $user = Ravada::Auth::SQL->search_by_id( $uid);

1211
1212
    $domain->shutdown(timeout => $timeout, name => $name, user => $user
                    , request => $request);
Francesc Guasch's avatar
Francesc Guasch committed
1213
1214
1215

}