Request.pm 30.8 KB
Newer Older
1
2
3
4
5
package Ravada::Request;

use strict;
use warnings;

6
7
8
9
10
11
=head1 NAME

Ravada::Request - Requests library for Ravada

=cut

12
13
use Carp qw(confess);
use Data::Dumper;
14
use Hash::Util qw(lock_hash);
15
16
use JSON::XS;
use Hash::Util;
Francesc Guasch's avatar
Francesc Guasch committed
17
use Time::Piece;
18
19
20
21
22
use Ravada;
use Ravada::Front;

use vars qw($AUTOLOAD);

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

26
27
28
29
30
31
=pod

Request a command to the ravada backend

=cut

Francesc Guasch's avatar
Francesc Guasch committed
32
my $COUNT = 0;
Francesc Guasch's avatar
Francesc Guasch committed
33
our %FIELD = map { $_ => 1 } qw(error output);
34
35
our %FIELD_RO = map { $_ => 1 } qw(id name);

36
our $args_manage = { name => 1 , uid => 1, id_domain => 1 };
37
38
39
40
41
42
our $args_prepare = { id_domain => 1 , uid => 1 };
our $args_remove_base = { id_domain => 1 , uid => 1 };
our $args_manage_iptables = {uid => 1, id_domain => 1, remote_ip => 1};

our %VALID_ARG = (
    create_domain => {
frankiejol's avatar
frankiejol committed
43
              vm => 2
44
45
           ,name => 1
           ,swap => 2
Francesc Guasch's avatar
Francesc Guasch committed
46
         ,id_iso => 2
47
         ,iso_file => 2
48
         ,iso_name => 2
Francesc Guasch's avatar
Francesc Guasch committed
49
        ,id_base => 2
50
       ,id_owner => 1
Francesc Guasch's avatar
Francesc Guasch committed
51
    ,id_template => 2
52
53
         ,memory => 2
           ,disk => 2
Francesc Guasch's avatar
Francesc Guasch committed
54
           #        ,network => 2
55
56
      ,remote_ip => 2
          ,start => 2
57
58
59
60
61
62
63
    }
    ,open_iptables => $args_manage_iptables
      ,remove_base => $args_remove_base
     ,prepare_base => $args_prepare
     ,pause_domain => $args_manage
    ,resume_domain => {%$args_manage, remote_ip => 1 }
    ,remove_domain => $args_manage
64
65
66
    ,shutdown => {
        alias => 'shutdown_domain'
        ,args => { name => 2, id_domain => 1, uid => 1, timeout => 2, at => 2
67
                       , id_vm => 2 }
68
    },
69
    ,force_shutdown_domain => { id_domain => 1, uid => 1, at => 2, id_vm => 2 }
70
    ,screenshot_domain => { id_domain => 1, filename => 2 }
Francesc Guasch's avatar
Francesc Guasch committed
71
    ,domain_autostart => { id_domain => 1 , uid => 1, value => 2 }
72
    ,copy_screenshot => { id_domain => 1, filename => 2 }
Francesc Guasch's avatar
Francesc Guasch committed
73
    ,start_domain => {%$args_manage, remote_ip => 2, name => 2, id_domain => 2 }
74
    ,start_clones => { id_domain => 1, uid => 1, remote_ip => 1 }
75
    ,rename_domain => { uid => 1, name => 1, id_domain => 1}
76
    ,dettach => { uid => 1, id_domain => 1 }
77
    ,set_driver => {uid => 1, id_domain => 1, id_option => 1}
78
    ,hybernate=> {uid => 1, id_domain => 1}
Francesc Guasch's avatar
Francesc Guasch committed
79
    ,download => {uid => 2, id_iso => 1, id_vm => 2, verbose => 2, delay => 2, test => 2}
80
    ,refresh_storage => { id_vm => 2 }
81
    ,set_base_vm=> {uid => 1, id_vm=> 1, id_domain => 1, value => 2 }
82
    ,cleanup => { }
Francesc Guasch's avatar
Francesc Guasch committed
83
84
85
86
    ,clone => { uid => 1, id_domain => 1, name => 2, memory => 2, number => 2, is_pool => 2
                ,start => 2, no_pool => 2
                ,remote_ip => 2
    }
Joel Alarcón's avatar
Joel Alarcón committed
87
    ,change_owner => {uid => 1, id_domain => 1}
Francesc Guasch's avatar
Francesc Guasch committed
88
    ,add_hardware => {uid => 1, id_domain => 1, name => 1, number => 2, data => 2 }
89
    ,remove_hardware => {uid => 1, id_domain => 1, name => 1, index => 1}
Francesc Guasch's avatar
Francesc Guasch committed
90
    ,change_hardware => {uid => 1, id_domain => 1, hardware => 1, index => 1, data => 1 }
JanFontanet's avatar
JanFontanet committed
91
    ,change_max_memory => {uid => 1, id_domain => 1, ram => 1}
92
    ,change_curr_memory => {uid => 1, id_domain => 1, ram => 1}
93
    ,enforce_limits => { timeout => 2, _force => 2 }
Francesc Guasch's avatar
Francesc Guasch committed
94
    ,refresh_machine => { id_domain => 1, uid => 1 }
95
    ,rebase_volumes => { uid => 1, id_base => 1, id_domain => 1 }
Francesc Guasch's avatar
Francesc Guasch committed
96
97
98
99
    # ports
    ,expose => { uid => 1, id_domain => 1, port => 1, name => 2, restricted => 2, id_port => 2}
    ,remove_expose => { uid => 1, id_domain => 1, port => 1}
    ,open_exposed_ports => {uid => 1, id_domain => 1 }
Francesc Guasch's avatar
Francesc Guasch committed
100
    # Virtual Managers or Nodes
Francesc Guasch's avatar
Francesc Guasch committed
101
    ,refresh_vms => { _force => 2, timeout_shutdown => 2 }
Francesc Guasch's avatar
Francesc Guasch committed
102
103
104
105
106

    ,shutdown_node => { id_node => 1, at => 2 }
    ,start_node => { id_node => 1, at => 2 }
    ,connect_node => { backend => 2, hostname => 2, id_node =>2, timeout => 2 }

Francesc Guasch's avatar
Francesc Guasch committed
107
    #users
108
    ,post_login => { user => 1, locale => 2 }
Francesc Guasch's avatar
Francesc Guasch committed
109

Francesc Guasch's avatar
Francesc Guasch committed
110
111
112
    #networks
    ,list_network_interfaces => { uid => 1, vm_type => 1, type => 2 }

Fernando Verdugo's avatar
Fernando Verdugo committed
113
    #isos
114
    ,list_isos => { vm_type => 2 }
Fernando Verdugo's avatar
Fernando Verdugo committed
115

Francesc Guasch's avatar
Francesc Guasch committed
116
    ,manage_pools => { uid => 2, id_domain => 2 }
117
    ,ping_backend => { uid => 2 }
118
119
120
);

our %CMD_SEND_MESSAGE = map { $_ => 1 }
121
    qw( create start shutdown prepare_base remove remove_base rename_domain screenshot download
122
            set_base_vm remove_base_vm
Francesc Guasch's avatar
Francesc Guasch committed
123
            domain_autostart hibernate hybernate
Francesc Guasch's avatar
Francesc Guasch committed
124
            change_owner
Francesc Guasch's avatar
Francesc Guasch committed
125
            change_max_memory change_curr_memory
Francesc Guasch's avatar
Francesc Guasch committed
126
            add_hardware remove_hardware set_driver change_hardware
127
            set_base_vm
Francesc Guasch's avatar
Francesc Guasch committed
128
            shutdown_node start_node
129
    );
130

Francesc Guasch's avatar
Francesc Guasch committed
131
132
our $TIMEOUT_SHUTDOWN = 120;

133
134
our $CONNECTOR;

135
our %COMMAND = (
Francesc Guasch's avatar
Francesc Guasch committed
136
137
138
139
    long => {
        limit => 4
        ,priority => 4
    } #default
140
141
142
    ,huge => {
        limit => 1
        ,commands => ['download']
Francesc Guasch's avatar
Francesc Guasch committed
143
        ,priority => 5
144
    }
145
146
    ,disk => {
        limit => 1
147
148
        ,commands => ['prepare_base','remove_base','set_base_vm','rebase_volumes'
                    , 'manage_pools']
149
150
        ,priority => 6
    }
Francesc Guasch's avatar
Francesc Guasch committed
151
    ,important=> {
152
        limit => 20
Francesc Guasch's avatar
Francesc Guasch committed
153
        ,priority => 1
Fernando Verdugo's avatar
Fernando Verdugo committed
154
        ,commands => ['clone','start','start_clones','create','open_iptables','list_network_interfaces','list_isos']
155
    }
Francesc Guasch's avatar
Francesc Guasch committed
156
157
158
159
160
    ,secondary => {
        limit => 50
        ,priority => 2
        ,commands => ['shutdown','shutdown_now']
    }
161
162
163
);
lock_hash %COMMAND;

164
165
166
167
168
169
170
171
172
173
sub _init_connector {
    $CONNECTOR = \$Ravada::CONNECTOR;
    $CONNECTOR = \$Ravada::Front::CONNECTOR   if !$$CONNECTOR;

}

=head2 BUILD

    Internal object builder, do not call

174
=cut
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212

sub BUILD {
    _init_connector();
}

sub _request {
    my $proto = shift;
    my $class=ref($proto) || $proto;

    my $self = {};
    bless ($self, $class);
    return $self;
}

=head2 open

Opens the information of a previous request by id

  my $req = Ravada::Request->open($id);

=cut

sub open {
    my $proto = shift;
    my $class = ref($proto) || $proto;

    my $id = shift or confess "Missing request id";

    _init_connector()   if !$CONNECTOR || !$$CONNECTOR;

    my $sth = $$CONNECTOR->dbh->prepare("SELECT * FROM requests "
        ." WHERE id=?");
    $sth->execute($id);
    my $row = $sth->fetchrow_hashref;

    confess "I can't find id=$id " if !defined $row;
    $sth->finish;

213
214
    my $args = {};
    $args = decode_json($row->{args}) if $row->{args};
215
216
217
218

    $row->{args} = $args;

    bless ($row, $class);
Francesc Guasch's avatar
Francesc Guasch committed
219
220
    $row->{priority} = $row->_set_priority();

221
222
223
    return $row;
}

224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
=head2 info

Returns information of the request

=cut

sub info {
    my $self = shift;
    my $user = shift;
    confess "USER ".$user->name." not authorized"
        unless $user->is_admin
            || ($self->defined_arg('uid') && $user->id == $self->args('uid'))
            || ($self->defined_arg('id_owner') && $user->id == $self->args('id_owner'));

    return {
Francesc Guasch's avatar
Francesc Guasch committed
239
240
        id => $self->id
        ,status => $self->status
241
242
243
244
245
        ,error => $self->error
        ,id_domain => $self->id_domain
    }
}

246
247
=head2 create_domain

Francesc Guasch's avatar
Francesc Guasch committed
248
249
    my $req = Ravada::Request->create_domain(
                        name => 'bla'
250
251
252
253
254
255
256
257
258
259
260
261
                    , id_iso => 1
    );


=cut

sub create_domain {
    my $proto = shift;
    my $class=ref($proto) || $proto;

    my %args = @_;

Francesc Guasch's avatar
Francesc Guasch committed
262
    my $args = _check_args('create_domain', @_ );
263

264
265
266
    confess "ERROR: Argument vm required without id_base"
        if !exists $args->{vm} && !exists $args->{id_base};

267
    my $self = {};
Francesc Guasch's avatar
Francesc Guasch committed
268
269
    if ($args->{network}) {
        $args->{network} = JSON::XS->new->convert_blessed->encode($args->{network});
270
271
272
    }

    bless($self,$class);
Francesc Guasch's avatar
Francesc Guasch committed
273
    return $self->_new_request(command => 'create' , args => encode_json($args));
274
275
276
277
}

=head2 remove_domain

Francesc Guasch's avatar
Francesc Guasch committed
278
279
    my $req = Ravada::Request->remove_domain(
                     name => 'bla'
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
                    , uid => $user->id
    );


=cut


sub remove_domain {
    my $proto = shift;
    my $class=ref($proto) || $proto;

    my %args = @_;
    confess "Missing domain name"   if !$args{name};
    confess "Name is not scalar"    if ref($args{name});
    confess "Missing uid"           if !$args{uid};

    for (keys %args) {
        confess "Invalid argument $_" if !$VALID_ARG{'remove_domain'}->{$_};
    }

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

303
    return $self->_new_request(command => 'remove' , args => \%args);
304
305
306
307
308
309
310

}

=head2 start_domain

Requests to start a domain

Francesc Guasch's avatar
Francesc Guasch committed
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
  my $req = Ravada::Request->start_domain(
     name => 'name'
    , uid => $user->id
  );

Mandatory arguments: one of those must be passed:

=over

=item * name or id_domain

=item * uid: user id

=item * remote_ip: [optional] IP of the remote client that requested to start the domain

=back
327
328
329
330
331
332
333
334
335

=cut

sub start_domain {
    my $proto = shift;
    my $class=ref($proto) || $proto;

    my $args = _check_args('start_domain', @_);

336
337
338
    confess "ERROR: choose either id_domain or name "
        if $args->{id_domain} && $args->{name};

339
340
341
    my $self = {};
    bless($self,$class);

342
    return $self->_new_request(command => 'start' , args => $args);
343
344
}

345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
=head2 start_clones

Requests to start the clones of a base

  my $req = Ravada::Request->start_clones( name => 'name', uid => $user->id );

=cut

sub start_clones {
    my $proto = shift;
    my $class=ref($proto) || $proto;

    my $args = _check_args('start_clones', @_);

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

362
    return $self->_new_request(command => 'start_clones' , args => $args);
363
364
}

365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
=head2 pause_domain

Requests to pause a domain

  my $req = Ravada::Request->pause_domain( name => 'name', uid => $user->id );

=cut

sub pause_domain {
    my $proto = shift;
    my $class=ref($proto) || $proto;

    my $args = _check_args('pause_domain', @_);

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

382
    return $self->_new_request(command => 'pause' , args => $args);
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
}

=head2 resume_domain

Requests to pause a domain

  my $req = Ravada::Request->resume_domain( name => 'name', uid => $user->id );

=cut

sub resume_domain {
    my $proto = shift;
    my $class=ref($proto) || $proto;

    my $args = _check_args('resume_domain', @_);

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

402
    return $self->_new_request(command => 'resume' , args => $args);
403
404
405
406
407
408
}



sub _check_args {
    my $sub = shift;
Francesc Guasch's avatar
Francesc Guasch committed
409
    confess "Odd number of elements ".Dumper(\@_)   if scalar(@_) % 2;
410
411
    my $args = { @_ };

412
413
    my $valid_args = valid_args($sub);
    for (qw(at after_request uid)) {
414
415
        $valid_args->{$_}=2 if !exists $valid_args->{$_};
    }
416
417
418
419

    confess "Unknown method $sub" if !$valid_args;
    for (keys %{$args}) {
        confess "Invalid argument $_ , valid args ".Dumper($valid_args)
420
        if !$valid_args->{$_};
421
422
    }

423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
    if (exists $args->{machine} && $VALID_ARG{$sub}->{id_domain}) {
        my $id_domain = _search_id_domain($args->{machine});

        die "Error: provided id_domain=$args->{id_domain} and machine=$args->{machine}. "
        ." But $args->{machine} has a different id=$id_domain\n"
        if exists $args->{id_domain} && $args->{id_domain}
        && $args->{id_domain} ne $id_domain;

        die "Error: unknown machine '$args->{machine}'\n" if !defined $id_domain;
        $args->{id_domain} = $id_domain;

    }
    my $valid = valid_args($sub);
    for (keys %$valid) {
        next if $valid->{$_} == 2; # optional arg
438
439
        confess "Missing argument $_"   if !exists $args->{$_};
    }
440
    delete $args->{machine} if exists $args->{machine} && exists $args->{id_domain};
441
442
443
444

    return $args;
}

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
481
482
483
484
485
486
487
sub _valid_args_common($command_req) {
    my %valid;
    my $found;
    if ( exists $VALID_ARG{$command_req}) {
        %valid = %{$VALID_ARG{$command_req}};
        %valid = %{$valid{args}} if exists $valid{args};
        $found++;
    } else {
        for my $command (keys %VALID_ARG) {
            if ( exists $VALID_ARG{$command}->{alias}
                    && $VALID_ARG{$command}->{alias} eq $command_req ) {
                %valid = %{$VALID_ARG{$command}->{args}};
                $found++;
                last;
            }
        }
    }
    confess "Error: Unknown command '$command_req'\n" if !$found;
    $valid{at} = 2;
    $valid{after_request} = 2;
    return \%valid;
}

sub valid_args_cli($command) {
    my $valid = _valid_args_common($command);

    if (exists $valid->{id_domain}) {
        $valid->{machine} = $valid->{id_domain};
        delete $valid->{id_domain};
    }
    return $valid;
}

sub valid_args($command=undef) {
    return %VALID_ARG if !defined $command;
    my $valid = _valid_args_common($command);
    if (exists $valid->{id_domain}) {
        $valid->{machine} = 2;
        $valid->{id_domain} = 2;
    }
    return $valid;
}

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
513
514
515
516
517
518
519
520
521
522
523
=head2 force_shutdown_domain

Requests to stop a domain now !

  my $req = Ravada::Request->shutdown_domain( name => 'name' , uid => $user->id );

=cut

sub force_shutdown_domain {
    my $proto = shift;
    my $class=ref($proto) || $proto;

    my $args = _check_args('force_shutdown_domain', @_ );

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

    return $self->_new_request(command => 'force_shutdown' , args => $args);
}

=head2 shutdown_domain

Requests to stop a domain

  my $req = Ravada::Request->shutdown_domain( name => 'name' , uid => $user->id );
  my $req = Ravada::Request->shutdown_domain( name => 'name' , uid => $user->id
                                            ,timeout => $timeout );

=cut

sub shutdown_domain {
    my $proto = shift;
    my $class=ref($proto) || $proto;

    my $args = _check_args('shutdown_domain', @_ );

Francesc Guasch's avatar
Francesc Guasch committed
524
    $args->{timeout} = $TIMEOUT_SHUTDOWN if !exists $args->{timeout};
525

Francesc Guasch's avatar
Francesc Guasch committed
526
527
528
    confess "ERROR: You must supply either id_domain or name ".Dumper($args)
        if !$args->{id_domain} && !$args->{name};

529
530
531
    my $self = {};
    bless($self,$class);

532
    return $self->_new_request(command => 'shutdown_domain' , args => $args);
533
534
}

Francesc Guasch's avatar
Francesc Guasch committed
535
536
537
538
539
540
541
542
543
sub new_request($self, $command, @args) {
    die "Error: Unknown request '$command'" if !$VALID_ARG{$command};
    return _new_request(
        $self
        ,command => $command
           ,args => _check_args($command, @args)
    );
}

Francesc Guasch's avatar
Francesc Guasch committed
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
sub _duplicated_request($command, $args) {
    return if !$args;
    my $args_d = decode_json($args);
    delete $args_d->{uid};
    my $sth = $$CONNECTOR->dbh->prepare(
        "SELECT id,args FROM requests WHERE status='requested'"
        ." AND command=?"
    );
    $sth->execute($command);
    while (my ($id,$args_found) = $sth->fetchrow) {

        my $args_found_d = decode_json($args_found);
        delete $args_found_d->{uid};

        next if join(".",sort keys %$args_d) ne join(".",sort keys %$args_found_d);
        my $args_d_s = join(".",map { $args_d->{$_} } sort keys %$args_d);
        my $args_found_s = join(".",map {$args_found_d->{$_} } sort keys %$args_found_d);
        next if $args_d_s ne $args_found_s;

        warn "$id\n$args_d_s\n$args_found_s\n"
            if $command eq 'clone' && $args =~ /a-1/;
        return $id;
    }
    return 0;
}

570
571
sub _new_request {
    my $self = shift;
572
573
574
    if ( !ref($self) ) {
        my $proto = $self ;
        my $class = ref($proto) || $proto;
Francesc Guasch's avatar
Francesc Guasch committed
575
576
577
        $self = {};
        bless ($self, $class);
    }
578
579
580
581
582
583
584
585
586
587
588
589
    my %args = @_;

    $args{status} = 'requested';

    if ($args{name}) {
        $args{domain_name} = $args{name};
        delete $args{name};
    }
    if ( ref $args{args} ) {
        $args{args}->{uid} = $args{args}->{id_owner}
            if !exists $args{args}->{uid};
        $args{at_time} = $args{args}->{at} if exists $args{args}->{at};
590
591
592
593
594
595
        my $id_domain_args = $args{args}->{id_domain};

        if ($id_domain_args) {
            confess "ERROR: Different id_domain: ".Dumper(\%args)
                if $args{id_domain} && $args{id_domain} ne $id_domain_args;
            $args{id_domain} = $id_domain_args;
596
597
598
            $args{after_request} = delete $args{args}->{after_request}
                if exists $args{args}->{after_request};

599
        }
600
601
602
        $args{args} = encode_json($args{args});
    }
    _init_connector()   if !$CONNECTOR || !$$CONNECTOR;
Francesc Guasch's avatar
Francesc Guasch committed
603
604
605
    if ($args{command} =~ /^(clone|manage_pools)$/) {
        if ( _duplicated_request($args{command}, $args{args})
            || ( $args{command} ne 'clone' && done_recently(undef, 60, $args{command}))) {
frankiejol's avatar
frankiejol committed
606
            #            warn "Warning: duplicated request for $args{command} $args{args}";
Francesc Guasch's avatar
Francesc Guasch committed
607
608
609
            return;
        }
    }
610
611
612
613
614
615
616
617
618
619
620
621

    my $sth = $$CONNECTOR->dbh->prepare(
        "INSERT INTO requests (".join(",",sort keys %args).")"
        ."  VALUES ( "
                .join(",", map { '?' } keys %args)
                ." )"
    );
    $sth->execute(map { $args{$_} } sort keys %args);
    $sth->finish;

    $self->{id} = $self->_last_insert_id();

Francesc Guasch's avatar
Francesc Guasch committed
622
623
624
625
626
    $sth = $$CONNECTOR->dbh->prepare(
    "UPDATE requests set date_req=date_changed"
    ." WHERE id=?");
    $sth->execute($self->{id});

627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
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
    return $self->open($self->{id});
}

sub _last_insert_id {
    my $driver = $$CONNECTOR->dbh->{Driver}->{Name};

    if ( $driver =~ /sqlite/i ) {
        return _last_insert_id_sqlite(@_);
    } elsif ( $driver =~ /mysql/i ) {
        return _last_insert_id_mysql(@_);
    } else {
        confess "I don't know how to get last_insert_id for $driver";
    }
}

sub _last_insert_id_mysql {
    my $self = shift;
    my $sth = $$CONNECTOR->dbh->prepare("SELECT last_insert_id()");
    $sth->execute;
    my ($id) = $sth->fetchrow;
    $sth->finish;
    return $id;

}

sub _last_insert_id_sqlite {
    my $self = shift;

    my $sth = $$CONNECTOR->dbh->prepare("SELECT last_insert_rowid()");
    $sth->execute;
    my ($id) = $sth->fetchrow;
    $sth->finish;
    return $id;
}

=head2 status

Returns or sets the status of a request

  $req->status('done');

  my $status = $req->status();

=cut

sub status {
    my $self = shift;
    my $status = shift;
    my $message = shift;

    if (!defined $status) {
        my $sth = $$CONNECTOR->dbh->prepare("SELECT * FROM requests "
            ." WHERE id=?");
        $sth->execute($self->{id});
        my $row = $sth->fetchrow_hashref;
        $sth->finish;

        return ($row->{status} or 'unknown');
    }

    my $sth = $$CONNECTOR->dbh->prepare("UPDATE requests set status=? "
            ." WHERE id=?");
689
690

    $status = substr($status,0,64);
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
    $sth->execute($status, $self->{id});
    $sth->finish;

    $self->_send_message($status, $message)
        if $CMD_SEND_MESSAGE{$self->command} || $self->error ;
    return $status;
}

sub _search_domain_name {
    my $self = shift;
    my $domain_id = shift;

    my $sth = $$CONNECTOR->dbh->prepare("SELECT name FROM domains where id=?");
    $sth->execute($domain_id);
    return $sth->fetchrow;
}

708
709
710
711
712
713
714
715
716
717
718
sub _search_id_domain($machine) {
    return $machine if $machine =~ /^\d+$/;

    _init_connector();
    my $sth = $$CONNECTOR->dbh->prepare("SELECT id FROM domains where name=?");
    $sth->execute($machine);
    my $id = $sth->fetchrow;
    return $id;
}


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
sub _send_message {
    my $self = shift;
    my $status = shift;
    my $message = ( shift or $self->error );

    my $uid;

    $uid = $self->args('id_owner') if $self->defined_arg('id_owner');
    $uid = $self->args('uid')      if !$uid && $self->defined_arg('uid');
    return if !$uid;

    my $domain_name = $self->defined_arg('name');
    if (!$domain_name) {
        my $domain_id = $self->defined_arg('id_domain');
        $domain_name = $self->_search_domain_name($domain_id)   if $domain_id;
        $domain_name = '' if !defined $domain_name;
    }
    $domain_name = "$domain_name "  if length $domain_name;

    $self->_remove_unnecessary_messages() if $self->status eq 'done';

    my $subject = $self->command." $domain_name ".$self->status;
    $subject = $message if $message && $self->status eq 'done'
            && length ($message)<60;

    my $sth = $$CONNECTOR->dbh->prepare(
        "INSERT INTO messages ( id_user, id_request, subject, message, date_shown ) "
        ." VALUES ( ?,?,?,?, NULL)"
    );
    $sth->execute($uid, $self->id,$subject, $message);
    $sth->finish;
}

sub _remove_unnecessary_messages {
    my $self = shift;

    my $uid;
    $uid = $self->defined_arg('id_owner');
    $uid = $self->defined_arg('uid')        if !$uid;
    return if !$uid;


    my $sth = $$CONNECTOR->dbh->prepare(
        "DELETE FROM messages WHERE id_user=? AND id_request=? "
        ." AND (message='' OR message IS NULL)"
    );

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

}

771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
sub _remove_messages {
    my $self = shift;

    my $uid;
    $uid = $self->defined_arg('id_owner');
    $uid = $self->defined_arg('uid')        if !$uid;
    return if !$uid;


    my $sth = $$CONNECTOR->dbh->prepare(
        "DELETE FROM messages WHERE id_user=? AND id_request=? "
    );

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

}


790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
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
835
836
837
838
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

=head2 result

  Returns the result of the request if any

  my $result = $req->result;

=cut

sub result {
    my $self = shift;

    my $value = shift;

    if (defined $value ) {
        my $sth = $$CONNECTOR->dbh->prepare("UPDATE requests set result=? "
            ." WHERE id=?");
        $sth->execute(encode_json($value), $self->{id});
        $sth->finish;

    } else {
        my $sth = $$CONNECTOR->dbh->prepare("SELECT result FROM requests where id=? ");
        $sth->execute($self->{id});
        ($value) = $sth->fetchrow;
        $value = decode_json($value)    if defined $value;
        $sth->finish;

    }

    return $value;
}

=head2 command

Returns the requested command

=cut

sub command {
    my $self = shift;
    return $self->{command};
}

=head2 args

Returns the requested command

  my $command = $req->command;

=cut


=head2 args

Returns the arguments of a request or the value of one argument field

  my $args = $request->args();
  print $args->{name};

  print $request->args('name');

=cut


sub args {
    my $self = shift;
    my $name = shift;
    return $self->{args}    if !$name;

    confess "Unknown argument $name ".Dumper($self->{args})
        if !exists $self->{args}->{$name};
    return $self->{args}->{$name};
}

Francesc Guasch's avatar
Francesc Guasch committed
864
865
866
867
868
869
870
871
872
873
sub arg($self, $name, $value) {

    confess "Unknown argument $name ".Dumper($self->{args})
        if !exists $self->{args}->{$name} && !defined $value;

    $self->{args}->{$name} = $value if defined $value;
    return $self->{args}->{$name};
}


874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
=head2 defined_arg

Returns if an argument is defined

=cut

sub defined_arg {
    my $self = shift;
    my $name = shift;
    confess "ERROR: missing arg name" if !defined $name;
    return $self->{args}->{$name};
}

=head2 screenshot_domain

Request the screenshot of a domain.

Arguments:

- optional filename , defaults to "storage_path/$id_domain.png"

Returns a Ravada::Request;

=cut

sub screenshot_domain {
    my $proto = shift;
    my $class=ref($proto) || $proto;

    my $args = _check_args('screenshot_domain', @_ );

    $args->{filename} = '' if !exists $args->{filename};

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

    return $self->_new_request(command => 'screenshot' , id_domain => $args->{id_domain}
        ,args => $args);

}

915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
=head2 copy_screenshot

Request to copy a screenshot from a domain to another

=cut

sub copy_screenshot {
  my $proto = shift;
  my $class=ref($proto) || $proto;

  my $args = _check_args('copy_screenshot', @_ );

  $args->{filename} = '' if !exists $args->{filename};

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

  return $self->_new_request(
       command => 'copy_screenshot'
      ,id_domain => $args->{id_domain}
      ,args => $args
      );
Joel Alarcón's avatar
Joel Alarcón committed
937

938
939
}

Francesc Guasch's avatar
Francesc Guasch committed
940
941
=head2 refresh_vms

942
Refreshes the Virtual Mangers
Francesc Guasch's avatar
Francesc Guasch committed
943
944
945
946
947
948
949
950

=cut

sub refresh_vms {
    my $proto = shift;
    my $class = ref($proto) || $proto;

    my $args = _check_args('refresh_vms', @_ );
951
952
953
    if  (!$args->{_force} ) {
          return if done_recently(undef,60,'refresh_vms') || _requested('refresh_vms');
    }
Francesc Guasch's avatar
Francesc Guasch committed
954

Francesc Guasch's avatar
Francesc Guasch committed
955
956
    $args->{timeout} = 120 if ! $args->{timeout};

Francesc Guasch's avatar
Francesc Guasch committed
957
958
959
    my $self = {};
    bless($self,$class);

960
    _init_connector();
Francesc Guasch's avatar
Francesc Guasch committed
961
962
963
964
965
966
    return $self->_new_request(
        command => 'refresh_vms'
        , args => $args
    );


967
968
969
970
971
972
973
974
975
976
977
978
979
}

=head2 set_base_vm

Enables a base in a Virtual Manager

=cut

sub set_base_vm {
    my $proto = shift;
    my $class = ref($proto) || $proto;

    my $args = _check_args('set_base_vm', @_ );
980
    $args->{value} = 1 if !exists $args->{value};
981
982

    my $self = {};
983
    bless ($self, $class);
984
985

    return $self->_new_request(
986
            command => 'set_base_vm'
987
             , args => $args
988
989
    );

990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
}

=head2 remove_base_vm

Disables a base in a Virtual Manager

=cut

sub remove_base_vm {
    my $proto = shift;
    my $class = ref($proto) || $proto;

    my $args = _check_args('set_base_vm', @_ );
    $args->{value} = 0;

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

    return $self->_new_request(
Francesc Guasch's avatar
Francesc Guasch committed
1009
            command => 'remove_base_vm'
1010
             , args => $args
1011
    );
1012
1013
1014

}

1015
1016
1017
1018
1019
1020
1021

=head2 type

Returns the type of the request

=cut

1022
sub type($self) {
1023
1024
    my $command = $self;
    $command = $self->command if ref($self);
1025
1026
1027
1028
1029
1030
    for my $type ( keys %COMMAND ) {
        return $type if grep /^$command$/, @{$COMMAND{$type}->{commands}};
    }
    return 'long';
}

Francesc Guasch's avatar
Francesc Guasch committed
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
sub _set_priority ($self) {
    my $command = $self;
    $command = $self->command if ref($self);
    for my $type ( keys %COMMAND ) {
        next if  !grep /^$command$/, @{$COMMAND{$type}->{commands}};
        return $COMMAND{$type}->{priority} if exists $COMMAND{$type}->{priority};
        return 10;
    }
}


1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
=head2 working_requests

Returns the number of working requests of the same type

    my $n = $request->working_requests();

=cut

sub count_requests($self) {
    my $sth = $$CONNECTOR->dbh->prepare(
1052
        "SELECT command FROM requests"
1053
1054
1055
        ." WHERE status = 'working' "
    );
    $sth->execute();
1056
1057
1058
1059
    my $n = 0;
    while ( my $command = $sth->fetchrow ) {
        $n++ if type($command) eq $self->type;
    }
1060
1061
1062
    return $n;
}

1063
=head2 requests_limit
Francesc Guasch's avatar
Francesc Guasch committed
1064

1065
    Returns the limit of requests of a type.
Francesc Guasch's avatar
Francesc Guasch committed
1066
1067
1068

=cut

1069
1070
1071
sub requests_limit($self, $type = $self->type) {
    confess "Error: no requests of type $type" if !exists $COMMAND{$type};
    return $COMMAND{$type}->{limit};
JanFontanet's avatar
JanFontanet committed
1072
1073
}

1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
=head2 domain_autostart

Sets the autostart flag on a domain

=cut

sub domain_autostart {
    my $proto = shift;
    my $class = ref($proto) || $proto;

Francesc Guasch's avatar
Francesc Guasch committed
1084
1085
    my $args = _check_args('domain_autostart', @_ );
    $args->{value} = 1 if !exists $args->{value};
1086
1087
1088
1089
1090
1091
1092
1093
1094

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

    return _new_request($self
        , command => 'domain_autostart'
        , args => $args
    );
}
1095

Francesc Guasch's avatar
Francesc Guasch committed
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
=head2 autostart_domain

Deprecated for domain_autostart

=cut

sub autostart_domain {
    return domain_autostart(@_);
}

Francesc Guasch's avatar
Francesc Guasch committed
1106
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
=head2 enforce_limits

Enforces virtual machine limits, ie: an user can only run one virtual machine
at a time, so the older ones are shut down.


    my $req = Ravada::Request->enforce_limits(
        timeout => $timeout
    );

Arguments:

=over

=item * timeout: seconds that are given to a virtual machine to shutdown itself.
After this time, it gets powered off. Defaults to 120 seconds.

=back

It is advisable configure virtual machines so they shut down easily if asked to.
Just a few hints:

=over

=item * install ACPI services

=item * Set default action for power off to shutdown, do not ask the user

=cut


1137
1138
1139
1140
1141
sub enforce_limits {
    my $proto = shift;

    my $class = ref($proto) || $proto;

Francesc Guasch's avatar
Francesc Guasch committed
1142
1143
    my $args = _check_args('enforce_limits', @_ );

1144
    return if !$args->{_force} && _requested('enforce_limits');
Francesc Guasch's avatar
Francesc Guasch committed
1145
    $args->{timeout} = $TIMEOUT_SHUTDOWN if !exists $args->{timeout};
1146
1147
1148
1149

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

Francesc Guasch's avatar
Francesc Guasch committed
1150
    my $req = _new_request($self
1151
1152
1153
        , command => 'enforce_limits'
        , args => $args
    );
Francesc Guasch's avatar
Francesc Guasch committed
1154
1155
1156
1157
1158
1159
1160

    if (!$args->{at} && (my $id_request = $req->done_recently(30))) {
        $req->status("done",$req->command." run recently by id_request: $id_request");
    }
    return $req;
}

1161
1162
1163
1164
1165
1166
=head2 refresh_machine

Refresh a machine information

=cut

1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
sub refresh_machine {
    my $proto = shift;

    my $class = ref($proto) || $proto;

    my $args = _check_args('refresh_machine', @_ );

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

    my $id_domain = $args->{id_domain};
    my $id_requested = _requested('refresh_machine',id_domain => $id_domain);
    return Ravada::Request->open($id_requested) if $id_requested;

1181
1182
    return if done_recently(undef,60,'refresh_machine');

1183
1184
1185
1186
1187
1188
1189
1190
1191
    my $req = _new_request($self
        , command => 'refresh_machine'
        , args => $args
    );

    return $req;

}

Francesc Guasch's avatar
Francesc Guasch committed
1192
1193
1194
1195
1196
1197
1198
sub _new_request_generic {
    my $command = shift;

    my $proto = shift;
    my $class = ref($proto) || $proto;

    my $args = _check_args($command, @_ );
1199
1200
1201
1202
1203

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


Francesc Guasch's avatar
Francesc Guasch committed
1204
1205
1206
1207
1208
1209
1210
    my $req = _new_request($self
        ,command => $command
        ,args => $args
    );
    return $req;
}

Francesc Guasch's avatar
Francesc Guasch committed
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
=head2 done_recently

Returns wether this command has been requested successfully recently.

  if ($request->done_recently($seconds)) {
    ... skips work ...
  } else {
    ... does work ...
  }

This method is used for commands that take long to run as garbage collection.

=cut

1225
sub done_recently($self, $seconds=60,$command=undef) {
1226
    _init_connector();
1227
1228
1229
1230
1231
    my $id_req = 0;
    if ($self) {
        $id_req = $self->id;
        $command = $self->command;
    }
Francesc Guasch's avatar
Francesc Guasch committed
1232
1233
1234
1235
1236
1237
1238
1239
1240
    my $sth = $$CONNECTOR->dbh->prepare(
        "SELECT id FROM requests"
        ." WHERE date_changed > ? "
        ."        AND command = ? "
        ."         AND ( status = 'done' OR status ='working') "
        ."         AND  error = '' "
        ."         AND id <> ? "
    );
    my $date= Time::Piece->localtime(time - $seconds);
1241
    $sth->execute($date->ymd." ".$date->hms, $command, $id_req);
Francesc Guasch's avatar
Francesc Guasch committed
1242
1243
    my ($id) = $sth->fetchrow;
    return $id;
1244
1245
}

1246
sub _requested($command, %fields) {
1247
    _init_connector();
1248
    my $query =
1249
1250
1251
        "SELECT id FROM requests"
        ."  WHERE command = ? "
        ."     AND status <> 'done' "
1252
1253
1254
1255
1256
1257
1258
1259
    ;
    my @values = ( $command );
    for my $key( keys %fields ) {
        $query.= " AND $key = ?";
        push @values,($fields{$key});
    }
    my $sth = $$CONNECTOR->dbh->prepare($query);
    $sth->execute(@values);
1260
1261
1262
1263
1264
    my ($id) = $sth->fetchrow;
    return $id;

}

1265
1266
1267
1268
1269
sub stop($self) {
    warn "Killing ".$self->command
        ." , pid: ".$self->pid
        .", stale for ".(time - $self->start_time)." seconds\n";
    my $ok = kill (15,$self->pid);
Francesc Guasch's avatar
Francesc Guasch committed
1270
    $self->status('done',"Killed start process after "
1271
1272
1273
1274
           .(time - $self->start_time)." seconds\n");

}

Francesc Guasch's avatar
Francesc Guasch committed
1275
1276
1277
1278
sub priority($self) {
    return $self->{priority};
}

1279
1280
1281
1282
1283
1284
1285
1286
1287
sub requirements_done($self) {
    my $after_request = $self->after_request();
    return 1 if !defined $after_request;

    my $req = Ravada::Request->open($self->after_request);
    return 1 if $req->status eq 'done';
    return 0;
}

1288
1289
1290
1291
1292
1293
sub AUTOLOAD {
    my $self = shift;

    my $name = $AUTOLOAD;
    $name =~ s/.*://;

1294
1295
1296
1297
1298
1299
1300
    if(!ref($self) && $VALID_ARG{$name} ) {
        return _new_request($self
            , command => $name
            , args => _check_args($name, @_)
        );
    }

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
    confess "Can't locate object method $name via package $self"
        if !ref($self);

    my $value = shift;
    $name =~ tr/[a-z][A-Z]_/_/c;

    confess "ERROR: Unknown field $name "
        if !exists $self->{$name} && !exists $FIELD{$name} && !exists $FIELD_RO{$name};
    if (!defined $value) {
        my $sth = $$CONNECTOR->dbh->prepare("SELECT * FROM requests "
            ." WHERE id=?");
        $sth->execute($self->{id});
        my $row = $sth->fetchrow_hashref;
        $sth->finish;

        return $row->{$name};
    }

    confess "ERROR: field $name is read only"
        if $FIELD_RO{$name};

    my $sth = $$CONNECTOR->dbh->prepare("UPDATE requests set $name=? "
            ." WHERE id=?");
    eval {
        $sth->execute($value, $self->{id});
        $sth->finish;
    };
    warn "$name=$value\n$@" if $@;
    return $value;

}

1333

1334
1335
sub DESTROY {}
1;