Request.pm 40.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
use Ravada;
use Ravada::Front;
Francesc Guasch's avatar
Francesc Guasch committed
20
use Ravada::Utils;
21
22
23

use vars qw($AUTOLOAD);

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

27
28
29
30
31
32
=pod

Request a command to the ravada backend

=cut

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

our $args_manage = { name => 1 , uid => 1 };
38
our $args_prepare = { id_domain => 1 , uid => 1, with_cd => 2 };
39
40
41
42
43
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
44
              vm => 2
45
46
           ,name => 1
           ,swap => 2
Francesc Guasch's avatar
Francesc Guasch committed
47
         ,id_iso => 2
48
         ,iso_file => 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
Francesc Guasch's avatar
Francesc Guasch committed
57
           ,data => 2
Francesc Guasch's avatar
Francesc Guasch committed
58
           ,options => 2
59
60
61
62
    }
    ,open_iptables => $args_manage_iptables
      ,remove_base => $args_remove_base
     ,prepare_base => $args_prepare
Francesc Guasch's avatar
Francesc Guasch committed
63
     ,spinoff => { id_domain => 1, uid => 1 }
64
65
66
     ,pause_domain => $args_manage
    ,resume_domain => {%$args_manage, remote_ip => 1 }
    ,remove_domain => $args_manage
Francesc Guasch's avatar
Francesc Guasch committed
67
    ,restore_domain => { id_domain => 1, uid => 1 }
68
    ,shutdown_domain => { name => 2, id_domain => 2, uid => 1, timeout => 2, at => 2
69
                       , check => 2
70
                       , id_vm => 2 }
71
    ,force_shutdown_domain => { id_domain => 1, uid => 1, at => 2, id_vm => 2 }
Roberto P. Rubio's avatar
Roberto P. Rubio committed
72
73
    ,reboot_domain => { name => 2, id_domain => 2, uid => 1, timeout => 2, at => 2
                       , id_vm => 2 }
Roberto P. Rubio's avatar
Roberto P. Rubio committed
74
    ,force_reboot_domain => { id_domain => 1, uid => 1, at => 2, id_vm => 2 }
Francesc Guasch's avatar
Francesc Guasch committed
75
    ,screenshot => { id_domain => 1 }
Francesc Guasch's avatar
Francesc Guasch committed
76
    ,domain_autostart => { id_domain => 1 , uid => 1, value => 2 }
Francesc Guasch's avatar
Francesc Guasch committed
77
    ,copy_screenshot => { id_domain => 1 }
Francesc Guasch's avatar
Francesc Guasch committed
78
    ,start_domain => {%$args_manage, remote_ip => 2, name => 2, id_domain => 2 }
Francesc Guasch's avatar
Francesc Guasch committed
79
    ,start_clones => { id_domain => 1, uid => 1, remote_ip => 1, sequential => 2 }
80
    ,shutdown_clones => { id_domain => 1, uid => 1, timeout => 2 }
81
    ,rename_domain => { uid => 1, name => 1, id_domain => 1}
82
    ,dettach => { uid => 1, id_domain => 1 }
83
    ,set_driver => {uid => 1, id_domain => 1, id_option => 1}
84
    ,hybernate=> {uid => 1, id_domain => 1}
85
    ,download => {uid => 2, id_iso => 1, id_vm => 2, vm => 2, verbose => 2, delay => 2, test => 2}
86
    ,refresh_storage => { id_vm => 2, uid => 2 }
87
    ,list_storage_pools => { id_vm => 1 , uid => 1 }
88
    ,check_storage => { uid => 1 }
89
    ,set_base_vm=> {uid => 1, id_vm=> 1, id_domain => 1, value => 2 }
90
    ,cleanup => { timeout => 2 }
91
    ,clone => { uid => 1, id_domain => 1, name => 2, memory => 2, number => 2, volatile => 2, id_owner => 2
Francesc Guasch's avatar
Francesc Guasch committed
92
93
94
95
96
97
98
                # If base has pools, from_pool = 1 if undefined
                # when from_pool is true the clone is picked from the pool
                # when from_pool is false the clone is created
                ,from_pool => 2
                # If base has pools, create anew and add to the pool
                ,add_to_pool => 2
                ,start => 2,
Francesc Guasch's avatar
Francesc Guasch committed
99
                ,remote_ip => 2
100
                ,with_cd => 2
Francesc Guasch's avatar
Francesc Guasch committed
101
    }
Joel Alarcón's avatar
Joel Alarcón committed
102
    ,change_owner => {uid => 1, id_domain => 1}
Francesc Guasch's avatar
Francesc Guasch committed
103
    ,add_hardware => {uid => 1, id_domain => 1, name => 1, number => 2, data => 2 }
104
    ,remove_hardware => {uid => 1, id_domain => 1, name => 1, index => 1}
Francesc Guasch's avatar
Francesc Guasch committed
105
    ,change_hardware => {uid => 1, id_domain => 1, hardware => 1, index => 2, data => 1 }
106
    ,enforce_limits => { timeout => 2, _force => 2 }
Francesc Guasch's avatar
Francesc Guasch committed
107
    ,refresh_machine => { id_domain => 1, uid => 1 }
108
    ,refresh_machine_ports => { id_domain => 1, uid => 1, timeout => 2 }
Francesc Guasch's avatar
Francesc Guasch committed
109
    ,rebase => { uid => 1, id_base => 1, id_domain => 1 }
110
    ,set_time => { uid => 1, id_domain => 1 }
Francesc Guasch's avatar
Francesc Guasch committed
111
    ,rsync_back => { uid => 1, id_domain => 1, id_node => 1 }
Francesc Guasch's avatar
Francesc Guasch committed
112
113
114
115
    # 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
116
    ,close_exposed_ports => { uid => 1, id_domain => 1, port => 2, clean => 2 }
Francesc Guasch's avatar
Francesc Guasch committed
117
    # Virtual Managers or Nodes
Francesc Guasch's avatar
Francesc Guasch committed
118
    ,refresh_vms => { _force => 2, timeout_shutdown => 2 }
Francesc Guasch's avatar
Francesc Guasch committed
119
120
121
122

    ,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 }
123
124
125
    ,migrate => { uid => 1, id_node => 1, id_domain => 1, start => 2, remote_ip => 2
        ,shutdown => 2, shutdown_timeout => 2
    }
Francesc Guasch's avatar
Francesc Guasch committed
126
127
    ,compact => { uid => 1, id_domain => 1 , keep_backup => 2 }
      ,purge => { uid => 1, id_domain => 1 }
Francesc Guasch's avatar
Francesc Guasch committed
128

Francesc Guasch's avatar
Francesc Guasch committed
129
130
    ,list_machine_types => { uid => 1, id_vm => 2, vm_type => 2}

Francesc Guasch's avatar
Francesc Guasch committed
131
    #users
132
    ,post_login => { user => 1, locale => 2 }
Francesc Guasch's avatar
Francesc Guasch committed
133

Francesc Guasch's avatar
Francesc Guasch committed
134
135
136
    #networks
    ,list_network_interfaces => { uid => 1, vm_type => 1, type => 2 }

Fernando Verdugo's avatar
Fernando Verdugo committed
137
138
139
    #isos
    ,list_isos => { vm_type => 1 }

Francesc Guasch's avatar
Francesc Guasch committed
140
    ,manage_pools => { uid => 2, id_domain => 2 }
141
    ,ping_backend => {}
142
143
144
);

our %CMD_SEND_MESSAGE = map { $_ => 1 }
145
    qw( create start shutdown force_shutdown reboot prepare_base remove remove_base rename_domain screenshot download
Francesc Guasch's avatar
Francesc Guasch committed
146
            clone
147
            set_base_vm remove_base_vm
Francesc Guasch's avatar
Francesc Guasch committed
148
            domain_autostart hibernate hybernate
Francesc Guasch's avatar
Francesc Guasch committed
149
            change_owner
Francesc Guasch's avatar
Francesc Guasch committed
150
            add_hardware remove_hardware set_driver change_hardware
Francesc Guasch's avatar
Francesc Guasch committed
151
            expose remove_expose
Francesc Guasch's avatar
Francesc Guasch committed
152
            rebase rebase_volumes
Roberto P. Rubio's avatar
Roberto P. Rubio committed
153
            shutdown_node reboot_node start_node
154
            start_domain
155
    );
156

157
158
159
160
our %CMD_NO_DUPLICATE = map { $_ => 1 }
qw(
    set_base_vm
    remove_base_vm
Francesc Guasch's avatar
Francesc Guasch committed
161
162
    rsync_back
    cleanup
163
164
    refresh_machine_ports
    set_time
165
166
);

Francesc Guasch's avatar
Francesc Guasch committed
167
our $TIMEOUT_SHUTDOWN = 120;
Roberto P. Rubio's avatar
Roberto P. Rubio committed
168
our $TIMEOUT_REBOOT = 20;
Francesc Guasch's avatar
Francesc Guasch committed
169

170
171
our $CONNECTOR;

172
our %COMMAND = (
Francesc Guasch's avatar
Francesc Guasch committed
173
174
    long => {
        limit => 4
Francesc Guasch's avatar
Francesc Guasch committed
175
        ,priority => 10
Francesc Guasch's avatar
Francesc Guasch committed
176
    } #default
Francesc Guasch's avatar
Francesc Guasch committed
177
178
179
180
181
182

    # list from low to high priority
    ,disk_low_priority => {
        limit => 2
        ,commands => ['rsync_back','check_storage', 'refresh_vms']
        ,priority => 30
183
    }
184
185
    ,disk => {
        limit => 1
186
        ,commands => ['prepare_base','remove_base','set_base_vm','rebase_volumes'
187
                    , 'remove_base_vm'
Francesc Guasch's avatar
Francesc Guasch committed
188
                    , 'screenshot'
Francesc Guasch's avatar
Francesc Guasch committed
189
                    , 'cleanup'
Francesc Guasch's avatar
Francesc Guasch committed
190
                    , 'compact'
191
                ]
Francesc Guasch's avatar
Francesc Guasch committed
192
        ,priority => 20
193
    }
Francesc Guasch's avatar
Francesc Guasch committed
194
195
196
197
    ,huge => {
        limit => 1
        ,commands => ['download']
        ,priority => 15
198
    }
Francesc Guasch's avatar
Francesc Guasch committed
199

Francesc Guasch's avatar
Francesc Guasch committed
200
201
    ,secondary => {
        limit => 50
Francesc Guasch's avatar
Francesc Guasch committed
202
        ,priority => 4
203
        ,commands => ['shutdown','shutdown_now', 'manage_pools','enforce_limits', 'set_time'
204
            ,'remove_domain','refresh_machine_ports'
205
        ]
Francesc Guasch's avatar
Francesc Guasch committed
206
207
208
209
210
    }

    ,important=> {
        limit => 20
        ,priority => 1
211
        ,commands => ['clone','start','start_clones','shutdown_clones','create','open_iptables','list_network_interfaces','list_isos','ping_backend','refresh_machine','open_exposed_ports']
Francesc Guasch's avatar
Francesc Guasch committed
212
    }
213
214
215
);
lock_hash %COMMAND;

Francesc Guasch's avatar
Francesc Guasch committed
216
217
218
219
our %CMD_VALIDATE = (
    clone => \&_validate_clone
    ,create => \&_validate_create_domain
    ,create_domain => \&_validate_create_domain
220
221
222
223
224
    ,start_domain => \&_validate_start_domain
    ,start => \&_validate_start_domain
    ,add_hardware=> \&_validate_change_hardware
    ,change_hardware=> \&_validate_change_hardware
    ,remove_hardware=> \&_validate_change_hardware
Francesc Guasch's avatar
Francesc Guasch committed
225
226
);

227
228
229
230
231
232
233
234
235
236
sub _init_connector {
    $CONNECTOR = \$Ravada::CONNECTOR;
    $CONNECTOR = \$Ravada::Front::CONNECTOR   if !$$CONNECTOR;

}

=head2 BUILD

    Internal object builder, do not call

237
=cut
238
239
240
241
242
243
244
245
246
247
248
249
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

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;

276
277
    my $args = {};
    $args = decode_json($row->{args}) if $row->{args};
278
279
280
281

    $row->{args} = $args;

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

284
285
286
    return $row;
}

287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
=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
302
303
        id => $self->id
        ,status => $self->status
304
305
        ,error => $self->error
        ,id_domain => $self->id_domain
306
        ,output => $self->output
307
308
309
    }
}

310
311
=head2 create_domain

Francesc Guasch's avatar
Francesc Guasch committed
312
313
    my $req = Ravada::Request->create_domain(
                        name => 'bla'
314
315
316
317
318
319
320
321
322
323
324
325
                    , id_iso => 1
    );


=cut

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

    my %args = @_;

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

328
329
330
    confess "ERROR: Argument vm required without id_base"
        if !exists $args->{vm} && !exists $args->{id_base};

331
    my $self = {};
Francesc Guasch's avatar
Francesc Guasch committed
332
333
    if ($args->{network}) {
        $args->{network} = JSON::XS->new->convert_blessed->encode($args->{network});
334
335
336
    }

    bless($self,$class);
Francesc Guasch's avatar
Francesc Guasch committed
337
    return $self->_new_request(command => 'create' , args => encode_json($args));
338
339
340
341
}

=head2 remove_domain

Francesc Guasch's avatar
Francesc Guasch committed
342
343
    my $req = Ravada::Request->remove_domain(
                     name => 'bla'
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
                    , 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);

367
    return $self->_new_request(command => 'remove' , args => \%args);
368
369
370
371
372
373
374

}

=head2 start_domain

Requests to start a domain

Francesc Guasch's avatar
Francesc Guasch committed
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
  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
391
392
393
394
395
396
397
398
399

=cut

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

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

400
401
402
    confess "ERROR: choose either id_domain or name "
        if $args->{id_domain} && $args->{name};

Francesc Guasch's avatar
Francesc Guasch committed
403
404
405
    confess "Error: remote ip invalid '$args->{remote_ip}'"
    if $args->{remote_ip} && $args->{remote_ip} !~ /^(localhost|\d+\.\d+\.\d+\.\d+)$/;

Francesc Guasch's avatar
Francesc Guasch committed
406
407
    _remove_low_priority_requests($args->{id_domain} or $args->{name});

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

411
    return $self->_new_request(command => 'start' , args => $args);
412
413
}

Francesc Guasch's avatar
Francesc Guasch committed
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
sub _remove_low_priority_requests($id_domain) {

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

    if ($id_domain !~ /^\d+$/) {
        $id_domain = _search_domain_id(undef,$id_domain);
    }
    for my $command (sort @{$COMMAND{disk_low_priority}->{commands}}) {
        my $sth = $$CONNECTOR->dbh->prepare("SELECT id FROM requests "
            ." WHERE command=? AND id_domain=? "
            ."    AND status <> 'done' "
        );
        $sth->execute($command, $id_domain);
        while ( my ($id_request) = $sth->fetchrow ) {
            my $req = Ravada::Request->open($id_request);
            $req->stop();
            warn "Stopping request $id_request";
        }
    }

}


437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
=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);

454
    return $self->_new_request(command => 'start_clones' , args => $args);
455
456
}

457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
=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);

474
    return $self->_new_request(command => 'pause' , args => $args);
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
}

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

494
    return $self->_new_request(command => 'resume' , args => $args);
495
496
497
498
499
500
}



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

    my $valid_args = $VALID_ARG{$sub};
505
    for (qw(at after_request after_request_ok retry _no_duplicate _force)) {
506
507
        $valid_args->{$_}=2 if !exists $valid_args->{$_};
    }
508
509
510
511
512
513
514
515
516

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

    for (keys %{$VALID_ARG{$sub}}) {
        next if $VALID_ARG{$sub}->{$_} == 2; # optional arg
Francesc Guasch's avatar
Francesc Guasch committed
517
        confess "Missing argument $_"   if !exists $args->{$_} || !defined $args->{$_};
518
519
520
521
522
523
524
525
526
    }

    return $args;
}

=head2 force_shutdown_domain

Requests to stop a domain now !

Roberto P. Rubio's avatar
Roberto P. Rubio committed
527
  my $req = Ravada::Request->force_shutdown_domain( name => 'name' , uid => $user->id );
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558

=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
559
560
561
    confess "ERROR: You must supply either id_domain or name ".Dumper($args)
        if !$args->{id_domain} && !$args->{name};

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

565
    return $self->_new_request(command => 'shutdown' , args => $args);
566
567
}

Roberto P. Rubio's avatar
Roberto P. Rubio committed
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
=head2 force_reboot_domain

Requests to stop a domain now !

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

=cut

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

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

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

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

Roberto P. Rubio's avatar
Roberto P. Rubio committed
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
=head2 reboot_domain

Requests to reboot a domain

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

=cut

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

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

    $args->{timeout} = $TIMEOUT_REBOOT if !exists $args->{timeout};

    confess "ERROR: You must supply either id_domain or name ".Dumper($args)
        if !$args->{id_domain} && !$args->{name};

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

    return $self->_new_request(command => 'reboot' , args => $args);
613
614
}

Francesc Guasch's avatar
Francesc Guasch committed
615
616
617
618
619
620
621
622
623
624
625
626
=head2 new_request

Creates a new request

    $req = Ravada::Request->new_request(
        start_domain
        ,uid => $user->id
        ,id_domain => $domain->id
    );

=cut

Francesc Guasch's avatar
Francesc Guasch committed
627
628
629
630
631
632
633
634
635
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)
    );
}

636
sub _duplicated_request($self=undef, $command=undef, $args=undef) {
Francesc Guasch's avatar
Francesc Guasch committed
637
    _init_connector()   if !$CONNECTOR || !$$CONNECTOR;
638
639
640
641
642
643
644
645
646
647

    my $args_d;
    if ($self) {
        confess "Error: do not supply args if you supply request" if $args;
        confess "Error: do not supply command if you supply request" if $command;
        $args_d = $self->args;
        $command = $self->command;
    } else {
        $args_d = decode_json($args);
    }
Francesc Guasch's avatar
Francesc Guasch committed
648
    delete $args_d->{uid};
649
    delete $args_d->{at};
Francesc Guasch's avatar
Francesc Guasch committed
650
    my $sth = $$CONNECTOR->dbh->prepare(
Francesc Guasch's avatar
Francesc Guasch committed
651
        "SELECT id,args FROM requests WHERE (status <> 'done')"
Francesc Guasch's avatar
Francesc Guasch committed
652
653
654
655
        ." AND command=?"
    );
    $sth->execute($command);
    while (my ($id,$args_found) = $sth->fetchrow) {
656
        next if $self && $self->id == $id;
Francesc Guasch's avatar
Francesc Guasch committed
657
658
659

        my $args_found_d = decode_json($args_found);
        delete $args_found_d->{uid};
660
        delete $args_found_d->{at};
Francesc Guasch's avatar
Francesc Guasch committed
661
662
663
664
665
666

        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;

Francesc Guasch's avatar
Francesc Guasch committed
667
        return Ravada::Request->open($id);
Francesc Guasch's avatar
Francesc Guasch committed
668
669
670
671
    }
    return 0;
}

672
673
sub _new_request {
    my $self = shift;
674
675
676
    if ( !ref($self) ) {
        my $proto = $self ;
        my $class = ref($proto) || $proto;
Francesc Guasch's avatar
Francesc Guasch committed
677
678
679
        $self = {};
        bless ($self, $class);
    }
680
681
    my %args = @_;

Francesc Guasch's avatar
Francesc Guasch committed
682
    $args{status} = 'requested';
683
684
685
686
687

    if ($args{name}) {
        $args{domain_name} = $args{name};
        delete $args{name};
    }
Francesc Guasch's avatar
Francesc Guasch committed
688
    my $no_duplicate = delete $args{_no_duplicate};
Francesc Guasch's avatar
Francesc Guasch committed
689
    my $uid;
690
691
692
    if ( ref $args{args} ) {
        $args{args}->{uid} = $args{args}->{id_owner}
            if !exists $args{args}->{uid};
Francesc Guasch's avatar
Francesc Guasch committed
693
694
        $uid = $args{args}->{uid} if exists $args{args}->{uid};

695
        $args{at_time} = $args{args}->{at} if exists $args{args}->{at};
696
697
698
699
700
701
702
        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;
        }
703
704
705
706
707
        for (qw(after_request after_request_ok retry)) {
            $args{$_} = delete $args{args}->{$_}
            if exists $args{args}->{$_};
        }

708
709
710
        $args{args} = encode_json($args{args});
    }
    _init_connector()   if !$CONNECTOR || !$$CONNECTOR;
711
    if ($args{command} =~ /^(clone|manage_pools)$/
712
        || $CMD_NO_DUPLICATE{$args{command}}
Francesc Guasch's avatar
Francesc Guasch committed
713
        || ($no_duplicate && $args{command} =~ /^(screenshot)$/)) {
Francesc Guasch's avatar
Francesc Guasch committed
714
715
716
717
718
719
720
721
        my $dupe = _duplicated_request(undef, $args{command}, $args{args});
        return $dupe if $dupe;

        my $recent;
        $recent = done_recently(undef, 60, $args{command})
        if $args{command} !~ /^(clone|migrate|set_base_vm)$/;
        return if $recent;

Francesc Guasch's avatar
Francesc Guasch committed
722
    }
723
724
725
726
727
728
729
730
731
732
733
734

    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
735
736
737
738
739
    $sth = $$CONNECTOR->dbh->prepare(
    "UPDATE requests set date_req=date_changed"
    ." WHERE id=?");
    $sth->execute($self->{id});

Francesc Guasch's avatar
Francesc Guasch committed
740
741

    my $request = $self->open($self->{id});
Francesc Guasch's avatar
Francesc Guasch committed
742
743
    $request->_validate();
    $request->status('requested') if $request->status ne'done';
Francesc Guasch's avatar
Francesc Guasch committed
744
745

    return $request;
746
747
}

Francesc Guasch's avatar
Francesc Guasch committed
748
749
750
751
752
753
754
sub _validate($self) {
    return if !exists $CMD_VALIDATE{$self->command};
    my $method = $CMD_VALIDATE{$self->command};
    return if !$method;
    $method->($self);
}

755
756
757
758
759
760
761
762
sub _validate_start_domain($self) {

    my $id_domain = $self->defined_arg('id_domain');
    if (!$id_domain) {
        my $domain_name = $self->defined_arg('name');
        $id_domain = _search_domain_id(undef,$domain_name);
    }
    return if !$id_domain;
763
764
765
766
767
768
769
    for my $command ('start','%_hardware') {
        my $req=$self->_search_request($command, id_domain => $id_domain);
        next if !$req;
        next if $req->at_time;
        next if $command eq 'start' && !$req->after_request();
        $self->after_request($req->id);
    }
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
}

sub _validate_change_hardware($self) {

    return if $self->after_request();

    my $id_domain = $self->defined_arg('id_domain');
    if (!$id_domain) {
        my $domain_name = $self->defined_arg('name');
        $id_domain = _search_domain_id(undef,$domain_name);
    }
    return if !$id_domain;
    my $req = $self->_search_request('%_hardware', id_domain => $id_domain);

    $self->after_request($req->id) if $req;
}


Francesc Guasch's avatar
Francesc Guasch committed
788
789
790
791
792
793
794
795
796
797
sub _validate_create_domain($self) {

    my $base;
    my $id_base = $self->defined_arg('id_base');

    my $id_owner = $self->defined_arg('id_owner') or confess "ERROR: Missing id_owner";
    my $owner = Ravada::Auth::SQL->search_by_id($id_owner) or confess "Unknown user id: $id_owner";

    $self->_validate_clone($id_base, $id_owner) if $id_base;

798
    unless ( $owner->is_admin
Francesc Guasch's avatar
Francesc Guasch committed
799
            || $owner->can_create_machine()
800
            || ($id_base && $owner->can_clone)) {
Francesc Guasch's avatar
Francesc Guasch committed
801

802
803
        return $self->_status_error("done","Error: access denied to user ".$owner->name);
    }
Francesc Guasch's avatar
Francesc Guasch committed
804

805
    $self->_check_downloading();
Francesc Guasch's avatar
Francesc Guasch committed
806
807
}

808
809
810
811
sub _check_downloading($self) {
    my $id_iso = $self->defined_arg('id_iso');
    my $iso_file = $self->defined_arg('iso_file');

Francesc Guasch's avatar
Francesc Guasch committed
812
813
    $iso_file = '' if $iso_file && $iso_file eq '<NONE>';

814
815
    return if !$id_iso && !$iso_file;

816
    my $sth = $$CONNECTOR->dbh->prepare(
Francesc Guasch's avatar
Francesc Guasch committed
817
        "SELECT id,downloading,device,has_cd,name,url "
818
819
820
821
        ." FROM iso_images "
        ." WHERE (id=? or device=?) "
    );
    $sth->execute($id_iso,$iso_file);
Francesc Guasch's avatar
Francesc Guasch committed
822
823
824
825
    my ($id_iso2,$downloading, $device, $has_cd, $iso_name, $iso_url)
        = $sth->fetchrow;

    return if !$downloading && $device;
826

827
    my $req_download = $self->_search_request('download', id_iso => $id_iso2);
Francesc Guasch's avatar
Francesc Guasch committed
828
829
830
831
832

    return $self->_status_error("done"
        ,"Error: ISO file required for $iso_name")
    if $has_cd && !$device && !$iso_file && !$iso_url && !$device;

Francesc Guasch's avatar
Francesc Guasch committed
833
    if ($has_cd && !$device && !$iso_file && !$req_download) {
834
835
836
        $req_download = Ravada::Request->download(
            id_iso => $id_iso2
            ,uid => Ravada::Utils::user_daemon->id
837
            ,vm => $self->defined_arg('vm')
838
839
840
841
842
843
844
        );
    }
    if (! $req_download) {
        _mark_iso_downloaded($id_iso2);
    } else {
        $self->after_request($req_download->id);
    }
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
    $sth = $$CONNECTOR->dbh->prepare("SELECT args FROM requests"
            ." WHERE id=?"
    );
    $sth->execute($self->id);
    my $args_json = $sth->fetchrow();
    my $args = decode_json($args_json);

    if (exists $args->{iso_file} && !$args->{iso_file}) {
        delete $args->{iso_file};
        $sth = $$CONNECTOR->dbh->prepare("UPDATE requests set args=?"
            ." WHERE id=?"
        );
        $sth->execute(encode_json($args), $self->id);
    }

860
861
862
863
864
865
866
867
868
869
}

sub _mark_iso_downloaded($id_iso) {
    my $sth = $$CONNECTOR->dbh->prepare("UPDATE iso_images "
        ." set downloading=0 "
        ." WHERE id=?"
    );
    $sth->execute($id_iso);
}

870
871
872
873
874
875
876
sub _search_request($self,$command,%fields) {
    my $query =
        "SELECT id, args FROM requests WHERE command like ?"
        ." AND status <> 'done' ";
    $query .= "AND id <> ".$self->id if $self;
    $query .= " ORDER BY date_req,id DESC ";
    my $sth= $$CONNECTOR->dbh->prepare($query);
877
878
    $sth->execute($command);

879
    my @reqs;
880
881
882
883
884
885
886
887
888
889
890
    while ( my ($id, $args_json) = $sth->fetchrow ) {
        return Ravada::Request->open($id) if !keys %fields;

        my $args = decode_json($args_json);
        my $found=1;
        for my $key (keys %fields) {
            if ( $args->{$key} ne $fields{$key} ) {
                $found = 0;
                last;
            }
        }
891
892
893
894
        next if !$found;
        my $req = Ravada::Request->open($id);
        return $req if !wantarray;
        push @reqs,($req);
895
    }
896
    return @reqs;
897
898
}

Francesc Guasch's avatar
Francesc Guasch committed
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
sub _validate_clone($self
                , $id_base= $self->args('id_domain')
                , $uid=$self->args('uid')) {

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

    if ( !$uid ) {
        $self->status('done');
        $self->error("Error: missing uid");
        return;
    }
    my $user = Ravada::Auth::SQL->search_by_id($uid);
    if ( !$user ) {
        $self->status('done');
        $self->error("Error: user id='$uid' does not exist");
        return;
    }
    return if $user->is_admin;
    return if $user->can_clone_all;
    return $self->_status_error('done'
        ,"Error: user ".$user->name." can not clone.")
        if !$user->can_clone();

    return $self->_status_error('done'
        ,"Error: ".$base->name." is not public.")
        if !$base->is_public;
}

927
sub _last_insert_id {
Francesc Guasch's avatar
Francesc Guasch committed
928
    return Ravada::Utils::last_insert_id($$CONNECTOR->dbh);
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
}

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

Francesc Guasch's avatar
Francesc Guasch committed
956
957
958
959
    for ( 1 .. 10 ) {
        eval {
            my $sth = $$CONNECTOR->dbh->prepare("UPDATE requests set status=? "
                ." WHERE id=?");
960

Francesc Guasch's avatar
Francesc Guasch committed
961
962
963
964
965
966
967
968
969
            $status = substr($status,0,64);

            $sth->execute($status, $self->{id});
            $sth->finish;
        };
        last if !$@;
        die $@ if $@ !~ /Deadlock found/;
        warn "Warning: retrying '$@'";
    }
970
971
972
973
974
975

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

Francesc Guasch's avatar
Francesc Guasch committed
976
977
978
979
980
sub _status_error($self, $status, $error) {
    $self->status($status);
    return $self->error($error);
}

Francesc Guasch's avatar
Francesc Guasch committed
981
982
983
984
985
986
=head2 at

Sets the time when the request will be scheduled

=cut

Francesc Guasch's avatar
Francesc Guasch committed
987
988
989
990
991
992
sub at($self, $value) {
    my $sth = $$CONNECTOR->dbh->prepare("UPDATE requests set at_time=? "
            ." WHERE id=?");
    $sth->execute($value, $self->{id});
}

993
994
995
996
997
998
999
1000
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;
}
For faster browsing, not all history is shown. View entire blame