Zonemaster/Backend/DB.pm untested

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