Ravada.pm 12.7 KB
Newer Older
1
2
3
4
package Test::Ravada;
use strict;
use warnings;

5
use  Carp qw(carp confess);
6
use  Data::Dumper;
7
8
use Hash::Util qw(lock_hash);
use IPC::Run3 qw(run3);
9
use  Test::More;
10

Francesc Guasch's avatar
Francesc Guasch committed
11
12
13
no warnings "experimental::signatures";
use feature qw(signatures);

14
15
16
use Ravada;
use Ravada::Auth::SQL;

17
18
19
20
21
22
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);

require Exporter;

@ISA = qw(Exporter);

23
24
@EXPORT = qw(base_domain_name new_domain_name rvd_back remove_old_disks remove_old_domains create_user user_admin wait_request rvd_front init init_vm clean new_pool_name
create_domain
25
    test_chain_prerouting
26
    find_ip_rule
27
28
    search_id_iso
    flush_rules open_ipt
29
    arg_create_dom
Francesc Guasch's avatar
Francesc Guasch committed
30
    vm_names
31
32
33
34
    search_iptable_remote
    clean_remote
    start_node shutdown_node
    start_domain_internal   shutdown_domain_internal
35
);
36
37

our $DEFAULT_CONFIG = "t/etc/ravada.conf";
38
our ($CONNECTOR, $CONFIG);
39
40

our $CONT = 0;
41
our $CONT_POOL= 0;
42
our $USER_ADMIN;
43
our $CHAIN = 'RAVADA';
44

Francesc Guasch's avatar
Francesc Guasch committed
45
46
47
48
our %ARG_CREATE_DOM = (
    KVM => []
    ,Void => []
);
49

50
51
52
sub user_admin {
    return $USER_ADMIN;
}
53

54
55
56
57
58
59
60
sub arg_create_dom {
    my $vm_name = shift;
    confess "Unknown vm $vm_name"
        if !$ARG_CREATE_DOM{$vm_name};
    return @{$ARG_CREATE_DOM{$vm_name}};
}

Francesc Guasch's avatar
Francesc Guasch committed
61
62
63
64
sub vm_names {
    return sort keys %ARG_CREATE_DOM;
}

65
66
67
sub create_domain {
    my $vm_name = shift;
    my $user = (shift or $USER_ADMIN);
68
    my $id_iso = (shift or 'Alpine');
69

70
71
    $vm_name = 'KVM' if $vm_name eq 'qemu';

72
73
74
75
76
    if ( $id_iso && $id_iso !~ /^\d+$/) {
        my $iso_name = $id_iso;
        $id_iso = search_id_iso($iso_name);
        warn "I can't find iso $iso_name" if !defined $id_iso;
    }
77
78
    confess "Missing id_iso" if !defined $id_iso;

79
    my $vm = rvd_back()->search_vm($vm_name);
80
    ok($vm,"Expecting VM $vm_name") or return;
81
82
83

    my $name = new_domain_name();

84
    my %arg_create = (id_iso => $id_iso);
85
86
87
88

    my $domain;
    eval { $domain = $vm->create_domain(name => $name
                    , id_owner => $user->id
89
90
                    , %arg_create
                    , active => 0
91
92
93
94
95
96
97
98
           );
    };
    is($@,'');

    return $domain;

}

99
sub base_domain_name {
100
101
    my ($name) = $0 =~ m{.*?/(.*)\.t};
    die "I can't find name in $0"   if !$name;
102
103
104
105
106
    $name =~ s{/}{_}g;

    return $name;
}

107
108
109
110
111
112
113
114
sub base_pool_name {
    my ($name) = $0 =~ m{.*?/(.*)\.t};
    die "I can't find name in $0"   if !$name;
    $name =~ s{/}{_}g;

    return "test_$name";
}

115
116
117
118
sub new_domain_name {
    return base_domain_name()."_".$CONT++;
}

119
120
121
122
sub new_pool_name {
    return base_pool_name()."_".$CONT_POOL++;
}

123
sub rvd_back {
124
    my ($connector, $config) = @_;
125
    init($connector,$config,0)    if $connector;
126

127
    my $rvd = Ravada->new(
128
129
            connector => $CONNECTOR
                , config => ( $CONFIG or $DEFAULT_CONFIG)
130
                , warn_error => 0
131
    );
132
    $USER_ADMIN = create_user('admin','admin',1)    if !$USER_ADMIN;
133
134
135

    $ARG_CREATE_DOM{KVM} = [ id_iso => search_id_iso('Alpine') ];

136
    return $rvd;
137
138
}

139
140
sub rvd_front {

141
    return Ravada::Front->new(
142
143
            connector => $CONNECTOR
                , config => ( $CONFIG or $DEFAULT_CONFIG)
144
    );
145
146
147
}

sub init {
148
149
150
151
    my $create_user;
    ($CONNECTOR, $CONFIG, $create_user) = @_;

    $create_user = 1 if !defined $create_user;
152
153
154

    confess "Missing connector : init(\$connector,\$config)" if !$CONNECTOR;

155
    $Ravada::CONNECTOR = $CONNECTOR if !$Ravada::CONNECTOR;
156
157
    Ravada::Auth::SQL::_init_connector($CONNECTOR);

158
    $Ravada::Domain::MIN_FREE_MEMORY = 512*1024;
159

160
161
}

162
163
164
sub _remove_old_domains_vm {
    my $vm_name = shift;

165
    my $domain;
166
167
168
169
170
171
172

    my $vm;
    eval {
        my $rvd_back=rvd_back();
        return if !$rvd_back;
        $vm = $rvd_back->search_vm($vm_name);
    };
173
    diag($@) if $@;
174

175
    return if !$vm;
176
177

    my $base_name = base_domain_name();
178

179
180
181
182
    my @domains;
    eval { @domains = $vm->list_domains() };

    for my $dom_name ( sort { $b cmp $a }  @domains) {
183
184
        next if $dom_name !~ /^$base_name/i;

185
186
187
188
        my $domain;
        eval {
            $domain = $vm->search_domain($dom_name);
        };
189
190
191
192
193
        next if !$domain;

        eval { $domain->shutdown_now($USER_ADMIN); };
        warn "Error shutdown ".$domain->name." $@" if $@ && $@ !~ /No DB info/i;

194
195
        $domain = $vm->search_domain($dom_name);
        eval {$domain->remove( $USER_ADMIN ) }  if $domain;
196
197
198
199
200
201
        if ( $@ && $@ =~ /No DB info/i ) {
            eval { $domain->domain->undefine() if $domain->domain };
        }

    }

202
}
203
204
205

sub _remove_old_domains_kvm {

206
207
208
    my $vm;
    
    eval {
209
210
        my $rvd_back = rvd_back();
        $vm = $rvd_back->search_vm('KVM');
211
    };
212
    diag($@) if $@;
213
    return if !$vm;
214

215
    my $base_name = base_domain_name();
216
    for my $domain ( $vm->vm->list_all_domains ) {
217
        next if $domain->get_name !~ /^$base_name/;
218
        my $domain_name = $domain->get_name;
219
220
221
        eval { 
            $domain->shutdown();
            sleep 1; 
222
223
            eval { $domain->destroy() if $domain->is_active };
            warn $@ if $@;
224
225
        }
            if $domain->is_active;
226
227
        warn "WARNING: error $@ trying to shutdown ".$domain_name
            if $@ && $@ !~ /error code: 42,/;
228

229
230
231
232
233
        eval {
            $domain->managed_save_remove()
                if $domain->has_managed_save_image();
        };
        warn $@ if $@ && $@ !~ /error code: 42,/;
234

235
        eval { $domain->undefine };
236
        warn $@ if $@ && $@ !~ /error code: 42,/;
237
238
239
    }
}

240
sub remove_old_domains {
241
242
    _remove_old_domains_vm('KVM');
    _remove_old_domains_vm('Void');
243
    _remove_old_domains_kvm();
244
245
}

246
sub _remove_old_disks_kvm {
247
248
    my $name = base_domain_name();
    confess "Unknown base domain name " if !$name;
249

250
#    my $rvd_back= rvd_back();
251
    my $vm = rvd_back()->search_vm('kvm');
252
253
254
    if (!$vm) {
        return;
    }
255
#    ok($vm,"I can't find a KVM virtual manager") or return;
256

257
258
    $vm->_refresh_storage_pools();

259
260
261
262
263
    for my $pool( $vm->vm->list_all_storage_pools ) {
        for my $volume  ( $pool->list_volumes ) {
            next if $volume->get_name !~ /^${name}_\d+.*\.(img|raw|ro\.qcow2|qcow2)$/;
            $volume->delete();
        }
264
265
266
267
    }
    $vm->storage_pool->refresh();
}

268
269
270
sub _remove_old_disks_void {
    my $name = base_domain_name();

271
    my $dir_img =  $Ravada::Domain::Void::DIR_TMP ;
272
273
    opendir my $ls,$dir_img or return;
    while (my $file = readdir $ls ) {
274
        next if $file !~ /^${name}_\d/;
275
276
277
278
279
280
281
282
283
284
285

        my $disk = "$dir_img/$file";
        next if ! -f $disk;

        unlink $disk or die "I can't remove $disk";

    }
    closedir $ls;
}

sub remove_old_disks {
286
287
    _remove_old_disks_void();
    _remove_old_disks_kvm();
288
289
}

290
291
sub create_user {
    my ($name, $pass, $is_admin) = @_;
292

293
    Ravada::Auth::SQL::add_user(name => $name, password => $pass, is_admin => $is_admin);
294
295
296
297
298
299
300
301
302

    my $user;
    eval {
        $user = Ravada::Auth::SQL->new(name => $name, password => $pass);
    };
    die $@ if !$user;
    return $user;
}

303
304
sub wait_request {
    my $req = shift;
305
306
307
    for my $cnt ( 0 .. 10 ) {
        diag("Request ".$req->id." ".$req->command." ".$req->status." ".localtime(time))
            if $cnt > 2;
308
309
310
311
312
313
        last if $req->status eq 'done';
        sleep 2;
    }

}

Francesc Guasch's avatar
Francesc Guasch committed
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
sub init_vm {
    my $vm = shift;
    return if $vm->type =~ /void/i;
    _qemu_storage_pool($vm) if $vm->type =~ /qemu/i;
}

sub _exists_storage_pool {
    my ($vm, $pool_name) = @_;
    for my $pool ($vm->vm->list_storage_pools) {
        return 1 if $pool->get_name eq $pool_name;
    }
    return;
}

sub _qemu_storage_pool {
    my $vm = shift;

331
332
333
334
    my $pool_name = new_pool_name();

    if ( _exists_storage_pool($vm, $pool_name)) {
        $vm->default_storage_pool_name($pool_name);
Francesc Guasch's avatar
Francesc Guasch committed
335
336
337
338
339
        return;
    }

    my $uuid = Ravada::VM::KVM::_new_uuid('68663afc-aaf4-4f1f-9fff-93684c260942');

340
    my $dir = "/var/tmp/$pool_name";
Francesc Guasch's avatar
Francesc Guasch committed
341
342
343
344
    mkdir $dir if ! -e $dir;

    my $xml =
"<pool type='dir'>
345
  <name>$pool_name</name>
Francesc Guasch's avatar
Francesc Guasch committed
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
  <uuid>$uuid</uuid>
  <capacity unit='bytes'></capacity>
  <allocation unit='bytes'></allocation>
  <available unit='bytes'></available>
  <source>
  </source>
  <target>
    <path>$dir</path>
    <permissions>
      <mode>0711</mode>
      <owner>0</owner>
      <group>0</group>
    </permissions>
  </target>
</pool>"
;
    my $pool;
    eval { $pool = $vm->vm->create_storage_pool($xml) };
    ok(!$@,"Expecting \$@='', got '".($@ or '')."'") or return;
    ok($pool,"Expecting a pool , got ".($pool or ''));

367
    $vm->default_storage_pool_name($pool_name);
Francesc Guasch's avatar
Francesc Guasch committed
368
369
370
371
}

sub remove_qemu_pools {
    my $vm = rvd_back->search_vm('kvm') or return;
372

373
374
375
376
377
378
379
380
    for my $pool  ( $vm->vm->list_all_storage_pools) {
        next if $pool->get_name !~ /^test_/;
        diag("Removing ".$pool->get_name." storage_pool");
        $pool->destroy();
        eval { $pool->undefine() };
        warn $@ if$@;
        ok(!$@ or $@ =~ /Storage pool not found/i);
    }
Francesc Guasch's avatar
Francesc Guasch committed
381
382
383
384
385
386
387
388
389
390
391
392

}

sub remove_old_pools {
    remove_qemu_pools();
}

sub clean {
    remove_old_domains();
    remove_old_disks();
    remove_old_pools();
}
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438

sub search_id_iso {
    my $name = shift;
    my $sth = $CONNECTOR->dbh->prepare("SELECT id FROM iso_images "
        ." WHERE name like ?"
    );
    $sth->execute("$name%");
    my ($id) = $sth->fetchrow;
    die "There is no iso called $name%" if !$id;
    return $id;
}

sub flush_rules {
    my $ipt = open_ipt();
    $ipt->flush_chain('filter', $CHAIN);
    $ipt->delete_chain('filter', 'INPUT', $CHAIN);

    my @cmd = ('iptables','-t','nat','-F','PREROUTING');
    my ($in,$out,$err);
    run3(\@cmd, \$in, \$out, \$err);
    die $err if $err;
}

sub open_ipt {
    my %opts = (
    	'use_ipv6' => 0,         # can set to 1 to force ip6tables usage
	    'ipt_rules_file' => '',  # optional file path from
	                             # which to read iptables rules
	    'iptout'   => '/tmp/iptables.out',
	    'ipterr'   => '/tmp/iptables.err',
	    'debug'    => 0,
	    'verbose'  => 0,

	    ### advanced options
	    'ipt_alarm' => 5,  ### max seconds to wait for iptables execution.
	    'ipt_exec_style' => 'waitpid',  ### can be 'waitpid',
	                                    ### 'system', or 'popen'.
	    'ipt_exec_sleep' => 1, ### add in time delay between execution of
	                           ### iptables commands (default is 0).
	);

	my $ipt_obj = IPTables::ChainMgr->new(%opts)
    	or die "[*] Could not acquire IPTables::ChainMgr object";

}

439
440
441
442
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
475
476
477
478
sub _iptables_list {
    my ($in, $out, $err);
    run3(['/sbin/iptables-save'], \$in, \$out, \$err);
    my ( %tables, $ret );

    my ($current_table);
    for my $line (split /\n/, $out) {
        chomp $line;

        next if ( $line eq "COMMIT" );
        next if ( $line =~ m/^#/ );
        next if ( $line =~ m/^:/ );

        if ( $line =~ m/^\*([a-z]+)$/ ) {
            $current_table = $1;
            $tables{$current_table} = [];
            next;
        }

        #my @parts = grep { ! /^\s+$/ && ! /^$/ } split (/(\-\-?[^\s]+\s[^\s]+)/i, $line);
        my @parts = grep { !/^\s+$/ && !/^$/ } split( /^\-\-?|\s+\-\-?/i, $line );

        my @option = ();
        for my $part (@parts) {
            my ( $key, $value ) = split( /\s/, $part, 2 );
            push( @option, $key => $value );
        }

        push( @{ $ret->{$current_table} }, \@option );

    }

    return $ret;
}

sub find_ip_rule {
    my %args = @_;
    my $remote_ip = delete $args{remote_ip};
    my $local_ip = delete $args{local_ip};
    my $local_port= delete $args{local_port};
479
    my $jump = ( delete $args{jump} or 'ACCEPT');
480
481
482
483

    die "ERROR: Unknown args ".Dumper(\%args)  if keys %args;

    my $iptables = _iptables_list();
484
    $remote_ip .= "/32" if defined $remote_ip && $remote_ip !~ m{/};
485
486
487
488
489
490
    $local_ip .= "/32"  if defined $local_ip && $local_ip !~ m{/};

    my @found;

    my $count = 0;
    for my $line (@{$iptables->{filter}}) {
491
492
493
        my %line= @$line;
        next if $line{A} ne $CHAIN;
        $line{s} = '0.0.0.0/0'  if !exists $line{s} && $line{p} =~ m/.cp$/;
494
        $count++;
495
496
497
498
499
        if((!defined $jump || ( exists $line{j} && $line{j} eq $jump ))
           && ( !defined $remote_ip || (exists $line{s} && $line{s} eq $remote_ip ))
           && ( !defined $local_ip || ( exists $line{d} && $line{d} eq $local_ip ))
           && ( !defined $local_port || ( exists $line{dport} && $line{dport} eq $local_port)))
        {
500
501
502
503

            push @found,($count);
        }
    }
504
    return if !scalar@found || !defined $found[0];
505
506
507
    return @found   if wantarray;
    return $found[0];
}
508

509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
sub shutdown_domain_internal($domain) {
    if ($domain->type eq 'KVM') {
        $domain->domain->destroy();
    } elsif ($domain->type eq 'Void') {
        $domain->_store(is_active => 0 );
    } else {
        confess "ERROR: I don't know how to shutdown internal domain of type ".$domain->type;
    }
}

sub start_domain_internal($domain) {
    if ($domain->type eq 'KVM') {
        $domain->domain->create();
    } elsif ($domain->type eq 'Void') {
        $domain->_store(is_active => 1 );
    } else {
        confess "ERROR: I don't know how to shutdown internal domain of type ".$domain->type;
    }
}

529
1;