Zonemaster/Backend/DB/MySQL.pm untested

filter: Statementstmt 0.0% 0 / 123 Branchbran 0.0% 0 / 28 Conditioncond 0.0% 0 / 10 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 15 Podpod 0.0% 0 / 7 totaltotal 0.0% 0 / 183 CC 15 SCAR 35.5
CC
15
Cov
0%
create_schema
90.0
drop_tables
30.0
from_config
6.0
CRAP 34.7
1 package Zonemaster::Backend::DB::MySQL;
2  
3 our $VERSION = '1.1.0';
4  
5 use Moose;
6 use 5.14.2;
7  
8 use DBI qw(:utils);
9 use Digest::MD5 qw(md5_hex);
10 use JSON::PP;
11  
12 use Zonemaster::Backend::Validator qw( untaint_ipv6_address );
13 use Zonemaster::Backend::Errors;
14  
15 with 'Zonemaster::Backend::DB';
16  
17 =head1 CLASS METHODS
18  
19 =head2 from_config
20  
21 Construct a new instance from a Zonemaster::Backend::Config.
22  
23 my $db = Zonemaster::Backend::DB::MySQL->from_config( $config );
24  
25 =cut
26  
27 sub from_config {
28 my ( $class, $config ) = @_;
29  
30 my $database = $config->MYSQL_database;
31 my $host = $config->MYSQL_host;
32 my $port = $config->MYSQL_port;
33 my $user = $config->MYSQL_user;
34 my $password = $config->MYSQL_password;
35  
36 if ( untaint_ipv6_address( $host ) ) {
37 $host = "[$host]";
38 }
39  
40 my $data_source_name = "DBI:mysql:database=$database;host=$host;port=$port";
41  
42 return $class->new(
43 {
44 data_source_name => $data_source_name,
45 user => $user,
46 password => $password,
47 dbhandle => undef,
48 }
49 );
50 }
51  
52 sub get_dbh_specific_attributes {
53 return {};
54 }
55  
56 sub create_schema {
57 my ( $self ) = @_;
58  
59 my $dbh = $self->dbh;
60  
61 ####################################################################
62 # TEST RESULTS
63 ####################################################################
64 $dbh->do(
65 'CREATE TABLE IF NOT EXISTS test_results (
66 id BIGINT AUTO_INCREMENT PRIMARY KEY,
67 hash_id VARCHAR(16) NOT NULL,
68 domain varchar(255) NOT NULL,
69 batch_id integer NULL,
70 created_at DATETIME NOT NULL,
71 started_at DATETIME DEFAULT NULL,
72 ended_at DATETIME DEFAULT NULL,
73 priority integer DEFAULT 10,
74 queue integer DEFAULT 0,
75 progress integer DEFAULT 0,
76 fingerprint character varying(32),
77 params blob NOT NULL,
78 results mediumblob DEFAULT NULL,
79 undelegated integer NOT NULL DEFAULT 0,
80  
81 UNIQUE (hash_id)
82 ) ENGINE=InnoDB
83 '
84 ) or die Zonemaster::Backend::Error::Internal->new( reason => "MySQL error, could not create 'test_results' table", data => $dbh->errstr() );
85  
86 # Manually create the index if it does not exist
87 # the clause IF NOT EXISTS is not available for MySQL (used with FreeBSD)
88  
89 # retrieve all indexes by key name
90 my $indexes = $dbh->selectall_hashref( 'SHOW INDEXES FROM test_results', 'Key_name' );
91  
92 if ( not exists($indexes->{test_results__hash_id}) ) {
93 $dbh->do(
94 'CREATE INDEX test_results__hash_id ON test_results (hash_id)'
95 );
96 }
97 if ( not exists($indexes->{test_results__fingerprint}) ) {
98 $dbh->do(
99 'CREATE INDEX test_results__fingerprint ON test_results (fingerprint)'
100 );
101 }
102 if ( not exists($indexes->{test_results__batch_id_progress}) ) {
103 $dbh->do(
104 'CREATE INDEX test_results__batch_id_progress ON test_results (batch_id, progress)'
105 );
106 }
107 if ( not exists($indexes->{test_results__progress}) ) {
108 $dbh->do(
109 'CREATE INDEX test_results__progress ON test_results (progress)'
110 );
111 }
112 if ( not exists($indexes->{test_results__domain_undelegated}) ) {
113 $dbh->do(
114 'CREATE INDEX test_results__domain_undelegated ON test_results (domain, undelegated)'
115 );
116 }
117  
118 ####################################################################
119 # LOG LEVEL
120 ####################################################################
121 $dbh->do(
122 "CREATE TABLE IF NOT EXISTS log_level (
123 value INT,
124 level VARCHAR(15),
125  
126 UNIQUE (value)
127 ) ENGINE=InnoDB
128 "
129 ) or die Zonemaster::Backend::Error::Internal->new( reason => "MySQL error, could not create 'log_level' table", data => $dbh->errstr() );
130  
131 my ( $c ) = $dbh->selectrow_array( "SELECT count(*) FROM log_level" );
132 if ( $c == 0 ) {
133 $dbh->do(
134 "INSERT INTO log_level (value, level)
135 VALUES
136 (-2, 'DEBUG3'),
137 (-1, 'DEBUG2'),
138 ( 0, 'DEBUG'),
139 ( 1, 'INFO'),
140 ( 2, 'NOTICE'),
141 ( 3, 'WARNING'),
142 ( 4, 'ERROR'),
143 ( 5, 'CRITICAL')
144 "
145 );
146 }
147  
148 ####################################################################
149 # RESULT ENTRIES
150 ####################################################################
151 $dbh->do(
152 "CREATE TABLE IF NOT EXISTS result_entries (
153 hash_id VARCHAR(16) NOT NULL,
154 level INT NOT NULL,
155 module VARCHAR(255) NOT NULL,
156 testcase VARCHAR(255) NOT NULL,
157 tag VARCHAR(255) NOT NULL,
158 timestamp REAL NOT NULL,
159 args BLOB NOT NULL,
160  
161 CONSTRAINT fk_hash_id FOREIGN KEY (hash_id) REFERENCES test_results(hash_id),
162 CONSTRAINT fk_level FOREIGN KEY (level) REFERENCES log_level(value)
163 ) ENGINE=InnoDB
164 "
165 ) or die Zonemaster::Backend::Error::Internal->new( reason => "MySQL error, could not create 'result_entries' table", data => $dbh->errstr() );
166  
167 $indexes = $dbh->selectall_hashref( 'SHOW INDEXES FROM result_entries', 'Key_name' );
168 if ( not exists($indexes->{result_entries__hash_id}) ) {
169 $dbh->do(
170 'CREATE INDEX result_entries__hash_id ON result_entries (hash_id)'
171 );
172 }
173  
174 if ( not exists($indexes->{result_entries__level}) ) {
175 $dbh->do(
176 'CREATE INDEX result_entries__level ON result_entries (level)'
177 );
178 }
179  
180  
181 ####################################################################
182 # BATCH JOBS
183 ####################################################################
184 $dbh->do(
185 'CREATE TABLE IF NOT EXISTS batch_jobs (
186 id integer AUTO_INCREMENT PRIMARY KEY,
187 username character varying(50) NOT NULL,
188 created_at DATETIME NOT NULL
189 ) ENGINE=InnoDB;
190 '
191 ) or die Zonemaster::Backend::Error::Internal->new( reason => "MySQL error, could not create 'batch_jobs' table", data => $dbh->errstr() );
192  
193  
194 ####################################################################
195 # USERS
196 ####################################################################
197 $dbh->do(
198 'CREATE TABLE IF NOT EXISTS users (
199 id integer AUTO_INCREMENT primary key,
200 username varchar(128),
201 api_key varchar(512),
202  
203 UNIQUE (username)
204 ) ENGINE=InnoDB;
205 '
206 ) or die Zonemaster::Backend::Error::Internal->new( reason => "MySQL error, could not create 'users' table", data => $dbh->errstr() );
207  
208 return;
209 }
210  
211 =head2 drop_tables
212  
213 Drop all the tables if they exist.
214  
215 =cut
216  
217 sub drop_tables {
218 my ( $self ) = @_;
219  
220 # remove any FOREIGN KEY before droping the table
221 # MariaDB <10.4 and MySQL do not support the IF EXISTS syntax
222 # on ALTER TABLE and DROP FOREIGN KEY
223 # MariaDB 10.3 is used on Ubuntu 20.04 LTS (eol 2023-04)
224 # MySQL is used on FreeBSD
225 my $tables = $self->dbh->selectall_hashref( 'SHOW TABLE STATUS', 'Name' );
226 if ( exists $tables->{result_entries} ) {
227 my @fk = $self->dbh->selectall_array( 'SELECT constraint_name FROM information_schema.referential_constraints' );
228 @fk = map { ref eq 'ARRAY' ? @$_ : $_ } @fk;
229 if ( grep( /^fk_hash_id$/, @fk ) ) {
230 $self->dbh->do( "ALTER TABLE result_entries DROP FOREIGN KEY fk_hash_id" );
231 }
232 if ( grep( /^fk_level$/, @fk ) ) {
233 $self->dbh->do( "ALTER TABLE result_entries DROP FOREIGN KEY fk_level" );
234 }
235 }
236  
237 $self->dbh->do( "DROP TABLE IF EXISTS test_results" );
238 $self->dbh->do( "DROP TABLE IF EXISTS result_entries" );
239 $self->dbh->do( "DROP TABLE IF EXISTS log_level" );
240 $self->dbh->do( "DROP TABLE IF EXISTS users" );
241 $self->dbh->do( "DROP TABLE IF EXISTS batch_jobs" );
242  
243 return;
244 }
245  
246 sub add_batch_job {
247 my ( $self, $params ) = @_;
248 my $batch_id;
249  
250 my $dbh = $self->dbh;
251  
252 if ( $self->user_authorized( $params->{username}, $params->{api_key} ) ) {
253 $batch_id = $self->create_new_batch_job( $params->{username} );
254  
255 my $test_params = $params->{test_params};
256 my $priority = $test_params->{priority};
257 my $queue_label = $test_params->{queue};
258  
259 $dbh->{AutoCommit} = 0;
260 eval {$dbh->do( "DROP INDEX test_results__hash_id ON test_results" );};
261 eval {$dbh->do( "DROP INDEX test_results__fingerprint ON test_results" );};
262 eval {$dbh->do( "DROP INDEX test_results__batch_id_progress ON test_results" );};
263 eval {$dbh->do( "DROP INDEX test_results__progress ON test_results" );};
264 eval {$dbh->do( "DROP INDEX test_results__domain_undelegated ON test_results" );};
265  
266 my $sth = $dbh->prepare(
267 q[
268 INSERT INTO test_results (
269 hash_id,
270 domain,
271 batch_id,
272 created_at,
273 priority,
274 queue,
275 fingerprint,
276 params,
277 undelegated
278 ) VALUES (?,?,?,?,?,?,?,?,?)
279 ],
280 );
281 foreach my $domain ( @{$params->{domains}} ) {
282 $test_params->{domain} = _normalize_domain( $domain );
283  
284 my $fingerprint = $self->generate_fingerprint( $test_params );
285 my $encoded_params = $self->encode_params( $test_params );
286 my $undelegated = $self->undelegated ( $test_params );
287  
288 my $hash_id = substr(md5_hex(time().rand()), 0, 16);
289 $sth->execute(
290 $hash_id,
291 $test_params->{domain},
292 $batch_id,
293 $self->format_time( time() ),
294 $priority,
295 $queue_label,
296 $fingerprint,
297 $encoded_params,
298 $undelegated,
299 );
300 }
301 $dbh->do( "CREATE INDEX test_results__hash_id ON test_results (hash_id, created_at)" );
302 $dbh->do( "CREATE INDEX test_results__fingerprint ON test_results (fingerprint)" );
303 $dbh->do( "CREATE INDEX test_results__batch_id_progress ON test_results (batch_id, progress)" );
304 $dbh->do( "CREATE INDEX test_results__progress ON test_results (progress)" );
305 $dbh->do( "CREATE INDEX test_results__domain_undelegated ON test_results (domain, undelegated)" );
306  
307 $dbh->commit();
308 $dbh->{AutoCommit} = 1;
309 }
310 else {
311 die Zonemaster::Backend::Error::PermissionDenied->new( message => 'User not authorized to use batch mode', data => { username => $params->{username}} );
312 }
313  
314 return $batch_id;
315 }
316  
317 sub get_relative_start_time {
318 my ( $self, $hash_id ) = @_;
319  
320 return $self->dbh->selectrow_array(
321 q[
322 SELECT ? - started_at
323 FROM test_results
324 WHERE hash_id = ?
325 ],
326 undef,
327 $self->format_time( time() ),
328 $hash_id,
329 );
330 }
331  
332 sub is_duplicate {
333 my ( $self ) = @_;
334  
335 # for the list of codes see:
336 # https://mariadb.com/kb/en/mariadb-error-codes/
337 # https://dev.mysql.com/doc/mysql-errors/8.0/en/server-error-reference.html
338 return ( $self->dbh->err == 1062 );
339 }
340  
341 no Moose;
342 __PACKAGE__->meta()->make_immutable();
343  
344 1;