Zonemaster/Backend/DB.pm untested

filter: Statementstmt 0.0% 0 / 355 Branchbran 0.0% 0 / 92 Conditioncond 0.0% 0 / 51 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 51 Podpod 0.0% 0 / 34 totaltotal 0.0% 0 / 583 CC 47 SCAR 28.8
CC
47
Cov
0%
test_progress
56.0
batch_status
56.0
get_test_history
42.0
CRAP 17.8
1 package Zonemaster::Backend::DB;
2  
3 our $VERSION = '1.2.0';
4  
5 use Moose::Role;
6  
7 use 5.14.2;
8  
9 use Carp qw( croak );
10 use DBI qw( :sql_types );
11 use Digest::MD5 qw( md5_hex );
12 use Encode;
13 use Exporter qw( import );
14 use JSON::PP;
15 use Log::Any qw( $log );
16 use POSIX qw( strftime );
17 use Readonly;
18 use Try::Tiny;
19  
20 use Zonemaster::Backend::Errors;
21 use Zonemaster::Engine::Normalization qw( normalize_name trim_space );
22 use Zonemaster::Engine::Logger::Entry;
23  
24 requires qw(
25 add_batch_job
26 create_schema
27 drop_tables
28 from_config
29 get_dbh_specific_attributes
30 get_relative_start_time
31 is_duplicate
32 is_unknown_table
33 );
34  
35 has 'data_source_name' => (
36 is => 'ro',
37 isa => 'Str',
38 required => 1,
39 );
40  
41 has 'user' => (
42 is => 'ro',
43 isa => 'Str',
44 required => 1,
45 );
46  
47 has 'password' => (
48 is => 'ro',
49 isa => 'Str',
50 required => 1,
51 );
52  
53 has 'dbhandle' => (
54 is => 'rw',
55 isa => 'Maybe[DBI::db]',
56 required => 1,
57 );
58  
59 =head2 $REQUIRED_SCHEMA_VERSION
60  
61 A positive integer. The database schema version that this module is compatible with.
62  
63 =cut
64  
65 Readonly our $REQUIRED_SCHEMA_VERSION => 1;
66  
67 =head2 $TEST_WAITING
68  
69 The test is waiting to be processed.
70  
71 =cut
72  
73 Readonly our $TEST_WAITING => 'WAITING';
74  
75 =head2 $TEST_RUNNING
76  
77 The test is currently being processed.
78  
79 =cut
80  
81 Readonly our $TEST_RUNNING => 'RUNNING';
82  
83 =head2 $TEST_COMPLETED
84  
85 The test was already processed.
86  
87 This state encompasses all of the following:
88  
89 =over 2
90  
91 =item
92  
93 The Zonemaster Engine test terminated normally.
94  
95 =item
96  
97 A critical error occurred while processing.
98  
99 =item
100  
101 The processing was cancelled because it took too long.
102  
103 =back
104  
105 =cut
106  
107 Readonly our $TEST_COMPLETED => 'COMPLETED';
108  
109 our @EXPORT_OK = qw(
110 $TEST_WAITING
111 $TEST_RUNNING
112 $TEST_COMPLETED
113 );
114  
115  
116 =head2 get_db_class
117  
118 Get the database adapter class for the given database type.
119  
120 Throws and exception if the database adapter class cannot be loaded.
121  
122 =cut
123  
124 sub get_db_class {
125 my ( $class, $db_type ) = @_;
126  
127 my $db_class = "Zonemaster::Backend::DB::$db_type";
128  
129 require( "$db_class.pm" =~ s{::}{/}gr );
130 $db_class->import();
131  
132 return $db_class;
133 }
134  
135 sub dbh {
136 my ( $self ) = @_;
137  
138 if ( $self->dbhandle && $self->dbhandle->ping ) {
139 return $self->dbhandle;
140 }
141  
142 if ( $self->user ) {
143 $log->noticef( "Connecting to database '%s' as user '%s'", $self->data_source_name, $self->user );
144 }
145 else {
146 $log->noticef( "Connecting to database '%s'", $self->data_source_name );
147 }
148  
149 my $attr = {
150 RaiseError => 1,
151 AutoCommit => 1,
152 AutoInactiveDestroy => 1,
153 };
154  
155 $attr = { %$attr, %{ $self->get_dbh_specific_attributes } };
156  
157 my $dbh = DBI->connect(
158 $self->data_source_name,
159 $self->user,
160 $self->password,
161 $attr
162 );
163  
164 $self->dbhandle( $dbh );
165  
166 return $self->dbhandle;
167 }
168  
169 =head2 get_schema_version
170  
171 Detect the schema version of the database.
172  
173 Returns an unsigned integer.
174  
175 The C<0> value means the database is in a schema state prior to schema versioning.
176  
177 =cut
178  
179 sub get_schema_version {
180 my ( $self ) = @_;
181  
182 my $dbh = $self->dbh;
183  
184 local $dbh->{RaiseError} = 0;
185 local $dbh->{PrintError} = 0;
186 my $result = $dbh->selectcol_arrayref( "SELECT version FROM schema_version LIMIT 2" );
187  
188 if ( $dbh->err ) {
189 if ( !$self->is_unknown_table ) {
190 croak "Failed to read schema version: " . $dbh->errstr;
191 }
192  
193 return 0;
194 }
195  
196 if ( @$result != 1
197 || !defined $result->[0]
198 || $result->[0] !~ qr{^[1-9][0-9]*$}
199 || $result->[0] < 1 )
200 {
201 croak 'Invalid schema version declaration';
202 }
203  
204 return $result->[0];
205 }
206  
207 =head2 assert_compatible_schema
208  
209 Assert that the database has a schema version that is compatible with this version of
210 Zonemaster Backend.
211  
212 Croaks if the database has an incompatible schema version, or if it is in an illegal state
213 with regard to schema version encoding.
214  
215 =cut
216  
217 sub assert_compatible_schema {
218 my ( $self ) = @_;
219  
220 my $db_schema_version = $self->get_schema_version;
221  
222 if ( $db_schema_version ne $REQUIRED_SCHEMA_VERSION ) {
223 croak "Expected schema version $REQUIRED_SCHEMA_VERSION, found $db_schema_version";
224 }
225  
226 return;
227 }
228  
229 sub add_api_user {
230 my ( $self, $username, $api_key ) = @_;
231  
232 die Zonemaster::Backend::Error::Internal->new( reason => "username or api_key not provided to the method add_api_user")
233 unless ( $username && $api_key );
234  
235 my $dbh = $self->dbh;
236 my $result;
237  
238 try {
239 $result = $dbh->do(
240 "INSERT INTO users (username, api_key) VALUES (?,?)",
241 undef,
242 $username,
243 $api_key,
244 );
245 } catch {
246 die Zonemaster::Backend::Error::Conflict->new( message => 'User already exists', data => { username => $username } )
247 if ( $self->is_duplicate );
248 };
249  
250 die Zonemaster::Backend::Error::Internal->new( reason => "add_api_user not successful")
251 unless ( $result );
252  
253 return $result;
254 }
255  
256 sub create_new_test {
257 my ( $self, $domain, $test_params, $seconds_between_tests_with_same_params, $batch_id ) = @_;
258  
259 my $dbh = $self->dbh;
260  
261 $test_params->{domain} = _normalize_domain( $domain );
262  
263 my $fingerprint = $self->generate_fingerprint( $test_params );
264 my $encoded_params = $self->encode_params( $test_params );
265 my $undelegated = $self->undelegated ( $test_params );
266  
267 my $hash_id;
268  
269 my $priority = $test_params->{priority};
270 my $queue_label = $test_params->{queue};
271 my $now = time();
272 my $threshold = $now - $seconds_between_tests_with_same_params;
273  
274 my $recent_hash_id = $self->recent_test_hash_id( $fingerprint, $threshold );
275  
276 if ( $recent_hash_id ) {
277 # A recent entry exists, so return its id
278 $hash_id = $recent_hash_id;
279 }
280 else {
281 $hash_id = substr(md5_hex($now.rand()), 0, 16);
282 $dbh->do(
283 q[
284 INSERT INTO test_results (
285 hash_id,
286 batch_id,
287 created_at,
288 priority,
289 queue,
290 fingerprint,
291 params,
292 domain,
293 undelegated
294 ) VALUES (?,?,?,?,?,?,?,?,?)
295 ],
296 undef,
297 $hash_id,
298 $batch_id,
299 $self->format_time( time() ),
300 $priority,
301 $queue_label,
302 $fingerprint,
303 $encoded_params,
304 encode_utf8( $test_params->{domain} ),
305 $undelegated,
306 );
307 }
308  
309 return $hash_id;
310 }
311  
312 # Search for recent test result with the test same parameters, where
313 # "threshold" gives the oldest start time.
314 sub recent_test_hash_id {
315 my ( $self, $fingerprint, $threshold ) = @_;
316  
317 my $dbh = $self->dbh;
318 my ( $recent_hash_id ) = $dbh->selectrow_array(
319 q[
320 SELECT hash_id
321 FROM test_results
322 WHERE fingerprint = ?
323 AND batch_id IS NULL
324 AND ( started_at IS NULL
325 OR started_at >= ? )
326 ],
327 undef,
328 $fingerprint,
329 $self->format_time( $threshold ),
330 );
331  
332 return $recent_hash_id;
333 }
334  
335 =head2 test_progress( $test_id, $progress )
336  
337 Get/set the progress value of the test associated with C<$test_id>.
338  
339 The given C<$progress> must be either C<undef> (when getting) or an number in
340 the range 0-100 inclusive (when setting).
341  
342 If defined, C<$progress> is clamped to 1-99 inclusive.
343  
344 Dies when:
345  
346 =over 2
347  
348 =item
349  
350 attempting to access a test that does not exist
351  
352 =item
353  
354 attempting to update a test that is in a state other than "running"
355  
356 =item
357  
358 attempting to set a progress value that is lower than the current one
359  
360 =item
361  
362 an error occurs in the database interface
363  
364 =back
365  
366 =cut
367  
368 sub test_progress {
369 my ( $self, $test_id, $progress ) = @_;
370  
371 if ( defined $progress ) {
372 if ( $progress < 0 || 100 < $progress ) {
373 die Zonemaster::Backend::Error::Internal->new( reason => "progress out of range" );
374 } elsif ( $progress < 1 ) {
375 $progress = 1;
376 } elsif ( 99 < $progress ) {
377 $progress = 99;
378 }
379  
380 my $rows_affected = $self->dbh->do(
381 q[
382 UPDATE test_results
383 SET progress = ?
384 WHERE hash_id = ?
385 AND 1 <= progress
386 AND progress <= ?
387 ],
388 undef,
389 $progress,
390 $test_id,
391 $progress,
392 );
393 if ( $rows_affected == 0 ) {
394 die Zonemaster::Backend::Error::Internal->new( reason => 'job not found or illegal update' );
395 }
396  
397 return $progress;
398 }
399  
400 my ( $result ) = $self->dbh->selectrow_array(
401 q[
402 SELECT progress
403 FROM test_results
404 WHERE hash_id = ?
405 ],
406 undef,
407 $test_id,
408 );
409 if ( !defined $result ) {
410 die Zonemaster::Backend::Error::Internal->new( reason => 'job not found' );
411 }
412  
413 return $result;
414 }
415  
416 sub test_state {
417 my ( $self, $test_id ) = @_;
418  
419 my ( $progress ) = $self->dbh->selectrow_array(
420 q[
421 SELECT progress
422 FROM test_results
423 WHERE hash_id = ?
424 ],
425 undef,
426 $test_id,
427 );
428 if ( !defined $progress ) {
429 die Zonemaster::Backend::Error::Internal->new( reason => 'job not found' );
430 }
431  
432 if ( $progress == 0 ) {
433 return $TEST_WAITING;
434 }
435 elsif ( 0 < $progress && $progress < 100 ) {
436 return $TEST_RUNNING;
437 }
438 elsif ( $progress == 100 ) {
439 return $TEST_COMPLETED;
440 }
441 else {
442 die Zonemaster::Backend::Error::Internal->new( reason => 'state could not be determined' );
443 }
444 }
445  
446 sub set_test_completed {
447 my ( $self, $test_id ) = @_;
448  
449 my $current_state = $self->test_state( $test_id );
450  
451 if ( $current_state ne $TEST_RUNNING ) {
452 die Zonemaster::Backend::Error::Internal->new( reason => 'illegal transition to COMPLETED' );
453 }
454  
455 my $rows_affected = $self->dbh->do(
456 q[
457 UPDATE test_results
458 SET progress = 100,
459 ended_at = ?
460 WHERE hash_id = ?
461 AND 0 < progress
462 AND progress < 100
463 ],
464 undef,
465 $self->format_time( time() ),
466 $test_id,
467 );
468  
469 if ( $rows_affected == 0 ) {
470 die Zonemaster::Backend::Error::Internal->new( reason => "job not found or illegal transition" );
471 }
472 }
473  
474 sub select_test_results {
475 my ( $self, $test_id ) = @_;
476  
477 my ( $hrefs ) = $self->dbh->selectall_hashref(
478 q[
479 SELECT
480 hash_id,
481 created_at,
482 params
483 FROM test_results
484 WHERE hash_id = ?
485 ],
486 'hash_id',
487 undef,
488 $test_id
489 );
490  
491 my $result = $hrefs->{$test_id};
492  
493 die Zonemaster::Backend::Error::ResourceNotFound->new( message => "Test not found", data => { test_id => $test_id } )
494 unless defined $result;
495  
496 $result->{created_at} = $self->to_iso8601( $result->{created_at} );
497  
498 return $result;
499 }
500  
501 # "$new_results" is JSON encoded
502 sub store_results {
503 my ( $self, $test_id, $new_results ) = @_;
504  
505 my $rows_affected = $self->dbh->do(
506 q[
507 UPDATE test_results
508 SET progress = 100,
509 ended_at = ?,
510 results = ?
511 WHERE hash_id = ?
512 AND 0 < progress
513 AND progress < 100
514 ],
515 undef,
516 $self->format_time( time() ),
517 $new_results,
518 $test_id,
519 );
520  
521 if ( $rows_affected == 0 ) {
522 die Zonemaster::Backend::Error::Internal->new( reason => "job not found or illegal transition" );
523 }
524  
525 return;
526 }
527  
528 sub test_results {
529 my ( $self, $test_id ) = @_;
530  
531 my $result = $self->select_test_results( $test_id );
532  
533 my @result_entries = $self->dbh->selectall_array(
534 q[
535 SELECT
536 l.level,
537 r.module,
538 r.testcase,
539 r.tag,
540 r.timestamp,
541 r.args
542 FROM result_entries r
543 INNER JOIN log_level l
544 ON r.level = l.value
545 WHERE hash_id = ?
546 ],
547 { Slice => {} },
548 $test_id
549 );
550  
551 eval {
552 $result->{params} = decode_json( $result->{params} );
553  
554 @result_entries = map {
555 {
556 %$_,
557 args => decode_json( $_->{args} ),
558 }
559 } @result_entries;
560  
561 $result->{results} = \@result_entries;
562 };
563  
564 die Zonemaster::Backend::Error::JsonError->new( reason => "$@", data => { test_id => $test_id } )
565 if $@;
566  
567 return $result;
568 }
569  
570 sub get_test_history {
571 my ( $self, $p ) = @_;
572  
573 my $dbh = $self->dbh;
574  
575 my $undelegated = undef;
576 if ($p->{filter} eq "undelegated") {
577 $undelegated = 1;
578 } elsif ($p->{filter} eq "delegated") {
579 $undelegated = 0;
580 }
581  
582 my @results;
583 my $query = q[
584 SELECT
585 (SELECT count(*) FROM result_entries WHERE result_entries.hash_id = test_results.hash_id AND level = ?) AS nb_critical,
586 (SELECT count(*) FROM result_entries WHERE result_entries.hash_id = test_results.hash_id AND level = ?) AS nb_error,
587 (SELECT count(*) FROM result_entries WHERE result_entries.hash_id = test_results.hash_id AND level = ?) AS nb_warning,
588 id,
589 hash_id,
590 created_at,
591 undelegated
592 FROM test_results
593 WHERE progress = 100 AND domain = ? AND ( ? IS NULL OR undelegated = ? )
594 ORDER BY created_at DESC
595 LIMIT ?
596 OFFSET ?];
597  
598 my $sth = $dbh->prepare( $query );
599  
600 my %levels = Zonemaster::Engine::Logger::Entry->levels();
601 $sth->bind_param( 1, $levels{CRITICAL} );
602 $sth->bind_param( 2, $levels{ERROR} );
603 $sth->bind_param( 3, $levels{WARNING} );
604 $sth->bind_param( 4, _normalize_domain( $p->{frontend_params}{domain} ) );
605 $sth->bind_param( 5, $undelegated, SQL_INTEGER );
606 $sth->bind_param( 6, $undelegated, SQL_INTEGER );
607 $sth->bind_param( 7, $p->{limit} );
608 $sth->bind_param( 8, $p->{offset} );
609  
610 $sth->execute();
611  
612 while ( my $h = $sth->fetchrow_hashref ) {
613 my $overall_result = 'ok';
614 if ( $h->{nb_critical} ) {
615 $overall_result = 'critical';
616 }
617 elsif ( $h->{nb_error} ) {
618 $overall_result = 'error';
619 }
620 elsif ( $h->{nb_warning} ) {
621 $overall_result = 'warning';
622 }
623  
624 push(
625 @results,
626 {
627 id => $h->{hash_id},
628 created_at => $self->to_iso8601( $h->{created_at} ),
629 undelegated => $h->{undelegated},
630 overall_result => $overall_result,
631 }
632 );
633 }
634  
635 return \@results;
636 }
637  
638 sub create_new_batch_job {
639 my ( $self, $username ) = @_;
640  
641 my $dbh = $self->dbh;
642 $dbh->do( q[ INSERT INTO batch_jobs (username, created_at) VALUES (?,?) ],
643 undef,
644 $username,
645 $self->format_time( time() ),
646 );
647 my $new_batch_id = $dbh->last_insert_id( undef, undef, "batch_jobs", undef );
648  
649 return $new_batch_id;
650 }
651  
652 sub user_authorized {
653 my ( $self, $user, $api_key ) = @_;
654  
655 my $dbh = $self->dbh;
656 my ( $id ) = $dbh->selectrow_array(
657 "SELECT id FROM users WHERE username = ? AND api_key = ?",
658 undef,
659 $user,
660 $api_key
661 );
662  
663 return $id;
664 }
665  
666 sub batch_exists_in_db {
667 my ( $self, $batch_id ) = @_;
668  
669 my $dbh = $self->dbh;
670 my ( $id ) = $dbh->selectrow_array(
671 q[ SELECT id FROM batch_jobs WHERE id = ? ],
672 undef,
673 $batch_id
674 );
675  
676 return $id;
677 }
678  
679 =head2 get_test_request( $queue_label )
680  
681 Find a waiting test and claim it for processing.
682  
683 If $queue_label is defined it must be an integer.
684 If defined, only tests in the associated queue are considered.
685 Otherwise tests from all queues are considered.
686  
687 Returns the test id and the batch id of the claimed test.
688 If there are no waiting tests to claim, C<undef> is returned for both ids.
689  
690 Only tests in the "waiting" state are considered.
691 When a test is claimed it is removed from the queue and it transitions to the
692 "running" state.
693  
694 It is safe for multiple callers running in parallel to allocate tests from the
695 same queues.
696  
697 Dies when an error occurs in the database interface.
698  
699 =cut
700  
701 sub get_test_request {
702 my ( $self, $queue_label ) = @_;
703  
704 while ( 1 ) {
705  
706 # Identify a candidate for allocation ...
707 my ( $hash_id, $batch_id );
708 if ( defined $queue_label ) {
709 ( $hash_id, $batch_id ) = $self->dbh->selectrow_array(
710 q[
711 SELECT hash_id,
712 batch_id
713 FROM test_results
714 WHERE progress = 0
715 AND queue = ?
716 ORDER BY priority DESC,
717 id ASC
718 LIMIT 1
719 ],
720 undef,
721 $queue_label,
722 );
723 }
724 else {
725 ( $hash_id, $batch_id ) = $self->dbh->selectrow_array(
726 q[
727 SELECT hash_id,
728 batch_id
729 FROM test_results
730 WHERE progress = 0
731 ORDER BY priority DESC,
732 id ASC
733 LIMIT 1
734 ],
735 );
736 }
737  
738 if ( defined $hash_id ) {
739  
740 # ... and race to be the first to claim it ...
741 if ( $self->claim_test( $hash_id ) ) {
742 return ( $hash_id, $batch_id );
743 }
744 }
745 else {
746 # ... or stop trying if there are no candidates.
747 return ( undef, undef );
748 }
749 }
750 }
751  
752 =head2 claim_test( $test_id )
753  
754 Claim a test for processing.
755  
756 Transitions a test from the "waiting" state to the "running" state.
757  
758 Returns true on successful transition.
759 Returns false if the given test does not exist or if it is not in the "waiting"
760 state.
761  
762 Dies when an error occurs in the database interface.
763  
764 =cut
765  
766 sub claim_test {
767 my ( $self, $test_id ) = @_;
768  
769 my $rows_affected = $self->dbh->do(
770 q[
771 UPDATE test_results
772 SET progress = 1,
773 started_at = ?
774 WHERE hash_id = ?
775 AND progress = 0
776 ],
777 undef,
778 $self->format_time( time() ),
779 $test_id,
780 );
781  
782 return $rows_affected == 1;
783 }
784  
785 sub get_test_params {
786 my ( $self, $test_id ) = @_;
787  
788 my $dbh = $self->dbh;
789 my ( $params_json ) = $dbh->selectrow_array( "SELECT params FROM test_results WHERE hash_id = ?", undef, $test_id );
790  
791 die Zonemaster::Backend::Error::ResourceNotFound->new( message => "Test not found", data => { test_id => $test_id } )
792 unless defined $params_json;
793  
794 my $result;
795 eval {
796 $result = decode_json( $params_json );
797 };
798  
799 die Zonemaster::Backend::Error::JsonError->new( reason => "$@", data => { test_id => $test_id } )
800 if $@;
801  
802 return $result;
803 }
804  
805 =head2 batch_status
806  
807 Returns number of tests per category (finished, running, waiting) for the given
808 batch, provided as C<batch_id>.
809  
810 If one or more of parameters C<list_running_tests>, C<list_finished_tests> or
811 C<list_waiting_tests> are included with true value, the C<hash_id> values for
812 that category is also included.
813  
814 =cut
815  
816 # Standard SQL, can be here
817 sub batch_status {
818 my ( $self, $test_params ) = @_;
819  
820 my $batch_id = $test_params->{batch_id};
821  
822 die Zonemaster::Backend::Error::ResourceNotFound->new( message => "Unknown batch", data => { batch_id => $batch_id } )
823 unless defined $self->batch_exists_in_db( $batch_id );
824  
825 my $dbh = $self->dbh;
826  
827 my %result;
828 $result{waiting_count} = 0;
829 $result{running_count} = 0;
830 $result{finished_count} = 0;
831  
832 my $query = "
833 SELECT hash_id, progress
834 FROM test_results
835 WHERE batch_id=?";
836  
837 my $sth1 = $dbh->prepare( $query );
838 $sth1->execute( $batch_id );
839  
840 while ( my $h = $sth1->fetchrow_hashref ) {
841 if ( $h->{progress} eq '0' ) {
842 $result{waiting_count}++;
843 push(@{$result{waiting_tests}}, $h->{hash_id}) if $test_params->{list_waiting_tests};
844 }
845 elsif ( $h->{progress} eq '100' ) {
846 $result{finished_count}++;
847 push(@{$result{finished_tests}}, $h->{hash_id}) if $test_params->{list_finished_tests};
848 }
849 else {
850 $result{running_count}++;
851 push(@{$result{running_tests}}, $h->{hash_id}) if $test_params->{list_running_tests};
852 }
853 }
854  
855 return \%result;
856 }
857  
858  
859 =head2 process_unfinished_tests($queue_label, $test_run_timeout)
860  
861 Append a new log entry C<BACKEND_TEST_AGENT:UNABLE_TO_FINISH_TEST> to all the
862 tests started more that $test_run_timeout seconds in the queue $queue_label.
863 Then store the results in database.
864  
865 =cut
866  
867 sub process_unfinished_tests {
868 my ( $self, $queue_label, $test_run_timeout ) = @_;
869  
870 my $sth1 = $self->select_unfinished_tests( #
871 $queue_label,
872 $test_run_timeout,
873 );
874  
875 my $msg = Zonemaster::Engine::Logger::Entry->new(
876 {
877 level => "CRITICAL",
878 module => "Backend",
879 testcase => "",
880 tag => "UNABLE_TO_FINISH_TEST",
881 args => { max_execution_time => $test_run_timeout },
882 timestamp => $test_run_timeout
883 }
884 );
885 while ( my $h = $sth1->fetchrow_hashref ) {
886 $self->force_end_test($h->{hash_id}, $msg);
887 }
888 }
889  
890 =head2 select_unfinished_tests($queue_label, $test_run_timeout)
891  
892 Search for all tests started more than $test_run_timeout seconds in the queue
893 $queue_label.
894  
895 =cut
896  
897 sub select_unfinished_tests {
898 my ( $self, $queue_label, $test_run_timeout ) = @_;
899  
900 if ( $queue_label ) {
901 my $sth = $self->dbh->prepare( "
902 SELECT hash_id, results
903 FROM test_results
904 WHERE started_at < ?
905 AND progress > 0
906 AND progress < 100
907 AND queue = ?" );
908 $sth->execute( #
909 $self->format_time( time() - $test_run_timeout ),
910 $queue_label,
911 );
912 return $sth;
913 }
914 else {
915 my $sth = $self->dbh->prepare( "
916 SELECT hash_id, results
917 FROM test_results
918 WHERE started_at < ?
919 AND progress > 0
920 AND progress < 100" );
921 $sth->execute( #
922 $self->format_time( time() - $test_run_timeout ),
923 );
924 return $sth;
925 }
926 }
927  
928 =head2 force_end_test($hash_id, $msg)
929  
930 Store the L<Zonemaster::Engine::Logger::Entry> $msg log entry into the database
931 and mark test with $hash_id as COMPLETED.
932  
933 =cut
934  
935 sub force_end_test {
936 my ( $self, $hash_id, $msg ) = @_;
937  
938 $self->add_result_entries( $hash_id, $msg );
939 $self->set_test_completed( $hash_id );
940 }
941  
942 =head2 process_dead_test($hash_id)
943  
944 Store a new log entry C<BACKEND_TEST_AGENT:TEST_DIED> in database for the test
945 with $hash_id.
946  
947 =cut
948  
949 sub process_dead_test {
950 my ( $self, $hash_id ) = @_;
951 my $msg = Zonemaster::Engine::Logger::Entry->new(
952 {
953 level => "CRITICAL",
954 module => "Backend",
955 testcase => "",
956 tag => "TEST_DIED",
957 args => {},
958 timestamp => $self->get_relative_start_time($hash_id)
959 }
960 );
961 $self->force_end_test($hash_id, $msg);
962 }
963  
964 # Converts the domain to lowercase and if the domain is not the root ('.')
965 # removes any trailing dot
966 sub _normalize_domain {
967 my ( $domain ) = @_;
968  
969 my ( $errors, $normalized_domain ) = normalize_name( trim_space( $domain ) );
970  
971 if ( scalar( @{$errors} ) ) {
972 die Zonemaster::Backend::Error::Internal->new( reason => "Normalizing domain returned errors.", data => [ map { $_->string } @{$errors} ] );
973 }
974  
975 return $normalized_domain;
976 }
977  
978 sub _project_params {
979 my ( $self, $params ) = @_;
980  
981 my %projection = ();
982  
983 $projection{domain} = _normalize_domain( $$params{domain} // "" );
984 $projection{ipv4} = $$params{ipv4};
985 $projection{ipv6} = $$params{ipv6};
986 $projection{profile} = lc( $$params{profile} // "default" );
987  
988 my $array_ds_info = $$params{ds_info} // [];
989 my @array_ds_info_sort = sort {
990 $a->{algorithm} cmp $b->{algorithm} or
991 $a->{digest} cmp $b->{digest} or
992 $a->{digtype} <=> $b->{digtype} or
993 $a->{keytag} <=> $b->{keytag}
994 } @$array_ds_info;
995  
996 $projection{ds_info} = \@array_ds_info_sort;
997  
998 my $array_nameservers = $$params{nameservers} // [];
999 for my $nameserver (@$array_nameservers) {
1000 if ( defined $$nameserver{ip} and $$nameserver{ip} eq "" ) {
1001 delete $$nameserver{ip};
1002 }
1003 $$nameserver{ns} = _normalize_domain( $$nameserver{ns} );
1004 }
1005 my @array_nameservers_sort = sort {
1006 $a->{ns} cmp $b->{ns} or
1007 ( defined $a->{ip} and defined $b->{ip} and $a->{ip} cmp $b->{ip} )
1008 } @$array_nameservers;
1009  
1010 $projection{nameservers} = \@array_nameservers_sort;
1011  
1012 return \%projection;
1013 }
1014  
1015 # Take a params object with text strings and return an UTF-8 binary string
1016 sub _params_to_json_str {
1017 my ( $self, $params ) = @_;
1018  
1019 my $js = JSON::PP->new;
1020 $js->canonical( 1 );
1021 $js->utf8( 1 );
1022  
1023 my $encoded_params = $js->encode( $params );
1024  
1025 return $encoded_params;
1026 }
1027  
1028 =head2 encode_params
1029  
1030 Encode the params object into a JSON string. First a projection of some
1031 parameters is performed then all additional properties are kept.
1032 Returns an UTF-8 binary string of the union of the given hash and its
1033 normalization using default values, see
1034 L<https://github.com/zonemaster/zonemaster/blob/master/docs/public/using/backend/rpcapi-reference.md#params-2>
1035  
1036 =cut
1037  
1038 sub encode_params {
1039 my ( $self, $params ) = @_;
1040  
1041 my $projected_params = $self->_project_params( $params );
1042 $params = { %$params, %$projected_params };
1043 my $encoded_params = $self->_params_to_json_str( $params );
1044  
1045 return $encoded_params;
1046 }
1047  
1048 =head2 generate_fingerprint
1049  
1050 Returns a fingerprint (an UTF-8 binary string) of the hash passed in argument
1051 (which contain text string).
1052 The fingerprint is computed after projecting the hash.
1053 Such fingerprint are usefull to find similar tests in the database.
1054  
1055 =cut
1056  
1057 sub generate_fingerprint {
1058 my ( $self, $params ) = @_;
1059  
1060 my $projected_params = $self->_project_params( $params );
1061 my $encoded_params = $self->_params_to_json_str( $projected_params );
1062 my $fingerprint = md5_hex( $encoded_params );
1063  
1064 return $fingerprint;
1065 }
1066  
1067  
1068 =head2 undelegated
1069  
1070 Returns the value 1 if the test to be created is if type undelegated,
1071 else value 0. The test is considered to be undelegated if the "ds_info" or
1072 "nameservers" parameters is are defined with data after projection.
1073  
1074 =cut
1075  
1076 sub undelegated {
1077 my ( $self, $params ) = @_;
1078  
1079 my $projected_params = $self->_project_params( $params );
1080  
1081 return 1 if defined( $$projected_params{ds_info}[0] );
1082 return 1 if defined( $$projected_params{nameservers}[0] );
1083 return 0;
1084 }
1085  
1086 sub format_time {
1087 my ( $class, $time ) = @_;
1088 return strftime "%Y-%m-%d %H:%M:%S", gmtime( $time );
1089 }
1090  
1091 sub to_iso8601 {
1092 my ( $class, $time ) = @_;
1093 $time =~ s/^([^ ]+) (.*)$/$1T$2Z/;
1094 return $time;
1095 }
1096  
1097 sub add_result_entries {
1098 my ( $self, $hash_id, @entries ) = @_;
1099 my @records;
1100  
1101 my $json = JSON::PP->new->allow_blessed->convert_blessed->canonical;
1102  
1103 my %levels = Zonemaster::Engine::Logger::Entry->levels();
1104  
1105 foreach my $e ( @entries ) {
1106 my $r = [
1107 $hash_id,
1108 $levels{ $e->level },
1109 $e->module,
1110 $e->testcase,
1111 $e->tag,
1112 $e->timestamp,
1113 $json->encode( $e->args // {} ),
1114 ];
1115  
1116 push @records, $r;
1117 }
1118 my $query_values = join ", ", ("(?, ?, ?, ?, ?, ?, ?)") x @records;
1119 my $query = "INSERT INTO result_entries (hash_id, level, module, testcase, tag, timestamp, args) VALUES $query_values";
1120 my $sth = $self->dbh->prepare($query);
1121 $sth = $sth->execute(map { @$_ } @records);
1122 }
1123  
1124 no Moose::Role;
1125  
1126 1;