blib/lib/App/Netdisco/JobQueue/PostgreSQL.pm untested

filter: Statementstmt 0.0% 0 / 222 Branchbran 0.0% 0 / 56 Conditioncond 0.0% 0 / 43 MC/DCmcdc 0.0% 0 / 24 Subroutinesub 0.0% 0 / 19 Podpod 0.0% 0 / 11 totaltotal 0.0% 0 / 375 CC 29 SCAR 36.3
CC
29
Cov
0%
jq_log
72.0
jq_insert
72.0
jq_getsome
56.0
CRAP 37.8
1 package App::Netdisco::JobQueue::PostgreSQL;
2  
3 use Dancer qw/:moose :syntax :script/;
4 use Dancer::Plugin::DBIC 'schema';
5  
6 use App::Netdisco::Util::Device 'get_denied_actions';
7 use App::Netdisco::Backend::Job;
8 use App::Netdisco::DB::ExplicitLocking ':modes';
9  
10 use JSON::PP ();
11 use Try::Tiny;
12  
13 use base 'Exporter';
14 our @EXPORT = ();
15 our @EXPORT_OK = qw/
16 jq_warm_thrusters
17 jq_getsome
18 jq_locked
19 jq_queued
20 jq_lock
21 jq_defer
22 jq_complete
23 jq_log
24 jq_userlog
25 jq_insert
26 jq_delete
27 /;
28 our %EXPORT_TAGS = ( all => \@EXPORT_OK );
29  
30 sub jq_warm_thrusters {
31 my $rs = schema(vars->{'tenant'})->resultset('DeviceSkip');
32  
33 schema(vars->{'tenant'})->txn_do(sub {
34 $rs->search({
35 backend => setting('workers')->{'BACKEND'},
36 }, { for => 'update' }, )->update({ actionset => [] });
37  
38 # on backend restart, allow one retry of all devices which have
39 # reached max retry (max_deferrals)
40 my $deferrals = setting('workers')->{'max_deferrals'} - 1;
41 $rs->search({
42 backend => setting('workers')->{'BACKEND'},
43 device => { '!=' => '255.255.255.255' },
44 deferrals => { '>' => $deferrals },
45 }, { for => 'update' }, )->update({ deferrals => $deferrals });
46  
47 $rs->search({
48 backend => setting('workers')->{'BACKEND'},
49 actionset => { -value => [] }, # special syntax for matching empty ARRAY
50 deferrals => 0,
51 })->delete;
52  
53 # also clean out any previous backend hint
54 # primeskiplist action will then run to recreate it
55 $rs->search({
56 backend => setting('workers')->{'BACKEND'},
57 device => '255.255.255.255',
58 actionset => { -value => [] }, # special syntax for matching empty ARRAY
59 })->delete;
60 });
61 }
62  
63 sub jq_getsome {
64 my ($num_slots, %queue) = @_;
65 return () unless $num_slots and $num_slots > 0;
66  
67 # a reserved queue takes only its actions, the general queue takes all but
68 # the reserved ones. with neither (an empty exclusion) every action matches.
69 my $actions = $queue{actions} || [];
70 my $only = ($queue{only} ? 'true' : 'false');
71  
72 my $jobs = schema(vars->{'tenant'})->resultset('Admin');
73 my @returned = ();
74  
75 # dbic reads any two element arrayref in bind as [ column, value ], so a list
76 # of exactly two would lose its first. [ undef, ... ] passes it through whole.
77 my $tasty = schema(vars->{'tenant'})->resultset('Virtual::TastyJobs')
78 ->search(undef,{ bind => [
79 setting('workers')->{'BACKEND'}, [ undef, $actions ], $only,
80 [ undef, setting('job_prio')->{'high'} ],
81 setting('workers')->{'BACKEND'}, setting('workers')->{'max_deferrals'},
82 setting('workers')->{'retry_after'}, $num_slots,
83 ]});
84  
85 while (my $job = $tasty->next) {
86 if ($job->device
87 and not scalar grep {$job->action eq $_} @{ setting('job_targets_prefix') }) {
88  
89 # need to handle device discovered since backend daemon started
90 # and the skiplist was primed. these should be checked against
91 # the various acls and have device_skip entry added if needed,
92 # and return false if it should have been skipped.
93 my @badactions = get_denied_actions($job->device);
94 if (scalar @badactions) {
95 schema(vars->{'tenant'})->resultset('DeviceSkip')->txn_do_locked(EXCLUSIVE, sub {
96 schema(vars->{'tenant'})->resultset('DeviceSkip')->find_or_create({
97 backend => setting('workers')->{'BACKEND'}, device => $job->device,
98 },{ key => 'device_skip_pkey' })->add_to_actionset(@badactions);
99 });
100  
101 # will now not be selected in a future _getsome()
102 next if scalar grep {$_ eq $job->action} @badactions;
103 }
104 }
105  
106 # remove any duplicate jobs, incuding possibly this job if there
107 # is already an equivalent job running
108  
109 # note that the self-removal of a job has an unhelpful log: it is
110 # reported as a duplicate of itself! however what's happening is that
111 # netdisco has seen another running job with same params (but the query
112 # cannot see that ID to use it in the message).
113  
114 my %job_properties = (
115 action => $job->action,
116 port => $job->port,
117 subaction => $job->subaction,
118 -or => [
119 { device => $job->device },
120 ($job->device_key ? ({ device_key => $job->device_key }) : ()),
121 ],
122 # never de-duplicate user-submitted jobs
123 username => { '=' => undef },
124 userip => { '=' => undef },
125 );
126  
127 my $gone = $jobs->search({
128 status => 'queued',
129 -and => [
130 %job_properties,
131 -or => [{
132 job => { '<' => $job->id },
133 },{
134 job => $job->id,
135 -exists => $jobs->search({
136 job => { '>' => $job->id },
137 status => 'queued',
138 backend => { '!=' => undef },
139 started => \[q/> (LOCALTIMESTAMP - ?::interval)/, setting('jobs_stale_after')],
140 %job_properties,
141 })->as_query,
142 }],
143 ],
144 }, { for => 'update' })
145 ->update({ status => 'info', log => (sprintf 'duplicate of %s', $job->id) });
146  
147 debug sprintf 'getsome: cancelled %s duplicate(s) of job %s', ($gone || 0), $job->id;
148 push @returned, App::Netdisco::Backend::Job->new({ $job->get_columns });
149 }
150  
151 return @returned;
152 }
153  
154 sub jq_locked {
155 my @returned = ();
156 my $rs = schema(vars->{'tenant'})->resultset('Admin')->search({
157 status => 'queued',
158 backend => setting('workers')->{'BACKEND'},
159 started => \[q/> (LOCALTIMESTAMP - ?::interval)/, setting('jobs_stale_after')],
160 });
161  
162 while (my $job = $rs->next) {
163 push @returned, App::Netdisco::Backend::Job->new({ $job->get_columns });
164 }
165 return @returned;
166 }
167  
168 sub jq_queued {
169 my $job_type = shift;
170  
171 return schema(vars->{'tenant'})->resultset('Admin')->search({
172 device => { '!=' => undef},
173 action => $job_type,
174 status => 'queued',
175 })->get_column('device')->all;
176 }
177  
178 sub jq_lock {
179 my $job = shift;
180 return true unless $job->id;
181 my $happy = false;
182  
183 # lock db row and update to show job has been picked
184 try {
185 my $updated = schema(vars->{'tenant'})->resultset('Admin')
186 ->search({ job => $job->id, status => 'queued' }, { for => 'update' })
187 ->update({
188 status => 'queued',
189 backend => setting('workers')->{'BACKEND'},
190 started => \"LOCALTIMESTAMP",
191 });
192  
193 $happy = true if $updated > 0;
194 }
195 catch {
196 error $_;
197 };
198  
199 return $happy;
200 }
201  
202 sub jq_defer {
203 my $job = shift;
204 my $happy = false;
205  
206 # note this taints all actions on the device. for example if both
207 # macsuck and arpnip are allowed, but macsuck fails 10 times, then
208 # arpnip (and every other action) will be prevented on the device.
209  
210 # seeing as defer is only triggered by an SNMP connect failure, this
211 # behaviour seems reasonable, to me (or desirable, perhaps).
212  
213 # the deferrable_actions setting exists as a workaround to this behaviour
214 # should it be needed by any action (that is, per-device action but
215 # do not increment deferrals count and simply try to run again).
216  
217 try {
218 schema(vars->{'tenant'})->resultset('DeviceSkip')->txn_do_locked(EXCLUSIVE, sub {
219 if ($job->device
220 and not scalar grep { $job->action eq $_ }
221 @{ setting('deferrable_actions') || [] }) {
222  
223 schema(vars->{'tenant'})->resultset('DeviceSkip')->find_or_create({
224 backend => setting('workers')->{'BACKEND'}, device => $job->device,
225 },{ key => 'device_skip_pkey' })->increment_deferrals;
226 }
227  
228 debug sprintf 'defer: job %s', ($job->id || 'unknown');
229  
230 # lock db row and update to show job is available
231 schema(vars->{'tenant'})->resultset('Admin')
232 ->search({ job => $job->id }, { for => 'update' })
233 ->update({
234 device => $job->device, # if job had alias this sets to canonical
235 status => 'queued',
236 backend => undef,
237 started => undef,
238 log => $job->log,
239 });
240 });
241 $happy = true;
242 }
243 catch {
244 error $_;
245 };
246  
247 return $happy;
248 }
249  
250 sub jq_complete {
251 my $job = shift;
252 my $happy = false;
253  
254 # lock db row and update to show job is done/error
255  
256 # now that SNMP connect failures are deferrals and not errors, any complete
257 # status, whether success or failure, indicates an SNMP connect. reset the
258 # connection failures counter to forget about occasional connect glitches.
259  
260 try {
261 schema(vars->{'tenant'})->resultset('DeviceSkip')->txn_do_locked(EXCLUSIVE, sub {
262 if ($job->device and not $job->is_offline
263 and not scalar grep {$job->action eq $_} @{ setting('job_targets_prefix') }) {
264  
265 schema(vars->{'tenant'})->resultset('DeviceSkip')->find_or_create({
266 backend => setting('workers')->{'BACKEND'}, device => $job->device,
267 },{ key => 'device_skip_pkey' })->update({ deferrals => 0 });
268 }
269  
270 schema(vars->{'tenant'})->resultset('Admin')
271 ->search({ job => $job->id }, { for => 'update' })
272 ->update({
273 status => $job->status,
274 log => (ref($job->log) eq ref('')) ? $job->log : '',
275 started => $job->started,
276 finished => $job->finished,
277 (($job->action eq 'hook') ? (subaction => $job->subaction) : ()),
278 ($job->only_namespace ? (action => ($job->action .'::'. $job->only_namespace)) : ()),
279 });
280 });
281 $happy = true;
282 }
283 catch {
284 # use DDP; p $job;
285 error $_;
286 };
287  
288 return $happy;
289 }
290  
291 sub jq_log {
292 return schema(vars->{'tenant'})->resultset('Admin')->search({
293 (param('backend') ? ('me.backend' => param('backend')) : ()),
294 (param('action') ? ('me.action' => param('action')) : ()),
295 # not target.ip: the join makes it equal to me.device, and an OR with it
296 # stops PostgreSQL using the admin(device) index
297 (param('device') ? ('me.device' => param('device')) : ()),
298 (param('username') ? ('me.username' => param('username')) : ()),
299 (param('status') ? (
300 (param('status') eq 'Running') ? (
301 -and => [
302 { 'me.backend' => { '!=' => undef } },
303 { 'me.status' => 'queued' },
304 ],
305 ) : (
306 'me.status' => lc(param('status'))
307 )
308 ) : ()),
309 (param('duration') ? (
310 -bool => [
311 -or => [
312 {
313 'me.finished' => undef,
314 'me.started' => { '<' => \[q{(CURRENT_TIMESTAMP - ? ::interval)}, param('duration') .' minutes'] },
315 },
316 -and => [
317 { 'me.started' => { '!=' => undef } },
318 { 'me.finished' => { '!=' => undef } },
319 \[ q{ (me.finished - me.started) > ? ::interval }, param('duration') .' minutes'],
320 ],
321 ],
322 ],
323 ) : ()),
324 'me.log' => [
325 { '=' => undef },
326 { '-not_like' => 'duplicate of %' },
327 ],
328 }, {
329 prefetch => 'target',
330 order_by => { -desc => [qw/entered device action/] },
331 rows => (setting('jobs_qdepth') || 50),
332 })->with_times->hri->all;
333 }
334  
335 sub jq_userlog {
336 my $user = shift;
337 return schema(vars->{'tenant'})->resultset('Admin')->search({
338 username => $user,
339 log => { '-not_like' => 'duplicate of %' },
340 finished => { '>' => \"(CURRENT_TIMESTAMP - interval '5 seconds')" },
341 })->with_times->all;
342 }
343  
344 sub jq_insert {
345 my $jobs = shift;
346 $jobs = [$jobs] if ref [] ne ref $jobs;
347  
348 my $happy = false;
349 try {
350 schema(vars->{'tenant'})->txn_do(sub {
351 if (scalar @$jobs == 1 and defined $jobs->[0]->{device} and
352 scalar grep {$_ eq $jobs->[0]->{action}} @{ setting('_inline_actions') || [] }) {
353  
354 # bit of a hack for heroku hosting to avoid DB overload
355 return true if setting('defanged_admin') ne 'admin';
356  
357 my $spec = $jobs->[0];
358 my $row = undef;
359  
360 if ($spec->{port}) {
361 $row = schema(vars->{'tenant'})->resultset('DevicePort')
362 ->find($spec->{port}, $spec->{device});
363 undef $row unless
364 scalar grep {('cf_'. $_) eq $spec->{action}}
365 grep {defined}
366 map {$_->{name}}
367 @{ setting('custom_fields')->{device_port} || [] };
368 }
369 else {
370 $row = schema(vars->{'tenant'})->resultset('Device')
371 ->find($spec->{device});
372 undef $row unless
373 scalar grep {('cf_'. $_) eq $spec->{action}}
374 grep {defined}
375 map {$_->{name}}
376 @{ setting('custom_fields')->{device} || [] };
377 }
378  
379 die 'failed to find row for custom field update' unless $row;
380  
381 my $coder = JSON::PP->new->utf8(0)->allow_nonref(1)->allow_unknown(1);
382 $spec->{subaction} = $coder->encode( $spec->{extra} || $spec->{subaction} );
383 $spec->{action} =~ s/^cf_//;
384 $row->make_column_dirty('custom_fields');
385 $row->update({
386 custom_fields => \['jsonb_set(custom_fields, ?, ?)'
387 => (qq{{$spec->{action}}}, $spec->{subaction}) ]
388 })->discard_changes();
389 }
390 else {
391 schema(vars->{'tenant'})->resultset('Admin')->populate([
392 map {{
393 device => $_->{device},
394 device_key => $_->{device_key},
395 port => $_->{port},
396 action => $_->{action},
397 subaction => ($_->{extra} || $_->{subaction}),
398 username => $_->{username},
399 userip => $_->{userip},
400 status => 'queued',
401 }} @$jobs
402 ]);
403 }
404 });
405 $happy = true;
406 }
407 catch {
408 error $_;
409 };
410  
411 return $happy;
412 }
413  
414 sub jq_delete {
415 my $id = shift;
416  
417 if ($id) {
418 schema(vars->{'tenant'})->txn_do(sub {
419 schema(vars->{'tenant'})->resultset('Admin')->search({ job => $id })->delete;
420 });
421 }
422 else {
423 schema(vars->{'tenant'})->txn_do(sub {
424 schema(vars->{'tenant'})->resultset('Admin')
425 ->search({ action => { '!=' => 'primeskiplist'} })->delete();
426 });
427 }
428 }
429  
430 true;