Front.pm 36.8 KB
Newer Older
1
2
3
4
5
package Ravada::Front;

use strict;
use warnings;

6
7
8
9
10
11
=head1 NAME

Ravada::Front - Web Frontend library for Ravada

=cut

12
use Carp qw(carp);
Francesc Guasch's avatar
Francesc Guasch committed
13
use DateTime;
14
use DateTime::Format::DateParse;
15
use Hash::Util qw(lock_hash);
Francesc Guasch's avatar
Francesc Guasch committed
16
use IPC::Run3 qw(run3);
17
18
19
use JSON::XS;
use Moose;
use Ravada;
20
use Ravada::Auth::LDAP;
21
use Ravada::Front::Domain;
22
use Ravada::Front::Domain::KVM;
23
24
use Ravada::Network;

Francesc Guasch's avatar
Francesc Guasch committed
25
26
27
use feature qw(signatures);
no warnings "experimental::signatures";

28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
use Data::Dumper;

has 'config' => (
    is => 'ro'
    ,isa => 'Str'
);
has 'connector' => (
        is => 'rw'
);
has 'backend' => (
    is => 'ro',
    isa => 'Ravada'

);

has 'fork' => (
    is => 'rw'
    ,isa => 'Int'
    ,default => 1
);

our $CONNECTOR;# = \$Ravada::CONNECTOR;
our $TIMEOUT = 20;
our @VM_TYPES = ('KVM');
our $DIR_SCREENSHOTS = "/var/www/img/screenshots";

our %VM;
55
our %VM_ID;
56
our $PID_FILE_BACKEND = '/var/run/rvd_back.pid';
57

Francesc Guasch's avatar
Francesc Guasch committed
58
our $LOCAL_TZ = DateTime::TimeZone->new(name => 'local');
Francesc Guasch's avatar
Francesc Guasch committed
59
60
61
62
63
64
65
###########################################################################
#
# method modifiers
#

around 'list_machines' => \&_around_list_machines;

66
67
68
69
70
71
72
73
74
75
76
=head2 BUILD

Internal constructor

=cut

sub BUILD {
    my $self = shift;
    if ($self->connector) {
        $CONNECTOR = $self->connector;
    } else {
77
        Ravada::_init_config($self->config()) if $self->config;
78
79
        $CONNECTOR = Ravada::_connect_dbh();
    }
80
81
    Ravada::_init_config($self->config()) if $self->config;
    Ravada::Auth::init($Ravada::CONFIG);
82
    $CONNECTOR->dbh();
Francesc Guasch's avatar
Francesc Guasch committed
83
    @VM_TYPES = @{$Ravada::CONFIG->{vm}};
84
85
86
87
88
89
90
91
92
93
}

=head2 list_bases

Returns a list of the base domains as a listref

    my $bases = $rvd_front->list_bases();

=cut

94
95
sub list_bases($self, %args) {
    $args{is_base} = 1;
Francesc Guasch's avatar
Francesc Guasch committed
96
    my $query = "SELECT name, id, is_base, id_owner FROM domains "
97
98
99
100
101
102
        ._where(%args)
        ." ORDER BY name";

    my $sth = $CONNECTOR->dbh->prepare($query);
    $sth->execute(map { $args{$_} } sort keys %args);

103
104
105
106
107
108
    my @bases = ();
    while ( my $row = $sth->fetchrow_hashref) {
        my $domain;
        eval { $domain   = $self->search_domain($row->{name}) };
        next if !$domain;
        $row->{has_clones} = $domain->has_clones;
Francesc Guasch's avatar
Francesc Guasch committed
109
        $row->{is_locked} = 0 if !exists $row->{is_locked};
110
        delete $row->{spice_password};
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
        push @bases, ($row);
    }
    $sth->finish;

    return \@bases;
}

=head2 list_machines_user

Returns a list of machines available to the user

If the user has ever clone the base, it shows this information. It show the
base data if not.

Arguments: user

Returns: listref of machines

=cut

131
sub list_machines_user($self, $user, $access_data={}) {
132
    my $sth = $CONNECTOR->dbh->prepare(
133
        "SELECT id,name,is_public, description, screenshot, id_owner"
134
        ." FROM domains "
135
        ." WHERE is_base=1"
136
137
        ." ORDER BY name "
    );
138
    my ($id, $name, $is_public, $description, $screenshot, $id_owner);
139
    $sth->execute;
140
    $sth->bind_columns(\($id, $name, $is_public, $description, $screenshot, $id_owner));
141

Francesc Guasch's avatar
Francesc Guasch committed
142
    my $bookings_enabled = $self->setting('/backend/bookings');
143
    my @list;
Francesc Guasch's avatar
Francesc Guasch committed
144

145
    while ( $sth->fetch ) {
Francesc Guasch's avatar
Francesc Guasch committed
146
147
148
149

        # check if enabled settings and this user not allowed
        next if $bookings_enabled && !Ravada::Front::Domain->open($id)->allowed_booking($user);

150
151
152
153
154
        my $is_active = 0;
        my $clone = $self->search_clone(
            id_owner =>$user->id
            ,id_base => $id
        );
155
        next unless $clone || $user->is_admin || ($is_public && $user->allowed_access($id));
156
        my %base = ( id => $id, name => $name
157
            , is_public => ($is_public or 0)
158
            , screenshot => ($screenshot or '')
159
            , description => ($description or '')
160
161
162
163
            , is_active => 0
            , id_clone => undef
            , name_clone => undef
            , is_locked => undef
164
            , can_hibernate => 0
165
166
167
168
        );

        if ($clone) {
            $base{is_locked} = $clone->is_locked;
Francesc Guasch's avatar
Francesc Guasch committed
169
            if ($clone->is_active && !$clone->is_locked && $user->can_screenshot) {
170
171
172
173
174
175
                if (!Ravada::Request::done_recently(undef,10,'screenshot')) {
                    my $req = Ravada::Request->screenshot(
                        id_domain => $clone->id
                        ,_no_duplicate => 1
                    );
                }
176
177
            }
            $base{name_clone} = $clone->name;
178
            $base{screenshot} = ( $clone->_data('screenshot')
179
                                or $base{screenshot});
180
181
            $base{description} = ( $clone->_data('description')
                                or $base{description});
182
            $base{is_active} = $clone->is_active;
Francesc Guasch's avatar
Francesc Guasch committed
183
184
185
            $base{id_clone} = $clone->id;
            $base{can_remove} = 0;
            $base{can_remove} = 1 if $user->can_remove && $clone->id_owner == $user->id;
186
            $base{can_hibernate} = 1 if $clone->is_active && !$clone->is_volatile;
187
        }
188
        next if !$self->_access_allowed($id, $base{id_clone}, $access_data);
189
190
191
192
193
194
195
196
        $base{screenshot} =~ s{^/var/www}{};
        lock_hash(%base);
        push @list,(\%base);
    }
    $sth->finish;
    return \@list;
}

197
198
199
200
201
202
203
204
205
206
207
208
209
sub _access_allowed($self, $id_base, $id_clone, $access_data) {
    if ($id_clone) {
        my $clone = Ravada::Front::Domain->open($id_clone);
        my $allowed = $clone->access_allowed(%$access_data);
        return $allowed if $allowed;
    }
    my $base = Ravada::Front::Domain->open($id_base);

    my $allowed = $base->access_allowed(%$access_data);
    return 1 if !defined $allowed;
    return $allowed;

}
210

211
212
sub list_machines($self, $user, @filter) {
    return $self->list_domains(@filter) if $user->can_list_machines();
serk's avatar
serk committed
213

Francesc Guasch's avatar
Francesc Guasch committed
214
    my @list = ();
215
    push @list,(@{filter_base_without_clones($self->list_domains(@filter))}) if $user->can_list_clones();
216
217
    push @list,(@{$self->_list_own_clones($user)}) if $user->can_list_clones_from_own_base();
    push @list,(@{$self->_list_own_machines($user)}) if $user->can_list_own_machines();
robertperez-upc's avatar
robertperez-upc committed
218

Francesc Guasch's avatar
Francesc Guasch committed
219
220
221
222
    return [@list] if scalar @list < 2;

    my %uniq = map { $_->{name} => $_ } @list;
    return [sort { $a->{name} cmp $b->{name} } values %uniq];
223
224
}

Francesc Guasch's avatar
Francesc Guasch committed
225
sub _init_available_actions($user, $m) {
robertperez-upc's avatar
robertperez-upc committed
226
  eval { $m->{can_shutdown} = $user->can_shutdown($m->{id}) };
Francesc Guasch's avatar
Francesc Guasch committed
227

Roberto P. Rubio's avatar
Roberto P. Rubio committed
228
229
        $m->{can_start} = 0;
        $m->{can_start} = 1 if $m->{id_owner} == $user->id || $user->is_admin;
Francesc Guasch's avatar
Francesc Guasch committed
230

Roberto P. Rubio's avatar
Roberto P. Rubio committed
231
        $m->{can_reboot} = $m->{can_shutdown} && $m->{can_start};
Francesc Guasch's avatar
Francesc Guasch committed
232

Roberto P. Rubio's avatar
Roberto P. Rubio committed
233
234
        $m->{can_view} = 0;
        $m->{can_view} = 1 if $m->{id_owner} == $user->id || $user->is_admin;
235

Roberto P. Rubio's avatar
Roberto P. Rubio committed
236
237
238
239
        $m->{can_manage} = ( $user->can_manage_machine($m->{id}) or 0);
        eval {
        $m->{can_change_settings} = ( $user->can_change_settings($m->{id}) or 0);
        };
Roberto P. Rubio's avatar
Roberto P. Rubio committed
240
241
242
        #may have been deleted just now
        next if $@ && $@ =~ /Unknown domain/;
        die $@ if $@;
243

Roberto P. Rubio's avatar
Roberto P. Rubio committed
244
        $m->{can_hibernate} = 0;
Roberto P. Rubio's avatar
Roberto P. Rubio committed
245
        $m->{can_hibernate} = 1 if $user->can_shutdown($m->{id})
Roberto P. Rubio's avatar
Roberto P. Rubio committed
246
        && !$m->{is_volatile};
Francesc Guasch's avatar
Francesc Guasch committed
247
        warn $@ if $@;
robertperez-upc's avatar
robertperez-upc committed
248
}
249

robertperez-upc's avatar
robertperez-upc committed
250
251
252
sub _around_list_machines($orig, $self, $user, @filter) {
    my $machines = $self->$orig($user, @filter);
    for my $m (@$machines) {
Francesc Guasch's avatar
Francesc Guasch committed
253
        _init_available_actions($user, $m);
254
        $m->{id_base} = undef if !exists $m->{id_base};
255
        lock_hash(%$m);
Francesc Guasch's avatar
Francesc Guasch committed
256
257
258
259
    }
    return $machines;
}

260
261
262
263
264
265
266
267
268
269
270
271
=pod

sub search_clone_data {
    my $self = shift;
    my %args = @_;
    my $query = "SELECT * FROM domains WHERE "
        .(join(" AND ", map { "$_ = ? " } sort keys %args));

    my $sth = $CONNECTOR->dbh->prepare($query);
    $sth->execute( map { $args{$_} } sort keys %args );
    my $row = $sth->fetchrow_hashref;
    return ( $row or {});
robertperez-upc's avatar
robertperez-upc committed
272

273
274
275
276
277
278
279
280
281
282
283
284
}

=cut

=head2 list_domains

Returns a list of the domains as a listref

    my $bases = $rvd_front->list_domains();

=cut

285
sub list_domains($self, %args) {
286

287
    my $query = "SELECT d.name, d.id, id_base, is_base, id_vm, status, is_public "
Francesc Guasch's avatar
Francesc Guasch committed
288
        ."      ,vms.name as node , is_volatile, client_status, id_owner "
Francesc Guasch's avatar
Francesc Guasch committed
289
        ."      ,comment, is_pool"
Francesc Guasch's avatar
Francesc Guasch committed
290
        ."      ,d.date_changed"
291
292
        ." FROM domains d LEFT JOIN vms "
        ."  ON d.id_vm = vms.id ";
293
294
295
296

    my $where = '';
    for my $field ( sort keys %args ) {
        $where .= " AND " if $where;
297
298
299
300
301
        if (!defined $args{$field}) {
            $where .= " $field IS NULL ";
            delete $args{$field};
            next;
        }
302
        $where .= " d.$field=?"
303
304
305
    }
    $where = "WHERE $where" if $where;

306
    my $sth = $CONNECTOR->dbh->prepare("$query $where ORDER BY d.id");
307
    $sth->execute(map { $args{$_} } sort keys %args);
robertperez-upc's avatar
robertperez-upc committed
308

309
310
    my @domains = ();
    while ( my $row = $sth->fetchrow_hashref) {
Francesc Guasch's avatar
Francesc Guasch committed
311
        for (qw(is_locked is_hibernated is_paused
312
313
314
                has_clones )) {
            $row->{$_} = 0;
        }
315
        my $domain ;
316
        my $t0 = time;
317
        eval { $domain   = $self->search_domain($row->{name}) };
318
        warn $@ if $@;
Francesc Guasch's avatar
Francesc Guasch committed
319
        $row->{remote_ip} = undef;
320
321
322
323
        if ( $row->{is_volatile} && !$domain ) {
            $self->_remove_domain_db($row->{id});
            next;
        }
324
325
        $row->{has_clones} = 0 if !exists $row->{has_clones};
        $row->{is_locked} = 0 if !exists $row->{is_locked};
Francesc Guasch's avatar
Francesc Guasch committed
326
327
        $row->{is_active} = 0;
        $row->{remote_ip} = undef;
328
329
        if ( $domain ) {
            $row->{is_locked} = $domain->is_locked;
Francesc Guasch's avatar
Francesc Guasch committed
330
            $row->{is_hibernated} = ( $domain->is_hibernated or 0);
331
            $row->{is_paused} = 1 if $domain->is_paused;
332
            $row->{is_active} = 1 if $row->{status} =~ /active|starting/;
333
            $row->{has_clones} = $domain->has_clones;
334
335
336
#            $row->{disk_size} = ( $domain->disk_size or 0);
#            $row->{disk_size} /= (1024*1024*1024);
#            $row->{disk_size} = 1 if $row->{disk_size} < 1;
337
            $row->{remote_ip} = $domain->remote_ip if $row->{is_active};
338
            $row->{node} = $domain->_vm->name if $domain->_vm;
339
            $row->{remote_ip} = $domain->client_status
340
                if $domain->client_status && $domain->client_status !~ /^connected/;
341
            if  ($domain->remote_ip && $domain->client_status && $domain->client_status =~ /^connected \((.*?)\)/ ) {
342
343
                $row->{remote_ip} = $domain->remote_ip.".$1";
            }
344
            $row->{autostart} = $domain->_data('autostart');
Francesc Guasch's avatar
Francesc Guasch committed
345
346
347
348
349
350
351
352
353
            if (!$row->{status} ) {
                if ($row->{is_active}) {
                    $row->{status} = 'active';
                } elsif ($row->{is_hibernated}) {
                    $row->{status} = 'hibernated';
                } else {
                    $row->{status} = 'down';
                }
            }
354
        }
355
        delete $row->{spice_password};
356
357
358
359
360
361
        push @domains, ($row);
    }
    $sth->finish;

    return \@domains;
}
serk's avatar
serk committed
362

serk's avatar
serk committed
363
364
=head2 filter_base_without_clones

robertperez-upc's avatar
robertperez-upc committed
365
filters the list of domains and drops all machines that are unacessible and
serk's avatar
serk committed
366
367
368
369
370
371
372
373
374
375
bases with 0 machines accessible

=cut

sub filter_base_without_clones($domains) {
    my @list;
    my $size_domains = scalar(@$domains);
    for (my $i = 0; $i < $size_domains; ++$i) {
        if (@$domains[$i]->{is_base}) {
            for (my $j = 0; $j < $size_domains; ++$j) {
376
377
378
379
                if ($j != $i && !($domains->[$j]->{is_base})
                        && defined $domains->[$j]->{id_base}
                        && $domains->[$j]->{id_base} eq $domains->[$i]->{id}) {
                    push @list, ($domains->[$i]);
serk's avatar
serk committed
380
381
382
383
384
385
386
387
388
389
390
                    last;
                }
            }
        }
        else {
            push @list, (@$domains[$i]);
        }
    }
    return \@list;
}

391
sub _list_own_clones($self, $user) {
serk's avatar
serk committed
392
393
394
395
396
397
398
399
    my $machines = $self->list_bases( id_owner => $user->id );
    for my $base (@$machines) {
        confess "ERROR: BAse without id ".Dumper($base) if !$base->{id};
        push @$machines,@{$self->list_domains( id_base => $base->{id} )};
    }
    return $machines;
}

400
sub _list_own_machines($self, $user) {
serk's avatar
serk committed
401
402
403
404
405
406
407
408
409
    my $machines = $self->list_domains(id_owner => $user->id);
    for my $clone (@$machines) {
        next if !$clone->{id_base};
        push @$machines,@{$self->list_domains( id => $clone->{id_base} )};
    }
    return $machines;
}


410
411
412
413
414
415
416
417
418
sub _where(%args) {
    my $where = '';
    for my $field ( sort keys %args ) {
        $where .= " AND " if $where;
        $where .= " $field=?"
    }
    $where = "WHERE $where" if $where;
    return $where;
}
419

420
421
422
423
424
425
426
427
428
=head2 list_clones
  Returns a list of the domains that are clones as a listref

      my $clones = $rvd_front->list_clones();
=cut

sub list_clones {
  my $self = shift;
  my %args = @_;
robertperez-upc's avatar
robertperez-upc committed
429

430
  my $domains = $self->list_domains();
431
432
433
434
435
436
  my @clones;
  for (@$domains ) {
    if($_->{id_base}) { push @clones, ($_); }
  }
  return \@clones;
}
437
438
439
440
441
442
sub _remove_domain_db($self, $id) {
    my $sth = $CONNECTOR->dbh->prepare("DELETE FROM domains WHERE id=?");
    $sth->execute($id);
    $sth->finish;
}

443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
=head2 domain_info

Returns information of a domain

    my $info = $rvd_front->domain_info( id => $id);
    my $info = $rvd_front->domain_info( name => $name);

=cut

sub domain_info {
    my $self = shift;

    my $domains = $self->list_domains(@_);
    return $domains->[0];
}

=head2 domain_exists

Returns true if the domain name exists

    if ($rvd->domain_exists('domain_name')) {
        ...
    }

=cut

sub domain_exists {
    my $self = shift;
    my $name = shift;

    my $sth = $CONNECTOR->dbh->prepare(
        "SELECT id FROM domains "
475
476
477
478
        ." WHERE name=? "
        ."    AND ( is_volatile = 0 "
        ."          OR is_volatile=1 AND status = 'active' "
        ."         ) "
479
480
481
482
483
484
485
486
    );
    $sth->execute($name);
    my ($id) = $sth->fetchrow;
    $sth->finish;
    return 0 if !defined $id;
    return 1;
}

487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511

=head2 node_exists

Returns true if the node name exists

    if ($rvd->node('node_name')) {
        ...
    }

=cut

sub node_exists {
    my $self = shift;
    my $name = shift;

    my $sth = $CONNECTOR->dbh->prepare(
        "SELECT id FROM vms"
        ." WHERE name=? "
    );
    $sth->execute($name);
    my ($id) = $sth->fetchrow;
    $sth->finish;
    return 0 if !defined $id;
    return 1;
}
512

513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
=head2 list_vm_types

Returns a reference to a list of Virtual Machine Managers known by the system

=cut

sub list_vm_types {
    my $self = shift;

    return $self->{cache}->{vm_types} if $self->{cache}->{vm_types};

    my $result = [@VM_TYPES];

    $self->{cache}->{vm_types} = $result if $result->[0];

    return $result;
}

Francesc Guasch's avatar
Francesc Guasch committed
531
532
533
534
535
536
=head2 list_vms

Returns a list of Virtual Managers

=cut

537
sub list_vms($self, $type=undef) {
Francesc Guasch's avatar
Francesc Guasch committed
538

539
    my $sql = "SELECT id,name,hostname,is_active, vm_type, enabled FROM vms ";
Francesc Guasch's avatar
Francesc Guasch committed
540

541
542
543
544
545
546
    my @args = ();
    if ($type) {
        $sql .= "WHERE (vm_type=? or vm_type=?)";
        my $type2 = $type;
        $type2 = 'qemu' if $type eq 'KVM';
        @args = ( $type, $type2);
Francesc Guasch's avatar
Francesc Guasch committed
547
    }
548
    my $sth = $CONNECTOR->dbh->prepare($sql." ORDER BY vm_type,name");
549
    $sth->execute(@args);
Francesc Guasch's avatar
Francesc Guasch committed
550

Francesc Guasch's avatar
Francesc Guasch committed
551
552
    my @list;
    while (my $row = $sth->fetchrow_hashref) {
553
554
        $row->{bases}= $self->_list_bases_vm($row->{id});
        $row->{machines}= $self->_list_machines_vm($row->{id});
Francesc Guasch's avatar
Francesc Guasch committed
555
        $row->{type} = $row->{vm_type};
Carlos Juan's avatar
Carlos Juan committed
556
        $row->{action_remove} = 'disabled' if length defined $row->{machines}[0];
Carlos Juan's avatar
Carlos Juan committed
557
        $row->{action_remove} = 'disabled' if $row->{hostname} eq 'localhost';
Carlos Juan's avatar
Carlos Juan committed
558
        $row->{action_remove} = 'disabled' if length defined $row->{bases}[0];
Francesc Guasch's avatar
Francesc Guasch committed
559
560
        $row->{is_local} = 0;
        $row->{is_local} = 1  if $row->{hostname} =~ /^(localhost|127)/;
Francesc Guasch's avatar
Francesc Guasch committed
561
        delete $row->{vm_type};
Francesc Guasch's avatar
Francesc Guasch committed
562
563
564
565
        lock_hash(%$row);
        push @list,($row);
    }
    $sth->finish;
566
    return @list;
Francesc Guasch's avatar
Francesc Guasch committed
567
568
}

569
sub _list_bases_vm($self, $id_node) {
Francesc Guasch's avatar
Francesc Guasch committed
570
571
572
573
574
    my $sth = $CONNECTOR->dbh->prepare(
        "SELECT d.id FROM domains d,bases_vm bv"
        ." WHERE d.is_base=1"
        ."  AND d.id = bv.id_domain "
        ."  AND bv.id_vm=?"
575
        ."  AND bv.enabled=1"
Francesc Guasch's avatar
Francesc Guasch committed
576
    );
577
578
    my @bases;
    $sth->execute($id_node);
Francesc Guasch's avatar
Francesc Guasch committed
579
    while ( my ($id_domain) = $sth->fetchrow ) {
580
        push @bases,($id_domain);
Francesc Guasch's avatar
Francesc Guasch committed
581
582
    }
    $sth->finish;
583
    return \@bases;
Francesc Guasch's avatar
Francesc Guasch committed
584
585
}

586
587
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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
sub _list_bases_vm_all($self, $id_node) {

    my $sth = $CONNECTOR->dbh->prepare(
        "SELECT d.id, d.name FROM domains d, vms v "
        ." WHERE is_base=? AND vm=v.vm_type"
        ."   AND d.vm =v.vm_type"
        ."   AND v.id=?"
        ." ORDER BY d.name "
    );
    $sth->execute(1, $id_node);
    my $sth_bv = $CONNECTOR->dbh->prepare(
        "SELECT bv.enabled FROM bases_vm bv, domains d "
        ." WHERE bv.id_domain=? AND bv.id_vm=?"
        ."   AND d.id = bv.id_domain "
    );
    my ($id_domain, $name_domain);
    $sth->bind_columns(\($id_domain, $name_domain));

    my $sth_clones = $CONNECTOR->dbh->prepare(
        "SELECT count(*) FROM domain_instances "
        ." WHERE id_vm=? AND id_domain IN (SELECT id FROM domains WHERE id_base=?) "
    );

    my @bases;
    while ( $sth->fetch ) {
        $sth_bv->execute($id_domain, $id_node);
        my ($enabled) = $sth_bv->fetchrow;

        $sth_clones->execute($id_node,$id_domain);
        my ($n_clones) = $sth_clones->fetchrow();

        push @bases,{
                  id => $id_domain
               ,name => $name_domain
             ,clones => $n_clones
            ,enabled => ( $enabled or 0)
        };
    }

    return \@bases;
}

628
629
sub _list_machines_vm($self, $id_node) {
    my $sth = $CONNECTOR->dbh->prepare(
630
        "SELECT d.id, name FROM domains d"
631
632
633
634
635
        ." WHERE d.status='active'"
        ."  AND d.id_vm=?"
    );
    my @bases;
    $sth->execute($id_node);
636
637
    while ( my ($id_domain, $name) = $sth->fetchrow ) {
        push @bases,({ id => $id_domain, name => $name });
638
639
640
641
    }
    $sth->finish;
    return \@bases;
}
642

643

644
645
646
647
648
649
650
651
=head2 list_iso_images

Returns a reference to a list of the ISO images known by the system

=cut

sub list_iso_images {
    my $self = shift;
652
653
654
    my $vm_name = shift;

    my $vm;
655
656
657
658
659
660
661
662
663
664
665
666
667

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

668
=head2 iso_file
joelalju's avatar
joelalju committed
669
670
671
672
673

Returns a reference to a list of the ISOs known by the system

=cut

Fernando Verdugo's avatar
Fernando Verdugo committed
674
sub iso_file ($self, $vm_type) {
675
676
677
678

    my $cache = $self->_cache_get("list_isos");
    return $cache if $cache;

Fernando Verdugo's avatar
Fernando Verdugo committed
679
680
681
    my $req = Ravada::Request->list_isos(
        vm_type => $vm_type
    );
682
    return [] if !$req;
Fernando Verdugo's avatar
Fernando Verdugo committed
683
684
685
    $self->wait_request($req);
    return [] if $req->status ne 'done';

686
687
    my $isos = [];
    $isos = decode_json($req->output()) if $req->output;
Fernando Verdugo's avatar
Fernando Verdugo committed
688

689
690
    $self->_cache_store("list_isos",$isos);

Fernando Verdugo's avatar
Fernando Verdugo committed
691
    return $isos;
joelalju's avatar
joelalju committed
692
693
}

694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
=head2 list_lxc_templates

Returns a reference to a list of the LXC templates known by the system

=cut


sub list_lxc_templates {
    my $self = shift;

    my @template;
    my $sth = $CONNECTOR->dbh->prepare(
        "SELECT * FROM lxc_templates ORDER BY name"
    );
    $sth->execute;
    while (my $row = $sth->fetchrow_hashref) {
        push @template,($row);
    }
    $sth->finish;
    return \@template;

}

=head2 list_users

Returns a reference to a list of the users

=cut

723
sub list_users($self,$name=undef) {
724
    my $sth = $CONNECTOR->dbh->prepare("SELECT id, name FROM users ");
725
    $sth->execute();
robertperez-upc's avatar
robertperez-upc committed
726

727
728
    my @users = ();
    while ( my $row = $sth->fetchrow_hashref) {
729
        next if defined $name && $row->{name} !~ /$name/;
730
731
732
733
734
735
736
        push @users, ($row);
    }
    $sth->finish;

    return \@users;
}

737

Francesc Guasch's avatar
Francesc Guasch committed
738
739
740
741
742
743
744
745
=head2 list_bases_network

Returns a reference to a list to all the bases in a network

    my $list = $rvd_front->list_bases_network($id_network);

=cut

746
747
748
749
750
sub list_bases_network($self, $id_network) {
    my $sth = $CONNECTOR->dbh->prepare("SELECT * FROM networks where name = 'default'");
    $sth->execute;
    my $default = $sth->fetchrow_hashref();
    $sth->finish;
751
752
753
    lock_hash(%$default);
    warn "Warning: all_domains and no_domains both true for default network ".Dumper($default)
    if $default->{all_domains} && $default->{no_domains};
754
755
756
757
758
759
760
761
762
763
764
765
766

    my $sth_nd = $CONNECTOR->dbh->prepare("SELECT id,allowed,anonymous FROM domains_network"
            ." WHERE id_domain=? AND id_network=? "
    );

    $sth = $CONNECTOR->dbh->prepare("SELECT * FROM domains where is_base=1 " 
        ." ORDER BY name");
    $sth->execute();
    my @bases;
    while (my $row = $sth->fetchrow_hashref) {

        $sth_nd->execute($row->{id}, $id_network);
        my ($id,$allowed, $anonymous) = $sth_nd->fetchrow;
767
768
769

        $row->{anonymous} = ( $anonymous or 0);

770
771
772
        if (defined $allowed) {
            $row->{allowed} = $allowed;
        } else {
773
774
            $row->{allowed} = $default->{all_domains};
            $row->{allowed} = 0 if $default->{no_domains};
775
776
777
778
779
780
781
782
783
        }

        lock_hash(%$row);
        push @bases,($row);
    }

    return \@bases;
}

784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
=head2 create_domain

Request the creation of a new domain or virtual machine

    # TODO: document the args here
    my $req = $rvd_front->create_domain( ... );

=cut

sub create_domain {
    my $self = shift;
    return Ravada::Request->create_domain(@_);
}

=head2 wait_request

Waits for a request for some seconds.

=head3 Arguments

robertperez-upc's avatar
robertperez-upc committed
804
=over
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
864
865
866
867
868
869

=item * request

=item * timeout (optional defaults to $Ravada::Front::TIMEOUT

=back

Returns: the request

=cut

sub wait_request {
    my $self = shift;
    my $req = shift or confess "Missing request";

    my $timeout = ( shift or $TIMEOUT );

    if ( $self->backend ) {
        if ($self->fork ) {
            $self->backend->process_requests();
        } else {
            $self->backend->_process_requests_dont_fork();
        }
    }

    for ( 1 .. $timeout ) {
        last if $req->status eq 'done';
        sleep 1;
    }
    $req->status("timeout")
        if $req->status eq 'working';
    return $req;

}

=head2 ping_backend

Checks if the backend is alive.

Return true if alive, false otherwise.

=cut

sub ping_backend {
    my $self = shift;

    my $req = Ravada::Request->ping_backend();
    $self->wait_request($req, 2);

    return 1 if $req->status() eq 'done';
    return 0;
}

sub _ping_backend_localhost {
    my $self = shift;
    return 1 if -e $PID_FILE_BACKEND;
    # TODO check the process with pid $PID_FILE_BACKEND is really alive
    return;
}

=head2 open_vm

Connects to a Virtual Machine Manager ( or VMM ( or VM )).
Returns a read-only connection to the VM.

joelalju's avatar
joelalju committed
870
871
  my $vm = $front->open_vm('KVM');

872
873
874
875
876
877
878
=cut

sub open_vm {
    my $self = shift;
    my $type = shift or confess "I need vm type";
    my $class = "Ravada::VM::$type";

879
    if (my $vm = $VM{$type}) {
880
        if (!$vm->ping || !$vm->is_alive) {
881
882
883
884
885
            $vm->disconnect();
            $vm->connect();
        } else {
            return $vm;
        }
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
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
    }

    my $proto = {};
    bless $proto,$class;

    my $vm = $proto->new(readonly => 1);
    eval { $vm->vm };
    warn $@ if $@;
    return if $@;
    return $vm if $0 =~ /\.t$/;

    $VM{$type} = $vm;
    return $vm;
}

=head2 search_vm

Calls to open_vm

=cut

sub search_vm {
    return open_vm(@_);
}

=head2 search_clone

Search for a clone of a domain owned by an user.

    my $domain_clone = $rvd_front->(id_base => $domain_base->id , id_owner => $user->id);

=head3 arguments

=over

=item id_base : The id of the base domain

=item id_user

=back

Returns the domain

=cut

sub search_clone {
    my $self = shift;
    my %args = @_;
    confess "Missing id_owner " if !$args{id_owner};
    confess "Missing id_base" if !$args{id_base};

    my ($id_base , $id_owner) = ($args{id_base} , $args{id_owner} );

    delete $args{id_base};
    delete $args{id_owner};

    confess "Unknown arguments ".Dumper(\%args) if keys %args;

    my $sth = $CONNECTOR->dbh->prepare(
        "SELECT id,name FROM domains "
946
        ." WHERE id_base=? AND id_owner=? AND (is_base=0 OR is_base=NULL)"
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
    );
    $sth->execute($id_base, $id_owner);

    my ($id_domain, $name) = $sth->fetchrow;
    $sth->finish;

    return if !$id_domain;

    return $self->search_domain($name);

}

=head2 search_domain

Searches a domain by name

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

Returns a Ravada::Domain object

=cut

sub search_domain {
    my $self = shift;

    my $name = shift;

974
    my $sth = $CONNECTOR->dbh->prepare("SELECT id, vm FROM domains WHERE name=?");
975
    $sth->execute($name);
976
    my ($id, $tipo) = $sth->fetchrow or return;
977

Francesc Guasch's avatar
Francesc Guasch committed
978
    return Ravada::Front::Domain->open($id);
979
980
981
982
983
984
985
986
}

=head2 list_requests

Returns a list of ruquests : ( id , domain_name, status, error )

=cut

987
sub list_requests($self, $id_domain_req=undef, $seconds=60) {
988

Francesc Guasch's avatar
Francesc Guasch committed
989
    my @now = localtime(time-$seconds);
990
991
992
993
994
    $now[4]++;
    for (0 .. 4) {
        $now[$_] = "0".$now[$_] if length($now[$_])<2;
    }
    my $time_recent = ($now[5]+=1900)."-".$now[4]."-".$now[3]
Francesc Guasch's avatar
Francesc Guasch committed
995
        ." ".$now[2].":".$now[1].":".$now[0];
996
    my $sth = $CONNECTOR->dbh->prepare(
997
        "SELECT requests.id, command, args, requests.date_changed, requests.status"
998
999
1000
1001
            ." ,requests.error, id_domain ,domains.name as domain"
        ." FROM requests left join domains "
        ."  ON requests.id_domain = domains.id"
        ." WHERE "
1002
        ."    requests.status <> 'done' "
1003
1004
        ."  OR ( requests.date_changed >= ?) "
        ." ORDER BY requests.date_changed "
1005
    );
1006
    $sth->execute($time_recent);
1007
    my @reqs;
1008
    my ($id_request, $command, $j_args, $date_changed, $status
1009
        , $error, $id_domain, $domain);
1010
    $sth->bind_columns(\($id_request, $command, $j_args, $date_changed, $status
1011
        , $error, $id_domain, $domain));
1012
1013

    while ( $sth->fetch) {
Francesc Guasch's avatar
Francesc Guasch committed
1014
        my $epoch_date_changed = time;
Francesc Guasch's avatar
Francesc Guasch committed
1015
1016
1017
1018
1019
1020
1021
1022
1023
        if ($date_changed) {
            my ($y,$m,$d,$hh,$mm,$ss) = $date_changed =~ /(\d{4})-(\d\d)-(\d\d) (\d+):(\d+):(\d+)/;
            if ($y)  {
                $epoch_date_changed = DateTime->new(year => $y, month => $m, day => $d
                    ,hour => $hh, minute => $mm, second => $ss
                    ,time_zone => $LOCAL_TZ
                )->epoch;
            }
        }
1024
1025
        next if $command eq 'enforce_limits'
                || $command eq 'refresh_storage'
1026
                || $command eq 'refresh_machine'
1027
                || $command eq 'ping_backend'
1028
                || $command eq 'cleanup'
Francesc Guasch's avatar
Francesc Guasch committed
1029
                || $command eq 'screenshot'
Francesc Guasch's avatar
Francesc Guasch committed
1030
                || $command eq 'connect_node'
1031
                || $command eq 'post_login'
Francesc Guasch's avatar
Francesc Guasch committed
1032
                || $command eq 'list_network_interfaces'
Fernando Verdugo's avatar
Fernando Verdugo committed
1033
                || $command eq 'list_isos'
Francesc Guasch's avatar
Francesc Guasch committed
1034
                || $command eq 'manage_pools'
1035
                ;
Francesc Guasch's avatar
Francesc Guasch committed
1036
        next if ( $command eq 'force_shutdown'
Roberto P. Rubio's avatar
Roberto P. Rubio committed
1037
                || $command eq 'force_reboot'
1038
1039
                || $command eq 'start'
                || $command eq 'shutdown'
Roberto P. Rubio's avatar
Roberto P. Rubio committed
1040
                || $command eq 'reboot'
1041
                || $command eq 'hibernate'
1042
                )
Francesc Guasch's avatar
Francesc Guasch committed
1043
1044
1045
                && time - $epoch_date_changed > 5
                && $status eq 'done'
                && !$error;
1046
        next if $id_domain_req && defined $id_domain && $id_domain != $id_domain_req;
1047
1048
        my $args;
        $args = decode_json($j_args) if $j_args;
1049

1050
1051
1052
1053
        if (!$domain && $args->{id_domain}) {
            $domain = $args->{id_domain};
        }
        $domain = $args->{name} if !$domain && $args->{name};
1054
1055
1056
1057
1058

        my $message = ( $self->_last_message($id_request) or $error or '');
        $message =~ s/^$command\s+$status(.*)/$1/i;

        push @reqs,{ id => $id_request,  command => $command, date_changed => $date_changed, status => $status, name => $args->{name}
1059
            ,domain => $domain
1060
            ,date => $date_changed
1061
            ,message => $message
Francesc Guasch's avatar
Francesc Guasch committed
1062
            ,error => $error
1063
        };
1064
1065
1066
1067
1068
    }
    $sth->finish;
    return \@reqs;
}

1069
1070
1071
1072
sub _last_message {
    my $self = shift;
    my $id_request = shift;
    my $sth = $CONNECTOR->dbh->prepare(
1073
        "SELECT subject , message FROM messages WHERE id_request=? ORDER BY date_send DESC,id DESC");
1074
1075
1076
1077
1078
    $sth->execute($id_request);
    my ($subject, $message) = $sth->fetchrow;

    return '' if !$subject;

1079
    $subject = '' if $message && $message =~ /^$subject/;
1080
1081
1082
1083
1084
    return "$subject ".($message or '');
    $sth->finish;

}

1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
=head2 search_domain_by_id

  my $domain = $ravada->search_domain_by_id($id);

=cut

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

1095
    my $sth = $CONNECTOR->dbh->prepare("SELECT name, id, id_base, is_base FROM domains WHERE id=?");
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
    $sth->execute($id);

    my $row = $sth->fetchrow_hashref;

    return if !keys %$row;

    lock_hash(%$row);

    return $self->search_domain($row->{name});
}

=head2 start_domain

Request to start a domain.

=head3 arguments

=over

=item user => $user : a Ravada::Auth::SQL user

=item name => $name : the domain name

=item remote_ip => $remote_ip: a Ravada::Auth::SQL user

1121
=back
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159

Returns an object: Ravada::Request.

    my $req = $rvd_front->start_domain(
               user => $user
              ,name => 'mydomain'
        , remote_ip => '192.168.1.1');

=cut

sub start_domain {
    my $self = shift;
    confess "ERROR: Must call start_domain with user=>\$user, name => \$name, remote_ip => \$ip"
        if scalar @_ % 2;

    my %args = @_;

    # TODO check for user argument
    $args{uid} = $args{user}->id    if $args{user};
    delete $args{user};

    return Ravada::Request->start_domain( %args );
}

=head2 list_bases_anonymous

List the available bases for anonymous user in a remote IP

    my $list = $rvd_front->list_bases_anonymous($remote_ip);

=cut

sub list_bases_anonymous {
    my $self = shift;
    my $ip = shift or confess "Missing remote IP";

    my $net = Ravada::Network->new(address => $ip);

serk's avatar
serk committed
1160
1161
1162
1163
    my $sth = $CONNECTOR->dbh->prepare(
        "SELECT id, name, id_base, is_public, file_screenshot "
        ."FROM domains where is_base=1 "
        ."AND is_public=1");
1164
    $sth->execute();
serk's avatar
serk committed
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
    my ($id, $name, $id_base, $is_public, $screenshot);
    $sth->bind_columns(\($id, $name, $id_base, $is_public, $screenshot));

    my @bases;
    while ( $sth->fetch) {
        next if !$net->allowed_anonymous($id);
        my %base = ( id => $id, name => $name
            , is_public => ($is_public or 0)
            , screenshot => ($screenshot or '')
            , is_active => 0
            , id_clone => undef
            , name_clone => undef
            , is_locked => undef
            , can_hibernate => 0
        );
        $base{screenshot} =~ s{^/var/www}{};
        lock_hash(%base);
        push @bases, (\%base);
1183
1184
1185
1186
1187
1188
1189
    }
    $sth->finish;

    return \@bases;

}

robertperez-upc's avatar
robertperez-upc committed
1190
=head2 disconnect_vm
1191
1192
1193
1194
1195
1196
1197
1198
1199

Disconnects all the conneted VMs

=cut

sub disconnect_vm {
    %VM = ();
}

1200
1201
=head2 enable_node

1202
Enables, disables or delete a node
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217

    $rvd->enable_node($id_node, $value);

Returns true if the node is enabled, false otherwise.

=cut

sub enable_node($self, $id_node, $value) {
    my $sth = $CONNECTOR->dbh->prepare("UPDATE vms SET enabled=? WHERE id=?");
    $sth->execute($value, $id_node);
    $sth->finish;

    return $value;
}

1218
1219
1220
1221
1222
1223
=head2 remove_node

Remove new node from the table VMs

=cut

1224
1225
1226
1227
1228
1229
1230
1231
sub remove_node($self, $id_node, $value) {
    my $sth = $CONNECTOR->dbh->prepare("DELETE FROM vms WHERE id=?");
    $sth->execute($id_node);
    $sth->finish;

    return $value;
}

1232
1233
1234
1235
1236
1237
=head2 add_node

Inserts a new node in the table VMs

=cut

1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
sub add_node($self,%arg) {
    my $sql = "INSERT INTO vms "
        ."("
        .join(",",sort keys %arg)
        .")"
        ." VALUES ( ".join(",", map { '?' } keys %arg).")";

    my $sth = $CONNECTOR->dbh->prepare($sql);
    $sth->execute(map { $arg{$_} } sort keys %arg );
    $sth->finish;
1248
1249
1250

    my $req = Ravada::Request->refresh_vms( _force => 1 );
    return $req->id;
1251
1252
}

1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
sub _cache_store($self, $key, $value, $timeout=60) {
    $self->{cache}->{$key} = [ $value, time+$timeout ];
}

sub _cache_get($self, $key) {

    delete $self->{cache}->{$key}
        if exists $self->{cache}->{$key}
            && $self->{cache}->{$key}->[1] < time;

    return if !exists $self->{cache}->{$key};

    return $self->{cache}->{$key}->[0];

}

1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
=head2 list_network_interfaces

Request to list the network interfaces. Returns a reference to the list.

    my $interfaces = $rvd_front->list_network_interfaces(
        vm_type => 'KVM'
        ,type => 'bridge'
        ,user => $user
    )

=cut

Francesc Guasch's avatar
Francesc Guasch committed
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
sub list_network_interfaces($self, %args) {

    my $vm_type = delete $args{vm_type}or confess "Error: missing vm_type";
    my $type = delete $args{type} or confess "Error: missing type";
    my $user = delete $args{user} or confess "Error: missing user";
    my $timeout = delete $args{timeout};
    $timeout = 60 if !defined $timeout;

    confess "Error: Unknown args ".Dumper(\%args) if keys %args;

    my $cache_key = "_interfaces_$type";
    return $self->{$cache_key} if exists $self->{$cache_key};

    my $req = Ravada::Request->list_network_interfaces(
        vm_type => $vm_type
          ,type => $type
           ,uid => $user->id
    );
    if  ( defined $timeout ) {
        $self->wait_request($req, $timeout);
    }
Francesc Guasch's avatar
Francesc Guasch committed
1302
    return [] if $req->status ne 'done' || !length($req->output);
Francesc Guasch's avatar
Francesc Guasch committed
1303
1304
1305
1306
1307
1308
1309

    my $interfaces = decode_json($req->output());
    $self->{$cache_key} = $interfaces;

    return $interfaces;
}

Francesc Guasch's avatar
Francesc Guasch committed
1310
sub _dbh {
Francesc Guasch's avatar
Francesc Guasch committed
1311
1312
    $CONNECTOR = $Ravada::CONNECTOR if !defined $CONNECTOR;
    confess if !defined $CONNECTOR;
Francesc Guasch's avatar
Francesc Guasch committed
1313
1314
1315
    return $CONNECTOR->dbh;
}

1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
sub _get_settings($self, $id_parent=0) {
    my $sth = $CONNECTOR->dbh->prepare(
        "SELECT id,name,value"
        ." FROM settings "
        ." WHERE id_parent= ? "
    );
    $sth->execute($id_parent);
    my $ret;
    while ( my ( $id, $name, $value) = $sth->fetchrow) {
        $value = 0+$value if defined $value && $value =~ /^\d+$/;
        my $setting_sons = $self->_get_settings($id);
        if ($setting_sons) {
            $ret->{$name} = $setting_sons;
        } else {
            $ret->{$name} = { id => $id, value => $value};
        }
    }
    return $ret;
}

1336
1337
1338
1339
1340
1341
=head2 settings_global

Returns the list of global settings as a hash

=cut

1342
1343
1344
1345
sub settings_global($self) {
    return $self->_get_settings();
}

Francesc Guasch's avatar
Francesc Guasch committed
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
sub setting($self, $name, $new_value=undef) {

    confess "Error: wrong new value '$new_value' for $name"
    if ref($new_value);

    Ravada::Front->_check_features($name, $new_value);

    my $sth = _dbh->prepare(
        "SELECT id,value "
        ." FROM settings "
        ." WHERE id_parent=? AND name=?"
    );
    my ($id, $value);
    my $id_parent = 0;
    for my $item (split m{/},$name) {
        next if !$item;
        $sth->execute($id_parent, $item);
        ($id, $value) = $sth->fetchrow;
        confess "Error: I can't find setting $item inside id_parent: $id_parent"
        if !$id;

        $id_parent = $id;
    }

    if (defined $new_value && $new_value ne $value) {
        my $sth_update = _dbh->prepare(
            "UPDATE settings set value=? WHERE id=? "
        );
        $sth_update->execute($new_value,$id);
        return $new_value;
    }
    return $value;
}

sub _check_features($self, $name, $new_value) {
    confess "Error: LDAP required for bookings."
    if $name eq '/backend/bookings' && $new_value && !$self->feature('ldap');

}

1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
sub _settings_by_id($self) {
    my $orig_settings;
    my $sth = $self->_dbh->prepare("SELECT id,value FROM settings");
    $sth->execute();
    while (my ($id, $value) = $sth->fetchrow) {
        $orig_settings->{$id} = $value;
    }
    return $orig_settings;
}

Francesc Guasch's avatar
Francesc Guasch committed
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
sub feature($self,$name=undef) {
    if (!defined $name) {
        my $feature;
        for my $cur_name ('ldap') {
            $feature->{$cur_name} = $self->feature($cur_name);
        }
        return $feature;
    }
    return 1 if exists $Ravada::CONFIG->{$name} && $Ravada::CONFIG->{$name};
    return 0;
}

1408
1409
1410
1411
1412
1413
=head2 update_settings_global

Updates the global settings

=cut

Francesc Guasch's avatar
Francesc Guasch committed
1414
sub update_settings_global($self, $arg, $user, $reload, $orig_settings = $self->_settings_by_id) {
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
    confess if !ref($arg);
    if (exists $arg->{frontend}
        && exists $arg->{frontend}->{maintenance}
        && !$arg->{frontend}->{maintenance}->{value}) {
        delete $arg->{frontend}->{maintenance_end};
        delete $arg->{frontend}->{maintenance_start};
    }
    for my $field (sort keys %$arg) {
        if ( !exists $arg->{$field}->{id} ) {
            confess if !keys %{$arg->{$field}};
Francesc Guasch's avatar
Francesc Guasch committed
1425
            $self->update_settings_global($arg->{$field}, $user, $reload, $orig_settings);
1426
1427
1428
1429
1430
1431
1432
1433
            next;
        }
        confess "Error: invalid field $field" if $field !~ /^\w+$/;
        my ( $value, $id )
                   = ($arg->{$field}->{value}
                    , $arg->{$field}->{id}
        );
        next if $orig_settings->{$id} eq $value;
Francesc Guasch's avatar
Francesc Guasch committed
1434
        $$reload++ if $field eq 'bookings';