Debian Codegraph @

lib/Test2/Harness/Runner/Resource/SharedJobSlots/State.pm

raw
1 package Test2::Harness::Runner::Resource::SharedJobSlots::State;
2 use strict;
3 use warnings;
4
5 our $VERSION = '1.000179';
6
7 use Test2::Harness::Util::File::JSON;
8 use Scalar::Util qw/weaken/;
9 use Time::HiRes qw/time/;
10 use List::Util qw/first min sum0 max/;
11 use Carp qw/croak confess carp/;
12 use Fcntl qw/:flock SEEK_END/;
13 use Errno qw/EINTR EAGAIN ESRCH/;
14
15 use Test2::Harness::Util::HashBase qw{
16 <state_file <state_fh
17 <state_umask
18 <runner_id <name <dir <runner_pid
19 <max_slots
20 <max_slots_per_job
21 <max_slots_per_run
22 <min_slots_per_run
23 <default_slots_per_job
24 <default_slots_per_run
25
26 <my_max_slots
27 <my_max_slots_per_job
28
29 <algorithm
30
31 <ready_assignments
32 +transaction
33
34 <registered
35 <unregistered
36 };
37
38 BEGIN {
39 for my $term (qw/runners local/) {
40 my $val = "$term";
41 my $const = uc($term);
42 no strict 'refs';
43 *{$const} = sub() { $val };
44 }
45 }
46
47 sub TIMEOUT() { 300 } # Timeout runs if they do not update at least every 5 min
48
49 sub init {
50 my $self = shift;
51
52 croak "'state_file' is a required attribute" unless $self->{+STATE_FILE};
53 croak "'max_slots' is a required attribute" unless $self->{+MAX_SLOTS};
54 croak "'max_slots_per_job' is a required attribute" unless $self->{+MAX_SLOTS_PER_JOB};
55 croak "'max_slots_per_run' is a required attribute" unless $self->{+MAX_SLOTS_PER_RUN};
56
57 $self->{+MY_MAX_SLOTS} //= $self->{+MAX_SLOTS};
58 $self->{+MY_MAX_SLOTS_PER_JOB} //= $self->{+MAX_SLOTS_PER_JOB};
59
60 $self->{+MIN_SLOTS_PER_RUN} //= 0;
61
62 $self->{+STATE_UMASK} //= 0007;
63
64 $self->{+NAME} //= $self->{+RUNNER_ID};
65
66 $self->{+ALGORITHM} //= '_redistribute_fair';
67 }
68
69 sub init_state {
70 my $self = shift;
71 return { RUNNERS() => {} };
72 }
73
74 sub state { shift->transaction('r') }
75
76 sub transaction {
77 my $self = shift;
78 my ($mode, $cb, @args) = @_;
79
80 $mode //= 'r';
81
82 my $write = $mode eq 'w' || $mode eq 'rw';
83 my $read = $mode eq 'ro' || $mode eq 'r';
84 croak "mode must be 'w', 'rw', 'r', or 'ro', got '$mode'" unless $write || $read;
85
86 confess "Write mode requires a 'runner_id'" if $write && !$self->{+RUNNER_ID};
87 confess "Write mode requires a 'runner_pid'" if $write && !$self->{+RUNNER_PID};
88
89 my ($lock, $state, $local);
90 if ($state = $self->{+TRANSACTION}) {
91 $local = $state->{+LOCAL};
92
93 confess "Attempted a 'write' transaction inside of a read-only transaction"
94 if $write && !$local->{write};
95 }
96 else {
97 my $oldmask = umask($self->{+STATE_UMASK});
98
99 my $ok = eval {
100 my $lockf = "$self->{+STATE_FILE}.LOCK";
101
102 open($lock, '>>', $lockf) or die "Could not open lock file '$lockf': $!";
103 while (1) {
104 last if flock($lock, $write ? LOCK_EX : LOCK_SH);
105 next if $! == EINTR || $! == EAGAIN;
106 warn "Could not get lock: $!";
107 }
108
109 $state = $self->_read_state();
110 $local = $state->{+LOCAL} = {
111 lock => $lock,
112 mode => $mode,
113 write => $write,
114 stack => [{cb => $cb, args => \@args}],
115 };
116
117 weaken($state->{+LOCAL}->{lock});
118
119 1;
120 };
121 my $err = $@;
122 umask($oldmask);
123 die $err unless $ok;
124 }
125
126 local @{$local}{qw/write mode stack/} = ($write, $mode, [@{$local->{stack}}, {cb => $cb, args => \@args}])
127 if $self->{+TRANSACTION};
128
129 local $self->{+TRANSACTION} = $state;
130
131 if ($write) {
132 if ($self->{+REGISTERED}) {
133 $self->_verify_registration($state);
134 }
135 else {
136 $self->_update_registration($state);
137 }
138 }
139 $self->_clear_old_registrations($state);
140
141 my $out;
142 my $ok = eval { $out = $cb ? $self->$cb($state, @args) : $state; 1 };
143 my $err = $@;
144
145 if ($ok && $write) {
146 $self->_clear_old_registrations($state);
147 $self->_update_registration($state) unless $self->{+UNREGISTERED};
148 $self->_write_state($state);
149 }
150
151 if ($lock) {
152 flock($lock, LOCK_UN) or die "Could not release lock: $!";
153 }
154
155 die $err unless $ok;
156
157 return $out;
158 }
159
160 sub _read_state {
161 my $self = shift;
162
163 return $self->init_state unless -e $self->{+STATE_FILE};
164
165 my $file = Test2::Harness::Util::File::JSON->new(name => $self->{+STATE_FILE});
166
167 my ($ok, $err);
168 for (1 .. 5) {
169 my $state;
170 $ok = eval { $state = $file->maybe_read(); 1};
171 $err = $@;
172
173 return $state ||= $self->init_state if $ok;
174
175 sleep 0.2;
176 }
177
178 warn "Corrupted state? Resetting state to initial. Error that caused this was:\n======\n$err\n======\n";
179
180 return $self->init_state;
181 }
182
183 sub _write_state {
184 my $self = shift;
185 my ($state) = @_;
186
187 my $state_copy = {%$state};
188
189 my $local = delete $state_copy->{+LOCAL};
190
191 confess "Attempted write with no lock" unless $local->{lock};
192 confess "Attempted write with a read-only lock" unless $local->{write};
193
194 my $oldmask = umask($self->{+STATE_UMASK});
195 my $ok = eval {
196 my $file = Test2::Harness::Util::File::JSON->new(name => $self->{+STATE_FILE});
197 $file->rewrite($state_copy);
198 1;
199 };
200 my $err = $@;
201
202 umask($oldmask);
203
204 die $err unless $ok;
205 }
206
207 sub update_registration { $_[0]->transaction(rw => '_update_registration') }
208 sub remove_registration { $_[0]->transaction(rw => '_update_registration', remove => 1) }
209
210 sub _update_registration {
211 my $self = shift;
212 my ($state, %params) = @_;
213
214 my $runner_id = $self->{+RUNNER_ID};
215 my $runner_pid = $self->{+RUNNER_PID};
216 my $entry = $state->{runners}->{$runner_id} //= $state->{runners}->{$runner_id} = {
217 runner_id => $runner_id,
218 runner_pid => $runner_pid,
219 name => $self->{+NAME},
220 dir => $self->{+DIR},
221 user => $ENV{USER},
222 added => time,
223
224 todo => 0,
225 allocated => 0,
226 allotment => 0,
227 assigned => {},
228
229 max_slots => $self->{+MY_MAX_SLOTS},
230 max_slots_per_job => $self->{+MY_MAX_SLOTS_PER_JOB},
231 };
232
233 # Update our last checking time
234 $entry->{seen} = time;
235
236 $self->{+REGISTERED} = 1;
237
238 return $state unless $params{remove};
239
240 $self->{+UNREGISTERED} = 1;
241 $entry->{remove} = 1;
242
243 return $state;
244 }
245
246 sub _verify_registration {
247 my $self = shift;
248 my ($state) = @_;
249
250 return unless $self->{+REGISTERED};
251
252 my $runner_id = $self->{+RUNNER_ID};
253 my $entry = $state->{+RUNNERS}->{$runner_id};
254
255 # Do not allow for a new expiration. If the state has already expired us we will see it.
256 $entry->{seen} = time if $entry;
257
258 return unless $self->{+UNREGISTERED} //= $self->_entry_expired($entry);
259
260 confess "Shared slot registration expired";
261 }
262
263 sub _entry_expired {
264 my $self = shift;
265 my ($entry) = @_;
266
267 return 1 unless $entry;
268 return 1 if $entry->{remove};
269
270 if (my $pid = $entry->{runner_pid}) {
271 my $ret = kill(0, $pid);
272 my $err = $!;
273 return 1 if $ret == 0 && $! == ESRCH;
274 }
275
276 my $seen = $entry->{seen} or return 1;
277 my $delta = time - $seen;
278
279 return 1 if $delta > TIMEOUT();
280
281 return 0;
282 }
283
284 sub _clear_old_registrations {
285 my $self = shift;
286 my ($state) = @_;
287
288 my $runners = $state->{+RUNNERS} //= {};
289
290 my (%removed);
291 for my $entry (values %$runners) {
292 $entry->{remove} = 1 if $self->_entry_expired($entry);
293 next unless $entry->{remove};
294
295 my $runner_id = $entry->{runner_id};
296
297 $self->{+UNREGISTERED} = 1 if $runner_id eq $self->{+RUNNER_ID};
298
299 delete $runners->{$runner_id};
300
301 $removed{$runner_id}++;
302 }
303
304 return \%removed;
305 }
306
307 sub allocate_slots {
308 my $self = shift;
309 my (%params) = @_;
310
311 my $con = $params{con} or croak "'con' is required";
312 my $job_id = $params{job_id} or croak "'job_id' is required";
313
314 return $self->transaction(rw => '_allocate_slots', con => $con, job_id => $job_id);
315 }
316
317 sub assign_slots {
318 my $self = shift;
319 my (%params) = @_;
320
321 my $job = $params{job} or croak "'job' is required";
322
323 return $self->transaction(rw => '_assign_slots', job => $job);
324 }
325
326 sub release_slots {
327 my $self = shift;
328 my (%params) = @_;
329
330 my $job_id = $params{job_id} or croak "'job_id' is required";
331
332 return $self->transaction(rw => '_release_slots', job_id => $job_id);
333 }
334
335 sub _allocate_slots {
336 my $self = shift;
337 my ($state, %params) = @_;
338
339 my $entry = $state->{runners}->{$self->{+RUNNER_ID}};
340 delete $entry->{_calc_cache};
341
342 my $job_id = $params{job_id};
343 my $con = $params{con};
344 my ($min, $max) = @$con;
345 $self->_runner_todo($entry, $job_id => $max);
346
347 my $allocated = $entry->{allocated};
348
349 # We have what we need already allocated
350 return $entry->{allocated} = $max
351 if $max <= $allocated;
352
353 return $entry->{allocated}
354 if $entry->{allocated} >= $min;
355
356 # Our allocation, if any, is not big enough, free it so we do not have a
357 # deadlock with all runner holding an insufficient allocation.
358 $allocated = $entry->{allocated} = 0;
359
360 my $calcs = $self->_runner_calcs($entry);
361
362 for (0 .. 1) {
363 $self->_redistribute($state) if $_; # Only run on second loop
364
365 # Cannot do anything if we have no allotment or no available slots.
366 # This will go to the next loop for a redistribution, or end the loop.
367 my $allotment = $entry->{allotment} or next;
368 my $available = $allotment - $calcs->{assigned} or next;
369
370 # If we get here we have an allotment (not 0) but it does not mean the
371 # minimum, so we have to skip the test.
372 return -1 if $allotment < $min;
373
374 next unless $available >= $min;
375
376 return $entry->{allocated} = min($available, $max);
377 }
378
379 return 0;
380 }
381
382 sub _assign_slots {
383 my $self = shift;
384 my ($state, %params) = @_;
385
386 my $entry = $state->{runners}->{$self->{+RUNNER_ID}};
387 delete $entry->{_calc_cache};
388
389 my $job = $params{job};
390 my $job_id = $job->{job_id};
391 my $allocated = $entry->{allocated};
392
393 $self->_runner_todo($entry, $job_id => -1);
394
395 $job->{count} = $allocated;
396 $job->{started} = time;
397
398 $entry->{allocated} = 0;
399
400 $entry->{assigned}->{$job->{job_id}} = $job;
401
402 return $job;
403 }
404
405 sub _release_slots {
406 my $self = shift;
407 my ($state, %params) = @_;
408
409 my $entry = $state->{runners}->{$self->{+RUNNER_ID}};
410
411 my $job_id = $params{job_id};
412
413 delete $entry->{assigned}->{$job_id};
414 delete $entry->{_calc_cache};
415
416 $self->_runner_todo($entry, $job_id => -1);
417
418 # Reduce our allotment if it makes sense to do so.
419 my $calcs = $self->_runner_calcs($entry);
420 $entry->{allotment} = $calcs->{total} if $entry->{allotment} > $calcs->{total};
421 }
422
423 sub _runner_todo {
424 my $sef = shift;
425 my ($entry, $job_id, $count) = @_;
426
427 my $jobs = $entry->{jobs} //= {};
428
429 if ($count) {
430 if ($count < 0) {
431 $count = delete $jobs->{$job_id};
432 }
433 else {
434 $jobs->{$job_id} = $count;
435 }
436 }
437 elsif ($job_id) {
438 $count = $jobs->{$job_id};
439 }
440
441 $entry->{todo} = sum0(values %$jobs);
442
443 return $count;
444 }
445
446 sub _runner_calcs {
447 my $self = shift;
448 my ($runner) = @_;
449
450 return $runner->{_calc_cache} if $runner->{_calc_cache};
451
452 my $max = min(grep {$_} $self->{+MAX_SLOTS_PER_RUN}, $runner->{max_slots});
453 my $assigned = sum0(map { $_->{count} } values %{$runner->{assigned} //= {}});
454 my $active = $runner->{allocated} + $assigned;
455 my $total = $runner->{todo} + $active;
456 my $wants = ($total >= $max) ? max($max, $active) : max($total, $active);
457
458 return $runner->{_calc_cache} = {
459 max => $max,
460 assigned => $assigned,
461 active => $active,
462 total => $total,
463 wants => $wants,
464 };
465 }
466
467 sub _redistribute {
468 my $self = shift;
469 my ($state) = @_;
470
471 my $max_run = $self->{+MAX_SLOTS_PER_RUN};
472
473 my $wanted = 0;
474 for my $runner (values %{$state->{+RUNNERS}}) {
475 my $calcs = $self->_runner_calcs($runner);
476 $runner->{allotment} = $calcs->{wants};
477 $wanted += $calcs->{wants};
478 }
479
480 # Everyone gets what they want!
481 my $max = $self->{+MAX_SLOTS};
482 return if $wanted <= $max;
483
484 my $meth = $self->{+ALGORITHM};
485
486 return $self->$meth($state);
487 }
488
489 sub _redistribute_first {
490 my $self = shift;
491 my ($state) = @_;
492
493 my $min = $self->{+MIN_SLOTS_PER_RUN};
494 my $max = $self->{+MAX_SLOTS};
495
496 my $c = 0;
497 for my $runner (sort { $a->{added} <=> $b->{added} } values %{$state->{+RUNNERS}}) {
498 my $calcs = $self->_runner_calcs($runner);
499 my $wants = $calcs->{wants};
500
501 if ($max >= $wants) {
502 $runner->{allotment} = $wants;
503 }
504 else {
505 $runner->{allotment} = max($max, $min, 0);
506 }
507
508 $max -= $runner->{allotment};
509
510 $c++;
511 }
512
513 return;
514 }
515
516 sub _redistribute_fair {
517 my $self = shift;
518 my ($state) = @_;
519
520 my $runs = scalar keys %{$state->{+RUNNERS}};
521
522 # Avoid a divide by 0 below.
523 return unless $runs;
524
525 my $total = $self->{+MAX_SLOTS};
526 my $min = $self->{+MIN_SLOTS_PER_RUN};
527
528 my $used = 0;
529 for my $runner (values %{$state->{+RUNNERS}}) {
530 my $calcs = $self->_runner_calcs($runner);
531
532 # We never want less than the 'active' number
533 my $set = $calcs->{active};
534
535 # If min is greater than the active number and there are todo tests, we
536 # use the min instead.
537 $set = $min if $set < $min && $runner->{todo};
538
539 $runner->{allotment} = $set;
540 $used += $set;
541 }
542
543 my $free = $total - $used;
544 return unless $free >= 1;
545
546 # Is there a more efficient way to do this? Yikes!
547 my @runners = values %{$state->{+RUNNERS}};
548 while ($free > 0) {
549 @runners = sort { $a->{allotment} <=> $b->{allotment} || $a->{added} <=> $b->{added} }
550 grep { my $c = $self->_runner_calcs($_); $c->{wants} > $_->{allotment} }
551 @runners;
552
553 $free--;
554 $runners[0]->{allotment}++;
555 }
556
557 return;
558 }
559
560 1;
561
562 __END__
563
564 =pod
565
566 =encoding UTF-8
567
568 =head1 NAME
569
570 Test2::Harness::Runner::Resource::SharedJobSlots::State - shared state for job slots
571
572 =head1 SOURCE
573
574 The source code repository for Test2-Harness can be found at
575 F<http://github.com/Test-More/Test2-Harness/>.
576
577 =head1 MAINTAINERS
578
579 =over 4
580
581 =item Chad Granum E<lt>[email protected]<gt>
582
583 =back
584
585 =head1 AUTHORS
586
587 =over 4
588
589 =item Chad Granum E<lt>[email protected]<gt>
590
591 =back
592
593 =head1 COPYRIGHT
594
595 Copyright 2022 Chad Granum E<lt>[email protected]<gt>.
596
597 This program is free software; you can redistribute it and/or
598 modify it under the same terms as Perl itself.
599
600 See F<http://dev.perl.org/licenses/>
601
602 =cut